Compare commits
421 Commits
Prerelease
...
v1.13.2
Author | SHA1 | Date | |
---|---|---|---|
2ad84f4379 | |||
c7aa16426f | |||
4e5bdec13a | |||
fbd43d9947 | |||
5dab89c9ec | |||
2a24effac0 | |||
972d3f1d39 | |||
a7aa5fd523 | |||
b9d8b69889 | |||
dedb9122df | |||
0e5bf0c27e | |||
a46436f61a | |||
6106adc6a5 | |||
fc693bc257 | |||
bba5c2cc8a | |||
0fb0e490f8 | |||
023e3d0c41 | |||
c11a359761 | |||
0da49bd92b | |||
b9ef713dd7 | |||
4948f3f213 | |||
7b1427b843 | |||
77a3c1c3ae | |||
2c236387b7 | |||
66e5136ba0 | |||
f748e3632d | |||
90688b238a | |||
986c91b5c8 | |||
8c13426492 | |||
fefd9b7427 | |||
8a55208c62 | |||
1f8b54a92d | |||
8d74a86bf1 | |||
6c82e98bbc | |||
94246104b8 | |||
347e5e9606 | |||
e4138c3e1e | |||
f2b5ae6894 | |||
0a89107b8b | |||
2a323f77ce | |||
59edcf33bd | |||
35506e179a | |||
6ce3805719 | |||
c1a82f2fae | |||
4f9478a336 | |||
e1dc2681f1 | |||
ce77c3fd8b | |||
9f1194056a | |||
b82c9ba190 | |||
6857b05039 | |||
abbbcb02c0 | |||
ec6144250d | |||
89d1222b8f | |||
de4985a9b6 | |||
6dd8cf6c0a | |||
6b2eae36f2 | |||
13445d815b | |||
e2d71abecd | |||
ddf1c74091 | |||
1bcc916807 | |||
c06b48af0e | |||
7e9549c05a | |||
1684756b79 | |||
88e4a9a755 | |||
b133bc58f0 | |||
82c9a1a2bb | |||
e1ec4a2502 | |||
b6dc539105 | |||
6e8d8befb8 | |||
4597ed49cf | |||
ef2f8317c7 | |||
9b89ff9f2d | |||
a9694fcdc0 | |||
5987f8e3b5 | |||
3a8eb72de2 | |||
d823dde43c | |||
d69e0bce4a | |||
7f197ede51 | |||
33abbdfd24 | |||
0703d6cbff | |||
af97922e94 | |||
db94dc76b4 | |||
99effb051b | |||
98f4f4d6c4 | |||
42e489e199 | |||
d3b88d1b4f | |||
ec318f1cc5 | |||
6cfae6919f | |||
b23a071050 | |||
732e82e3d0 | |||
fecbc7a091 | |||
4b39362039 | |||
835cab58cf | |||
9317dd610b | |||
8dc56b56ad | |||
4611fbfe0c | |||
b725c91b05 | |||
482062376e | |||
32fc990c68 | |||
dfeb901417 | |||
02933ae568 | |||
4ca2d4146b | |||
5d97a7f9ca | |||
6eab1f158a | |||
65a289e16f | |||
637707e58f | |||
95e602bf3b | |||
4ac192f520 | |||
473d0f74bd | |||
93ea1248e3 | |||
97270dcbe0 | |||
50cc274b2e | |||
3867329ef3 | |||
2899a126fc | |||
5391425123 | |||
1e7af0bbc7 | |||
dd67a8c8ba | |||
28ba9c5efa | |||
bb413ece49 | |||
31f4d20477 | |||
57a15088c2 | |||
be6d55e5c4 | |||
09419d88af | |||
9c4bae6f23 | |||
b74320008a | |||
35b87e79a7 | |||
9be70f67ca | |||
bb86098235 | |||
dec32da262 | |||
a33e511c12 | |||
d71a2ce61e | |||
133bb2319f | |||
7d84a47683 | |||
38e6b81d07 | |||
143c5de51d | |||
3e424dea7b | |||
b0fd50453a | |||
fe3ad3724c | |||
e1c6142851 | |||
6e7002dbd3 | |||
6a4063af0d | |||
6b636c051a | |||
9a035d3c51 | |||
850c52d07c | |||
10f8f5dd7b | |||
4e272ff066 | |||
a73e690172 | |||
947d9d4560 | |||
179bc6ecdf | |||
fbabcfce94 | |||
3a92ad47e7 | |||
92a20a5362 | |||
9565b5194c | |||
23b2f3b971 | |||
f93dd6052e | |||
80df572b18 | |||
0c64d7e56a | |||
a8ce283727 | |||
ab8e9e7d7a | |||
dbce268692 | |||
fef9f95e65 | |||
60e1947ed2 | |||
5b35822945 | |||
0a76876764 | |||
e382496e4c | |||
0c91a4e0f3 | |||
56fae0b1f5 | |||
baee951657 | |||
253dc24e40 | |||
503b1efd8a | |||
50f2ecbcb0 | |||
97e158989f | |||
e732fbb414 | |||
f8a168e64d | |||
e599621a32 | |||
59ab2083aa | |||
2d7c4eda66 | |||
3cc1870aee | |||
8eec86232c | |||
10d2d14938 | |||
8ce9737f3d | |||
6b44178108 | |||
6664547f43 | |||
10383e2701 | |||
f4b9f2965f | |||
2ba933d16a | |||
669961e496 | |||
f979491013 | |||
0d55b28805 | |||
9c70e649ca | |||
8c079bf5bc | |||
2cdf4a0532 | |||
4ba34ce672 | |||
637f1b5aed | |||
56a87125e0 | |||
6fedc8d942 | |||
dbb834d964 | |||
449946cc15 | |||
c3671a154d | |||
6874fb785b | |||
5141ddc96e | |||
6a03371731 | |||
b658bb415b | |||
85405a54c7 | |||
30a0834e72 | |||
109a76e1fc | |||
c1a99b9be4 | |||
bf55428954 | |||
5e55d6b08f | |||
21098d2627 | |||
8da67ba61c | |||
54a0947bb4 | |||
a562b249a2 | |||
5af17f70b4 | |||
ca5bb91977 | |||
bbac54433e | |||
b6a5ec6490 | |||
aaf700f0b5 | |||
2ce89aca1e | |||
efdf69022a | |||
d4d1d4cc2a | |||
a8c4900891 | |||
930a7af8e7 | |||
77acd4ba8d | |||
691cf1d8d6 | |||
d1decb8e58 | |||
625c4a1079 | |||
341ef19099 | |||
2563b20019 | |||
1b3b5b4dfe | |||
2e6bdc5636 | |||
be298cfa16 | |||
277e71b26a | |||
f7c903a586 | |||
ff4a5bef9b | |||
d8dc44e786 | |||
c968104a19 | |||
f7481ecadf | |||
85c37b473a | |||
23bc231df3 | |||
2146b605f7 | |||
8853e97b40 | |||
7d04904109 | |||
a5acd3aa97 | |||
099aa1e3c2 | |||
63fdb348db | |||
81ee44f6c0 | |||
130a3a261d | |||
94368f43eb | |||
9a55213ddc | |||
5055542d61 | |||
23063ae0b9 | |||
a7f9aa909a | |||
15ecc451f3 | |||
186a4cfdf3 | |||
220ef9e2e2 | |||
7079116aa8 | |||
b9e6de45e6 | |||
d3503ff940 | |||
c3f4e1ba2e | |||
695fb64fa8 | |||
eea9a12560 | |||
0a4570b55c | |||
d32ab9ce74 | |||
94648989b8 | |||
07522d3c2e | |||
c14c07d2e3 | |||
9511ccfe47 | |||
ed17a1bf23 | |||
2a4f2f3942 | |||
3254eaf51c | |||
7941bae141 | |||
35a6666a84 | |||
73d5042774 | |||
9126cbab91 | |||
f8366f6e42 | |||
100c9b94ba | |||
8343c3597e | |||
d31adafa11 | |||
1acc6759e9 | |||
e995003c27 | |||
9edee2435c | |||
5d337b75f9 | |||
2188fad9c1 | |||
edc73f3f33 | |||
ade424cbb4 | |||
6e03773134 | |||
4ad0294655 | |||
43d3a0c8ea | |||
c045a4f2a7 | |||
20611eb8dc | |||
8ff7e180a4 | |||
3827e00b54 | |||
c52e689d0d | |||
cb517cb529 | |||
50bb620aa1 | |||
c745ea63b2 | |||
8e959bd245 | |||
298ca42369 | |||
ed9b9ce3c5 | |||
1298d2f8b6 | |||
6e84f685ce | |||
1ad87cfec9 | |||
9e9f459c0e | |||
fa3e0c726e | |||
3b038310ab | |||
6709936a8f | |||
04e5d02ab9 | |||
1af39cb228 | |||
c95735f083 | |||
fa2e6be05d | |||
4092a7c84b | |||
58d299c737 | |||
11ddac2b5f | |||
1f95c74f1e | |||
a197fbd4b5 | |||
708b8beadf | |||
0e1601e5b6 | |||
c7355510a2 | |||
1faa172944 | |||
7a8c98cd90 | |||
13e907bbd0 | |||
39e7832676 | |||
9b999e72ce | |||
e1a61503e4 | |||
9272d02149 | |||
067c02aba1 | |||
d0268bb9a2 | |||
fb4872ff7f | |||
2044458df9 | |||
d6df026550 | |||
7858ca6cc5 | |||
ac36473d13 | |||
72fb153fe0 | |||
527a602eba | |||
a71fd3b4df | |||
2ebc0383b5 | |||
7431001ed6 | |||
149b4b5b43 | |||
c0eb9aac1c | |||
79469fc8d6 | |||
948700eed6 | |||
3ab82849d4 | |||
0f43a19fdb | |||
cc1c1340a3 | |||
fe25ae83df | |||
c787bbe0e5 | |||
7aff9aac82 | |||
8b09db5f7f | |||
b5623602f5 | |||
16b27b3a1f | |||
8b00be9039 | |||
fa9e27c5e4 | |||
f4d9384603 | |||
c4408612b3 | |||
0742f7db26 | |||
891c2fe899 | |||
b831eb178b | |||
962ceaa89e | |||
d52b00bd34 | |||
aa0d174ccb | |||
b8e9c3d55a | |||
0b4c498c93 | |||
efc7c82cac | |||
63917aa020 | |||
5016f529af | |||
5bd5f1bfda | |||
d4dcbce9cb | |||
df8196a68c | |||
c1631759fc | |||
9e9c3c810f | |||
463101aec1 | |||
2072964701 | |||
aded1b78b5 | |||
ca9c859059 | |||
55811dae32 | |||
7136d145f8 | |||
2fbbf7519f | |||
663bf4fbb0 | |||
f0a22a4a4c | |||
4ab91520bd | |||
980d8a2641 | |||
a95d439852 | |||
a08e39faec | |||
b3295262c1 | |||
27aa026568 | |||
9969e1706e | |||
fb58595d44 | |||
bdfa16ca6f | |||
b307bcb4a9 | |||
f26941091b | |||
6cd5769ed7 | |||
41adfa65b3 | |||
3fbb7c7a2d | |||
0aa82c04ea | |||
5c6f2694c7 | |||
eca7615f08 | |||
52d559bb38 | |||
259736390a | |||
7db07630a7 | |||
d617b0f447 | |||
80ff5917f7 | |||
b401da5eba | |||
05b25c334f | |||
2c5a47a275 | |||
b2605a9012 | |||
b929a19f48 | |||
4b04faa88b | |||
5fee0b5bf1 | |||
27120fb0f5 | |||
0cf539fb82 | |||
26a38bd8de | |||
ebbce4d061 | |||
5acd2f6c3a | |||
fe2bc903b8 | |||
658f1f5cda | |||
5ccc047fe4 | |||
6d704b9cd1 | |||
5f957b5cf9 | |||
8681728b8d | |||
45a02e3439 |
14
.github/workflows/prerelease.yml
vendored
14
.github/workflows/prerelease.yml
vendored
@ -17,7 +17,7 @@ jobs:
|
|||||||
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@v3
|
||||||
with:
|
with:
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
|
|
||||||
@ -34,7 +34,7 @@ jobs:
|
|||||||
|
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
if: ${{env.GITHUB_REF_NAME=='Beta'}}
|
if: ${{github.ref_name=='Beta'}}
|
||||||
run: |
|
run: |
|
||||||
go test ./...
|
go test ./...
|
||||||
|
|
||||||
@ -43,19 +43,19 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
NAME: Clash.Meta
|
NAME: Clash.Meta
|
||||||
BINDIR: bin
|
BINDIR: bin
|
||||||
run: make -j releases
|
run: make -j$(($(nproc) + 1)) releases
|
||||||
|
|
||||||
- name: Delete current release assets
|
- name: Delete current release assets
|
||||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||||
with:
|
with:
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
tag: Prerelease-${{env.GITHUB_REF_NAME}}
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
deleteOnlyFromDrafts: false
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
- name: Tag Repo
|
- name: Tag Repo
|
||||||
uses: richardsimko/update-tag@v1
|
uses: richardsimko/update-tag@v1
|
||||||
with:
|
with:
|
||||||
tag_name: Prerelease-${{env.GITHUB_REF_NAME}}
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
@ -63,8 +63,8 @@ jobs:
|
|||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
if: ${{ success() }}
|
if: ${{ success() }}
|
||||||
with:
|
with:
|
||||||
tag: ${{env.GITHUB_REF_NAME}}
|
tag: ${{ github.ref_name }}
|
||||||
tag_name: Prerelease-${{env.GITHUB_REF_NAME}}
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
files: bin/*
|
files: bin/*
|
||||||
prerelease: true
|
prerelease: true
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
|
2
.github/workflows/release.yaml
vendored
2
.github/workflows/release.yaml
vendored
@ -33,7 +33,7 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
NAME: Clash.Meta
|
NAME: Clash.Meta
|
||||||
BINDIR: bin
|
BINDIR: bin
|
||||||
run: make -j releases
|
run: make -j$(($(nproc) + 1)) releases
|
||||||
|
|
||||||
- name: Upload Release
|
- name: Upload Release
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
|
@ -16,7 +16,7 @@ RUN go mod download &&\
|
|||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata
|
RUN apk add --no-cache ca-certificates tzdata iptables
|
||||||
|
|
||||||
VOLUME ["/root/.config/clash/"]
|
VOLUME ["/root/.config/clash/"]
|
||||||
|
|
||||||
|
49
Makefile
49
Makefile
@ -5,25 +5,22 @@ ifeq ($(BRANCH),Alpha)
|
|||||||
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
||||||
else ifeq ($(BRANCH),Beta)
|
else ifeq ($(BRANCH),Beta)
|
||||||
VERSION=beta-$(shell git rev-parse --short HEAD)
|
VERSION=beta-$(shell git rev-parse --short HEAD)
|
||||||
else ifeq ($(BRANCH),HEAD)
|
else ifeq ($(BRANCH),)
|
||||||
VERSION=$(shell git describe --tags)
|
VERSION=$(shell git describe --tags)
|
||||||
else
|
else
|
||||||
VERSION=unknown
|
VERSION=$(shell git rev-parse --short HEAD)
|
||||||
endif
|
endif
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64v1 \
|
darwin-amd64 \
|
||||||
darwin-amd64v2 \
|
|
||||||
darwin-amd64v3 \
|
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64v1 \
|
linux-amd64-compatible \
|
||||||
linux-amd64v2 \
|
linux-amd64 \
|
||||||
linux-amd64v3 \
|
|
||||||
linux-armv5 \
|
linux-armv5 \
|
||||||
linux-armv6 \
|
linux-armv6 \
|
||||||
linux-armv7 \
|
linux-armv7 \
|
||||||
@ -41,9 +38,8 @@ PLATFORM_LIST = \
|
|||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
windows-386 \
|
windows-386 \
|
||||||
windows-amd64v1 \
|
windows-amd64-compatible \
|
||||||
windows-amd64v2 \
|
windows-amd64 \
|
||||||
windows-amd64v3 \
|
|
||||||
windows-arm64 \
|
windows-arm64 \
|
||||||
windows-arm32v7
|
windows-arm32v7
|
||||||
|
|
||||||
@ -54,30 +50,24 @@ all:linux-amd64 linux-arm64\
|
|||||||
docker:
|
docker:
|
||||||
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64v3:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64v2:
|
darwin-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64v1:
|
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-386:
|
linux-386:
|
||||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64v3:
|
linux-amd64:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64v2:
|
linux-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64v1:
|
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-arm64:
|
linux-arm64:
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -123,15 +113,12 @@ freebsd-arm64:
|
|||||||
windows-386:
|
windows-386:
|
||||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64v3:
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64v2:
|
windows-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64v1:
|
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
|
||||||
|
|
||||||
windows-arm64:
|
windows-arm64:
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
@ -160,3 +147,11 @@ lint:
|
|||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm $(BINDIR)/*
|
rm $(BINDIR)/*
|
||||||
|
|
||||||
|
CLANG ?= clang-14
|
||||||
|
CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
||||||
|
|
||||||
|
ebpf: export BPF_CLANG := $(CLANG)
|
||||||
|
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
||||||
|
ebpf:
|
||||||
|
cd component/ebpf/ && go generate ./...
|
@ -251,8 +251,8 @@ User=clash-meta
|
|||||||
Group=clash-meta
|
Group=clash-meta
|
||||||
LimitNPROC=500
|
LimitNPROC=500
|
||||||
LimitNOFILE=1000000
|
LimitNOFILE=1000000
|
||||||
CapabilityBoundingSet=cap_net_admin
|
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
|
||||||
AmbientCapabilities=cap_net_admin
|
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
|
||||||
Restart=always
|
Restart=always
|
||||||
ExecStartPre=/usr/bin/sleep 1s
|
ExecStartPre=/usr/bin/sleep 1s
|
||||||
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
||||||
@ -274,7 +274,7 @@ $ systemctl start Clash-Meta
|
|||||||
|
|
||||||
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
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).
|
To display process name in GUI please use [Dashboard For Meta](https://github.com/MetaCubeX/clash-dashboard).
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
@ -4,17 +4,15 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -41,11 +39,6 @@ func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
|||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
||||||
wasCancel := false
|
|
||||||
if err != nil {
|
|
||||||
wasCancel = strings.Contains(err.Error(), "operation was canceled")
|
|
||||||
}
|
|
||||||
p.alive.Store(err == nil || wasCancel)
|
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,7 +52,6 @@ func (p *Proxy) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
||||||
p.alive.Store(err == nil)
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -152,25 +144,32 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{
|
client := http.Client{
|
||||||
|
Timeout: 30 * time.Second,
|
||||||
Transport: transport,
|
Transport: transport,
|
||||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
return http.ErrUseLastResponse
|
return http.ErrUseLastResponse
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
defer client.CloseIdleConnections()
|
defer client.CloseIdleConnections()
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
|
||||||
if unifiedDelay {
|
if unifiedDelay {
|
||||||
start = time.Now()
|
second := time.Now()
|
||||||
resp, err = client.Do(req)
|
resp, err = client.Do(req)
|
||||||
if err != nil {
|
if err == nil {
|
||||||
return
|
_ = resp.Body.Close()
|
||||||
|
start = second
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ = resp.Body.Close()
|
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ import (
|
|||||||
// NewHTTPS receive CONNECT request and return ConnContext
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPCONNECT
|
metadata.Type = C.HTTPS
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
@ -26,7 +26,8 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
|||||||
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
||||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||||
case socks5.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv6len]))
|
ip6, _ := netip.AddrFromSlice(target[1 : 1+net.IPv6len])
|
||||||
|
metadata.DstIP = ip6.Unmap()
|
||||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,24 +2,25 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha1"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
"net"
|
"net"
|
||||||
"regexp"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
name string
|
name string
|
||||||
addr string
|
addr string
|
||||||
iface string
|
iface string
|
||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
rmark int
|
rmark int
|
||||||
|
id string
|
||||||
|
prefer C.DNSPrefer
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implements C.ProxyAdapter
|
// Name implements C.ProxyAdapter
|
||||||
@ -27,6 +28,20 @@ func (b *Base) Name() string {
|
|||||||
return b.name
|
return b.name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Id implements C.ProxyAdapter
|
||||||
|
func (b *Base) Id() string {
|
||||||
|
if b.id == "" {
|
||||||
|
id, err := uuid.NewV6()
|
||||||
|
if err != nil {
|
||||||
|
b.id = b.name
|
||||||
|
} else {
|
||||||
|
b.id = id.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return b.id
|
||||||
|
}
|
||||||
|
|
||||||
// Type implements C.ProxyAdapter
|
// Type implements C.ProxyAdapter
|
||||||
func (b *Base) Type() C.AdapterType {
|
func (b *Base) Type() C.AdapterType {
|
||||||
return b.tp
|
return b.tp
|
||||||
@ -37,6 +52,10 @@ func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return c, errors.New("no support")
|
return c, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
@ -61,6 +80,7 @@ func (b *Base) SupportUDP() bool {
|
|||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]string{
|
return json.Marshal(map[string]string{
|
||||||
"type": b.Type().String(),
|
"type": b.Type().String(),
|
||||||
|
"id": b.Id(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,7 +90,7 @@ func (b *Base) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (b *Base) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -84,12 +104,25 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
|||||||
opts = append(opts, dialer.WithRoutingMark(b.rmark))
|
opts = append(opts, dialer.WithRoutingMark(b.rmark))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch b.prefer {
|
||||||
|
case C.IPv4Only:
|
||||||
|
opts = append(opts, dialer.WithOnlySingleStack(true))
|
||||||
|
case C.IPv6Only:
|
||||||
|
opts = append(opts, dialer.WithOnlySingleStack(false))
|
||||||
|
case C.IPv4Prefer:
|
||||||
|
opts = append(opts, dialer.WithPreferIPv4())
|
||||||
|
case C.IPv6Prefer:
|
||||||
|
opts = append(opts, dialer.WithPreferIPv6())
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||||
|
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaseOption struct {
|
type BaseOption struct {
|
||||||
@ -99,22 +132,29 @@ type BaseOption struct {
|
|||||||
UDP bool
|
UDP bool
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
|
Prefer C.DNSPrefer
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBase(opt BaseOption) *Base {
|
func NewBase(opt BaseOption) *Base {
|
||||||
return &Base{
|
return &Base{
|
||||||
name: opt.Name,
|
name: opt.Name,
|
||||||
addr: opt.Addr,
|
addr: opt.Addr,
|
||||||
tp: opt.Type,
|
tp: opt.Type,
|
||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
|
prefer: opt.Prefer,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
|
actualRemoteDestination string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) RemoteDestination() string {
|
||||||
|
return c.actualRemoteDestination
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@ -128,12 +168,17 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
return &conn{c, []string{a.Name()}}
|
return &conn{c, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
net.PacketConn
|
net.PacketConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
|
actualRemoteDestination string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) RemoteDestination() string {
|
||||||
|
return c.actualRemoteDestination
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@ -147,30 +192,17 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
return &packetConn{pc, []string{a.Name()}}
|
return &packetConn{pc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
func uuidMap(str string) string {
|
func parseRemoteDestination(addr string) string {
|
||||||
match, _ := regexp.MatchString(`[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$`, str)
|
if dst, _, err := net.SplitHostPort(addr); err == nil {
|
||||||
if !match {
|
return dst
|
||||||
var Nil [16]byte
|
} else {
|
||||||
h := sha1.New()
|
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
|
||||||
h.Write(Nil[:])
|
return dst
|
||||||
h.Write([]byte(str))
|
} else {
|
||||||
u := h.Sum(nil)[:16]
|
return ""
|
||||||
u[6] = (u[6] & 0x0f) | (5 << 4)
|
}
|
||||||
u[8] = u[8]&(0xff>>2) | (0x02 << 6)
|
|
||||||
buf := make([]byte, 36)
|
|
||||||
hex.Encode(buf[0:8], u[0:4])
|
|
||||||
buf[8] = '-'
|
|
||||||
hex.Encode(buf[9:13], u[4:6])
|
|
||||||
buf[13] = '-'
|
|
||||||
hex.Encode(buf[14:18], u[6:8])
|
|
||||||
buf[18] = '-'
|
|
||||||
hex.Encode(buf[19:23], u[8:10])
|
|
||||||
buf[23] = '-'
|
|
||||||
hex.Encode(buf[24:], u[10:])
|
|
||||||
return string(buf)
|
|
||||||
}
|
}
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
@ -40,9 +40,10 @@ type directPacketConn struct {
|
|||||||
func NewDirect() *Direct {
|
func NewDirect() *Direct {
|
||||||
return &Direct{
|
return &Direct{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "DIRECT",
|
name: "DIRECT",
|
||||||
tp: C.Direct,
|
tp: C.Direct,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -50,19 +51,10 @@ func NewDirect() *Direct {
|
|||||||
func NewCompatible() *Direct {
|
func NewCompatible() *Direct {
|
||||||
return &Direct{
|
return &Direct{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "COMPATIBLE",
|
name: "COMPATIBLE",
|
||||||
tp: C.Compatible,
|
tp: C.Compatible,
|
||||||
udp: true,
|
udp: true,
|
||||||
},
|
prefer: C.DualStack,
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPass() *Direct {
|
|
||||||
return &Direct{
|
|
||||||
Base: &Base{
|
|
||||||
name: "PASS",
|
|
||||||
tp: C.Pass,
|
|
||||||
udp: true,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,7 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -35,6 +36,7 @@ type HttpOption struct {
|
|||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -126,30 +128,41 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHttp(option HttpOption) *Http {
|
func NewHttp(option HttpOption) (*Http, error) {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
sni := option.Server
|
sni := option.Server
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
tlsConfig = &tls.Config{
|
if len(option.Fingerprint) == 0 {
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||||
ServerName: sni,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
}, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Http{
|
return &Http{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
option: &option,
|
option: &option,
|
||||||
}
|
}, nil
|
||||||
}
|
}
|
||||||
|
332
adapter/outbound/hysteria.go
Normal file
332
adapter/outbound/hysteria.go
Normal file
@ -0,0 +1,332 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/lucas-clemente/quic-go"
|
||||||
|
"github.com/lucas-clemente/quic-go/congestion"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/core"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
mbpsToBps = 125000
|
||||||
|
minSpeedBPS = 16384
|
||||||
|
|
||||||
|
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
||||||
|
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
||||||
|
DefaultMaxIncomingStreams = 1024
|
||||||
|
|
||||||
|
DefaultALPN = "hysteria"
|
||||||
|
DefaultProtocol = "udp"
|
||||||
|
)
|
||||||
|
|
||||||
|
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||||
|
|
||||||
|
type Hysteria struct {
|
||||||
|
*Base
|
||||||
|
|
||||||
|
client *core.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
hdc := hyDialerWithContext{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hyDialer: func() (net.PacketConn, error) {
|
||||||
|
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
||||||
|
},
|
||||||
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
|
return resolveUDPAddrWithPrefer("udp", addr, h.prefer)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), &hdc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(tcpConn, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
hdc := hyDialerWithContext{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hyDialer: func() (net.PacketConn, error) {
|
||||||
|
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
||||||
|
},
|
||||||
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
|
return resolveUDPAddrWithPrefer("udp", addr, h.prefer)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
udpConn, err := h.client.DialUDP(&hdc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type HysteriaOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
|
ObfsProtocol string `proxy:"obfs-protocol,omitempty"` // compatible with Stash
|
||||||
|
Up string `proxy:"up"`
|
||||||
|
UpSpeed int `proxy:"up-speed,omitempty"` // compatible with Stash
|
||||||
|
Down string `proxy:"down"`
|
||||||
|
DownSpeed int `proxy:"down-speed,omitempty"` // compatible with Stash
|
||||||
|
Auth string `proxy:"auth,omitempty"`
|
||||||
|
AuthString string `proxy:"auth_str,omitempty"`
|
||||||
|
Obfs string `proxy:"obfs,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
|
CustomCAString string `proxy:"ca_str,omitempty"`
|
||||||
|
ReceiveWindowConn int `proxy:"recv_window_conn,omitempty"`
|
||||||
|
ReceiveWindow int `proxy:"recv_window,omitempty"`
|
||||||
|
DisableMTUDiscovery bool `proxy:"disable_mtu_discovery,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||||
|
var up, down uint64
|
||||||
|
up = stringToBps(c.Up)
|
||||||
|
if up == 0 {
|
||||||
|
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
||||||
|
}
|
||||||
|
|
||||||
|
down = stringToBps(c.Down)
|
||||||
|
if down == 0 {
|
||||||
|
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
||||||
|
}
|
||||||
|
|
||||||
|
return up, down, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
||||||
|
clientTransport := &transport.ClientTransport{
|
||||||
|
Dialer: &net.Dialer{
|
||||||
|
Timeout: 8 * time.Second,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
serverName := option.Server
|
||||||
|
if option.SNI != "" {
|
||||||
|
serverName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
ServerName: serverName,
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
}
|
||||||
|
|
||||||
|
var bs []byte
|
||||||
|
var err error
|
||||||
|
if len(option.CustomCA) > 0 {
|
||||||
|
bs, err = os.ReadFile(option.CustomCA)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
|
||||||
|
}
|
||||||
|
} else if option.CustomCAString != "" {
|
||||||
|
bs = []byte(option.CustomCAString)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(bs) > 0 {
|
||||||
|
block, _ := pem.Decode(bs)
|
||||||
|
if block == nil {
|
||||||
|
return nil, fmt.Errorf("CA cert is not PEM")
|
||||||
|
}
|
||||||
|
|
||||||
|
fpBytes := sha256.Sum256(block.Bytes)
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) != 0 {
|
||||||
|
var err error
|
||||||
|
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.ALPN) > 0 {
|
||||||
|
tlsConfig.NextProtos = option.ALPN
|
||||||
|
} else {
|
||||||
|
tlsConfig.NextProtos = []string{DefaultALPN}
|
||||||
|
}
|
||||||
|
|
||||||
|
quicConfig := &quic.Config{
|
||||||
|
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
|
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
|
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
|
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
|
KeepAlivePeriod: 10 * time.Second,
|
||||||
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
|
EnableDatagrams: true,
|
||||||
|
}
|
||||||
|
if option.ObfsProtocol != "" {
|
||||||
|
option.Protocol = option.ObfsProtocol
|
||||||
|
}
|
||||||
|
if option.Protocol == "" {
|
||||||
|
option.Protocol = DefaultProtocol
|
||||||
|
}
|
||||||
|
if option.ReceiveWindowConn == 0 {
|
||||||
|
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
|
||||||
|
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
||||||
|
}
|
||||||
|
if option.ReceiveWindow == 0 {
|
||||||
|
quicConfig.InitialConnectionReceiveWindow = DefaultConnectionReceiveWindow / 10
|
||||||
|
quicConfig.MaxConnectionReceiveWindow = DefaultConnectionReceiveWindow
|
||||||
|
}
|
||||||
|
if !quicConfig.DisablePathMTUDiscovery && pmtud_fix.DisablePathMTUDiscovery {
|
||||||
|
log.Infoln("hysteria: Path MTU Discovery is not yet supported on this platform")
|
||||||
|
}
|
||||||
|
|
||||||
|
var auth = []byte(option.AuthString)
|
||||||
|
if option.Auth != "" {
|
||||||
|
auth, err = base64.StdEncoding.DecodeString(option.Auth)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var obfuscator obfs.Obfuscator
|
||||||
|
if len(option.Obfs) > 0 {
|
||||||
|
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
||||||
|
}
|
||||||
|
|
||||||
|
up, down, err := option.Speed()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if option.UpSpeed != 0 {
|
||||||
|
up = uint64(option.UpSpeed * mbpsToBps)
|
||||||
|
}
|
||||||
|
if option.DownSpeed != 0 {
|
||||||
|
down = uint64(option.DownSpeed * mbpsToBps)
|
||||||
|
}
|
||||||
|
client, err := core.NewClient(
|
||||||
|
addr, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
||||||
|
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
||||||
|
}, obfuscator,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||||
|
}
|
||||||
|
return &Hysteria{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Hysteria,
|
||||||
|
udp: true,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
client: client,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func stringToBps(s string) uint64 {
|
||||||
|
if s == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// when have not unit, use Mbps
|
||||||
|
if v, err := strconv.Atoi(s); err == nil {
|
||||||
|
return stringToBps(fmt.Sprintf("%d Mbps", v))
|
||||||
|
}
|
||||||
|
|
||||||
|
m := rateStringRegexp.FindStringSubmatch(s)
|
||||||
|
if m == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var n uint64
|
||||||
|
switch m[2] {
|
||||||
|
case "K":
|
||||||
|
n = 1 << 10
|
||||||
|
case "M":
|
||||||
|
n = 1 << 20
|
||||||
|
case "G":
|
||||||
|
n = 1 << 30
|
||||||
|
case "T":
|
||||||
|
n = 1 << 40
|
||||||
|
default:
|
||||||
|
n = 1
|
||||||
|
}
|
||||||
|
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||||
|
n = v * n
|
||||||
|
if m[3] == "b" {
|
||||||
|
// Bits, need to convert to bytes
|
||||||
|
n = n >> 3
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
type hyPacketConn struct {
|
||||||
|
core.UDPConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *hyPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
b, addrStr, err := c.UDPConn.ReadFrom()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n = copy(p, b)
|
||||||
|
addr = M.ParseSocksaddr(addrStr).UDPAddr()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
|
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n = len(p)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type hyDialerWithContext struct {
|
||||||
|
hyDialer func() (net.PacketConn, error)
|
||||||
|
ctx context.Context
|
||||||
|
remoteAddr func(host string) (net.Addr, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) ListenPacket() (net.PacketConn, error) {
|
||||||
|
return h.hyDialer()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) Context() context.Context {
|
||||||
|
return h.ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) RemoteAddr(host string) (net.Addr, error) {
|
||||||
|
return h.remoteAddr(host)
|
||||||
|
}
|
@ -27,9 +27,21 @@ func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
func NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
return &Reject{
|
return &Reject{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "REJECT",
|
name: "REJECT",
|
||||||
tp: C.Reject,
|
tp: C.Reject,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPass() *Reject {
|
||||||
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "PASS",
|
||||||
|
tp: C.Pass,
|
||||||
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,14 +13,18 @@ import (
|
|||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
"github.com/sagernet/sing-shadowsocks"
|
||||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
"github.com/sagernet/sing/common/uot"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
*Base
|
*Base
|
||||||
cipher core.Cipher
|
method shadowsocks.Method
|
||||||
|
|
||||||
|
option *ShadowSocksOption
|
||||||
// obfs
|
// obfs
|
||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
@ -37,6 +41,7 @@ type ShadowSocksOption struct {
|
|||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
|
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -49,6 +54,7 @@ type v2rayObfsOption struct {
|
|||||||
Host string `obfs:"host,omitempty"`
|
Host string `obfs:"host,omitempty"`
|
||||||
Path string `obfs:"path,omitempty"`
|
Path string `obfs:"path,omitempty"`
|
||||||
TLS bool `obfs:"tls,omitempty"`
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
Headers map[string]string `obfs:"headers,omitempty"`
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
@ -69,9 +75,10 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c = ss.cipher.StreamConn(c)
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
_, err := c.Write(serializesSocksAddr(metadata))
|
return ss.method.DialConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443"))
|
||||||
return c, err
|
}
|
||||||
|
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -90,26 +97,43 @@ func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
if ss.option.UDPOverTCP {
|
||||||
|
tcpConn, err := ss.DialContext(ctx, metadata, opts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
||||||
|
}
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddr("udp", ss.addr)
|
addr, err := resolveUDPAddrWithPrefer("udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.Close()
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
||||||
|
return newPacketConn(pc, ss), nil
|
||||||
|
}
|
||||||
|
|
||||||
pc = ss.cipher.PacketConn(pc)
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
|
func (ss *ShadowSocks) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if ss.option.UDPOverTCP {
|
||||||
|
return newPacketConn(uot.NewClientConn(c), ss), nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) SupportUOT() bool {
|
||||||
|
return ss.option.UDPOverTCP
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
cipher := option.Cipher
|
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
||||||
password := option.Password
|
|
||||||
ciph, err := core.PickCipher(cipher, nil, password)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
}
|
}
|
||||||
@ -155,15 +179,17 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
cipher: ciph,
|
method: method,
|
||||||
|
|
||||||
|
option: &option,
|
||||||
obfsMode: obfsMode,
|
obfsMode: obfsMode,
|
||||||
v2rayOption: v2rayOption,
|
v2rayOption: v2rayOption,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -8,12 +8,11 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
||||||
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/shadowaead"
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/shadowstream"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocksR struct {
|
type ShadowSocksR struct {
|
||||||
@ -80,7 +79,7 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddr("udp", ssr.addr)
|
addr, err := resolveUDPAddrWithPrefer("udp", ssr.addr, ssr.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.Close()
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -144,12 +143,13 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
|
|
||||||
return &ShadowSocksR{
|
return &ShadowSocksR{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
|
@ -99,7 +99,13 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
|
||||||
return s.ListenPacketOnStreamConn(c, metadata)
|
err = snell.WriteUDPHeader(c, s.version)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := snell.PacketConn(c)
|
||||||
|
return newPacketConn(pc, s), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
@ -146,12 +152,13 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
|
|
||||||
s := &Snell{
|
s := &Snell{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -33,6 +34,7 @@ type Socks5Option struct {
|
|||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
@ -138,30 +140,40 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) *Socks5 {
|
func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig = &tls.Config{
|
tlsConfig = &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Socks5{
|
return &Socks5{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
skipCertVerify: option.SkipCertVerify,
|
skipCertVerify: option.SkipCertVerify,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
}
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type socksPacketConn struct {
|
type socksPacketConn struct {
|
||||||
|
@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -13,8 +14,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Trojan struct {
|
type Trojan struct {
|
||||||
@ -25,7 +24,7 @@ type Trojan struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
transport *gun.TransportWrap
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
@ -37,6 +36,7 @@ type TrojanOption struct {
|
|||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
@ -161,7 +161,13 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.ListenPacketOnStreamConn(c, metadata)
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
return newPacketConn(pc, t), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
@ -184,6 +190,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
FlowShow: option.FlowShow,
|
FlowShow: option.FlowShow,
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
@ -202,12 +209,13 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
|
|
||||||
t := &Trojan{
|
t := &Trojan{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Trojan,
|
tp: C.Trojan,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
instance: trojan.New(tOption),
|
instance: trojan.New(tOption),
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -230,6 +238,15 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: tOption.ServerName,
|
ServerName: tOption.ServerName,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if t.option.Flow != "" {
|
if t.option.Flow != "" {
|
||||||
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
xtls "github.com/xtls/go"
|
xtls "github.com/xtls/go"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@ -74,6 +75,63 @@ func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
|||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func resolveUDPAddrWithPrefer(network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var ip netip.Addr
|
||||||
|
switch prefer {
|
||||||
|
case C.IPv4Only:
|
||||||
|
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||||
|
case C.IPv6Only:
|
||||||
|
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||||
|
case C.IPv6Prefer:
|
||||||
|
var ips []netip.Addr
|
||||||
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
var fallback netip.Addr
|
||||||
|
if err == nil {
|
||||||
|
for _, addr := range ips {
|
||||||
|
if addr.Is6() {
|
||||||
|
ip = addr
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
if !fallback.IsValid() {
|
||||||
|
fallback = addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ip = fallback
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// C.IPv4Prefer, C.DualStack and other
|
||||||
|
var ips []netip.Addr
|
||||||
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
var fallback netip.Addr
|
||||||
|
if err == nil {
|
||||||
|
for _, addr := range ips {
|
||||||
|
if addr.Is4() {
|
||||||
|
ip = addr
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
if !fallback.IsValid() {
|
||||||
|
fallback = addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ip.IsValid() && fallback.IsValid() {
|
||||||
|
ip = fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
|
}
|
||||||
|
|
||||||
func safeConnClose(c net.Conn, err error) {
|
func safeConnClose(c net.Conn, err error) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
|
@ -6,6 +6,8 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -18,8 +20,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -35,7 +35,7 @@ type Vless struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
transport *gun.TransportWrap
|
||||||
}
|
}
|
||||||
|
|
||||||
type VlessOption struct {
|
type VlessOption struct {
|
||||||
@ -56,6 +56,7 @@ type VlessOption struct {
|
|||||||
WSPath string `proxy:"ws-path,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,27 +72,39 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
header := http.Header{}
|
|
||||||
for key, value := range v.option.WSOpts.Headers {
|
for key, value := range v.option.WSOpts.Headers {
|
||||||
header.Add(key, value)
|
wsOpts.Headers.Add(key, value)
|
||||||
}
|
}
|
||||||
wsOpts.Headers = header
|
|
||||||
}
|
}
|
||||||
|
if v.option.TLS {
|
||||||
|
wsOpts.TLS = true
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
ServerName: host,
|
||||||
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
|
NextProtos: []string{"http/1.1"},
|
||||||
|
}
|
||||||
|
|
||||||
wsOpts.TLS = true
|
if len(v.option.Fingerprint) == 0 {
|
||||||
wsOpts.TLSConfig = &tls.Config{
|
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
MinVersion: tls.VersionTLS12,
|
} else {
|
||||||
ServerName: host,
|
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
}
|
||||||
NextProtos: []string{"http/1.1"},
|
|
||||||
}
|
if v.option.ServerName != "" {
|
||||||
if v.option.ServerName != "" {
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
wsOpts.TLSConfig.ServerName = host
|
||||||
wsOpts.TLSConfig.ServerName = host
|
}
|
||||||
|
} else {
|
||||||
|
if host := wsOpts.Headers.Get("Host"); host == "" {
|
||||||
|
wsOpts.Headers.Set("Host", convert.RandHost())
|
||||||
|
convert.SetUserAgent(wsOpts.Headers)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
@ -148,6 +161,7 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
xtlsOpts := vless.XTLSConfig{
|
xtlsOpts := vless.XTLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -164,6 +178,7 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -396,18 +411,19 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
client, err := vless.NewClient(uuidMap(option.UUID), addons, option.FlowShow)
|
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
v := &Vless{
|
v := &Vless{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vless,
|
tp: C.Vless,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -432,10 +448,10 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
}
|
}
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
}
|
})
|
||||||
|
|
||||||
if v.option.ServerName == "" {
|
if v.option.ServerName == "" {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
@ -5,18 +5,21 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
vmess "github.com/sagernet/sing-vmess"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
"golang.org/x/net/http2"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
@ -27,30 +30,32 @@ type Vmess struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
transport *gun.TransportWrap
|
||||||
}
|
}
|
||||||
|
|
||||||
type VmessOption struct {
|
type VmessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
AlterID int `proxy:"alterId"`
|
AlterID int `proxy:"alterId"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
// TODO: compatible with VMESS WS older version configurations
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
|
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||||
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -80,49 +85,52 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
var err error
|
var err error
|
||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
if v.option.WSOpts.Path == "" {
|
|
||||||
v.option.WSOpts.Path = v.option.WSPath
|
|
||||||
}
|
|
||||||
if len(v.option.WSOpts.Headers) == 0 {
|
|
||||||
v.option.WSOpts.Headers = v.option.WSHeaders
|
|
||||||
}
|
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &clashVMess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
header := http.Header{}
|
|
||||||
for key, value := range v.option.WSOpts.Headers {
|
for key, value := range v.option.WSOpts.Headers {
|
||||||
header.Add(key, value)
|
wsOpts.Headers.Add(key, value)
|
||||||
}
|
}
|
||||||
wsOpts.Headers = header
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
wsOpts.TLS = true
|
wsOpts.TLS = true
|
||||||
wsOpts.TLSConfig = &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: host,
|
ServerName: host,
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"http/1.1"},
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(v.option.Fingerprint) == 0 {
|
||||||
|
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
c, err = clashVMess.StreamWebsocketConn(c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &vmess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
}
|
}
|
||||||
@ -131,24 +139,24 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
httpOpts := &vmess.HTTPConfig{
|
httpOpts := &clashVMess.HTTPConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Method: v.option.HTTPOpts.Method,
|
Method: v.option.HTTPOpts.Method,
|
||||||
Path: v.option.HTTPOpts.Path,
|
Path: v.option.HTTPOpts.Path,
|
||||||
Headers: v.option.HTTPOpts.Headers,
|
Headers: v.option.HTTPOpts.Headers,
|
||||||
}
|
}
|
||||||
|
|
||||||
c = vmess.StreamHTTPConn(c, httpOpts)
|
c = clashVMess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
@ -158,24 +166,24 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamTLSConn(c, &tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, &tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
h2Opts := &vmess.H2Config{
|
h2Opts := &clashVMess.H2Config{
|
||||||
Hosts: v.option.HTTP2Opts.Host,
|
Hosts: v.option.HTTP2Opts.Host,
|
||||||
Path: v.option.HTTP2Opts.Path,
|
Path: v.option.HTTP2Opts.Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamH2Conn(c, h2Opts)
|
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
default:
|
default:
|
||||||
// handle TLS
|
// handle TLS
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &vmess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
}
|
}
|
||||||
@ -184,15 +192,22 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
return v.client.StreamConn(c, parseVmessAddr(metadata))
|
if v.option.XUDP {
|
||||||
|
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -205,7 +220,7 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
c, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -235,6 +250,13 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if v.option.PacketAddr {
|
||||||
|
_metadata := *metadata // make a copy
|
||||||
|
metadata = &_metadata
|
||||||
|
metadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
|
metadata.DstPort = "443"
|
||||||
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.transport != nil && len(opts) == 0 {
|
||||||
@ -244,7 +266,11 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
if v.option.XUDP {
|
||||||
|
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -260,11 +286,21 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
if v.option.PacketAddr {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindConn(c)}, v), nil
|
||||||
|
} else if pc, ok := c.(net.PacketConn); ok {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
|
}
|
||||||
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if v.option.PacketAddr {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindConn(c)}, v), nil
|
||||||
|
} else if pc, ok := c.(net.PacketConn); ok {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
|
}
|
||||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -275,18 +311,28 @@ func (v *Vmess) SupportUOT() bool {
|
|||||||
|
|
||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
security := strings.ToLower(option.Cipher)
|
security := strings.ToLower(option.Cipher)
|
||||||
client, err := vmess.NewClient(vmess.Config{
|
var options []vmess.ClientOption
|
||||||
UUID: uuidMap(option.UUID),
|
if option.GlobalPadding {
|
||||||
AlterID: uint16(option.AlterID),
|
options = append(options, vmess.ClientWithGlobalPadding())
|
||||||
Security: security,
|
}
|
||||||
HostName: option.Server,
|
if option.AuthenticatedLength {
|
||||||
Port: strconv.Itoa(option.Port),
|
options = append(options, vmess.ClientWithAuthenticatedLength())
|
||||||
IsAead: option.AlterID == 0,
|
}
|
||||||
})
|
client, err := vmess.NewClient(option.UUID, security, option.AlterID, options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch option.PacketEncoding {
|
||||||
|
case "packetaddr", "packet":
|
||||||
|
option.PacketAddr = true
|
||||||
|
case "xudp":
|
||||||
|
option.XUDP = true
|
||||||
|
}
|
||||||
|
if option.XUDP {
|
||||||
|
option.PacketAddr = false
|
||||||
|
}
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2", "grpc":
|
case "h2", "grpc":
|
||||||
if !option.TLS {
|
if !option.TLS {
|
||||||
@ -296,12 +342,13 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
|
|
||||||
v := &Vmess{
|
v := &Vmess{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vmess,
|
tp: C.Vmess,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -341,44 +388,29 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
type threadSafePacketConn struct {
|
||||||
var addrType byte
|
net.PacketConn
|
||||||
var addr []byte
|
access sync.Mutex
|
||||||
switch metadata.AddrType {
|
}
|
||||||
case C.AtypIPv4:
|
|
||||||
addrType = byte(vmess.AtypIPv4)
|
|
||||||
addr = make([]byte, net.IPv4len)
|
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
|
||||||
case C.AtypIPv6:
|
|
||||||
addrType = byte(vmess.AtypIPv6)
|
|
||||||
addr = make([]byte, net.IPv6len)
|
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
|
||||||
case C.AtypDomainName:
|
|
||||||
addrType = byte(vmess.AtypDomainName)
|
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
|
||||||
addr[0] = byte(len(metadata.Host))
|
|
||||||
copy(addr[1:], []byte(metadata.Host))
|
|
||||||
}
|
|
||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
return &vmess.DstAddr{
|
c.access.Lock()
|
||||||
UDP: metadata.NetWork == C.UDP,
|
defer c.access.Unlock()
|
||||||
AddrType: addrType,
|
return c.PacketConn.WriteTo(b, addr)
|
||||||
Addr: addr,
|
|
||||||
Port: uint(port),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type vmessPacketConn struct {
|
type vmessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
|
access sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
uc.access.Lock()
|
||||||
|
defer uc.access.Unlock()
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,21 +3,19 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/Dreamacro/clash/log"
|
"errors"
|
||||||
"go.uber.org/atomic"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
failedTimes *atomic.Int32
|
testUrl string
|
||||||
failedTime *atomic.Int64
|
selected string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@ -31,10 +29,9 @@ 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.onDialSuccess()
|
||||||
f.failedTime.Store(-1)
|
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed()
|
f.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
@ -46,41 +43,11 @@ 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 {
|
||||||
@ -105,22 +72,55 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (f *Fallback) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxy := f.findAliveProxy(true)
|
proxy := f.findAliveProxy(touch)
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||||
proxies := f.GetProxies(touch)
|
proxies := f.GetProxies(touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if proxy.Alive() {
|
if len(f.selected) == 0 {
|
||||||
return proxy
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if proxy.Name() == f.selected {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
} else {
|
||||||
|
f.selected = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Set(name string) error {
|
||||||
|
var p C.Proxy
|
||||||
|
for _, proxy := range f.GetProxies(false) {
|
||||||
|
if proxy.Name() == name {
|
||||||
|
p = proxy
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if p == nil {
|
||||||
|
return errors.New("proxy not exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
f.selected = name
|
||||||
|
if !p.Alive() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
||||||
|
defer cancel()
|
||||||
|
_, _ = p.URLTest(ctx, f.testUrl)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||||
return &Fallback{
|
return &Fallback{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
@ -133,8 +133,7 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
failedTimes: atomic.NewInt32(-1),
|
testUrl: option.URL,
|
||||||
failedTime: atomic.NewInt64(-1),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,21 +1,31 @@
|
|||||||
package outboundgroup
|
package outboundgroup
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupBase struct {
|
type GroupBase struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
filter *regexp2.Regexp
|
filterRegs []*regexp2.Regexp
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
versions sync.Map // map[string]uint
|
failedTestMux sync.Mutex
|
||||||
proxies sync.Map // map[string][]C.Proxy
|
failedTimes int
|
||||||
|
failedTime time.Time
|
||||||
|
failedTesting *atomic.Bool
|
||||||
|
proxies [][]C.Proxy
|
||||||
|
versions []atomic.Uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
type GroupBaseOption struct {
|
type GroupBaseOption struct {
|
||||||
@ -25,74 +35,216 @@ type GroupBaseOption struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
var filter *regexp2.Regexp = nil
|
var filterRegs []*regexp2.Regexp
|
||||||
if opt.filter != "" {
|
if opt.filter != "" {
|
||||||
filter = regexp2.MustCompile(opt.filter, 0)
|
for _, filter := range strings.Split(opt.filter, "`") {
|
||||||
|
filterReg := regexp2.MustCompile(filter, 0)
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return &GroupBase{
|
|
||||||
Base: outbound.NewBase(opt.BaseOption),
|
gb := &GroupBase{
|
||||||
filter: filter,
|
Base: outbound.NewBase(opt.BaseOption),
|
||||||
providers: opt.providers,
|
filterRegs: filterRegs,
|
||||||
|
providers: opt.providers,
|
||||||
|
failedTesting: atomic.NewBool(false),
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
||||||
|
gb.versions = make([]atomic.Uint32, len(opt.providers))
|
||||||
|
|
||||||
|
return gb
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) Touch() {
|
||||||
|
for _, pd := range gb.providers {
|
||||||
|
pd.Touch()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||||
if gb.filter == nil {
|
if len(gb.filterRegs) == 0 {
|
||||||
var proxies []C.Proxy
|
var proxies []C.Proxy
|
||||||
for _, pd := range gb.providers {
|
for _, pd := range gb.providers {
|
||||||
if touch {
|
if touch {
|
||||||
proxies = append(proxies, pd.ProxiesWithTouch()...)
|
pd.Touch()
|
||||||
} else {
|
|
||||||
proxies = append(proxies, pd.Proxies()...)
|
|
||||||
}
|
}
|
||||||
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
}
|
}
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
}
|
}
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
//TODO("Touch Version 没变的")
|
|
||||||
for _, pd := range gb.providers {
|
|
||||||
if pd.VehicleType() == types.Compatible {
|
|
||||||
if touch {
|
|
||||||
gb.proxies.Store(pd.Name(), pd.ProxiesWithTouch())
|
|
||||||
} else {
|
|
||||||
gb.proxies.Store(pd.Name(), pd.Proxies())
|
|
||||||
}
|
|
||||||
|
|
||||||
gb.versions.Store(pd.Name(), pd.Version())
|
for i, pd := range gb.providers {
|
||||||
|
if touch {
|
||||||
|
pd.Touch()
|
||||||
|
}
|
||||||
|
|
||||||
|
if pd.VehicleType() == types.Compatible {
|
||||||
|
gb.versions[i].Store(pd.Version())
|
||||||
|
gb.proxies[i] = pd.Proxies()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if version, ok := gb.versions.Load(pd.Name()); !ok || version != pd.Version() {
|
version := gb.versions[i].Load()
|
||||||
|
if version != pd.Version() && gb.versions[i].CompareAndSwap(version, pd.Version()) {
|
||||||
var (
|
var (
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
newProxies []C.Proxy
|
newProxies []C.Proxy
|
||||||
)
|
)
|
||||||
|
|
||||||
if touch {
|
proxies = pd.Proxies()
|
||||||
proxies = pd.ProxiesWithTouch()
|
proxiesSet := map[string]struct{}{}
|
||||||
} else {
|
for _, filterReg := range gb.filterRegs {
|
||||||
proxies = pd.Proxies()
|
for _, p := range proxies {
|
||||||
}
|
name := p.Name()
|
||||||
|
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
||||||
for _, p := range proxies {
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
if mat, _ := gb.filter.FindStringMatch(p.Name()); mat != nil {
|
proxiesSet[name] = struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
gb.proxies.Store(pd.Name(), newProxies)
|
gb.proxies[i] = newProxies
|
||||||
gb.versions.Store(pd.Name(), pd.Version())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var proxies []C.Proxy
|
var proxies []C.Proxy
|
||||||
gb.proxies.Range(func(key, value any) bool {
|
for _, p := range gb.proxies {
|
||||||
proxies = append(proxies, value.([]C.Proxy)...)
|
proxies = append(proxies, p...)
|
||||||
return true
|
}
|
||||||
})
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
||||||
|
var newProxies []C.Proxy
|
||||||
|
proxiesSet := map[string]struct{}{}
|
||||||
|
for _, filterReg := range gb.filterRegs {
|
||||||
|
for _, p := range proxies {
|
||||||
|
name := p.Name()
|
||||||
|
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range proxies { // add not matched proxies at the end
|
||||||
|
name := p.Name()
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
proxies = newProxies
|
||||||
|
}
|
||||||
|
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16, error) {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
var lock sync.Mutex
|
||||||
|
mp := map[string]uint16{}
|
||||||
|
proxies := gb.GetProxies(false)
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
proxy := proxy
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
delay, err := proxy.URLTest(ctx, url)
|
||||||
|
if err == nil {
|
||||||
|
lock.Lock()
|
||||||
|
mp[proxy.Name()] = delay
|
||||||
|
lock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
if len(mp) == 0 {
|
||||||
|
return mp, fmt.Errorf("get delay: all proxies timeout")
|
||||||
|
} else {
|
||||||
|
return mp, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
||||||
|
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(err.Error(), "connection refused") {
|
||||||
|
go gb.healthCheck()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
gb.failedTestMux.Lock()
|
||||||
|
defer gb.failedTestMux.Unlock()
|
||||||
|
|
||||||
|
gb.failedTimes++
|
||||||
|
if gb.failedTimes == 1 {
|
||||||
|
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
||||||
|
gb.failedTime = time.Now()
|
||||||
|
} else {
|
||||||
|
if time.Since(gb.failedTime) > gb.failedTimeoutInterval() {
|
||||||
|
gb.failedTimes = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
|
if gb.failedTimes >= gb.maxFailedTimes() {
|
||||||
|
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||||
|
gb.healthCheck()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) healthCheck() {
|
||||||
|
if gb.failedTesting.Load() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.failedTesting.Store(true)
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
for _, proxyProvider := range gb.providers {
|
||||||
|
wg.Add(1)
|
||||||
|
proxyProvider := proxyProvider
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
proxyProvider.HealthCheck()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
gb.failedTesting.Store(false)
|
||||||
|
gb.failedTimes = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) failedIntervalTime() int64 {
|
||||||
|
return 5 * time.Second.Milliseconds()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) onDialSuccess() {
|
||||||
|
if !gb.failedTesting.Load() {
|
||||||
|
gb.failedTimes = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) maxFailedTimes() int {
|
||||||
|
return 5
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) failedTimeoutInterval() time.Duration {
|
||||||
|
return 5 * time.Second
|
||||||
|
}
|
||||||
|
@ -5,7 +5,9 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
"net"
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
@ -27,15 +29,17 @@ type LoadBalance struct {
|
|||||||
var errStrategy = errors.New("unsupported strategy")
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
|
|
||||||
func parseStrategy(config map[string]any) string {
|
func parseStrategy(config map[string]any) string {
|
||||||
if elm, ok := config["strategy"]; ok {
|
if strategy, ok := config["strategy"].(string); ok {
|
||||||
if strategy, ok := elm.(string); ok {
|
return strategy
|
||||||
return strategy
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return "consistent-hashing"
|
return "consistent-hashing"
|
||||||
}
|
}
|
||||||
|
|
||||||
func getKey(metadata *C.Metadata) string {
|
func getKey(metadata *C.Metadata) string {
|
||||||
|
if metadata == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
if metadata.Host != "" {
|
if metadata.Host != "" {
|
||||||
// ip host
|
// ip host
|
||||||
if ip := net.ParseIP(metadata.Host); ip != nil {
|
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||||
@ -54,6 +58,16 @@ func getKey(metadata *C.Metadata) string {
|
|||||||
return metadata.DstIP.String()
|
return metadata.DstIP.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getKeyWithSrcAndDst(metadata *C.Metadata) string {
|
||||||
|
dst := getKey(metadata)
|
||||||
|
src := ""
|
||||||
|
if metadata != nil {
|
||||||
|
src = metadata.SrcIP.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("%s%s", src, dst)
|
||||||
|
}
|
||||||
|
|
||||||
func jumpHash(key uint64, buckets int32) int32 {
|
func jumpHash(key uint64, buckets int32) int32 {
|
||||||
var b, j int64
|
var b, j int64
|
||||||
|
|
||||||
@ -68,14 +82,17 @@ func jumpHash(key uint64, buckets int32) int32 {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
|
proxy := lb.Unwrap(metadata, true)
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(lb)
|
c.AppendToChains(lb)
|
||||||
|
lb.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
proxy := lb.Unwrap(metadata)
|
|
||||||
|
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -88,7 +105,7 @@ func (lb *LoadBalance) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
proxy := lb.Unwrap(metadata)
|
proxy := lb.Unwrap(metadata, true)
|
||||||
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -126,19 +143,61 @@ func strategyConsistentHashing() strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// when availability is poor, traverse the entire list to get the available nodes
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func strategyStickySessions() strategyFn {
|
||||||
|
ttl := time.Minute * 10
|
||||||
|
maxRetry := 5
|
||||||
|
lruCache := cache.NewLRUCache[uint64, int](
|
||||||
|
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
|
cache.WithSize[uint64, int](1000))
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
|
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
||||||
|
length := len(proxies)
|
||||||
|
idx, has := lruCache.Get(key)
|
||||||
|
if !has {
|
||||||
|
idx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||||
|
}
|
||||||
|
|
||||||
|
nowIdx := idx
|
||||||
|
for i := 1; i < maxRetry; i++ {
|
||||||
|
proxy := proxies[nowIdx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
if nowIdx != idx {
|
||||||
|
lruCache.Delete(key)
|
||||||
|
lruCache.Set(key, nowIdx)
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxy
|
||||||
|
} else {
|
||||||
|
nowIdx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lruCache.Delete(key)
|
||||||
|
lruCache.Set(key, 0)
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxies := lb.GetProxies(true)
|
proxies := lb.GetProxies(touch)
|
||||||
return lb.strategyFn(proxies, metadata)
|
return lb.strategyFn(proxies, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
var all []string
|
||||||
for _, proxy := range lb.GetProxies(false) {
|
for _, proxy := range lb.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
@ -155,6 +214,8 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
strategyFn = strategyConsistentHashing()
|
strategyFn = strategyConsistentHashing()
|
||||||
case "round-robin":
|
case "round-robin":
|
||||||
strategyFn = strategyRoundRobin()
|
strategyFn = strategyRoundRobin()
|
||||||
|
case "sticky-sessions":
|
||||||
|
strategyFn = strategyStickySessions()
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||||
}
|
}
|
||||||
|
@ -75,8 +75,12 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
providers = append(providers, pd)
|
providers = append(providers, pd)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
} else {
|
} else {
|
||||||
if groupOption.URL == "" || groupOption.Interval == 0 {
|
if groupOption.URL == "" {
|
||||||
return nil, errMissHealthCheck
|
groupOption.URL = "http://www.gstatic.com/generate_204"
|
||||||
|
}
|
||||||
|
|
||||||
|
if groupOption.Interval == 0 {
|
||||||
|
groupOption.Interval = 300
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||||
|
@ -153,11 +153,11 @@ func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy)
|
|||||||
for n, proxy := range rawProxies {
|
for n, proxy := range rawProxies {
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
chainProxies = append(chainProxies, proxy)
|
chainProxies = append(chainProxies, proxy)
|
||||||
subproxy := proxy.Unwrap(metadata)
|
subproxy := proxy.Unwrap(metadata, touch)
|
||||||
for subproxy != nil {
|
for subproxy != nil {
|
||||||
chainProxies = append(chainProxies, subproxy)
|
chainProxies = append(chainProxies, subproxy)
|
||||||
proxies[n] = subproxy
|
proxies[n] = subproxy
|
||||||
subproxy = subproxy.Unwrap(metadata)
|
subproxy = subproxy.Unwrap(metadata, touch)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -170,6 +170,11 @@ func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy)
|
|||||||
return targetProxies, chainProxies
|
return targetProxies, chainProxies
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *Relay) Addr() string {
|
||||||
|
proxies, _ := r.proxies(nil, true)
|
||||||
|
return proxies[len(proxies)-1].Addr()
|
||||||
|
}
|
||||||
|
|
||||||
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
||||||
return &Relay{
|
return &Relay{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
|
@ -74,8 +74,8 @@ func (s *Selector) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(*C.Metadata) C.Proxy {
|
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return s.selectedProxy(true)
|
return s.selectedProxy(touch)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
|
@ -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,12 +22,10 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
fastSingle *singledo.Single[C.Proxy]
|
fastSingle *singledo.Single[C.Proxy]
|
||||||
failedTimes *atomic.Int32
|
|
||||||
failedTime *atomic.Int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
func (u *URLTest) Now() string {
|
||||||
@ -38,13 +34,13 @@ func (u *URLTest) Now() string {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
proxy := u.fast(true)
|
||||||
|
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
u.failedTimes.Store(-1)
|
u.onDialSuccess()
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed()
|
u.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
@ -54,21 +50,18 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(u)
|
pc.AppendToChains(u)
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
u.onDialFailed()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (u *URLTest) Unwrap(*C.Metadata) C.Proxy {
|
func (u *URLTest) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return u.fast(true)
|
return u.fast(touch)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
proxies := u.GetProxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
@ -97,6 +90,9 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
|
|
||||||
return u.fastNode, nil
|
return u.fastNode, nil
|
||||||
})
|
})
|
||||||
|
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
||||||
|
u.Touch()
|
||||||
|
}
|
||||||
|
|
||||||
return elm
|
return elm
|
||||||
}
|
}
|
||||||
@ -123,32 +119,6 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) onDialFailed() {
|
|
||||||
if u.failedTime.Load() == -1 {
|
|
||||||
log.Warnln("%s first failed", u.Name())
|
|
||||||
now := time.Now().UnixMilli()
|
|
||||||
u.failedTime.Store(now)
|
|
||||||
u.failedTimes.Store(1)
|
|
||||||
} else {
|
|
||||||
if u.failedTime.Load()-time.Now().UnixMilli() > 5*1000 {
|
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
failedCount := u.failedTimes.Inc()
|
|
||||||
log.Warnln("%s failed count: %d", u.Name(), failedCount)
|
|
||||||
if failedCount >= 5 {
|
|
||||||
log.Warnln("because %s failed multiple times, active health check", u.Name())
|
|
||||||
for _, proxyProvider := range u.providers {
|
|
||||||
go proxyProvider.HealthCheck()
|
|
||||||
}
|
|
||||||
|
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseURLTestOption(config map[string]any) []urlTestOption {
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
opts := []urlTestOption{}
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
@ -171,13 +141,12 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
Interface: option.Interface,
|
Interface: option.Interface,
|
||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
|
|
||||||
option.Filter,
|
option.Filter,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
failedTimes: atomic.NewInt32(-1),
|
|
||||||
failedTime: atomic.NewInt64(-1),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
@ -51,3 +51,7 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SelectAble interface {
|
||||||
|
Set(string) error
|
||||||
|
}
|
||||||
|
@ -40,14 +40,14 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewSocks5(*socksOption)
|
proxy, err = outbound.NewSocks5(*socksOption)
|
||||||
case "http":
|
case "http":
|
||||||
httpOption := &outbound.HttpOption{}
|
httpOption := &outbound.HttpOption{}
|
||||||
err = decoder.Decode(mapping, httpOption)
|
err = decoder.Decode(mapping, httpOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewHttp(*httpOption)
|
proxy, err = outbound.NewHttp(*httpOption)
|
||||||
case "vmess":
|
case "vmess":
|
||||||
vmessOption := &outbound.VmessOption{
|
vmessOption := &outbound.VmessOption{
|
||||||
HTTPOpts: outbound.HTTPOptions{
|
HTTPOpts: outbound.HTTPOptions{
|
||||||
@ -81,6 +81,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewTrojan(*trojanOption)
|
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||||
|
case "hysteria":
|
||||||
|
hyOption := &outbound.HysteriaOption{}
|
||||||
|
err = decoder.Decode(mapping, hyOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewHysteria(*hyOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
@ -1,185 +0,0 @@
|
|||||||
package provider
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/md5"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
fileMode os.FileMode = 0o666
|
|
||||||
dirMode os.FileMode = 0o755
|
|
||||||
)
|
|
||||||
|
|
||||||
type parser = func([]byte) (any, error)
|
|
||||||
|
|
||||||
type fetcher struct {
|
|
||||||
name string
|
|
||||||
vehicle types.Vehicle
|
|
||||||
updatedAt *time.Time
|
|
||||||
ticker *time.Ticker
|
|
||||||
done chan struct{}
|
|
||||||
hash [16]byte
|
|
||||||
parser parser
|
|
||||||
onUpdate func(any)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) Name() string {
|
|
||||||
return f.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) VehicleType() types.VehicleType {
|
|
||||||
return f.vehicle.Type()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) Initial() (any, error) {
|
|
||||||
var (
|
|
||||||
buf []byte
|
|
||||||
err error
|
|
||||||
isLocal bool
|
|
||||||
)
|
|
||||||
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
|
||||||
buf, err = os.ReadFile(f.vehicle.Path())
|
|
||||||
modTime := stat.ModTime()
|
|
||||||
f.updatedAt = &modTime
|
|
||||||
isLocal = true
|
|
||||||
} else {
|
|
||||||
buf, err = f.vehicle.Read()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err := f.parser(buf)
|
|
||||||
if err != nil {
|
|
||||||
if !isLocal {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse local file error, fallback to remote
|
|
||||||
buf, err = f.vehicle.Read()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err = f.parser(buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
isLocal = false
|
|
||||||
}
|
|
||||||
|
|
||||||
if f.vehicle.Type() != types.File && !isLocal {
|
|
||||||
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
f.hash = md5.Sum(buf)
|
|
||||||
|
|
||||||
// pull proxies automatically
|
|
||||||
if f.ticker != nil {
|
|
||||||
go f.pullLoop()
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) Update() (any, bool, error) {
|
|
||||||
buf, err := f.vehicle.Read()
|
|
||||||
if err != nil {
|
|
||||||
return nil, false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
hash := md5.Sum(buf)
|
|
||||||
if bytes.Equal(f.hash[:], hash[:]) {
|
|
||||||
f.updatedAt = &now
|
|
||||||
os.Chtimes(f.vehicle.Path(), now, now)
|
|
||||||
return nil, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err := f.parser(buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if f.vehicle.Type() != types.File {
|
|
||||||
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
|
||||||
return nil, false, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
f.updatedAt = &now
|
|
||||||
f.hash = hash
|
|
||||||
|
|
||||||
return proxies, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) Destroy() error {
|
|
||||||
if f.ticker != nil {
|
|
||||||
f.done <- struct{}{}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) pullLoop() {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-f.ticker.C:
|
|
||||||
elm, same, err := f.Update()
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if same {
|
|
||||||
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Infoln("[Provider] %s's proxies update", f.Name())
|
|
||||||
if f.onUpdate != nil {
|
|
||||||
f.onUpdate(elm)
|
|
||||||
}
|
|
||||||
case <-f.done:
|
|
||||||
f.ticker.Stop()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func safeWrite(path string, buf []byte) error {
|
|
||||||
dir := filepath.Dir(path)
|
|
||||||
|
|
||||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
|
||||||
if err := os.MkdirAll(dir, dirMode); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return os.WriteFile(path, buf, fileMode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(any)) *fetcher {
|
|
||||||
var ticker *time.Ticker
|
|
||||||
if interval != 0 {
|
|
||||||
ticker = time.NewTicker(interval)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &fetcher{
|
|
||||||
name: name,
|
|
||||||
ticker: ticker,
|
|
||||||
vehicle: vehicle,
|
|
||||||
parser: parser,
|
|
||||||
done: make(chan struct{}, 1),
|
|
||||||
onUpdate: onUpdate,
|
|
||||||
}
|
|
||||||
}
|
|
@ -5,8 +5,11 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -26,25 +29,21 @@ type HealthCheck struct {
|
|||||||
lazy bool
|
lazy bool
|
||||||
lastTouch *atomic.Int64
|
lastTouch *atomic.Int64
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
|
singleDo *singledo.Single[struct{}]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
t := time.NewTicker(30 * time.Second)
|
time.Sleep(30 * time.Second)
|
||||||
<-t.C
|
hc.lazyCheck()
|
||||||
t.Stop()
|
|
||||||
hc.check()
|
|
||||||
}()
|
}()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
now := time.Now().Unix()
|
hc.lazyCheck()
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
|
||||||
hc.check()
|
|
||||||
}
|
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
@ -52,6 +51,17 @@ func (hc *HealthCheck) process() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) lazyCheck() bool {
|
||||||
|
now := time.Now().Unix()
|
||||||
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
|
hc.check()
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
log.Debugln("Skip once health check because we are lazy")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
hc.proxies = proxies
|
hc.proxies = proxies
|
||||||
}
|
}
|
||||||
@ -65,17 +75,29 @@ func (hc *HealthCheck) touch() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
for _, proxy := range hc.proxies {
|
id := ""
|
||||||
p := proxy
|
if uid, err := uuid.NewV4(); err == nil {
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
id = uid.String()
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
}
|
||||||
defer cancel()
|
log.Debugln("Start New Health Checking {%s}", id)
|
||||||
_, _ = p.URLTest(ctx, hc.url)
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
return false, nil
|
for _, proxy := range hc.proxies {
|
||||||
})
|
p := proxy
|
||||||
}
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
b.Wait()
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
|
defer cancel()
|
||||||
|
log.Debugln("Health Checking %s {%s}", p.Name(), id)
|
||||||
|
_, _ = p.URLTest(ctx, hc.url)
|
||||||
|
log.Debugln("Health Checked %s : %t %d ms {%s}", p.Name(), p.Alive(), p.LastDelay(), id)
|
||||||
|
return false, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
b.Wait()
|
||||||
|
log.Debugln("Finish A Health Checking {%s}", id)
|
||||||
|
return struct{}{}, nil
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
func (hc *HealthCheck) close() {
|
||||||
@ -90,5 +112,6 @@ func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *He
|
|||||||
lazy: lazy,
|
lazy: lazy,
|
||||||
lastTouch: atomic.NewInt64(0),
|
lastTouch: atomic.NewInt64(0),
|
||||||
done: make(chan struct{}, 1),
|
done: make(chan struct{}, 1),
|
||||||
|
singleDo: singledo.NewSingle[struct{}](time.Second),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,7 @@ package provider
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
@ -20,12 +21,13 @@ type healthCheckSchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path"`
|
Path string `provider:"path"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
@ -51,14 +53,15 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
var vehicle types.Vehicle
|
var vehicle types.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
case "file":
|
case "file":
|
||||||
vehicle = NewFileVehicle(path)
|
vehicle = resource.NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
vehicle = NewHTTPVehicle(schema.URL, path)
|
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
}
|
}
|
||||||
|
|
||||||
interval := time.Duration(uint(schema.Interval)) * time.Second
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
filter := schema.Filter
|
filter := schema.Filter
|
||||||
return NewProxySetProvider(name, interval, filter, vehicle, hc)
|
excludeFilter := schema.ExcludeFilter
|
||||||
|
return NewProxySetProvider(name, interval, filter, excludeFilter, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
@ -4,16 +4,18 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
"math"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -24,20 +26,16 @@ type ProxySchema struct {
|
|||||||
Proxies []map[string]any `yaml:"proxies"`
|
Proxies []map[string]any `yaml:"proxies"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// for auto gc
|
// ProxySetProvider for auto gc
|
||||||
type ProxySetProvider struct {
|
type ProxySetProvider struct {
|
||||||
*proxySetProvider
|
*proxySetProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxySetProvider struct {
|
type proxySetProvider struct {
|
||||||
*fetcher
|
*resource.Fetcher[[]C.Proxy]
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
version uint
|
version uint32
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) Version() uint {
|
|
||||||
return pp.version
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -46,13 +44,16 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
//TODO maybe error because year value overflow
|
"updatedAt": pp.UpdatedAt,
|
||||||
"updatedAt": pp.updatedAt,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Version() uint32 {
|
||||||
|
return pp.version
|
||||||
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Name() string {
|
func (pp *proxySetProvider) Name() string {
|
||||||
return pp.name
|
return pp.Fetcher.Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) HealthCheck() {
|
func (pp *proxySetProvider) HealthCheck() {
|
||||||
@ -60,24 +61,19 @@ func (pp *proxySetProvider) HealthCheck() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Update() error {
|
func (pp *proxySetProvider) Update() error {
|
||||||
elm, same, err := pp.fetcher.Update()
|
elm, same, err := pp.Fetcher.Update()
|
||||||
if err == nil && !same {
|
if err == nil && !same {
|
||||||
pp.onUpdate(elm)
|
pp.OnUpdate(elm)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Initial() error {
|
func (pp *proxySetProvider) Initial() error {
|
||||||
elm, err := pp.fetcher.Initial()
|
elm, err := pp.Fetcher.Initial()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
pp.OnUpdate(elm)
|
||||||
pp.onUpdate(elm)
|
|
||||||
if pp.healthCheck.auto() {
|
|
||||||
go pp.healthCheck.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -89,30 +85,39 @@ func (pp *proxySetProvider) Proxies() []C.Proxy {
|
|||||||
return pp.proxies
|
return pp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
func (pp *proxySetProvider) Touch() {
|
||||||
pp.healthCheck.touch()
|
pp.healthCheck.touch()
|
||||||
return pp.Proxies()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
if pp.healthCheck.auto() {
|
if pp.healthCheck.auto() {
|
||||||
go pp.healthCheck.check()
|
defer func() { go pp.healthCheck.lazyCheck() }()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
pd.fetcher.Destroy()
|
_ = pd.Fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
//filterReg, err := regexp.Compile(filter)
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
|
}
|
||||||
|
var filterRegs []*regexp2.Regexp
|
||||||
|
for _, filter := range strings.Split(filter, "`") {
|
||||||
|
filterReg, err := regexp2.Compile(filter, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
|
}
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
}
|
}
|
||||||
|
|
||||||
pd := &proxySetProvider{
|
pd := &proxySetProvider{
|
||||||
@ -120,60 +125,15 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
onUpdate := func(elm any) {
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, filterRegs, excludeFilterReg), proxiesOnUpdate(pd))
|
||||||
ret := elm.([]C.Proxy)
|
pd.Fetcher = fetcher
|
||||||
pd.setProxies(ret)
|
|
||||||
if pd.version == math.MaxUint {
|
|
||||||
pd.version = 0
|
|
||||||
} else {
|
|
||||||
pd.version++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
proxiesParseAndFilter := func(buf []byte) (any, error) {
|
|
||||||
schema := &ProxySchema{}
|
|
||||||
|
|
||||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if schema.Proxies == nil {
|
|
||||||
return nil, errors.New("file must have a `proxies` field")
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies := []C.Proxy{}
|
|
||||||
for idx, mapping := range schema.Proxies {
|
|
||||||
name, ok := mapping["name"]
|
|
||||||
mat, _ := filterReg.FindStringMatch(name.(string))
|
|
||||||
if ok && len(filter) > 0 && mat == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
|
||||||
}
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
if len(filter) > 0 {
|
|
||||||
return nil, errors.New("doesn't match any proxy, please check your filter")
|
|
||||||
}
|
|
||||||
return nil, errors.New("file doesn't have any proxy")
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
fetcher := newFetcher(name, interval, vehicle, proxiesParseAndFilter, onUpdate)
|
|
||||||
pd.fetcher = fetcher
|
|
||||||
|
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// for auto gc
|
// CompatibleProvider for auto gc
|
||||||
type CompatibleProvider struct {
|
type CompatibleProvider struct {
|
||||||
*compatibleProvider
|
*compatibleProvider
|
||||||
}
|
}
|
||||||
@ -182,11 +142,7 @@ type compatibleProvider struct {
|
|||||||
name string
|
name string
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
version uint
|
version uint32
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Version() uint {
|
|
||||||
return cp.version
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -198,6 +154,10 @@ func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Version() uint32 {
|
||||||
|
return cp.version
|
||||||
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Name() string {
|
func (cp *compatibleProvider) Name() string {
|
||||||
return cp.name
|
return cp.name
|
||||||
}
|
}
|
||||||
@ -211,10 +171,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -230,9 +186,8 @@ func (cp *compatibleProvider) Proxies() []C.Proxy {
|
|||||||
return cp.proxies
|
return cp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) ProxiesWithTouch() []C.Proxy {
|
func (cp *compatibleProvider) Touch() {
|
||||||
cp.healthCheck.touch()
|
cp.healthCheck.touch()
|
||||||
return cp.Proxies()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopCompatibleProvider(pd *CompatibleProvider) {
|
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||||
@ -244,6 +199,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,
|
||||||
@ -254,3 +213,71 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
||||||
|
return func(elm []C.Proxy) {
|
||||||
|
pd.setProxies(elm)
|
||||||
|
pd.version += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func proxiesParseAndFilter(filter string, excludeFilter string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
||||||
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
|
proxies, err1 := convert.ConvertsV2Ray(buf)
|
||||||
|
if err1 != nil {
|
||||||
|
return nil, fmt.Errorf("%s, %w", err.Error(), err1)
|
||||||
|
}
|
||||||
|
schema.Proxies = proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
if schema.Proxies == nil {
|
||||||
|
return nil, errors.New("file must have a `proxies` field")
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
proxiesSet := map[string]struct{}{}
|
||||||
|
for _, filterReg := range filterRegs {
|
||||||
|
for idx, mapping := range schema.Proxies {
|
||||||
|
mName, ok := mapping["name"]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name, ok := mName.(string)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(excludeFilter) > 0 {
|
||||||
|
if mat, _ := excludeFilterReg.FindStringMatch(name); mat != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(filter) > 0 {
|
||||||
|
if mat, _ := filterReg.FindStringMatch(name); mat == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := proxiesSet[name]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
|
}
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
if len(filter) > 0 {
|
||||||
|
return nil, errors.New("doesn't match any proxy, please check your filter")
|
||||||
|
}
|
||||||
|
return nil, errors.New("file doesn't have any proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
45
common/convert/base64.go
Normal file
45
common/convert/base64.go
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
package convert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
encRaw = base64.RawStdEncoding
|
||||||
|
enc = base64.StdEncoding
|
||||||
|
)
|
||||||
|
|
||||||
|
// DecodeBase64 try to decode content from the given bytes,
|
||||||
|
// which can be in base64.RawStdEncoding, base64.StdEncoding or just plaintext.
|
||||||
|
func DecodeBase64(buf []byte) []byte {
|
||||||
|
result, err := tryDecodeBase64(buf)
|
||||||
|
if err != nil {
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func tryDecodeBase64(buf []byte) ([]byte, error) {
|
||||||
|
dBuf := make([]byte, encRaw.DecodedLen(len(buf)))
|
||||||
|
n, err := encRaw.Decode(dBuf, buf)
|
||||||
|
if err != nil {
|
||||||
|
n, err = enc.Decode(dBuf, buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dBuf[:n], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlSafe(data string) string {
|
||||||
|
return strings.NewReplacer("+", "-", "/", "_").Replace(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeUrlSafe(data string) string {
|
||||||
|
dcBuf, err := base64.RawURLEncoding.DecodeString(data)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return string(dcBuf)
|
||||||
|
}
|
387
common/convert/converter.go
Normal file
387
common/convert/converter.go
Normal file
@ -0,0 +1,387 @@
|
|||||||
|
package convert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
||||||
|
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||||
|
data := DecodeBase64(buf)
|
||||||
|
|
||||||
|
arr := strings.Split(string(data), "\n")
|
||||||
|
|
||||||
|
proxies := make([]map[string]any, 0, len(arr))
|
||||||
|
names := make(map[string]int, 200)
|
||||||
|
|
||||||
|
for _, line := range arr {
|
||||||
|
line = strings.TrimRight(line, " \r")
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
scheme, body, found := strings.Cut(line, "://")
|
||||||
|
if !found {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
scheme = strings.ToLower(scheme)
|
||||||
|
switch scheme {
|
||||||
|
case "hysteria":
|
||||||
|
urlHysteria, err := url.Parse(line)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
query := urlHysteria.Query()
|
||||||
|
name := uniqueName(names, urlHysteria.Fragment)
|
||||||
|
hysteria := make(map[string]any, 20)
|
||||||
|
|
||||||
|
hysteria["name"] = name
|
||||||
|
hysteria["type"] = scheme
|
||||||
|
hysteria["server"] = urlHysteria.Hostname()
|
||||||
|
hysteria["port"] = urlHysteria.Port()
|
||||||
|
hysteria["sni"] = query.Get("peer")
|
||||||
|
hysteria["obfs"] = query.Get("obfs")
|
||||||
|
hysteria["alpn"] = []string{query.Get("alpn")}
|
||||||
|
hysteria["auth_str"] = query.Get("auth")
|
||||||
|
hysteria["protocol"] = query.Get("protocol")
|
||||||
|
up := query.Get("up")
|
||||||
|
down := query.Get("down")
|
||||||
|
if up == "" {
|
||||||
|
up = query.Get("upmbps")
|
||||||
|
}
|
||||||
|
if down == "" {
|
||||||
|
down = query.Get("downmbps")
|
||||||
|
}
|
||||||
|
hysteria["down"] = down
|
||||||
|
hysteria["up"] = up
|
||||||
|
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
||||||
|
|
||||||
|
proxies = append(proxies, hysteria)
|
||||||
|
|
||||||
|
case "trojan":
|
||||||
|
urlTrojan, err := url.Parse(line)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
query := urlTrojan.Query()
|
||||||
|
|
||||||
|
name := uniqueName(names, urlTrojan.Fragment)
|
||||||
|
trojan := make(map[string]any, 20)
|
||||||
|
|
||||||
|
trojan["name"] = name
|
||||||
|
trojan["type"] = scheme
|
||||||
|
trojan["server"] = urlTrojan.Hostname()
|
||||||
|
trojan["port"] = urlTrojan.Port()
|
||||||
|
trojan["password"] = urlTrojan.User.Username()
|
||||||
|
trojan["udp"] = true
|
||||||
|
trojan["skip-cert-verify"] = false
|
||||||
|
|
||||||
|
sni := query.Get("sni")
|
||||||
|
if sni != "" {
|
||||||
|
trojan["sni"] = sni
|
||||||
|
}
|
||||||
|
|
||||||
|
network := strings.ToLower(query.Get("type"))
|
||||||
|
if network != "" {
|
||||||
|
trojan["network"] = network
|
||||||
|
}
|
||||||
|
|
||||||
|
switch network {
|
||||||
|
case "ws":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
wsOpts := make(map[string]any)
|
||||||
|
|
||||||
|
headers["User-Agent"] = RandUserAgent()
|
||||||
|
|
||||||
|
wsOpts["path"] = query.Get("path")
|
||||||
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
|
trojan["ws-opts"] = wsOpts
|
||||||
|
|
||||||
|
case "grpc":
|
||||||
|
grpcOpts := make(map[string]any)
|
||||||
|
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||||
|
trojan["grpc-opts"] = grpcOpts
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies = append(proxies, trojan)
|
||||||
|
|
||||||
|
case "vless":
|
||||||
|
urlVLess, err := url.Parse(line)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
query := urlVLess.Query()
|
||||||
|
vless := make(map[string]any, 20)
|
||||||
|
handleVShareLink(names, urlVLess, scheme, vless)
|
||||||
|
if flow := query.Get("flow"); flow != "" {
|
||||||
|
vless["flow"] = strings.ToLower(flow)
|
||||||
|
}
|
||||||
|
proxies = append(proxies, vless)
|
||||||
|
|
||||||
|
case "vmess":
|
||||||
|
// V2RayN-styled share link
|
||||||
|
// https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)
|
||||||
|
dcBuf, err := tryDecodeBase64([]byte(body))
|
||||||
|
if err != nil {
|
||||||
|
// Xray VMessAEAD share link
|
||||||
|
urlVMess, err := url.Parse(line)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
query := urlVMess.Query()
|
||||||
|
vmess := make(map[string]any, 20)
|
||||||
|
handleVShareLink(names, urlVMess, scheme, vmess)
|
||||||
|
vmess["alterId"] = 0
|
||||||
|
vmess["cipher"] = "auto"
|
||||||
|
if encryption := query.Get("encryption"); encryption != "" {
|
||||||
|
vmess["cipher"] = encryption
|
||||||
|
}
|
||||||
|
if packetEncoding := query.Get("packetEncoding"); packetEncoding != "" {
|
||||||
|
switch packetEncoding {
|
||||||
|
case "packet":
|
||||||
|
vmess["packet-addr"] = true
|
||||||
|
case "xudp":
|
||||||
|
vmess["xudp"] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
proxies = append(proxies, vmess)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonDc := json.NewDecoder(bytes.NewReader(dcBuf))
|
||||||
|
values := make(map[string]any, 20)
|
||||||
|
|
||||||
|
if jsonDc.Decode(&values) != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
name := uniqueName(names, values["ps"].(string))
|
||||||
|
vmess := make(map[string]any, 20)
|
||||||
|
|
||||||
|
vmess["name"] = name
|
||||||
|
vmess["type"] = scheme
|
||||||
|
vmess["server"] = values["add"]
|
||||||
|
vmess["port"] = values["port"]
|
||||||
|
vmess["uuid"] = values["id"]
|
||||||
|
if alterId, ok := values["aid"]; ok {
|
||||||
|
vmess["alterId"] = alterId
|
||||||
|
} else {
|
||||||
|
vmess["alterId"] = 0
|
||||||
|
}
|
||||||
|
vmess["udp"] = true
|
||||||
|
vmess["tls"] = false
|
||||||
|
vmess["skip-cert-verify"] = false
|
||||||
|
|
||||||
|
vmess["cipher"] = "auto"
|
||||||
|
if cipher, ok := values["scy"]; ok && cipher != "" {
|
||||||
|
vmess["cipher"] = cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
if sni, ok := values["sni"]; ok && sni != "" {
|
||||||
|
vmess["servername"] = sni
|
||||||
|
}
|
||||||
|
|
||||||
|
network := strings.ToLower(values["net"].(string))
|
||||||
|
if values["type"] == "http" {
|
||||||
|
network = "http"
|
||||||
|
} else if network == "http" {
|
||||||
|
network = "h2"
|
||||||
|
}
|
||||||
|
vmess["network"] = network
|
||||||
|
|
||||||
|
tls := strings.ToLower(values["tls"].(string))
|
||||||
|
if strings.HasSuffix(tls, "tls") {
|
||||||
|
vmess["tls"] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
switch network {
|
||||||
|
case "http":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
httpOpts := make(map[string]any)
|
||||||
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
|
headers["Host"] = []string{host.(string)}
|
||||||
|
}
|
||||||
|
httpOpts["path"] = []string{"/"}
|
||||||
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
|
httpOpts["path"] = []string{path.(string)}
|
||||||
|
}
|
||||||
|
httpOpts["headers"] = headers
|
||||||
|
|
||||||
|
vmess["http-opts"] = httpOpts
|
||||||
|
|
||||||
|
case "h2":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
h2Opts := make(map[string]any)
|
||||||
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
|
headers["Host"] = []string{host.(string)}
|
||||||
|
}
|
||||||
|
|
||||||
|
h2Opts["path"] = values["path"]
|
||||||
|
h2Opts["headers"] = headers
|
||||||
|
|
||||||
|
vmess["h2-opts"] = h2Opts
|
||||||
|
|
||||||
|
case "ws":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
wsOpts := make(map[string]any)
|
||||||
|
wsOpts["path"] = []string{"/"}
|
||||||
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
|
headers["Host"] = host.(string)
|
||||||
|
}
|
||||||
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
|
wsOpts["path"] = path.(string)
|
||||||
|
}
|
||||||
|
wsOpts["headers"] = headers
|
||||||
|
vmess["ws-opts"] = wsOpts
|
||||||
|
|
||||||
|
case "grpc":
|
||||||
|
grpcOpts := make(map[string]any)
|
||||||
|
grpcOpts["grpc-service-name"] = values["path"]
|
||||||
|
vmess["grpc-opts"] = grpcOpts
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies = append(proxies, vmess)
|
||||||
|
|
||||||
|
case "ss":
|
||||||
|
urlSS, err := url.Parse(line)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
name := uniqueName(names, urlSS.Fragment)
|
||||||
|
port := urlSS.Port()
|
||||||
|
|
||||||
|
if port == "" {
|
||||||
|
dcBuf, err := encRaw.DecodeString(urlSS.Host)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
urlSS, err = url.Parse("ss://" + string(dcBuf))
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
cipher = urlSS.User.Username()
|
||||||
|
password string
|
||||||
|
)
|
||||||
|
|
||||||
|
if password, found = urlSS.User.Password(); !found {
|
||||||
|
dcBuf, _ := enc.DecodeString(cipher)
|
||||||
|
if !strings.Contains(string(dcBuf), "2022-blake3") {
|
||||||
|
dcBuf, _ = encRaw.DecodeString(cipher)
|
||||||
|
}
|
||||||
|
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||||
|
if !found {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ss := make(map[string]any, 20)
|
||||||
|
|
||||||
|
ss["name"] = name
|
||||||
|
ss["type"] = scheme
|
||||||
|
ss["server"] = urlSS.Hostname()
|
||||||
|
ss["port"] = urlSS.Port()
|
||||||
|
ss["cipher"] = cipher
|
||||||
|
ss["password"] = password
|
||||||
|
query := urlSS.Query()
|
||||||
|
ss["udp"] = true
|
||||||
|
if strings.Contains(query.Get("plugin"), "obfs") {
|
||||||
|
obfsParams := strings.Split(query.Get("plugin"), ";")
|
||||||
|
ss["plugin"] = "obfs"
|
||||||
|
ss["plugin-opts"] = map[string]any{
|
||||||
|
"host": obfsParams[2][10:],
|
||||||
|
"mode": obfsParams[1][5:],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
proxies = append(proxies, ss)
|
||||||
|
case "ssr":
|
||||||
|
dcBuf, err := encRaw.DecodeString(body)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ssr://host:port:protocol:method:obfs:urlsafebase64pass/?obfsparam=urlsafebase64&protoparam=&remarks=urlsafebase64&group=urlsafebase64&udpport=0&uot=1
|
||||||
|
|
||||||
|
before, after, ok := strings.Cut(string(dcBuf), "/?")
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeArr := strings.Split(before, ":")
|
||||||
|
|
||||||
|
if len(beforeArr) != 6 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
host := beforeArr[0]
|
||||||
|
port := beforeArr[1]
|
||||||
|
protocol := beforeArr[2]
|
||||||
|
method := beforeArr[3]
|
||||||
|
obfs := beforeArr[4]
|
||||||
|
password := decodeUrlSafe(urlSafe(beforeArr[5]))
|
||||||
|
|
||||||
|
query, err := url.ParseQuery(urlSafe(after))
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
remarks := decodeUrlSafe(query.Get("remarks"))
|
||||||
|
name := uniqueName(names, remarks)
|
||||||
|
|
||||||
|
obfsParam := decodeUrlSafe(query.Get("obfsparam"))
|
||||||
|
protocolParam := query.Get("protoparam")
|
||||||
|
|
||||||
|
ssr := make(map[string]any, 20)
|
||||||
|
|
||||||
|
ssr["name"] = name
|
||||||
|
ssr["type"] = scheme
|
||||||
|
ssr["server"] = host
|
||||||
|
ssr["port"] = port
|
||||||
|
ssr["cipher"] = method
|
||||||
|
ssr["password"] = password
|
||||||
|
ssr["obfs"] = obfs
|
||||||
|
ssr["protocol"] = protocol
|
||||||
|
ssr["udp"] = true
|
||||||
|
|
||||||
|
if obfsParam != "" {
|
||||||
|
ssr["obfs-param"] = obfsParam
|
||||||
|
}
|
||||||
|
|
||||||
|
if protocolParam != "" {
|
||||||
|
ssr["protocol-param"] = protocolParam
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies = append(proxies, ssr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, fmt.Errorf("convert v2ray subscribe error: format invalid")
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func uniqueName(names map[string]int, name string) string {
|
||||||
|
if index, ok := names[name]; ok {
|
||||||
|
index++
|
||||||
|
names[name] = index
|
||||||
|
name = fmt.Sprintf("%s-%02d", name, index)
|
||||||
|
} else {
|
||||||
|
index = 0
|
||||||
|
names[name] = index
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
316
common/convert/util.go
Normal file
316
common/convert/util.go
Normal file
@ -0,0 +1,316 @@
|
|||||||
|
package convert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var hostsSuffix = []string{
|
||||||
|
"-cdn.aliyuncs.com",
|
||||||
|
".alicdn.com",
|
||||||
|
".pan.baidu.com",
|
||||||
|
".tbcache.com",
|
||||||
|
".aliyuncdn.com",
|
||||||
|
".vod.miguvideo.com",
|
||||||
|
".cibntv.net",
|
||||||
|
".myqcloud.com",
|
||||||
|
".smtcdns.com",
|
||||||
|
".alikunlun.com",
|
||||||
|
".smtcdns.net",
|
||||||
|
".apcdns.net",
|
||||||
|
".cdn-go.cn",
|
||||||
|
".cdntip.com",
|
||||||
|
".cdntips.com",
|
||||||
|
".alidayu.com",
|
||||||
|
".alidns.com",
|
||||||
|
".cdngslb.com",
|
||||||
|
".mxhichina.com",
|
||||||
|
".alibabadns.com",
|
||||||
|
}
|
||||||
|
|
||||||
|
var userAgents = []string{
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; Moto C Build/NRD90M.059) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 5.1.1; SM-J120M Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; Moto G (5) Build/NPPS25.137-93-14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; SM-G570M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 5.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0; CAM-L03 Build/HUAWEICAM-L03) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3",
|
||||||
|
"Mozilla/5.0 (Linux; Android 8.0.0; FIG-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.1 Safari/533.2",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (X11; Datanyze; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 5.1.1; SM-J111M Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; SM-J700M Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Slackware/Chrome/12.0.742.100 Safari/534.30",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 8.0.0; WAS-LX3 Build/HUAWEIWAS-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.1805 Safari/537.36 MVisionPlayer/1.0.0.0",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; TRT-LX3 Build/HUAWEITRT-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0; vivo 1610 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 4.4.2; de-de; SAMSUNG GT-I9195 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.5 Chrome/28.0.1500.94 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 8.0.0; ANE-LX3 Build/HUAWEIANE-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (X11; U; Linux i586; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.1 Safari/533.2",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; SM-G610M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; SM-J500M Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0; vivo 1606 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; SM-G610M Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.1; vivo 1716 Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; SM-G570M Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0; MYA-L22 Build/HUAWEIMYA-L22) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 5.1; A1601 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; TRT-LX2 Build/HUAWEITRT-LX2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.649.0 Safari/534.17",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0; CAM-L21 Build/HUAWEICAM-L21; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.3 Safari/534.24",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.1.2; Redmi 4X Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 4.4.2; SM-G7102 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 5.1; HUAWEI CUN-L22 Build/HUAWEICUN-L22; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 5.1.1; A37fw Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; SM-J730GM Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; SM-G610F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.1.2; Redmi Note 5A Build/N2G47H; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; Redmi Note 4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Unknown; Linux) AppleWebKit/538.1 (KHTML, like Gecko) Chrome/v1.0.0 Safari/538.1",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; BLL-L22 Build/HUAWEIBLL-L22) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.0; SM-J710F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.1.1; CPH1723 Build/N6F26Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 8.0.0; FIG-LX3 Build/HUAWEIFIG-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 6.1; de-DE) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.649.0 Safari/534.17",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 7.1; Mi A1 Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36 MVisionPlayer/1.0.0.0",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 5.1; A37f Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.93 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; CPH1607 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; vivo 1603 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; Redmi 4A Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/60.0.3112.116 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.83 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Linux; Android 6.0; vivo 1713 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
hostsLen = len(hostsSuffix)
|
||||||
|
uaLen = len(userAgents)
|
||||||
|
)
|
||||||
|
|
||||||
|
func RandHost() string {
|
||||||
|
id, _ := uuid.NewV4()
|
||||||
|
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
||||||
|
base = strings.ReplaceAll(base, "-", "")
|
||||||
|
base = strings.ReplaceAll(base, "_", "")
|
||||||
|
buf := []byte(base)
|
||||||
|
prefix := string(buf[:3]) + "---"
|
||||||
|
prefix += string(buf[6:8]) + "-"
|
||||||
|
prefix += string(buf[len(buf)-8:])
|
||||||
|
|
||||||
|
return prefix + hostsSuffix[rand.Intn(hostsLen)]
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandUserAgent() string {
|
||||||
|
return userAgents[rand.Intn(uaLen)]
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetUserAgent(header http.Header) {
|
||||||
|
if header.Get("User-Agent") != "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userAgent := RandUserAgent()
|
||||||
|
header.Set("User-Agent", userAgent)
|
||||||
|
}
|
89
common/convert/v.go
Normal file
89
common/convert/v.go
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
package convert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) {
|
||||||
|
// Xray VMessAEAD / VLESS share link standard
|
||||||
|
// https://github.com/XTLS/Xray-core/discussions/716
|
||||||
|
query := url.Query()
|
||||||
|
proxy["name"] = uniqueName(names, url.Fragment)
|
||||||
|
proxy["type"] = scheme
|
||||||
|
proxy["server"] = url.Hostname()
|
||||||
|
proxy["port"] = url.Port()
|
||||||
|
proxy["uuid"] = url.User.Username()
|
||||||
|
proxy["udp"] = true
|
||||||
|
proxy["skip-cert-verify"] = false
|
||||||
|
proxy["tls"] = false
|
||||||
|
tls := strings.ToLower(query.Get("security"))
|
||||||
|
if strings.HasSuffix(tls, "tls") {
|
||||||
|
proxy["tls"] = true
|
||||||
|
}
|
||||||
|
if sni := query.Get("sni"); sni != "" {
|
||||||
|
proxy["servername"] = sni
|
||||||
|
}
|
||||||
|
|
||||||
|
network := strings.ToLower(query.Get("type"))
|
||||||
|
if network == "" {
|
||||||
|
network = "tcp"
|
||||||
|
}
|
||||||
|
fakeType := strings.ToLower(query.Get("headerType"))
|
||||||
|
if fakeType == "http" {
|
||||||
|
network = "http"
|
||||||
|
} else if network == "http" {
|
||||||
|
network = "h2"
|
||||||
|
}
|
||||||
|
proxy["network"] = network
|
||||||
|
switch network {
|
||||||
|
case "tcp":
|
||||||
|
if fakeType != "none" {
|
||||||
|
headers := make(map[string]any)
|
||||||
|
httpOpts := make(map[string]any)
|
||||||
|
httpOpts["path"] = []string{"/"}
|
||||||
|
|
||||||
|
if host := query.Get("host"); host != "" {
|
||||||
|
headers["Host"] = []string{host}
|
||||||
|
}
|
||||||
|
|
||||||
|
if method := query.Get("method"); method != "" {
|
||||||
|
httpOpts["method"] = method
|
||||||
|
}
|
||||||
|
|
||||||
|
if path := query.Get("path"); path != "" {
|
||||||
|
httpOpts["path"] = []string{path}
|
||||||
|
}
|
||||||
|
httpOpts["headers"] = headers
|
||||||
|
proxy["http-opts"] = httpOpts
|
||||||
|
}
|
||||||
|
|
||||||
|
case "http":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
h2Opts := make(map[string]any)
|
||||||
|
h2Opts["path"] = []string{"/"}
|
||||||
|
if path := query.Get("path"); path != "" {
|
||||||
|
h2Opts["path"] = []string{path}
|
||||||
|
}
|
||||||
|
if host := query.Get("host"); host != "" {
|
||||||
|
h2Opts["host"] = []string{host}
|
||||||
|
}
|
||||||
|
h2Opts["headers"] = headers
|
||||||
|
proxy["h2-opts"] = h2Opts
|
||||||
|
|
||||||
|
case "ws":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
wsOpts := make(map[string]any)
|
||||||
|
headers["User-Agent"] = RandUserAgent()
|
||||||
|
headers["Host"] = query.Get("host")
|
||||||
|
wsOpts["path"] = query.Get("path")
|
||||||
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
|
proxy["ws-opts"] = wsOpts
|
||||||
|
|
||||||
|
case "grpc":
|
||||||
|
grpcOpts := make(map[string]any)
|
||||||
|
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||||
|
proxy["grpc-opts"] = grpcOpts
|
||||||
|
}
|
||||||
|
}
|
@ -1,5 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
const (
|
|
||||||
UA = "Clash"
|
|
||||||
)
|
|
@ -4,8 +4,6 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Relay copies between left and right bidirectionally.
|
// Relay copies between left and right bidirectionally.
|
||||||
@ -13,18 +11,14 @@ func Relay(leftConn, rightConn net.Conn) {
|
|||||||
ch := make(chan error)
|
ch := make(chan error)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
buf := pool.Get(pool.RelayBufferSize)
|
|
||||||
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// See also https://github.com/Dreamacro/clash/pull/1209
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
_, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||||
pool.Put(buf)
|
|
||||||
leftConn.SetReadDeadline(time.Now())
|
leftConn.SetReadDeadline(time.Now())
|
||||||
ch <- err
|
ch <- err
|
||||||
}()
|
}()
|
||||||
|
|
||||||
buf := pool.Get(pool.RelayBufferSize)
|
_, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||||
io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
|
||||||
pool.Put(buf)
|
|
||||||
rightConn.SetReadDeadline(time.Now())
|
rightConn.SetReadDeadline(time.Now())
|
||||||
<-ch
|
<-ch
|
||||||
}
|
}
|
||||||
|
@ -52,8 +52,8 @@ func (alloc *Allocator) Put(buf []byte) error {
|
|||||||
return errors.New("allocator Put() incorrect buffer size")
|
return errors.New("allocator Put() incorrect buffer size")
|
||||||
}
|
}
|
||||||
|
|
||||||
//lint:ignore SA6002 ignore temporarily
|
|
||||||
//nolint
|
//nolint
|
||||||
|
//lint:ignore SA6002 ignore temporarily
|
||||||
alloc.buffers[bits].Put(buf)
|
alloc.buffers[bits].Put(buf)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
7
common/pool/sing.go
Normal file
7
common/pool/sing.go
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import "github.com/sagernet/sing/common/buf"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
buf.DefaultAllocator = defaultAllocator
|
||||||
|
}
|
@ -25,7 +25,6 @@ type Result[T any] struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do single.Do likes sync.singleFlight
|
// Do single.Do likes sync.singleFlight
|
||||||
//lint:ignore ST1008 it likes sync.singleFlight
|
|
||||||
func (s *Single[T]) Do(fn func() (T, error)) (v T, err error, shared bool) {
|
func (s *Single[T]) Do(fn func() (T, error)) (v T, err error, shared bool) {
|
||||||
s.mux.Lock()
|
s.mux.Lock()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
@ -159,9 +159,19 @@ func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
|||||||
for valSlice.Len() <= i {
|
for valSlice.Len() <= i {
|
||||||
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
||||||
}
|
}
|
||||||
currentField := valSlice.Index(i)
|
|
||||||
|
|
||||||
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
||||||
|
if currentData == nil {
|
||||||
|
// in weakly type mode, null will convert to zero value
|
||||||
|
if d.option.WeaklyTypedInput {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// in non-weakly type mode, null will convert to nil if element's zero value is nil, otherwise return an error
|
||||||
|
if elemKind := valElemType.Kind(); elemKind == reflect.Map || elemKind == reflect.Slice {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return fmt.Errorf("'%s' can not be null", fieldName)
|
||||||
|
}
|
||||||
|
currentField := valSlice.Index(i)
|
||||||
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
16
common/utils/uuid.go
Normal file
16
common/utils/uuid.go
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var uuidNamespace, _ = uuid.FromString("00000000-0000-0000-0000-000000000000")
|
||||||
|
|
||||||
|
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
||||||
|
func UUIDMap(str string) (uuid.UUID, error) {
|
||||||
|
u, err := uuid.FromString(str)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.NewV5(uuidNamespace, str), nil
|
||||||
|
}
|
||||||
|
return u, nil
|
||||||
|
}
|
74
common/utils/uuid_test.go
Normal file
74
common/utils/uuid_test.go
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUUIDMap(t *testing.T) {
|
||||||
|
type args struct {
|
||||||
|
str string
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args args
|
||||||
|
want uuid.UUID
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "uuid-test-1",
|
||||||
|
args: args{
|
||||||
|
str: "82410302-039e-41b6-98b0-d964084b4170",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("82410302-039e-41b6-98b0-d964084b4170"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "uuid-test-2",
|
||||||
|
args: args{
|
||||||
|
str: "88c502e6-d7eb-4c8e-8259-94cb13d83c77",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("88c502e6-d7eb-4c8e-8259-94cb13d83c77"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "uuid-map-1",
|
||||||
|
args: args{
|
||||||
|
str: "123456",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("f8598425-92f2-5508-a071-4fc67f9040ac"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
// GENERATED BY 'xray uuid -i'
|
||||||
|
{
|
||||||
|
name: "uuid-map-2",
|
||||||
|
args: args{
|
||||||
|
str: "a9dk23bz0",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("c91481b6-fc0f-5d9e-b166-5ddf07b9c3c5"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "uuid-map-2",
|
||||||
|
args: args{
|
||||||
|
str: "中文123",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("145c544c-2229-59e5-8dbb-3f33b7610d26"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, err := UUIDMap(tt.args.str)
|
||||||
|
if (err != nil) != tt.wantErr {
|
||||||
|
t.Errorf("UUIDMap() error = %v, wantErr %v", err, tt.wantErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Errorf("UUIDMap() got = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@ -4,18 +4,22 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
"go.uber.org/atomic"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
dialMux sync.Mutex
|
dialMux sync.Mutex
|
||||||
actualSingleDialContext = singleDialContext
|
actualSingleDialContext = singleDialContext
|
||||||
actualDualStackDialContext = dualStackDialContext
|
actualDualStackDialContext = dualStackDialContext
|
||||||
|
tcpConcurrent = false
|
||||||
DisableIPv6 = false
|
DisableIPv6 = false
|
||||||
|
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||||
|
ErrorDisableIPv6 = errors.New("IPv6 is disabled, dialer cancel")
|
||||||
)
|
)
|
||||||
|
|
||||||
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||||
@ -32,13 +36,23 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
o(opt)
|
o(opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if opt.network == 4 || opt.network == 6 {
|
||||||
|
if strings.Contains(network, "tcp") {
|
||||||
|
network = "tcp"
|
||||||
|
} else {
|
||||||
|
network = "udp"
|
||||||
|
}
|
||||||
|
|
||||||
|
network = fmt.Sprintf("%s%d", network, opt.network)
|
||||||
|
}
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
return actualSingleDialContext(ctx, network, address, opt)
|
return actualSingleDialContext(ctx, network, address, opt)
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return actualDualStackDialContext(ctx, network, address, opt)
|
return actualDualStackDialContext(ctx, network, address, opt)
|
||||||
default:
|
default:
|
||||||
return nil, errors.New("network invalid")
|
return nil, ErrorInvalidedNetworkStack
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -76,17 +90,22 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
|
|
||||||
func SetDial(concurrent bool) {
|
func SetDial(concurrent bool) {
|
||||||
dialMux.Lock()
|
dialMux.Lock()
|
||||||
|
tcpConcurrent = concurrent
|
||||||
if concurrent {
|
if concurrent {
|
||||||
actualSingleDialContext = concurrentSingleDialContext
|
actualSingleDialContext = concurrentSingleDialContext
|
||||||
actualDualStackDialContext = concurrentDualStackDialContext
|
actualDualStackDialContext = concurrentDualStackDialContext
|
||||||
} else {
|
} else {
|
||||||
actualSingleDialContext = singleDialContext
|
actualSingleDialContext = singleDialContext
|
||||||
actualDualStackDialContext = concurrentDualStackDialContext
|
actualDualStackDialContext = dualStackDialContext
|
||||||
}
|
}
|
||||||
|
|
||||||
dialMux.Unlock()
|
dialMux.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetDial() bool {
|
||||||
|
return tcpConcurrent
|
||||||
|
}
|
||||||
|
|
||||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
dialer := &net.Dialer{}
|
dialer := &net.Dialer{}
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
@ -99,7 +118,7 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
}
|
}
|
||||||
|
|
||||||
if DisableIPv6 && destination.Is6() {
|
if DisableIPv6 && destination.Is6() {
|
||||||
return nil, fmt.Errorf("IPv6 is diabled, dialer cancel")
|
return nil, ErrorDisableIPv6
|
||||||
}
|
}
|
||||||
|
|
||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||||
@ -161,29 +180,35 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
go startRacer(ctx, network+"4", host, opt.direct, false)
|
go startRacer(ctx, network+"4", host, opt.direct, false)
|
||||||
go startRacer(ctx, network+"6", host, opt.direct, true)
|
go startRacer(ctx, network+"6", host, opt.direct, true)
|
||||||
|
|
||||||
for res := range results {
|
count := 2
|
||||||
if res.error == nil {
|
for i := 0; i < count; i++ {
|
||||||
return res.Conn, nil
|
select {
|
||||||
}
|
case res := <-results:
|
||||||
|
if res.error == nil {
|
||||||
if !res.ipv6 {
|
return res.Conn, nil
|
||||||
primary = res
|
|
||||||
} else {
|
|
||||||
fallback = res
|
|
||||||
}
|
|
||||||
|
|
||||||
if primary.done && fallback.done {
|
|
||||||
if primary.resolved {
|
|
||||||
return nil, primary.error
|
|
||||||
} else if fallback.resolved {
|
|
||||||
return nil, fallback.error
|
|
||||||
} else {
|
|
||||||
return nil, primary.error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !res.ipv6 {
|
||||||
|
primary = res
|
||||||
|
} else {
|
||||||
|
fallback = res
|
||||||
|
}
|
||||||
|
|
||||||
|
if primary.done && fallback.done {
|
||||||
|
if primary.resolved {
|
||||||
|
return nil, primary.error
|
||||||
|
} else if fallback.resolved {
|
||||||
|
return nil, fallback.error
|
||||||
|
} else {
|
||||||
|
return nil, primary.error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, errors.New("never touched")
|
return nil, errors.New("dual stack tcp shake hands failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
@ -193,13 +218,16 @@ func concurrentDualStackDialContext(ctx context.Context, network, address string
|
|||||||
}
|
}
|
||||||
|
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
|
|
||||||
if opt.direct {
|
if opt.direct {
|
||||||
ips, err = resolver.ResolveAllIP(host)
|
ips, err = resolver.ResolveAllIP(host)
|
||||||
} else {
|
} else {
|
||||||
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -211,30 +239,49 @@ func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr
|
|||||||
ip netip.Addr
|
ip netip.Addr
|
||||||
net.Conn
|
net.Conn
|
||||||
error
|
error
|
||||||
resolved bool
|
isPrimary bool
|
||||||
|
done bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
preferCount := atomic.NewInt32(0)
|
||||||
results := make(chan dialResult)
|
results := make(chan dialResult)
|
||||||
|
|
||||||
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
||||||
result := dialResult{ip: ip}
|
result := dialResult{ip: ip, done: true}
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
case <-returned:
|
case <-returned:
|
||||||
if result.Conn != nil {
|
if result.Conn != nil {
|
||||||
result.Conn.Close()
|
_ = result.Conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
if strings.Contains(network, "tcp") {
|
||||||
v := "4"
|
network = "tcp"
|
||||||
if ip.Is6() {
|
} else {
|
||||||
v = "6"
|
network = "udp"
|
||||||
}
|
}
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network+v, ip, port, opt)
|
if ip.Is6() {
|
||||||
|
network += "6"
|
||||||
|
if opt.prefer != 4 {
|
||||||
|
result.isPrimary = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip.Is4() {
|
||||||
|
network += "4"
|
||||||
|
if opt.prefer != 6 {
|
||||||
|
result.isPrimary = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if result.isPrimary {
|
||||||
|
preferCount.Add(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, ip := range ips {
|
for _, ip := range ips {
|
||||||
@ -242,18 +289,49 @@ func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr
|
|||||||
}
|
}
|
||||||
|
|
||||||
connCount := len(ips)
|
connCount := len(ips)
|
||||||
for res := range results {
|
var fallback dialResult
|
||||||
connCount--
|
var primaryError error
|
||||||
if res.error == nil {
|
for i := 0; i < connCount; i++ {
|
||||||
return res.Conn, nil
|
select {
|
||||||
}
|
case res := <-results:
|
||||||
|
if res.error == nil {
|
||||||
if connCount == 0 {
|
if res.isPrimary {
|
||||||
|
return res.Conn, nil
|
||||||
|
} else {
|
||||||
|
if !fallback.done || fallback.error != nil {
|
||||||
|
fallback = res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if res.isPrimary {
|
||||||
|
primaryError = res.error
|
||||||
|
preferCount.Add(-1)
|
||||||
|
if preferCount.Load() == 0 && fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, errors.New("all ip tcp shake hands failed")
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if primaryError != nil {
|
||||||
|
return nil, primaryError
|
||||||
|
}
|
||||||
|
|
||||||
|
if fallback.error != nil {
|
||||||
|
return nil, fallback.error
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
||||||
}
|
}
|
||||||
|
|
||||||
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
@ -285,25 +363,45 @@ func singleDialContext(ctx context.Context, network string, address string, opt
|
|||||||
}
|
}
|
||||||
|
|
||||||
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
return concurrentIPv4DialContext(ctx, network, address, opt)
|
||||||
|
default:
|
||||||
|
return concurrentIPv6DialContext(ctx, network, address, opt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentIPv4DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
switch network {
|
if !opt.direct {
|
||||||
case "tcp4", "udp4":
|
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
||||||
if !opt.direct {
|
} else {
|
||||||
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
ips, err = resolver.ResolveAllIPv4(host)
|
||||||
} else {
|
}
|
||||||
ips, err = resolver.ResolveAllIPv4(host)
|
|
||||||
}
|
if err != nil {
|
||||||
default:
|
return nil, err
|
||||||
if !opt.direct {
|
}
|
||||||
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
ips, err = resolver.ResolveAllIPv6(host)
|
}
|
||||||
}
|
|
||||||
|
func concurrentIPv6DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
if !opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPv6(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import "go.uber.org/atomic"
|
import (
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
DefaultOptions []Option
|
DefaultOptions []Option
|
||||||
@ -13,6 +15,8 @@ type option struct {
|
|||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
direct bool
|
direct bool
|
||||||
|
network int
|
||||||
|
prefer int
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opt *option)
|
type Option func(opt *option)
|
||||||
@ -40,3 +44,25 @@ func WithDirect() Option {
|
|||||||
opt.direct = true
|
opt.direct = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WithPreferIPv4() Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.prefer = 4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithPreferIPv6() Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.prefer = 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithOnlySingleStack(isIPv4 bool) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
if isIPv4 {
|
||||||
|
opt.network = 4
|
||||||
|
} else {
|
||||||
|
opt.network = 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
99
component/ebpf/bpf/bpf_endian.h
Normal file
99
component/ebpf/bpf/bpf_endian.h
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
|
||||||
|
#ifndef __BPF_ENDIAN__
|
||||||
|
#define __BPF_ENDIAN__
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Isolate byte #n and put it into byte #m, for __u##b type.
|
||||||
|
* E.g., moving byte #6 (nnnnnnnn) into byte #1 (mmmmmmmm) for __u64:
|
||||||
|
* 1) xxxxxxxx nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx
|
||||||
|
* 2) nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx 00000000
|
||||||
|
* 3) 00000000 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn
|
||||||
|
* 4) 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn 00000000
|
||||||
|
*/
|
||||||
|
#define ___bpf_mvb(x, b, n, m) ((__u##b)(x) << (b-(n+1)*8) >> (b-8) << (m*8))
|
||||||
|
|
||||||
|
#define ___bpf_swab16(x) ((__u16)( \
|
||||||
|
___bpf_mvb(x, 16, 0, 1) | \
|
||||||
|
___bpf_mvb(x, 16, 1, 0)))
|
||||||
|
|
||||||
|
#define ___bpf_swab32(x) ((__u32)( \
|
||||||
|
___bpf_mvb(x, 32, 0, 3) | \
|
||||||
|
___bpf_mvb(x, 32, 1, 2) | \
|
||||||
|
___bpf_mvb(x, 32, 2, 1) | \
|
||||||
|
___bpf_mvb(x, 32, 3, 0)))
|
||||||
|
|
||||||
|
#define ___bpf_swab64(x) ((__u64)( \
|
||||||
|
___bpf_mvb(x, 64, 0, 7) | \
|
||||||
|
___bpf_mvb(x, 64, 1, 6) | \
|
||||||
|
___bpf_mvb(x, 64, 2, 5) | \
|
||||||
|
___bpf_mvb(x, 64, 3, 4) | \
|
||||||
|
___bpf_mvb(x, 64, 4, 3) | \
|
||||||
|
___bpf_mvb(x, 64, 5, 2) | \
|
||||||
|
___bpf_mvb(x, 64, 6, 1) | \
|
||||||
|
___bpf_mvb(x, 64, 7, 0)))
|
||||||
|
|
||||||
|
/* LLVM's BPF target selects the endianness of the CPU
|
||||||
|
* it compiles on, or the user specifies (bpfel/bpfeb),
|
||||||
|
* respectively. The used __BYTE_ORDER__ is defined by
|
||||||
|
* the compiler, we cannot rely on __BYTE_ORDER from
|
||||||
|
* libc headers, since it doesn't reflect the actual
|
||||||
|
* requested byte order.
|
||||||
|
*
|
||||||
|
* Note, LLVM's BPF target has different __builtin_bswapX()
|
||||||
|
* semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE
|
||||||
|
* in bpfel and bpfeb case, which means below, that we map
|
||||||
|
* to cpu_to_be16(). We could use it unconditionally in BPF
|
||||||
|
* case, but better not rely on it, so that this header here
|
||||||
|
* can be used from application and BPF program side, which
|
||||||
|
* use different targets.
|
||||||
|
*/
|
||||||
|
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
|
||||||
|
# define __bpf_ntohs(x) __builtin_bswap16(x)
|
||||||
|
# define __bpf_htons(x) __builtin_bswap16(x)
|
||||||
|
# define __bpf_constant_ntohs(x) ___bpf_swab16(x)
|
||||||
|
# define __bpf_constant_htons(x) ___bpf_swab16(x)
|
||||||
|
# define __bpf_ntohl(x) __builtin_bswap32(x)
|
||||||
|
# define __bpf_htonl(x) __builtin_bswap32(x)
|
||||||
|
# define __bpf_constant_ntohl(x) ___bpf_swab32(x)
|
||||||
|
# define __bpf_constant_htonl(x) ___bpf_swab32(x)
|
||||||
|
# define __bpf_be64_to_cpu(x) __builtin_bswap64(x)
|
||||||
|
# define __bpf_cpu_to_be64(x) __builtin_bswap64(x)
|
||||||
|
# define __bpf_constant_be64_to_cpu(x) ___bpf_swab64(x)
|
||||||
|
# define __bpf_constant_cpu_to_be64(x) ___bpf_swab64(x)
|
||||||
|
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
|
||||||
|
# define __bpf_ntohs(x) (x)
|
||||||
|
# define __bpf_htons(x) (x)
|
||||||
|
# define __bpf_constant_ntohs(x) (x)
|
||||||
|
# define __bpf_constant_htons(x) (x)
|
||||||
|
# define __bpf_ntohl(x) (x)
|
||||||
|
# define __bpf_htonl(x) (x)
|
||||||
|
# define __bpf_constant_ntohl(x) (x)
|
||||||
|
# define __bpf_constant_htonl(x) (x)
|
||||||
|
# define __bpf_be64_to_cpu(x) (x)
|
||||||
|
# define __bpf_cpu_to_be64(x) (x)
|
||||||
|
# define __bpf_constant_be64_to_cpu(x) (x)
|
||||||
|
# define __bpf_constant_cpu_to_be64(x) (x)
|
||||||
|
#else
|
||||||
|
# error "Fix your compiler's __BYTE_ORDER__?!"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define bpf_htons(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_htons(x) : __bpf_htons(x))
|
||||||
|
#define bpf_ntohs(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_ntohs(x) : __bpf_ntohs(x))
|
||||||
|
#define bpf_htonl(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_htonl(x) : __bpf_htonl(x))
|
||||||
|
#define bpf_ntohl(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_ntohl(x) : __bpf_ntohl(x))
|
||||||
|
#define bpf_cpu_to_be64(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_cpu_to_be64(x) : __bpf_cpu_to_be64(x))
|
||||||
|
#define bpf_be64_to_cpu(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_be64_to_cpu(x) : __bpf_be64_to_cpu(x))
|
||||||
|
|
||||||
|
#endif /* __BPF_ENDIAN__ */
|
4139
component/ebpf/bpf/bpf_helper_defs.h
Normal file
4139
component/ebpf/bpf/bpf_helper_defs.h
Normal file
File diff suppressed because it is too large
Load Diff
262
component/ebpf/bpf/bpf_helpers.h
Normal file
262
component/ebpf/bpf/bpf_helpers.h
Normal file
@ -0,0 +1,262 @@
|
|||||||
|
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
|
||||||
|
#ifndef __BPF_HELPERS__
|
||||||
|
#define __BPF_HELPERS__
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Note that bpf programs need to include either
|
||||||
|
* vmlinux.h (auto-generated from BTF) or linux/types.h
|
||||||
|
* in advance since bpf_helper_defs.h uses such types
|
||||||
|
* as __u64.
|
||||||
|
*/
|
||||||
|
#include "bpf_helper_defs.h"
|
||||||
|
|
||||||
|
#define __uint(name, val) int (*name)[val]
|
||||||
|
#define __type(name, val) typeof(val) *name
|
||||||
|
#define __array(name, val) typeof(val) *name[]
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper macro to place programs, maps, license in
|
||||||
|
* different sections in elf_bpf file. Section names
|
||||||
|
* are interpreted by libbpf depending on the context (BPF programs, BPF maps,
|
||||||
|
* extern variables, etc).
|
||||||
|
* To allow use of SEC() with externs (e.g., for extern .maps declarations),
|
||||||
|
* make sure __attribute__((unused)) doesn't trigger compilation warning.
|
||||||
|
*/
|
||||||
|
#define SEC(name) \
|
||||||
|
_Pragma("GCC diagnostic push") \
|
||||||
|
_Pragma("GCC diagnostic ignored \"-Wignored-attributes\"") \
|
||||||
|
__attribute__((section(name), used)) \
|
||||||
|
_Pragma("GCC diagnostic pop") \
|
||||||
|
|
||||||
|
/* Avoid 'linux/stddef.h' definition of '__always_inline'. */
|
||||||
|
#undef __always_inline
|
||||||
|
#define __always_inline inline __attribute__((always_inline))
|
||||||
|
|
||||||
|
#ifndef __noinline
|
||||||
|
#define __noinline __attribute__((noinline))
|
||||||
|
#endif
|
||||||
|
#ifndef __weak
|
||||||
|
#define __weak __attribute__((weak))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Use __hidden attribute to mark a non-static BPF subprogram effectively
|
||||||
|
* static for BPF verifier's verification algorithm purposes, allowing more
|
||||||
|
* extensive and permissive BPF verification process, taking into account
|
||||||
|
* subprogram's caller context.
|
||||||
|
*/
|
||||||
|
#define __hidden __attribute__((visibility("hidden")))
|
||||||
|
|
||||||
|
/* When utilizing vmlinux.h with BPF CO-RE, user BPF programs can't include
|
||||||
|
* any system-level headers (such as stddef.h, linux/version.h, etc), and
|
||||||
|
* commonly-used macros like NULL and KERNEL_VERSION aren't available through
|
||||||
|
* vmlinux.h. This just adds unnecessary hurdles and forces users to re-define
|
||||||
|
* them on their own. So as a convenience, provide such definitions here.
|
||||||
|
*/
|
||||||
|
#ifndef NULL
|
||||||
|
#define NULL ((void *)0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef KERNEL_VERSION
|
||||||
|
#define KERNEL_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c)))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper macros to manipulate data structures
|
||||||
|
*/
|
||||||
|
#ifndef offsetof
|
||||||
|
#define offsetof(TYPE, MEMBER) ((unsigned long)&((TYPE *)0)->MEMBER)
|
||||||
|
#endif
|
||||||
|
#ifndef container_of
|
||||||
|
#define container_of(ptr, type, member) \
|
||||||
|
({ \
|
||||||
|
void *__mptr = (void *)(ptr); \
|
||||||
|
((type *)(__mptr - offsetof(type, member))); \
|
||||||
|
})
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper macro to throw a compilation error if __bpf_unreachable() gets
|
||||||
|
* built into the resulting code. This works given BPF back end does not
|
||||||
|
* implement __builtin_trap(). This is useful to assert that certain paths
|
||||||
|
* of the program code are never used and hence eliminated by the compiler.
|
||||||
|
*
|
||||||
|
* For example, consider a switch statement that covers known cases used by
|
||||||
|
* the program. __bpf_unreachable() can then reside in the default case. If
|
||||||
|
* the program gets extended such that a case is not covered in the switch
|
||||||
|
* statement, then it will throw a build error due to the default case not
|
||||||
|
* being compiled out.
|
||||||
|
*/
|
||||||
|
#ifndef __bpf_unreachable
|
||||||
|
# define __bpf_unreachable() __builtin_trap()
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper function to perform a tail call with a constant/immediate map slot.
|
||||||
|
*/
|
||||||
|
#if __clang_major__ >= 8 && defined(__bpf__)
|
||||||
|
static __always_inline void
|
||||||
|
bpf_tail_call_static(void *ctx, const void *map, const __u32 slot)
|
||||||
|
{
|
||||||
|
if (!__builtin_constant_p(slot))
|
||||||
|
__bpf_unreachable();
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Provide a hard guarantee that LLVM won't optimize setting r2 (map
|
||||||
|
* pointer) and r3 (constant map index) from _different paths_ ending
|
||||||
|
* up at the _same_ call insn as otherwise we won't be able to use the
|
||||||
|
* jmpq/nopl retpoline-free patching by the x86-64 JIT in the kernel
|
||||||
|
* given they mismatch. See also d2e4c1e6c294 ("bpf: Constant map key
|
||||||
|
* tracking for prog array pokes") for details on verifier tracking.
|
||||||
|
*
|
||||||
|
* Note on clobber list: we need to stay in-line with BPF calling
|
||||||
|
* convention, so even if we don't end up using r0, r4, r5, we need
|
||||||
|
* to mark them as clobber so that LLVM doesn't end up using them
|
||||||
|
* before / after the call.
|
||||||
|
*/
|
||||||
|
asm volatile("r1 = %[ctx]\n\t"
|
||||||
|
"r2 = %[map]\n\t"
|
||||||
|
"r3 = %[slot]\n\t"
|
||||||
|
"call 12"
|
||||||
|
:: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot)
|
||||||
|
: "r0", "r1", "r2", "r3", "r4", "r5");
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper structure used by eBPF C program
|
||||||
|
* to describe BPF map attributes to libbpf loader
|
||||||
|
*/
|
||||||
|
struct bpf_map_def {
|
||||||
|
unsigned int type;
|
||||||
|
unsigned int key_size;
|
||||||
|
unsigned int value_size;
|
||||||
|
unsigned int max_entries;
|
||||||
|
unsigned int map_flags;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum libbpf_pin_type {
|
||||||
|
LIBBPF_PIN_NONE,
|
||||||
|
/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
|
||||||
|
LIBBPF_PIN_BY_NAME,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum libbpf_tristate {
|
||||||
|
TRI_NO = 0,
|
||||||
|
TRI_YES = 1,
|
||||||
|
TRI_MODULE = 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
#define __kconfig __attribute__((section(".kconfig")))
|
||||||
|
#define __ksym __attribute__((section(".ksyms")))
|
||||||
|
|
||||||
|
#ifndef ___bpf_concat
|
||||||
|
#define ___bpf_concat(a, b) a ## b
|
||||||
|
#endif
|
||||||
|
#ifndef ___bpf_apply
|
||||||
|
#define ___bpf_apply(fn, n) ___bpf_concat(fn, n)
|
||||||
|
#endif
|
||||||
|
#ifndef ___bpf_nth
|
||||||
|
#define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N
|
||||||
|
#endif
|
||||||
|
#ifndef ___bpf_narg
|
||||||
|
#define ___bpf_narg(...) \
|
||||||
|
___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define ___bpf_fill0(arr, p, x) do {} while (0)
|
||||||
|
#define ___bpf_fill1(arr, p, x) arr[p] = x
|
||||||
|
#define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill(arr, args...) \
|
||||||
|
___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args)
|
||||||
|
|
||||||
|
/*
|
||||||
|
* BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values
|
||||||
|
* in a structure.
|
||||||
|
*/
|
||||||
|
#define BPF_SEQ_PRINTF(seq, fmt, args...) \
|
||||||
|
({ \
|
||||||
|
static const char ___fmt[] = fmt; \
|
||||||
|
unsigned long long ___param[___bpf_narg(args)]; \
|
||||||
|
\
|
||||||
|
_Pragma("GCC diagnostic push") \
|
||||||
|
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
||||||
|
___bpf_fill(___param, args); \
|
||||||
|
_Pragma("GCC diagnostic pop") \
|
||||||
|
\
|
||||||
|
bpf_seq_printf(seq, ___fmt, sizeof(___fmt), \
|
||||||
|
___param, sizeof(___param)); \
|
||||||
|
})
|
||||||
|
|
||||||
|
/*
|
||||||
|
* BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of
|
||||||
|
* an array of u64.
|
||||||
|
*/
|
||||||
|
#define BPF_SNPRINTF(out, out_size, fmt, args...) \
|
||||||
|
({ \
|
||||||
|
static const char ___fmt[] = fmt; \
|
||||||
|
unsigned long long ___param[___bpf_narg(args)]; \
|
||||||
|
\
|
||||||
|
_Pragma("GCC diagnostic push") \
|
||||||
|
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
||||||
|
___bpf_fill(___param, args); \
|
||||||
|
_Pragma("GCC diagnostic pop") \
|
||||||
|
\
|
||||||
|
bpf_snprintf(out, out_size, ___fmt, \
|
||||||
|
___param, sizeof(___param)); \
|
||||||
|
})
|
||||||
|
|
||||||
|
#ifdef BPF_NO_GLOBAL_DATA
|
||||||
|
#define BPF_PRINTK_FMT_MOD
|
||||||
|
#else
|
||||||
|
#define BPF_PRINTK_FMT_MOD static const
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define __bpf_printk(fmt, ...) \
|
||||||
|
({ \
|
||||||
|
BPF_PRINTK_FMT_MOD char ____fmt[] = fmt; \
|
||||||
|
bpf_trace_printk(____fmt, sizeof(____fmt), \
|
||||||
|
##__VA_ARGS__); \
|
||||||
|
})
|
||||||
|
|
||||||
|
/*
|
||||||
|
* __bpf_vprintk wraps the bpf_trace_vprintk helper with variadic arguments
|
||||||
|
* instead of an array of u64.
|
||||||
|
*/
|
||||||
|
#define __bpf_vprintk(fmt, args...) \
|
||||||
|
({ \
|
||||||
|
static const char ___fmt[] = fmt; \
|
||||||
|
unsigned long long ___param[___bpf_narg(args)]; \
|
||||||
|
\
|
||||||
|
_Pragma("GCC diagnostic push") \
|
||||||
|
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
||||||
|
___bpf_fill(___param, args); \
|
||||||
|
_Pragma("GCC diagnostic pop") \
|
||||||
|
\
|
||||||
|
bpf_trace_vprintk(___fmt, sizeof(___fmt), \
|
||||||
|
___param, sizeof(___param)); \
|
||||||
|
})
|
||||||
|
|
||||||
|
/* Use __bpf_printk when bpf_printk call has 3 or fewer fmt args
|
||||||
|
* Otherwise use __bpf_vprintk
|
||||||
|
*/
|
||||||
|
#define ___bpf_pick_printk(...) \
|
||||||
|
___bpf_nth(_, ##__VA_ARGS__, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \
|
||||||
|
__bpf_vprintk, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \
|
||||||
|
__bpf_vprintk, __bpf_vprintk, __bpf_printk /*3*/, __bpf_printk /*2*/,\
|
||||||
|
__bpf_printk /*1*/, __bpf_printk /*0*/)
|
||||||
|
|
||||||
|
/* Helper macro to print out debug messages */
|
||||||
|
#define bpf_printk(fmt, args...) ___bpf_pick_printk(args)(fmt, ##args)
|
||||||
|
|
||||||
|
#endif
|
342
component/ebpf/bpf/redir.c
Normal file
342
component/ebpf/bpf/redir.c
Normal file
@ -0,0 +1,342 @@
|
|||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
//#include <linux/types.h>
|
||||||
|
|
||||||
|
#include <linux/bpf.h>
|
||||||
|
#include <linux/if_ether.h>
|
||||||
|
//#include <linux/if_packet.h>
|
||||||
|
//#include <linux/if_vlan.h>
|
||||||
|
#include <linux/ip.h>
|
||||||
|
#include <linux/in.h>
|
||||||
|
#include <linux/tcp.h>
|
||||||
|
//#include <linux/udp.h>
|
||||||
|
|
||||||
|
#include <linux/pkt_cls.h>
|
||||||
|
|
||||||
|
#include "bpf_endian.h"
|
||||||
|
#include "bpf_helpers.h"
|
||||||
|
|
||||||
|
#define IP_CSUM_OFF (ETH_HLEN + offsetof(struct iphdr, check))
|
||||||
|
#define IP_DST_OFF (ETH_HLEN + offsetof(struct iphdr, daddr))
|
||||||
|
#define IP_SRC_OFF (ETH_HLEN + offsetof(struct iphdr, saddr))
|
||||||
|
#define IP_PROTO_OFF (ETH_HLEN + offsetof(struct iphdr, protocol))
|
||||||
|
#define TCP_CSUM_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, check))
|
||||||
|
#define TCP_SRC_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, source))
|
||||||
|
#define TCP_DST_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, dest))
|
||||||
|
//#define UDP_CSUM_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, check))
|
||||||
|
//#define UDP_SRC_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, source))
|
||||||
|
//#define UDP_DST_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, dest))
|
||||||
|
#define IS_PSEUDO 0x10
|
||||||
|
|
||||||
|
struct origin_info {
|
||||||
|
__be32 ip;
|
||||||
|
__be16 port;
|
||||||
|
__u16 pad;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct origin_info *origin_info_unused __attribute__((unused));
|
||||||
|
|
||||||
|
struct redir_info {
|
||||||
|
__be32 sip;
|
||||||
|
__be32 dip;
|
||||||
|
__be16 sport;
|
||||||
|
__be16 dport;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct redir_info *redir_info_unused __attribute__((unused));
|
||||||
|
|
||||||
|
struct {
|
||||||
|
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
||||||
|
__type(key, struct redir_info);
|
||||||
|
__type(value, struct origin_info);
|
||||||
|
__uint(max_entries, 65535);
|
||||||
|
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
||||||
|
} pair_original_dst_map SEC(".maps");
|
||||||
|
|
||||||
|
struct {
|
||||||
|
__uint(type, BPF_MAP_TYPE_ARRAY);
|
||||||
|
__type(key, __u32);
|
||||||
|
__type(value, __u32);
|
||||||
|
__uint(max_entries, 3);
|
||||||
|
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
||||||
|
} redir_params_map SEC(".maps");
|
||||||
|
|
||||||
|
static __always_inline int rewrite_ip(struct __sk_buff *skb, __be32 new_ip, bool is_dest) {
|
||||||
|
int ret, off = 0, flags = IS_PSEUDO;
|
||||||
|
__be32 old_ip;
|
||||||
|
|
||||||
|
if (is_dest)
|
||||||
|
ret = bpf_skb_load_bytes(skb, IP_DST_OFF, &old_ip, 4);
|
||||||
|
else
|
||||||
|
ret = bpf_skb_load_bytes(skb, IP_SRC_OFF, &old_ip, 4);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
off = TCP_CSUM_OFF;
|
||||||
|
// __u8 proto;
|
||||||
|
//
|
||||||
|
// ret = bpf_skb_load_bytes(skb, IP_PROTO_OFF, &proto, 1);
|
||||||
|
// if (ret < 0) {
|
||||||
|
// return BPF_DROP;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// switch (proto) {
|
||||||
|
// case IPPROTO_TCP:
|
||||||
|
// off = TCP_CSUM_OFF;
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case IPPROTO_UDP:
|
||||||
|
// off = UDP_CSUM_OFF;
|
||||||
|
// flags |= BPF_F_MARK_MANGLED_0;
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case IPPROTO_ICMPV6:
|
||||||
|
// off = offsetof(struct icmp6hdr, icmp6_cksum);
|
||||||
|
// break;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// if (off) {
|
||||||
|
ret = bpf_l4_csum_replace(skb, off, old_ip, new_ip, flags | sizeof(new_ip));
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
// }
|
||||||
|
|
||||||
|
ret = bpf_l3_csum_replace(skb, IP_CSUM_OFF, old_ip, new_ip, sizeof(new_ip));
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_dest)
|
||||||
|
ret = bpf_skb_store_bytes(skb, IP_DST_OFF, &new_ip, sizeof(new_ip), 0);
|
||||||
|
else
|
||||||
|
ret = bpf_skb_store_bytes(skb, IP_SRC_OFF, &new_ip, sizeof(new_ip), 0);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static __always_inline int rewrite_port(struct __sk_buff *skb, __be16 new_port, bool is_dest) {
|
||||||
|
int ret, off = 0;
|
||||||
|
__be16 old_port;
|
||||||
|
|
||||||
|
if (is_dest)
|
||||||
|
ret = bpf_skb_load_bytes(skb, TCP_DST_OFF, &old_port, 2);
|
||||||
|
else
|
||||||
|
ret = bpf_skb_load_bytes(skb, TCP_SRC_OFF, &old_port, 2);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
off = TCP_CSUM_OFF;
|
||||||
|
|
||||||
|
ret = bpf_l4_csum_replace(skb, off, old_port, new_port, sizeof(new_port));
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_dest)
|
||||||
|
ret = bpf_skb_store_bytes(skb, TCP_DST_OFF, &new_port, sizeof(new_port), 0);
|
||||||
|
else
|
||||||
|
ret = bpf_skb_store_bytes(skb, TCP_SRC_OFF, &new_port, sizeof(new_port), 0);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static __always_inline bool is_lan_ip(__be32 addr) {
|
||||||
|
if (addr == 0xffffffff)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
__u8 fist = (__u8)(addr & 0xff);
|
||||||
|
|
||||||
|
if (fist == 127 || fist == 10)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
__u8 second = (__u8)((addr >> 8) & 0xff);
|
||||||
|
|
||||||
|
if (fist == 172 && second >= 16 && second <= 31)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (fist == 192 && second == 168)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("tc_clash_auto_redir_ingress")
|
||||||
|
int tc_redir_ingress_func(struct __sk_buff *skb) {
|
||||||
|
void *data = (void *)(long)skb->data;
|
||||||
|
void *data_end = (void *)(long)skb->data_end;
|
||||||
|
struct ethhdr *eth = data;
|
||||||
|
|
||||||
|
if ((void *)(eth + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (eth->h_proto != bpf_htons(ETH_P_IP))
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
||||||
|
if ((void *)(iph + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__u32 key = 0, *route_index, *redir_ip, *redir_port;
|
||||||
|
|
||||||
|
route_index = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!route_index)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (iph->protocol == IPPROTO_ICMP && *route_index != 0)
|
||||||
|
return bpf_redirect(*route_index, 0);
|
||||||
|
|
||||||
|
if (iph->protocol != IPPROTO_TCP)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
||||||
|
if ((void *)(tcph + 1) > data_end)
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
|
||||||
|
key = 1;
|
||||||
|
redir_ip = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!redir_ip)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
key = 2;
|
||||||
|
redir_port = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!redir_port)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__be32 new_ip = bpf_htonl(*redir_ip);
|
||||||
|
__be16 new_port = bpf_htonl(*redir_port) >> 16;
|
||||||
|
__be32 old_ip = iph->daddr;
|
||||||
|
__be16 old_port = tcph->dest;
|
||||||
|
|
||||||
|
if (old_ip == new_ip || is_lan_ip(old_ip) || bpf_ntohs(old_port) == 53) {
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct redir_info p_key = {
|
||||||
|
.sip = iph->saddr,
|
||||||
|
.sport = tcph->source,
|
||||||
|
.dip = new_ip,
|
||||||
|
.dport = new_port,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (tcph->syn && !tcph->ack) {
|
||||||
|
struct origin_info origin = {
|
||||||
|
.ip = old_ip,
|
||||||
|
.port = old_port,
|
||||||
|
};
|
||||||
|
|
||||||
|
bpf_map_update_elem(&pair_original_dst_map, &p_key, &origin, BPF_NOEXIST);
|
||||||
|
|
||||||
|
if (rewrite_ip(skb, new_ip, true) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_port(skb, new_port, true) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
struct origin_info *origin = bpf_map_lookup_elem(&pair_original_dst_map, &p_key);
|
||||||
|
if (!origin) {
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_ip(skb, new_ip, true) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_port(skb, new_port, true) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("tc_clash_auto_redir_egress")
|
||||||
|
int tc_redir_egress_func(struct __sk_buff *skb) {
|
||||||
|
void *data = (void *)(long)skb->data;
|
||||||
|
void *data_end = (void *)(long)skb->data_end;
|
||||||
|
struct ethhdr *eth = data;
|
||||||
|
|
||||||
|
if ((void *)(eth + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (eth->h_proto != bpf_htons(ETH_P_IP))
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__u32 key = 0, *redir_ip, *redir_port; // *clash_mark
|
||||||
|
|
||||||
|
// clash_mark = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
// if (clash_mark && *clash_mark != 0 && *clash_mark == skb->mark)
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
|
||||||
|
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
||||||
|
if ((void *)(iph + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (iph->protocol != IPPROTO_TCP)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
||||||
|
if ((void *)(tcph + 1) > data_end)
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
|
||||||
|
key = 1;
|
||||||
|
redir_ip = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!redir_ip)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
key = 2;
|
||||||
|
redir_port = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!redir_port)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__be32 new_ip = bpf_htonl(*redir_ip);
|
||||||
|
__be16 new_port = bpf_htonl(*redir_port) >> 16;
|
||||||
|
__be32 old_ip = iph->saddr;
|
||||||
|
__be16 old_port = tcph->source;
|
||||||
|
|
||||||
|
if (old_ip != new_ip || old_port != new_port) {
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct redir_info p_key = {
|
||||||
|
.sip = iph->daddr,
|
||||||
|
.sport = tcph->dest,
|
||||||
|
.dip = iph->saddr,
|
||||||
|
.dport = tcph->source,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct origin_info *origin = bpf_map_lookup_elem(&pair_original_dst_map, &p_key);
|
||||||
|
if (!origin) {
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tcph->fin && tcph->ack) {
|
||||||
|
bpf_map_delete_elem(&pair_original_dst_map, &p_key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_ip(skb, origin->ip, false) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_port(skb, origin->port, false) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
char _license[] SEC("license") = "GPL";
|
103
component/ebpf/bpf/tc.c
Normal file
103
component/ebpf/bpf/tc.c
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
#include <stdbool.h>
|
||||||
|
#include <linux/bpf.h>
|
||||||
|
#include <linux/if_ether.h>
|
||||||
|
#include <linux/ip.h>
|
||||||
|
#include <linux/in.h>
|
||||||
|
//#include <linux/tcp.h>
|
||||||
|
//#include <linux/udp.h>
|
||||||
|
#include <linux/pkt_cls.h>
|
||||||
|
|
||||||
|
#include "bpf_endian.h"
|
||||||
|
#include "bpf_helpers.h"
|
||||||
|
|
||||||
|
struct {
|
||||||
|
__uint(type, BPF_MAP_TYPE_ARRAY);
|
||||||
|
__type(key, __u32);
|
||||||
|
__type(value, __u32);
|
||||||
|
__uint(max_entries, 2);
|
||||||
|
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
||||||
|
} tc_params_map SEC(".maps");
|
||||||
|
|
||||||
|
static __always_inline bool is_lan_ip(__be32 addr) {
|
||||||
|
if (addr == 0xffffffff)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
__u8 fist = (__u8)(addr & 0xff);
|
||||||
|
|
||||||
|
if (fist == 127 || fist == 10)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
__u8 second = (__u8)((addr >> 8) & 0xff);
|
||||||
|
|
||||||
|
if (fist == 172 && second >= 16 && second <= 31)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (fist == 192 && second == 168)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("tc_clash_redirect_to_tun")
|
||||||
|
int tc_tun_func(struct __sk_buff *skb) {
|
||||||
|
void *data = (void *)(long)skb->data;
|
||||||
|
void *data_end = (void *)(long)skb->data_end;
|
||||||
|
struct ethhdr *eth = data;
|
||||||
|
|
||||||
|
if ((void *)(eth + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (eth->h_proto == bpf_htons(ETH_P_ARP))
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__u32 key = 0, *clash_mark, *tun_ifindex;
|
||||||
|
|
||||||
|
clash_mark = bpf_map_lookup_elem(&tc_params_map, &key);
|
||||||
|
if (!clash_mark)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (skb->mark == *clash_mark)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (eth->h_proto == bpf_htons(ETH_P_IP)) {
|
||||||
|
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
||||||
|
if ((void *)(iph + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (iph->protocol == IPPROTO_ICMP)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__be32 daddr = iph->daddr;
|
||||||
|
|
||||||
|
if (is_lan_ip(daddr))
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
// if (iph->protocol == IPPROTO_TCP) {
|
||||||
|
// struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
||||||
|
// if ((void *)(tcph + 1) > data_end)
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
//
|
||||||
|
// __u16 source = bpf_ntohs(tcph->source);
|
||||||
|
// if (source == 22 || source == 80 || source == 443 || source == 8080 || source == 8443 || source == 9090 || (source >= 7890 && source <= 7895))
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
// } else if (iph->protocol == IPPROTO_UDP) {
|
||||||
|
// struct udphdr *udph = (struct udphdr *)(iph + 1);
|
||||||
|
// if ((void *)(udph + 1) > data_end)
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
//
|
||||||
|
// __u16 source = bpf_ntohs(udph->source);
|
||||||
|
// if (source == 53 || (source >= 135 && source <= 139))
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
key = 1;
|
||||||
|
tun_ifindex = bpf_map_lookup_elem(&tc_params_map, &key);
|
||||||
|
if (!tun_ifindex)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
//return bpf_redirect(*tun_ifindex, BPF_F_INGRESS); // __bpf_rx_skb
|
||||||
|
return bpf_redirect(*tun_ifindex, 0); // __bpf_tx_skb / __dev_xmit_skb
|
||||||
|
}
|
||||||
|
|
||||||
|
char _license[] SEC("license") = "GPL";
|
13
component/ebpf/byteorder/byteorder.go
Normal file
13
component/ebpf/byteorder/byteorder.go
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
package byteorder
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NetIPv4ToHost32 converts an net.IP to a uint32 in host byte order. ip
|
||||||
|
// must be a IPv4 address, otherwise the function will panic.
|
||||||
|
func NetIPv4ToHost32(ip net.IP) uint32 {
|
||||||
|
ipv4 := ip.To4()
|
||||||
|
_ = ipv4[3] // Assert length of ipv4.
|
||||||
|
return Native.Uint32(ipv4)
|
||||||
|
}
|
12
component/ebpf/byteorder/byteorder_bigendian.go
Normal file
12
component/ebpf/byteorder/byteorder_bigendian.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
||||||
|
|
||||||
|
package byteorder
|
||||||
|
|
||||||
|
import "encoding/binary"
|
||||||
|
|
||||||
|
var Native binary.ByteOrder = binary.BigEndian
|
||||||
|
|
||||||
|
func HostToNetwork16(u uint16) uint16 { return u }
|
||||||
|
func HostToNetwork32(u uint32) uint32 { return u }
|
||||||
|
func NetworkToHost16(u uint16) uint16 { return u }
|
||||||
|
func NetworkToHost32(u uint32) uint32 { return u }
|
15
component/ebpf/byteorder/byteorder_littleendian.go
Normal file
15
component/ebpf/byteorder/byteorder_littleendian.go
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
||||||
|
|
||||||
|
package byteorder
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"math/bits"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Native binary.ByteOrder = binary.LittleEndian
|
||||||
|
|
||||||
|
func HostToNetwork16(u uint16) uint16 { return bits.ReverseBytes16(u) }
|
||||||
|
func HostToNetwork32(u uint32) uint32 { return bits.ReverseBytes32(u) }
|
||||||
|
func NetworkToHost16(u uint16) uint16 { return bits.ReverseBytes16(u) }
|
||||||
|
func NetworkToHost32(u uint32) uint32 { return bits.ReverseBytes32(u) }
|
33
component/ebpf/ebpf.go
Normal file
33
component/ebpf/ebpf.go
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
package ebpf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TcEBpfProgram struct {
|
||||||
|
pros []C.EBpf
|
||||||
|
rawNICs []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TcEBpfProgram) RawNICs() []string {
|
||||||
|
return t.rawNICs
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TcEBpfProgram) Close() {
|
||||||
|
for _, p := range t.pros {
|
||||||
|
p.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TcEBpfProgram) Lookup(srcAddrPort netip.AddrPort) (addr socks5.Addr, err error) {
|
||||||
|
for _, p := range t.pros {
|
||||||
|
addr, err = p.Lookup(srcAddrPort)
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
138
component/ebpf/ebpf_linux.go
Normal file
138
component/ebpf/ebpf_linux.go
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
//go:build !android
|
||||||
|
|
||||||
|
package ebpf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/cmd"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/ebpf/redir"
|
||||||
|
"github.com/Dreamacro/clash/component/ebpf/tc"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetAutoDetectInterface() (string, error) {
|
||||||
|
routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, route := range routes {
|
||||||
|
if route.Dst == nil {
|
||||||
|
lk, err := netlink.LinkByIndex(route.LinkIndex)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if lk.Type() == "tuntap" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return lk.Attrs().Name, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", fmt.Errorf("interface not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTcEBpfProgram new redirect to tun ebpf program
|
||||||
|
func NewTcEBpfProgram(ifaceNames []string, tunName string) (*TcEBpfProgram, error) {
|
||||||
|
tunIface, err := netlink.LinkByName(tunName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q: %w", tunName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tunIndex := uint32(tunIface.Attrs().Index)
|
||||||
|
|
||||||
|
dialer.DefaultRoutingMark.Store(C.ClashTrafficMark)
|
||||||
|
|
||||||
|
ifMark := uint32(dialer.DefaultRoutingMark.Load())
|
||||||
|
|
||||||
|
var pros []C.EBpf
|
||||||
|
for _, ifaceName := range ifaceNames {
|
||||||
|
iface, err := netlink.LinkByName(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q: %w", ifaceName, err)
|
||||||
|
}
|
||||||
|
if iface.Attrs().OperState != netlink.OperUp {
|
||||||
|
return nil, fmt.Errorf("network iface %q is down", ifaceName)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := iface.Attrs()
|
||||||
|
index := attrs.Index
|
||||||
|
|
||||||
|
tcPro := tc.NewEBpfTc(ifaceName, index, ifMark, tunIndex)
|
||||||
|
if err = tcPro.Start(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pros = append(pros, tcPro)
|
||||||
|
}
|
||||||
|
|
||||||
|
systemSetting(ifaceNames...)
|
||||||
|
|
||||||
|
return &TcEBpfProgram{pros: pros, rawNICs: ifaceNames}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRedirEBpfProgram new auto redirect ebpf program
|
||||||
|
func NewRedirEBpfProgram(ifaceNames []string, redirPort uint16, defaultRouteInterfaceName string) (*TcEBpfProgram, error) {
|
||||||
|
defaultRouteInterface, err := netlink.LinkByName(defaultRouteInterfaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q: %w", defaultRouteInterfaceName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultRouteIndex := uint32(defaultRouteInterface.Attrs().Index)
|
||||||
|
|
||||||
|
var pros []C.EBpf
|
||||||
|
for _, ifaceName := range ifaceNames {
|
||||||
|
iface, err := netlink.LinkByName(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q: %w", ifaceName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := iface.Attrs()
|
||||||
|
index := attrs.Index
|
||||||
|
|
||||||
|
addrs, err := netlink.AddrList(iface, netlink.FAMILY_V4)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q address: %w", ifaceName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(addrs) == 0 {
|
||||||
|
return nil, fmt.Errorf("network iface %q does not contain any ipv4 addresses", ifaceName)
|
||||||
|
}
|
||||||
|
|
||||||
|
address, _ := netip.AddrFromSlice(addrs[0].IP)
|
||||||
|
redirAddrPort := netip.AddrPortFrom(address, redirPort)
|
||||||
|
|
||||||
|
redirPro := redir.NewEBpfRedirect(ifaceName, index, 0, defaultRouteIndex, redirAddrPort)
|
||||||
|
if err = redirPro.Start(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pros = append(pros, redirPro)
|
||||||
|
}
|
||||||
|
|
||||||
|
systemSetting(ifaceNames...)
|
||||||
|
|
||||||
|
return &TcEBpfProgram{pros: pros, rawNICs: ifaceNames}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func systemSetting(ifaceNames ...string) {
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.ip_forward=1")
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.forwarding=1")
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.accept_local=1")
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.accept_redirects=1")
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.rp_filter=0")
|
||||||
|
|
||||||
|
for _, ifaceName := range ifaceNames {
|
||||||
|
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.forwarding=1", ifaceName))
|
||||||
|
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.accept_local=1", ifaceName))
|
||||||
|
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.accept_redirects=1", ifaceName))
|
||||||
|
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.rp_filter=0", ifaceName))
|
||||||
|
}
|
||||||
|
}
|
21
component/ebpf/ebpf_others.go
Normal file
21
component/ebpf/ebpf_others.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
//go:build !linux || android
|
||||||
|
|
||||||
|
package ebpf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewTcEBpfProgram new ebpf tc program
|
||||||
|
func NewTcEBpfProgram(_ []string, _ string) (*TcEBpfProgram, error) {
|
||||||
|
return nil, fmt.Errorf("system not supported")
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRedirEBpfProgram new ebpf redirect program
|
||||||
|
func NewRedirEBpfProgram(_ []string, _ uint16, _ string) (*TcEBpfProgram, error) {
|
||||||
|
return nil, fmt.Errorf("system not supported")
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAutoDetectInterface() (string, error) {
|
||||||
|
return "", fmt.Errorf("system not supported")
|
||||||
|
}
|
216
component/ebpf/redir/auto_redirect.go
Normal file
216
component/ebpf/redir/auto_redirect.go
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
"github.com/cilium/ebpf/rlimit"
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/ebpf/byteorder"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf ../bpf/redir.c
|
||||||
|
|
||||||
|
const (
|
||||||
|
mapKey1 uint32 = 0
|
||||||
|
mapKey2 uint32 = 1
|
||||||
|
mapKey3 uint32 = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
type EBpfRedirect struct {
|
||||||
|
objs io.Closer
|
||||||
|
originMap *ebpf.Map
|
||||||
|
qdisc netlink.Qdisc
|
||||||
|
filter netlink.Filter
|
||||||
|
filterEgress netlink.Filter
|
||||||
|
|
||||||
|
ifName string
|
||||||
|
ifIndex int
|
||||||
|
ifMark uint32
|
||||||
|
rtIndex uint32
|
||||||
|
redirIp uint32
|
||||||
|
redirPort uint16
|
||||||
|
|
||||||
|
bpfPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEBpfRedirect(ifName string, ifIndex int, ifMark uint32, routeIndex uint32, redirAddrPort netip.AddrPort) *EBpfRedirect {
|
||||||
|
return &EBpfRedirect{
|
||||||
|
ifName: ifName,
|
||||||
|
ifIndex: ifIndex,
|
||||||
|
ifMark: ifMark,
|
||||||
|
rtIndex: routeIndex,
|
||||||
|
redirIp: binary.BigEndian.Uint32(redirAddrPort.Addr().AsSlice()),
|
||||||
|
redirPort: redirAddrPort.Port(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfRedirect) Start() error {
|
||||||
|
if err := rlimit.RemoveMemlock(); err != nil {
|
||||||
|
return fmt.Errorf("remove memory lock: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.bpfPath = filepath.Join(C.BpfFSPath, e.ifName)
|
||||||
|
if err := os.MkdirAll(e.bpfPath, os.ModePerm); err != nil {
|
||||||
|
return fmt.Errorf("failed to create bpf fs subpath: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var objs bpfObjects
|
||||||
|
if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
|
||||||
|
Maps: ebpf.MapOptions{
|
||||||
|
PinPath: e.bpfPath,
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("loading objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.objs = &objs
|
||||||
|
e.originMap = objs.bpfMaps.PairOriginalDstMap
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey1, e.rtIndex, ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey2, e.redirIp, ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey3, uint32(e.redirPort), ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := netlink.QdiscAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Handle: netlink.MakeHandle(0xffff, 0),
|
||||||
|
Parent: netlink.HANDLE_CLSACT,
|
||||||
|
}
|
||||||
|
|
||||||
|
qdisc := &netlink.GenericQdisc{
|
||||||
|
QdiscAttrs: attrs,
|
||||||
|
QdiscType: "clsact",
|
||||||
|
}
|
||||||
|
|
||||||
|
e.qdisc = qdisc
|
||||||
|
|
||||||
|
if err := netlink.QdiscAdd(qdisc); err != nil {
|
||||||
|
if os.IsExist(err) {
|
||||||
|
_ = netlink.QdiscDel(qdisc)
|
||||||
|
err = netlink.QdiscAdd(qdisc)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot add clsact qdisc: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
filterAttrs := netlink.FilterAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Parent: netlink.HANDLE_MIN_INGRESS,
|
||||||
|
Handle: netlink.MakeHandle(0, 1),
|
||||||
|
Protocol: unix.ETH_P_IP,
|
||||||
|
Priority: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
filter := &netlink.BpfFilter{
|
||||||
|
FilterAttrs: filterAttrs,
|
||||||
|
Fd: objs.bpfPrograms.TcRedirIngressFunc.FD(),
|
||||||
|
Name: "clash-redir-ingress-" + e.ifName,
|
||||||
|
DirectAction: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := netlink.FilterAdd(filter); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot attach ebpf object to filter ingress: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.filter = filter
|
||||||
|
|
||||||
|
filterAttrsEgress := netlink.FilterAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Parent: netlink.HANDLE_MIN_EGRESS,
|
||||||
|
Handle: netlink.MakeHandle(0, 1),
|
||||||
|
Protocol: unix.ETH_P_IP,
|
||||||
|
Priority: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
filterEgress := &netlink.BpfFilter{
|
||||||
|
FilterAttrs: filterAttrsEgress,
|
||||||
|
Fd: objs.bpfPrograms.TcRedirEgressFunc.FD(),
|
||||||
|
Name: "clash-redir-egress-" + e.ifName,
|
||||||
|
DirectAction: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := netlink.FilterAdd(filterEgress); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot attach ebpf object to filter egress: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.filterEgress = filterEgress
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfRedirect) Close() {
|
||||||
|
if e.filter != nil {
|
||||||
|
_ = netlink.FilterDel(e.filter)
|
||||||
|
}
|
||||||
|
if e.filterEgress != nil {
|
||||||
|
_ = netlink.FilterDel(e.filterEgress)
|
||||||
|
}
|
||||||
|
if e.qdisc != nil {
|
||||||
|
_ = netlink.QdiscDel(e.qdisc)
|
||||||
|
}
|
||||||
|
if e.objs != nil {
|
||||||
|
_ = e.objs.Close()
|
||||||
|
}
|
||||||
|
_ = os.Remove(filepath.Join(e.bpfPath, "redir_params_map"))
|
||||||
|
_ = os.Remove(filepath.Join(e.bpfPath, "pair_original_dst_map"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfRedirect) Lookup(srcAddrPort netip.AddrPort) (socks5.Addr, error) {
|
||||||
|
rAddr := srcAddrPort.Addr().Unmap()
|
||||||
|
if rAddr.Is6() {
|
||||||
|
return nil, fmt.Errorf("remote address is ipv6")
|
||||||
|
}
|
||||||
|
|
||||||
|
srcIp := binary.BigEndian.Uint32(rAddr.AsSlice())
|
||||||
|
scrPort := srcAddrPort.Port()
|
||||||
|
|
||||||
|
key := bpfRedirInfo{
|
||||||
|
Sip: byteorder.HostToNetwork32(srcIp),
|
||||||
|
Sport: byteorder.HostToNetwork16(scrPort),
|
||||||
|
Dip: byteorder.HostToNetwork32(e.redirIp),
|
||||||
|
Dport: byteorder.HostToNetwork16(e.redirPort),
|
||||||
|
}
|
||||||
|
|
||||||
|
origin := bpfOriginInfo{}
|
||||||
|
|
||||||
|
err := e.originMap.Lookup(key, &origin)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := make([]byte, net.IPv4len+3)
|
||||||
|
addr[0] = socks5.AtypIPv4
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint32(addr[1:1+net.IPv4len], byteorder.NetworkToHost32(origin.Ip)) // big end
|
||||||
|
binary.BigEndian.PutUint16(addr[1+net.IPv4len:3+net.IPv4len], byteorder.NetworkToHost16(origin.Port)) // big end
|
||||||
|
return addr, nil
|
||||||
|
}
|
138
component/ebpf/redir/bpf_bpfeb.go
Normal file
138
component/ebpf/redir/bpf_bpfeb.go
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
// Code generated by bpf2go; DO NOT EDIT.
|
||||||
|
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
||||||
|
// +build arm64be armbe mips mips64 mips64p32 ppc64 s390 s390x sparc sparc64
|
||||||
|
|
||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
)
|
||||||
|
|
||||||
|
type bpfOriginInfo struct {
|
||||||
|
Ip uint32
|
||||||
|
Port uint16
|
||||||
|
Pad uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
type bpfRedirInfo struct {
|
||||||
|
Sip uint32
|
||||||
|
Dip uint32
|
||||||
|
Sport uint16
|
||||||
|
Dport uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpf returns the embedded CollectionSpec for bpf.
|
||||||
|
func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||||
|
reader := bytes.NewReader(_BpfBytes)
|
||||||
|
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't load bpf: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpfObjects loads bpf and converts it into a struct.
|
||||||
|
//
|
||||||
|
// The following types are suitable as obj argument:
|
||||||
|
//
|
||||||
|
// *bpfObjects
|
||||||
|
// *bpfPrograms
|
||||||
|
// *bpfMaps
|
||||||
|
//
|
||||||
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
|
spec, err := loadBpf()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.LoadAndAssign(obj, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfSpecs struct {
|
||||||
|
bpfProgramSpecs
|
||||||
|
bpfMapSpecs
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfProgramSpecs struct {
|
||||||
|
TcRedirEgressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_egress_func"`
|
||||||
|
TcRedirIngressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_ingress_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfMapSpecs struct {
|
||||||
|
PairOriginalDstMap *ebpf.MapSpec `ebpf:"pair_original_dst_map"`
|
||||||
|
RedirParamsMap *ebpf.MapSpec `ebpf:"redir_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfObjects contains all objects after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfObjects struct {
|
||||||
|
bpfPrograms
|
||||||
|
bpfMaps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *bpfObjects) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
&o.bpfPrograms,
|
||||||
|
&o.bpfMaps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMaps contains all maps after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfMaps struct {
|
||||||
|
PairOriginalDstMap *ebpf.Map `ebpf:"pair_original_dst_map"`
|
||||||
|
RedirParamsMap *ebpf.Map `ebpf:"redir_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *bpfMaps) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
m.PairOriginalDstMap,
|
||||||
|
m.RedirParamsMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfPrograms struct {
|
||||||
|
TcRedirEgressFunc *ebpf.Program `ebpf:"tc_redir_egress_func"`
|
||||||
|
TcRedirIngressFunc *ebpf.Program `ebpf:"tc_redir_ingress_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bpfPrograms) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
p.TcRedirEgressFunc,
|
||||||
|
p.TcRedirIngressFunc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _BpfClose(closers ...io.Closer) error {
|
||||||
|
for _, closer := range closers {
|
||||||
|
if err := closer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not access this directly.
|
||||||
|
//go:embed bpf_bpfeb.o
|
||||||
|
var _BpfBytes []byte
|
BIN
component/ebpf/redir/bpf_bpfeb.o
Normal file
BIN
component/ebpf/redir/bpf_bpfeb.o
Normal file
Binary file not shown.
138
component/ebpf/redir/bpf_bpfel.go
Normal file
138
component/ebpf/redir/bpf_bpfel.go
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
// Code generated by bpf2go; DO NOT EDIT.
|
||||||
|
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
||||||
|
// +build 386 amd64 amd64p32 arm arm64 mips64le mips64p32le mipsle ppc64le riscv64
|
||||||
|
|
||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
)
|
||||||
|
|
||||||
|
type bpfOriginInfo struct {
|
||||||
|
Ip uint32
|
||||||
|
Port uint16
|
||||||
|
Pad uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
type bpfRedirInfo struct {
|
||||||
|
Sip uint32
|
||||||
|
Dip uint32
|
||||||
|
Sport uint16
|
||||||
|
Dport uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpf returns the embedded CollectionSpec for bpf.
|
||||||
|
func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||||
|
reader := bytes.NewReader(_BpfBytes)
|
||||||
|
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't load bpf: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpfObjects loads bpf and converts it into a struct.
|
||||||
|
//
|
||||||
|
// The following types are suitable as obj argument:
|
||||||
|
//
|
||||||
|
// *bpfObjects
|
||||||
|
// *bpfPrograms
|
||||||
|
// *bpfMaps
|
||||||
|
//
|
||||||
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
|
spec, err := loadBpf()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.LoadAndAssign(obj, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfSpecs struct {
|
||||||
|
bpfProgramSpecs
|
||||||
|
bpfMapSpecs
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfProgramSpecs struct {
|
||||||
|
TcRedirEgressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_egress_func"`
|
||||||
|
TcRedirIngressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_ingress_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfMapSpecs struct {
|
||||||
|
PairOriginalDstMap *ebpf.MapSpec `ebpf:"pair_original_dst_map"`
|
||||||
|
RedirParamsMap *ebpf.MapSpec `ebpf:"redir_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfObjects contains all objects after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfObjects struct {
|
||||||
|
bpfPrograms
|
||||||
|
bpfMaps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *bpfObjects) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
&o.bpfPrograms,
|
||||||
|
&o.bpfMaps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMaps contains all maps after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfMaps struct {
|
||||||
|
PairOriginalDstMap *ebpf.Map `ebpf:"pair_original_dst_map"`
|
||||||
|
RedirParamsMap *ebpf.Map `ebpf:"redir_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *bpfMaps) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
m.PairOriginalDstMap,
|
||||||
|
m.RedirParamsMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfPrograms struct {
|
||||||
|
TcRedirEgressFunc *ebpf.Program `ebpf:"tc_redir_egress_func"`
|
||||||
|
TcRedirIngressFunc *ebpf.Program `ebpf:"tc_redir_ingress_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bpfPrograms) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
p.TcRedirEgressFunc,
|
||||||
|
p.TcRedirIngressFunc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _BpfClose(closers ...io.Closer) error {
|
||||||
|
for _, closer := range closers {
|
||||||
|
if err := closer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not access this directly.
|
||||||
|
//go:embed bpf_bpfel.o
|
||||||
|
var _BpfBytes []byte
|
BIN
component/ebpf/redir/bpf_bpfel.o
Normal file
BIN
component/ebpf/redir/bpf_bpfel.o
Normal file
Binary file not shown.
119
component/ebpf/tc/bpf_bpfeb.go
Normal file
119
component/ebpf/tc/bpf_bpfeb.go
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
// Code generated by bpf2go; DO NOT EDIT.
|
||||||
|
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
||||||
|
// +build arm64be armbe mips mips64 mips64p32 ppc64 s390 s390x sparc sparc64
|
||||||
|
|
||||||
|
package tc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// loadBpf returns the embedded CollectionSpec for bpf.
|
||||||
|
func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||||
|
reader := bytes.NewReader(_BpfBytes)
|
||||||
|
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't load bpf: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpfObjects loads bpf and converts it into a struct.
|
||||||
|
//
|
||||||
|
// The following types are suitable as obj argument:
|
||||||
|
//
|
||||||
|
// *bpfObjects
|
||||||
|
// *bpfPrograms
|
||||||
|
// *bpfMaps
|
||||||
|
//
|
||||||
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
|
spec, err := loadBpf()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.LoadAndAssign(obj, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfSpecs struct {
|
||||||
|
bpfProgramSpecs
|
||||||
|
bpfMapSpecs
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfProgramSpecs struct {
|
||||||
|
TcTunFunc *ebpf.ProgramSpec `ebpf:"tc_tun_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfMapSpecs struct {
|
||||||
|
TcParamsMap *ebpf.MapSpec `ebpf:"tc_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfObjects contains all objects after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfObjects struct {
|
||||||
|
bpfPrograms
|
||||||
|
bpfMaps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *bpfObjects) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
&o.bpfPrograms,
|
||||||
|
&o.bpfMaps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMaps contains all maps after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfMaps struct {
|
||||||
|
TcParamsMap *ebpf.Map `ebpf:"tc_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *bpfMaps) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
m.TcParamsMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfPrograms struct {
|
||||||
|
TcTunFunc *ebpf.Program `ebpf:"tc_tun_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bpfPrograms) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
p.TcTunFunc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _BpfClose(closers ...io.Closer) error {
|
||||||
|
for _, closer := range closers {
|
||||||
|
if err := closer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not access this directly.
|
||||||
|
//go:embed bpf_bpfeb.o
|
||||||
|
var _BpfBytes []byte
|
BIN
component/ebpf/tc/bpf_bpfeb.o
Normal file
BIN
component/ebpf/tc/bpf_bpfeb.o
Normal file
Binary file not shown.
119
component/ebpf/tc/bpf_bpfel.go
Normal file
119
component/ebpf/tc/bpf_bpfel.go
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
// Code generated by bpf2go; DO NOT EDIT.
|
||||||
|
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
||||||
|
// +build 386 amd64 amd64p32 arm arm64 mips64le mips64p32le mipsle ppc64le riscv64
|
||||||
|
|
||||||
|
package tc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// loadBpf returns the embedded CollectionSpec for bpf.
|
||||||
|
func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||||
|
reader := bytes.NewReader(_BpfBytes)
|
||||||
|
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't load bpf: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpfObjects loads bpf and converts it into a struct.
|
||||||
|
//
|
||||||
|
// The following types are suitable as obj argument:
|
||||||
|
//
|
||||||
|
// *bpfObjects
|
||||||
|
// *bpfPrograms
|
||||||
|
// *bpfMaps
|
||||||
|
//
|
||||||
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
|
spec, err := loadBpf()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.LoadAndAssign(obj, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfSpecs struct {
|
||||||
|
bpfProgramSpecs
|
||||||
|
bpfMapSpecs
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfProgramSpecs struct {
|
||||||
|
TcTunFunc *ebpf.ProgramSpec `ebpf:"tc_tun_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfMapSpecs struct {
|
||||||
|
TcParamsMap *ebpf.MapSpec `ebpf:"tc_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfObjects contains all objects after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfObjects struct {
|
||||||
|
bpfPrograms
|
||||||
|
bpfMaps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *bpfObjects) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
&o.bpfPrograms,
|
||||||
|
&o.bpfMaps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMaps contains all maps after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfMaps struct {
|
||||||
|
TcParamsMap *ebpf.Map `ebpf:"tc_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *bpfMaps) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
m.TcParamsMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfPrograms struct {
|
||||||
|
TcTunFunc *ebpf.Program `ebpf:"tc_tun_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bpfPrograms) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
p.TcTunFunc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _BpfClose(closers ...io.Closer) error {
|
||||||
|
for _, closer := range closers {
|
||||||
|
if err := closer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not access this directly.
|
||||||
|
//go:embed bpf_bpfel.o
|
||||||
|
var _BpfBytes []byte
|
BIN
component/ebpf/tc/bpf_bpfel.o
Normal file
BIN
component/ebpf/tc/bpf_bpfel.o
Normal file
Binary file not shown.
147
component/ebpf/tc/redirect_to_tun.go
Normal file
147
component/ebpf/tc/redirect_to_tun.go
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package tc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
"github.com/cilium/ebpf/rlimit"
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf ../bpf/tc.c
|
||||||
|
|
||||||
|
const (
|
||||||
|
mapKey1 uint32 = 0
|
||||||
|
mapKey2 uint32 = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
type EBpfTC struct {
|
||||||
|
objs io.Closer
|
||||||
|
qdisc netlink.Qdisc
|
||||||
|
filter netlink.Filter
|
||||||
|
|
||||||
|
ifName string
|
||||||
|
ifIndex int
|
||||||
|
ifMark uint32
|
||||||
|
tunIfIndex uint32
|
||||||
|
|
||||||
|
bpfPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEBpfTc(ifName string, ifIndex int, ifMark uint32, tunIfIndex uint32) *EBpfTC {
|
||||||
|
return &EBpfTC{
|
||||||
|
ifName: ifName,
|
||||||
|
ifIndex: ifIndex,
|
||||||
|
ifMark: ifMark,
|
||||||
|
tunIfIndex: tunIfIndex,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfTC) Start() error {
|
||||||
|
if err := rlimit.RemoveMemlock(); err != nil {
|
||||||
|
return fmt.Errorf("remove memory lock: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.bpfPath = filepath.Join(C.BpfFSPath, e.ifName)
|
||||||
|
if err := os.MkdirAll(e.bpfPath, os.ModePerm); err != nil {
|
||||||
|
return fmt.Errorf("failed to create bpf fs subpath: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var objs bpfObjects
|
||||||
|
if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
|
||||||
|
Maps: ebpf.MapOptions{
|
||||||
|
PinPath: e.bpfPath,
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("loading objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.objs = &objs
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.TcParamsMap.Update(mapKey1, e.ifMark, ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.TcParamsMap.Update(mapKey2, e.tunIfIndex, ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := netlink.QdiscAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Handle: netlink.MakeHandle(0xffff, 0),
|
||||||
|
Parent: netlink.HANDLE_CLSACT,
|
||||||
|
}
|
||||||
|
|
||||||
|
qdisc := &netlink.GenericQdisc{
|
||||||
|
QdiscAttrs: attrs,
|
||||||
|
QdiscType: "clsact",
|
||||||
|
}
|
||||||
|
|
||||||
|
e.qdisc = qdisc
|
||||||
|
|
||||||
|
if err := netlink.QdiscAdd(qdisc); err != nil {
|
||||||
|
if os.IsExist(err) {
|
||||||
|
_ = netlink.QdiscDel(qdisc)
|
||||||
|
err = netlink.QdiscAdd(qdisc)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot add clsact qdisc: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
filterAttrs := netlink.FilterAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Parent: netlink.HANDLE_MIN_EGRESS,
|
||||||
|
Handle: netlink.MakeHandle(0, 1),
|
||||||
|
Protocol: unix.ETH_P_ALL,
|
||||||
|
Priority: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
filter := &netlink.BpfFilter{
|
||||||
|
FilterAttrs: filterAttrs,
|
||||||
|
Fd: objs.bpfPrograms.TcTunFunc.FD(),
|
||||||
|
Name: "clash-tc-" + e.ifName,
|
||||||
|
DirectAction: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := netlink.FilterAdd(filter); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot attach ebpf object to filter: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.filter = filter
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfTC) Close() {
|
||||||
|
if e.filter != nil {
|
||||||
|
_ = netlink.FilterDel(e.filter)
|
||||||
|
}
|
||||||
|
if e.qdisc != nil {
|
||||||
|
_ = netlink.QdiscDel(e.qdisc)
|
||||||
|
}
|
||||||
|
if e.objs != nil {
|
||||||
|
_ = e.objs.Close()
|
||||||
|
}
|
||||||
|
_ = os.Remove(filepath.Join(e.bpfPath, "tc_params_map"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfTC) Lookup(_ netip.AddrPort) (socks5.Addr, error) {
|
||||||
|
return nil, fmt.Errorf("not supported")
|
||||||
|
}
|
@ -166,7 +166,7 @@ func New(options Options) (*Pool, error) {
|
|||||||
var (
|
var (
|
||||||
hostAddr = options.IPNet.Masked().Addr()
|
hostAddr = options.IPNet.Masked().Addr()
|
||||||
gateway = hostAddr.Next()
|
gateway = hostAddr.Next()
|
||||||
first = gateway.Next().Next()
|
first = gateway.Next().Next().Next() // default start with 198.18.0.4
|
||||||
last = nnip.UnMasked(*options.IPNet)
|
last = nnip.UnMasked(*options.IPNet)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -62,16 +62,16 @@ func TestPool_Basic(t *testing.T) {
|
|||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
bar, exist := pool.LookBack(last)
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
assert.True(t, pool.Lookup("foo.com") == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
assert.True(t, pool.Lookup("foo.com") == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 5}))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.True(t, pool.Gateway() == netip.AddrFrom4([4]byte{192, 168, 0, 1}))
|
assert.True(t, pool.Gateway() == netip.AddrFrom4([4]byte{192, 168, 0, 1}))
|
||||||
assert.True(t, pool.Broadcast() == netip.AddrFrom4([4]byte{192, 168, 0, 15}))
|
assert.True(t, pool.Broadcast() == netip.AddrFrom4([4]byte{192, 168, 0, 15}))
|
||||||
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
||||||
assert.True(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 4})))
|
assert.True(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 5})))
|
||||||
assert.False(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 5})))
|
assert.False(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 6})))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("::1")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("::1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -90,16 +90,16 @@ func TestPool_BasicV6(t *testing.T) {
|
|||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
bar, exist := pool.LookBack(last)
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
assert.True(t, first == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8803"))
|
assert.True(t, first == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
||||||
assert.True(t, pool.Lookup("foo.com") == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8803"))
|
assert.True(t, pool.Lookup("foo.com") == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
||||||
assert.True(t, last == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
assert.True(t, last == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805"))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.True(t, pool.Gateway() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8801"))
|
assert.True(t, pool.Gateway() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8801"))
|
||||||
assert.True(t, pool.Broadcast() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8bff"))
|
assert.True(t, pool.Broadcast() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8bff"))
|
||||||
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
||||||
assert.True(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804")))
|
assert.True(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805")))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8806")))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("127.0.0.1")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("127.0.0.1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -116,7 +116,7 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
for _, pool := range pools {
|
for _, pool := range pools {
|
||||||
foo := pool.Lookup("foo.com")
|
foo := pool.Lookup("foo.com")
|
||||||
bar := pool.Lookup("bar.com")
|
bar := pool.Lookup("bar.com")
|
||||||
for i := 0; i < 10; i++ {
|
for i := 0; i < 9; i++ {
|
||||||
pool.Lookup(fmt.Sprintf("%d.com", i))
|
pool.Lookup(fmt.Sprintf("%d.com", i))
|
||||||
}
|
}
|
||||||
baz := pool.Lookup("baz.com")
|
baz := pool.Lookup("baz.com")
|
||||||
@ -198,8 +198,8 @@ func TestPool_Clone(t *testing.T) {
|
|||||||
|
|
||||||
first := pool.Lookup("foo.com")
|
first := pool.Lookup("foo.com")
|
||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 5}))
|
||||||
|
|
||||||
newPool, _ := New(Options{
|
newPool, _ := New(Options{
|
||||||
IPNet: &ipnet,
|
IPNet: &ipnet,
|
||||||
|
@ -30,7 +30,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
|||||||
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
||||||
}
|
}
|
||||||
|
|
||||||
domains, err := l.LoadSite(file, list)
|
domains, err := l.LoadSiteByPath(file, list)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -59,7 +59,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
||||||
return l.LoadIP(C.GeoipName, country)
|
return l.LoadIPByPath(C.GeoipName, country)
|
||||||
}
|
}
|
||||||
|
|
||||||
var loaders map[string]func() LoaderImplementation
|
var loaders map[string]func() LoaderImplementation
|
||||||
|
@ -5,8 +5,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type LoaderImplementation interface {
|
type LoaderImplementation interface {
|
||||||
LoadSite(filename, list string) ([]*router.Domain, error)
|
LoadSiteByPath(filename, list string) ([]*router.Domain, error)
|
||||||
LoadIP(filename, country string) ([]*router.CIDR, error)
|
LoadSiteByBytes(geositeBytes []byte, list string) ([]*router.Domain, error)
|
||||||
|
LoadIPByPath(filename, country string) ([]*router.CIDR, error)
|
||||||
|
LoadIPByBytes(geoipBytes []byte, country string) ([]*router.CIDR, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Loader interface {
|
type Loader interface {
|
||||||
|
52
component/geodata/init.go
Normal file
52
component/geodata/init.go
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
var initFlag bool
|
||||||
|
|
||||||
|
func InitGeoSite() error {
|
||||||
|
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
||||||
|
log.Infoln("Can't find GeoSite.dat, start download")
|
||||||
|
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
log.Infoln("Download GeoSite.dat finish")
|
||||||
|
}
|
||||||
|
if !initFlag {
|
||||||
|
if err := Verify(C.GeositeName); err != nil {
|
||||||
|
log.Warnln("GeoSite.dat invalid, remove and download: %s", err)
|
||||||
|
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't remove invalid GeoSite.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initFlag = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadGeoSite(path string) (err error) {
|
||||||
|
resp, err := http.Get(C.GeoSiteUrl)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, resp.Body)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
@ -1,6 +1,7 @@
|
|||||||
package memconservative
|
package memconservative
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
@ -13,7 +14,7 @@ type memConservativeLoader struct {
|
|||||||
geositecache GeoSiteCache
|
geositecache GeoSiteCache
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memConservativeLoader) LoadIP(filename, country string) ([]*router.CIDR, error) {
|
func (m *memConservativeLoader) LoadIPByPath(filename, country string) ([]*router.CIDR, error) {
|
||||||
defer runtime.GC()
|
defer runtime.GC()
|
||||||
geoip, err := m.geoipcache.Unmarshal(filename, country)
|
geoip, err := m.geoipcache.Unmarshal(filename, country)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -22,7 +23,11 @@ func (m *memConservativeLoader) LoadIP(filename, country string) ([]*router.CIDR
|
|||||||
return geoip.Cidr, nil
|
return geoip.Cidr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memConservativeLoader) LoadSite(filename, list string) ([]*router.Domain, error) {
|
func (m *memConservativeLoader) LoadIPByBytes(geoipBytes []byte, country string) ([]*router.CIDR, error) {
|
||||||
|
return nil, errors.New("memConservative do not support LoadIPByBytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memConservativeLoader) LoadSiteByPath(filename, list string) ([]*router.Domain, error) {
|
||||||
defer runtime.GC()
|
defer runtime.GC()
|
||||||
geosite, err := m.geositecache.Unmarshal(filename, list)
|
geosite, err := m.geositecache.Unmarshal(filename, list)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -31,6 +36,10 @@ func (m *memConservativeLoader) LoadSite(filename, list string) ([]*router.Domai
|
|||||||
return geosite.Domain, nil
|
return geosite.Domain, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *memConservativeLoader) LoadSiteByBytes(geositeBytes []byte, list string) ([]*router.Domain, error) {
|
||||||
|
return nil, errors.New("memConservative do not support LoadSiteByBytes")
|
||||||
|
}
|
||||||
|
|
||||||
func newMemConservativeLoader() geodata.LoaderImplementation {
|
func newMemConservativeLoader() geodata.LoaderImplementation {
|
||||||
return &memConservativeLoader{make(map[string]*router.GeoIP), make(map[string]*router.GeoSite)}
|
return &memConservativeLoader{make(map[string]*router.GeoIP), make(map[string]*router.GeoSite)}
|
||||||
}
|
}
|
||||||
|
@ -33,9 +33,10 @@ func domainToMatcher(domain *Domain) (strmatcher.Matcher, error) {
|
|||||||
|
|
||||||
type DomainMatcher struct {
|
type DomainMatcher struct {
|
||||||
matchers strmatcher.IndexMatcher
|
matchers strmatcher.IndexMatcher
|
||||||
|
not bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMphMatcherGroup(domains []*Domain) (*DomainMatcher, error) {
|
func NewMphMatcherGroup(domains []*Domain, not bool) (*DomainMatcher, error) {
|
||||||
g := strmatcher.NewMphMatcherGroup()
|
g := strmatcher.NewMphMatcherGroup()
|
||||||
for _, d := range domains {
|
for _, d := range domains {
|
||||||
matcherType, f := matcherTypeMap[d.Type]
|
matcherType, f := matcherTypeMap[d.Type]
|
||||||
@ -50,11 +51,12 @@ func NewMphMatcherGroup(domains []*Domain) (*DomainMatcher, error) {
|
|||||||
g.Build()
|
g.Build()
|
||||||
return &DomainMatcher{
|
return &DomainMatcher{
|
||||||
matchers: g,
|
matchers: g,
|
||||||
|
not: not,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewDomainMatcher new domain matcher.
|
// NewDomainMatcher new domain matcher.
|
||||||
func NewDomainMatcher(domains []*Domain) (*DomainMatcher, error) {
|
func NewDomainMatcher(domains []*Domain, not bool) (*DomainMatcher, error) {
|
||||||
g := new(strmatcher.MatcherGroup)
|
g := new(strmatcher.MatcherGroup)
|
||||||
for _, d := range domains {
|
for _, d := range domains {
|
||||||
m, err := domainToMatcher(d)
|
m, err := domainToMatcher(d)
|
||||||
@ -66,11 +68,16 @@ func NewDomainMatcher(domains []*Domain) (*DomainMatcher, error) {
|
|||||||
|
|
||||||
return &DomainMatcher{
|
return &DomainMatcher{
|
||||||
matchers: g,
|
matchers: g,
|
||||||
|
not: not,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *DomainMatcher) ApplyDomain(domain string) bool {
|
func (m *DomainMatcher) ApplyDomain(domain string) bool {
|
||||||
return len(m.matchers.Match(strings.ToLower(domain))) > 0
|
isMatched := len(m.matchers.Match(strings.ToLower(domain))) > 0
|
||||||
|
if m.not {
|
||||||
|
isMatched = !isMatched
|
||||||
|
}
|
||||||
|
return isMatched
|
||||||
}
|
}
|
||||||
|
|
||||||
// CIDRList is an alias of []*CIDR to provide sort.Interface.
|
// CIDRList is an alias of []*CIDR to provide sort.Interface.
|
||||||
|
@ -29,11 +29,7 @@ func ReadAsset(file string) ([]byte, error) {
|
|||||||
return ReadFile(C.Path.GetAssetLocation(file))
|
return ReadFile(C.Path.GetAssetLocation(file))
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadIP(filename, country string) ([]*router.CIDR, error) {
|
func loadIP(geoipBytes []byte, 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
|
var geoipList router.GeoIPList
|
||||||
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
|
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -45,14 +41,10 @@ func loadIP(filename, country string) ([]*router.CIDR, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, fmt.Errorf("country not found in %s%s%s", filename, ": ", country)
|
return nil, fmt.Errorf("country %s not found", country)
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadSite(filename, list string) ([]*router.Domain, error) {
|
func loadSite(geositeBytes []byte, 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
|
var geositeList router.GeoSiteList
|
||||||
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
|
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -64,17 +56,33 @@ func loadSite(filename, list string) ([]*router.Domain, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, fmt.Errorf("list not found in %s%s%s", filename, ": ", list)
|
return nil, fmt.Errorf("list %s not found", list)
|
||||||
}
|
}
|
||||||
|
|
||||||
type standardLoader struct{}
|
type standardLoader struct{}
|
||||||
|
|
||||||
func (d standardLoader) LoadSite(filename, list string) ([]*router.Domain, error) {
|
func (d standardLoader) LoadSiteByPath(filename, list string) ([]*router.Domain, error) {
|
||||||
return loadSite(filename, list)
|
geositeBytes, err := ReadAsset(filename)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
|
||||||
|
}
|
||||||
|
return loadSite(geositeBytes, list)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d standardLoader) LoadIP(filename, country string) ([]*router.CIDR, error) {
|
func (d standardLoader) LoadSiteByBytes(geositeBytes []byte, list string) ([]*router.Domain, error) {
|
||||||
return loadIP(filename, country)
|
return loadSite(geositeBytes, list)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d standardLoader) LoadIPByPath(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())
|
||||||
|
}
|
||||||
|
return loadIP(geoipBytes, country)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d standardLoader) LoadIPByBytes(geoipBytes []byte, country string) ([]*router.CIDR, error) {
|
||||||
|
return loadIP(geoipBytes, country)
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
package geodata
|
package geodata
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var geoLoaderName = "memconservative"
|
var geoLoaderName = "memconservative"
|
||||||
@ -21,20 +21,30 @@ func SetLoader(newLoader string) {
|
|||||||
geoLoaderName = newLoader
|
geoLoaderName = newLoader
|
||||||
}
|
}
|
||||||
|
|
||||||
func Verify(name string) bool {
|
func Verify(name string) error {
|
||||||
switch name {
|
switch name {
|
||||||
case C.GeositeName:
|
case C.GeositeName:
|
||||||
_, _, err := LoadGeoSiteMatcher("CN")
|
_, _, err := LoadGeoSiteMatcher("CN")
|
||||||
return err == nil
|
return err
|
||||||
case C.GeoipName:
|
case C.GeoipName:
|
||||||
_, _, err := LoadGeoIPMatcher("CN")
|
_, _, err := LoadGeoIPMatcher("CN")
|
||||||
return err == nil
|
return err
|
||||||
default:
|
default:
|
||||||
return false
|
return fmt.Errorf("not support name")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
||||||
|
if len(countryCode) == 0 {
|
||||||
|
return nil, 0, fmt.Errorf("country code could not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
not := false
|
||||||
|
if countryCode[0] == '!' {
|
||||||
|
not = true
|
||||||
|
countryCode = countryCode[1:]
|
||||||
|
}
|
||||||
|
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
@ -50,7 +60,7 @@ func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error)
|
|||||||
matcher, err := router.NewDomainMatcher(domains)
|
matcher, err := router.NewDomainMatcher(domains)
|
||||||
mph:minimal perfect hash algorithm
|
mph:minimal perfect hash algorithm
|
||||||
*/
|
*/
|
||||||
matcher, err := router.NewMphMatcherGroup(domains)
|
matcher, err := router.NewMphMatcherGroup(domains, not)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@ -59,12 +69,21 @@ func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
||||||
|
if len(country) == 0 {
|
||||||
|
return nil, 0, fmt.Errorf("country code could not be empty")
|
||||||
|
}
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
records, err := geoLoader.LoadGeoIP(strings.ReplaceAll(country, "!", ""))
|
not := false
|
||||||
|
if country[0] == '!' {
|
||||||
|
not = true
|
||||||
|
country = country[1:]
|
||||||
|
}
|
||||||
|
|
||||||
|
records, err := geoLoader.LoadGeoIP(country)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@ -72,7 +91,7 @@ func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
|||||||
geoIP := &router.GeoIP{
|
geoIP := &router.GeoIP{
|
||||||
CountryCode: country,
|
CountryCode: country,
|
||||||
Cidr: records,
|
Cidr: records,
|
||||||
ReverseMatch: strings.Contains(country, "!"),
|
ReverseMatch: not,
|
||||||
}
|
}
|
||||||
|
|
||||||
matcher, err := router.NewGeoIPMatcher(geoIP)
|
matcher, err := router.NewGeoIPMatcher(geoIP)
|
||||||
|
64
component/http/http.go
Normal file
64
component/http/http.go
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/Dreamacro/clash/component/tls"
|
||||||
|
"github.com/Dreamacro/clash/listener/inner"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
URL "net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
UA = "Clash"
|
||||||
|
)
|
||||||
|
|
||||||
|
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
||||||
|
method = strings.ToUpper(method)
|
||||||
|
urlRes, err := URL.Parse(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(method, urlRes.String(), body)
|
||||||
|
for k, v := range header {
|
||||||
|
for _, v := range v {
|
||||||
|
req.Header.Add(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := header["User-Agent"]; !ok {
|
||||||
|
req.Header.Set("User-Agent", UA)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if user := urlRes.User; user != nil {
|
||||||
|
password, _ := user.Password()
|
||||||
|
req.SetBasicAuth(user.Username(), password)
|
||||||
|
}
|
||||||
|
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
transport := &http.Transport{
|
||||||
|
// from http.DefaultTransport
|
||||||
|
MaxIdleConns: 100,
|
||||||
|
IdleConnTimeout: 30 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
conn := inner.HandleTcp(address, urlRes.Hostname())
|
||||||
|
return conn, nil
|
||||||
|
},
|
||||||
|
TLSClientConfig: tls.GetDefaultTLSConfig(),
|
||||||
|
}
|
||||||
|
|
||||||
|
client := http.Client{Transport: transport}
|
||||||
|
return client.Do(req)
|
||||||
|
|
||||||
|
}
|
@ -2,11 +2,7 @@ package process
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"runtime"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -20,7 +16,7 @@ const (
|
|||||||
UDP = "udp"
|
UDP = "udp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (string, error) {
|
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (int32, string, error) {
|
||||||
return findProcessName(network, srcIP, srcPort)
|
return findProcessName(network, srcIP, srcPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -31,52 +27,3 @@ func FindUid(network string, srcIP netip.Addr, srcPort int) (int32, error) {
|
|||||||
}
|
}
|
||||||
return uid, nil
|
return uid, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ShouldFindProcess(metadata *C.Metadata) bool {
|
|
||||||
if runtime.GOOS == "android" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if metadata.Process != "" || metadata.ProcessPath != "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for _, ip := range localIPs {
|
|
||||||
if ip == metadata.SrcIP {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func AppendLocalIPs(ip ...netip.Addr) {
|
|
||||||
localIPs = append(ip, localIPs...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getLocalIPs() []netip.Addr {
|
|
||||||
ips := []netip.Addr{netip.IPv4Unspecified(), netip.IPv6Unspecified()}
|
|
||||||
|
|
||||||
netInterfaces, err := net.Interfaces()
|
|
||||||
if err != nil {
|
|
||||||
ips = append(ips, netip.AddrFrom4([4]byte{127, 0, 0, 1}), nnip.IpToAddr(net.IPv6loopback))
|
|
||||||
return ips
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < len(netInterfaces); i++ {
|
|
||||||
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
|
|
||||||
adds, _ := netInterfaces[i].Addrs()
|
|
||||||
|
|
||||||
for _, address := range adds {
|
|
||||||
if ipNet, ok := address.(*net.IPNet); ok {
|
|
||||||
ips = append(ips, nnip.IpToAddr(ipNet.IP))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ips
|
|
||||||
}
|
|
||||||
|
|
||||||
var localIPs []netip.Addr
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
localIPs = getLocalIPs()
|
|
||||||
}
|
|
||||||
|
@ -3,11 +3,11 @@ package process
|
|||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
|
||||||
|
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -17,11 +17,27 @@ const (
|
|||||||
proccallnumpidinfo = 0x2
|
proccallnumpidinfo = 0x2
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var structSize = func() int {
|
||||||
|
value, _ := syscall.Sysctl("kern.osrelease")
|
||||||
|
major, _, _ := strings.Cut(value, ".")
|
||||||
|
n, _ := strconv.ParseInt(major, 10, 64)
|
||||||
|
switch true {
|
||||||
|
case n >= 22:
|
||||||
|
return 408
|
||||||
|
default:
|
||||||
|
// from darwin-xnu/bsd/netinet/in_pcblist.c:get_pcblist_n
|
||||||
|
// size/offset are round up (aligned) to 8 bytes in darwin
|
||||||
|
// rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) +
|
||||||
|
// 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n))
|
||||||
|
return 384
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||||
return 0, 0, ErrPlatformNotSupport
|
return 0, 0, ErrPlatformNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, port int) (string, error) {
|
func findProcessName(network string, ip netip.Addr, port int) (int32, string, error) {
|
||||||
var spath string
|
var spath string
|
||||||
switch network {
|
switch network {
|
||||||
case TCP:
|
case TCP:
|
||||||
@ -29,27 +45,24 @@ func findProcessName(network string, ip netip.Addr, port int) (string, error) {
|
|||||||
case UDP:
|
case UDP:
|
||||||
spath = "net.inet.udp.pcblist_n"
|
spath = "net.inet.udp.pcblist_n"
|
||||||
default:
|
default:
|
||||||
return "", ErrInvalidNetwork
|
return -1, "", ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
isIPv4 := ip.Is4()
|
isIPv4 := ip.Is4()
|
||||||
|
|
||||||
value, err := syscall.Sysctl(spath)
|
value, err := syscall.Sysctl(spath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return -1, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
buf := []byte(value)
|
buf := []byte(value)
|
||||||
|
itemSize := structSize
|
||||||
// from darwin-xnu/bsd/netinet/in_pcblist.c:get_pcblist_n
|
|
||||||
// size/offset are round up (aligned) to 8 bytes in darwin
|
|
||||||
// rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) +
|
|
||||||
// 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n))
|
|
||||||
itemSize := 384
|
|
||||||
if network == TCP {
|
if network == TCP {
|
||||||
// rup8(sizeof(xtcpcb_n))
|
// rup8(sizeof(xtcpcb_n))
|
||||||
itemSize += 208
|
itemSize += 208
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var fallbackUDPProcess string
|
||||||
// skip the first xinpgen(24 bytes) block
|
// skip the first xinpgen(24 bytes) block
|
||||||
for i := 24; i+itemSize <= len(buf); i += itemSize {
|
for i := 24; i+itemSize <= len(buf); i += itemSize {
|
||||||
// offset of xinpcb_n and xsocket_n
|
// offset of xinpcb_n and xsocket_n
|
||||||
@ -63,28 +76,40 @@ func findProcessName(network string, ip netip.Addr, port int) (string, error) {
|
|||||||
// xinpcb_n.inp_vflag
|
// xinpcb_n.inp_vflag
|
||||||
flag := buf[inp+44]
|
flag := buf[inp+44]
|
||||||
|
|
||||||
var srcIP netip.Addr
|
var (
|
||||||
|
srcIP netip.Addr
|
||||||
|
srcIsIPv4 bool
|
||||||
|
)
|
||||||
switch {
|
switch {
|
||||||
case flag&0x1 > 0 && isIPv4:
|
case flag&0x1 > 0 && isIPv4:
|
||||||
// ipv4
|
// ipv4
|
||||||
srcIP = nnip.IpToAddr(buf[inp+76 : inp+80])
|
srcIP, _ = netip.AddrFromSlice(buf[inp+76 : inp+80])
|
||||||
|
srcIsIPv4 = true
|
||||||
case flag&0x2 > 0 && !isIPv4:
|
case flag&0x2 > 0 && !isIPv4:
|
||||||
// ipv6
|
// ipv6
|
||||||
srcIP = nnip.IpToAddr(buf[inp+64 : inp+80])
|
srcIP, _ = netip.AddrFromSlice(buf[inp+64 : inp+80])
|
||||||
default:
|
default:
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip != srcIP && (network == TCP || !srcIP.IsUnspecified()) {
|
if ip == srcIP {
|
||||||
continue
|
// xsocket_n.so_last_pid
|
||||||
|
pid := readNativeUint32(buf[so+68 : so+72])
|
||||||
|
pp, err := getExecPathFromPID(pid)
|
||||||
|
return -1, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// xsocket_n.so_last_pid
|
// udp packet connection may be not equal with srcIP
|
||||||
pid := readNativeUint32(buf[so+68 : so+72])
|
if network == UDP && srcIP.IsUnspecified() && isIPv4 == srcIsIPv4 {
|
||||||
return getExecPathFromPID(pid)
|
fallbackUDPProcess, _ = getExecPathFromPID(readNativeUint32(buf[so+68 : so+72]))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", ErrNotFound
|
if network == UDP && fallbackUDPProcess != "" {
|
||||||
|
return -1, fallbackUDPProcess, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1, "", ErrNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
func getExecPathFromPID(pid uint32) (string, error) {
|
func getExecPathFromPID(pid uint32) (string, error) {
|
||||||
|
@ -25,7 +25,7 @@ func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32,
|
|||||||
return 0, 0, ErrPlatformNotSupport
|
return 0, 0, ErrPlatformNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
if err := initSearcher(); err != nil {
|
if err := initSearcher(); err != nil {
|
||||||
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
||||||
@ -35,7 +35,7 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (string, error)
|
|||||||
})
|
})
|
||||||
|
|
||||||
if defaultSearcher == nil {
|
if defaultSearcher == nil {
|
||||||
return "", ErrPlatformNotSupport
|
return -1, "", ErrPlatformNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
var spath string
|
var spath string
|
||||||
@ -46,21 +46,22 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (string, error)
|
|||||||
case UDP:
|
case UDP:
|
||||||
spath = "net.inet.udp.pcblist"
|
spath = "net.inet.udp.pcblist"
|
||||||
default:
|
default:
|
||||||
return "", ErrInvalidNetwork
|
return -1, "", ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
value, err := syscall.Sysctl(spath)
|
value, err := syscall.Sysctl(spath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return -1, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
buf := []byte(value)
|
buf := []byte(value)
|
||||||
pid, err := defaultSearcher.Search(buf, ip, uint16(srcPort), isTCP)
|
pid, err := defaultSearcher.Search(buf, ip, uint16(srcPort), isTCP)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return -1, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return getExecPathFromPID(pid)
|
pp, err := getExecPathFromPID(pid)
|
||||||
|
return -1, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func getExecPathFromPID(pid uint32) (string, error) {
|
func getExecPathFromPID(pid uint32) (string, error) {
|
||||||
|
@ -8,6 +8,8 @@ import (
|
|||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"unicode"
|
"unicode"
|
||||||
@ -32,12 +34,14 @@ const (
|
|||||||
pathProc = "/proc"
|
pathProc = "/proc"
|
||||||
)
|
)
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) {
|
||||||
inode, uid, err := resolveSocketByNetlink(network, ip, srcPort)
|
inode, uid, err := resolveSocketByNetlink(network, ip, srcPort)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return -1, "", err
|
||||||
}
|
}
|
||||||
return resolveProcessNameByProcSearch(inode, uid)
|
|
||||||
|
pp, err := resolveProcessNameByProcSearch(inode, uid)
|
||||||
|
return uid, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||||
@ -107,7 +111,7 @@ func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32,
|
|||||||
return 0, 0, fmt.Errorf("netlink message: NLMSG_ERROR")
|
return 0, 0, fmt.Errorf("netlink message: NLMSG_ERROR")
|
||||||
}
|
}
|
||||||
|
|
||||||
inode, uid := unpackSocketDiagResponse(&message)
|
inode, uid := unpackSocketDiagResponse(&messages[0])
|
||||||
if inode < 0 || uid < 0 {
|
if inode < 0 || uid < 0 {
|
||||||
return 0, 0, fmt.Errorf("invalid inode(%d) or uid(%d)", inode, uid)
|
return 0, 0, fmt.Errorf("invalid inode(%d) or uid(%d)", inode, uid)
|
||||||
}
|
}
|
||||||
@ -194,9 +198,19 @@ func resolveProcessNameByProcSearch(inode, uid int32) (string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if runtime.GOOS == "android" {
|
||||||
|
if bytes.Equal(buffer[:n], socket) {
|
||||||
|
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
if bytes.Equal(buffer[:n], socket) {
|
return splitCmdline(cmdline), nil
|
||||||
return os.Readlink(path.Join(processPath, "exe"))
|
}
|
||||||
|
} else {
|
||||||
|
if bytes.Equal(buffer[:n], socket) {
|
||||||
|
return os.Readlink(path.Join(processPath, "exe"))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -204,6 +218,19 @@ func resolveProcessNameByProcSearch(inode, uid int32) (string, error) {
|
|||||||
return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode)
|
return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func splitCmdline(cmdline []byte) string {
|
||||||
|
cmdline = bytes.Trim(cmdline, " ")
|
||||||
|
|
||||||
|
idx := bytes.IndexFunc(cmdline, func(r rune) bool {
|
||||||
|
return unicode.IsControl(r) || unicode.IsSpace(r)
|
||||||
|
})
|
||||||
|
|
||||||
|
if idx == -1 {
|
||||||
|
return filepath.Base(string(cmdline))
|
||||||
|
}
|
||||||
|
return filepath.Base(string(cmdline[:idx]))
|
||||||
|
}
|
||||||
|
|
||||||
func isPid(s string) bool {
|
func isPid(s string) bool {
|
||||||
return strings.IndexFunc(s, func(r rune) bool {
|
return strings.IndexFunc(s, func(r rune) bool {
|
||||||
return !unicode.IsDigit(r)
|
return !unicode.IsDigit(r)
|
||||||
|
@ -4,8 +4,8 @@ package process
|
|||||||
|
|
||||||
import "net/netip"
|
import "net/netip"
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) {
|
||||||
return "", ErrPlatformNotSupport
|
return -1, "", ErrPlatformNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||||
|
@ -62,7 +62,7 @@ func initWin32API() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
err := initWin32API()
|
err := initWin32API()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -86,21 +86,22 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (string, error)
|
|||||||
fn = getExUDPTable
|
fn = getExUDPTable
|
||||||
class = udpTablePid
|
class = udpTablePid
|
||||||
default:
|
default:
|
||||||
return "", ErrInvalidNetwork
|
return -1, "", ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
buf, err := getTransportTable(fn, family, class)
|
buf, err := getTransportTable(fn, family, class)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return -1, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
s := newSearcher(family == windows.AF_INET, network == TCP)
|
s := newSearcher(family == windows.AF_INET, network == TCP)
|
||||||
|
|
||||||
pid, err := s.Search(buf, ip, uint16(srcPort))
|
pid, err := s.Search(buf, ip, uint16(srcPort))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return -1, "", err
|
||||||
}
|
}
|
||||||
return getExecPathFromPID(pid)
|
pp, err := getExecPathFromPID(pid)
|
||||||
|
return -1, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
type searcher struct {
|
type searcher struct {
|
||||||
|
@ -41,7 +41,6 @@ type Resolver interface {
|
|||||||
ResolveIPv4(host string) (ip netip.Addr, err error)
|
ResolveIPv4(host string) (ip netip.Addr, err error)
|
||||||
ResolveIPv6(host string) (ip netip.Addr, err error)
|
ResolveIPv6(host string) (ip netip.Addr, err error)
|
||||||
ResolveAllIP(host string) (ip []netip.Addr, err error)
|
ResolveAllIP(host string) (ip []netip.Addr, err error)
|
||||||
ResolveAllIPPrimaryIPv4(host string) (ips []netip.Addr, err error)
|
|
||||||
ResolveAllIPv4(host string) (ips []netip.Addr, err error)
|
ResolveAllIPv4(host string) (ips []netip.Addr, err error)
|
||||||
ResolveAllIPv6(host string) (ips []netip.Addr, err error)
|
ResolveAllIPv6(host string) (ips []netip.Addr, err error)
|
||||||
}
|
}
|
||||||
@ -55,7 +54,7 @@ func ResolveIPv4WithResolver(host string, r Resolver) (netip.Addr, error) {
|
|||||||
if ips, err := ResolveAllIPv4WithResolver(host, r); err == nil {
|
if ips, err := ResolveAllIPv4WithResolver(host, r); err == nil {
|
||||||
return ips[rand.Intn(len(ips))], nil
|
return ips[rand.Intn(len(ips))], nil
|
||||||
} else {
|
} else {
|
||||||
return netip.Addr{}, nil
|
return netip.Addr{}, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,10 +73,10 @@ func ResolveIPv6WithResolver(host string, r Resolver) (netip.Addr, error) {
|
|||||||
|
|
||||||
// ResolveIPWithResolver same as ResolveIP, but with a resolver
|
// ResolveIPWithResolver same as ResolveIP, but with a resolver
|
||||||
func ResolveIPWithResolver(host string, r Resolver) (netip.Addr, error) {
|
func ResolveIPWithResolver(host string, r Resolver) (netip.Addr, error) {
|
||||||
if ips, err := ResolveAllIPPrimaryIPv4WithResolver(host, r); err == nil {
|
if ip, err := ResolveIPv4WithResolver(host, r); err == nil {
|
||||||
return ips[rand.Intn(len(ips))], nil
|
return ip, nil
|
||||||
} else {
|
} else {
|
||||||
return netip.Addr{}, err
|
return ResolveIPv6WithResolver(host, r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -89,7 +88,11 @@ func ResolveIP(host string) (netip.Addr, error) {
|
|||||||
// ResolveIPv4ProxyServerHost proxies server host only
|
// ResolveIPv4ProxyServerHost proxies server host only
|
||||||
func ResolveIPv4ProxyServerHost(host string) (netip.Addr, error) {
|
func ResolveIPv4ProxyServerHost(host string) (netip.Addr, error) {
|
||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
return ResolveIPv4WithResolver(host, ProxyServerHostResolver)
|
if ip, err := ResolveIPv4WithResolver(host, ProxyServerHostResolver); err != nil {
|
||||||
|
return ResolveIPv4(host)
|
||||||
|
} else {
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return ResolveIPv4(host)
|
return ResolveIPv4(host)
|
||||||
}
|
}
|
||||||
@ -97,7 +100,11 @@ func ResolveIPv4ProxyServerHost(host string) (netip.Addr, error) {
|
|||||||
// ResolveIPv6ProxyServerHost proxies server host only
|
// ResolveIPv6ProxyServerHost proxies server host only
|
||||||
func ResolveIPv6ProxyServerHost(host string) (netip.Addr, error) {
|
func ResolveIPv6ProxyServerHost(host string) (netip.Addr, error) {
|
||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
return ResolveIPv6WithResolver(host, ProxyServerHostResolver)
|
if ip, err := ResolveIPv6WithResolver(host, ProxyServerHostResolver); err != nil {
|
||||||
|
return ResolveIPv6(host)
|
||||||
|
} else {
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return ResolveIPv6(host)
|
return ResolveIPv6(host)
|
||||||
}
|
}
|
||||||
@ -105,7 +112,11 @@ func ResolveIPv6ProxyServerHost(host string) (netip.Addr, error) {
|
|||||||
// ResolveProxyServerHost proxies server host only
|
// ResolveProxyServerHost proxies server host only
|
||||||
func ResolveProxyServerHost(host string) (netip.Addr, error) {
|
func ResolveProxyServerHost(host string) (netip.Addr, error) {
|
||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
return ResolveIPWithResolver(host, ProxyServerHostResolver)
|
if ip, err := ResolveIPWithResolver(host, ProxyServerHostResolver); err != nil {
|
||||||
|
return ResolveIP(host)
|
||||||
|
} else {
|
||||||
|
return ip, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return ResolveIP(host)
|
return ResolveIP(host)
|
||||||
}
|
}
|
||||||
@ -145,7 +156,6 @@ func ResolveAllIPv6WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
|
|
||||||
return []netip.Addr{netip.AddrFrom16(*(*[16]byte)(ipAddrs[rand.Intn(len(ipAddrs))]))}, nil
|
return []netip.Addr{netip.AddrFrom16(*(*[16]byte)(ipAddrs[rand.Intn(len(ipAddrs))]))}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return []netip.Addr{}, ErrIPNotFound
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -158,7 +168,7 @@ func ResolveAllIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if ip.Is4() {
|
if ip.Is4() || ip.Is4In6() {
|
||||||
return []netip.Addr{ip}, nil
|
return []netip.Addr{ip}, nil
|
||||||
}
|
}
|
||||||
return []netip.Addr{}, ErrIPVersion
|
return []netip.Addr{}, ErrIPVersion
|
||||||
@ -185,7 +195,6 @@ func ResolveAllIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
|
|
||||||
return []netip.Addr{netip.AddrFrom4(*(*[4]byte)(ip))}, nil
|
return []netip.Addr{netip.AddrFrom4(*(*[4]byte)(ip))}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return []netip.Addr{}, ErrIPNotFound
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -194,6 +203,11 @@ func ResolveAllIPWithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
return []netip.Addr{node.Data}, nil
|
return []netip.Addr{node.Data}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err == nil {
|
||||||
|
return []netip.Addr{ip}, nil
|
||||||
|
}
|
||||||
|
|
||||||
if r != nil {
|
if r != nil {
|
||||||
if DisableIPv6 {
|
if DisableIPv6 {
|
||||||
return r.ResolveAllIPv4(host)
|
return r.ResolveAllIPv4(host)
|
||||||
@ -204,11 +218,6 @@ func ResolveAllIPWithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
return ResolveAllIPv4(host)
|
return ResolveAllIPv4(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
|
||||||
if err == nil {
|
|
||||||
return []netip.Addr{ip}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if DefaultResolver == nil {
|
if DefaultResolver == nil {
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -217,39 +226,6 @@ func ResolveAllIPWithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
|
|
||||||
return []netip.Addr{nnip.IpToAddr(ipAddr.IP)}, nil
|
return []netip.Addr{nnip.IpToAddr(ipAddr.IP)}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return []netip.Addr{}, ErrIPNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
func ResolveAllIPPrimaryIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
|
||||||
return []netip.Addr{node.Data}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if r != nil {
|
|
||||||
if DisableIPv6 {
|
|
||||||
return r.ResolveAllIPv4(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
return r.ResolveAllIPPrimaryIPv4(host)
|
|
||||||
} else if DisableIPv6 {
|
|
||||||
return ResolveAllIPv4(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
|
||||||
if err == nil {
|
|
||||||
return []netip.Addr{ip}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if DefaultResolver == nil {
|
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
|
||||||
if err != nil {
|
|
||||||
return []netip.Addr{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return []netip.Addr{nnip.IpToAddr(ipAddr.IP)}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return []netip.Addr{}, ErrIPNotFound
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -269,7 +245,6 @@ func ResolveAllIPv6ProxyServerHost(host string) ([]netip.Addr, error) {
|
|||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
return ResolveAllIPv6WithResolver(host, ProxyServerHostResolver)
|
return ResolveAllIPv6WithResolver(host, ProxyServerHostResolver)
|
||||||
}
|
}
|
||||||
|
|
||||||
return ResolveAllIPv6(host)
|
return ResolveAllIPv6(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -277,7 +252,6 @@ func ResolveAllIPv4ProxyServerHost(host string) ([]netip.Addr, error) {
|
|||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
return ResolveAllIPv4WithResolver(host, ProxyServerHostResolver)
|
return ResolveAllIPv4WithResolver(host, ProxyServerHostResolver)
|
||||||
}
|
}
|
||||||
|
|
||||||
return ResolveAllIPv4(host)
|
return ResolveAllIPv4(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -285,6 +259,5 @@ func ResolveAllIPProxyServerHost(host string) ([]netip.Addr, error) {
|
|||||||
if ProxyServerHostResolver != nil {
|
if ProxyServerHostResolver != nil {
|
||||||
return ResolveAllIPWithResolver(host, ProxyServerHostResolver)
|
return ResolveAllIPWithResolver(host, ProxyServerHostResolver)
|
||||||
}
|
}
|
||||||
|
|
||||||
return ResolveAllIP(host)
|
return ResolveAllIP(host)
|
||||||
}
|
}
|
||||||
|
213
component/resource/fetcher.go
Normal file
213
component/resource/fetcher.go
Normal file
@ -0,0 +1,213 @@
|
|||||||
|
package resource
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/md5"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
fileMode os.FileMode = 0o666
|
||||||
|
dirMode os.FileMode = 0o755
|
||||||
|
)
|
||||||
|
|
||||||
|
type Parser[V any] func([]byte) (V, error)
|
||||||
|
|
||||||
|
type Fetcher[V any] struct {
|
||||||
|
resourceType string
|
||||||
|
name string
|
||||||
|
vehicle types.Vehicle
|
||||||
|
UpdatedAt *time.Time
|
||||||
|
ticker *time.Ticker
|
||||||
|
done chan struct{}
|
||||||
|
hash [16]byte
|
||||||
|
parser Parser[V]
|
||||||
|
interval time.Duration
|
||||||
|
OnUpdate func(V)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher[V]) Name() string {
|
||||||
|
return f.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher[V]) VehicleType() types.VehicleType {
|
||||||
|
return f.vehicle.Type()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher[V]) Initial() (V, error) {
|
||||||
|
var (
|
||||||
|
buf []byte
|
||||||
|
err error
|
||||||
|
isLocal bool
|
||||||
|
forceUpdate bool
|
||||||
|
)
|
||||||
|
|
||||||
|
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
||||||
|
buf, err = os.ReadFile(f.vehicle.Path())
|
||||||
|
modTime := stat.ModTime()
|
||||||
|
f.UpdatedAt = &modTime
|
||||||
|
isLocal = true
|
||||||
|
if f.interval != 0 && modTime.Add(f.interval).Before(time.Now()) {
|
||||||
|
log.Infoln("[Provider] %s not updated for a long time, force refresh", f.Name())
|
||||||
|
forceUpdate = true
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
buf, err = f.vehicle.Read()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return getZero[V](), err
|
||||||
|
}
|
||||||
|
|
||||||
|
var contents V
|
||||||
|
if forceUpdate {
|
||||||
|
var forceBuf []byte
|
||||||
|
if forceBuf, err = f.vehicle.Read(); err == nil {
|
||||||
|
if contents, err = f.parser(forceBuf); err == nil {
|
||||||
|
isLocal = false
|
||||||
|
buf = forceBuf
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil || !forceUpdate {
|
||||||
|
contents, err = f.parser(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if !isLocal {
|
||||||
|
return getZero[V](), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse local file error, fallback to remote
|
||||||
|
buf, err = f.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return getZero[V](), err
|
||||||
|
}
|
||||||
|
|
||||||
|
contents, err = f.parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
return getZero[V](), err
|
||||||
|
}
|
||||||
|
|
||||||
|
isLocal = false
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.vehicle.Type() != types.File && !isLocal {
|
||||||
|
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||||
|
return getZero[V](), err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
f.hash = md5.Sum(buf)
|
||||||
|
|
||||||
|
// pull contents automatically
|
||||||
|
if f.ticker != nil {
|
||||||
|
go f.pullLoop()
|
||||||
|
}
|
||||||
|
|
||||||
|
return contents, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher[V]) Update() (V, bool, error) {
|
||||||
|
buf, err := f.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return getZero[V](), false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
hash := md5.Sum(buf)
|
||||||
|
if bytes.Equal(f.hash[:], hash[:]) {
|
||||||
|
f.UpdatedAt = &now
|
||||||
|
_ = os.Chtimes(f.vehicle.Path(), now, now)
|
||||||
|
return getZero[V](), true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
contents, err := f.parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
return getZero[V](), false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.vehicle.Type() != types.File {
|
||||||
|
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||||
|
return getZero[V](), false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
f.UpdatedAt = &now
|
||||||
|
f.hash = hash
|
||||||
|
|
||||||
|
return contents, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher[V]) Destroy() error {
|
||||||
|
if f.ticker != nil {
|
||||||
|
f.done <- struct{}{}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher[V]) pullLoop() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-f.ticker.C:
|
||||||
|
elm, same, err := f.Update()
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if same {
|
||||||
|
log.Debugln("[Provider] %s's content doesn't change", f.Name())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Infoln("[Provider] %s's content update", f.Name())
|
||||||
|
if f.OnUpdate != nil {
|
||||||
|
f.OnUpdate(elm)
|
||||||
|
}
|
||||||
|
case <-f.done:
|
||||||
|
f.ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func safeWrite(path string, buf []byte) error {
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
|
||||||
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
|
if err := os.MkdirAll(dir, dirMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return os.WriteFile(path, buf, fileMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
|
||||||
|
var ticker *time.Ticker
|
||||||
|
if interval != 0 {
|
||||||
|
ticker = time.NewTicker(interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Fetcher[V]{
|
||||||
|
name: name,
|
||||||
|
ticker: ticker,
|
||||||
|
vehicle: vehicle,
|
||||||
|
parser: parser,
|
||||||
|
done: make(chan struct{}, 1),
|
||||||
|
OnUpdate: onUpdate,
|
||||||
|
interval: interval,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getZero[V any]() V {
|
||||||
|
var result V
|
||||||
|
return result
|
||||||
|
}
|
@ -1,17 +1,13 @@
|
|||||||
package provider
|
package resource
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"github.com/Dreamacro/clash/listener/inner"
|
netHttp "github.com/Dreamacro/clash/component/http"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
netHttp "github.com/Dreamacro/clash/common/net"
|
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type FileVehicle struct {
|
type FileVehicle struct {
|
||||||
@ -50,52 +46,16 @@ func (h *HTTPVehicle) Path() string {
|
|||||||
func (h *HTTPVehicle) Read() ([]byte, error) {
|
func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
resp, err := netHttp.HttpRequest(ctx, h.url, http.MethodGet, nil, nil)
|
||||||
uri, err := url.Parse(h.url)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
|
||||||
req.Header.Set("User-Agent", netHttp.UA)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if user := uri.User; user != nil {
|
|
||||||
password, _ := user.Password()
|
|
||||||
req.SetBasicAuth(user.Username(), password)
|
|
||||||
}
|
|
||||||
|
|
||||||
req = req.WithContext(ctx)
|
|
||||||
|
|
||||||
transport := &http.Transport{
|
|
||||||
// from http.DefaultTransport
|
|
||||||
MaxIdleConns: 100,
|
|
||||||
IdleConnTimeout: 90 * time.Second,
|
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
|
||||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
conn := inner.HandleTcp(address, uri.Hostname())
|
|
||||||
return conn, nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
buf, err := io.ReadAll(resp.Body)
|
buf, err := io.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return buf, nil
|
return buf, nil
|
||||||
}
|
}
|
||||||
|
|
@ -2,46 +2,52 @@ package sniffer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/trie"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/sniffer"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrorUnsupportedSniffer = errors.New("unsupported sniffer")
|
ErrorUnsupportedSniffer = errors.New("unsupported sniffer")
|
||||||
ErrorSniffFailed = errors.New("all sniffer failed")
|
ErrorSniffFailed = errors.New("all sniffer failed")
|
||||||
|
ErrNoClue = errors.New("not enough information for making a decision")
|
||||||
)
|
)
|
||||||
|
|
||||||
var Dispatcher SnifferDispatcher
|
var Dispatcher *SnifferDispatcher
|
||||||
|
|
||||||
type (
|
type SnifferDispatcher struct {
|
||||||
SnifferDispatcher struct {
|
enable bool
|
||||||
enable bool
|
|
||||||
|
|
||||||
sniffers []C.Sniffer
|
sniffers []sniffer.Sniffer
|
||||||
|
|
||||||
foreDomain *trie.DomainTrie[bool]
|
forceDomain *trie.DomainTrie[bool]
|
||||||
skipSNI *trie.DomainTrie[bool]
|
skipSNI *trie.DomainTrie[bool]
|
||||||
portRanges *[]utils.Range[uint16]
|
portRanges *[]utils.Range[uint16]
|
||||||
}
|
skipList *cache.LruCache[string, uint8]
|
||||||
)
|
rwMux sync.RWMutex
|
||||||
|
|
||||||
|
forceDnsMapping bool
|
||||||
|
parsePureIp bool
|
||||||
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
||||||
bufConn, ok := conn.(*CN.BufferedConn)
|
bufConn, ok := conn.(*N.BufferedConn)
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if metadata.Host == "" || sd.foreDomain.Search(metadata.Host) != nil {
|
if (metadata.Host == "" && sd.parsePureIp) || sd.forceDomain.Search(metadata.Host) != nil || (metadata.DNSMode == C.DNSMapping && sd.forceDnsMapping) {
|
||||||
port, err := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, err := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Debugln("[Sniffer] Dst port is error")
|
log.Debugln("[Sniffer] Dst port is error")
|
||||||
@ -60,7 +66,17 @@ func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sd.rwMux.RLock()
|
||||||
|
dst := fmt.Sprintf("%s:%s", metadata.DstIP, metadata.DstPort)
|
||||||
|
if count, ok := sd.skipList.Get(dst); ok && count > 5 {
|
||||||
|
log.Debugln("[Sniffer] Skip sniffing[%s] due to multiple failures", dst)
|
||||||
|
defer sd.rwMux.RUnlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sd.rwMux.RUnlock()
|
||||||
|
|
||||||
if host, err := sd.sniffDomain(bufConn, metadata); err != nil {
|
if host, err := sd.sniffDomain(bufConn, metadata); err != nil {
|
||||||
|
sd.cacheSniffFailed(metadata)
|
||||||
log.Debugln("[Sniffer] All sniffing sniff failed with from [%s:%s] to [%s:%s]", metadata.SrcIP, metadata.SrcPort, metadata.String(), metadata.DstPort)
|
log.Debugln("[Sniffer] All sniffing sniff failed with from [%s:%s] to [%s:%s]", metadata.SrcIP, metadata.SrcPort, metadata.String(), metadata.DstPort)
|
||||||
return
|
return
|
||||||
} else {
|
} else {
|
||||||
@ -69,41 +85,56 @@ func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sd.rwMux.RLock()
|
||||||
|
sd.skipList.Delete(dst)
|
||||||
|
sd.rwMux.RUnlock()
|
||||||
|
|
||||||
sd.replaceDomain(metadata, host)
|
sd.replaceDomain(metadata, host)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string) {
|
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string) {
|
||||||
log.Debugln("[Sniffer] Sniff TCP [%s:%s]-->[%s:%s] success, replace domain [%s]-->[%s]",
|
dstIP := ""
|
||||||
metadata.SrcIP, metadata.SrcPort,
|
if metadata.DstIP.IsValid() {
|
||||||
metadata.DstIP, metadata.DstPort,
|
dstIP = metadata.DstIP.String()
|
||||||
metadata.Host, host)
|
}
|
||||||
|
originHost := metadata.Host
|
||||||
|
if originHost != host {
|
||||||
|
log.Infoln("[Sniffer] Sniff TCP [%s:%s]-->[%s:%s] success, replace domain [%s]-->[%s]",
|
||||||
|
metadata.SrcIP, metadata.SrcPort,
|
||||||
|
dstIP, metadata.DstPort,
|
||||||
|
metadata.Host, host)
|
||||||
|
} else {
|
||||||
|
log.Debugln("[Sniffer] Sniff TCP [%s:%s]-->[%s:%s] success, replace domain [%s]-->[%s]",
|
||||||
|
metadata.SrcIP, metadata.SrcPort,
|
||||||
|
dstIP, metadata.DstPort,
|
||||||
|
metadata.Host, host)
|
||||||
|
}
|
||||||
|
|
||||||
metadata.AddrType = C.AtypDomainName
|
metadata.AddrType = C.AtypDomainName
|
||||||
metadata.Host = host
|
metadata.Host = host
|
||||||
metadata.DNSMode = C.DNSMapping
|
metadata.DNSMode = C.DNSNormal
|
||||||
resolver.InsertHostByIP(metadata.DstIP, host)
|
|
||||||
metadata.DstIP = netip.Addr{}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) Enable() bool {
|
func (sd *SnifferDispatcher) Enable() bool {
|
||||||
return sd.enable
|
return sd.enable
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) sniffDomain(conn *CN.BufferedConn, metadata *C.Metadata) (string, error) {
|
func (sd *SnifferDispatcher) sniffDomain(conn *N.BufferedConn, metadata *C.Metadata) (string, error) {
|
||||||
for _, sniffer := range sd.sniffers {
|
for _, s := range sd.sniffers {
|
||||||
if sniffer.SupportNetwork() == C.TCP {
|
if s.SupportNetwork() == C.TCP {
|
||||||
conn.SetReadDeadline(time.Now().Add(3 * time.Second))
|
_ = conn.SetReadDeadline(time.Now().Add(1 * time.Second))
|
||||||
_, err := conn.Peek(1)
|
_, err := conn.Peek(1)
|
||||||
conn.SetReadDeadline(time.Time{})
|
_ = conn.SetReadDeadline(time.Time{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_, ok := err.(*net.OpError)
|
_, ok := err.(*net.OpError)
|
||||||
if ok {
|
if ok {
|
||||||
log.Errorln("[Sniffer] [%s] Maybe read timeout, Consider adding skip", metadata.DstIP.String())
|
sd.cacheSniffFailed(metadata)
|
||||||
conn.Close()
|
log.Errorln("[Sniffer] [%s] may not have any sent data, Consider adding skip", metadata.DstIP.String())
|
||||||
|
_ = conn.Close()
|
||||||
}
|
}
|
||||||
log.Errorln("[Sniffer] %v", err)
|
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,9 +145,15 @@ func (sd *SnifferDispatcher) sniffDomain(conn *CN.BufferedConn, metadata *C.Meta
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
host, err := sniffer.SniffTCP(bytes)
|
host, err := s.SniffTCP(bytes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Debugln("[Sniffer] [%s] Sniff data failed %s", sniffer.Protocol(), metadata.DstIP)
|
//log.Debugln("[Sniffer] [%s] Sniff data failed %s", s.Protocol(), metadata.DstIP)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = netip.ParseAddr(host)
|
||||||
|
if err == nil {
|
||||||
|
//log.Debugln("[Sniffer] [%s] Sniff data failed %s", s.Protocol(), metadata.DstIP)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -127,6 +164,17 @@ func (sd *SnifferDispatcher) sniffDomain(conn *CN.BufferedConn, metadata *C.Meta
|
|||||||
return "", ErrorSniffFailed
|
return "", ErrorSniffFailed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (sd *SnifferDispatcher) cacheSniffFailed(metadata *C.Metadata) {
|
||||||
|
sd.rwMux.Lock()
|
||||||
|
dst := fmt.Sprintf("%s:%s", metadata.DstIP, metadata.DstPort)
|
||||||
|
count, _ := sd.skipList.Get(dst)
|
||||||
|
if count <= 5 {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
sd.skipList.Set(dst, count)
|
||||||
|
sd.rwMux.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
func NewCloseSnifferDispatcher() (*SnifferDispatcher, error) {
|
func NewCloseSnifferDispatcher() (*SnifferDispatcher, error) {
|
||||||
dispatcher := SnifferDispatcher{
|
dispatcher := SnifferDispatcher{
|
||||||
enable: false,
|
enable: false,
|
||||||
@ -135,32 +183,38 @@ func NewCloseSnifferDispatcher() (*SnifferDispatcher, error) {
|
|||||||
return &dispatcher, nil
|
return &dispatcher, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSnifferDispatcher(needSniffer []C.SnifferType, forceDomain *trie.DomainTrie[bool],
|
func NewSnifferDispatcher(needSniffer []sniffer.Type, forceDomain *trie.DomainTrie[bool],
|
||||||
skipSNI *trie.DomainTrie[bool], ports *[]utils.Range[uint16]) (*SnifferDispatcher, error) {
|
skipSNI *trie.DomainTrie[bool], ports *[]utils.Range[uint16],
|
||||||
|
forceDnsMapping bool, parsePureIp bool) (*SnifferDispatcher, error) {
|
||||||
dispatcher := SnifferDispatcher{
|
dispatcher := SnifferDispatcher{
|
||||||
enable: true,
|
enable: true,
|
||||||
foreDomain: forceDomain,
|
forceDomain: forceDomain,
|
||||||
skipSNI: skipSNI,
|
skipSNI: skipSNI,
|
||||||
portRanges: ports,
|
portRanges: ports,
|
||||||
|
skipList: cache.NewLRUCache[string, uint8](cache.WithSize[string, uint8](128), cache.WithAge[string, uint8](600)),
|
||||||
|
forceDnsMapping: forceDnsMapping,
|
||||||
|
parsePureIp: parsePureIp,
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, snifferName := range needSniffer {
|
for _, snifferName := range needSniffer {
|
||||||
sniffer, err := NewSniffer(snifferName)
|
s, err := NewSniffer(snifferName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorln("Sniffer name[%s] is error", snifferName)
|
log.Errorln("Sniffer name[%s] is error", snifferName)
|
||||||
return &SnifferDispatcher{enable: false}, err
|
return &SnifferDispatcher{enable: false}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatcher.sniffers = append(dispatcher.sniffers, sniffer)
|
dispatcher.sniffers = append(dispatcher.sniffers, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &dispatcher, nil
|
return &dispatcher, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSniffer(name C.SnifferType) (C.Sniffer, error) {
|
func NewSniffer(name sniffer.Type) (sniffer.Sniffer, error) {
|
||||||
switch name {
|
switch name {
|
||||||
case C.TLS:
|
case sniffer.TLS:
|
||||||
return &TLSSniffer{}, nil
|
return &TLSSniffer{}, nil
|
||||||
|
case sniffer.HTTP:
|
||||||
|
return &HTTPSniffer{}, nil
|
||||||
default:
|
default:
|
||||||
return nil, ErrorUnsupportedSniffer
|
return nil, ErrorUnsupportedSniffer
|
||||||
}
|
}
|
||||||
|
121
component/sniffer/http_sniffer.go
Normal file
121
component/sniffer/http_sniffer.go
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
package sniffer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// refer to https://pkg.go.dev/net/http@master#pkg-constants
|
||||||
|
methods = [...]string{"get", "post", "head", "put", "delete", "options", "connect", "patch", "trace"}
|
||||||
|
errNotHTTPMethod = errors.New("not an HTTP method")
|
||||||
|
)
|
||||||
|
|
||||||
|
type version byte
|
||||||
|
|
||||||
|
const (
|
||||||
|
HTTP1 version = iota
|
||||||
|
HTTP2
|
||||||
|
)
|
||||||
|
|
||||||
|
type HTTPSniffer struct {
|
||||||
|
version version
|
||||||
|
host string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (http *HTTPSniffer) Protocol() string {
|
||||||
|
switch http.version {
|
||||||
|
case HTTP1:
|
||||||
|
return "http1"
|
||||||
|
case HTTP2:
|
||||||
|
return "http2"
|
||||||
|
default:
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (http *HTTPSniffer) SupportNetwork() C.NetWork {
|
||||||
|
return C.TCP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (http *HTTPSniffer) SniffTCP(bytes []byte) (string, error) {
|
||||||
|
domain, err := SniffHTTP(bytes)
|
||||||
|
if err == nil {
|
||||||
|
return *domain, nil
|
||||||
|
} else {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func beginWithHTTPMethod(b []byte) error {
|
||||||
|
for _, m := range &methods {
|
||||||
|
if len(b) >= len(m) && strings.EqualFold(string(b[:len(m)]), m) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(b) < len(m) {
|
||||||
|
return ErrNoClue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errNotHTTPMethod
|
||||||
|
}
|
||||||
|
|
||||||
|
func SniffHTTP(b []byte) (*string, error) {
|
||||||
|
if err := beginWithHTTPMethod(b); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = &HTTPSniffer{
|
||||||
|
version: HTTP1,
|
||||||
|
}
|
||||||
|
|
||||||
|
headers := bytes.Split(b, []byte{'\n'})
|
||||||
|
for i := 1; i < len(headers); i++ {
|
||||||
|
header := headers[i]
|
||||||
|
if len(header) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
parts := bytes.SplitN(header, []byte{':'}, 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
key := strings.ToLower(string(parts[0]))
|
||||||
|
if key == "host" {
|
||||||
|
rawHost := strings.ToLower(string(bytes.TrimSpace(parts[1])))
|
||||||
|
host, _, err := net.SplitHostPort(rawHost)
|
||||||
|
if err != nil {
|
||||||
|
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
|
||||||
|
return parseHost(rawHost)
|
||||||
|
} else {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if net.ParseIP(host) != nil {
|
||||||
|
return nil, fmt.Errorf("host is ip")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &host, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, ErrNoClue
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseHost(host string) (*string, error) {
|
||||||
|
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
|
||||||
|
if net.ParseIP(host[1:len(host)-1]) != nil {
|
||||||
|
return nil, fmt.Errorf("host is ip")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if net.ParseIP(host) != nil {
|
||||||
|
return nil, fmt.Errorf("host is ip")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &host, nil
|
||||||
|
}
|
3
component/sniffer/quic_sniffer.go
Normal file
3
component/sniffer/quic_sniffer.go
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package sniffer
|
||||||
|
|
||||||
|
//TODO
|
@ -11,7 +11,6 @@ import (
|
|||||||
var (
|
var (
|
||||||
errNotTLS = errors.New("not TLS header")
|
errNotTLS = errors.New("not TLS header")
|
||||||
errNotClientHello = errors.New("not client hello")
|
errNotClientHello = errors.New("not client hello")
|
||||||
ErrNoClue = errors.New("not enough information for making a decision")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type TLSSniffer struct {
|
type TLSSniffer struct {
|
||||||
|
140
component/tls/config.go
Normal file
140
component/tls/config.go
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
package tls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
xtls "github.com/xtls/go"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var globalFingerprints = make([][32]byte, 0, 0)
|
||||||
|
var mutex sync.Mutex
|
||||||
|
|
||||||
|
func verifyPeerCertificateAndFingerprints(fingerprints *[][32]byte, insecureSkipVerify bool) func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||||
|
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||||
|
if insecureSkipVerify {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var preErr error
|
||||||
|
for i := range rawCerts {
|
||||||
|
rawCert := rawCerts[i]
|
||||||
|
cert, err := x509.ParseCertificate(rawCert)
|
||||||
|
if err == nil {
|
||||||
|
opts := x509.VerifyOptions{
|
||||||
|
CurrentTime: time.Now(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := cert.Verify(opts); err == nil {
|
||||||
|
return nil
|
||||||
|
} else {
|
||||||
|
fingerprint := sha256.Sum256(cert.Raw)
|
||||||
|
for _, fp := range *fingerprints {
|
||||||
|
if bytes.Equal(fingerprint[:], fp[:]) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
preErr = err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return preErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddCertFingerprint(fingerprint string) error {
|
||||||
|
fpByte, err2 := convertFingerprint(fingerprint)
|
||||||
|
if err2 != nil {
|
||||||
|
return err2
|
||||||
|
}
|
||||||
|
|
||||||
|
mutex.Lock()
|
||||||
|
globalFingerprints = append(globalFingerprints, *fpByte)
|
||||||
|
mutex.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func convertFingerprint(fingerprint string) (*[32]byte, error) {
|
||||||
|
fpByte, err := hex.DecodeString(fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(fpByte) != 32 {
|
||||||
|
return nil, fmt.Errorf("fingerprint string length error,need sha25 fingerprint")
|
||||||
|
}
|
||||||
|
return (*[32]byte)(fpByte), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetDefaultTLSConfig() *tls.Config {
|
||||||
|
return GetGlobalFingerprintTLCConfig(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSpecifiedFingerprintTLSConfig specified fingerprint
|
||||||
|
func GetSpecifiedFingerprintTLSConfig(tlsConfig *tls.Config, fingerprint string) (*tls.Config, error) {
|
||||||
|
if fingerprintBytes, err := convertFingerprint(fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
if tlsConfig == nil {
|
||||||
|
return &tls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, false),
|
||||||
|
}, nil
|
||||||
|
} else {
|
||||||
|
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, tlsConfig.InsecureSkipVerify)
|
||||||
|
tlsConfig.InsecureSkipVerify = true
|
||||||
|
return tlsConfig, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetGlobalFingerprintTLCConfig(tlsConfig *tls.Config) *tls.Config {
|
||||||
|
if tlsConfig == nil {
|
||||||
|
return &tls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&globalFingerprints, false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&globalFingerprints, tlsConfig.InsecureSkipVerify)
|
||||||
|
tlsConfig.InsecureSkipVerify = true
|
||||||
|
return tlsConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSpecifiedFingerprintXTLSConfig specified fingerprint
|
||||||
|
func GetSpecifiedFingerprintXTLSConfig(tlsConfig *xtls.Config, fingerprint string) (*xtls.Config, error) {
|
||||||
|
if fingerprintBytes, err := convertFingerprint(fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
if tlsConfig == nil {
|
||||||
|
return &xtls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, false),
|
||||||
|
}, nil
|
||||||
|
} else {
|
||||||
|
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, tlsConfig.InsecureSkipVerify)
|
||||||
|
tlsConfig.InsecureSkipVerify = true
|
||||||
|
return tlsConfig, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetGlobalFingerprintXTLCConfig(tlsConfig *xtls.Config) *xtls.Config {
|
||||||
|
if tlsConfig == nil {
|
||||||
|
return &xtls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&globalFingerprints, false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&globalFingerprints, tlsConfig.InsecureSkipVerify)
|
||||||
|
tlsConfig.InsecureSkipVerify = true
|
||||||
|
return tlsConfig
|
||||||
|
}
|
484
config/config.go
484
config/config.go
@ -2,9 +2,9 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"container/list"
|
"container/list"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/listener/tun/ipstack/commons"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
@ -15,8 +15,8 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
R "github.com/Dreamacro/clash/rule"
|
R "github.com/Dreamacro/clash/rules"
|
||||||
RP "github.com/Dreamacro/clash/rule/provider"
|
RP "github.com/Dreamacro/clash/rules/provider"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
@ -30,11 +30,13 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/trie"
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
providerTypes "github.com/Dreamacro/clash/constant/provider"
|
providerTypes "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"github.com/Dreamacro/clash/constant/sniffer"
|
||||||
|
snifferTypes "github.com/Dreamacro/clash/constant/sniffer"
|
||||||
"github.com/Dreamacro/clash/dns"
|
"github.com/Dreamacro/clash/dns"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
T "github.com/Dreamacro/clash/tunnel"
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
// General config
|
// General config
|
||||||
@ -45,11 +47,15 @@ type General struct {
|
|||||||
UnifiedDelay bool
|
UnifiedDelay bool
|
||||||
LogLevel log.LogLevel `json:"log-level"`
|
LogLevel log.LogLevel `json:"log-level"`
|
||||||
IPv6 bool `json:"ipv6"`
|
IPv6 bool `json:"ipv6"`
|
||||||
Interface string `json:"-"`
|
Interface string `json:"interface-name"`
|
||||||
RoutingMark int `json:"-"`
|
RoutingMark int `json:"-"`
|
||||||
GeodataMode bool `json:"geodata-mode"`
|
GeodataMode bool `json:"geodata-mode"`
|
||||||
GeodataLoader string `json:"geodata-loader"`
|
GeodataLoader string `json:"geodata-loader"`
|
||||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||||
|
EnableProcess bool `json:"enable-process"`
|
||||||
|
Tun Tun `json:"tun"`
|
||||||
|
Sniffing bool `json:"sniffing"`
|
||||||
|
EBpf EBpf `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inbound config
|
// Inbound config
|
||||||
@ -62,6 +68,7 @@ type Inbound struct {
|
|||||||
Authentication []string `json:"authentication"`
|
Authentication []string `json:"authentication"`
|
||||||
AllowLan bool `json:"allow-lan"`
|
AllowLan bool `json:"allow-lan"`
|
||||||
BindAddress string `json:"bind-address"`
|
BindAddress string `json:"bind-address"`
|
||||||
|
InboundTfo bool `json:"inbound-tfo"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Controller config
|
// Controller config
|
||||||
@ -74,6 +81,7 @@ type Controller struct {
|
|||||||
// DNS config
|
// DNS config
|
||||||
type DNS struct {
|
type DNS struct {
|
||||||
Enable bool `yaml:"enable"`
|
Enable bool `yaml:"enable"`
|
||||||
|
PreferH3 bool `yaml:"prefer-h3"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
NameServer []dns.NameServer `yaml:"nameserver"`
|
NameServer []dns.NameServer `yaml:"nameserver"`
|
||||||
Fallback []dns.NameServer `yaml:"fallback"`
|
Fallback []dns.NameServer `yaml:"fallback"`
|
||||||
@ -96,12 +104,6 @@ type FallbackFilter struct {
|
|||||||
GeoSite []*router.DomainMatcher `yaml:"geosite"`
|
GeoSite []*router.DomainMatcher `yaml:"geosite"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
|
||||||
GroupsList = list.New()
|
|
||||||
ProxiesList = list.New()
|
|
||||||
ParsingProxiesCallback func(groupsList *list.List, proxiesList *list.List)
|
|
||||||
)
|
|
||||||
|
|
||||||
// Profile config
|
// Profile config
|
||||||
type Profile struct {
|
type Profile struct {
|
||||||
StoreSelected bool `yaml:"store-selected"`
|
StoreSelected bool `yaml:"store-selected"`
|
||||||
@ -116,6 +118,73 @@ type Tun struct {
|
|||||||
DNSHijack []netip.AddrPort `yaml:"dns-hijack" json:"dns-hijack"`
|
DNSHijack []netip.AddrPort `yaml:"dns-hijack" json:"dns-hijack"`
|
||||||
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
||||||
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
|
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
|
||||||
|
RedirectToTun []string `yaml:"-" json:"-"`
|
||||||
|
|
||||||
|
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
|
||||||
|
Inet4Address []ListenPrefix `yaml:"inet4-address" json:"inet4_address,omitempty"`
|
||||||
|
Inet6Address []ListenPrefix `yaml:"inet6-address" json:"inet6_address,omitempty"`
|
||||||
|
StrictRoute bool `yaml:"strict-route" json:"strict_route,omitempty"`
|
||||||
|
Inet4RouteAddress []ListenPrefix `yaml:"inet4_route_address" json:"inet4_route_address,omitempty"`
|
||||||
|
Inet6RouteAddress []ListenPrefix `yaml:"inet6_route_address" json:"inet6_route_address,omitempty"`
|
||||||
|
IncludeUID []uint32 `yaml:"include-uid" json:"include_uid,omitempty"`
|
||||||
|
IncludeUIDRange []string `yaml:"include-uid-range" json:"include_uid_range,omitempty"`
|
||||||
|
ExcludeUID []uint32 `yaml:"exclude-uid" json:"exclude_uid,omitempty"`
|
||||||
|
ExcludeUIDRange []string `yaml:"exclude-uid-range" json:"exclude_uid_range,omitempty"`
|
||||||
|
IncludeAndroidUser []int `yaml:"include-android-user" json:"include_android_user,omitempty"`
|
||||||
|
IncludePackage []string `yaml:"include-package" json:"include_package,omitempty"`
|
||||||
|
ExcludePackage []string `yaml:"exclude-package" json:"exclude_package,omitempty"`
|
||||||
|
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint_independent_nat,omitempty"`
|
||||||
|
UDPTimeout int64 `yaml:"udp-timeout" json:"udp_timeout,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListenPrefix netip.Prefix
|
||||||
|
|
||||||
|
func (p ListenPrefix) MarshalJSON() ([]byte, error) {
|
||||||
|
prefix := netip.Prefix(p)
|
||||||
|
if !prefix.IsValid() {
|
||||||
|
return json.Marshal(nil)
|
||||||
|
}
|
||||||
|
return json.Marshal(prefix.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p ListenPrefix) MarshalYAML() (interface{}, error) {
|
||||||
|
prefix := netip.Prefix(p)
|
||||||
|
if !prefix.IsValid() {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return prefix.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *ListenPrefix) UnmarshalJSON(bytes []byte) error {
|
||||||
|
var value string
|
||||||
|
err := json.Unmarshal(bytes, &value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
prefix, err := netip.ParsePrefix(value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*p = ListenPrefix(prefix)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *ListenPrefix) UnmarshalYAML(node *yaml.Node) error {
|
||||||
|
var value string
|
||||||
|
err := node.Decode(&value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
prefix, err := netip.ParsePrefix(value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*p = ListenPrefix(prefix)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p ListenPrefix) Build() netip.Prefix {
|
||||||
|
return netip.Prefix(p)
|
||||||
}
|
}
|
||||||
|
|
||||||
// IPTables config
|
// IPTables config
|
||||||
@ -126,17 +195,20 @@ type IPTables struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Sniffer struct {
|
type Sniffer struct {
|
||||||
Enable bool
|
Enable bool
|
||||||
Force bool
|
Sniffers []sniffer.Type
|
||||||
Sniffers []C.SnifferType
|
Reverses *trie.DomainTrie[bool]
|
||||||
Reverses *trie.DomainTrie[bool]
|
ForceDomain *trie.DomainTrie[bool]
|
||||||
ForceDomain *trie.DomainTrie[bool]
|
SkipDomain *trie.DomainTrie[bool]
|
||||||
SkipSNI *trie.DomainTrie[bool]
|
Ports *[]utils.Range[uint16]
|
||||||
Ports *[]utils.Range[uint16]
|
ForceDnsMapping bool
|
||||||
|
ParsePureIp bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Experimental config
|
// Experimental config
|
||||||
type Experimental struct{}
|
type Experimental struct {
|
||||||
|
Fingerprints []string `yaml:"fingerprints"`
|
||||||
|
}
|
||||||
|
|
||||||
// Config is clash config manager
|
// Config is clash config manager
|
||||||
type Config struct {
|
type Config struct {
|
||||||
@ -148,6 +220,7 @@ type Config struct {
|
|||||||
Hosts *trie.DomainTrie[netip.Addr]
|
Hosts *trie.DomainTrie[netip.Addr]
|
||||||
Profile *Profile
|
Profile *Profile
|
||||||
Rules []C.Rule
|
Rules []C.Rule
|
||||||
|
SubRules *map[string][]C.Rule
|
||||||
Users []auth.AuthUser
|
Users []auth.AuthUser
|
||||||
Proxies map[string]C.Proxy
|
Proxies map[string]C.Proxy
|
||||||
Providers map[string]providerTypes.ProxyProvider
|
Providers map[string]providerTypes.ProxyProvider
|
||||||
@ -157,6 +230,7 @@ type Config struct {
|
|||||||
|
|
||||||
type RawDNS struct {
|
type RawDNS struct {
|
||||||
Enable bool `yaml:"enable"`
|
Enable bool `yaml:"enable"`
|
||||||
|
PreferH3 bool `yaml:"prefer-h3"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
UseHosts bool `yaml:"use-hosts"`
|
UseHosts bool `yaml:"use-hosts"`
|
||||||
NameServer []string `yaml:"nameserver"`
|
NameServer []string `yaml:"nameserver"`
|
||||||
@ -186,6 +260,23 @@ type RawTun struct {
|
|||||||
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
|
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
|
||||||
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
||||||
AutoDetectInterface bool `yaml:"auto-detect-interface"`
|
AutoDetectInterface bool `yaml:"auto-detect-interface"`
|
||||||
|
RedirectToTun []string `yaml:"-" json:"-"`
|
||||||
|
|
||||||
|
MTU uint32 `yaml:"mtu" json:"mtu,omitempty"`
|
||||||
|
//Inet4Address []ListenPrefix `yaml:"inet4-address" json:"inet4_address,omitempty"`
|
||||||
|
Inet6Address []ListenPrefix `yaml:"inet6-address" json:"inet6_address,omitempty"`
|
||||||
|
StrictRoute bool `yaml:"strict-route" json:"strict_route,omitempty"`
|
||||||
|
Inet4RouteAddress []ListenPrefix `yaml:"inet4_route_address" json:"inet4_route_address,omitempty"`
|
||||||
|
Inet6RouteAddress []ListenPrefix `yaml:"inet6_route_address" json:"inet6_route_address,omitempty"`
|
||||||
|
IncludeUID []uint32 `yaml:"include-uid" json:"include_uid,omitempty"`
|
||||||
|
IncludeUIDRange []string `yaml:"include-uid-range" json:"include_uid_range,omitempty"`
|
||||||
|
ExcludeUID []uint32 `yaml:"exclude-uid" json:"exclude_uid,omitempty"`
|
||||||
|
ExcludeUIDRange []string `yaml:"exclude-uid-range" json:"exclude_uid_range,omitempty"`
|
||||||
|
IncludeAndroidUser []int `yaml:"include-android-user" json:"include_android_user,omitempty"`
|
||||||
|
IncludePackage []string `yaml:"include-package" json:"include_package,omitempty"`
|
||||||
|
ExcludePackage []string `yaml:"exclude-package" json:"exclude_package,omitempty"`
|
||||||
|
EndpointIndependentNat bool `yaml:"endpoint-independent-nat" json:"endpoint_independent_nat,omitempty"`
|
||||||
|
UDPTimeout int64 `yaml:"udp-timeout" json:"udp_timeout,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawConfig struct {
|
type RawConfig struct {
|
||||||
@ -194,6 +285,7 @@ type RawConfig struct {
|
|||||||
RedirPort int `yaml:"redir-port"`
|
RedirPort int `yaml:"redir-port"`
|
||||||
TProxyPort int `yaml:"tproxy-port"`
|
TProxyPort int `yaml:"tproxy-port"`
|
||||||
MixedPort int `yaml:"mixed-port"`
|
MixedPort int `yaml:"mixed-port"`
|
||||||
|
InboundTfo bool `yaml:"inbound-tfo"`
|
||||||
Authentication []string `yaml:"authentication"`
|
Authentication []string `yaml:"authentication"`
|
||||||
AllowLan bool `yaml:"allow-lan"`
|
AllowLan bool `yaml:"allow-lan"`
|
||||||
BindAddress string `yaml:"bind-address"`
|
BindAddress string `yaml:"bind-address"`
|
||||||
@ -209,31 +301,53 @@ type RawConfig struct {
|
|||||||
GeodataMode bool `yaml:"geodata-mode"`
|
GeodataMode bool `yaml:"geodata-mode"`
|
||||||
GeodataLoader string `yaml:"geodata-loader"`
|
GeodataLoader string `yaml:"geodata-loader"`
|
||||||
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
||||||
|
EnableProcess bool `yaml:"enable-process" json:"enable-process"`
|
||||||
|
|
||||||
Sniffer SnifferRaw `yaml:"sniffer"`
|
Sniffer RawSniffer `yaml:"sniffer"`
|
||||||
ProxyProvider map[string]map[string]any `yaml:"proxy-providers"`
|
ProxyProvider map[string]map[string]any `yaml:"proxy-providers"`
|
||||||
RuleProvider map[string]map[string]any `yaml:"rule-providers"`
|
RuleProvider map[string]map[string]any `yaml:"rule-providers"`
|
||||||
Hosts map[string]string `yaml:"hosts"`
|
Hosts map[string]string `yaml:"hosts"`
|
||||||
DNS RawDNS `yaml:"dns"`
|
DNS RawDNS `yaml:"dns"`
|
||||||
Tun RawTun `yaml:"tun"`
|
Tun RawTun `yaml:"tun"`
|
||||||
|
EBpf EBpf `yaml:"ebpf"`
|
||||||
IPTables IPTables `yaml:"iptables"`
|
IPTables IPTables `yaml:"iptables"`
|
||||||
Experimental Experimental `yaml:"experimental"`
|
Experimental Experimental `yaml:"experimental"`
|
||||||
Profile Profile `yaml:"profile"`
|
Profile Profile `yaml:"profile"`
|
||||||
|
GeoXUrl RawGeoXUrl `yaml:"geox-url"`
|
||||||
Proxy []map[string]any `yaml:"proxies"`
|
Proxy []map[string]any `yaml:"proxies"`
|
||||||
ProxyGroup []map[string]any `yaml:"proxy-groups"`
|
ProxyGroup []map[string]any `yaml:"proxy-groups"`
|
||||||
Rule []string `yaml:"rules"`
|
Rule []string `yaml:"rules"`
|
||||||
|
SubRules map[string][]string `yaml:"sub-rules"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SnifferRaw struct {
|
type RawGeoXUrl struct {
|
||||||
Enable bool `yaml:"enable" json:"enable"`
|
GeoIp string `yaml:"geoip" json:"geoip"`
|
||||||
Sniffing []string `yaml:"sniffing" json:"sniffing"`
|
Mmdb string `yaml:"mmdb" json:"mmdb"`
|
||||||
Force bool `yaml:"force" json:"force"`
|
GeoSite string `yaml:"geosite" json:"geosite"`
|
||||||
Reverse []string `yaml:"reverses" json:"reverses"`
|
|
||||||
ForceDomain []string `yaml:"force-domain" json:"force-domain"`
|
|
||||||
SkipSNI []string `yaml:"skip-sni" json:"skip-sni"`
|
|
||||||
Ports []string `yaml:"port-whitelist" json:"port-whitelist"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RawSniffer struct {
|
||||||
|
Enable bool `yaml:"enable" json:"enable"`
|
||||||
|
Sniffing []string `yaml:"sniffing" json:"sniffing"`
|
||||||
|
ForceDomain []string `yaml:"force-domain" json:"force-domain"`
|
||||||
|
SkipDomain []string `yaml:"skip-domain" json:"skip-domain"`
|
||||||
|
Ports []string `yaml:"port-whitelist" json:"port-whitelist"`
|
||||||
|
ForceDnsMapping bool `yaml:"force-dns-mapping" json:"force-dns-mapping"`
|
||||||
|
ParsePureIp bool `yaml:"parse-pure-ip" json:"parse-pure-ip"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EBpf config
|
||||||
|
type EBpf struct {
|
||||||
|
RedirectToTun []string `yaml:"redirect-to-tun" json:"redirect-to-tun"`
|
||||||
|
AutoRedir []string `yaml:"auto-redir" json:"auto-redir"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
GroupsList = list.New()
|
||||||
|
ProxiesList = list.New()
|
||||||
|
ParsingProxiesCallback func(groupsList *list.List, proxiesList *list.List)
|
||||||
|
)
|
||||||
|
|
||||||
// Parse config
|
// Parse config
|
||||||
func Parse(buf []byte) (*Config, error) {
|
func Parse(buf []byte) (*Config, error) {
|
||||||
rawCfg, err := UnmarshalRawConfig(buf)
|
rawCfg, err := UnmarshalRawConfig(buf)
|
||||||
@ -249,6 +363,7 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
rawCfg := &RawConfig{
|
rawCfg := &RawConfig{
|
||||||
AllowLan: false,
|
AllowLan: false,
|
||||||
BindAddress: "*",
|
BindAddress: "*",
|
||||||
|
IPv6: true,
|
||||||
Mode: T.Rule,
|
Mode: T.Rule,
|
||||||
GeodataMode: C.GeodataMode,
|
GeodataMode: C.GeodataMode,
|
||||||
GeodataLoader: "memconservative",
|
GeodataLoader: "memconservative",
|
||||||
@ -260,13 +375,19 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
Proxy: []map[string]any{},
|
Proxy: []map[string]any{},
|
||||||
ProxyGroup: []map[string]any{},
|
ProxyGroup: []map[string]any{},
|
||||||
TCPConcurrent: false,
|
TCPConcurrent: false,
|
||||||
|
EnableProcess: false,
|
||||||
Tun: RawTun{
|
Tun: RawTun{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
Device: "",
|
Device: "",
|
||||||
AutoDetectInterface: true,
|
|
||||||
Stack: C.TunGvisor,
|
Stack: C.TunGvisor,
|
||||||
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
|
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
|
||||||
AutoRoute: true,
|
AutoRoute: true,
|
||||||
|
AutoDetectInterface: true,
|
||||||
|
Inet6Address: []ListenPrefix{ListenPrefix(netip.MustParsePrefix("fdfe:dcba:9876::1/126"))},
|
||||||
|
},
|
||||||
|
EBpf: EBpf{
|
||||||
|
RedirectToTun: []string{},
|
||||||
|
AutoRedir: []string{},
|
||||||
},
|
},
|
||||||
IPTables: IPTables{
|
IPTables: IPTables{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
@ -275,6 +396,7 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
},
|
},
|
||||||
DNS: RawDNS{
|
DNS: RawDNS{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
|
IPv6: false,
|
||||||
UseHosts: true,
|
UseHosts: true,
|
||||||
EnhancedMode: C.DNSMapping,
|
EnhancedMode: C.DNSMapping,
|
||||||
FakeIPRange: "198.18.0.1/16",
|
FakeIPRange: "198.18.0.1/16",
|
||||||
@ -300,18 +422,23 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
"www.msftconnecttest.com",
|
"www.msftconnecttest.com",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Sniffer: SnifferRaw{
|
Sniffer: RawSniffer{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
Force: false,
|
Sniffing: []string{},
|
||||||
Sniffing: []string{},
|
ForceDomain: []string{},
|
||||||
Reverse: []string{},
|
SkipDomain: []string{},
|
||||||
ForceDomain: []string{},
|
Ports: []string{},
|
||||||
SkipSNI: []string{},
|
ForceDnsMapping: true,
|
||||||
Ports: []string{},
|
ParsePureIp: true,
|
||||||
},
|
},
|
||||||
Profile: Profile{
|
Profile: Profile{
|
||||||
StoreSelected: true,
|
StoreSelected: true,
|
||||||
},
|
},
|
||||||
|
GeoXUrl: RawGeoXUrl{
|
||||||
|
GeoIp: "https://ghproxy.com/https://raw.githubusercontent.com/Loyalsoldier/v2ray-rules-dat/release/geoip.dat",
|
||||||
|
Mmdb: "https://ghproxy.com/https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb",
|
||||||
|
GeoSite: "https://ghproxy.com/https://raw.githubusercontent.com/Loyalsoldier/v2ray-rules-dat/release/geosite.dat",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := yaml.Unmarshal(buf, rawCfg); err != nil {
|
if err := yaml.Unmarshal(buf, rawCfg); err != nil {
|
||||||
@ -335,12 +462,6 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.General = general
|
config.General = general
|
||||||
|
|
||||||
tunCfg, err := parseTun(rawCfg.Tun, config.General)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
config.Tun = tunCfg
|
|
||||||
|
|
||||||
dialer.DefaultInterface.Store(config.General.Interface)
|
dialer.DefaultInterface.Store(config.General.Interface)
|
||||||
|
|
||||||
proxies, providers, err := parseProxies(rawCfg)
|
proxies, providers, err := parseProxies(rawCfg)
|
||||||
@ -350,12 +471,18 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
config.Proxies = proxies
|
config.Proxies = proxies
|
||||||
config.Providers = providers
|
config.Providers = providers
|
||||||
|
|
||||||
rules, ruleProviders, err := parseRules(rawCfg, proxies)
|
subRules, ruleProviders, err := parseSubRules(rawCfg, proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.SubRules = subRules
|
||||||
|
config.RuleProviders = ruleProviders
|
||||||
|
|
||||||
|
rules, err := parseRules(rawCfg, proxies, subRules)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config.Rules = rules
|
config.Rules = rules
|
||||||
config.RuleProviders = ruleProviders
|
|
||||||
|
|
||||||
hosts, err := parseHosts(rawCfg)
|
hosts, err := parseHosts(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -369,6 +496,12 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.DNS = dnsCfg
|
config.DNS = dnsCfg
|
||||||
|
|
||||||
|
tunCfg, err := parseTun(rawCfg.Tun, config.General, dnsCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.Tun = tunCfg
|
||||||
|
|
||||||
config.Users = parseAuthentication(rawCfg.Authentication)
|
config.Users = parseAuthentication(rawCfg.Authentication)
|
||||||
|
|
||||||
config.Sniffer, err = parseSniffer(rawCfg.Sniffer)
|
config.Sniffer, err = parseSniffer(rawCfg.Sniffer)
|
||||||
@ -392,7 +525,7 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
return nil, fmt.Errorf("external-ui: %s not exist", externalUI)
|
return nil, fmt.Errorf("external-ui: %s not exist", externalUI)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
cfg.Tun.RedirectToTun = cfg.EBpf.RedirectToTun
|
||||||
return &General{
|
return &General{
|
||||||
Inbound: Inbound{
|
Inbound: Inbound{
|
||||||
Port: cfg.Port,
|
Port: cfg.Port,
|
||||||
@ -402,6 +535,7 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
MixedPort: cfg.MixedPort,
|
MixedPort: cfg.MixedPort,
|
||||||
AllowLan: cfg.AllowLan,
|
AllowLan: cfg.AllowLan,
|
||||||
BindAddress: cfg.BindAddress,
|
BindAddress: cfg.BindAddress,
|
||||||
|
InboundTfo: cfg.InboundTfo,
|
||||||
},
|
},
|
||||||
Controller: Controller{
|
Controller: Controller{
|
||||||
ExternalController: cfg.ExternalController,
|
ExternalController: cfg.ExternalController,
|
||||||
@ -417,6 +551,8 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
GeodataMode: cfg.GeodataMode,
|
GeodataMode: cfg.GeodataMode,
|
||||||
GeodataLoader: cfg.GeodataLoader,
|
GeodataLoader: cfg.GeodataLoader,
|
||||||
TCPConcurrent: cfg.TCPConcurrent,
|
TCPConcurrent: cfg.TCPConcurrent,
|
||||||
|
EnableProcess: cfg.EnableProcess,
|
||||||
|
EBpf: cfg.EBpf,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -428,8 +564,8 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
providersConfig := cfg.ProxyProvider
|
providersConfig := cfg.ProxyProvider
|
||||||
|
|
||||||
var proxyList []string
|
var proxyList []string
|
||||||
_proxiesList := list.New()
|
proxiesList := list.New()
|
||||||
_groupsList := list.New()
|
groupsList := list.New()
|
||||||
|
|
||||||
proxies["DIRECT"] = adapter.NewProxy(outbound.NewDirect())
|
proxies["DIRECT"] = adapter.NewProxy(outbound.NewDirect())
|
||||||
proxies["REJECT"] = adapter.NewProxy(outbound.NewReject())
|
proxies["REJECT"] = adapter.NewProxy(outbound.NewReject())
|
||||||
@ -449,7 +585,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
}
|
}
|
||||||
proxies[proxy.Name()] = proxy
|
proxies[proxy.Name()] = proxy
|
||||||
proxyList = append(proxyList, proxy.Name())
|
proxyList = append(proxyList, proxy.Name())
|
||||||
_proxiesList.PushBack(mapping)
|
proxiesList.PushBack(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
// keep the original order of ProxyGroups in config file
|
// keep the original order of ProxyGroups in config file
|
||||||
@ -459,7 +595,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
return nil, nil, fmt.Errorf("proxy group %d: missing name", idx)
|
return nil, nil, fmt.Errorf("proxy group %d: missing name", idx)
|
||||||
}
|
}
|
||||||
proxyList = append(proxyList, groupName)
|
proxyList = append(proxyList, groupName)
|
||||||
_groupsList.PushBack(mapping)
|
groupsList.PushBack(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if any loop exists and sort the ProxyGroups
|
// check if any loop exists and sort the ProxyGroups
|
||||||
@ -514,8 +650,8 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
[]providerTypes.ProxyProvider{pd},
|
[]providerTypes.ProxyProvider{pd},
|
||||||
)
|
)
|
||||||
proxies["GLOBAL"] = adapter.NewProxy(global)
|
proxies["GLOBAL"] = adapter.NewProxy(global)
|
||||||
ProxiesList = _proxiesList
|
ProxiesList = proxiesList
|
||||||
GroupsList = _groupsList
|
GroupsList = groupsList
|
||||||
if ParsingProxiesCallback != nil {
|
if ParsingProxiesCallback != nil {
|
||||||
// refresh tray menu
|
// refresh tray menu
|
||||||
go ParsingProxiesCallback(GroupsList, ProxiesList)
|
go ParsingProxiesCallback(GroupsList, ProxiesList)
|
||||||
@ -523,12 +659,13 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
return proxies, providersMap, nil
|
return proxies, providersMap, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, map[string]providerTypes.RuleProvider, error) {
|
func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy) (subRules *map[string][]C.Rule, ruleProviders map[string]providerTypes.RuleProvider, err error) {
|
||||||
ruleProviders := map[string]providerTypes.RuleProvider{}
|
ruleProviders = map[string]providerTypes.RuleProvider{}
|
||||||
|
subRules = &map[string][]C.Rule{}
|
||||||
log.Infoln("Geodata Loader mode: %s", geodata.LoaderName())
|
log.Infoln("Geodata Loader mode: %s", geodata.LoaderName())
|
||||||
// parse rule provider
|
// parse rule provider
|
||||||
for name, mapping := range cfg.RuleProvider {
|
for name, mapping := range cfg.RuleProvider {
|
||||||
rp, err := RP.ParseRuleProvider(name, mapping)
|
rp, err := RP.ParseRuleProvider(name, mapping, R.ParseRule)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
@ -537,9 +674,104 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, map[strin
|
|||||||
RP.SetRuleProvider(rp)
|
RP.SetRuleProvider(rp)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for name, rawRules := range cfg.SubRules {
|
||||||
|
var rules []C.Rule
|
||||||
|
for idx, line := range rawRules {
|
||||||
|
rawRule := trimArr(strings.Split(line, ","))
|
||||||
|
var (
|
||||||
|
payload string
|
||||||
|
target string
|
||||||
|
params []string
|
||||||
|
ruleName = strings.ToUpper(rawRule[0])
|
||||||
|
)
|
||||||
|
|
||||||
|
l := len(rawRule)
|
||||||
|
|
||||||
|
if ruleName == "NOT" || ruleName == "OR" || ruleName == "AND" || ruleName == "SUB-RULE" {
|
||||||
|
target = rawRule[l-1]
|
||||||
|
payload = strings.Join(rawRule[1:l-1], ",")
|
||||||
|
} else {
|
||||||
|
if l < 2 {
|
||||||
|
return nil, nil, fmt.Errorf("sub-rules[%d] [%s] error: format invalid", idx, line)
|
||||||
|
}
|
||||||
|
if l < 4 {
|
||||||
|
rawRule = append(rawRule, make([]string, 4-l)...)
|
||||||
|
}
|
||||||
|
if ruleName == "MATCH" {
|
||||||
|
l = 2
|
||||||
|
}
|
||||||
|
if l >= 3 {
|
||||||
|
l = 3
|
||||||
|
payload = rawRule[1]
|
||||||
|
}
|
||||||
|
target = rawRule[l-1]
|
||||||
|
params = rawRule[l:]
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := proxies[target]; !ok && ruleName != "SUB-RULE" {
|
||||||
|
return nil, nil, fmt.Errorf("sub-rules[%d:%s] [%s] error: proxy [%s] not found", idx, name, line, target)
|
||||||
|
}
|
||||||
|
|
||||||
|
params = trimArr(params)
|
||||||
|
parsed, parseErr := R.ParseRule(ruleName, payload, target, params, subRules)
|
||||||
|
if parseErr != nil {
|
||||||
|
return nil, nil, fmt.Errorf("sub-rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
rules = append(rules, parsed)
|
||||||
|
}
|
||||||
|
(*subRules)[name] = rules
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = verifySubRule(subRules); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifySubRule(subRules *map[string][]C.Rule) error {
|
||||||
|
for name := range *subRules {
|
||||||
|
err := verifySubRuleCircularReferences(name, subRules, []string{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifySubRuleCircularReferences(n string, subRules *map[string][]C.Rule, arr []string) error {
|
||||||
|
isInArray := func(v string, array []string) bool {
|
||||||
|
for _, c := range array {
|
||||||
|
if v == c {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
arr = append(arr, n)
|
||||||
|
for i, rule := range (*subRules)[n] {
|
||||||
|
if rule.RuleType() == C.SubRules {
|
||||||
|
if _, ok := (*subRules)[rule.Adapter()]; !ok {
|
||||||
|
return fmt.Errorf("sub-rule[%d:%s] error: [%s] not found", i, n, rule.Adapter())
|
||||||
|
}
|
||||||
|
if isInArray(rule.Adapter(), arr) {
|
||||||
|
arr = append(arr, rule.Adapter())
|
||||||
|
return fmt.Errorf("sub-rule error: circular references [%s]", strings.Join(arr, "->"))
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := verifySubRuleCircularReferences(rule.Adapter(), subRules, arr); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseRules(cfg *RawConfig, proxies map[string]C.Proxy, subRules *map[string][]C.Rule) ([]C.Rule, error) {
|
||||||
var rules []C.Rule
|
var rules []C.Rule
|
||||||
rulesConfig := cfg.Rule
|
rulesConfig := cfg.Rule
|
||||||
mode := cfg.Mode
|
|
||||||
|
|
||||||
// parse rules
|
// parse rules
|
||||||
for idx, line := range rulesConfig {
|
for idx, line := range rulesConfig {
|
||||||
@ -551,18 +783,14 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, map[strin
|
|||||||
ruleName = strings.ToUpper(rule[0])
|
ruleName = strings.ToUpper(rule[0])
|
||||||
)
|
)
|
||||||
|
|
||||||
if mode == T.Script && ruleName != "GEOSITE" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
l := len(rule)
|
l := len(rule)
|
||||||
|
|
||||||
if ruleName == "NOT" || ruleName == "OR" || ruleName == "AND" {
|
if ruleName == "NOT" || ruleName == "OR" || ruleName == "AND" || ruleName == "SUB-RULE" {
|
||||||
target = rule[l-1]
|
target = rule[l-1]
|
||||||
payload = strings.Join(rule[1:l-1], ",")
|
payload = strings.Join(rule[1:l-1], ",")
|
||||||
} else {
|
} else {
|
||||||
if l < 2 {
|
if l < 2 {
|
||||||
return nil, nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line)
|
return nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line)
|
||||||
}
|
}
|
||||||
if l < 4 {
|
if l < 4 {
|
||||||
rule = append(rule, make([]string, 4-l)...)
|
rule = append(rule, make([]string, 4-l)...)
|
||||||
@ -577,22 +805,18 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, map[strin
|
|||||||
target = rule[l-1]
|
target = rule[l-1]
|
||||||
params = rule[l:]
|
params = rule[l:]
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := proxies[target]; !ok {
|
if _, ok := proxies[target]; !ok {
|
||||||
return nil, nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
|
if ruleName != "SUB-RULE" {
|
||||||
|
return nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
|
||||||
|
} else if _, ok = (*subRules)[target]; !ok {
|
||||||
|
return nil, fmt.Errorf("rules[%d] [%s] error: sub-rule [%s] not found", idx, line, target)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
params = trimArr(params)
|
params = trimArr(params)
|
||||||
|
parsed, parseErr := R.ParseRule(ruleName, payload, target, params, subRules)
|
||||||
if ruleName == "GEOSITE" {
|
|
||||||
if err := initGeoSite(); err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("can't initial GeoSite: %s", err)
|
|
||||||
}
|
|
||||||
initMode = false
|
|
||||||
}
|
|
||||||
parsed, parseErr := R.ParseRule(ruleName, payload, target, params)
|
|
||||||
if parseErr != nil {
|
if parseErr != nil {
|
||||||
return nil, nil, fmt.Errorf("rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
return nil, fmt.Errorf("rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
rules = append(rules, parsed)
|
rules = append(rules, parsed)
|
||||||
@ -600,7 +824,7 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, map[strin
|
|||||||
|
|
||||||
runtime.GC()
|
runtime.GC()
|
||||||
|
|
||||||
return rules, ruleProviders, nil
|
return rules, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseHosts(cfg *RawConfig) (*trie.DomainTrie[netip.Addr], error) {
|
func parseHosts(cfg *RawConfig) (*trie.DomainTrie[netip.Addr], error) {
|
||||||
@ -654,7 +878,8 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
var addr, dnsNetType string
|
var addr, dnsNetType, proxyAdapter string
|
||||||
|
params := map[string]string{}
|
||||||
switch u.Scheme {
|
switch u.Scheme {
|
||||||
case "udp":
|
case "udp":
|
||||||
addr, err = hostWithDefaultPort(u.Host, "53")
|
addr, err = hostWithDefaultPort(u.Host, "53")
|
||||||
@ -669,11 +894,25 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
clearURL := url.URL{Scheme: "https", Host: u.Host, Path: u.Path}
|
clearURL := url.URL{Scheme: "https", Host: u.Host, Path: u.Path}
|
||||||
addr = clearURL.String()
|
addr = clearURL.String()
|
||||||
dnsNetType = "https" // DNS over HTTPS
|
dnsNetType = "https" // DNS over HTTPS
|
||||||
|
if len(u.Fragment) != 0 {
|
||||||
|
for _, s := range strings.Split(u.Fragment, "&") {
|
||||||
|
arr := strings.Split(s, "=")
|
||||||
|
if len(arr) == 0 {
|
||||||
|
continue
|
||||||
|
} else if len(arr) == 1 {
|
||||||
|
proxyAdapter = arr[0]
|
||||||
|
} else if len(arr) == 2 {
|
||||||
|
params[arr[0]] = arr[1]
|
||||||
|
} else {
|
||||||
|
params[arr[0]] = strings.Join(arr[1:], "=")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
case "dhcp":
|
case "dhcp":
|
||||||
addr = u.Host
|
addr = u.Host
|
||||||
dnsNetType = "dhcp" // UDP from DHCP
|
dnsNetType = "dhcp" // UDP from DHCP
|
||||||
case "quic":
|
case "quic":
|
||||||
addr, err = hostWithDefaultPort(u.Host, "784")
|
addr, err = hostWithDefaultPort(u.Host, "853")
|
||||||
dnsNetType = "quic" // DNS over QUIC
|
dnsNetType = "quic" // DNS over QUIC
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
||||||
@ -688,8 +927,9 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
dns.NameServer{
|
dns.NameServer{
|
||||||
Net: dnsNetType,
|
Net: dnsNetType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
ProxyAdapter: u.Fragment,
|
ProxyAdapter: proxyAdapter,
|
||||||
Interface: dialer.DefaultInterface,
|
Interface: dialer.DefaultInterface,
|
||||||
|
Params: params,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -730,7 +970,7 @@ func parseFallbackIPCIDR(ips []string) ([]*netip.Prefix, error) {
|
|||||||
func parseFallbackGeoSite(countries []string, rules []C.Rule) ([]*router.DomainMatcher, error) {
|
func parseFallbackGeoSite(countries []string, rules []C.Rule) ([]*router.DomainMatcher, error) {
|
||||||
var sites []*router.DomainMatcher
|
var sites []*router.DomainMatcher
|
||||||
if len(countries) > 0 {
|
if len(countries) > 0 {
|
||||||
if err := initGeoSite(); err != nil {
|
if err := geodata.InitGeoSite(); err != nil {
|
||||||
return nil, fmt.Errorf("can't initial GeoSite: %s", err)
|
return nil, fmt.Errorf("can't initial GeoSite: %s", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -771,6 +1011,7 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[netip.Addr], rules []C.R
|
|||||||
dnsCfg := &DNS{
|
dnsCfg := &DNS{
|
||||||
Enable: cfg.Enable,
|
Enable: cfg.Enable,
|
||||||
Listen: cfg.Listen,
|
Listen: cfg.Listen,
|
||||||
|
PreferH3: cfg.PreferH3,
|
||||||
IPv6: cfg.IPv6,
|
IPv6: cfg.IPv6,
|
||||||
EnhancedMode: cfg.EnhancedMode,
|
EnhancedMode: cfg.EnhancedMode,
|
||||||
FallbackFilter: FallbackFilter{
|
FallbackFilter: FallbackFilter{
|
||||||
@ -806,8 +1047,10 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[netip.Addr], rules []C.R
|
|||||||
host, _, err := net.SplitHostPort(ns.Addr)
|
host, _, err := net.SplitHostPort(ns.Addr)
|
||||||
if err != nil || net.ParseIP(host) == nil {
|
if err != nil || net.ParseIP(host) == nil {
|
||||||
u, err := url.Parse(ns.Addr)
|
u, err := url.Parse(ns.Addr)
|
||||||
if err != nil || net.ParseIP(u.Host) == nil {
|
if err == nil && net.ParseIP(u.Host) == nil {
|
||||||
return nil, errors.New("default nameserver should be pure IP")
|
if ip, _, err := net.SplitHostPort(u.Host); err != nil || net.ParseIP(ip) == nil {
|
||||||
|
return nil, errors.New("default nameserver should be pure IP")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -883,18 +1126,7 @@ func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
|||||||
return users
|
return users
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseTun(rawTun RawTun, general *General) (*Tun, error) {
|
func parseTun(rawTun RawTun, general *General, dnsCfg *DNS) (*Tun, error) {
|
||||||
if rawTun.Enable && rawTun.AutoDetectInterface {
|
|
||||||
autoDetectInterfaceName, err := commons.GetAutoDetectInterface()
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("Can not find auto detect interface.[%s]", err)
|
|
||||||
} else {
|
|
||||||
log.Warnln("Auto detect interface: %s", autoDetectInterfaceName)
|
|
||||||
}
|
|
||||||
|
|
||||||
general.Interface = autoDetectInterfaceName
|
|
||||||
}
|
|
||||||
|
|
||||||
var dnsHijack []netip.AddrPort
|
var dnsHijack []netip.AddrPort
|
||||||
|
|
||||||
for _, d := range rawTun.DNSHijack {
|
for _, d := range rawTun.DNSHijack {
|
||||||
@ -910,6 +1142,14 @@ func parseTun(rawTun RawTun, general *General) (*Tun, error) {
|
|||||||
dnsHijack = append(dnsHijack, addrPort)
|
dnsHijack = append(dnsHijack, addrPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var tunAddressPrefix netip.Prefix
|
||||||
|
if dnsCfg.FakeIPRange != nil {
|
||||||
|
tunAddressPrefix = *dnsCfg.FakeIPRange.IPNet()
|
||||||
|
} else {
|
||||||
|
tunAddressPrefix = netip.MustParsePrefix("198.18.0.1/16")
|
||||||
|
}
|
||||||
|
tunAddressPrefix = netip.PrefixFrom(tunAddressPrefix.Addr(), 30)
|
||||||
|
|
||||||
return &Tun{
|
return &Tun{
|
||||||
Enable: rawTun.Enable,
|
Enable: rawTun.Enable,
|
||||||
Device: rawTun.Device,
|
Device: rawTun.Device,
|
||||||
@ -917,18 +1157,37 @@ func parseTun(rawTun RawTun, general *General) (*Tun, error) {
|
|||||||
DNSHijack: dnsHijack,
|
DNSHijack: dnsHijack,
|
||||||
AutoRoute: rawTun.AutoRoute,
|
AutoRoute: rawTun.AutoRoute,
|
||||||
AutoDetectInterface: rawTun.AutoDetectInterface,
|
AutoDetectInterface: rawTun.AutoDetectInterface,
|
||||||
|
RedirectToTun: rawTun.RedirectToTun,
|
||||||
|
|
||||||
|
MTU: rawTun.MTU,
|
||||||
|
Inet4Address: []ListenPrefix{ListenPrefix(tunAddressPrefix)},
|
||||||
|
Inet6Address: rawTun.Inet6Address,
|
||||||
|
StrictRoute: rawTun.StrictRoute,
|
||||||
|
Inet4RouteAddress: rawTun.Inet4RouteAddress,
|
||||||
|
Inet6RouteAddress: rawTun.Inet6RouteAddress,
|
||||||
|
IncludeUID: rawTun.IncludeUID,
|
||||||
|
IncludeUIDRange: rawTun.IncludeUIDRange,
|
||||||
|
ExcludeUID: rawTun.ExcludeUID,
|
||||||
|
ExcludeUIDRange: rawTun.ExcludeUIDRange,
|
||||||
|
IncludeAndroidUser: rawTun.IncludeAndroidUser,
|
||||||
|
IncludePackage: rawTun.IncludePackage,
|
||||||
|
ExcludePackage: rawTun.ExcludePackage,
|
||||||
|
EndpointIndependentNat: rawTun.EndpointIndependentNat,
|
||||||
|
UDPTimeout: rawTun.UDPTimeout,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseSniffer(snifferRaw SnifferRaw) (*Sniffer, error) {
|
func parseSniffer(snifferRaw RawSniffer) (*Sniffer, error) {
|
||||||
sniffer := &Sniffer{
|
sniffer := &Sniffer{
|
||||||
Enable: snifferRaw.Enable,
|
Enable: snifferRaw.Enable,
|
||||||
Force: snifferRaw.Force,
|
ForceDnsMapping: snifferRaw.ForceDnsMapping,
|
||||||
|
ParsePureIp: snifferRaw.ParsePureIp,
|
||||||
}
|
}
|
||||||
|
|
||||||
var ports []utils.Range[uint16]
|
var ports []utils.Range[uint16]
|
||||||
if len(snifferRaw.Ports) == 0 {
|
if len(snifferRaw.Ports) == 0 {
|
||||||
ports = append(ports, *utils.NewRange[uint16](0, 65535))
|
ports = append(ports, *utils.NewRange[uint16](80, 80))
|
||||||
|
ports = append(ports, *utils.NewRange[uint16](443, 443))
|
||||||
} else {
|
} else {
|
||||||
for _, portRange := range snifferRaw.Ports {
|
for _, portRange := range snifferRaw.Ports {
|
||||||
portRaws := strings.Split(portRange, "-")
|
portRaws := strings.Split(portRange, "-")
|
||||||
@ -954,11 +1213,11 @@ func parseSniffer(snifferRaw SnifferRaw) (*Sniffer, error) {
|
|||||||
|
|
||||||
sniffer.Ports = &ports
|
sniffer.Ports = &ports
|
||||||
|
|
||||||
loadSniffer := make(map[C.SnifferType]struct{})
|
loadSniffer := make(map[snifferTypes.Type]struct{})
|
||||||
|
|
||||||
for _, snifferName := range snifferRaw.Sniffing {
|
for _, snifferName := range snifferRaw.Sniffing {
|
||||||
find := false
|
find := false
|
||||||
for _, snifferType := range C.SnifferList {
|
for _, snifferType := range snifferTypes.List {
|
||||||
if snifferType.String() == strings.ToUpper(snifferName) {
|
if snifferType.String() == strings.ToUpper(snifferName) {
|
||||||
find = true
|
find = true
|
||||||
loadSniffer[snifferType] = struct{}{}
|
loadSniffer[snifferType] = struct{}{}
|
||||||
@ -973,7 +1232,6 @@ func parseSniffer(snifferRaw SnifferRaw) (*Sniffer, error) {
|
|||||||
for st := range loadSniffer {
|
for st := range loadSniffer {
|
||||||
sniffer.Sniffers = append(sniffer.Sniffers, st)
|
sniffer.Sniffers = append(sniffer.Sniffers, st)
|
||||||
}
|
}
|
||||||
|
|
||||||
sniffer.ForceDomain = trie.New[bool]()
|
sniffer.ForceDomain = trie.New[bool]()
|
||||||
for _, domain := range snifferRaw.ForceDomain {
|
for _, domain := range snifferRaw.ForceDomain {
|
||||||
err := sniffer.ForceDomain.Insert(domain, true)
|
err := sniffer.ForceDomain.Insert(domain, true)
|
||||||
@ -982,35 +1240,13 @@ func parseSniffer(snifferRaw SnifferRaw) (*Sniffer, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sniffer.SkipSNI = trie.New[bool]()
|
sniffer.SkipDomain = trie.New[bool]()
|
||||||
for _, domain := range snifferRaw.SkipSNI {
|
for _, domain := range snifferRaw.SkipDomain {
|
||||||
err := sniffer.SkipSNI.Insert(domain, true)
|
err := sniffer.SkipDomain.Insert(domain, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("error domian[%s] in force-domain, error:%v", domain, err)
|
return nil, fmt.Errorf("error domian[%s] in force-domain, error:%v", domain, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compatibility, remove it when release
|
|
||||||
if strings.Contains(C.Version, "alpha") || strings.Contains(C.Version, "develop") || strings.Contains(C.Version, "1.10.0") {
|
|
||||||
log.Warnln("Sniffer param force and reverses deprecated, will be removed in the release version, see https://github.com/MetaCubeX/Clash.Meta/commit/48a01adb7a4f38974b9d9639f931d0d245aebf28")
|
|
||||||
if snifferRaw.Force {
|
|
||||||
// match all domain
|
|
||||||
sniffer.ForceDomain.Insert("+", true)
|
|
||||||
for _, domain := range snifferRaw.Reverse {
|
|
||||||
err := sniffer.SkipSNI.Insert(domain, true)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("error domian[%s], error:%v", domain, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for _, domain := range snifferRaw.Reverse {
|
|
||||||
err := sniffer.ForceDomain.Insert(domain, true)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("error domian[%s], error:%v", domain, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return sniffer, nil
|
return sniffer, nil
|
||||||
}
|
}
|
||||||
|
@ -12,10 +12,8 @@ import (
|
|||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var initMode = true
|
|
||||||
|
|
||||||
func downloadMMDB(path string) (err error) {
|
func downloadMMDB(path string) (err error) {
|
||||||
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/geoip/release/Country.mmdb")
|
resp, err := http.Get(C.MmdbUrl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -32,7 +30,7 @@ func downloadMMDB(path string) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func downloadGeoIP(path string) (err error) {
|
func downloadGeoIP(path string) (err error) {
|
||||||
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/v2ray-rules-dat/release/geoip.dat")
|
resp, err := http.Get(C.GeoIpUrl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -48,45 +46,6 @@ func downloadGeoIP(path string) (err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadGeoSite(path string) (err error) {
|
|
||||||
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/v2ray-rules-dat/release/geosite.dat")
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
_, err = io.Copy(f, resp.Body)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func initGeoSite() error {
|
|
||||||
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
|
||||||
log.Infoln("Can't find GeoSite.dat, start download")
|
|
||||||
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
log.Infoln("Download GeoSite.dat finish")
|
|
||||||
}
|
|
||||||
if initMode {
|
|
||||||
if !geodata.Verify(C.GeositeName) {
|
|
||||||
log.Warnln("GeoSite.dat invalid, remove and download")
|
|
||||||
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
|
||||||
return fmt.Errorf("can't remove invalid GeoSite.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func initGeoIP() error {
|
func initGeoIP() error {
|
||||||
if C.GeodataMode {
|
if C.GeodataMode {
|
||||||
if _, err := os.Stat(C.Path.GeoIP()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.GeoIP()); os.IsNotExist(err) {
|
||||||
@ -97,8 +56,8 @@ func initGeoIP() error {
|
|||||||
log.Infoln("Download GeoIP.dat finish")
|
log.Infoln("Download GeoIP.dat finish")
|
||||||
}
|
}
|
||||||
|
|
||||||
if !geodata.Verify(C.GeoipName) {
|
if err := geodata.Verify(C.GeoipName); err != nil {
|
||||||
log.Warnln("GeoIP.dat invalid, remove and download")
|
log.Warnln("GeoIP.dat invalid, remove and download: %s", err)
|
||||||
if err := os.Remove(C.Path.GeoIP()); err != nil {
|
if err := os.Remove(C.Path.GeoIP()); err != nil {
|
||||||
return fmt.Errorf("can't remove invalid GeoIP.dat: %s", err.Error())
|
return fmt.Errorf("can't remove invalid GeoIP.dat: %s", err.Error())
|
||||||
}
|
}
|
||||||
@ -159,6 +118,9 @@ func Init(dir string) error {
|
|||||||
if !C.GeodataMode {
|
if !C.GeodataMode {
|
||||||
C.GeodataMode = rawCfg.GeodataMode
|
C.GeodataMode = rawCfg.GeodataMode
|
||||||
}
|
}
|
||||||
|
C.GeoIpUrl = rawCfg.GeoXUrl.GeoIp
|
||||||
|
C.GeoSiteUrl = rawCfg.GeoXUrl.GeoSite
|
||||||
|
C.MmdbUrl = rawCfg.GeoXUrl.Mmdb
|
||||||
// initial GeoIP
|
// initial GeoIP
|
||||||
if err := initGeoIP(); err != nil {
|
if err := initGeoIP(); err != nil {
|
||||||
return fmt.Errorf("can't initial GeoIP: %w", err)
|
return fmt.Errorf("can't initial GeoIP: %w", err)
|
||||||
|
81
config/updateGeo.go
Normal file
81
config/updateGeo.go
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/geodata"
|
||||||
|
_ "github.com/Dreamacro/clash/component/geodata/standard"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/oschwald/geoip2-golang"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
func UpdateGeoDatabases() error {
|
||||||
|
defer runtime.GC()
|
||||||
|
geoLoader, err := geodata.GetGeoDataLoader("standard")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if C.GeodataMode {
|
||||||
|
data, err := downloadForBytes(C.GeoIpUrl)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoIP database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = geoLoader.LoadIPByBytes(data, "cn"); err != nil {
|
||||||
|
return fmt.Errorf("invalid GeoIP database file: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if saveFile(data, C.Path.GeoIP()) != nil {
|
||||||
|
return fmt.Errorf("can't save GeoIP database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
data, err := downloadForBytes(C.MmdbUrl)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't download MMDB database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
instance, err := geoip2.FromBytes(data)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid MMDB database file: %s", err)
|
||||||
|
}
|
||||||
|
_ = instance.Close()
|
||||||
|
|
||||||
|
if saveFile(data, C.Path.MMDB()) != nil {
|
||||||
|
return fmt.Errorf("can't save MMDB database file: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := downloadForBytes(C.GeoSiteUrl)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoSite database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = geoLoader.LoadSiteByBytes(data, "cn"); err != nil {
|
||||||
|
return fmt.Errorf("invalid GeoSite database file: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if saveFile(data, C.Path.GeoSite()) != nil {
|
||||||
|
return fmt.Errorf("can't save GeoSite database file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadForBytes(url string) ([]byte, error) {
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
return io.ReadAll(resp.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveFile(bytes []byte, path string) error {
|
||||||
|
return os.WriteFile(path, bytes, 0o644)
|
||||||
|
}
|
@ -30,6 +30,7 @@ const (
|
|||||||
Vmess
|
Vmess
|
||||||
Vless
|
Vless
|
||||||
Trojan
|
Trojan
|
||||||
|
Hysteria
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -41,6 +42,7 @@ const (
|
|||||||
type Connection interface {
|
type Connection interface {
|
||||||
Chains() Chain
|
Chains() Chain
|
||||||
AppendToChains(adapter ProxyAdapter)
|
AppendToChains(adapter ProxyAdapter)
|
||||||
|
RemoteDestination() string
|
||||||
}
|
}
|
||||||
|
|
||||||
type Chain []string
|
type Chain []string
|
||||||
@ -104,7 +106,13 @@ type ProxyAdapter interface {
|
|||||||
ListenPacketOnStreamConn(c net.Conn, metadata *Metadata) (PacketConn, error)
|
ListenPacketOnStreamConn(c net.Conn, metadata *Metadata) (PacketConn, error)
|
||||||
|
|
||||||
// Unwrap extracts the proxy from a proxy-group. It returns nil when nothing to extract.
|
// Unwrap extracts the proxy from a proxy-group. It returns nil when nothing to extract.
|
||||||
Unwrap(metadata *Metadata) Proxy
|
Unwrap(metadata *Metadata, touch bool) Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
type Group interface {
|
||||||
|
URLTest(ctx context.Context, url string) (mp map[string]uint16, err error)
|
||||||
|
GetProxies(touch bool) []Proxy
|
||||||
|
Touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
type DelayHistory struct {
|
type DelayHistory struct {
|
||||||
@ -155,6 +163,8 @@ func (at AdapterType) String() string {
|
|||||||
return "Vless"
|
return "Vless"
|
||||||
case Trojan:
|
case Trojan:
|
||||||
return "Trojan"
|
return "Trojan"
|
||||||
|
case Hysteria:
|
||||||
|
return "Hysteria"
|
||||||
|
|
||||||
case Relay:
|
case Relay:
|
||||||
return "Relay"
|
return "Relay"
|
||||||
|
@ -16,6 +16,7 @@ const (
|
|||||||
DNSNormal DNSMode = iota
|
DNSNormal DNSMode = iota
|
||||||
DNSFakeIP
|
DNSFakeIP
|
||||||
DNSMapping
|
DNSMapping
|
||||||
|
DNSHosts
|
||||||
)
|
)
|
||||||
|
|
||||||
type DNSMode int
|
type DNSMode int
|
||||||
@ -64,7 +65,52 @@ func (e DNSMode) String() string {
|
|||||||
return "fake-ip"
|
return "fake-ip"
|
||||||
case DNSMapping:
|
case DNSMapping:
|
||||||
return "redir-host"
|
return "redir-host"
|
||||||
|
case DNSHosts:
|
||||||
|
return "hosts"
|
||||||
default:
|
default:
|
||||||
return "unknown"
|
return "unknown"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DNSPrefer int
|
||||||
|
|
||||||
|
const (
|
||||||
|
DualStack DNSPrefer = iota
|
||||||
|
IPv4Only
|
||||||
|
IPv6Only
|
||||||
|
IPv4Prefer
|
||||||
|
IPv6Prefer
|
||||||
|
)
|
||||||
|
|
||||||
|
var dnsPreferMap = map[string]DNSPrefer{
|
||||||
|
DualStack.String(): DualStack,
|
||||||
|
IPv4Only.String(): IPv4Only,
|
||||||
|
IPv6Only.String(): IPv6Only,
|
||||||
|
IPv4Prefer.String(): IPv4Prefer,
|
||||||
|
IPv6Prefer.String(): IPv6Prefer,
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d DNSPrefer) String() string {
|
||||||
|
switch d {
|
||||||
|
case DualStack:
|
||||||
|
return "dual"
|
||||||
|
case IPv4Only:
|
||||||
|
return "ipv4"
|
||||||
|
case IPv6Only:
|
||||||
|
return "ipv6"
|
||||||
|
case IPv4Prefer:
|
||||||
|
return "ipv4-prefer"
|
||||||
|
case IPv6Prefer:
|
||||||
|
return "ipv6-prefer"
|
||||||
|
default:
|
||||||
|
return "dual"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDNSPrefer(prefer string) DNSPrefer {
|
||||||
|
if p, ok := dnsPreferMap[prefer]; ok {
|
||||||
|
return p
|
||||||
|
} else {
|
||||||
|
return DualStack
|
||||||
|
}
|
||||||
|
}
|
||||||
|
20
constant/ebpf.go
Normal file
20
constant/ebpf.go
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
package constant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
BpfFSPath = "/sys/fs/bpf/clash"
|
||||||
|
|
||||||
|
TcpAutoRedirPort = 't'<<8 | 'r'<<0
|
||||||
|
ClashTrafficMark = 'c'<<24 | 'l'<<16 | 't'<<8 | 'm'<<0
|
||||||
|
)
|
||||||
|
|
||||||
|
type EBpf interface {
|
||||||
|
Start() error
|
||||||
|
Close()
|
||||||
|
Lookup(srcAddrPort netip.AddrPort) (socks5.Addr, error)
|
||||||
|
}
|
7
constant/features/no_doq.go
Normal file
7
constant/features/no_doq.go
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
//go:build no_doq
|
||||||
|
|
||||||
|
package features
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
TAGS = append(TAGS, "no_doq")
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user