Compare commits
274 Commits
dev-refact
...
meta-main
Author | SHA1 | Date | |
---|---|---|---|
d78b2b1cfb | |||
3e20912339 | |||
b2d7149a95 | |||
64be213b66 | |||
68b28ed530 | |||
3eacce9a66 | |||
6dadc2357a | |||
698d8ca701 | |||
1a4b00c70e | |||
64552fbd00 | |||
7c8d8f56e1 | |||
93ada8989f | |||
4b4c3dc41e | |||
b699fb046b | |||
ae08d13de4 | |||
1d784231b0 | |||
5fd79890e7 | |||
53b2a480ef | |||
943137de3b | |||
2d3aad573e | |||
409cd4f6a1 | |||
bd526ad0a1 | |||
4673d2093a | |||
94a765ee31 | |||
dcd2417fce | |||
4c5853e5e7 | |||
52f4cb599a | |||
90f6cc233c | |||
e20d01a679 | |||
9a5c0a4b6d | |||
1b0d09068b | |||
3373b62b02 | |||
508e257543 | |||
7b0cd14b00 | |||
22fb219ad8 | |||
c34c5ff1f9 | |||
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 | |||
d823dde43c | |||
d69e0bce4a | |||
7f197ede51 | |||
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 | |||
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 | |||
625c4a1079 | |||
341ef19099 | |||
2563b20019 | |||
1b3b5b4dfe | |||
2e6bdc5636 | |||
be298cfa16 | |||
277e71b26a | |||
f7c903a586 | |||
ff4a5bef9b | |||
d8dc44e786 | |||
c968104a19 | |||
f7481ecadf | |||
85c37b473a | |||
23bc231df3 | |||
2146b605f7 | |||
8853e97b40 | |||
099aa1e3c2 | |||
63fdb348db | |||
81ee44f6c0 | |||
130a3a261d | |||
94368f43eb |
12
.github/workflows/build.yaml
vendored
12
.github/workflows/build.yaml
vendored
@ -5,12 +5,14 @@ jobs:
|
|||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Set up Go
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/setup-go@v1
|
uses: actions/checkout@v3
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: 1.18
|
go-version: '1.19'
|
||||||
- name: Check out code
|
check-latest: true
|
||||||
uses: actions/checkout@v1
|
cache: true
|
||||||
- name: Build
|
- name: Build
|
||||||
run: make all
|
run: make all
|
||||||
- name: Release
|
- name: Release
|
||||||
|
21
.github/workflows/prerelease.yml
vendored
21
.github/workflows/prerelease.yml
vendored
@ -12,26 +12,15 @@ jobs:
|
|||||||
Build:
|
Build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Cache go module
|
- name: Setup Go
|
||||||
uses: actions/cache@v2
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
go-version: '1.19'
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
check-latest: true
|
||||||
restore-keys: |
|
cache: true
|
||||||
${{ runner.os }}-go-
|
|
||||||
|
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
if: ${{github.ref_name=='Beta'}}
|
if: ${{github.ref_name=='Beta'}}
|
||||||
|
22
.github/workflows/release.yaml
vendored
22
.github/workflows/release.yaml
vendored
@ -7,24 +7,16 @@ jobs:
|
|||||||
Build:
|
Build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
go-version: '1.19'
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
check-latest: true
|
||||||
restore-keys: |
|
cache: true
|
||||||
${{ runner.os }}-go-
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: |
|
run: |
|
||||||
go test ./...
|
go test ./...
|
||||||
|
@ -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/"]
|
||||||
|
|
||||||
|
10
Makefile
10
Makefile
@ -12,7 +12,7 @@ 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='
|
||||||
|
|
||||||
@ -147,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 ./...
|
22
README.md
22
README.md
@ -212,6 +212,21 @@ proxies:
|
|||||||
grpc-service-name: grpcname
|
grpc-service-name: grpcname
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Support outbound transport protocol `Wireguard`
|
||||||
|
```yaml
|
||||||
|
proxies:
|
||||||
|
- name: "wg"
|
||||||
|
type: wireguard
|
||||||
|
server: 162.159.192.1
|
||||||
|
port: 2480
|
||||||
|
ip: 172.16.0.2
|
||||||
|
ipv6: fd01:5ca1:ab1e:80fa:ab85:6eea:213f:f4a5
|
||||||
|
private-key: eCtXsJZ27+4PbhDkHnB923tkUn2Gj59wZw5wFA75MnU=
|
||||||
|
public-key: Cr8hWlKvtDt7nrvf+f0brNQQzabAqrjfBvas9pmowjo=
|
||||||
|
udp: true
|
||||||
|
```
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
Work on Linux OS who's supported `iptables`
|
Work on Linux OS who's supported `iptables`
|
||||||
|
|
||||||
@ -251,8 +266,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 +289,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).
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@ -286,6 +301,7 @@ the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library
|
|||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||||
|
* [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
|
@ -4,16 +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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -40,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -151,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
|
||||||
}
|
}
|
||||||
|
|
||||||
if unifiedDelay {
|
|
||||||
start = time.Now()
|
|
||||||
resp, err = client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = resp.Body.Close()
|
_ = resp.Body.Close()
|
||||||
|
|
||||||
|
if unifiedDelay {
|
||||||
|
second := time.Now()
|
||||||
|
resp, err = client.Do(req)
|
||||||
|
if err == nil {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
start = second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -198,7 +198,6 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr = C.Metadata{
|
addr = C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: u.Hostname(),
|
Host: u.Hostname(),
|
||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
|
@ -17,5 +17,9 @@ func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn) *context.ConnCo
|
|||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
|
if ip, port, err := parseAddr(conn.LocalAddr().String()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -16,5 +16,9 @@ func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
|||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
|
if ip, port, err := parseAddr(conn.LocalAddr().String()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,7 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
||||||
@ -17,14 +17,20 @@ func (s *PacketAdapter) Metadata() *C.Metadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewPacket is PacketAdapter generator
|
// NewPacket is PacketAdapter generator
|
||||||
func NewPacket(target M.Socksaddr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
||||||
metadata := socksAddrToMetadata(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.UDP
|
metadata.NetWork = C.UDP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
|
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
||||||
|
if ip, port, err := parseAddr(p.InAddr().String()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return &PacketAdapter{
|
return &PacketAdapter{
|
||||||
UDPPacket: packet,
|
UDPPacket: packet,
|
||||||
|
@ -22,6 +22,14 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnCo
|
|||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
localAddr := conn.LocalAddr()
|
||||||
|
// Filter when net.Addr interface is nil
|
||||||
|
if localAddr != nil {
|
||||||
|
if ip, port, err := parseAddr(localAddr.String()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
@ -32,17 +40,12 @@ func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
|||||||
metadata.Type = C.INNER
|
metadata.Type = C.INNER
|
||||||
metadata.DNSMode = C.DNSMapping
|
metadata.DNSMode = C.DNSMapping
|
||||||
metadata.Host = host
|
metadata.Host = host
|
||||||
metadata.AddrType = C.AtypDomainName
|
|
||||||
metadata.Process = C.ClashName
|
metadata.Process = C.ClashName
|
||||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||||
metadata.DstPort = port
|
metadata.DstPort = port
|
||||||
if host == "" {
|
if host == "" {
|
||||||
if ip, err := netip.ParseAddr(h); err == nil {
|
if ip, err := netip.ParseAddr(h); err == nil {
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
if ip.Is6() {
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,39 +1,19 @@
|
|||||||
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"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func socksAddrToMetadata(addr M.Socksaddr) *C.Metadata {
|
|
||||||
metadata := &C.Metadata{}
|
|
||||||
switch addr.Family() {
|
|
||||||
case M.AddressFamilyIPv4:
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
metadata.DstIP = addr.Addr
|
|
||||||
case M.AddressFamilyIPv6:
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
metadata.DstIP = addr.Addr
|
|
||||||
case M.AddressFamilyFqdn:
|
|
||||||
metadata.AddrType = C.AtypDomainName
|
|
||||||
metadata.Host = addr.Fqdn
|
|
||||||
}
|
|
||||||
metadata.DstPort = strconv.Itoa(int(addr.Port))
|
|
||||||
return metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{}
|
||||||
AddrType: int(target[0]),
|
|
||||||
}
|
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
@ -44,7 +24,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]))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,7 +44,6 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
@ -71,12 +51,6 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
switch {
|
|
||||||
case ip.Is6():
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
default:
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -4,16 +4,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"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"
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
@ -24,6 +20,7 @@ type Base struct {
|
|||||||
udp bool
|
udp bool
|
||||||
rmark int
|
rmark int
|
||||||
id string
|
id string
|
||||||
|
prefer C.DNSPrefer
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implements C.ProxyAdapter
|
// Name implements C.ProxyAdapter
|
||||||
@ -93,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -107,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 {
|
||||||
@ -122,6 +132,7 @@ 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 {
|
||||||
@ -132,6 +143,7 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
|
prefer: opt.Prefer,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -161,7 +173,6 @@ func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
|||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
net.PacketConn
|
net.PacketConn
|
||||||
nc N.PacketConn
|
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
actualRemoteDestination string
|
actualRemoteDestination string
|
||||||
}
|
}
|
||||||
@ -180,22 +191,8 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *packetConn) ReadPacket(buffer *buf.Buffer) (addr M.Socksaddr, err error) {
|
|
||||||
return c.nc.ReadPacket(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *packetConn) WritePacket(buffer *buf.Buffer, addr M.Socksaddr) error {
|
|
||||||
return c.nc.WritePacket(buffer, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
var nc N.PacketConn
|
return &packetConn{pc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
if n, isNc := pc.(N.PacketConn); isNc {
|
|
||||||
nc = n
|
|
||||||
} else {
|
|
||||||
nc = &bufio.PacketConnWrapper{PacketConn: pc}
|
|
||||||
}
|
|
||||||
return &packetConn{pc, nc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRemoteDestination(addr string) string {
|
func parseRemoteDestination(addr string) string {
|
||||||
|
@ -43,6 +43,7 @@ func NewDirect() *Direct {
|
|||||||
name: "DIRECT",
|
name: "DIRECT",
|
||||||
tp: C.Direct,
|
tp: C.Direct,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -53,6 +54,7 @@ func NewCompatible() *Direct {
|
|||||||
name: "COMPATIBLE",
|
name: "COMPATIBLE",
|
||||||
tp: C.Compatible,
|
tp: C.Compatible,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,7 +88,7 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// 增加headers
|
//增加headers
|
||||||
if len(h.option.Headers) != 0 {
|
if len(h.option.Headers) != 0 {
|
||||||
for key, value := range h.option.Headers {
|
for key, value := range h.option.Headers {
|
||||||
req.Header.Add(key, value)
|
req.Header.Add(key, value)
|
||||||
@ -126,16 +128,26 @@ 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 {
|
||||||
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: sni,
|
ServerName: sni,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
}, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -146,10 +158,11 @@ func NewHttp(option HttpOption) *Http {
|
|||||||
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
|
||||||
}
|
}
|
||||||
|
@ -2,28 +2,31 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"github.com/lucas-clemente/quic-go"
|
"github.com/lucas-clemente/quic-go"
|
||||||
"github.com/lucas-clemente/quic-go/congestion"
|
"github.com/lucas-clemente/quic-go/congestion"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
hyCongestion "github.com/tobyxdd/hysteria/pkg/congestion"
|
|
||||||
"github.com/tobyxdd/hysteria/pkg/core"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/tobyxdd/hysteria/pkg/obfs"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"github.com/tobyxdd/hysteria/pkg/pmtud_fix"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/tobyxdd/hysteria/pkg/transport"
|
"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 (
|
const (
|
||||||
@ -44,23 +47,38 @@ type Hysteria struct {
|
|||||||
*Base
|
*Base
|
||||||
|
|
||||||
client *core.Client
|
client *core.Client
|
||||||
clientTransport *transport.ClientTransport
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), hyDialer(func() (net.PacketConn, error) {
|
hdc := hyDialerWithContext{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hyDialer: func() (net.PacketConn, error) {
|
||||||
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(tcpConn, h), nil
|
return NewConn(tcpConn, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
udpConn, err := h.client.DialUDP(hyDialer(func() (net.PacketConn, error) {
|
hdc := hyDialerWithContext{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hyDialer: func() (net.PacketConn, error) {
|
||||||
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -73,16 +91,18 @@ type HysteriaOption struct {
|
|||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Protocol string `proxy:"protocol,omitempty"`
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
Up string `proxy:"up,omitempty"`
|
ObfsProtocol string `proxy:"obfs-protocol,omitempty"` // compatible with Stash
|
||||||
UpMbps int `proxy:"up_mbps,omitempty"`
|
Up string `proxy:"up"`
|
||||||
Down string `proxy:"down,omitempty"`
|
UpSpeed int `proxy:"up-speed,omitempty"` // compatible with Stash
|
||||||
DownMbps int `proxy:"down_mbps,omitempty"`
|
Down string `proxy:"down"`
|
||||||
|
DownSpeed int `proxy:"down-speed,omitempty"` // compatible with Stash
|
||||||
Auth string `proxy:"auth,omitempty"`
|
Auth string `proxy:"auth,omitempty"`
|
||||||
AuthString string `proxy:"auth_str,omitempty"`
|
AuthString string `proxy:"auth_str,omitempty"`
|
||||||
Obfs string `proxy:"obfs,omitempty"`
|
Obfs string `proxy:"obfs,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"`
|
||||||
ALPN string `proxy:"alpn,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
CustomCAString string `proxy:"ca_str,omitempty"`
|
CustomCAString string `proxy:"ca_str,omitempty"`
|
||||||
ReceiveWindowConn int `proxy:"recv_window_conn,omitempty"`
|
ReceiveWindowConn int `proxy:"recv_window_conn,omitempty"`
|
||||||
@ -92,22 +112,16 @@ type HysteriaOption struct {
|
|||||||
|
|
||||||
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||||
var up, down uint64
|
var up, down uint64
|
||||||
if len(c.Up) > 0 {
|
|
||||||
up = stringToBps(c.Up)
|
up = stringToBps(c.Up)
|
||||||
if up == 0 {
|
if up == 0 {
|
||||||
return 0, 0, errors.New("invalid speed format")
|
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
up = uint64(c.UpMbps) * mbpsToBps
|
|
||||||
}
|
|
||||||
if len(c.Down) > 0 {
|
|
||||||
down = stringToBps(c.Down)
|
down = stringToBps(c.Down)
|
||||||
if down == 0 {
|
if down == 0 {
|
||||||
return 0, 0, errors.New("invalid speed format")
|
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
||||||
}
|
|
||||||
} else {
|
|
||||||
down = uint64(c.DownMbps) * mbpsToBps
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return up, down, nil
|
return up, down, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -121,73 +135,103 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
serverName := option.Server
|
serverName := option.Server
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
serverName = option.Server
|
serverName = option.SNI
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: serverName,
|
ServerName: serverName,
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
MinVersion: tls.VersionTLS13,
|
MinVersion: tls.VersionTLS13,
|
||||||
}
|
}
|
||||||
if len(option.ALPN) > 0 {
|
|
||||||
tlsConfig.NextProtos = []string{option.ALPN}
|
var bs []byte
|
||||||
} else {
|
var err error
|
||||||
tlsConfig.NextProtos = []string{DefaultALPN}
|
|
||||||
}
|
|
||||||
if len(option.CustomCA) > 0 {
|
if len(option.CustomCA) > 0 {
|
||||||
bs, err := ioutil.ReadFile(option.CustomCA)
|
bs, err = os.ReadFile(option.CustomCA)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
|
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
|
||||||
}
|
}
|
||||||
cp := x509.NewCertPool()
|
|
||||||
if !cp.AppendCertsFromPEM(bs) {
|
|
||||||
return nil, fmt.Errorf("hysteria %s failed to parse ca_str", addr)
|
|
||||||
}
|
|
||||||
tlsConfig.RootCAs = cp
|
|
||||||
} else if option.CustomCAString != "" {
|
} else if option.CustomCAString != "" {
|
||||||
cp := x509.NewCertPool()
|
bs = []byte(option.CustomCAString)
|
||||||
if !cp.AppendCertsFromPEM([]byte(option.CustomCAString)) {
|
|
||||||
return nil, fmt.Errorf("hysteria %s failed to parse ca_str", addr)
|
|
||||||
}
|
}
|
||||||
tlsConfig.RootCAs = cp
|
|
||||||
|
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{
|
quicConfig := &quic.Config{
|
||||||
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
KeepAlive: true,
|
KeepAlivePeriod: 10 * time.Second,
|
||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
EnableDatagrams: true,
|
EnableDatagrams: true,
|
||||||
}
|
}
|
||||||
|
if option.ObfsProtocol != "" {
|
||||||
|
option.Protocol = option.ObfsProtocol
|
||||||
|
}
|
||||||
if option.Protocol == "" {
|
if option.Protocol == "" {
|
||||||
option.Protocol = DefaultProtocol
|
option.Protocol = DefaultProtocol
|
||||||
}
|
}
|
||||||
if option.ReceiveWindowConn == 0 {
|
if option.ReceiveWindowConn == 0 {
|
||||||
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow
|
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
|
||||||
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
||||||
}
|
}
|
||||||
if option.ReceiveWindow == 0 {
|
if option.ReceiveWindow == 0 {
|
||||||
quicConfig.InitialConnectionReceiveWindow = DefaultConnectionReceiveWindow
|
quicConfig.InitialConnectionReceiveWindow = DefaultConnectionReceiveWindow / 10
|
||||||
quicConfig.MaxConnectionReceiveWindow = DefaultConnectionReceiveWindow
|
quicConfig.MaxConnectionReceiveWindow = DefaultConnectionReceiveWindow
|
||||||
}
|
}
|
||||||
if !quicConfig.DisablePathMTUDiscovery && pmtud_fix.DisablePathMTUDiscovery {
|
if !quicConfig.DisablePathMTUDiscovery && pmtud_fix.DisablePathMTUDiscovery {
|
||||||
log.Infoln("hysteria: Path MTU Discovery is not yet supported on this platform")
|
log.Infoln("hysteria: Path MTU Discovery is not yet supported on this platform")
|
||||||
}
|
}
|
||||||
var auth []byte
|
|
||||||
|
var auth = []byte(option.AuthString)
|
||||||
if option.Auth != "" {
|
if option.Auth != "" {
|
||||||
authBytes, err := base64.StdEncoding.DecodeString(option.Auth)
|
auth, err = base64.StdEncoding.DecodeString(option.Auth)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("hysteria %s parse auth error: %w", addr, err)
|
return nil, err
|
||||||
}
|
}
|
||||||
auth = authBytes
|
|
||||||
} else {
|
|
||||||
auth = []byte(option.AuthString)
|
|
||||||
}
|
}
|
||||||
var obfuscator obfs.Obfuscator
|
var obfuscator obfs.Obfuscator
|
||||||
if len(option.Obfs) > 0 {
|
if len(option.Obfs) > 0 {
|
||||||
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
||||||
}
|
}
|
||||||
up, down, _ := option.Speed()
|
|
||||||
|
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(
|
client, err := core.NewClient(
|
||||||
addr, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
addr, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
||||||
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
||||||
@ -204,9 +248,9 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
udp: true,
|
udp: true,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
clientTransport: clientTransport,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -214,6 +258,12 @@ func stringToBps(s string) uint64 {
|
|||||||
if s == "" {
|
if s == "" {
|
||||||
return 0
|
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)
|
m := rateStringRegexp.FindStringSubmatch(s)
|
||||||
if m == nil {
|
if m == nil {
|
||||||
return 0
|
return 0
|
||||||
@ -263,8 +313,20 @@ func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
type hyDialer func() (net.PacketConn, error)
|
type hyDialerWithContext struct {
|
||||||
|
hyDialer func() (net.PacketConn, error)
|
||||||
func (h hyDialer) ListenPacket() (net.PacketConn, error) {
|
ctx context.Context
|
||||||
return h()
|
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)
|
||||||
}
|
}
|
||||||
|
@ -30,6 +30,7 @@ func NewReject() *Reject {
|
|||||||
name: "REJECT",
|
name: "REJECT",
|
||||||
tp: C.Reject,
|
tp: C.Reject,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -40,6 +41,7 @@ func NewPass() *Reject {
|
|||||||
name: "PASS",
|
name: "PASS",
|
||||||
tp: C.Pass,
|
tp: C.Pass,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,12 +17,14 @@ import (
|
|||||||
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
"github.com/sagernet/sing/common/uot"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
*Base
|
*Base
|
||||||
method shadowsocks.Method
|
method shadowsocks.Method
|
||||||
|
|
||||||
|
option *ShadowSocksOption
|
||||||
// obfs
|
// obfs
|
||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
@ -39,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 {
|
||||||
@ -51,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"`
|
||||||
@ -71,6 +75,9 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
|
return ss.method.DialConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443"))
|
||||||
|
}
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -90,12 +97,19 @@ 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
|
||||||
@ -104,6 +118,19 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
return newPacketConn(pc, ss), nil
|
return newPacketConn(pc, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if ss.option.UDPOverTCP {
|
||||||
|
return newPacketConn(uot.NewClientConn(c), ss), nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) SupportUOT() bool {
|
||||||
|
return ss.option.UDPOverTCP
|
||||||
|
}
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
||||||
@ -158,9 +185,11 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
method: method,
|
method: method,
|
||||||
|
|
||||||
|
option: &option,
|
||||||
obfsMode: obfsMode,
|
obfsMode: obfsMode,
|
||||||
v2rayOption: v2rayOption,
|
v2rayOption: v2rayOption,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -79,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
|
||||||
@ -149,6 +149,7 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
|
@ -158,6 +158,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -5,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,13 +140,22 @@ 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{
|
||||||
@ -155,13 +166,14 @@ func NewSocks5(option Socks5Option) *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"
|
||||||
@ -35,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"`
|
||||||
@ -188,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 {
|
||||||
@ -212,6 +215,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
instance: trojan.New(tOption),
|
instance: trojan.New(tOption),
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -234,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 {
|
||||||
|
@ -3,7 +3,9 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
xtls "github.com/xtls/go"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@ -11,7 +13,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
xtls "github.com/xtls/go"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -43,10 +44,11 @@ func getClientXSessionCache() xtls.ClientSessionCache {
|
|||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
var buf [][]byte
|
var buf [][]byte
|
||||||
aType := uint8(metadata.AddrType)
|
addrType := metadata.AddrType()
|
||||||
|
aType := uint8(addrType)
|
||||||
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
switch metadata.AddrType {
|
switch addrType {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
lenM := uint8(len(metadata.Host))
|
lenM := uint8(len(metadata.Host))
|
||||||
host := []byte(metadata.Host)
|
host := []byte(metadata.Host)
|
||||||
@ -74,6 +76,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()
|
||||||
|
@ -15,8 +15,10 @@ import (
|
|||||||
"github.com/Dreamacro/clash/common/convert"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
)
|
)
|
||||||
@ -55,6 +57,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,31 +73,40 @@ 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
|
wsOpts.TLS = true
|
||||||
wsOpts.TLSConfig = &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
MinVersion: tls.VersionTLS12,
|
MinVersion: tls.VersionTLS12,
|
||||||
ServerName: host,
|
ServerName: host,
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"http/1.1"},
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(v.option.Fingerprint) == 0 {
|
||||||
|
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
||||||
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
|
if host := wsOpts.Headers.Get("Host"); host == "" {
|
||||||
wsOpts.Headers.Set("Host", convert.RandHost())
|
wsOpts.Headers.Set("Host", convert.RandHost())
|
||||||
convert.SetUserAgent(wsOpts.Headers)
|
convert.SetUserAgent(wsOpts.Headers)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
@ -150,6 +162,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 {
|
||||||
@ -166,6 +179,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 {
|
||||||
@ -267,16 +281,16 @@ func (v *Vless) SupportUOT() bool {
|
|||||||
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||||
var addrType byte
|
var addrType byte
|
||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType {
|
switch metadata.AddrType() {
|
||||||
case C.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
addrType = vless.AtypIPv4
|
addrType = vless.AtypIPv4
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case C.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
addrType = vless.AtypIPv6
|
addrType = vless.AtypIPv6
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case C.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
addrType = vless.AtypDomainName
|
addrType = vless.AtypDomainName
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
addr[0] = byte(len(metadata.Host))
|
addr[0] = byte(len(metadata.Host))
|
||||||
@ -410,6 +424,7 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
tp: C.Vless,
|
tp: C.Vless,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -434,10 +449,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,17 +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/common/convert"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
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"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
@ -41,15 +45,17 @@ type VmessOption struct {
|
|||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
// TODO: compatible with VMESS WS older version configurations
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||||
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -81,13 +87,13 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
case "ws":
|
case "ws":
|
||||||
|
|
||||||
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: make(http.Header),
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
@ -98,26 +104,33 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
wsOpts.Headers.Set("Host", convert.RandHost())
|
|
||||||
convert.SetUserAgent(wsOpts.Headers)
|
|
||||||
}
|
}
|
||||||
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,
|
||||||
}
|
}
|
||||||
@ -126,27 +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
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
http.Header(v.option.HTTPOpts.Headers).Set("Host", convert.RandHost())
|
|
||||||
convert.SetUserAgent(v.option.HTTPOpts.Headers)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
httpOpts := &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"},
|
||||||
@ -156,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,
|
||||||
}
|
}
|
||||||
@ -182,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
|
||||||
@ -203,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
|
||||||
}
|
}
|
||||||
@ -233,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 {
|
||||||
@ -242,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 {
|
||||||
@ -258,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -273,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: 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 {
|
||||||
@ -300,6 +348,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -339,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
328
adapter/outbound/wireguard.go
Normal file
328
adapter/outbound/wireguard.go
Normal file
@ -0,0 +1,328 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/listener/sing"
|
||||||
|
|
||||||
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
"github.com/sagernet/sing/common/debug"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
"github.com/sagernet/wireguard-go/device"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WireGuard struct {
|
||||||
|
*Base
|
||||||
|
bind *wireguard.ClientBind
|
||||||
|
device *device.Device
|
||||||
|
tunDevice wireguard.Device
|
||||||
|
dialer *wgDialer
|
||||||
|
startOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
type WireGuardOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key"`
|
||||||
|
PublicKey string `proxy:"public-key"`
|
||||||
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
|
Reserved []int `proxy:"reserved,omitempty"`
|
||||||
|
Workers int `proxy:"workers,omitempty"`
|
||||||
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgDialer struct {
|
||||||
|
options []dialer.Option
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *wgDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
return dialer.DialContext(ctx, network, destination.String(), d.options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *wgDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
return dialer.ListenPacket(ctx, "udp", "", d.options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||||
|
outbound := &WireGuard{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.WireGuard,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
dialer: &wgDialer{},
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(outbound, closeWireGuard)
|
||||||
|
|
||||||
|
var reserved [3]uint8
|
||||||
|
if len(option.Reserved) > 0 {
|
||||||
|
if len(option.Reserved) != 3 {
|
||||||
|
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
||||||
|
}
|
||||||
|
reserved[0] = uint8(option.Reserved[0])
|
||||||
|
reserved[1] = uint8(option.Reserved[1])
|
||||||
|
reserved[2] = uint8(option.Reserved[2])
|
||||||
|
}
|
||||||
|
peerAddr := M.ParseSocksaddr(option.Server)
|
||||||
|
peerAddr.Port = uint16(option.Port)
|
||||||
|
outbound.bind = wireguard.NewClientBind(context.Background(), outbound.dialer, peerAddr, reserved)
|
||||||
|
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||||
|
if len(option.Ip) > 0 {
|
||||||
|
if !strings.Contains(option.Ip, "/") {
|
||||||
|
option.Ip = option.Ip + "/32"
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(option.Ip); err == nil {
|
||||||
|
localPrefixes = append(localPrefixes, prefix)
|
||||||
|
} else {
|
||||||
|
return nil, E.Cause(err, "ip address parse error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(option.Ipv6) > 0 {
|
||||||
|
if !strings.Contains(option.Ipv6, "/") {
|
||||||
|
option.Ipv6 = option.Ipv6 + "/128"
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(option.Ipv6); err == nil {
|
||||||
|
localPrefixes = append(localPrefixes, prefix)
|
||||||
|
} else {
|
||||||
|
return nil, E.Cause(err, "ipv6 address parse error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(localPrefixes) == 0 {
|
||||||
|
return nil, E.New("missing local address")
|
||||||
|
}
|
||||||
|
var privateKey, peerPublicKey, preSharedKey string
|
||||||
|
{
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode private key")
|
||||||
|
}
|
||||||
|
privateKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
{
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode peer public key")
|
||||||
|
}
|
||||||
|
peerPublicKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
if option.PreSharedKey != "" {
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode pre shared key")
|
||||||
|
}
|
||||||
|
preSharedKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
ipcConf := "private_key=" + privateKey
|
||||||
|
ipcConf += "\npublic_key=" + peerPublicKey
|
||||||
|
ipcConf += "\nendpoint=" + peerAddr.String()
|
||||||
|
if preSharedKey != "" {
|
||||||
|
ipcConf += "\npreshared_key=" + preSharedKey
|
||||||
|
}
|
||||||
|
var has4, has6 bool
|
||||||
|
for _, address := range localPrefixes {
|
||||||
|
if address.Addr().Is4() {
|
||||||
|
has4 = true
|
||||||
|
} else {
|
||||||
|
has6 = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if has4 {
|
||||||
|
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
||||||
|
}
|
||||||
|
if has6 {
|
||||||
|
ipcConf += "\nallowed_ip=::/0"
|
||||||
|
}
|
||||||
|
mtu := option.MTU
|
||||||
|
if mtu == 0 {
|
||||||
|
mtu = 1408
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "create WireGuard device")
|
||||||
|
}
|
||||||
|
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
||||||
|
Verbosef: func(format string, args ...interface{}) {
|
||||||
|
sing.Logger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
|
},
|
||||||
|
Errorf: func(format string, args ...interface{}) {
|
||||||
|
sing.Logger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
|
},
|
||||||
|
}, option.Workers)
|
||||||
|
if debug.Enabled {
|
||||||
|
sing.Logger.Trace("created wireguard ipc conf: \n", ipcConf)
|
||||||
|
}
|
||||||
|
err = outbound.device.IpcSet(ipcConf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "setup wireguard")
|
||||||
|
}
|
||||||
|
//err = outbound.tunDevice.Start()
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeWireGuard(w *WireGuard) {
|
||||||
|
if w.device != nil {
|
||||||
|
w.device.Close()
|
||||||
|
}
|
||||||
|
_ = common.Close(w.tunDevice)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
w.dialer.options = opts
|
||||||
|
var conn net.Conn
|
||||||
|
w.startOnce.Do(func() {
|
||||||
|
err = w.tunDevice.Start()
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
var addrs []netip.Addr
|
||||||
|
addrs, err = resolver.ResolveAllIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
conn, err = N.DialSerial(ctx, w.tunDevice, "tcp", M.ParseSocksaddr(metadata.RemoteAddress()), addrs)
|
||||||
|
} else {
|
||||||
|
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.ParseSocksaddr(metadata.Pure().RemoteAddress()))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(&wgConn{conn, w}, w), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
w.dialer.options = opts
|
||||||
|
var pc net.PacketConn
|
||||||
|
w.startOnce.Do(func() {
|
||||||
|
err = w.tunDevice.Start()
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
pc, err = w.tunDevice.ListenPacket(ctx, M.ParseSocksaddr(metadata.Pure().RemoteAddress()))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(&wgPacketConn{pc, w}, w), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgConn struct {
|
||||||
|
conn net.Conn
|
||||||
|
wg *WireGuard
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *wgConn) Read(b []byte) (n int, err error) {
|
||||||
|
defer runtime.KeepAlive(c.wg)
|
||||||
|
return c.conn.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *wgConn) Write(b []byte) (n int, err error) {
|
||||||
|
defer runtime.KeepAlive(c.wg)
|
||||||
|
return c.conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *wgConn) Close() error {
|
||||||
|
defer runtime.KeepAlive(c.wg)
|
||||||
|
return c.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *wgConn) LocalAddr() net.Addr {
|
||||||
|
defer runtime.KeepAlive(c.wg)
|
||||||
|
return c.conn.LocalAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *wgConn) RemoteAddr() net.Addr {
|
||||||
|
defer runtime.KeepAlive(c.wg)
|
||||||
|
return c.conn.RemoteAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *wgConn) SetDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.wg)
|
||||||
|
return c.conn.SetDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *wgConn) SetReadDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.wg)
|
||||||
|
return c.conn.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *wgConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.wg)
|
||||||
|
return c.conn.SetWriteDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgPacketConn struct {
|
||||||
|
pc net.PacketConn
|
||||||
|
wg *WireGuard
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *wgPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
defer runtime.KeepAlive(pc.wg)
|
||||||
|
return pc.pc.ReadFrom(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *wgPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
|
defer runtime.KeepAlive(pc.wg)
|
||||||
|
return pc.pc.WriteTo(p, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *wgPacketConn) Close() error {
|
||||||
|
defer runtime.KeepAlive(pc.wg)
|
||||||
|
return pc.pc.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *wgPacketConn) LocalAddr() net.Addr {
|
||||||
|
defer runtime.KeepAlive(pc.wg)
|
||||||
|
return pc.pc.LocalAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *wgPacketConn) SetDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(pc.wg)
|
||||||
|
return pc.pc.SetDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *wgPacketConn) SetReadDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(pc.wg)
|
||||||
|
return pc.pc.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *wgPacketConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(pc.wg)
|
||||||
|
return pc.pc.SetWriteDeadline(t)
|
||||||
|
}
|
@ -4,12 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"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 {
|
||||||
@ -32,7 +31,7 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
f.onDialSuccess()
|
f.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed()
|
f.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
@ -73,24 +72,30 @@ 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)
|
||||||
al := proxies[0]
|
for _, proxy := range proxies {
|
||||||
for i := len(proxies) - 1; i > -1; i-- {
|
if len(f.selected) == 0 {
|
||||||
proxy := proxies[i]
|
if proxy.Alive() {
|
||||||
if proxy.Name() == f.selected && proxy.Alive() {
|
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
if proxy.Name() == f.selected {
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
al = proxy
|
return proxy
|
||||||
|
} else {
|
||||||
|
f.selected = ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return al
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Set(name string) error {
|
func (f *Fallback) Set(name string) error {
|
||||||
@ -126,6 +131,7 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
|
option.ExcludeFilter,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
@ -3,102 +3,164 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"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"
|
"go.uber.org/atomic"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupBase struct {
|
type GroupBase struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
filter *regexp2.Regexp
|
filterRegs []*regexp2.Regexp
|
||||||
|
excludeFilterReg *regexp2.Regexp
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
versions sync.Map // map[string]uint
|
|
||||||
proxies sync.Map // map[string][]C.Proxy
|
|
||||||
failedTestMux sync.Mutex
|
failedTestMux sync.Mutex
|
||||||
failedTimes int
|
failedTimes int
|
||||||
failedTime time.Time
|
failedTime time.Time
|
||||||
failedTesting *atomic.Bool
|
failedTesting *atomic.Bool
|
||||||
|
proxies [][]C.Proxy
|
||||||
|
versions []atomic.Uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
type GroupBaseOption struct {
|
type GroupBaseOption struct {
|
||||||
outbound.BaseOption
|
outbound.BaseOption
|
||||||
filter string
|
filter string
|
||||||
|
excludeFilter string
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
var filter *regexp2.Regexp = nil
|
var excludeFilterReg *regexp2.Regexp
|
||||||
if opt.filter != "" {
|
if opt.excludeFilter != "" {
|
||||||
filter = regexp2.MustCompile(opt.filter, 0)
|
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
||||||
}
|
}
|
||||||
return &GroupBase{
|
|
||||||
|
var filterRegs []*regexp2.Regexp
|
||||||
|
if opt.filter != "" {
|
||||||
|
for _, filter := range strings.Split(opt.filter, "`") {
|
||||||
|
filterReg := regexp2.MustCompile(filter, 0)
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gb := &GroupBase{
|
||||||
Base: outbound.NewBase(opt.BaseOption),
|
Base: outbound.NewBase(opt.BaseOption),
|
||||||
filter: filter,
|
filterRegs: filterRegs,
|
||||||
|
excludeFilterReg: excludeFilterReg,
|
||||||
providers: opt.providers,
|
providers: opt.providers,
|
||||||
failedTesting: atomic.NewBool(false),
|
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 {
|
|
||||||
var proxies []C.Proxy
|
var proxies []C.Proxy
|
||||||
|
if len(gb.filterRegs) == 0 {
|
||||||
for _, pd := range gb.providers {
|
for _, pd := range gb.providers {
|
||||||
if touch {
|
if touch {
|
||||||
pd.Touch()
|
pd.Touch()
|
||||||
}
|
}
|
||||||
proxies = append(proxies, pd.Proxies()...)
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
}
|
}
|
||||||
if len(proxies) == 0 {
|
} else {
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
for i, pd := range gb.providers {
|
||||||
}
|
|
||||||
return proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, pd := range gb.providers {
|
|
||||||
if touch {
|
if touch {
|
||||||
pd.Touch()
|
pd.Touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
if pd.VehicleType() == types.Compatible {
|
if pd.VehicleType() == types.Compatible {
|
||||||
gb.proxies.Store(pd.Name(), pd.Proxies())
|
gb.versions[i].Store(pd.Version())
|
||||||
gb.versions.Store(pd.Name(), 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
|
||||||
)
|
)
|
||||||
|
|
||||||
proxies = pd.Proxies()
|
proxies = pd.Proxies()
|
||||||
|
proxiesSet := map[string]struct{}{}
|
||||||
|
for _, filterReg := range gb.filterRegs {
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
if mat, _ := gb.filter.FindStringMatch(p.Name()); mat != nil {
|
name := p.Name()
|
||||||
|
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
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
|
|
||||||
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
|
||||||
|
}
|
||||||
|
|
||||||
|
if gb.excludeFilterReg != nil {
|
||||||
|
var newProxies []C.Proxy
|
||||||
|
for _, p := range proxies {
|
||||||
|
name := p.Name()
|
||||||
|
if mat, _ := gb.excludeFilterReg.FindStringMatch(name); mat != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
proxies = newProxies
|
||||||
|
}
|
||||||
|
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -112,11 +174,11 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16
|
|||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
delay, err := proxy.URLTest(ctx, url)
|
delay, err := proxy.URLTest(ctx, url)
|
||||||
lock.Lock()
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
lock.Lock()
|
||||||
mp[proxy.Name()] = delay
|
mp[proxy.Name()] = delay
|
||||||
}
|
|
||||||
lock.Unlock()
|
lock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}()
|
}()
|
||||||
@ -130,8 +192,13 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) onDialFailed() {
|
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
||||||
if gb.failedTesting.Load() {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -145,13 +212,25 @@ func (gb *GroupBase) onDialFailed() {
|
|||||||
gb.failedTime = time.Now()
|
gb.failedTime = time.Now()
|
||||||
} else {
|
} else {
|
||||||
if time.Since(gb.failedTime) > gb.failedTimeoutInterval() {
|
if time.Since(gb.failedTime) > gb.failedTimeoutInterval() {
|
||||||
|
gb.failedTimes = 0
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
if gb.failedTimes >= gb.maxFailedTimes() {
|
if gb.failedTimes >= gb.maxFailedTimes() {
|
||||||
gb.failedTesting.Store(true)
|
|
||||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
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{}
|
wg := sync.WaitGroup{}
|
||||||
for _, proxyProvider := range gb.providers {
|
for _, proxyProvider := range gb.providers {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
@ -165,9 +244,6 @@ func (gb *GroupBase) onDialFailed() {
|
|||||||
wg.Wait()
|
wg.Wait()
|
||||||
gb.failedTesting.Store(false)
|
gb.failedTesting.Store(false)
|
||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) failedIntervalTime() int64 {
|
func (gb *GroupBase) failedIntervalTime() int64 {
|
||||||
|
@ -5,15 +5,16 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
"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"
|
||||||
|
|
||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -28,11 +29,9 @@ 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"
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,17 +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()
|
lb.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
lb.onDialFailed()
|
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
|
||||||
}
|
}
|
||||||
@ -106,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...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -144,6 +143,13 @@ func strategyConsistentHashing() strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// when availability is poor, traverse the entire list to get the available nodes
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -184,8 +190,8 @@ func strategyStickySessions() strategyFn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -222,6 +228,7 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
|
option.ExcludeFilter,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
|
@ -30,6 +30,7 @@ type GroupCommonOption struct {
|
|||||||
Lazy bool `group:"lazy,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
|
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
|
@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -185,6 +185,7 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
"",
|
"",
|
||||||
|
"",
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
|
@ -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 {
|
||||||
@ -99,6 +99,7 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
|
option.ExcludeFilter,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
|
@ -34,12 +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.onDialSuccess()
|
u.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed()
|
u.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
@ -55,12 +56,12 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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()
|
||||||
@ -89,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
|
||||||
}
|
}
|
||||||
@ -139,6 +143,7 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
},
|
},
|
||||||
|
|
||||||
option.Filter,
|
option.Filter,
|
||||||
|
option.ExcludeFilter,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
|
@ -16,32 +16,19 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
if ip, err := netip.ParseAddr(host); err != nil {
|
||||||
if err != nil {
|
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: netip.Addr{},
|
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
err = nil
|
} else {
|
||||||
return
|
|
||||||
} else if ip.Is4() {
|
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv4,
|
|
||||||
Host: "",
|
Host: "",
|
||||||
DstIP: ip,
|
DstIP: ip,
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
addr = &C.Metadata{
|
|
||||||
AddrType: C.AtypIPv6,
|
|
||||||
Host: "",
|
|
||||||
DstIP: ip,
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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{
|
||||||
@ -88,6 +88,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewHysteria(*hyOption)
|
proxy, err = outbound.NewHysteria(*hyOption)
|
||||||
|
case "wireguard":
|
||||||
|
hyOption := &outbound.WireGuardOption{}
|
||||||
|
err = decoder.Decode(mapping, hyOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewWireGuard(*hyOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
@ -5,7 +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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -25,6 +29,7 @@ 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() {
|
||||||
@ -32,16 +37,13 @@ func (hc *HealthCheck) process() {
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(30 * time.Second)
|
time.Sleep(30 * time.Second)
|
||||||
hc.check()
|
hc.lazyCheck()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
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
|
||||||
@ -49,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
|
||||||
}
|
}
|
||||||
@ -62,17 +75,29 @@ func (hc *HealthCheck) touch() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
|
id := ""
|
||||||
|
if uid, err := uuid.NewV4(); err == nil {
|
||||||
|
id = uid.String()
|
||||||
|
}
|
||||||
|
log.Debugln("Start New Health Checking {%s}", id)
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
log.Debugln("Health Checking %s {%s}", p.Name(), id)
|
||||||
_, _ = p.URLTest(ctx, hc.url)
|
_, _ = p.URLTest(ctx, hc.url)
|
||||||
|
log.Debugln("Health Checked %s : %t %d ms {%s}", p.Name(), p.Alive(), p.LastDelay(), id)
|
||||||
return false, nil
|
return false, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Wait()
|
b.Wait()
|
||||||
|
log.Debugln("Finish A Health Checking {%s}", id)
|
||||||
|
return struct{}{}, nil
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
func (hc *HealthCheck) close() {
|
||||||
@ -87,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"
|
||||||
@ -25,6 +26,7 @@ type proxyProviderSchema struct {
|
|||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -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)
|
||||||
}
|
}
|
||||||
|
@ -1,18 +1,24 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -30,10 +36,11 @@ type ProxySetProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proxySetProvider struct {
|
type proxySetProvider struct {
|
||||||
*fetcher[[]C.Proxy]
|
*resource.Fetcher[[]C.Proxy]
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
version uint
|
version uint32
|
||||||
|
subscriptionInfo *SubscriptionInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -42,16 +49,17 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"updatedAt": pp.updatedAt,
|
"updatedAt": pp.UpdatedAt,
|
||||||
|
"subscriptionInfo": pp.subscriptionInfo,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Version() uint {
|
func (pp *proxySetProvider) Version() uint32 {
|
||||||
return pp.version
|
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() {
|
||||||
@ -59,19 +67,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)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,20 +99,62 @@ func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
|||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
if pp.healthCheck.auto() {
|
if pp.healthCheck.auto() {
|
||||||
defer func() { go pp.healthCheck.check() }()
|
defer func() { go pp.healthCheck.lazyCheck() }()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) getSubscriptionInfo() {
|
||||||
|
if pp.VehicleType() != types.HTTP {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
||||||
|
defer cancel()
|
||||||
|
resp, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
|
http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
||||||
|
if userInfoStr == "" {
|
||||||
|
resp2, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
|
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp2.Body.Close()
|
||||||
|
userInfoStr = strings.TrimSpace(resp2.Header.Get("subscription-userinfo"))
|
||||||
|
if userInfoStr == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pp.subscriptionInfo, err = NewSubscriptionInfo(userInfoStr)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[Provider] get subscription-userinfo: %e", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
_ = pd.fetcher.Destroy()
|
_ = pd.Fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, 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) {
|
||||||
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
|
}
|
||||||
|
var filterRegs []*regexp2.Regexp
|
||||||
|
for _, filter := range strings.Split(filter, "`") {
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
filterReg, err := regexp2.Compile(filter, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
|
||||||
if hc.auto() {
|
if hc.auto() {
|
||||||
go hc.process()
|
go hc.process()
|
||||||
@ -115,9 +165,10 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
fetcher := newFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg), proxiesOnUpdate(pd))
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, filterRegs, excludeFilterReg), proxiesOnUpdate(pd))
|
||||||
pd.fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
|
|
||||||
|
pd.getSubscriptionInfo()
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
@ -132,7 +183,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) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -144,7 +195,7 @@ func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Version() uint {
|
func (cp *compatibleProvider) Version() uint32 {
|
||||||
return cp.version
|
return cp.version
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -207,15 +258,12 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
||||||
return func(elm []C.Proxy) {
|
return func(elm []C.Proxy) {
|
||||||
pd.setProxies(elm)
|
pd.setProxies(elm)
|
||||||
if pd.version == math.MaxUint {
|
pd.version += 1
|
||||||
pd.version = 0
|
pd.getSubscriptionInfo()
|
||||||
} else {
|
|
||||||
pd.version++
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, filterReg *regexp2.Regexp) parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, excludeFilter string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
@ -232,18 +280,38 @@ func proxiesParseAndFilter(filter string, filterReg *regexp2.Regexp) parser[[]C.
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
|
proxiesSet := map[string]struct{}{}
|
||||||
|
for _, filterReg := range filterRegs {
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
name, ok := mapping["name"]
|
mName, ok := mapping["name"]
|
||||||
mat, _ := filterReg.FindStringMatch(name.(string))
|
if !ok {
|
||||||
if ok && len(filter) > 0 && mat == nil {
|
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
|
continue
|
||||||
}
|
}
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
}
|
}
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
if len(filter) > 0 {
|
if len(filter) > 0 {
|
||||||
|
57
adapter/provider/subscription_info.go
Normal file
57
adapter/provider/subscription_info.go
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SubscriptionInfo struct {
|
||||||
|
Upload int64
|
||||||
|
Download int64
|
||||||
|
Total int64
|
||||||
|
Expire int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSubscriptionInfo(str string) (si *SubscriptionInfo, err error) {
|
||||||
|
si = &SubscriptionInfo{}
|
||||||
|
str = strings.ToLower(str)
|
||||||
|
reTraffic := regexp2.MustCompile("upload=(\\d+); download=(\\d+); total=(\\d+)", 0)
|
||||||
|
reExpire := regexp2.MustCompile("expire=(\\d+)", 0)
|
||||||
|
|
||||||
|
match, err := reTraffic.FindStringMatch(str)
|
||||||
|
if err != nil || match == nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
group := match.Groups()
|
||||||
|
si.Upload, err = str2uint64(group[1].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
si.Download, err = str2uint64(group[2].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
si.Total, err = str2uint64(group[3].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
match, _ = reExpire.FindStringMatch(str)
|
||||||
|
if match != nil {
|
||||||
|
group = match.Groups()
|
||||||
|
si.Expire, err = str2uint64(group[1].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func str2uint64(str string) (int64, error) {
|
||||||
|
i, err := strconv.ParseInt(str, 10, 64)
|
||||||
|
return i, err
|
||||||
|
}
|
@ -14,6 +14,7 @@ func ExecCmd(cmdStr string) (string, error) {
|
|||||||
cmd = exec.Command(args[0])
|
cmd = exec.Command(args[0])
|
||||||
} else {
|
} else {
|
||||||
cmd = exec.Command(args[0], args[1:]...)
|
cmd = exec.Command(args[0], args[1:]...)
|
||||||
|
|
||||||
}
|
}
|
||||||
prepareBackgroundCommand(cmd)
|
prepareBackgroundCommand(cmd)
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
|
@ -7,4 +7,5 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
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)
|
||||||
|
}
|
@ -2,7 +2,6 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
@ -10,34 +9,9 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
var enc = base64.StdEncoding
|
|
||||||
|
|
||||||
func DecodeBase64(buf []byte) ([]byte, error) {
|
|
||||||
dBuf := make([]byte, enc.DecodedLen(len(buf)))
|
|
||||||
n, err := enc.Decode(dBuf, buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return dBuf[:n], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeBase64StringToString decode base64 string to string
|
|
||||||
func DecodeBase64StringToString(s string) (string, error) {
|
|
||||||
dBuf, err := enc.DecodeString(s)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(dBuf), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
||||||
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||||
data, err := DecodeBase64(buf)
|
data := DecodeBase64(buf)
|
||||||
if err != nil {
|
|
||||||
data = buf
|
|
||||||
}
|
|
||||||
|
|
||||||
arr := strings.Split(string(data), "\n")
|
arr := strings.Split(string(data), "\n")
|
||||||
|
|
||||||
@ -73,11 +47,19 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria["port"] = urlHysteria.Port()
|
hysteria["port"] = urlHysteria.Port()
|
||||||
hysteria["sni"] = query.Get("peer")
|
hysteria["sni"] = query.Get("peer")
|
||||||
hysteria["obfs"] = query.Get("obfs")
|
hysteria["obfs"] = query.Get("obfs")
|
||||||
hysteria["alpn"] = query.Get("alpn")
|
hysteria["alpn"] = []string{query.Get("alpn")}
|
||||||
hysteria["auth_str"] = query.Get("auth")
|
hysteria["auth_str"] = query.Get("auth")
|
||||||
hysteria["protocol"] = query.Get("protocol")
|
hysteria["protocol"] = query.Get("protocol")
|
||||||
hysteria["down_mbps"], _ = strconv.Atoi(query.Get("downmbps"))
|
up := query.Get("up")
|
||||||
hysteria["up_mbps"], _ = strconv.Atoi(query.Get("upmbps"))
|
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"))
|
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
||||||
|
|
||||||
proxies = append(proxies, hysteria)
|
proxies = append(proxies, hysteria)
|
||||||
@ -116,7 +98,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
|
|
||||||
// headers["Host"] = RandHost()
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
headers["User-Agent"] = RandUserAgent()
|
||||||
|
|
||||||
wsOpts["path"] = query.Get("path")
|
wsOpts["path"] = query.Get("path")
|
||||||
@ -133,94 +114,45 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
proxies = append(proxies, trojan)
|
proxies = append(proxies, trojan)
|
||||||
|
|
||||||
case "vless":
|
case "vless":
|
||||||
urlVless, err := url.Parse(line)
|
urlVLess, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
query := urlVLess.Query()
|
||||||
query := urlVless.Query()
|
|
||||||
|
|
||||||
name := uniqueName(names, urlVless.Fragment)
|
|
||||||
vless := make(map[string]any, 20)
|
vless := make(map[string]any, 20)
|
||||||
|
handleVShareLink(names, urlVLess, scheme, vless)
|
||||||
vless["name"] = name
|
if flow := query.Get("flow"); flow != "" {
|
||||||
vless["type"] = scheme
|
vless["flow"] = strings.ToLower(flow)
|
||||||
vless["server"] = urlVless.Hostname()
|
|
||||||
vless["port"] = urlVless.Port()
|
|
||||||
vless["uuid"] = urlVless.User.Username()
|
|
||||||
vless["udp"] = true
|
|
||||||
vless["skip-cert-verify"] = false
|
|
||||||
|
|
||||||
sni := query.Get("sni")
|
|
||||||
if sni != "" {
|
|
||||||
vless["servername"] = sni
|
|
||||||
}
|
}
|
||||||
|
|
||||||
flow := strings.ToLower(query.Get("flow"))
|
|
||||||
if flow != "" {
|
|
||||||
vless["flow"] = flow
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(query.Get("type"))
|
|
||||||
if network != "" {
|
|
||||||
fakeType := strings.ToLower(query.Get("headerType"))
|
|
||||||
if network == "tcp" && fakeType == "http" {
|
|
||||||
network = "http"
|
|
||||||
}
|
|
||||||
if network == "http" {
|
|
||||||
network = "h2"
|
|
||||||
}
|
|
||||||
vless["network"] = network
|
|
||||||
}
|
|
||||||
|
|
||||||
switch network {
|
|
||||||
case "http":
|
|
||||||
headers := make(map[string]any)
|
|
||||||
httpOpts := make(map[string]any)
|
|
||||||
|
|
||||||
if query.Get("method") != "" {
|
|
||||||
httpOpts["method"] = query.Get("method")
|
|
||||||
}
|
|
||||||
if query.Get("path") != "" {
|
|
||||||
httpOpts["path"] = query.Get("path")
|
|
||||||
}
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
httpOpts["headers"] = headers
|
|
||||||
|
|
||||||
vless["http-opts"] = httpOpts
|
|
||||||
|
|
||||||
case "h2":
|
|
||||||
headers := make(map[string]any)
|
|
||||||
h2Opts := make(map[string]any)
|
|
||||||
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
h2Opts["path"] = query.Get("path")
|
|
||||||
h2Opts["headers"] = headers
|
|
||||||
|
|
||||||
vless["h2-opts"] = h2Opts
|
|
||||||
|
|
||||||
case "ws":
|
|
||||||
headers := make(map[string]any)
|
|
||||||
wsOpts := make(map[string]any)
|
|
||||||
|
|
||||||
// headers["Host"] = RandHost()
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
wsOpts["path"] = query.Get("path")
|
|
||||||
wsOpts["headers"] = headers
|
|
||||||
|
|
||||||
vless["ws-opts"] = wsOpts
|
|
||||||
|
|
||||||
case "grpc":
|
|
||||||
grpcOpts := make(map[string]any)
|
|
||||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
|
||||||
vless["grpc-opts"] = grpcOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, vless)
|
proxies = append(proxies, vless)
|
||||||
|
|
||||||
case "vmess":
|
case "vmess":
|
||||||
dcBuf, err := enc.DecodeString(body)
|
// 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 {
|
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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -239,26 +171,34 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
vmess["server"] = values["add"]
|
vmess["server"] = values["add"]
|
||||||
vmess["port"] = values["port"]
|
vmess["port"] = values["port"]
|
||||||
vmess["uuid"] = values["id"]
|
vmess["uuid"] = values["id"]
|
||||||
vmess["alterId"] = values["aid"]
|
if alterId, ok := values["aid"]; ok {
|
||||||
vmess["cipher"] = "auto"
|
vmess["alterId"] = alterId
|
||||||
|
} else {
|
||||||
|
vmess["alterId"] = 0
|
||||||
|
}
|
||||||
vmess["udp"] = true
|
vmess["udp"] = true
|
||||||
|
vmess["tls"] = false
|
||||||
vmess["skip-cert-verify"] = false
|
vmess["skip-cert-verify"] = false
|
||||||
|
|
||||||
sni := values["sni"]
|
vmess["cipher"] = "auto"
|
||||||
if sni != "" {
|
if cipher, ok := values["scy"]; ok && cipher != "" {
|
||||||
vmess["sni"] = sni
|
vmess["cipher"] = cipher
|
||||||
}
|
}
|
||||||
|
|
||||||
host := values["host"]
|
if sni, ok := values["sni"]; ok && sni != "" {
|
||||||
network := strings.ToLower(values["net"].(string))
|
vmess["servername"] = sni
|
||||||
|
}
|
||||||
|
|
||||||
|
network := strings.ToLower(values["net"].(string))
|
||||||
|
if values["type"] == "http" {
|
||||||
|
network = "http"
|
||||||
|
} else if network == "http" {
|
||||||
|
network = "h2"
|
||||||
|
}
|
||||||
vmess["network"] = network
|
vmess["network"] = network
|
||||||
|
|
||||||
tls := strings.ToLower(values["tls"].(string))
|
tls := strings.ToLower(values["tls"].(string))
|
||||||
if tls != "" && tls != "0" && tls != "null" {
|
if strings.HasSuffix(tls, "tls") {
|
||||||
if host != nil {
|
|
||||||
vmess["servername"] = host
|
|
||||||
}
|
|
||||||
vmess["tls"] = true
|
vmess["tls"] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -266,11 +206,13 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
case "http":
|
case "http":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
httpOpts := make(map[string]any)
|
httpOpts := make(map[string]any)
|
||||||
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
// headers["Host"] = RandHost()
|
headers["Host"] = []string{host.(string)}
|
||||||
headers["User-Agent"] = RandUserAgent()
|
}
|
||||||
httpOpts["method"] = values["method"]
|
httpOpts["path"] = []string{"/"}
|
||||||
httpOpts["path"] = values["path"]
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
|
httpOpts["path"] = []string{path.(string)}
|
||||||
|
}
|
||||||
httpOpts["headers"] = headers
|
httpOpts["headers"] = headers
|
||||||
|
|
||||||
vmess["http-opts"] = httpOpts
|
vmess["http-opts"] = httpOpts
|
||||||
@ -278,9 +220,10 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
case "h2":
|
case "h2":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
h2Opts := make(map[string]any)
|
h2Opts := make(map[string]any)
|
||||||
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
|
headers["Host"] = []string{host.(string)}
|
||||||
|
}
|
||||||
|
|
||||||
// headers["Host"] = RandHost()
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
h2Opts["path"] = values["path"]
|
h2Opts["path"] = values["path"]
|
||||||
h2Opts["headers"] = headers
|
h2Opts["headers"] = headers
|
||||||
|
|
||||||
@ -289,15 +232,14 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
case "ws":
|
case "ws":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
|
wsOpts["path"] = []string{"/"}
|
||||||
headers["Host"] = RandHost()
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
headers["User-Agent"] = RandUserAgent()
|
headers["Host"] = host.(string)
|
||||||
|
}
|
||||||
if values["path"] != nil {
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
wsOpts["path"] = values["path"]
|
wsOpts["path"] = path.(string)
|
||||||
}
|
}
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
vmess["ws-opts"] = wsOpts
|
vmess["ws-opts"] = wsOpts
|
||||||
|
|
||||||
case "grpc":
|
case "grpc":
|
||||||
@ -318,7 +260,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
port := urlSS.Port()
|
port := urlSS.Port()
|
||||||
|
|
||||||
if port == "" {
|
if port == "" {
|
||||||
dcBuf, err := enc.DecodeString(urlSS.Host)
|
dcBuf, err := encRaw.DecodeString(urlSS.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -335,18 +277,17 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
if password, found = urlSS.User.Password(); !found {
|
if password, found = urlSS.User.Password(); !found {
|
||||||
dcBuf, err := enc.DecodeString(cipher)
|
dcBuf, _ := enc.DecodeString(cipher)
|
||||||
if err != nil {
|
if !strings.Contains(string(dcBuf), "2022-blake3") {
|
||||||
continue
|
dcBuf, _ = encRaw.DecodeString(cipher)
|
||||||
}
|
}
|
||||||
|
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||||
if !found {
|
if !found {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ss := make(map[string]any, 20)
|
ss := make(map[string]any, 10)
|
||||||
|
|
||||||
ss["name"] = name
|
ss["name"] = name
|
||||||
ss["type"] = scheme
|
ss["type"] = scheme
|
||||||
@ -354,11 +295,22 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
ss["port"] = urlSS.Port()
|
ss["port"] = urlSS.Port()
|
||||||
ss["cipher"] = cipher
|
ss["cipher"] = cipher
|
||||||
ss["password"] = password
|
ss["password"] = password
|
||||||
|
query := urlSS.Query()
|
||||||
ss["udp"] = true
|
ss["udp"] = true
|
||||||
|
if query.Get("udp-over-tcp") == "true" || query.Get("uot") == "1" {
|
||||||
|
ss["udp-over-tcp"] = true
|
||||||
|
}
|
||||||
|
if strings.Contains(query.Get("plugin"), "obfs") {
|
||||||
|
obfsParams := strings.Split(query.Get("plugin"), ";")
|
||||||
|
ss["plugin"] = "obfs"
|
||||||
|
ss["plugin-opts"] = map[string]any{
|
||||||
|
"host": obfsParams[2][10:],
|
||||||
|
"mode": obfsParams[1][5:],
|
||||||
|
}
|
||||||
|
}
|
||||||
proxies = append(proxies, ss)
|
proxies = append(proxies, ss)
|
||||||
case "ssr":
|
case "ssr":
|
||||||
dcBuf, err := enc.DecodeString(body)
|
dcBuf, err := encRaw.DecodeString(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -425,18 +377,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
return proxies, nil
|
return proxies, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func urlSafe(data string) string {
|
|
||||||
return strings.ReplaceAll(strings.ReplaceAll(data, "+", "-"), "/", "_")
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeUrlSafe(data string) string {
|
|
||||||
dcBuf, err := base64.URLEncoding.DecodeString(data)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return string(dcBuf)
|
|
||||||
}
|
|
||||||
|
|
||||||
func uniqueName(names map[string]int, name string) string {
|
func uniqueName(names map[string]int, name string) string {
|
||||||
if index, ok := names[name]; ok {
|
if index, ok := names[name]; ok {
|
||||||
index++
|
index++
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
@ -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
|
||||||
}
|
}
|
||||||
|
@ -6,16 +6,10 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"math/bits"
|
"math/bits"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var defaultAllocator = NewAllocator()
|
var defaultAllocator = NewAllocator()
|
||||||
|
|
||||||
func init() {
|
|
||||||
buf.DefaultAllocator = defaultAllocator
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
||||||
type Allocator struct {
|
type Allocator struct {
|
||||||
buffers []sync.Pool
|
buffers []sync.Pool
|
||||||
|
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
|
||||||
|
}
|
@ -1,10 +1,9 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
"reflect"
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestUUIDMap(t *testing.T) {
|
func TestUUIDMap(t *testing.T) {
|
||||||
|
@ -8,6 +8,7 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
"github.com/Dreamacro/clash/component/iface"
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
|
|
||||||
"github.com/insomniacslk/dhcp/dhcpv4"
|
"github.com/insomniacslk/dhcp/dhcpv4"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -6,6 +6,7 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/iface"
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
|
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -4,11 +4,12 @@ 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 (
|
||||||
@ -17,6 +18,8 @@ var (
|
|||||||
actualDualStackDialContext = dualStackDialContext
|
actualDualStackDialContext = dualStackDialContext
|
||||||
tcpConcurrent = false
|
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) {
|
||||||
@ -33,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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -105,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))
|
||||||
@ -167,7 +180,10 @@ 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
|
||||||
|
for i := 0; i < count; i++ {
|
||||||
|
select {
|
||||||
|
case res := <-results:
|
||||||
if res.error == nil {
|
if res.error == nil {
|
||||||
return res.Conn, nil
|
return res.Conn, nil
|
||||||
}
|
}
|
||||||
@ -187,9 +203,12 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
return nil, primary.error
|
return nil, primary.error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, errors.New("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) {
|
||||||
@ -199,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -217,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 {
|
||||||
@ -248,17 +289,48 @@ 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
|
||||||
|
for i := 0; i < connCount; i++ {
|
||||||
|
select {
|
||||||
|
case res := <-results:
|
||||||
if res.error == nil {
|
if res.error == nil {
|
||||||
|
if res.isPrimary {
|
||||||
return res.Conn, nil
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
if connCount == 0 {
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if primaryError != nil {
|
||||||
|
return nil, primaryError
|
||||||
|
}
|
||||||
|
|
||||||
|
if fallback.error != nil {
|
||||||
|
return nil, fallback.error
|
||||||
|
}
|
||||||
|
|
||||||
return nil, fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
return nil, fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -291,26 +363,46 @@ 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 {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
if !opt.direct {
|
if !opt.direct {
|
||||||
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
||||||
} else {
|
} else {
|
||||||
ips, err = resolver.ResolveAllIPv4(host)
|
ips, err = resolver.ResolveAllIPv4(host)
|
||||||
}
|
}
|
||||||
default:
|
|
||||||
if !opt.direct {
|
if err != nil {
|
||||||
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
return nil, err
|
||||||
} else {
|
}
|
||||||
ips, err = resolver.ResolveAllIPv6(host)
|
|
||||||
}
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func concurrentIPv6DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
if !opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPv6(host)
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -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
|
||||||
|
}
|
137
component/ebpf/ebpf_linux.go
Normal file
137
component/ebpf/ebpf_linux.go
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
//go:build !android
|
||||||
|
|
||||||
|
package ebpf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
"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"
|
||||||
|
"github.com/sagernet/netlink"
|
||||||
|
)
|
||||||
|
|
||||||
|
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/sagernet/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/sagernet/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")
|
||||||
|
}
|
@ -34,7 +34,7 @@ type Pool struct {
|
|||||||
offset netip.Addr
|
offset netip.Addr
|
||||||
cycle bool
|
cycle bool
|
||||||
mux sync.Mutex
|
mux sync.Mutex
|
||||||
host *trie.DomainTrie[bool]
|
host *trie.DomainTrie[struct{}]
|
||||||
ipnet *netip.Prefix
|
ipnet *netip.Prefix
|
||||||
store store
|
store store
|
||||||
}
|
}
|
||||||
@ -150,7 +150,7 @@ func (p *Pool) restoreState() {
|
|||||||
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
IPNet *netip.Prefix
|
IPNet *netip.Prefix
|
||||||
Host *trie.DomainTrie[bool]
|
Host *trie.DomainTrie[struct{}]
|
||||||
|
|
||||||
// Size sets the maximum number of entries in memory
|
// Size sets the maximum number of entries in memory
|
||||||
// and does not work if Persistence is true
|
// and does not work if Persistence is true
|
||||||
@ -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)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -9,6 +9,7 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/component/profile/cachefile"
|
"github.com/Dreamacro/clash/component/profile/cachefile"
|
||||||
"github.com/Dreamacro/clash/component/trie"
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"go.etcd.io/bbolt"
|
"go.etcd.io/bbolt"
|
||||||
)
|
)
|
||||||
@ -61,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")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -89,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")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -115,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")
|
||||||
@ -127,8 +128,8 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
|
|
||||||
func TestPool_Skip(t *testing.T) {
|
func TestPool_Skip(t *testing.T) {
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
||||||
tree := trie.New[bool]()
|
tree := trie.New[struct{}]()
|
||||||
tree.Insert("example.com", true)
|
tree.Insert("example.com", struct{}{})
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
IPNet: &ipnet,
|
IPNet: &ipnet,
|
||||||
Size: 10,
|
Size: 10,
|
||||||
@ -197,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,
|
||||||
|
@ -3,10 +3,10 @@ package geodata
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
@ -329,6 +329,7 @@ func NewGeoIPMatcher(geoip *GeoIP) (*GeoIPMatcher, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *MultiGeoIPMatcher) ApplyIp(ip net.IP) bool {
|
func (m *MultiGeoIPMatcher) ApplyIp(ip net.IP) bool {
|
||||||
|
|
||||||
for _, matcher := range m.matchers {
|
for _, matcher := range m.matchers {
|
||||||
if matcher.Match(ip) {
|
if matcher.Match(ip) {
|
||||||
return true
|
return true
|
||||||
|
@ -7,11 +7,10 @@
|
|||||||
package router
|
package router
|
||||||
|
|
||||||
import (
|
import (
|
||||||
reflect "reflect"
|
|
||||||
sync "sync"
|
|
||||||
|
|
||||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||||
|
reflect "reflect"
|
||||||
|
sync "sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/geodata"
|
"github.com/Dreamacro/clash/component/geodata"
|
||||||
"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"
|
||||||
|
|
||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -2,7 +2,6 @@ package geodata
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"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"
|
||||||
)
|
)
|
||||||
|
@ -2,15 +2,14 @@ package http
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"github.com/Dreamacro/clash/component/tls"
|
||||||
|
"github.com/Dreamacro/clash/listener/inner"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
URL "net/url"
|
URL "net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/listener/inner"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -53,12 +52,13 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
|||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
log.Infoln(urlRes.String())
|
|
||||||
conn := inner.HandleTcp(address, urlRes.Hostname())
|
conn := inner.HandleTcp(address, urlRes.Hostname())
|
||||||
return conn, nil
|
return conn, nil
|
||||||
},
|
},
|
||||||
|
TLSClientConfig: tls.GetDefaultTLSConfig(),
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
client := http.Client{Transport: transport}
|
||||||
return client.Do(req)
|
return client.Do(req)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
package mmdb
|
package mmdb
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/oschwald/geoip2-golang"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/oschwald/geoip2-golang"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -2,19 +2,13 @@ package process
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrInvalidNetwork = errors.New("invalid network")
|
ErrInvalidNetwork = errors.New("invalid network")
|
||||||
ErrPlatformNotSupport = errors.New("not support on this platform")
|
ErrPlatformNotSupport = errors.New("not support on this platform")
|
||||||
ErrNotFound = errors.New("process not found")
|
ErrNotFound = errors.New("process not found")
|
||||||
|
|
||||||
enableFindProcess = true
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -22,10 +16,6 @@ const (
|
|||||||
UDP = "udp"
|
UDP = "udp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func EnableFindProcess(e bool) {
|
|
||||||
enableFindProcess = e
|
|
||||||
}
|
|
||||||
|
|
||||||
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (int32, string, error) {
|
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (int32, string, error) {
|
||||||
return findProcessName(network, srcIP, srcPort)
|
return findProcessName(network, srcIP, srcPort)
|
||||||
}
|
}
|
||||||
@ -37,51 +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 !enableFindProcess ||
|
|
||||||
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,10 +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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -16,6 +17,22 @@ 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
|
||||||
}
|
}
|
||||||
@ -39,16 +56,13 @@ func findProcessName(network string, ip netip.Addr, port int) (int32, string, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
@ -62,28 +76,39 @@ func findProcessName(network string, ip netip.Addr, port int) (int32, string, er
|
|||||||
// 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
|
// xsocket_n.so_last_pid
|
||||||
pid := readNativeUint32(buf[so+68 : so+72])
|
pid := readNativeUint32(buf[so+68 : so+72])
|
||||||
pp, err := getExecPathFromPID(pid)
|
pp, err := getExecPathFromPID(pid)
|
||||||
return -1, pp, err
|
return -1, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// udp packet connection may be not equal with srcIP
|
||||||
|
if network == UDP && srcIP.IsUnspecified() && isIPv4 == srcIsIPv4 {
|
||||||
|
fallbackUDPProcess, _ = getExecPathFromPID(readNativeUint32(buf[so+68 : so+72]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if network == UDP && fallbackUDPProcess != "" {
|
||||||
|
return -1, fallbackUDPProcess, nil
|
||||||
|
}
|
||||||
|
|
||||||
return -1, "", ErrNotFound
|
return -1, "", ErrNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -39,6 +39,7 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return -1, "", err
|
return -1, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
pp, err := resolveProcessNameByProcSearch(inode, uid)
|
pp, err := resolveProcessNameByProcSearch(inode, uid)
|
||||||
return uid, pp, err
|
return uid, pp, err
|
||||||
}
|
}
|
||||||
@ -110,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)
|
||||||
}
|
}
|
||||||
@ -197,7 +198,6 @@ func resolveProcessNameByProcSearch(inode, uid int32) (string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if runtime.GOOS == "android" {
|
if runtime.GOOS == "android" {
|
||||||
if bytes.Equal(buffer[:n], socket) {
|
if bytes.Equal(buffer[:n], socket) {
|
||||||
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
|
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
|
||||||
|
@ -9,6 +9,7 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"golang.org/x/sys/windows"
|
"golang.org/x/sys/windows"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -8,6 +8,7 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/profile"
|
"github.com/Dreamacro/clash/component/profile"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"go.etcd.io/bbolt"
|
"go.etcd.io/bbolt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -95,7 +94,6 @@ func ResolveIPv4ProxyServerHost(host string) (netip.Addr, error) {
|
|||||||
return ip, nil
|
return ip, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ResolveIPv4(host)
|
return ResolveIPv4(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -108,7 +106,6 @@ func ResolveIPv6ProxyServerHost(host string) (netip.Addr, error) {
|
|||||||
return ip, nil
|
return ip, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ResolveIPv6(host)
|
return ResolveIPv6(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -121,7 +118,6 @@ func ResolveProxyServerHost(host string) (netip.Addr, error) {
|
|||||||
return ip, err
|
return ip, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ResolveIP(host)
|
return ResolveIP(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -131,7 +127,7 @@ func ResolveAllIPv6WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
if ip := node.Data; ip.Is6() {
|
if ip := node.Data(); ip.Is6() {
|
||||||
return []netip.Addr{ip}, nil
|
return []netip.Addr{ip}, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -158,22 +154,29 @@ func ResolveAllIPv6WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
return []netip.Addr{}, ErrIPNotFound
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
return []netip.Addr{netip.AddrFrom16(*(*[16]byte)(ipAddrs[rand.Intn(len(ipAddrs))]))}, nil
|
addrs := make([]netip.Addr, 0, len(ipAddrs))
|
||||||
|
for _, ipAddr := range ipAddrs {
|
||||||
|
addrs = append(addrs, nnip.IpToAddr(ipAddr))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
rand.Shuffle(len(addrs), func(i, j int) {
|
||||||
|
addrs[i], addrs[j] = addrs[j], addrs[i]
|
||||||
|
})
|
||||||
|
return addrs, nil
|
||||||
|
}
|
||||||
return []netip.Addr{}, ErrIPNotFound
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResolveAllIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
func ResolveAllIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
if ip := node.Data; ip.Is4() {
|
if ip := node.Data(); ip.Is4() {
|
||||||
return []netip.Addr{node.Data}, nil
|
return []netip.Addr{node.Data()}, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
@ -193,20 +196,27 @@ func ResolveAllIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
|||||||
return []netip.Addr{}, ErrIPNotFound
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := ipAddrs[rand.Intn(len(ipAddrs))].To4()
|
addrs := make([]netip.Addr, 0, len(ipAddrs))
|
||||||
if ip == nil {
|
for _, ipAddr := range ipAddrs {
|
||||||
return []netip.Addr{}, ErrIPVersion
|
addrs = append(addrs, nnip.IpToAddr(ipAddr))
|
||||||
}
|
}
|
||||||
|
|
||||||
return []netip.Addr{netip.AddrFrom4(*(*[4]byte)(ip))}, nil
|
rand.Shuffle(len(addrs), func(i, j int) {
|
||||||
|
addrs[i], addrs[j] = addrs[j], addrs[i]
|
||||||
|
})
|
||||||
|
return addrs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return []netip.Addr{}, ErrIPNotFound
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResolveAllIPWithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
func ResolveAllIPWithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
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 {
|
||||||
@ -219,52 +229,23 @@ 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)
|
ipAddrs, err := net.DefaultResolver.LookupIP(context.Background(), "ip", host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return []netip.Addr{}, err
|
return []netip.Addr{}, err
|
||||||
}
|
} else if len(ipAddrs) == 0 {
|
||||||
|
|
||||||
return []netip.Addr{nnip.IpToAddr(ipAddr.IP)}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return []netip.Addr{}, ErrIPNotFound
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
addrs := make([]netip.Addr, 0, len(ipAddrs))
|
||||||
func ResolveAllIPPrimaryIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
for _, ipAddr := range ipAddrs {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
addrs = append(addrs, nnip.IpToAddr(ipAddr))
|
||||||
return []netip.Addr{node.Data}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if r != nil {
|
rand.Shuffle(len(addrs), func(i, j int) {
|
||||||
if DisableIPv6 {
|
addrs[i], addrs[j] = addrs[j], addrs[i]
|
||||||
return r.ResolveAllIPv4(host)
|
})
|
||||||
|
return addrs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -284,7 +265,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -292,7 +272,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -300,6 +279,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)
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package provider
|
package resource
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@ -16,45 +16,49 @@ var (
|
|||||||
dirMode os.FileMode = 0o755
|
dirMode os.FileMode = 0o755
|
||||||
)
|
)
|
||||||
|
|
||||||
type parser[V any] func([]byte) (V, error)
|
type Parser[V any] func([]byte) (V, error)
|
||||||
|
|
||||||
type fetcher[V any] struct {
|
type Fetcher[V any] struct {
|
||||||
|
resourceType string
|
||||||
name string
|
name string
|
||||||
vehicle types.Vehicle
|
vehicle types.Vehicle
|
||||||
updatedAt *time.Time
|
UpdatedAt *time.Time
|
||||||
ticker *time.Ticker
|
ticker *time.Ticker
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
hash [16]byte
|
hash [16]byte
|
||||||
parser parser[V]
|
parser Parser[V]
|
||||||
interval time.Duration
|
interval time.Duration
|
||||||
onUpdate func(V)
|
OnUpdate func(V)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) Name() string {
|
func (f *Fetcher[V]) Name() string {
|
||||||
return f.name
|
return f.name
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) VehicleType() types.VehicleType {
|
func (f *Fetcher[V]) Vehicle() types.Vehicle {
|
||||||
|
return f.vehicle
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher[V]) VehicleType() types.VehicleType {
|
||||||
return f.vehicle.Type()
|
return f.vehicle.Type()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) Initial() (V, error) {
|
func (f *Fetcher[V]) Initial() (V, error) {
|
||||||
var (
|
var (
|
||||||
buf []byte
|
buf []byte
|
||||||
err error
|
err error
|
||||||
isLocal bool
|
isLocal bool
|
||||||
|
forceUpdate bool
|
||||||
)
|
)
|
||||||
|
|
||||||
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
||||||
buf, err = os.ReadFile(f.vehicle.Path())
|
buf, err = os.ReadFile(f.vehicle.Path())
|
||||||
modTime := stat.ModTime()
|
modTime := stat.ModTime()
|
||||||
f.updatedAt = &modTime
|
f.UpdatedAt = &modTime
|
||||||
isLocal = true
|
isLocal = true
|
||||||
if f.interval != 0 && modTime.Add(f.interval).Before(time.Now()) {
|
if f.interval != 0 && modTime.Add(f.interval).Before(time.Now()) {
|
||||||
defer func() {
|
log.Infoln("[Provider] %s not updated for a long time, force refresh", f.Name())
|
||||||
log.Infoln("[Provider] %s's proxies not updated for a long time, force refresh", f.Name())
|
forceUpdate = true
|
||||||
go f.Update()
|
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
buf, err = f.vehicle.Read()
|
buf, err = f.vehicle.Read()
|
||||||
@ -64,7 +68,21 @@ func (f *fetcher[V]) Initial() (V, error) {
|
|||||||
return getZero[V](), err
|
return getZero[V](), err
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies, err := f.parser(buf)
|
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 err != nil {
|
||||||
if !isLocal {
|
if !isLocal {
|
||||||
return getZero[V](), err
|
return getZero[V](), err
|
||||||
@ -76,7 +94,7 @@ func (f *fetcher[V]) Initial() (V, error) {
|
|||||||
return getZero[V](), err
|
return getZero[V](), err
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies, err = f.parser(buf)
|
contents, err = f.parser(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), err
|
return getZero[V](), err
|
||||||
}
|
}
|
||||||
@ -92,15 +110,15 @@ func (f *fetcher[V]) Initial() (V, error) {
|
|||||||
|
|
||||||
f.hash = md5.Sum(buf)
|
f.hash = md5.Sum(buf)
|
||||||
|
|
||||||
// pull proxies automatically
|
// pull contents automatically
|
||||||
if f.ticker != nil {
|
if f.ticker != nil {
|
||||||
go f.pullLoop()
|
go f.pullLoop()
|
||||||
}
|
}
|
||||||
|
|
||||||
return proxies, nil
|
return contents, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) Update() (V, bool, error) {
|
func (f *Fetcher[V]) Update() (V, bool, error) {
|
||||||
buf, err := f.vehicle.Read()
|
buf, err := f.vehicle.Read()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), false, err
|
return getZero[V](), false, err
|
||||||
@ -109,12 +127,12 @@ func (f *fetcher[V]) Update() (V, bool, error) {
|
|||||||
now := time.Now()
|
now := time.Now()
|
||||||
hash := md5.Sum(buf)
|
hash := md5.Sum(buf)
|
||||||
if bytes.Equal(f.hash[:], hash[:]) {
|
if bytes.Equal(f.hash[:], hash[:]) {
|
||||||
f.updatedAt = &now
|
f.UpdatedAt = &now
|
||||||
os.Chtimes(f.vehicle.Path(), now, now)
|
_ = os.Chtimes(f.vehicle.Path(), now, now)
|
||||||
return getZero[V](), true, nil
|
return getZero[V](), true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies, err := f.parser(buf)
|
contents, err := f.parser(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), false, err
|
return getZero[V](), false, err
|
||||||
}
|
}
|
||||||
@ -125,20 +143,20 @@ func (f *fetcher[V]) Update() (V, bool, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
f.updatedAt = &now
|
f.UpdatedAt = &now
|
||||||
f.hash = hash
|
f.hash = hash
|
||||||
|
|
||||||
return proxies, false, nil
|
return contents, false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) Destroy() error {
|
func (f *Fetcher[V]) Destroy() error {
|
||||||
if f.ticker != nil {
|
if f.ticker != nil {
|
||||||
f.done <- struct{}{}
|
f.done <- struct{}{}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) pullLoop() {
|
func (f *Fetcher[V]) pullLoop() {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-f.ticker.C:
|
case <-f.ticker.C:
|
||||||
@ -149,13 +167,13 @@ func (f *fetcher[V]) pullLoop() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if same {
|
if same {
|
||||||
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
|
log.Debugln("[Provider] %s's content doesn't change", f.Name())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Infoln("[Provider] %s's proxies update", f.Name())
|
log.Infoln("[Provider] %s's content update", f.Name())
|
||||||
if f.onUpdate != nil {
|
if f.OnUpdate != nil {
|
||||||
f.onUpdate(elm)
|
f.OnUpdate(elm)
|
||||||
}
|
}
|
||||||
case <-f.done:
|
case <-f.done:
|
||||||
f.ticker.Stop()
|
f.ticker.Stop()
|
||||||
@ -176,19 +194,20 @@ func safeWrite(path string, buf []byte) error {
|
|||||||
return os.WriteFile(path, buf, fileMode)
|
return os.WriteFile(path, buf, fileMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser parser[V], onUpdate func(V)) *fetcher[V] {
|
func NewFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
|
||||||
var ticker *time.Ticker
|
var ticker *time.Ticker
|
||||||
if interval != 0 {
|
if interval != 0 {
|
||||||
ticker = time.NewTicker(interval)
|
ticker = time.NewTicker(interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &fetcher[V]{
|
return &Fetcher[V]{
|
||||||
name: name,
|
name: name,
|
||||||
ticker: ticker,
|
ticker: ticker,
|
||||||
vehicle: vehicle,
|
vehicle: vehicle,
|
||||||
parser: parser,
|
parser: parser,
|
||||||
done: make(chan struct{}, 1),
|
done: make(chan struct{}, 1),
|
||||||
onUpdate: onUpdate,
|
OnUpdate: onUpdate,
|
||||||
|
interval: interval,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,14 +1,13 @@
|
|||||||
package provider
|
package resource
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
netHttp "github.com/Dreamacro/clash/component/http"
|
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type FileVehicle struct {
|
type FileVehicle struct {
|
||||||
@ -36,6 +35,10 @@ type HTTPVehicle struct {
|
|||||||
path string
|
path string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Url() string {
|
||||||
|
return h.url
|
||||||
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Type() types.VehicleType {
|
func (h *HTTPVehicle) Type() types.VehicleType {
|
||||||
return types.HTTP
|
return types.HTTP
|
||||||
}
|
}
|
||||||
@ -47,7 +50,7 @@ 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)
|
resp, err := clashHttp.HttpRequest(ctx, h.url, http.MethodGet, nil, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
@ -2,14 +2,16 @@ package sniffer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
N "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"
|
"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/constant/sniffer"
|
||||||
@ -22,27 +24,30 @@ var (
|
|||||||
ErrNoClue = errors.New("not enough information for making a decision")
|
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 []sniffer.Sniffer
|
sniffers []sniffer.Sniffer
|
||||||
|
|
||||||
foreDomain *trie.DomainTrie[bool]
|
forceDomain *trie.DomainTrie[struct{}]
|
||||||
skipSNI *trie.DomainTrie[bool]
|
skipSNI *trie.DomainTrie[struct{}]
|
||||||
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")
|
||||||
@ -61,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 {
|
||||||
@ -70,36 +85,51 @@ 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) {
|
||||||
|
dstIP := ""
|
||||||
|
if metadata.DstIP.IsValid() {
|
||||||
|
dstIP = metadata.DstIP.String()
|
||||||
|
}
|
||||||
|
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]",
|
log.Debugln("[Sniffer] Sniff TCP [%s:%s]-->[%s:%s] success, replace domain [%s]-->[%s]",
|
||||||
metadata.SrcIP, metadata.SrcPort,
|
metadata.SrcIP, metadata.SrcPort,
|
||||||
metadata.DstIP, metadata.DstPort,
|
dstIP, metadata.DstPort,
|
||||||
metadata.Host, host)
|
metadata.Host, host)
|
||||||
|
}
|
||||||
|
|
||||||
metadata.AddrType = C.AtypDomainName
|
|
||||||
metadata.Host = host
|
metadata.Host = host
|
||||||
metadata.DNSMode = C.DNSMapping
|
metadata.DNSMode = C.DNSNormal
|
||||||
resolver.InsertHostByIP(metadata.DstIP, host)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
|
sd.cacheSniffFailed(metadata)
|
||||||
log.Errorln("[Sniffer] [%s] may not have any sent data, Consider adding skip", metadata.DstIP.String())
|
log.Errorln("[Sniffer] [%s] may not have any sent data, Consider adding skip", metadata.DstIP.String())
|
||||||
_ = conn.Close()
|
_ = conn.Close()
|
||||||
}
|
}
|
||||||
@ -114,15 +144,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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = netip.ParseAddr(host)
|
_, err = netip.ParseAddr(host)
|
||||||
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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -133,6 +163,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,
|
||||||
@ -141,24 +182,27 @@ func NewCloseSnifferDispatcher() (*SnifferDispatcher, error) {
|
|||||||
return &dispatcher, nil
|
return &dispatcher, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSnifferDispatcher(needSniffer []sniffer.Type, forceDomain *trie.DomainTrie[bool],
|
func NewSnifferDispatcher(needSniffer []sniffer.Type, forceDomain *trie.DomainTrie[struct{}],
|
||||||
skipSNI *trie.DomainTrie[bool], ports *[]utils.Range[uint16],
|
skipSNI *trie.DomainTrie[struct{}], ports *[]utils.Range[uint16],
|
||||||
) (*SnifferDispatcher, error) {
|
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
|
||||||
|
@ -3,6 +3,7 @@ package sniffer
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@ -89,13 +90,32 @@ func SniffHTTP(b []byte) (*string, error) {
|
|||||||
host, _, err := net.SplitHostPort(rawHost)
|
host, _, err := net.SplitHostPort(rawHost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
|
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
|
||||||
host = rawHost
|
return parseHost(rawHost)
|
||||||
} else {
|
} else {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if net.ParseIP(host) != nil {
|
||||||
|
return nil, fmt.Errorf("host is ip")
|
||||||
|
}
|
||||||
|
|
||||||
return &host, nil
|
return &host, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, ErrNoClue
|
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
|
||||||
|
}
|
||||||
|
@ -1,3 +1,3 @@
|
|||||||
package sniffer
|
package sniffer
|
||||||
|
|
||||||
// TODO
|
//TODO
|
||||||
|
@ -13,7 +13,8 @@ var (
|
|||||||
errNotClientHello = errors.New("not client hello")
|
errNotClientHello = errors.New("not client hello")
|
||||||
)
|
)
|
||||||
|
|
||||||
type TLSSniffer struct{}
|
type TLSSniffer struct {
|
||||||
|
}
|
||||||
|
|
||||||
func (tls *TLSSniffer) Protocol() string {
|
func (tls *TLSSniffer) Protocol() string {
|
||||||
return "tls"
|
return "tls"
|
||||||
|
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
|
||||||
|
}
|
@ -17,7 +17,7 @@ var ErrInvalidDomain = errors.New("invalid domain")
|
|||||||
|
|
||||||
// DomainTrie contains the main logic for adding and searching nodes for domain segments.
|
// DomainTrie contains the main logic for adding and searching nodes for domain segments.
|
||||||
// support wildcard domain (e.g *.google.com)
|
// support wildcard domain (e.g *.google.com)
|
||||||
type DomainTrie[T comparable] struct {
|
type DomainTrie[T any] struct {
|
||||||
root *Node[T]
|
root *Node[T]
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,13 +74,13 @@ func (t *DomainTrie[T]) insert(parts []string, data T) {
|
|||||||
for i := len(parts) - 1; i >= 0; i-- {
|
for i := len(parts) - 1; i >= 0; i-- {
|
||||||
part := parts[i]
|
part := parts[i]
|
||||||
if !node.hasChild(part) {
|
if !node.hasChild(part) {
|
||||||
node.addChild(part, newNode(getZero[T]()))
|
node.addChild(part, newNode[T]())
|
||||||
}
|
}
|
||||||
|
|
||||||
node = node.getChild(part)
|
node = node.getChild(part)
|
||||||
}
|
}
|
||||||
|
|
||||||
node.Data = data
|
node.setData(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Search is the most important part of the Trie.
|
// Search is the most important part of the Trie.
|
||||||
@ -96,7 +96,7 @@ func (t *DomainTrie[T]) Search(domain string) *Node[T] {
|
|||||||
|
|
||||||
n := t.search(t.root, parts)
|
n := t.search(t.root, parts)
|
||||||
|
|
||||||
if n == nil || n.Data == getZero[T]() {
|
if n.isEmpty() {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,13 +109,13 @@ func (t *DomainTrie[T]) search(node *Node[T], parts []string) *Node[T] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if c := node.getChild(parts[len(parts)-1]); c != nil {
|
if c := node.getChild(parts[len(parts)-1]); c != nil {
|
||||||
if n := t.search(c, parts[:len(parts)-1]); n != nil && n.Data != getZero[T]() {
|
if n := t.search(c, parts[:len(parts)-1]); !n.isEmpty() {
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if c := node.getChild(wildcard); c != nil {
|
if c := node.getChild(wildcard); c != nil {
|
||||||
if n := t.search(c, parts[:len(parts)-1]); n != nil && n.Data != getZero[T]() {
|
if n := t.search(c, parts[:len(parts)-1]); !n.isEmpty() {
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -124,6 +124,6 @@ func (t *DomainTrie[T]) search(node *Node[T], parts []string) *Node[T] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New returns a new, empty Trie.
|
// New returns a new, empty Trie.
|
||||||
func New[T comparable]() *DomainTrie[T] {
|
func New[T any]() *DomainTrie[T] {
|
||||||
return &DomainTrie[T]{root: newNode[T](getZero[T]())}
|
return &DomainTrie[T]{root: newNode[T]()}
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,7 @@ func TestTrie_Basic(t *testing.T) {
|
|||||||
|
|
||||||
node := tree.Search("example.com")
|
node := tree.Search("example.com")
|
||||||
assert.NotNil(t, node)
|
assert.NotNil(t, node)
|
||||||
assert.True(t, node.Data == localIP)
|
assert.True(t, node.Data() == localIP)
|
||||||
assert.NotNil(t, tree.Insert("", localIP))
|
assert.NotNil(t, tree.Insert("", localIP))
|
||||||
assert.Nil(t, tree.Search(""))
|
assert.Nil(t, tree.Search(""))
|
||||||
assert.NotNil(t, tree.Search("localhost"))
|
assert.NotNil(t, tree.Search("localhost"))
|
||||||
@ -75,7 +75,7 @@ func TestTrie_Priority(t *testing.T) {
|
|||||||
assertFn := func(domain string, data int) {
|
assertFn := func(domain string, data int) {
|
||||||
node := tree.Search(domain)
|
node := tree.Search(domain)
|
||||||
assert.NotNil(t, node)
|
assert.NotNil(t, node)
|
||||||
assert.Equal(t, data, node.Data)
|
assert.Equal(t, data, node.Data())
|
||||||
}
|
}
|
||||||
|
|
||||||
for idx, domain := range domains {
|
for idx, domain := range domains {
|
||||||
|
@ -2,7 +2,9 @@ package trie
|
|||||||
|
|
||||||
import "errors"
|
import "errors"
|
||||||
|
|
||||||
var ErrorOverMaxValue = errors.New("the value don't over max value")
|
var (
|
||||||
|
ErrorOverMaxValue = errors.New("the value don't over max value")
|
||||||
|
)
|
||||||
|
|
||||||
type IpCidrNode struct {
|
type IpCidrNode struct {
|
||||||
Mark bool
|
Mark bool
|
||||||
|
@ -1,9 +1,8 @@
|
|||||||
package trie
|
package trie
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"net"
|
||||||
)
|
)
|
||||||
|
|
||||||
type IPV6 bool
|
type IPV6 bool
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user