Compare commits
26 Commits
Author | SHA1 | Date | |
---|---|---|---|
5dd94c8298 | |||
412b44a981 | |||
aef4dd3fe7 | |||
6a92c6af4e | |||
e010940b61 | |||
2c9a4d276a | |||
4dfba73e5c | |||
c282d662ca | |||
b3d7594813 | |||
dd9bdf4e2f | |||
275cc7edf3 | |||
8c9e0b3884 | |||
30d4668008 | |||
02333a859a | |||
f9cc1cc363 | |||
fb7d340233 | |||
6a661bff0c | |||
d1dd21417b | |||
b866f06414 | |||
9683c297a7 | |||
f6c7281bb7 | |||
83bfe521b1 | |||
b52d0c16e9 | |||
132a6a6a2f | |||
03e4b5d525 | |||
a0221bf897 |
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
|
||||||
|
"
|
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
|
10
.github/workflows/docker.yml
vendored
10
.github/workflows/docker.yml
vendored
@ -13,7 +13,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
@ -49,14 +49,16 @@ jobs:
|
|||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||||
push: true
|
push: true
|
||||||
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
|
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
- name: Get all docker tags
|
- name: Get all docker tags
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
uses: actions/github-script@v4
|
uses: actions/github-script@v6
|
||||||
id: tags
|
id: tags
|
||||||
with:
|
with:
|
||||||
script: |
|
script: |
|
||||||
const ref = `${context.payload.ref.replace(/\/?refs\/tags\//, '')}`
|
const ref = context.payload.ref.replace(/\/?refs\/tags\//, '')
|
||||||
const tags = [
|
const tags = [
|
||||||
'dreamacro/clash:latest',
|
'dreamacro/clash:latest',
|
||||||
`dreamacro/clash:${ref}`,
|
`dreamacro/clash:${ref}`,
|
||||||
@ -74,3 +76,5 @@ jobs:
|
|||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||||
push: true
|
push: true
|
||||||
tags: ${{steps.tags.outputs.result}}
|
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
|
@ -1,44 +1,46 @@
|
|||||||
name: Dev
|
name: Release
|
||||||
on: [push]
|
on: [push]
|
||||||
jobs:
|
jobs:
|
||||||
dev-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:
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
- 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: 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_name: Dev
|
|
||||||
files: bin/*
|
files: bin/*
|
||||||
prerelease: true
|
draft: true
|
||||||
|
|
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
|
|
16
.golangci.yaml
Normal file
16
.golangci.yaml
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
linters:
|
||||||
|
disable-all: true
|
||||||
|
enable:
|
||||||
|
- gofumpt
|
||||||
|
- staticcheck
|
||||||
|
- govet
|
||||||
|
- gci
|
||||||
|
|
||||||
|
linters-settings:
|
||||||
|
gci:
|
||||||
|
sections:
|
||||||
|
- standard
|
||||||
|
- prefix(github.com/Dreamacro/clash)
|
||||||
|
- default
|
||||||
|
staticcheck:
|
||||||
|
go: '1.18'
|
@ -12,7 +12,7 @@ RUN go mod download && \
|
|||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates
|
RUN apk add --no-cache ca-certificates tzdata
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
COPY --from=builder /clash /
|
COPY --from=builder /clash /
|
||||||
ENTRYPOINT ["/clash"]
|
ENTRYPOINT ["/clash"]
|
||||||
|
72
Makefile
72
Makefile
@ -1,52 +1,41 @@
|
|||||||
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" )
|
|
||||||
ifeq ($(BRANCH),Dev)
|
|
||||||
VERSION=develop-$(shell git rev-parse --short HEAD)
|
|
||||||
endif
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
AUTOIPTABLES=Enable
|
|
||||||
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)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
GOBUILDOP=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
|
||||||
-X "github.com/Dreamacro/clash/constant.AutoIptables=$(AUTOIPTABLES)" \
|
|
||||||
-w -s -buildid='
|
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
|
darwin-amd64-v3 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
|
linux-386 \
|
||||||
linux-amd64 \
|
linux-amd64 \
|
||||||
|
linux-amd64-v3 \
|
||||||
linux-armv5 \
|
linux-armv5 \
|
||||||
linux-armv6 \
|
linux-armv6 \
|
||||||
linux-armv7 \
|
linux-armv7 \
|
||||||
linux-armv8 \
|
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 \
|
||||||
|
linux-mips64 \
|
||||||
|
linux-mips64le \
|
||||||
freebsd-386 \
|
freebsd-386 \
|
||||||
freebsd-amd64 \
|
freebsd-amd64 \
|
||||||
|
freebsd-amd64-v3 \
|
||||||
freebsd-arm64
|
freebsd-arm64
|
||||||
|
|
||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
windows-386 \
|
windows-386 \
|
||||||
windows-amd64 \
|
windows-amd64 \
|
||||||
|
windows-amd64-v3 \
|
||||||
windows-arm64 \
|
windows-arm64 \
|
||||||
windows-arm32v7
|
windows-arm32v7
|
||||||
|
|
||||||
|
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
||||||
all:linux-amd64-AutoIptables linux-amd64\
|
|
||||||
linux-arm64 linux-arm64-AutoIptables linux-armv7\
|
|
||||||
darwin-amd64 darwin-arm64\
|
|
||||||
windows-amd64 windows-386 \
|
|
||||||
linux-mips-hardfloat linux-mips-softfloat linux-mips64 linux-mips64le linux-mipsle-hardfloat linux-mipsle-softfloat# Most used
|
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
$(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@ -54,6 +43,9 @@ docker:
|
|||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
darwin-amd64-v3:
|
||||||
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -63,39 +55,21 @@ linux-386:
|
|||||||
linux-amd64:
|
linux-amd64:
|
||||||
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64-AutoIptables:
|
linux-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=linux $(GOBUILDOP) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-arm64:
|
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-arm64-AutoIptables:
|
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILDOP) -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)-$@
|
||||||
|
|
||||||
linux-armv5-AutoIptables:
|
|
||||||
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILDOP) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-armv6:
|
linux-armv6:
|
||||||
GOARCH=arm GOOS=linux GOARM=6 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm GOOS=linux GOARM=6 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-armv6-AutoIptables:
|
|
||||||
GOARCH=arm GOOS=linux GOARM=6 $(GOBUILDOP) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
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-armv7-AutoIptables:
|
|
||||||
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILDOP) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-armv8:
|
linux-armv8:
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-armv8-AutoIptables:
|
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILDOP) -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)-$@
|
||||||
|
|
||||||
@ -120,6 +94,9 @@ freebsd-386:
|
|||||||
freebsd-amd64:
|
freebsd-amd64:
|
||||||
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-amd64-v3:
|
||||||
|
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
freebsd-arm64:
|
freebsd-arm64:
|
||||||
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -129,6 +106,9 @@ windows-386:
|
|||||||
windows-amd64:
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-amd64-v3:
|
||||||
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-arm64:
|
windows-arm64:
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
@ -148,5 +128,13 @@ $(zip_releases): %.zip : %
|
|||||||
all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
||||||
|
|
||||||
releases: $(gz_releases) $(zip_releases)
|
releases: $(gz_releases) $(zip_releases)
|
||||||
|
|
||||||
|
lint:
|
||||||
|
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)/*
|
||||||
|
273
README.md
273
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,260 +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 by the XRAY-CORE.
|
|
||||||
```yaml
|
|
||||||
proxies:
|
|
||||||
# Vless + TCP Sample
|
|
||||||
- name: "vless-tcp"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
network: tcp
|
|
||||||
servername: example.com # AKA SNI
|
|
||||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
# Vless + WS Sample
|
|
||||||
- name: "vless-ws"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
udp: true
|
|
||||||
network: ws
|
|
||||||
servername: example.com # priority over wss host
|
|
||||||
# skip-cert-verify: true
|
|
||||||
ws-path: /path
|
|
||||||
ws-headers:
|
|
||||||
Host: example.com
|
|
||||||
|
|
||||||
# Trojan + XTLS Sample
|
|
||||||
- name: "proxy name"
|
|
||||||
type: trojan
|
|
||||||
server: server name
|
|
||||||
port: 443
|
|
||||||
password: password
|
|
||||||
udp: true
|
|
||||||
servername: server name # AKA SNI
|
|
||||||
flow: xtls-rprx-direct # Enable XTLS: xtls-rprx-direct | xtls-rprx-origin
|
|
||||||
skip-cert-verify: false
|
|
||||||
```
|
|
||||||
|
|
||||||
### IPTABLES auto-configuration
|
|
||||||
Only work on Linux OS who support `iptables`, Clash will auto-configuration iptables for tproxy listener when `tproxy-port` value isn't zero.
|
|
||||||
|
|
||||||
If `TPROXY` is enabled, the `TUN` must be disabled.
|
|
||||||
```yaml
|
|
||||||
# Enable the TPROXY listener
|
|
||||||
tproxy-port: 9898
|
|
||||||
# Disable the TUN listener
|
|
||||||
tun:
|
|
||||||
enable: false
|
|
||||||
```
|
|
||||||
Create user given name `Clash.Meta`.
|
|
||||||
|
|
||||||
Run Meta Kernel by user `Clash.Meta` as a daemon.
|
|
||||||
|
|
||||||
Create the systemd configuration file at /etc/systemd/system/clash.service:
|
|
||||||
|
|
||||||
```
|
|
||||||
[Unit]
|
|
||||||
Description=Clash.Meta Daemon, Another Clash Kernel.
|
|
||||||
After=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
User=Clash.Meta
|
|
||||||
Group=Clash.Meta
|
|
||||||
CapabilityBoundingSet=cap_net_admin
|
|
||||||
AmbientCapabilities=cap_net_admin
|
|
||||||
Restart=always
|
|
||||||
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)
|
||||||
Build the Clash.Meta locally
|
|
||||||
```shell
|
|
||||||
$ git clone https://github.com/MetaCubeX/Clash.Meta.git
|
|
||||||
$ cd Clash.Meta
|
|
||||||
$ make # build for all platform or 'make darwin-amd64' for specific platform, darwin-amd64
|
|
||||||
```
|
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
|
@ -16,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
|
||||||
@ -93,7 +91,7 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
return inner, err
|
return inner, err
|
||||||
}
|
}
|
||||||
|
|
||||||
mapping := map[string]interface{}{}
|
mapping := map[string]any{}
|
||||||
json.Unmarshal(inner, &mapping)
|
json.Unmarshal(inner, &mapping)
|
||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
@ -116,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
|
||||||
@ -154,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
|
||||||
|
@ -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)
|
|
||||||
}
|
|
||||||
|
@ -44,13 +44,3 @@ func NewDirect() *Direct {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCompatible() *Direct {
|
|
||||||
return &Direct{
|
|
||||||
Base: &Base{
|
|
||||||
name: "COMPATIBLE",
|
|
||||||
tp: C.Compatible,
|
|
||||||
udp: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -136,6 +136,7 @@ func NewHttp(option HttpOption) *Http {
|
|||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
|
@ -29,14 +29,14 @@ type ShadowSocks struct {
|
|||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]interface{} `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -160,6 +160,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
cipher: ciph,
|
cipher: ciph,
|
||||||
|
|
||||||
|
@ -92,6 +92,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 +109,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
|
||||||
@ -142,6 +149,7 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
|
@ -23,13 +23,13 @@ type Snell struct {
|
|||||||
|
|
||||||
type SnellOption struct {
|
type SnellOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Psk string `proxy:"psk"`
|
Psk string `proxy:"psk"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Version int `proxy:"version,omitempty"`
|
Version int `proxy:"version,omitempty"`
|
||||||
ObfsOpts map[string]interface{} `proxy:"obfs-opts,omitempty"`
|
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type streamOption struct {
|
type streamOption struct {
|
||||||
@ -142,6 +142,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -154,6 +154,7 @@ func NewSocks5(option Socks5Option) *Socks5 {
|
|||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
|
@ -4,7 +4,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
xtls "github.com/xtls/go"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -34,7 +33,6 @@ type TrojanOption struct {
|
|||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
@ -84,19 +82,7 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
var tc trojan.Command
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
if xtlsConn, ok := c.(*xtls.Conn); ok {
|
|
||||||
xtlsConn.RPRX = true
|
|
||||||
if t.instance.GetFlow() == trojan.XRD {
|
|
||||||
xtlsConn.DirectMode = true
|
|
||||||
tc = trojan.CommandXRD
|
|
||||||
} else {
|
|
||||||
tc = trojan.CommandXRO
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tc = trojan.CommandTCP
|
|
||||||
}
|
|
||||||
err = t.instance.WriteHeader(c, tc, serializesSocksAddr(metadata))
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -170,13 +156,10 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
tOption := &trojan.Option{
|
tOption := &trojan.Option{
|
||||||
Password: option.Password,
|
Password: option.Password,
|
||||||
Flow: option.Flow,
|
ALPN: option.ALPN,
|
||||||
ALPN: option.ALPN,
|
ServerName: option.Server,
|
||||||
ServerName: option.Server,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
|
||||||
ClientSessionCache: getClientSessionCache(),
|
|
||||||
ClientXSessionCache: getClientXSessionCache(),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
@ -190,6 +173,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
tp: C.Trojan,
|
tp: C.Trojan,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
instance: trojan.New(tOption),
|
instance: trojan.New(tOption),
|
||||||
option: &option,
|
option: &option,
|
||||||
|
@ -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,26 +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 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 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)
|
||||||
|
@ -1,444 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"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 = 8192
|
|
||||||
)
|
|
||||||
|
|
||||||
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":
|
|
||||||
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)
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.option.TLS {
|
|
||||||
wsOpts.TLS = true
|
|
||||||
wsOpts.TLSConfig = &tls.Config{
|
|
||||||
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:
|
|
||||||
// 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) {
|
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
var 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.Atoi(metadata.DstPort)
|
|
||||||
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 []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) writePacket(b []byte, addr net.Addr) (int, error) {
|
|
||||||
length := len(b)
|
|
||||||
defer func() {
|
|
||||||
c.cache = c.cache[:0]
|
|
||||||
}()
|
|
||||||
c.cache = append(c.cache, byte(length>>8), byte(length))
|
|
||||||
c.cache = append(c.cache, b...)
|
|
||||||
n, err := c.Conn.Write(c.cache)
|
|
||||||
if n > 2 {
|
|
||||||
return n - 2, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
if len(b) <= maxLength {
|
|
||||||
return c.writePacket(b, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := 0
|
|
||||||
total := len(b)
|
|
||||||
for offset < total {
|
|
||||||
cursor := offset + maxLength
|
|
||||||
if cursor > total {
|
|
||||||
cursor = total
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := c.writePacket(b[offset:cursor], addr)
|
|
||||||
if err != nil {
|
|
||||||
return offset + n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset = cursor
|
|
||||||
}
|
|
||||||
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
c.mux.Lock()
|
|
||||||
defer c.mux.Unlock()
|
|
||||||
|
|
||||||
length := len(b)
|
|
||||||
if c.remain > 0 {
|
|
||||||
if c.remain < length {
|
|
||||||
length = c.remain
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := c.Conn.Read(b[:length])
|
|
||||||
if err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c.remain -= n
|
|
||||||
return n, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var packetLength uint16
|
|
||||||
if err := binary.Read(c.Conn, binary.BigEndian, &packetLength); err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
remain := int(packetLength)
|
|
||||||
n, err := c.Conn.Read(b[:length])
|
|
||||||
remain -= n
|
|
||||||
if remain > 0 {
|
|
||||||
c.remain = remain
|
|
||||||
}
|
|
||||||
return n, c.rAddr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
func NewVless(option VlessOption) (*Vless, error) {
|
|
||||||
if !option.TLS && option.Network == "grpc" {
|
|
||||||
return nil, fmt.Errorf("TLS must be true with vless-grpc")
|
|
||||||
}
|
|
||||||
|
|
||||||
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 vless 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
|
|
||||||
}
|
|
@ -280,6 +280,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
tp: C.Vmess,
|
tp: C.Vmess,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
package outboundgroup
|
package outboundgroup
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
|
||||||
"regexp"
|
|
||||||
"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,28 +20,5 @@ func getProvidersProxies(providers []provider.ProxyProvider, touch bool, filter
|
|||||||
proxies = append(proxies, provider.Proxies()...)
|
proxies = append(proxies, provider.Proxies()...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return proxies
|
||||||
var filterReg *regexp.Regexp = nil
|
|
||||||
matchedProxies := []C.Proxy{}
|
|
||||||
if len(filter) > 0 {
|
|
||||||
filterReg = regexp.MustCompile(filter)
|
|
||||||
for _, p := range proxies {
|
|
||||||
if filterReg.MatchString(p.Name()) {
|
|
||||||
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,12 +55,11 @@ 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 := make([]string, 0)
|
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())
|
||||||
}
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": f.Type().String(),
|
"type": f.Type().String(),
|
||||||
"now": f.Now(),
|
"now": f.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
@ -116,8 +73,8 @@ 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() (interface{}, 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)
|
||||||
@ -142,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,14 +23,13 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
var errStrategy = errors.New("unsupported strategy")
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
|
|
||||||
func parseStrategy(config map[string]interface{}) string {
|
func parseStrategy(config map[string]any) string {
|
||||||
if elm, ok := config["strategy"]; ok {
|
if elm, ok := config["strategy"]; ok {
|
||||||
if strategy, ok := elm.(string); ok {
|
if strategy, ok := elm.(string); ok {
|
||||||
return strategy
|
return strategy
|
||||||
@ -141,8 +140,8 @@ 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() (interface{}, 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,13 +149,11 @@ 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 := make([]string, 0)
|
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())
|
||||||
}
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": lb.Type().String(),
|
"type": lb.Type().String(),
|
||||||
"all": all,
|
"all": all,
|
||||||
})
|
})
|
||||||
@ -183,6 +180,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,10 +29,9 @@ 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]interface{}, 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) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
groupOption := &GroupCommonOption{
|
groupOption := &GroupCommonOption{
|
||||||
@ -96,8 +95,6 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
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,21 +68,19 @@ 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 := make([]string, 0)
|
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())
|
||||||
}
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": r.Type().String(),
|
"type": r.Type().String(),
|
||||||
"all": all,
|
"all": all,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := r.single.Do(func() (interface{}, 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)
|
||||||
@ -113,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,13 +49,12 @@ 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 := make([]string, 0)
|
var all []string
|
||||||
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
for _, proxy := range getProvidersProxies(s.providers, false, s.filter) {
|
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"type": s.Type().String(),
|
"type": s.Type().String(),
|
||||||
"now": s.Now(),
|
"now": s.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
@ -68,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()
|
||||||
@ -85,8 +83,8 @@ func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
elm, _, _ := s.single.Do(func() (interface{}, 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
|
||||||
@ -100,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,
|
||||||
@ -109,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,12 +39,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,12 +48,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -73,15 +58,15 @@ func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := u.single.Do(func() (interface{}, 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, _ := u.fastSingle.Do(func() (interface{}, error) {
|
elm, _, _ := u.fastSingle.Do(func() (any, error) {
|
||||||
proxies := u.proxies(touch)
|
proxies := u.proxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
@ -125,46 +110,18 @@ 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 := make([]string, 0)
|
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())
|
||||||
}
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": u.Type().String(),
|
"type": u.Type().String(),
|
||||||
"now": u.Now(),
|
"now": u.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) onDialFailed() {
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
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]interface{}) []urlTestOption {
|
|
||||||
opts := []urlTestOption{}
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
// tolerance
|
// tolerance
|
||||||
@ -185,13 +142,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 {
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]interface{}) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
@ -60,13 +60,6 @@ func ParseProxy(mapping map[string]interface{}) (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)
|
||||||
|
@ -16,7 +16,7 @@ var (
|
|||||||
dirMode os.FileMode = 0o755
|
dirMode os.FileMode = 0o755
|
||||||
)
|
)
|
||||||
|
|
||||||
type parser = func([]byte) (interface{}, error)
|
type parser = func([]byte) (any, error)
|
||||||
|
|
||||||
type fetcher struct {
|
type fetcher struct {
|
||||||
name string
|
name string
|
||||||
@ -26,7 +26,7 @@ type fetcher struct {
|
|||||||
done chan struct{}
|
done chan struct{}
|
||||||
hash [16]byte
|
hash [16]byte
|
||||||
parser parser
|
parser parser
|
||||||
onUpdate func(interface{})
|
onUpdate func(any)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher) Name() string {
|
func (f *fetcher) Name() string {
|
||||||
@ -37,7 +37,7 @@ func (f *fetcher) VehicleType() types.VehicleType {
|
|||||||
return f.vehicle.Type()
|
return f.vehicle.Type()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher) Initial() (interface{}, error) {
|
func (f *fetcher) Initial() (any, error) {
|
||||||
var (
|
var (
|
||||||
buf []byte
|
buf []byte
|
||||||
err error
|
err error
|
||||||
@ -92,7 +92,7 @@ func (f *fetcher) Initial() (interface{}, error) {
|
|||||||
return proxies, nil
|
return proxies, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher) Update() (interface{}, bool, error) {
|
func (f *fetcher) Update() (any, bool, error) {
|
||||||
buf, err := f.vehicle.Read()
|
buf, err := f.vehicle.Read()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
@ -168,7 +168,7 @@ func safeWrite(path string, buf []byte) error {
|
|||||||
return os.WriteFile(path, buf, fileMode)
|
return os.WriteFile(path, buf, fileMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(interface{})) *fetcher {
|
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(any)) *fetcher {
|
||||||
var ticker *time.Ticker
|
var ticker *time.Ticker
|
||||||
if interval != 0 {
|
if interval != 0 {
|
||||||
ticker = time.NewTicker(interval)
|
ticker = time.NewTicker(interval)
|
||||||
|
@ -62,7 +62,7 @@ func (hc *HealthCheck) check() {
|
|||||||
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum(10))
|
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum(10))
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (interface{}, error) {
|
b.Go(p.Name(), func() (any, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
p.URLTest(ctx, hc.url)
|
p.URLTest(ctx, hc.url)
|
||||||
|
@ -28,7 +28,7 @@ type proxyProviderSchema struct {
|
|||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]interface{}) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
schema := &proxyProviderSchema{
|
schema := &proxyProviderSchema{
|
||||||
|
@ -20,7 +20,7 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type ProxySchema struct {
|
type ProxySchema struct {
|
||||||
Proxies []map[string]interface{} `yaml:"proxies"`
|
Proxies []map[string]any `yaml:"proxies"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// for auto gc
|
// for auto gc
|
||||||
@ -35,7 +35,7 @@ type proxySetProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"name": pp.Name(),
|
"name": pp.Name(),
|
||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
@ -67,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -106,17 +102,21 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
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,
|
||||||
}
|
}
|
||||||
|
|
||||||
onUpdate := func(elm interface{}) {
|
onUpdate := func(elm any) {
|
||||||
ret := elm.([]C.Proxy)
|
ret := elm.([]C.Proxy)
|
||||||
pd.setProxies(ret)
|
pd.setProxies(ret)
|
||||||
}
|
}
|
||||||
|
|
||||||
proxiesParseAndFilter := func(buf []byte) (interface{}, error) {
|
proxiesParseAndFilter := func(buf []byte) (any, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
@ -169,7 +169,7 @@ type compatibleProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"name": cp.Name(),
|
"name": cp.Name(),
|
||||||
"type": cp.Type().String(),
|
"type": cp.Type().String(),
|
||||||
"vehicleType": cp.VehicleType().String(),
|
"vehicleType": cp.VehicleType().String(),
|
||||||
@ -190,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -223,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,7 +2,6 @@ package provider
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"github.com/Dreamacro/clash/listener/inner"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -10,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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -57,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
|
||||||
}
|
}
|
||||||
@ -77,8 +74,7 @@ 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
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
type Option = func(b *Batch)
|
type Option = func(b *Batch)
|
||||||
|
|
||||||
type Result struct {
|
type Result struct {
|
||||||
Value interface{}
|
Value any
|
||||||
Err error
|
Err error
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,7 +38,7 @@ type Batch struct {
|
|||||||
cancel func()
|
cancel func()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Batch) Go(key string, fn func() (interface{}, error)) {
|
func (b *Batch) Go(key string, fn func() (any, error)) {
|
||||||
b.wg.Add(1)
|
b.wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
defer b.wg.Done()
|
defer b.wg.Done()
|
||||||
|
@ -14,11 +14,11 @@ func TestBatch(t *testing.T) {
|
|||||||
b, _ := New(context.Background())
|
b, _ := New(context.Background())
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
b.Go("foo", func() (interface{}, error) {
|
b.Go("foo", func() (any, error) {
|
||||||
time.Sleep(time.Millisecond * 100)
|
time.Sleep(time.Millisecond * 100)
|
||||||
return "foo", nil
|
return "foo", nil
|
||||||
})
|
})
|
||||||
b.Go("bar", func() (interface{}, error) {
|
b.Go("bar", func() (any, error) {
|
||||||
time.Sleep(time.Millisecond * 150)
|
time.Sleep(time.Millisecond * 150)
|
||||||
return "bar", nil
|
return "bar", nil
|
||||||
})
|
})
|
||||||
@ -45,7 +45,7 @@ func TestBatchWithConcurrencyNum(t *testing.T) {
|
|||||||
now := time.Now()
|
now := time.Now()
|
||||||
for i := 0; i < 7; i++ {
|
for i := 0; i < 7; i++ {
|
||||||
idx := i
|
idx := i
|
||||||
b.Go(strconv.Itoa(idx), func() (interface{}, error) {
|
b.Go(strconv.Itoa(idx), func() (any, error) {
|
||||||
time.Sleep(time.Millisecond * 100)
|
time.Sleep(time.Millisecond * 100)
|
||||||
return strconv.Itoa(idx), nil
|
return strconv.Itoa(idx), nil
|
||||||
})
|
})
|
||||||
@ -64,12 +64,12 @@ func TestBatchWithConcurrencyNum(t *testing.T) {
|
|||||||
func TestBatchContext(t *testing.T) {
|
func TestBatchContext(t *testing.T) {
|
||||||
b, ctx := New(context.Background())
|
b, ctx := New(context.Background())
|
||||||
|
|
||||||
b.Go("error", func() (interface{}, error) {
|
b.Go("error", func() (any, error) {
|
||||||
time.Sleep(time.Millisecond * 100)
|
time.Sleep(time.Millisecond * 100)
|
||||||
return nil, errors.New("test error")
|
return nil, errors.New("test error")
|
||||||
})
|
})
|
||||||
|
|
||||||
b.Go("ctx", func() (interface{}, error) {
|
b.Go("ctx", func() (any, error) {
|
||||||
<-ctx.Done()
|
<-ctx.Done()
|
||||||
return nil, ctx.Err()
|
return nil, ctx.Err()
|
||||||
})
|
})
|
||||||
|
10
common/cache/cache.go
vendored
10
common/cache/cache.go
vendored
@ -18,11 +18,11 @@ type cache struct {
|
|||||||
|
|
||||||
type element struct {
|
type element struct {
|
||||||
Expired time.Time
|
Expired time.Time
|
||||||
Payload interface{}
|
Payload any
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put element in Cache with its ttl
|
// Put element in Cache with its ttl
|
||||||
func (c *cache) Put(key interface{}, payload interface{}, ttl time.Duration) {
|
func (c *cache) Put(key any, payload any, ttl time.Duration) {
|
||||||
c.mapping.Store(key, &element{
|
c.mapping.Store(key, &element{
|
||||||
Payload: payload,
|
Payload: payload,
|
||||||
Expired: time.Now().Add(ttl),
|
Expired: time.Now().Add(ttl),
|
||||||
@ -30,7 +30,7 @@ func (c *cache) Put(key interface{}, payload interface{}, ttl time.Duration) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get element in Cache, and drop when it expired
|
// Get element in Cache, and drop when it expired
|
||||||
func (c *cache) Get(key interface{}) interface{} {
|
func (c *cache) Get(key any) any {
|
||||||
item, exist := c.mapping.Load(key)
|
item, exist := c.mapping.Load(key)
|
||||||
if !exist {
|
if !exist {
|
||||||
return nil
|
return nil
|
||||||
@ -45,7 +45,7 @@ func (c *cache) Get(key interface{}) interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetWithExpire element in Cache with Expire Time
|
// GetWithExpire element in Cache with Expire Time
|
||||||
func (c *cache) GetWithExpire(key interface{}) (payload interface{}, expired time.Time) {
|
func (c *cache) GetWithExpire(key any) (payload any, expired time.Time) {
|
||||||
item, exist := c.mapping.Load(key)
|
item, exist := c.mapping.Load(key)
|
||||||
if !exist {
|
if !exist {
|
||||||
return
|
return
|
||||||
@ -60,7 +60,7 @@ func (c *cache) GetWithExpire(key interface{}) (payload interface{}, expired tim
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *cache) cleanup() {
|
func (c *cache) cleanup() {
|
||||||
c.mapping.Range(func(k, v interface{}) bool {
|
c.mapping.Range(func(k, v any) bool {
|
||||||
key := k.(string)
|
key := k.(string)
|
||||||
elm := v.(*element)
|
elm := v.(*element)
|
||||||
if time.Since(elm.Expired) > 0 {
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
34
common/cache/lrucache.go
vendored
34
common/cache/lrucache.go
vendored
@ -12,7 +12,7 @@ import (
|
|||||||
type Option func(*LruCache)
|
type Option func(*LruCache)
|
||||||
|
|
||||||
// EvictCallback is used to get a callback when a cache entry is evicted
|
// EvictCallback is used to get a callback when a cache entry is evicted
|
||||||
type EvictCallback = func(key interface{}, value interface{})
|
type EvictCallback = func(key any, value any)
|
||||||
|
|
||||||
// WithEvict set the evict callback
|
// WithEvict set the evict callback
|
||||||
func WithEvict(cb EvictCallback) Option {
|
func WithEvict(cb EvictCallback) Option {
|
||||||
@ -57,7 +57,7 @@ type LruCache struct {
|
|||||||
maxAge int64
|
maxAge int64
|
||||||
maxSize int
|
maxSize int
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
cache map[interface{}]*list.Element
|
cache map[any]*list.Element
|
||||||
lru *list.List // Front is least-recent
|
lru *list.List // Front is least-recent
|
||||||
updateAgeOnGet bool
|
updateAgeOnGet bool
|
||||||
staleReturn bool
|
staleReturn bool
|
||||||
@ -68,7 +68,7 @@ type LruCache struct {
|
|||||||
func NewLRUCache(options ...Option) *LruCache {
|
func NewLRUCache(options ...Option) *LruCache {
|
||||||
lc := &LruCache{
|
lc := &LruCache{
|
||||||
lru: list.New(),
|
lru: list.New(),
|
||||||
cache: make(map[interface{}]*list.Element),
|
cache: make(map[any]*list.Element),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
@ -78,9 +78,9 @@ func NewLRUCache(options ...Option) *LruCache {
|
|||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the interface{} representation of a cached response and a bool
|
// Get returns the any representation of a cached response and a bool
|
||||||
// set to true if the key was found.
|
// set to true if the key was found.
|
||||||
func (c *LruCache) Get(key interface{}) (interface{}, bool) {
|
func (c *LruCache) Get(key any) (any, bool) {
|
||||||
entry := c.get(key)
|
entry := c.get(key)
|
||||||
if entry == nil {
|
if entry == nil {
|
||||||
return nil, false
|
return nil, false
|
||||||
@ -90,11 +90,11 @@ func (c *LruCache) Get(key interface{}) (interface{}, bool) {
|
|||||||
return value, true
|
return value, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetWithExpire returns the interface{} representation of a cached response,
|
// GetWithExpire returns the any representation of a cached response,
|
||||||
// a time.Time Give expected expires,
|
// a time.Time Give expected expires,
|
||||||
// and a bool set to true if the key was found.
|
// and a bool set to true if the key was found.
|
||||||
// This method will NOT check the maxAge of element and will NOT update the expires.
|
// This method will NOT check the maxAge of element and will NOT update the expires.
|
||||||
func (c *LruCache) GetWithExpire(key interface{}) (interface{}, time.Time, bool) {
|
func (c *LruCache) GetWithExpire(key any) (any, time.Time, bool) {
|
||||||
entry := c.get(key)
|
entry := c.get(key)
|
||||||
if entry == nil {
|
if entry == nil {
|
||||||
return nil, time.Time{}, false
|
return nil, time.Time{}, false
|
||||||
@ -104,7 +104,7 @@ func (c *LruCache) GetWithExpire(key interface{}) (interface{}, time.Time, bool)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Exist returns if key exist in cache but not put item to the head of linked list
|
// Exist returns if key exist in cache but not put item to the head of linked list
|
||||||
func (c *LruCache) Exist(key interface{}) bool {
|
func (c *LruCache) Exist(key any) bool {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
@ -112,8 +112,8 @@ func (c *LruCache) Exist(key interface{}) bool {
|
|||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set stores the interface{} representation of a response for a given key.
|
// Set stores the any representation of a response for a given key.
|
||||||
func (c *LruCache) Set(key interface{}, value interface{}) {
|
func (c *LruCache) Set(key any, value any) {
|
||||||
expires := int64(0)
|
expires := int64(0)
|
||||||
if c.maxAge > 0 {
|
if c.maxAge > 0 {
|
||||||
expires = time.Now().Unix() + c.maxAge
|
expires = time.Now().Unix() + c.maxAge
|
||||||
@ -121,9 +121,9 @@ func (c *LruCache) Set(key interface{}, value interface{}) {
|
|||||||
c.SetWithExpire(key, value, time.Unix(expires, 0))
|
c.SetWithExpire(key, value, time.Unix(expires, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetWithExpire stores the interface{} representation of a response for a given key and given expires.
|
// SetWithExpire stores the any representation of a response for a given key and given expires.
|
||||||
// The expires time will round to second.
|
// The expires time will round to second.
|
||||||
func (c *LruCache) SetWithExpire(key interface{}, value interface{}, expires time.Time) {
|
func (c *LruCache) SetWithExpire(key any, value any, expires time.Time) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
@ -155,7 +155,7 @@ func (c *LruCache) CloneTo(n *LruCache) {
|
|||||||
defer n.mu.Unlock()
|
defer n.mu.Unlock()
|
||||||
|
|
||||||
n.lru = list.New()
|
n.lru = list.New()
|
||||||
n.cache = make(map[interface{}]*list.Element)
|
n.cache = make(map[any]*list.Element)
|
||||||
|
|
||||||
for e := c.lru.Front(); e != nil; e = e.Next() {
|
for e := c.lru.Front(); e != nil; e = e.Next() {
|
||||||
elm := e.Value.(*entry)
|
elm := e.Value.(*entry)
|
||||||
@ -163,7 +163,7 @@ func (c *LruCache) CloneTo(n *LruCache) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *LruCache) get(key interface{}) *entry {
|
func (c *LruCache) get(key any) *entry {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
@ -188,7 +188,7 @@ func (c *LruCache) get(key interface{}) *entry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Delete removes the value associated with a key.
|
// Delete removes the value associated with a key.
|
||||||
func (c *LruCache) Delete(key interface{}) {
|
func (c *LruCache) Delete(key any) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
|
|
||||||
if le, ok := c.cache[key]; ok {
|
if le, ok := c.cache[key]; ok {
|
||||||
@ -217,7 +217,7 @@ func (c *LruCache) deleteElement(le *list.Element) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type entry struct {
|
type entry struct {
|
||||||
key interface{}
|
key any
|
||||||
value interface{}
|
value any
|
||||||
expires int64
|
expires int64
|
||||||
}
|
}
|
||||||
|
2
common/cache/lrucache_test.go
vendored
2
common/cache/lrucache_test.go
vendored
@ -126,7 +126,7 @@ func TestExist(t *testing.T) {
|
|||||||
|
|
||||||
func TestEvict(t *testing.T) {
|
func TestEvict(t *testing.T) {
|
||||||
temp := 0
|
temp := 0
|
||||||
evict := func(key interface{}, value interface{}) {
|
evict := func(key any, value any) {
|
||||||
temp = key.(int) + value.(int)
|
temp = key.(int) + value.(int)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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"
|
|
||||||
)
|
|
30
common/net/relay.go
Normal file
30
common/net/relay.go
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Relay copies between left and right bidirectionally.
|
||||||
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
|
ch := make(chan error)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
|
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
||||||
|
pool.Put(buf)
|
||||||
|
leftConn.SetReadDeadline(time.Now())
|
||||||
|
ch <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
|
io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
||||||
|
pool.Put(buf)
|
||||||
|
rightConn.SetReadDeadline(time.Now())
|
||||||
|
<-ch
|
||||||
|
}
|
@ -1,46 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func SplitNetworkType(s string) (string, string, error) {
|
|
||||||
var (
|
|
||||||
shecme string
|
|
||||||
hostPort string
|
|
||||||
)
|
|
||||||
result := strings.Split(s, "://")
|
|
||||||
if len(result) == 2 {
|
|
||||||
shecme = result[0]
|
|
||||||
hostPort = result[1]
|
|
||||||
} else if len(result) == 1 {
|
|
||||||
hostPort = result[0]
|
|
||||||
} else {
|
|
||||||
return "", "", fmt.Errorf("tcp/udp style error")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(shecme) == 0 {
|
|
||||||
shecme = "udp"
|
|
||||||
}
|
|
||||||
|
|
||||||
if shecme != "tcp" && shecme != "udp" {
|
|
||||||
return "", "", fmt.Errorf("scheme should be tcp:// or udp://")
|
|
||||||
} else {
|
|
||||||
return shecme, hostPort, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
|
|
||||||
temp := s
|
|
||||||
hasPort = true
|
|
||||||
|
|
||||||
if !strings.Contains(s, ":") && !strings.Contains(s, "]:") {
|
|
||||||
temp += ":0"
|
|
||||||
hasPort = false
|
|
||||||
}
|
|
||||||
|
|
||||||
host, port, err = net.SplitHostPort(temp)
|
|
||||||
return
|
|
||||||
}
|
|
@ -1,3 +1,3 @@
|
|||||||
package observable
|
package observable
|
||||||
|
|
||||||
type Iterable <-chan interface{}
|
type Iterable <-chan any
|
||||||
|
@ -9,8 +9,8 @@ import (
|
|||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func iterator(item []interface{}) chan interface{} {
|
func iterator(item []any) chan any {
|
||||||
ch := make(chan interface{})
|
ch := make(chan any)
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(100 * time.Millisecond)
|
time.Sleep(100 * time.Millisecond)
|
||||||
for _, elm := range item {
|
for _, elm := range item {
|
||||||
@ -22,7 +22,7 @@ func iterator(item []interface{}) chan interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable(t *testing.T) {
|
func TestObservable(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]any{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
@ -34,7 +34,7 @@ func TestObservable(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_MultiSubscribe(t *testing.T) {
|
func TestObservable_MultiSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]any{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
ch1, _ := src.Subscribe()
|
ch1, _ := src.Subscribe()
|
||||||
ch2, _ := src.Subscribe()
|
ch2, _ := src.Subscribe()
|
||||||
@ -42,7 +42,7 @@ func TestObservable_MultiSubscribe(t *testing.T) {
|
|||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan any) {
|
||||||
for range ch {
|
for range ch {
|
||||||
count.Inc()
|
count.Inc()
|
||||||
}
|
}
|
||||||
@ -55,7 +55,7 @@ func TestObservable_MultiSubscribe(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribe(t *testing.T) {
|
func TestObservable_UnSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]any{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
@ -65,7 +65,7 @@ func TestObservable_UnSubscribe(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1})
|
iter := iterator([]any{1})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, _ := src.Subscribe()
|
data, _ := src.Subscribe()
|
||||||
<-data
|
<-data
|
||||||
@ -75,14 +75,14 @@ func TestObservable_SubscribeClosedSource(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
||||||
sub := Subscription(make(chan interface{}))
|
sub := Subscription(make(chan any))
|
||||||
iter := iterator([]interface{}{1})
|
iter := iterator([]any{1})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
src.UnSubscribe(sub)
|
src.UnSubscribe(sub)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]any{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
max := 100
|
max := 100
|
||||||
|
|
||||||
@ -94,7 +94,7 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(max)
|
wg.Add(max)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan any) {
|
||||||
for range ch {
|
for range ch {
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
@ -115,7 +115,7 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_Observable_1000(b *testing.B) {
|
func Benchmark_Observable_1000(b *testing.B) {
|
||||||
ch := make(chan interface{})
|
ch := make(chan any)
|
||||||
o := NewObservable(ch)
|
o := NewObservable(ch)
|
||||||
num := 1000
|
num := 1000
|
||||||
|
|
||||||
|
@ -4,14 +4,14 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Subscription <-chan interface{}
|
type Subscription <-chan any
|
||||||
|
|
||||||
type Subscriber struct {
|
type Subscriber struct {
|
||||||
buffer chan interface{}
|
buffer chan any
|
||||||
once sync.Once
|
once sync.Once
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscriber) Emit(item interface{}) {
|
func (s *Subscriber) Emit(item any) {
|
||||||
s.buffer <- item
|
s.buffer <- item
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,7 +27,7 @@ func (s *Subscriber) Close() {
|
|||||||
|
|
||||||
func newSubscriber() *Subscriber {
|
func newSubscriber() *Subscriber {
|
||||||
sub := &Subscriber{
|
sub := &Subscriber{
|
||||||
buffer: make(chan interface{}, 200),
|
buffer: make(chan any, 200),
|
||||||
}
|
}
|
||||||
return sub
|
return sub
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@ type Picker struct {
|
|||||||
|
|
||||||
once sync.Once
|
once sync.Once
|
||||||
errOnce sync.Once
|
errOnce sync.Once
|
||||||
result interface{}
|
result any
|
||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,7 +43,7 @@ func WithTimeout(ctx context.Context, timeout time.Duration) (*Picker, context.C
|
|||||||
|
|
||||||
// Wait blocks until all function calls from the Go method have returned,
|
// Wait blocks until all function calls from the Go method have returned,
|
||||||
// then returns the first nil error result (if any) from them.
|
// then returns the first nil error result (if any) from them.
|
||||||
func (p *Picker) Wait() interface{} {
|
func (p *Picker) Wait() any {
|
||||||
p.wg.Wait()
|
p.wg.Wait()
|
||||||
if p.cancel != nil {
|
if p.cancel != nil {
|
||||||
p.cancel()
|
p.cancel()
|
||||||
@ -58,7 +58,7 @@ func (p *Picker) Error() error {
|
|||||||
|
|
||||||
// Go calls the given function in a new goroutine.
|
// Go calls the given function in a new goroutine.
|
||||||
// The first call to return a nil error cancels the group; its result will be returned by Wait.
|
// The first call to return a nil error cancels the group; its result will be returned by Wait.
|
||||||
func (p *Picker) Go(f func() (interface{}, error)) {
|
func (p *Picker) Go(f func() (any, error)) {
|
||||||
p.wg.Add(1)
|
p.wg.Add(1)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
|
@ -8,8 +8,8 @@ import (
|
|||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func sleepAndSend(ctx context.Context, delay int, input interface{}) func() (interface{}, error) {
|
func sleepAndSend(ctx context.Context, delay int, input any) func() (any, error) {
|
||||||
return func() (interface{}, error) {
|
return func() (any, error) {
|
||||||
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
|
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
|
||||||
select {
|
select {
|
||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
|
@ -23,7 +23,7 @@ func NewAllocator() *Allocator {
|
|||||||
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
|
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
|
||||||
for k := range alloc.buffers {
|
for k := range alloc.buffers {
|
||||||
i := k
|
i := k
|
||||||
alloc.buffers[k].New = func() interface{} {
|
alloc.buffers[k].New = func() any {
|
||||||
return make([]byte, 1<<uint32(i))
|
return make([]byte, 1<<uint32(i))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
var bufferPool = sync.Pool{New: func() interface{} { return &bytes.Buffer{} }}
|
var bufferPool = sync.Pool{New: func() any { return &bytes.Buffer{} }}
|
||||||
|
|
||||||
func GetBuffer() *bytes.Buffer {
|
func GetBuffer() *bytes.Buffer {
|
||||||
return bufferPool.Get().(*bytes.Buffer)
|
return bufferPool.Get().(*bytes.Buffer)
|
||||||
|
@ -6,12 +6,12 @@ import (
|
|||||||
|
|
||||||
// Queue is a simple concurrent safe queue
|
// Queue is a simple concurrent safe queue
|
||||||
type Queue struct {
|
type Queue struct {
|
||||||
items []interface{}
|
items []any
|
||||||
lock sync.RWMutex
|
lock sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put add the item to the queue.
|
// Put add the item to the queue.
|
||||||
func (q *Queue) Put(items ...interface{}) {
|
func (q *Queue) Put(items ...any) {
|
||||||
if len(items) == 0 {
|
if len(items) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -22,7 +22,7 @@ func (q *Queue) Put(items ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Pop returns the head of items.
|
// Pop returns the head of items.
|
||||||
func (q *Queue) Pop() interface{} {
|
func (q *Queue) Pop() any {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -35,7 +35,7 @@ func (q *Queue) Pop() interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Last returns the last of item.
|
// Last returns the last of item.
|
||||||
func (q *Queue) Last() interface{} {
|
func (q *Queue) Last() any {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -47,8 +47,8 @@ func (q *Queue) Last() interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Copy get the copy of queue.
|
// Copy get the copy of queue.
|
||||||
func (q *Queue) Copy() []interface{} {
|
func (q *Queue) Copy() []any {
|
||||||
items := []interface{}{}
|
items := []any{}
|
||||||
q.lock.RLock()
|
q.lock.RLock()
|
||||||
items = append(items, q.items...)
|
items = append(items, q.items...)
|
||||||
q.lock.RUnlock()
|
q.lock.RUnlock()
|
||||||
@ -66,6 +66,6 @@ func (q *Queue) Len() int64 {
|
|||||||
// New is a constructor for a new concurrent safe queue.
|
// New is a constructor for a new concurrent safe queue.
|
||||||
func New(hint int64) *Queue {
|
func New(hint int64) *Queue {
|
||||||
return &Queue{
|
return &Queue{
|
||||||
items: make([]interface{}, 0, hint),
|
items: make([]any, 0, hint),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ import (
|
|||||||
|
|
||||||
type call struct {
|
type call struct {
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
val interface{}
|
val any
|
||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -20,13 +20,13 @@ type Single struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Result struct {
|
type Result struct {
|
||||||
Val interface{}
|
Val any
|
||||||
Err error
|
Err error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do single.Do likes sync.singleFlight
|
// Do single.Do likes sync.singleFlight
|
||||||
//lint:ignore ST1008 it likes sync.singleFlight
|
//lint:ignore ST1008 it likes sync.singleFlight
|
||||||
func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, 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()
|
||||||
if now.Before(s.last.Add(s.wait)) {
|
if now.Before(s.last.Add(s.wait)) {
|
||||||
|
@ -13,7 +13,7 @@ func TestBasic(t *testing.T) {
|
|||||||
single := NewSingle(time.Millisecond * 30)
|
single := NewSingle(time.Millisecond * 30)
|
||||||
foo := 0
|
foo := 0
|
||||||
shardCount := atomic.NewInt32(0)
|
shardCount := atomic.NewInt32(0)
|
||||||
call := func() (interface{}, error) {
|
call := func() (any, error) {
|
||||||
foo++
|
foo++
|
||||||
time.Sleep(time.Millisecond * 5)
|
time.Sleep(time.Millisecond * 5)
|
||||||
return nil, nil
|
return nil, nil
|
||||||
@ -40,7 +40,7 @@ func TestBasic(t *testing.T) {
|
|||||||
func TestTimer(t *testing.T) {
|
func TestTimer(t *testing.T) {
|
||||||
single := NewSingle(time.Millisecond * 30)
|
single := NewSingle(time.Millisecond * 30)
|
||||||
foo := 0
|
foo := 0
|
||||||
call := func() (interface{}, error) {
|
call := func() (any, error) {
|
||||||
foo++
|
foo++
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@ -56,7 +56,7 @@ func TestTimer(t *testing.T) {
|
|||||||
func TestReset(t *testing.T) {
|
func TestReset(t *testing.T) {
|
||||||
single := NewSingle(time.Millisecond * 30)
|
single := NewSingle(time.Millisecond * 30)
|
||||||
foo := 0
|
foo := 0
|
||||||
call := func() (interface{}, error) {
|
call := func() (any, error) {
|
||||||
foo++
|
foo++
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build !linux
|
//go:build !linux
|
||||||
// +build !linux
|
|
||||||
|
|
||||||
package sockopt
|
package sockopt
|
||||||
|
|
||||||
|
@ -28,8 +28,8 @@ func NewDecoder(option Option) *Decoder {
|
|||||||
return &Decoder{option: &option}
|
return &Decoder{option: &option}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode transform a map[string]interface{} to a struct
|
// Decode transform a map[string]any to a struct
|
||||||
func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
||||||
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
||||||
return fmt.Errorf("Decode must recive a ptr struct")
|
return fmt.Errorf("Decode must recive a ptr struct")
|
||||||
}
|
}
|
||||||
@ -45,12 +45,8 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tag := field.Tag.Get(d.option.TagName)
|
tag := field.Tag.Get(d.option.TagName)
|
||||||
str := strings.SplitN(tag, ",", 2)
|
key, omitKey, found := strings.Cut(tag, ",")
|
||||||
key := str[0]
|
omitempty := found && omitKey == "omitempty"
|
||||||
omitempty := false
|
|
||||||
if len(str) > 1 {
|
|
||||||
omitempty = str[1] == "omitempty"
|
|
||||||
}
|
|
||||||
|
|
||||||
value, ok := src[key]
|
value, ok := src[key]
|
||||||
if !ok || value == nil {
|
if !ok || value == nil {
|
||||||
@ -68,7 +64,7 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
||||||
switch val.Kind() {
|
switch val.Kind() {
|
||||||
case reflect.Int:
|
case reflect.Int:
|
||||||
return d.decodeInt(name, data, val)
|
return d.decodeInt(name, data, val)
|
||||||
@ -89,12 +85,14 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case kind == reflect.Int:
|
case kind == reflect.Int:
|
||||||
val.SetInt(dataVal.Int())
|
val.SetInt(dataVal.Int())
|
||||||
|
case kind == reflect.Float64 && d.option.WeaklyTypedInput:
|
||||||
|
val.SetInt(int64(dataVal.Float()))
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
var i int64
|
var i int64
|
||||||
i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
|
i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
|
||||||
@ -112,7 +110,7 @@ func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (e
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
@ -129,7 +127,7 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeBool(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
@ -146,7 +144,7 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
||||||
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
@ -161,9 +159,19 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
|
|||||||
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
|
||||||
}
|
}
|
||||||
@ -173,7 +181,7 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decodeMap(name string, data any, val reflect.Value) error {
|
||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valKeyType := valType.Key()
|
valKeyType := valType.Key()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
@ -245,7 +253,7 @@ func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val refle
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decodeStruct(name string, data any, val reflect.Value) error {
|
||||||
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
|
|
||||||
// If the type of the value to write to and the data match directly,
|
// If the type of the value to write to and the data match directly,
|
||||||
@ -273,7 +281,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
}
|
}
|
||||||
|
|
||||||
dataValKeys := make(map[reflect.Value]struct{})
|
dataValKeys := make(map[reflect.Value]struct{})
|
||||||
dataValKeysUnused := make(map[interface{}]struct{})
|
dataValKeysUnused := make(map[any]struct{})
|
||||||
for _, dataValKey := range dataVal.MapKeys() {
|
for _, dataValKey := range dataVal.MapKeys() {
|
||||||
dataValKeys[dataValKey] = struct{}{}
|
dataValKeys[dataValKey] = struct{}{}
|
||||||
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
|
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
|
||||||
@ -398,7 +406,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) setInterface(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) setInterface(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
val.Set(dataVal)
|
val.Set(dataVal)
|
||||||
return nil
|
return nil
|
||||||
|
@ -27,7 +27,7 @@ type BazOptional struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_Basic(t *testing.T) {
|
func TestStructure_Basic(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
"bar": "test",
|
"bar": "test",
|
||||||
"extra": false,
|
"extra": false,
|
||||||
@ -45,7 +45,7 @@ func TestStructure_Basic(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_Slice(t *testing.T) {
|
func TestStructure_Slice(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
"bar": []string{"one", "two"},
|
"bar": []string{"one", "two"},
|
||||||
}
|
}
|
||||||
@ -62,7 +62,7 @@ func TestStructure_Slice(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_Optional(t *testing.T) {
|
func TestStructure_Optional(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -77,7 +77,7 @@ func TestStructure_Optional(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_MissingKey(t *testing.T) {
|
func TestStructure_MissingKey(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -87,14 +87,14 @@ func TestStructure_MissingKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_ParamError(t *testing.T) {
|
func TestStructure_ParamError(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{}
|
rawMap := map[string]any{}
|
||||||
s := Baz{}
|
s := Baz{}
|
||||||
err := decoder.Decode(rawMap, s)
|
err := decoder.Decode(rawMap, s)
|
||||||
assert.NotNilf(t, err, "should throw error: %#v", s)
|
assert.NotNilf(t, err, "should throw error: %#v", s)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_SliceTypeError(t *testing.T) {
|
func TestStructure_SliceTypeError(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
"bar": []int{1, 2},
|
"bar": []int{1, 2},
|
||||||
}
|
}
|
||||||
@ -105,7 +105,7 @@ func TestStructure_SliceTypeError(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_WeakType(t *testing.T) {
|
func TestStructure_WeakType(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": "1",
|
"foo": "1",
|
||||||
"bar": []int{1},
|
"bar": []int{1},
|
||||||
}
|
}
|
||||||
@ -122,7 +122,7 @@ func TestStructure_WeakType(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_Nest(t *testing.T) {
|
func TestStructure_Nest(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -137,3 +137,45 @@ func TestStructure_Nest(t *testing.T) {
|
|||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
assert.Equal(t, s.BazOptional, goal)
|
assert.Equal(t, s.BazOptional, goal)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceNilValue(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"foo": 1,
|
||||||
|
"bar": []any{"bar", nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
goal := &BazSlice{
|
||||||
|
Foo: 1,
|
||||||
|
Bar: []string{"bar", ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &BazSlice{}
|
||||||
|
err := weakTypeDecoder.Decode(rawMap, s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, goal.Bar, s.Bar)
|
||||||
|
|
||||||
|
s = &BazSlice{}
|
||||||
|
err = decoder.Decode(rawMap, s)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceNilValueComplex(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"bar": []any{map[string]any{"bar": "foo"}, nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &struct {
|
||||||
|
Bar []map[string]any `test:"bar"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Nil(t, s.Bar[1])
|
||||||
|
|
||||||
|
ss := &struct {
|
||||||
|
Bar []Baz `test:"bar"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err = decoder.Decode(rawMap, ss)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
}
|
||||||
|
@ -36,7 +36,7 @@ func NewAuthenticator(users []AuthUser) Authenticator {
|
|||||||
au.storage.Store(user.User, user.Pass)
|
au.storage.Store(user.User, user.Pass)
|
||||||
}
|
}
|
||||||
usernames := make([]string, 0, len(users))
|
usernames := make([]string, 0, len(users))
|
||||||
au.storage.Range(func(key, value interface{}) bool {
|
au.storage.Range(func(key, value any) bool {
|
||||||
usernames = append(usernames, key.(string))
|
usernames = append(usernames, key.(string))
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
@ -4,9 +4,9 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/iface"
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type controlFn = func(network, address string, c syscall.RawConn) error
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build !linux && !darwin
|
//go:build !linux && !darwin
|
||||||
// +build !linux,!darwin
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
|
@ -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.interfaceName != "" {
|
ip, err = resolver.ResolveIPv4(host)
|
||||||
ip, err = resolver.ResolveIPv4WithMain(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
if opt.interfaceName != "" {
|
ip, err = resolver.ResolveIPv6(host)
|
||||||
ip, err = resolver.ResolveIPv6WithMain(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
|
||||||
@ -135,24 +127,16 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
|
|
||||||
var ip net.IP
|
var ip net.IP
|
||||||
if ipv6 {
|
if ipv6 {
|
||||||
if opt.interfaceName != "" {
|
ip, result.error = resolver.ResolveIPv6(host)
|
||||||
ip, result.error = resolver.ResolveIPv6WithMain(host)
|
|
||||||
} else {
|
|
||||||
ip, result.error = resolver.ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
if opt.interfaceName != "" {
|
ip, result.error = resolver.ResolveIPv4(host)
|
||||||
ip, result.error = resolver.ResolveIPv4WithMain(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, false)
|
go startRacer(ctx, network+"4", host, false)
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build linux
|
//go:build linux
|
||||||
// +build linux
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build !linux
|
//go:build !linux
|
||||||
// +build !linux
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows
|
//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows
|
||||||
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
||||||
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
|
@ -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,71 +0,0 @@
|
|||||||
package router
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"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
|
|
||||||
}
|
|
@ -1,725 +0,0 @@
|
|||||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
|
||||||
// versions:
|
|
||||||
// protoc-gen-go v1.27.1
|
|
||||||
// protoc v3.17.3
|
|
||||||
// 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,83 +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,41 +0,0 @@
|
|||||||
package geodata
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
var geoLoaderName = "memconservative"
|
|
||||||
|
|
||||||
// geoLoaderName = "standard"
|
|
||||||
|
|
||||||
func LoaderName() string {
|
|
||||||
return geoLoaderName
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetLoader(newLoader string) {
|
|
||||||
geoLoaderName = newLoader
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
@ -23,7 +23,7 @@ var (
|
|||||||
var interfaces = singledo.NewSingle(time.Second * 20)
|
var interfaces = singledo.NewSingle(time.Second * 20)
|
||||||
|
|
||||||
func ResolveInterface(name string) (*Interface, error) {
|
func ResolveInterface(name string) (*Interface, error) {
|
||||||
value, err, _ := interfaces.Do(func() (interface{}, error) {
|
value, err, _ := interfaces.Do(func() (any, error) {
|
||||||
ifaces, err := net.Interfaces()
|
ifaces, err := net.Interfaces()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -6,17 +6,17 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Factory = func(context.Context) (interface{}, error)
|
type Factory = func(context.Context) (any, error)
|
||||||
|
|
||||||
type entry struct {
|
type entry struct {
|
||||||
elm interface{}
|
elm any
|
||||||
time time.Time
|
time time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(*pool)
|
type Option func(*pool)
|
||||||
|
|
||||||
// WithEvict set the evict callback
|
// WithEvict set the evict callback
|
||||||
func WithEvict(cb func(interface{})) Option {
|
func WithEvict(cb func(any)) Option {
|
||||||
return func(p *pool) {
|
return func(p *pool) {
|
||||||
p.evict = cb
|
p.evict = cb
|
||||||
}
|
}
|
||||||
@ -32,7 +32,7 @@ func WithAge(maxAge int64) Option {
|
|||||||
// WithSize defined max size of Pool
|
// WithSize defined max size of Pool
|
||||||
func WithSize(maxSize int) Option {
|
func WithSize(maxSize int) Option {
|
||||||
return func(p *pool) {
|
return func(p *pool) {
|
||||||
p.ch = make(chan interface{}, maxSize)
|
p.ch = make(chan any, maxSize)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,13 +42,13 @@ type Pool struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type pool struct {
|
type pool struct {
|
||||||
ch chan interface{}
|
ch chan any
|
||||||
factory Factory
|
factory Factory
|
||||||
evict func(interface{})
|
evict func(any)
|
||||||
maxAge int64
|
maxAge int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *pool) GetContext(ctx context.Context) (interface{}, error) {
|
func (p *pool) GetContext(ctx context.Context) (any, error) {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@ -68,11 +68,11 @@ func (p *pool) GetContext(ctx context.Context) (interface{}, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *pool) Get() (interface{}, error) {
|
func (p *pool) Get() (any, error) {
|
||||||
return p.GetContext(context.Background())
|
return p.GetContext(context.Background())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *pool) Put(item interface{}) {
|
func (p *pool) Put(item any) {
|
||||||
e := &entry{
|
e := &entry{
|
||||||
elm: item,
|
elm: item,
|
||||||
time: time.Now(),
|
time: time.Now(),
|
||||||
@ -100,7 +100,7 @@ func recycle(p *Pool) {
|
|||||||
|
|
||||||
func New(factory Factory, options ...Option) *Pool {
|
func New(factory Factory, options ...Option) *Pool {
|
||||||
p := &pool{
|
p := &pool{
|
||||||
ch: make(chan interface{}, 10),
|
ch: make(chan any, 10),
|
||||||
factory: factory,
|
factory: factory,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,7 +10,7 @@ import (
|
|||||||
|
|
||||||
func lg() Factory {
|
func lg() Factory {
|
||||||
initial := -1
|
initial := -1
|
||||||
return func(context.Context) (interface{}, error) {
|
return func(context.Context) (any, error) {
|
||||||
initial++
|
initial++
|
||||||
return initial, nil
|
return initial, nil
|
||||||
}
|
}
|
||||||
@ -34,7 +34,7 @@ func TestPool_MaxSize(t *testing.T) {
|
|||||||
size := 5
|
size := 5
|
||||||
pool := New(g, WithSize(size))
|
pool := New(g, WithSize(size))
|
||||||
|
|
||||||
items := []interface{}{}
|
items := []any{}
|
||||||
|
|
||||||
for i := 0; i < size; i++ {
|
for i := 0; i < size; i++ {
|
||||||
item, _ := pool.Get()
|
item, _ := pool.Get()
|
||||||
|
@ -3,7 +3,6 @@ package process
|
|||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"net"
|
"net"
|
||||||
"path/filepath"
|
|
||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
@ -96,7 +95,7 @@ func getExecPathFromPID(pid uint32) (string, error) {
|
|||||||
return "", errno
|
return "", errno
|
||||||
}
|
}
|
||||||
|
|
||||||
return filepath.Base(unix.ByteSliceToString(buf)), nil
|
return unix.ByteSliceToString(buf), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func readNativeUint32(b []byte) uint32 {
|
func readNativeUint32(b []byte) uint32 {
|
||||||
|
@ -4,7 +4,6 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@ -77,7 +76,7 @@ func getExecPathFromPID(pid uint32) (string, error) {
|
|||||||
return "", errno
|
return "", errno
|
||||||
}
|
}
|
||||||
|
|
||||||
return filepath.Base(string(buf[:size-1])), nil
|
return string(buf[:size-1]), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func readNativeUint32(b []byte) uint32 {
|
func readNativeUint32(b []byte) uint32 {
|
||||||
|
@ -4,12 +4,12 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
"unicode"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
@ -25,17 +25,6 @@ var nativeEndian = func() binary.ByteOrder {
|
|||||||
return binary.LittleEndian
|
return binary.LittleEndian
|
||||||
}()
|
}()
|
||||||
|
|
||||||
type (
|
|
||||||
SocketResolver func(network string, ip net.IP, srcPort int) (inode, uid int, err error)
|
|
||||||
ProcessNameResolver func(inode, uid int) (name string, err error)
|
|
||||||
)
|
|
||||||
|
|
||||||
// export for android
|
|
||||||
var (
|
|
||||||
DefaultSocketResolver SocketResolver = resolveSocketByNetlink
|
|
||||||
DefaultProcessNameResolver ProcessNameResolver = resolveProcessNameByProcSearch
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + 8 + 48
|
sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + 8 + 48
|
||||||
socketDiagByFamily = 20
|
socketDiagByFamily = 20
|
||||||
@ -43,15 +32,15 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||||
inode, uid, err := DefaultSocketResolver(network, ip, srcPort)
|
inode, uid, err := resolveSocketByNetlink(network, ip, srcPort)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return DefaultProcessNameResolver(inode, uid)
|
return resolveProcessNameByProcSearch(inode, uid)
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int, int, error) {
|
func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int32, int32, error) {
|
||||||
var family byte
|
var family byte
|
||||||
var protocol byte
|
var protocol byte
|
||||||
|
|
||||||
@ -74,13 +63,12 @@ func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int, int, e
|
|||||||
|
|
||||||
socket, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_INET_DIAG)
|
socket, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_INET_DIAG)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, fmt.Errorf("dial netlink: %w", err)
|
||||||
}
|
}
|
||||||
defer syscall.Close(socket)
|
defer syscall.Close(socket)
|
||||||
|
|
||||||
syscall.SetNonblock(socket, true)
|
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &syscall.Timeval{Usec: 100})
|
||||||
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &syscall.Timeval{Usec: 50})
|
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &syscall.Timeval{Usec: 100})
|
||||||
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &syscall.Timeval{Usec: 50})
|
|
||||||
|
|
||||||
if err := syscall.Connect(socket, &syscall.SockaddrNetlink{
|
if err := syscall.Connect(socket, &syscall.SockaddrNetlink{
|
||||||
Family: syscall.AF_NETLINK,
|
Family: syscall.AF_NETLINK,
|
||||||
@ -92,7 +80,7 @@ func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int, int, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
if _, err := syscall.Write(socket, req); err != nil {
|
if _, err := syscall.Write(socket, req); err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, fmt.Errorf("write request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
rb := pool.Get(pool.RelayBufferSize)
|
rb := pool.Get(pool.RelayBufferSize)
|
||||||
@ -100,24 +88,27 @@ func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int, int, e
|
|||||||
|
|
||||||
n, err := syscall.Read(socket, rb)
|
n, err := syscall.Read(socket, rb)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, fmt.Errorf("read response: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
messages, err := syscall.ParseNetlinkMessage(rb[:n])
|
messages, err := syscall.ParseNetlinkMessage(rb[:n])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, fmt.Errorf("parse netlink message: %w", err)
|
||||||
} else if len(messages) == 0 {
|
} else if len(messages) == 0 {
|
||||||
return 0, 0, io.ErrUnexpectedEOF
|
return 0, 0, fmt.Errorf("unexcepted netlink response")
|
||||||
}
|
}
|
||||||
|
|
||||||
message := messages[0]
|
message := messages[0]
|
||||||
if message.Header.Type&syscall.NLMSG_ERROR != 0 {
|
if message.Header.Type&syscall.NLMSG_ERROR != 0 {
|
||||||
return 0, 0, syscall.ESRCH
|
return 0, 0, fmt.Errorf("netlink message: NLMSG_ERROR")
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, inode := unpackSocketDiagResponse(&messages[0])
|
inode, uid := unpackSocketDiagResponse(&messages[0])
|
||||||
|
if inode < 0 || uid < 0 {
|
||||||
|
return 0, 0, fmt.Errorf("invalid inode(%d) or uid(%d)", inode, uid)
|
||||||
|
}
|
||||||
|
|
||||||
return int(uid), int(inode), nil
|
return inode, uid, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func packSocketDiagRequest(family, protocol byte, source net.IP, sourcePort uint16) []byte {
|
func packSocketDiagRequest(family, protocol byte, source net.IP, sourcePort uint16) []byte {
|
||||||
@ -155,20 +146,20 @@ func packSocketDiagRequest(family, protocol byte, source net.IP, sourcePort uint
|
|||||||
return buf
|
return buf
|
||||||
}
|
}
|
||||||
|
|
||||||
func unpackSocketDiagResponse(msg *syscall.NetlinkMessage) (inode, uid uint32) {
|
func unpackSocketDiagResponse(msg *syscall.NetlinkMessage) (inode, uid int32) {
|
||||||
if len(msg.Data) < 72 {
|
if len(msg.Data) < 72 {
|
||||||
return 0, 0
|
return 0, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
data := msg.Data
|
data := msg.Data
|
||||||
|
|
||||||
uid = nativeEndian.Uint32(data[64:68])
|
uid = int32(nativeEndian.Uint32(data[64:68]))
|
||||||
inode = nativeEndian.Uint32(data[68:72])
|
inode = int32(nativeEndian.Uint32(data[68:72]))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveProcessNameByProcSearch(inode, uid int) (string, error) {
|
func resolveProcessNameByProcSearch(inode, uid int32) (string, error) {
|
||||||
files, err := os.ReadDir(pathProc)
|
files, err := os.ReadDir(pathProc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@ -205,38 +196,16 @@ func resolveProcessNameByProcSearch(inode, uid int) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if bytes.Equal(buffer[:n], socket) {
|
if bytes.Equal(buffer[:n], socket) {
|
||||||
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
|
return os.Readlink(path.Join(processPath, "exe"))
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return splitCmdline(cmdline), nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", syscall.ESRCH
|
return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode)
|
||||||
}
|
|
||||||
|
|
||||||
func splitCmdline(cmdline []byte) string {
|
|
||||||
indexOfEndOfString := len(cmdline)
|
|
||||||
|
|
||||||
for i, c := range cmdline {
|
|
||||||
if c == 0 {
|
|
||||||
indexOfEndOfString = i
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return filepath.Base(string(cmdline[:indexOfEndOfString]))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func isPid(s string) bool {
|
func isPid(s string) bool {
|
||||||
for _, s := range s {
|
return strings.IndexFunc(s, func(r rune) bool {
|
||||||
if s < '0' || s > '9' {
|
return !unicode.IsDigit(r)
|
||||||
return false
|
}) == -1
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,4 @@
|
|||||||
//go:build !darwin && !linux && !windows && (!freebsd || !amd64)
|
//go:build !darwin && !linux && !windows && (!freebsd || !amd64)
|
||||||
// +build !darwin
|
|
||||||
// +build !linux
|
|
||||||
// +build !windows
|
|
||||||
// +build !freebsd !amd64
|
|
||||||
|
|
||||||
package process
|
package process
|
||||||
|
|
||||||
|
@ -3,7 +3,6 @@ package process
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"path/filepath"
|
|
||||||
"sync"
|
"sync"
|
||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
@ -175,7 +174,7 @@ func newSearcher(isV4, isTCP bool) *searcher {
|
|||||||
func getTransportTable(fn uintptr, family int, class int) ([]byte, error) {
|
func getTransportTable(fn uintptr, family int, class int) ([]byte, error) {
|
||||||
for size, buf := uint32(8), make([]byte, 8); ; {
|
for size, buf := uint32(8), make([]byte, 8); ; {
|
||||||
ptr := unsafe.Pointer(&buf[0])
|
ptr := unsafe.Pointer(&buf[0])
|
||||||
err, _, _ := syscall.Syscall6(fn, 6, uintptr(ptr), uintptr(unsafe.Pointer(&size)), 0, uintptr(family), uintptr(class), 0)
|
err, _, _ := syscall.SyscallN(fn, uintptr(ptr), uintptr(unsafe.Pointer(&size)), 0, uintptr(family), uintptr(class), 0)
|
||||||
|
|
||||||
switch err {
|
switch err {
|
||||||
case 0:
|
case 0:
|
||||||
@ -210,15 +209,15 @@ func getExecPathFromPID(pid uint32) (string, error) {
|
|||||||
|
|
||||||
buf := make([]uint16, syscall.MAX_LONG_PATH)
|
buf := make([]uint16, syscall.MAX_LONG_PATH)
|
||||||
size := uint32(len(buf))
|
size := uint32(len(buf))
|
||||||
r1, _, err := syscall.Syscall6(
|
r1, _, err := syscall.SyscallN(
|
||||||
queryProcName, 4,
|
queryProcName,
|
||||||
uintptr(h),
|
uintptr(h),
|
||||||
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
|
||||||
}
|
}
|
||||||
return filepath.Base(syscall.UTF16ToString(buf[:size])), nil
|
return syscall.UTF16ToString(buf[:size]), nil
|
||||||
}
|
}
|
||||||
|
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"}
|
||||||
|
}
|
@ -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
|
||||||
|
|
||||||
// MainResolver resolve ip with main domain server
|
|
||||||
MainResolver 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,14 +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 ResolveIPv4WithMain(host string) (net.IP, error) {
|
|
||||||
return ResolveIPv4WithResolver(host, MainResolver)
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
||||||
@ -65,8 +54,8 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||||
@ -83,14 +72,6 @@ func ResolveIPv4WithResolver(host string, r Resolver) (net.IP, error) {
|
|||||||
|
|
||||||
// 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 ResolveIPv6WithMain(host string) (net.IP, error) {
|
|
||||||
return ResolveIPv6WithResolver(host, MainResolver)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ResolveIPv6WithResolver(host string, r Resolver) (net.IP, error) {
|
|
||||||
if DisableIPv6 {
|
if DisableIPv6 {
|
||||||
return nil, ErrIPv6Disabled
|
return nil, ErrIPv6Disabled
|
||||||
}
|
}
|
||||||
@ -109,8 +90,8 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||||
@ -157,8 +138,3 @@ func ResolveIPWithResolver(host string, r Resolver) (net.IP, error) {
|
|||||||
func ResolveIP(host string) (net.IP, error) {
|
func ResolveIP(host string) (net.IP, error) {
|
||||||
return ResolveIPWithResolver(host, DefaultResolver)
|
return ResolveIPWithResolver(host, DefaultResolver)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPWithMainResolver with a host, use main resolver, return ip
|
|
||||||
func ResolveIPWithMainResolver(host string) (net.IP, error) {
|
|
||||||
return ResolveIPWithResolver(host, MainResolver)
|
|
||||||
}
|
|
||||||
|
@ -51,7 +51,7 @@ func ValidAndSplitDomain(domain string) ([]string, bool) {
|
|||||||
// 3. subdomain.*.example.com
|
// 3. subdomain.*.example.com
|
||||||
// 4. .example.com
|
// 4. .example.com
|
||||||
// 5. +.example.com
|
// 5. +.example.com
|
||||||
func (t *DomainTrie) Insert(domain string, data interface{}) error {
|
func (t *DomainTrie) Insert(domain string, data any) error {
|
||||||
parts, valid := ValidAndSplitDomain(domain)
|
parts, valid := ValidAndSplitDomain(domain)
|
||||||
if !valid {
|
if !valid {
|
||||||
return ErrInvalidDomain
|
return ErrInvalidDomain
|
||||||
@ -68,7 +68,7 @@ func (t *DomainTrie) Insert(domain string, data interface{}) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *DomainTrie) insert(parts []string, data interface{}) {
|
func (t *DomainTrie) insert(parts []string, data any) {
|
||||||
node := t.root
|
node := t.root
|
||||||
// reverse storage domain part to save space
|
// reverse storage domain part to save space
|
||||||
for i := len(parts) - 1; i >= 0; i-- {
|
for i := len(parts) - 1; i >= 0; i-- {
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user