Compare commits
192 Commits
Author | SHA1 | Date | |
---|---|---|---|
65071ea7d1 | |||
3093fc4f33 | |||
984fca4726 | |||
cc42d787d4 | |||
e2e0fd4eba | |||
bad9f2e6dc | |||
68bf6f16ac | |||
cca701c641 | |||
09ec7c8a62 | |||
68f312288d | |||
191243a1d2 | |||
b0fed73236 | |||
f125e1ce9e | |||
e2216b7824 | |||
7632827177 | |||
b0e76ec791 | |||
a82745f544 | |||
cbb8ef5dfe | |||
a181e35865 | |||
014537e1ea | |||
9b50f56e7c | |||
9cbca162a0 | |||
f73f32e41c | |||
cfc30753af | |||
081e94c738 | |||
5dd57bab67 | |||
492a731ec1 | |||
0b1aff5759 | |||
8f1475d5d0 | |||
c6b84b0f20 | |||
02ba78ab90 | |||
57db8dfe23 | |||
8e16738465 | |||
fa94403629 | |||
1beb2919e7 | |||
75c5d0482e | |||
55bcabdf46 | |||
abf80601e1 | |||
26f97b45d6 | |||
29315ce8e5 | |||
65f84d21ea | |||
e3ac58bc51 | |||
c66438d794 | |||
411e587460 | |||
6cc9c68458 | |||
d1c858d7ff | |||
3eef1ee064 | |||
514d374b8c | |||
a2334430c1 | |||
c8a3d6edd9 | |||
bda2ca3c13 | |||
f4b734c74c | |||
c2cdf43239 | |||
b939c81d3e | |||
0e92496eeb | |||
ea482598e0 | |||
16f3567ddc | |||
73f8da091e | |||
6bdaadc581 | |||
73a2cf593e | |||
665bfcab2d | |||
8be860472a | |||
1ec74f13f7 | |||
564b834e00 | |||
da04e00767 | |||
e0faffbfbd | |||
a0c7641ad5 | |||
1f592c43de | |||
4d7350923c | |||
76a7945994 | |||
a2bbd1cc8d | |||
4ec66d299a | |||
4e46cbfbde | |||
1a44dcee55 | |||
6c7d1657a5 | |||
38e210a851 | |||
359ee70daa | |||
db6b2b7702 | |||
603d0809b4 | |||
614cc93cac | |||
1cb75350e2 | |||
42ef4fedfa | |||
2284acce94 | |||
919daf0dbb | |||
6d824c8745 | |||
1d94546902 | |||
ad7508f203 | |||
d391fda051 | |||
fe0f2d9ef9 | |||
b9110c164d | |||
6c8631d5cc | |||
61734e5cac | |||
77fb9a9c01 | |||
af28b99b2a | |||
4f79bb7931 | |||
644abcf071 | |||
183f2d974c | |||
e914317bef | |||
5e20fedf5f | |||
54337ecdf3 | |||
c7de0e0253 | |||
b72219c06a | |||
64b23257db | |||
8d1251f128 | |||
c57f17d094 | |||
cd44901e90 | |||
766d08a8eb | |||
c3ef05b257 | |||
093453582f | |||
767aa182b9 | |||
ad11a2b813 | |||
dafecebdc0 | |||
e7174866e5 | |||
fdaa6a22a4 | |||
fd0c71a485 | |||
3c1f9a9953 | |||
3ef81afc76 | |||
03d0c8620e | |||
63b5387164 | |||
fb6a032872 | |||
47ad8e08be | |||
e1af4ddda3 | |||
58e05c42c9 | |||
880cc90e10 | |||
2af758e5f1 | |||
2c44b4e170 | |||
7906fbfee6 | |||
17565ec93b | |||
26acaee424 | |||
9b6e56a65e | |||
7fa3d3aa0b | |||
1120c8185d | |||
41af94ea66 | |||
36539bb670 | |||
8e88e0b9f5 | |||
097f3e250c | |||
9c2972afb0 | |||
7aae781569 | |||
92f71fd25f | |||
f44ba26f0c | |||
73140ab826 | |||
4971b9d804 | |||
654e76d91e | |||
984bf27d9b | |||
546b2bc24b | |||
d4e4f6d2d7 | |||
b047ca0294 | |||
2b1e69153b | |||
ae8d42fb82 | |||
89ae640487 | |||
6e0c3a368f | |||
033f902ace | |||
6b1a4385b2 | |||
e552b5475f | |||
8b631f11b8 | |||
1a9104c003 | |||
872a28a5eb | |||
c7557b8e48 | |||
c6fed3e97f | |||
ed17478961 | |||
b674983034 | |||
a22b1cd69e | |||
f1be9b3f4a | |||
534282839c | |||
8dd7632d0a | |||
51e9f3598e | |||
76caab19bf | |||
234f7dbd3b | |||
e404695a0d | |||
75cd72385a | |||
d9fa051dd8 | |||
98394095e4 | |||
c58400572c | |||
3b291d3fbf | |||
15a8d7c473 | |||
67b9314693 | |||
99f7c4f821 | |||
0cb594dd5d | |||
bd431fbf49 | |||
8c0168d3a8 | |||
7ae3e78b15 | |||
d61a5af335 | |||
f90066f286 | |||
463da578dd | |||
1eefa71e1f | |||
969c235490 | |||
f35ff24d0c | |||
94f990da31 | |||
d6931ec491 | |||
19b403da86 | |||
6ecd1c31e5 | |||
a7233f6036 |
33
.github/genReleaseNote.sh
vendored
33
.github/genReleaseNote.sh
vendored
@ -1 +1,32 @@
|
||||
git log --pretty=format:"* %s by @%an" v1.14.x..v1.14.y | sort -f | uniq > release.md
|
||||
#!/bin/bash
|
||||
|
||||
while getopts "v:" opt; do
|
||||
case $opt in
|
||||
v)
|
||||
version_range=$OPTARG
|
||||
;;
|
||||
\?)
|
||||
echo "Invalid option: -$OPTARG" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ -z "$version_range" ]; then
|
||||
echo "Please provide the version range using -v option. Example: ./genReleashNote.sh -v v1.14.1...v1.14.2"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "## What's Changed" > release.md
|
||||
git log --pretty=format:"* %s by @%an" --grep="^feat" -i $version_range | sort -f | uniq >> release.md
|
||||
echo "" >> release.md
|
||||
|
||||
echo "## BUG & Fix" >> release.md
|
||||
git log --pretty=format:"* %s by @%an" --grep="^fix" -i $version_range | sort -f | uniq >> release.md
|
||||
echo "" >> release.md
|
||||
|
||||
echo "## Maintenance" >> release.md
|
||||
git log --pretty=format:"* %s by @%an" --grep="^chore\|^docs\|^refactor" -i $version_range | sort -f | uniq >> release.md
|
||||
echo "" >> release.md
|
||||
|
||||
echo "**Full Changelog**: https://github.com/MetaCubeX/Clash.Meta/compare/$version_range" >> release.md
|
||||
|
49
.github/workflows/build.yml
vendored
49
.github/workflows/build.yml
vendored
@ -94,11 +94,6 @@ jobs:
|
||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Set variables
|
||||
if: ${{github.ref_name=='Beta'}}
|
||||
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Set variables
|
||||
if: ${{github.ref_name=='Meta'}}
|
||||
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
@ -126,9 +121,9 @@ jobs:
|
||||
shell: bash
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: "1.20"
|
||||
go-version: "1.21"
|
||||
check-latest: true
|
||||
|
||||
- name: Test
|
||||
@ -223,7 +218,7 @@ jobs:
|
||||
working-directory: bin
|
||||
|
||||
- name: Delete current release assets
|
||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||
uses: 8Mi-Tech/delete-release-assets-action@main
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: Prerelease-${{ github.ref_name }}
|
||||
@ -246,18 +241,14 @@ jobs:
|
||||
Release created at ${{ env.BUILDTIME }}
|
||||
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
||||
<br>
|
||||
### release version
|
||||
`default(not specified in file name)`: compiled with GOAMD64=v3
|
||||
`cgo`: support lwip tun stack, compiled with GOAMD64=v1
|
||||
`compatible`: compiled with GOAMD64=v1
|
||||
Check details between different architectural levels [here](https://github.com/golang/go/wiki/MinimumRequirements#amd64).
|
||||
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/Clash.Meta/wiki/FAQ)
|
||||
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
||||
EOF
|
||||
|
||||
- name: Upload Prerelease
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag: ${{ github.ref_name }}
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
files: |
|
||||
bin/*
|
||||
@ -271,6 +262,23 @@ jobs:
|
||||
needs: [Build]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get tags
|
||||
run: |
|
||||
echo "CURRENTVERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
|
||||
git fetch --tags
|
||||
echo "PREVERSION=$(git describe --tags --abbrev=0 HEAD^)" >> $GITHUB_ENV
|
||||
|
||||
- name: Generate release notes
|
||||
run: |
|
||||
cp ./.github/genReleaseNote.sh ./
|
||||
bash ./genReleaseNote.sh -v ${PREVERSION}...${CURRENTVERSION}
|
||||
rm ./genReleaseNote.sh
|
||||
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: artifact
|
||||
@ -284,12 +292,13 @@ jobs:
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag: ${{ github.ref_name }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
files: bin/*
|
||||
generate_release_notes: true
|
||||
body_path: release.md
|
||||
|
||||
Docker:
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
permissions: write-all
|
||||
needs: [Build]
|
||||
runs-on: ubuntu-latest
|
||||
@ -309,10 +318,10 @@ jobs:
|
||||
working-directory: bin
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
uses: docker/setup-qemu-action@v2
|
||||
|
||||
- name: Setup Docker buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
uses: docker/setup-buildx-action@v2
|
||||
with:
|
||||
version: latest
|
||||
|
||||
@ -320,7 +329,7 @@ jobs:
|
||||
# https://github.com/docker/metadata-action
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v3
|
||||
uses: docker/metadata-action@v4
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
||||
- name: Show files
|
||||
@ -329,7 +338,7 @@ jobs:
|
||||
ls bin/
|
||||
- name: Log into registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v1
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||
@ -339,7 +348,7 @@ jobs:
|
||||
# https://github.com/docker/build-push-action
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
uses: docker/build-push-action@v2
|
||||
uses: docker/build-push-action@v4
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
|
@ -4,9 +4,9 @@ RUN echo "I'm building for $TARGETPLATFORM"
|
||||
|
||||
RUN apk add --no-cache gzip && \
|
||||
mkdir /clash-config && \
|
||||
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
||||
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
||||
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||
wget -O /clash-config/geoip.metadb https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb && \
|
||||
wget -O /clash-config/geosite.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat && \
|
||||
wget -O /clash-config/geoip.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat
|
||||
|
||||
COPY docker/file-name.sh /clash/file-name.sh
|
||||
WORKDIR /clash
|
||||
|
5
Makefile
5
Makefile
@ -31,6 +31,8 @@ PLATFORM_LIST = \
|
||||
linux-mips-hardfloat \
|
||||
linux-mipsle-softfloat \
|
||||
linux-mipsle-hardfloat \
|
||||
linux-riscv64 \
|
||||
linux-loong64 \
|
||||
android-arm64 \
|
||||
freebsd-386 \
|
||||
freebsd-amd64 \
|
||||
@ -103,6 +105,9 @@ linux-mips64le:
|
||||
|
||||
linux-riscv64:
|
||||
GOARCH=riscv64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-loong64:
|
||||
GOARCH=loong64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
android-arm64:
|
||||
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
@ -3,25 +3,40 @@ package adapter
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/atomic"
|
||||
"github.com/Dreamacro/clash/common/queue"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
)
|
||||
|
||||
var UnifiedDelay = atomic.NewBool(false)
|
||||
|
||||
const (
|
||||
defaultHistoriesNum = 10
|
||||
)
|
||||
|
||||
type extraProxyState struct {
|
||||
history *queue.Queue[C.DelayHistory]
|
||||
alive *atomic.Bool
|
||||
}
|
||||
|
||||
type Proxy struct {
|
||||
C.ProxyAdapter
|
||||
history *queue.Queue[C.DelayHistory]
|
||||
alive *atomic.Bool
|
||||
url string
|
||||
extra map[string]*extraProxyState
|
||||
}
|
||||
|
||||
// Alive implements C.Proxy
|
||||
@ -29,6 +44,17 @@ func (p *Proxy) Alive() bool {
|
||||
return p.alive.Load()
|
||||
}
|
||||
|
||||
// AliveForTestUrl implements C.Proxy
|
||||
func (p *Proxy) AliveForTestUrl(url string) bool {
|
||||
if p.extra != nil {
|
||||
if state, ok := p.extra[url]; ok {
|
||||
return state.alive.Load()
|
||||
}
|
||||
}
|
||||
|
||||
return p.alive.Load()
|
||||
}
|
||||
|
||||
// Dial implements C.Proxy
|
||||
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
||||
@ -65,6 +91,42 @@ func (p *Proxy) DelayHistory() []C.DelayHistory {
|
||||
return histories
|
||||
}
|
||||
|
||||
// DelayHistoryForTestUrl implements C.Proxy
|
||||
func (p *Proxy) DelayHistoryForTestUrl(url string) []C.DelayHistory {
|
||||
var queueM []C.DelayHistory
|
||||
if p.extra != nil {
|
||||
if state, ok := p.extra[url]; ok {
|
||||
queueM = state.history.Copy()
|
||||
}
|
||||
}
|
||||
|
||||
if queueM == nil {
|
||||
queueM = p.history.Copy()
|
||||
}
|
||||
|
||||
histories := []C.DelayHistory{}
|
||||
for _, item := range queueM {
|
||||
histories = append(histories, item)
|
||||
}
|
||||
return histories
|
||||
}
|
||||
|
||||
func (p *Proxy) ExtraDelayHistory() map[string][]C.DelayHistory {
|
||||
extra := map[string][]C.DelayHistory{}
|
||||
if p.extra != nil && len(p.extra) != 0 {
|
||||
for testUrl, option := range p.extra {
|
||||
histories := []C.DelayHistory{}
|
||||
queueM := option.history.Copy()
|
||||
for _, item := range queueM {
|
||||
histories = append(histories, item)
|
||||
}
|
||||
|
||||
extra[testUrl] = histories
|
||||
}
|
||||
}
|
||||
return extra
|
||||
}
|
||||
|
||||
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
||||
// implements C.Proxy
|
||||
func (p *Proxy) LastDelay() (delay uint16) {
|
||||
@ -80,6 +142,30 @@ func (p *Proxy) LastDelay() (delay uint16) {
|
||||
return history.Delay
|
||||
}
|
||||
|
||||
// LastDelayForTestUrl implements C.Proxy
|
||||
func (p *Proxy) LastDelayForTestUrl(url string) (delay uint16) {
|
||||
var max uint16 = 0xffff
|
||||
|
||||
alive := p.alive.Load()
|
||||
history := p.history.Last()
|
||||
|
||||
if p.extra != nil {
|
||||
if state, ok := p.extra[url]; ok {
|
||||
alive = state.alive.Load()
|
||||
history = state.history.Last()
|
||||
}
|
||||
}
|
||||
|
||||
if !alive {
|
||||
return max
|
||||
}
|
||||
|
||||
if history.Delay == 0 {
|
||||
return max
|
||||
}
|
||||
return history.Delay
|
||||
}
|
||||
|
||||
// MarshalJSON implements C.ProxyAdapter
|
||||
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||
inner, err := p.ProxyAdapter.MarshalJSON()
|
||||
@ -90,6 +176,8 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||
mapping := map[string]any{}
|
||||
_ = json.Unmarshal(inner, &mapping)
|
||||
mapping["history"] = p.DelayHistory()
|
||||
mapping["extra"] = p.ExtraDelayHistory()
|
||||
mapping["alive"] = p.Alive()
|
||||
mapping["name"] = p.Name()
|
||||
mapping["udp"] = p.SupportUDP()
|
||||
mapping["xudp"] = p.SupportXUDP()
|
||||
@ -99,16 +187,53 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||
|
||||
// URLTest get the delay for the specified URL
|
||||
// implements C.Proxy
|
||||
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
||||
func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16], store C.DelayHistoryStoreType) (t uint16, err error) {
|
||||
defer func() {
|
||||
p.alive.Store(err == nil)
|
||||
record := C.DelayHistory{Time: time.Now()}
|
||||
if err == nil {
|
||||
record.Delay = t
|
||||
}
|
||||
p.history.Put(record)
|
||||
if p.history.Len() > 10 {
|
||||
p.history.Pop()
|
||||
alive := err == nil
|
||||
store = p.determineFinalStoreType(store, url)
|
||||
|
||||
switch store {
|
||||
case C.OriginalHistory:
|
||||
p.alive.Store(alive)
|
||||
record := C.DelayHistory{Time: time.Now()}
|
||||
if alive {
|
||||
record.Delay = t
|
||||
}
|
||||
p.history.Put(record)
|
||||
if p.history.Len() > defaultHistoriesNum {
|
||||
p.history.Pop()
|
||||
}
|
||||
|
||||
// test URL configured by the proxy provider
|
||||
if len(p.url) == 0 {
|
||||
p.url = url
|
||||
}
|
||||
case C.ExtraHistory:
|
||||
record := C.DelayHistory{Time: time.Now()}
|
||||
if alive {
|
||||
record.Delay = t
|
||||
}
|
||||
|
||||
if p.extra == nil {
|
||||
p.extra = map[string]*extraProxyState{}
|
||||
}
|
||||
|
||||
state, ok := p.extra[url]
|
||||
if !ok {
|
||||
state = &extraProxyState{
|
||||
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
||||
alive: atomic.NewBool(true),
|
||||
}
|
||||
p.extra[url] = state
|
||||
}
|
||||
|
||||
state.alive.Store(alive)
|
||||
state.history.Put(record)
|
||||
if state.history.Len() > defaultHistoriesNum {
|
||||
state.history.Pop()
|
||||
}
|
||||
default:
|
||||
log.Debugln("health check result will be discarded, url: %s alive: %t, delay: %d", url, alive, t)
|
||||
}
|
||||
}()
|
||||
|
||||
@ -172,12 +297,17 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
if expectedStatus != nil && !expectedStatus.Check(uint16(resp.StatusCode)) {
|
||||
// maybe another value should be returned for differentiation
|
||||
err = errors.New("response status is inconsistent with the expected status")
|
||||
}
|
||||
|
||||
t = uint16(time.Since(start) / time.Millisecond)
|
||||
return
|
||||
}
|
||||
|
||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||
return &Proxy{adapter, queue.New[C.DelayHistory](10), atomic.NewBool(true)}
|
||||
return &Proxy{adapter, queue.New[C.DelayHistory](defaultHistoriesNum), atomic.NewBool(true), "", map[string]*extraProxyState{}}
|
||||
}
|
||||
|
||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||
@ -198,11 +328,36 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||
return
|
||||
}
|
||||
}
|
||||
uintPort, err := strconv.ParseUint(port, 10, 16)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
addr = C.Metadata{
|
||||
Host: u.Hostname(),
|
||||
DstIP: netip.Addr{},
|
||||
DstPort: port,
|
||||
DstPort: uint16(uintPort),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Proxy) determineFinalStoreType(store C.DelayHistoryStoreType, url string) C.DelayHistoryStoreType {
|
||||
if store != C.DropHistory {
|
||||
return store
|
||||
}
|
||||
|
||||
if len(p.url) == 0 || url == p.url {
|
||||
return C.OriginalHistory
|
||||
}
|
||||
|
||||
if p.extra == nil {
|
||||
store = C.ExtraHistory
|
||||
} else {
|
||||
if _, ok := p.extra[url]; ok {
|
||||
store = C.ExtraHistory
|
||||
} else if len(p.extra) < 2*C.DefaultMaxHealthCheckUrlNum {
|
||||
store = C.ExtraHistory
|
||||
}
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
@ -16,6 +16,12 @@ func WithInName(name string) Addition {
|
||||
}
|
||||
}
|
||||
|
||||
func WithInUser(user string) Addition {
|
||||
return func(metadata *C.Metadata) {
|
||||
metadata.InUser = user
|
||||
}
|
||||
}
|
||||
|
||||
func WithSpecialRules(specialRules string) Addition {
|
||||
return func(metadata *C.Metadata) {
|
||||
metadata.SpecialRules = specialRules
|
||||
|
@ -17,6 +17,10 @@ func SetTfo(open bool) {
|
||||
lc.DisableTFO = !open
|
||||
}
|
||||
|
||||
func SetMPTCP(open bool) {
|
||||
setMultiPathTCP(&lc.ListenConfig, open)
|
||||
}
|
||||
|
||||
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
||||
return lc.Listen(ctx, network, address)
|
||||
}
|
||||
|
10
adapter/inbound/mptcp_go120.go
Normal file
10
adapter/inbound/mptcp_go120.go
Normal file
@ -0,0 +1,10 @@
|
||||
//go:build !go1.21
|
||||
|
||||
package inbound
|
||||
|
||||
import "net"
|
||||
|
||||
const multipathTCPAvailable = false
|
||||
|
||||
func setMultiPathTCP(listenConfig *net.ListenConfig, open bool) {
|
||||
}
|
11
adapter/inbound/mptcp_go121.go
Normal file
11
adapter/inbound/mptcp_go121.go
Normal file
@ -0,0 +1,11 @@
|
||||
//go:build go1.21
|
||||
|
||||
package inbound
|
||||
|
||||
import "net"
|
||||
|
||||
const multipathTCPAvailable = true
|
||||
|
||||
func setMultiPathTCP(listenConfig *net.ListenConfig, open bool) {
|
||||
listenConfig.SetMultipathTCP(open)
|
||||
}
|
@ -3,6 +3,7 @@ package inbound
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/context"
|
||||
@ -30,21 +31,20 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Ad
|
||||
return context.NewConnContext(conn, metadata)
|
||||
}
|
||||
|
||||
func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
||||
func NewInner(conn net.Conn, address string) *context.ConnContext {
|
||||
metadata := &C.Metadata{}
|
||||
metadata.NetWork = C.TCP
|
||||
metadata.Type = C.INNER
|
||||
metadata.DNSMode = C.DNSNormal
|
||||
metadata.Host = host
|
||||
metadata.Process = C.ClashName
|
||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||
metadata.DstPort = port
|
||||
if host == "" {
|
||||
if ip, err := netip.ParseAddr(h); err == nil {
|
||||
metadata.DstIP = ip
|
||||
} else {
|
||||
metadata.Host = h
|
||||
}
|
||||
if h, port, err := net.SplitHostPort(address); err == nil {
|
||||
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
||||
metadata.DstPort = uint16(port)
|
||||
}
|
||||
if ip, err := netip.ParseAddr(h); err == nil {
|
||||
metadata.DstIP = ip
|
||||
} else {
|
||||
metadata.Host = h
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -20,14 +20,14 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||
case socks5.AtypDomainName:
|
||||
// trim for FQDN
|
||||
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
|
||||
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||
metadata.DstPort = uint16((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||
case socks5.AtypIPv4:
|
||||
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 = uint16((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||
case socks5.AtypIPv6:
|
||||
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 = uint16((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||
}
|
||||
|
||||
return metadata
|
||||
@ -43,11 +43,16 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
||||
// trim FQDN (#737)
|
||||
host = strings.TrimRight(host, ".")
|
||||
|
||||
var uint16Port uint16
|
||||
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
||||
uint16Port = uint16(port)
|
||||
}
|
||||
|
||||
metadata := &C.Metadata{
|
||||
NetWork: C.TCP,
|
||||
Host: host,
|
||||
DstIP: netip.Addr{},
|
||||
DstPort: port,
|
||||
DstPort: uint16Port,
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
@ -58,10 +63,10 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
||||
return metadata
|
||||
}
|
||||
|
||||
func parseAddr(addr net.Addr) (netip.Addr, string, error) {
|
||||
func parseAddr(addr net.Addr) (netip.Addr, uint16, error) {
|
||||
// Filter when net.Addr interface is nil
|
||||
if addr == nil {
|
||||
return netip.Addr{}, "", errors.New("nil addr")
|
||||
return netip.Addr{}, 0, errors.New("nil addr")
|
||||
}
|
||||
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
|
||||
ip, port, err := parseAddr(rawAddr.RawAddr())
|
||||
@ -72,9 +77,14 @@ func parseAddr(addr net.Addr) (netip.Addr, string, error) {
|
||||
addrStr := addr.String()
|
||||
host, port, err := net.SplitHostPort(addrStr)
|
||||
if err != nil {
|
||||
return netip.Addr{}, "", err
|
||||
return netip.Addr{}, 0, err
|
||||
}
|
||||
|
||||
var uint16Port uint16
|
||||
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
||||
uint16Port = uint16(port)
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
return ip, port, err
|
||||
return ip, uint16Port, err
|
||||
}
|
||||
|
@ -21,6 +21,7 @@ type Base struct {
|
||||
udp bool
|
||||
xudp bool
|
||||
tfo bool
|
||||
mpTcp bool
|
||||
rmark int
|
||||
id string
|
||||
prefer C.DNSPrefer
|
||||
@ -45,8 +46,8 @@ func (b *Base) Type() C.AdapterType {
|
||||
return b.tp
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (b *Base) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
return c, C.ErrNotSupport
|
||||
}
|
||||
|
||||
@ -143,11 +144,16 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
||||
opts = append(opts, dialer.WithTFO(true))
|
||||
}
|
||||
|
||||
if b.mpTcp {
|
||||
opts = append(opts, dialer.WithMPTCP(true))
|
||||
}
|
||||
|
||||
return opts
|
||||
}
|
||||
|
||||
type BasicOption struct {
|
||||
TFO bool `proxy:"tfo,omitempty" group:"tfo,omitempty"`
|
||||
MPTCP bool `proxy:"mptcp,omitempty" group:"mptcp,omitempty"`
|
||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
||||
@ -161,6 +167,7 @@ type BaseOption struct {
|
||||
UDP bool
|
||||
XUDP bool
|
||||
TFO bool
|
||||
MPTCP bool
|
||||
Interface string
|
||||
RoutingMark int
|
||||
Prefer C.DNSPrefer
|
||||
@ -174,6 +181,7 @@ func NewBase(opt BaseOption) *Base {
|
||||
udp: opt.UDP,
|
||||
xudp: opt.XUDP,
|
||||
tfo: opt.TFO,
|
||||
mpTcp: opt.MPTCP,
|
||||
iface: opt.Interface,
|
||||
rmark: opt.RoutingMark,
|
||||
prefer: opt.Prefer,
|
||||
@ -220,7 +228,7 @@ func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||
}
|
||||
|
||||
type packetConn struct {
|
||||
net.PacketConn
|
||||
N.EnhancePacketConn
|
||||
chain C.Chain
|
||||
adapterName string
|
||||
connID string
|
||||
@ -242,15 +250,28 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
||||
}
|
||||
|
||||
func (c *packetConn) LocalAddr() net.Addr {
|
||||
lAddr := c.PacketConn.LocalAddr()
|
||||
lAddr := c.EnhancePacketConn.LocalAddr()
|
||||
return N.NewCustomAddr(c.adapterName, c.connID, lAddr) // make quic-go's connMultiplexer happy
|
||||
}
|
||||
|
||||
func (c *packetConn) Upstream() any {
|
||||
return c.EnhancePacketConn
|
||||
}
|
||||
|
||||
func (c *packetConn) WriterReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *packetConn) ReaderReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||
epc := N.NewEnhancePacketConn(pc)
|
||||
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
|
||||
pc = N.NewDeadlinePacketConn(pc) // most conn from outbound can't handle readDeadline correctly
|
||||
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
|
||||
}
|
||||
return &packetConn{pc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), parseRemoteDestination(a.Addr())}
|
||||
return &packetConn{epc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), parseRemoteDestination(a.Addr())}
|
||||
}
|
||||
|
||||
func parseRemoteDestination(addr string) string {
|
||||
|
@ -3,8 +3,6 @@ package outbound
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
@ -39,11 +37,7 @@ func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newPacketConn(&directPacketConn{pc}, d), nil
|
||||
}
|
||||
|
||||
type directPacketConn struct {
|
||||
net.PacketConn
|
||||
return newPacketConn(pc, d), nil
|
||||
}
|
||||
|
||||
func NewDirect() *Direct {
|
||||
|
@ -10,7 +10,6 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
@ -41,12 +40,10 @@ type HttpOption struct {
|
||||
Headers map[string]string `proxy:"headers,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (h *Http) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
if h.tlsConfig != nil {
|
||||
cc := tls.Client(c, h.tlsConfig)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
err := cc.HandshakeContext(ctx)
|
||||
c = cc
|
||||
if err != nil {
|
||||
@ -83,7 +80,7 @@ func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metad
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = h.StreamConn(c, metadata)
|
||||
c, err = h.StreamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -98,34 +95,36 @@ func (h *Http) SupportWithDialer() C.NetWork {
|
||||
|
||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||
addr := metadata.RemoteAddress()
|
||||
req := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{
|
||||
Host: addr,
|
||||
},
|
||||
Host: addr,
|
||||
Header: http.Header{
|
||||
"Proxy-Connection": []string{"Keep-Alive"},
|
||||
},
|
||||
HeaderString := "CONNECT " + addr + " HTTP/1.1\r\n"
|
||||
tempHeaders := map[string]string{
|
||||
"Host": addr,
|
||||
"User-Agent": "Go-http-client/1.1",
|
||||
"Proxy-Connection": "Keep-Alive",
|
||||
}
|
||||
|
||||
//增加headers
|
||||
if len(h.option.Headers) != 0 {
|
||||
for key, value := range h.option.Headers {
|
||||
req.Header.Add(key, value)
|
||||
}
|
||||
for key, value := range h.option.Headers {
|
||||
tempHeaders[key] = value
|
||||
}
|
||||
|
||||
if h.user != "" && h.pass != "" {
|
||||
auth := h.user + ":" + h.pass
|
||||
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
||||
tempHeaders["Proxy-Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
|
||||
}
|
||||
|
||||
if err := req.Write(rw); err != nil {
|
||||
for key, value := range tempHeaders {
|
||||
HeaderString += key + ": " + value + "\r\n"
|
||||
}
|
||||
|
||||
HeaderString += "\r\n"
|
||||
|
||||
_, err := rw.Write([]byte(HeaderString))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := http.ReadResponse(bufio.NewReader(rw), req)
|
||||
resp, err := http.ReadResponse(bufio.NewReader(rw), nil)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -178,6 +177,7 @@ func NewHttp(option HttpOption) (*Http, error) {
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Http,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
|
@ -318,6 +318,16 @@ func (c *hyPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (c *hyPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||
b, addrStr, err := c.UDPConn.ReadFrom()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data = b
|
||||
addr = M.ParseSocksaddr(addrStr).UDPAddr()
|
||||
return
|
||||
}
|
||||
|
||||
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
||||
if err != nil {
|
||||
|
@ -78,8 +78,11 @@ type nopPacketConn struct{}
|
||||
|
||||
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
||||
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
||||
func (npc nopPacketConn) Close() error { return nil }
|
||||
func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
||||
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||
func (npc nopPacketConn) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
||||
return nil, nil, nil, io.EOF
|
||||
}
|
||||
func (npc nopPacketConn) Close() error { return nil }
|
||||
func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
||||
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||
|
@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/common/structure"
|
||||
@ -17,13 +16,10 @@ import (
|
||||
"github.com/Dreamacro/clash/transport/restls"
|
||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||
|
||||
restlsC "github.com/3andne/restls-client-go"
|
||||
shadowsocks "github.com/metacubex/sing-shadowsocks"
|
||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
"github.com/metacubex/sing-shadowsocks2"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/common/uot"
|
||||
)
|
||||
@ -87,14 +83,7 @@ type restlsOption struct {
|
||||
RestlsScript string `obfs:"restls-script,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
// fix tls handshake not timeout
|
||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
return ss.StreamConnContext(ctx, c, metadata)
|
||||
}
|
||||
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
useEarly := false
|
||||
switch ss.obfsMode {
|
||||
@ -105,7 +94,7 @@ func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metada
|
||||
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
||||
case "websocket":
|
||||
var err error
|
||||
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
||||
c, err = v2rayObfs.NewV2rayObfs(ctx, c, ss.v2rayOption)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||
}
|
||||
@ -196,7 +185,7 @@ func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dial
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pc = ss.method.DialPacketConn(bufio.NewBindPacketConn(pc, addr))
|
||||
pc = ss.method.DialPacketConn(N.NewBindPacketConn(pc, addr))
|
||||
return newPacketConn(pc, ss), nil
|
||||
}
|
||||
|
||||
@ -234,7 +223,9 @@ func (ss *ShadowSocks) SupportUOT() bool {
|
||||
|
||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password, time.Now)
|
||||
method, err := shadowsocks.CreateMethod(context.Background(), option.Cipher, shadowsocks.MethodOptions{
|
||||
Password: option.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||
}
|
||||
@ -312,7 +303,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
switch option.UDPOverTCPVersion {
|
||||
case uot.Version, uot.LegacyVersion:
|
||||
case 0:
|
||||
option.UDPOverTCPVersion = uot.Version
|
||||
option.UDPOverTCPVersion = uot.LegacyVersion
|
||||
default:
|
||||
return nil, fmt.Errorf("ss %s unknown udp over tcp protocol version: %d", addr, option.UDPOverTCPVersion)
|
||||
}
|
||||
@ -324,6 +315,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
tp: C.Shadowsocks,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
@ -338,36 +330,3 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
restlsConfig: restlsConfig,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type ssPacketConn struct {
|
||||
net.PacketConn
|
||||
rAddr net.Addr
|
||||
}
|
||||
|
||||
func (spc *ssPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||
}
|
||||
|
||||
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
n, _, e := spc.PacketConn.ReadFrom(b)
|
||||
if e != nil {
|
||||
return 0, nil, e
|
||||
}
|
||||
|
||||
addr := socks5.SplitAddr(b[:n])
|
||||
if addr == nil {
|
||||
return 0, nil, errors.New("parse addr error")
|
||||
}
|
||||
|
||||
udpAddr := addr.UDPAddr()
|
||||
if udpAddr == nil {
|
||||
return 0, nil, errors.New("parse addr error")
|
||||
}
|
||||
|
||||
copy(b, b[len(addr):])
|
||||
return n - len(addr), udpAddr, e
|
||||
}
|
||||
|
@ -2,16 +2,19 @@ package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/proxydialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
||||
)
|
||||
@ -38,8 +41,8 @@ type ShadowSocksROption struct {
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (ssr *ShadowSocksR) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
c = ssr.obfs.StreamConn(c)
|
||||
c = ssr.cipher.StreamConn(c)
|
||||
var (
|
||||
@ -83,7 +86,7 @@ func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dia
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = ssr.StreamConn(c, metadata)
|
||||
c, err = ssr.StreamConnContext(ctx, c, metadata)
|
||||
return NewConn(c, ssr), err
|
||||
}
|
||||
|
||||
@ -110,9 +113,9 @@ func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Di
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pc = ssr.cipher.PacketConn(pc)
|
||||
pc = ssr.protocol.PacketConn(pc)
|
||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
||||
epc := ssr.cipher.PacketConn(N.NewEnhancePacketConn(pc))
|
||||
epc = ssr.protocol.PacketConn(epc)
|
||||
return newPacketConn(&ssrPacketConn{EnhancePacketConn: epc, rAddr: addr}, ssr), nil
|
||||
}
|
||||
|
||||
// SupportWithDialer implements C.ProxyAdapter
|
||||
@ -178,6 +181,7 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||
tp: C.ShadowsocksR,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
@ -188,3 +192,62 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||
protocol: protocol,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type ssrPacketConn struct {
|
||||
N.EnhancePacketConn
|
||||
rAddr net.Addr
|
||||
}
|
||||
|
||||
func (spc *ssrPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return spc.EnhancePacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||
}
|
||||
|
||||
func (spc *ssrPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
n, _, e := spc.EnhancePacketConn.ReadFrom(b)
|
||||
if e != nil {
|
||||
return 0, nil, e
|
||||
}
|
||||
|
||||
addr := socks5.SplitAddr(b[:n])
|
||||
if addr == nil {
|
||||
return 0, nil, errors.New("parse addr error")
|
||||
}
|
||||
|
||||
udpAddr := addr.UDPAddr()
|
||||
if udpAddr == nil {
|
||||
return 0, nil, errors.New("parse addr error")
|
||||
}
|
||||
|
||||
copy(b, b[len(addr):])
|
||||
return n - len(addr), udpAddr, e
|
||||
}
|
||||
|
||||
func (spc *ssrPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||
data, put, _, err = spc.EnhancePacketConn.WaitReadFrom()
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
_addr := socks5.SplitAddr(data)
|
||||
if _addr == nil {
|
||||
if put != nil {
|
||||
put()
|
||||
}
|
||||
return nil, nil, nil, errors.New("parse addr error")
|
||||
}
|
||||
|
||||
addr = _addr.UDPAddr()
|
||||
if addr == nil {
|
||||
if put != nil {
|
||||
put()
|
||||
}
|
||||
return nil, nil, nil, errors.New("parse addr error")
|
||||
}
|
||||
|
||||
data = data[len(_addr):]
|
||||
return
|
||||
}
|
||||
|
@ -92,12 +92,12 @@ func (s *SingMux) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
||||
if pc == nil {
|
||||
return nil, E.New("packetConn is nil")
|
||||
}
|
||||
return newPacketConn(CN.NewRefPacketConn(pc, s), s.ProxyAdapter), nil
|
||||
return newPacketConn(CN.NewRefPacketConn(CN.NewThreadSafePacketConn(pc), s), s.ProxyAdapter), nil
|
||||
}
|
||||
|
||||
func (s *SingMux) SupportUDP() bool {
|
||||
if s.onlyTcp {
|
||||
return s.ProxyAdapter.SupportUOT()
|
||||
return s.ProxyAdapter.SupportUDP()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
@ -52,15 +52,14 @@ func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
||||
return snell.StreamConn(c, option.psk, option.version)
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (s *Snell) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||
if metadata.NetWork == C.UDP {
|
||||
err := snell.WriteUDPHeader(c, s.version)
|
||||
return c, err
|
||||
}
|
||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
||||
err := snell.WriteHeader(c, metadata.String(), uint(metadata.DstPort), s.version)
|
||||
return c, err
|
||||
}
|
||||
|
||||
@ -72,8 +71,7 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
||||
return nil, err
|
||||
}
|
||||
|
||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
||||
if err = snell.WriteHeader(c, metadata.String(), uint(metadata.DstPort), s.version); err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
@ -101,7 +99,7 @@ func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = s.StreamConn(c, metadata)
|
||||
c, err = s.StreamConnContext(ctx, c, metadata)
|
||||
return NewConn(c, s), err
|
||||
}
|
||||
|
||||
@ -183,6 +181,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
tp: C.Snell,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
|
@ -39,12 +39,10 @@ type Socks5Option struct {
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (ss *Socks5) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
if ss.tls {
|
||||
cc := tls.Client(c, ss.tlsConfig)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
err := cc.HandshakeContext(ctx)
|
||||
c = cc
|
||||
if err != nil {
|
||||
@ -88,7 +86,7 @@ func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, me
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = ss.StreamConn(c, metadata)
|
||||
c, err = ss.StreamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -198,6 +196,7 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||
tp: C.Socks5,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
|
@ -14,7 +14,6 @@ import (
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/gun"
|
||||
"github.com/Dreamacro/clash/transport/trojan"
|
||||
"github.com/Dreamacro/clash/transport/vless"
|
||||
)
|
||||
|
||||
type Trojan struct {
|
||||
@ -45,12 +44,10 @@ type TrojanOption struct {
|
||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||
Flow string `proxy:"flow,omitempty"`
|
||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||
func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error) {
|
||||
if t.option.Network == "ws" {
|
||||
host, port, _ := net.SplitHostPort(t.addr)
|
||||
wsOpts := &trojan.WebsocketOption{
|
||||
@ -71,14 +68,14 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||
wsOpts.Headers = header
|
||||
}
|
||||
|
||||
return t.instance.StreamWebsocketConn(c, wsOpts)
|
||||
return t.instance.StreamWebsocketConn(ctx, c, wsOpts)
|
||||
}
|
||||
|
||||
return t.instance.StreamConn(c)
|
||||
return t.instance.StreamConn(ctx, c)
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
var err error
|
||||
|
||||
if tlsC.HaveGlobalFingerprint() && len(t.option.ClientFingerprint) == 0 {
|
||||
@ -88,18 +85,13 @@ func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
||||
if t.transport != nil {
|
||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig, t.realityConfig)
|
||||
} else {
|
||||
c, err = t.plainStream(c)
|
||||
c, err = t.plainStream(ctx, c)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||
}
|
||||
|
||||
c, err = t.instance.PresetXTLSConn(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if metadata.NetWork == C.UDP {
|
||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||
return c, err
|
||||
@ -117,12 +109,6 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c, err = t.instance.PresetXTLSConn(c)
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
@ -151,7 +137,7 @@ func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, met
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = t.StreamConn(c, metadata)
|
||||
c, err = t.StreamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -199,7 +185,7 @@ func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, me
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
tcpKeepAlive(c)
|
||||
c, err = t.plainStream(c)
|
||||
c, err = t.plainStream(ctx, c)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||
}
|
||||
@ -237,24 +223,10 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
ALPN: option.ALPN,
|
||||
ServerName: option.Server,
|
||||
SkipCertVerify: option.SkipCertVerify,
|
||||
FlowShow: option.FlowShow,
|
||||
Fingerprint: option.Fingerprint,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
}
|
||||
|
||||
switch option.Network {
|
||||
case "", "tcp":
|
||||
if len(option.Flow) >= 16 {
|
||||
option.Flow = option.Flow[:16]
|
||||
switch option.Flow {
|
||||
case vless.XRO, vless.XRD, vless.XRS:
|
||||
tOption.Flow = option.Flow
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if option.SNI != "" {
|
||||
tOption.ServerName = option.SNI
|
||||
}
|
||||
@ -266,6 +238,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
tp: C.Trojan,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
|
@ -13,13 +13,14 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/quic-go"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/proxydialer"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/tuic"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
"github.com/metacubex/quic-go"
|
||||
)
|
||||
|
||||
type Tuic struct {
|
||||
@ -33,7 +34,9 @@ type TuicOption struct {
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Token string `proxy:"token"`
|
||||
Token string `proxy:"token,omitempty"`
|
||||
UUID string `proxy:"uuid,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
Ip string `proxy:"ip,omitempty"`
|
||||
HeartbeatInterval int `proxy:"heartbeat-interval,omitempty"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
@ -46,6 +49,7 @@ type TuicOption struct {
|
||||
|
||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
||||
CWND int `proxy:"cwnd,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
CustomCA string `proxy:"ca,omitempty"`
|
||||
@ -90,11 +94,7 @@ func (t *Tuic) SupportWithDialer() C.NetWork {
|
||||
return C.ALLNet
|
||||
}
|
||||
|
||||
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
||||
return t.dialWithDialer(ctx, dialer.NewDialer(opts...))
|
||||
}
|
||||
|
||||
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
||||
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (transport *quic.Transport, addr net.Addr, err error) {
|
||||
if len(t.option.DialerProxy) > 0 {
|
||||
dialer, err = proxydialer.NewByName(t.option.DialerProxy, dialer)
|
||||
if err != nil {
|
||||
@ -106,10 +106,14 @@ func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.Pack
|
||||
return nil, nil, err
|
||||
}
|
||||
addr = udpAddr
|
||||
var pc net.PacketConn
|
||||
pc, err = dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
transport = &quic.Transport{Conn: pc}
|
||||
transport.SetCreatedConn(true) // auto close conn
|
||||
transport.SetSingleUse(true) // auto close transport
|
||||
return
|
||||
}
|
||||
|
||||
@ -158,7 +162,7 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||
}
|
||||
|
||||
if len(option.ALPN) > 0 {
|
||||
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||
tlsConfig.NextProtos = option.ALPN
|
||||
} else {
|
||||
tlsConfig.NextProtos = []string{"h3"}
|
||||
@ -172,8 +176,9 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
option.HeartbeatInterval = 10000
|
||||
}
|
||||
|
||||
udpRelayMode := tuic.QUIC
|
||||
if option.UdpRelayMode != "quic" {
|
||||
option.UdpRelayMode = "native"
|
||||
udpRelayMode = tuic.NATIVE
|
||||
}
|
||||
|
||||
if option.MaxUdpRelayPacketSize == 0 {
|
||||
@ -184,14 +189,23 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
option.MaxOpenStreams = 100
|
||||
}
|
||||
|
||||
if option.CWND == 0 {
|
||||
option.CWND = 32
|
||||
}
|
||||
|
||||
packetOverHead := tuic.PacketOverHeadV4
|
||||
if len(option.Token) == 0 {
|
||||
packetOverHead = tuic.PacketOverHeadV5
|
||||
}
|
||||
|
||||
if option.MaxDatagramFrameSize == 0 {
|
||||
option.MaxDatagramFrameSize = option.MaxUdpRelayPacketSize + tuic.PacketOverHead
|
||||
option.MaxDatagramFrameSize = option.MaxUdpRelayPacketSize + packetOverHead
|
||||
}
|
||||
|
||||
if option.MaxDatagramFrameSize > 1400 {
|
||||
option.MaxDatagramFrameSize = 1400
|
||||
}
|
||||
option.MaxUdpRelayPacketSize = option.MaxDatagramFrameSize - tuic.PacketOverHead
|
||||
option.MaxUdpRelayPacketSize = option.MaxDatagramFrameSize - packetOverHead
|
||||
|
||||
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
||||
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||
@ -220,12 +234,10 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
if len(option.Ip) > 0 {
|
||||
addr = net.JoinHostPort(option.Ip, strconv.Itoa(option.Port))
|
||||
}
|
||||
host := option.Server
|
||||
if option.DisableSni {
|
||||
host = ""
|
||||
tlsConfig.ServerName = ""
|
||||
tlsConfig.InsecureSkipVerify = true // tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config
|
||||
}
|
||||
tkn := tuic.GenTKN(option.Token)
|
||||
|
||||
t := &Tuic{
|
||||
Base: &Base{
|
||||
@ -251,21 +263,40 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
if clientMaxOpenStreams < 1 {
|
||||
clientMaxOpenStreams = 1
|
||||
}
|
||||
clientOption := &tuic.ClientOption{
|
||||
TlsConfig: tlsConfig,
|
||||
QuicConfig: quicConfig,
|
||||
Host: host,
|
||||
Token: tkn,
|
||||
UdpRelayMode: option.UdpRelayMode,
|
||||
CongestionController: option.CongestionController,
|
||||
ReduceRtt: option.ReduceRtt,
|
||||
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
||||
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||
FastOpen: option.FastOpen,
|
||||
MaxOpenStreams: clientMaxOpenStreams,
|
||||
}
|
||||
|
||||
t.client = tuic.NewPoolClient(clientOption)
|
||||
if len(option.Token) > 0 {
|
||||
tkn := tuic.GenTKN(option.Token)
|
||||
clientOption := &tuic.ClientOptionV4{
|
||||
TlsConfig: tlsConfig,
|
||||
QuicConfig: quicConfig,
|
||||
Token: tkn,
|
||||
UdpRelayMode: udpRelayMode,
|
||||
CongestionController: option.CongestionController,
|
||||
ReduceRtt: option.ReduceRtt,
|
||||
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
||||
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||
FastOpen: option.FastOpen,
|
||||
MaxOpenStreams: clientMaxOpenStreams,
|
||||
CWND: option.CWND,
|
||||
}
|
||||
|
||||
t.client = tuic.NewPoolClientV4(clientOption)
|
||||
} else {
|
||||
clientOption := &tuic.ClientOptionV5{
|
||||
TlsConfig: tlsConfig,
|
||||
QuicConfig: quicConfig,
|
||||
Uuid: uuid.FromStringOrNil(option.UUID),
|
||||
Password: option.Password,
|
||||
UdpRelayMode: udpRelayMode,
|
||||
CongestionController: option.CongestionController,
|
||||
ReduceRtt: option.ReduceRtt,
|
||||
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||
MaxOpenStreams: clientMaxOpenStreams,
|
||||
CWND: option.CWND,
|
||||
}
|
||||
|
||||
t.client = tuic.NewPoolClientV5(clientOption)
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
@ -4,10 +4,8 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
xtls "github.com/xtls/go"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@ -17,9 +15,8 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
globalClientSessionCache tls.ClientSessionCache
|
||||
globalClientXSessionCache xtls.ClientSessionCache
|
||||
once sync.Once
|
||||
globalClientSessionCache tls.ClientSessionCache
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func tcpKeepAlive(c net.Conn) {
|
||||
@ -36,18 +33,11 @@ func getClientSessionCache() tls.ClientSessionCache {
|
||||
return globalClientSessionCache
|
||||
}
|
||||
|
||||
func getClientXSessionCache() xtls.ClientSessionCache {
|
||||
once.Do(func() {
|
||||
globalClientXSessionCache = xtls.NewLRUClientSessionCache(128)
|
||||
})
|
||||
return globalClientXSessionCache
|
||||
}
|
||||
|
||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||
var buf [][]byte
|
||||
addrType := metadata.AddrType()
|
||||
aType := uint8(addrType)
|
||||
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||
p := uint(metadata.DstPort)
|
||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||
switch addrType {
|
||||
case socks5.AtypDomainName:
|
||||
|
@ -13,6 +13,8 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/Dreamacro/clash/common/convert"
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/proxydialer"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
@ -24,8 +26,8 @@ import (
|
||||
"github.com/Dreamacro/clash/transport/vless"
|
||||
"github.com/Dreamacro/clash/transport/vmess"
|
||||
|
||||
vmessSing "github.com/sagernet/sing-vmess"
|
||||
"github.com/sagernet/sing-vmess/packetaddr"
|
||||
vmessSing "github.com/metacubex/sing-vmess"
|
||||
"github.com/metacubex/sing-vmess/packetaddr"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
@ -54,7 +56,6 @@ type VlessOption struct {
|
||||
Port int `proxy:"port"`
|
||||
UUID string `proxy:"uuid"`
|
||||
Flow string `proxy:"flow,omitempty"`
|
||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||
@ -74,7 +75,7 @@ type VlessOption struct {
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
var err error
|
||||
|
||||
if tlsC.HaveGlobalFingerprint() && len(v.option.ClientFingerprint) == 0 {
|
||||
@ -128,10 +129,10 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
convert.SetUserAgent(wsOpts.Headers)
|
||||
}
|
||||
}
|
||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||
case "http":
|
||||
// readability first, so just copy default TLS logic
|
||||
c, err = v.streamTLSOrXTLSConn(c, false)
|
||||
c, err = v.streamTLSConn(ctx, c, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -146,7 +147,7 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
|
||||
c = vmess.StreamHTTPConn(c, httpOpts)
|
||||
case "h2":
|
||||
c, err = v.streamTLSOrXTLSConn(c, true)
|
||||
c, err = v.streamTLSConn(ctx, c, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -161,8 +162,8 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
||||
default:
|
||||
// default tcp network
|
||||
// handle TLS And XTLS
|
||||
c, err = v.streamTLSOrXTLSConn(c, false)
|
||||
// handle TLS
|
||||
c, err = v.streamTLSConn(ctx, c, false)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@ -178,7 +179,7 @@ func (v *Vless) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err
|
||||
metadata = &C.Metadata{
|
||||
NetWork: C.UDP,
|
||||
Host: packetaddr.SeqPacketMagicAddress,
|
||||
DstPort: "443",
|
||||
DstPort: 443,
|
||||
}
|
||||
} else {
|
||||
metadata = &C.Metadata{ // a clear metadata only contains ip
|
||||
@ -200,23 +201,10 @@ func (v *Vless) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err
|
||||
return
|
||||
}
|
||||
|
||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||
if v.option.TLS {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
|
||||
if v.isLegacyXTLSEnabled() && !isH2 {
|
||||
xtlsOpts := vless.XTLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
Fingerprint: v.option.Fingerprint,
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
xtlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
|
||||
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
||||
|
||||
} else if v.option.TLS {
|
||||
tlsOpts := vmess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
@ -233,16 +221,12 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
|
||||
return vmess.StreamTLSConn(conn, &tlsOpts)
|
||||
return vmess.StreamTLSConn(ctx, conn, &tlsOpts)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (v *Vless) isLegacyXTLSEnabled() bool {
|
||||
return v.client.Addons != nil && v.client.Addons.Flow != vless.XRV
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||
// gun transport
|
||||
@ -282,7 +266,7 @@ func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = v.StreamConn(c, metadata)
|
||||
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||
}
|
||||
@ -347,7 +331,7 @@ func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = v.StreamConn(c, metadata)
|
||||
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||
}
|
||||
@ -372,15 +356,21 @@ func (v *Vless) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metada
|
||||
}
|
||||
|
||||
if v.option.XUDP {
|
||||
return newPacketConn(&threadSafePacketConn{
|
||||
PacketConn: vmessSing.NewXUDPConn(c, M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||
}, v), nil
|
||||
var globalID [8]byte
|
||||
if metadata.SourceValid() {
|
||||
globalID = utils.GlobalID(metadata.SourceAddress())
|
||||
}
|
||||
return newPacketConn(N.NewThreadSafePacketConn(
|
||||
vmessSing.NewXUDPConn(c,
|
||||
globalID,
|
||||
M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||
), v), nil
|
||||
} else if v.option.PacketAddr {
|
||||
return newPacketConn(&threadSafePacketConn{
|
||||
PacketConn: packetaddr.NewConn(&vlessPacketConn{
|
||||
return newPacketConn(N.NewThreadSafePacketConn(
|
||||
packetaddr.NewConn(&vlessPacketConn{
|
||||
Conn: c, rAddr: metadata.UDPAddr(),
|
||||
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||
}, v), nil
|
||||
), v), nil
|
||||
}
|
||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||
}
|
||||
@ -409,12 +399,11 @@ func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
||||
copy(addr[1:], metadata.Host)
|
||||
}
|
||||
|
||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||
return &vless.DstAddr{
|
||||
UDP: metadata.NetWork == C.UDP,
|
||||
AddrType: addrType,
|
||||
Addr: addr,
|
||||
Port: uint16(port),
|
||||
Port: metadata.DstPort,
|
||||
Mux: metadata.NetWork == C.UDP && xudp,
|
||||
}
|
||||
}
|
||||
@ -518,11 +507,11 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
switch option.Flow {
|
||||
case vless.XRV:
|
||||
log.Warnln("To use %s, ensure your server is upgrade to Xray-core v1.8.0+", vless.XRV)
|
||||
fallthrough
|
||||
case vless.XRO, vless.XRD, vless.XRS:
|
||||
addons = &vless.Addons{
|
||||
Flow: option.Flow,
|
||||
}
|
||||
case vless.XRO, vless.XRD, vless.XRS:
|
||||
log.Fatalln("Legacy XTLS protocol %s is deprecated and no longer supported", option.Flow)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||
}
|
||||
@ -541,7 +530,7 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
option.PacketAddr = false
|
||||
}
|
||||
|
||||
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||
client, err := vless.NewClient(option.UUID, addons)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -554,6 +543,7 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
udp: option.UDP,
|
||||
xudp: option.XUDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
@ -595,15 +585,19 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
Host: v.option.ServerName,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
}
|
||||
tlsConfig := tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
ServerName: v.option.ServerName,
|
||||
})
|
||||
|
||||
if v.option.ServerName == "" {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsConfig.ServerName = host
|
||||
gunConfig.Host = host
|
||||
if option.ServerName == "" {
|
||||
gunConfig.Host = v.addr
|
||||
}
|
||||
var tlsConfig *tls.Config
|
||||
if option.TLS {
|
||||
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
ServerName: v.option.ServerName,
|
||||
})
|
||||
if option.ServerName == "" {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsConfig.ServerName = host
|
||||
}
|
||||
}
|
||||
|
||||
v.gunTLSConfig = tlsConfig
|
||||
|
@ -12,6 +12,7 @@ import (
|
||||
"sync"
|
||||
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/proxydialer"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
@ -20,8 +21,8 @@ import (
|
||||
"github.com/Dreamacro/clash/transport/gun"
|
||||
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||
|
||||
vmess "github.com/sagernet/sing-vmess"
|
||||
"github.com/sagernet/sing-vmess/packetaddr"
|
||||
vmess "github.com/metacubex/sing-vmess"
|
||||
"github.com/metacubex/sing-vmess/packetaddr"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
@ -89,8 +90,8 @@ type WSOptions struct {
|
||||
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
// StreamConnContext implements C.ProxyAdapter
|
||||
func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
var err error
|
||||
|
||||
if tlsC.HaveGlobalFingerprint() && (len(v.option.ClientFingerprint) == 0) {
|
||||
@ -138,7 +139,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
wsOpts.TLSConfig.ServerName = host
|
||||
}
|
||||
}
|
||||
c, err = clashVMess.StreamWebsocketConn(c, wsOpts)
|
||||
c, err = clashVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||
case "http":
|
||||
// readability first, so just copy default TLS logic
|
||||
if v.option.TLS {
|
||||
@ -153,7 +154,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
if v.option.ServerName != "" {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -182,7 +183,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
|
||||
c, err = clashVMess.StreamTLSConn(c, &tlsOpts)
|
||||
c, err = clashVMess.StreamTLSConn(ctx, c, &tlsOpts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -210,7 +211,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
tlsOpts.Host = v.option.ServerName
|
||||
}
|
||||
|
||||
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||
}
|
||||
}
|
||||
|
||||
@ -223,30 +224,44 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
func (v *Vmess) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
|
||||
if metadata.NetWork == C.UDP {
|
||||
if v.option.XUDP {
|
||||
var globalID [8]byte
|
||||
if metadata.SourceValid() {
|
||||
globalID = utils.GlobalID(metadata.SourceAddress())
|
||||
}
|
||||
if N.NeedHandshake(c) {
|
||||
conn = v.client.DialEarlyXUDPPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||
conn = v.client.DialEarlyXUDPPacketConn(c,
|
||||
globalID,
|
||||
M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||
} else {
|
||||
conn, err = v.client.DialXUDPPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||
conn, err = v.client.DialXUDPPacketConn(c,
|
||||
globalID,
|
||||
M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||
}
|
||||
} else if v.option.PacketAddr {
|
||||
if N.NeedHandshake(c) {
|
||||
conn = v.client.DialEarlyPacketConn(c, M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
||||
conn = v.client.DialEarlyPacketConn(c,
|
||||
M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
||||
} else {
|
||||
conn, err = v.client.DialPacketConn(c, M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
||||
conn, err = v.client.DialPacketConn(c,
|
||||
M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
||||
}
|
||||
conn = packetaddr.NewBindConn(conn)
|
||||
} else {
|
||||
if N.NeedHandshake(c) {
|
||||
conn = v.client.DialEarlyPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||
conn = v.client.DialEarlyPacketConn(c,
|
||||
M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||
} else {
|
||||
conn, err = v.client.DialPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||
conn, err = v.client.DialPacketConn(c,
|
||||
M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if N.NeedHandshake(c) {
|
||||
conn = v.client.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
conn = v.client.DialEarlyConn(c,
|
||||
M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
} else {
|
||||
conn, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
conn, err = v.client.DialConn(c,
|
||||
M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
@ -294,7 +309,7 @@ func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = v.StreamConn(c, metadata)
|
||||
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||
return NewConn(c, v), err
|
||||
}
|
||||
|
||||
@ -355,7 +370,7 @@ func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = v.StreamConn(c, metadata)
|
||||
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||
}
|
||||
@ -379,7 +394,7 @@ func (v *Vmess) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metada
|
||||
}
|
||||
|
||||
if pc, ok := c.(net.PacketConn); ok {
|
||||
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||
return newPacketConn(N.NewThreadSafePacketConn(pc), v), nil
|
||||
}
|
||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||
}
|
||||
@ -413,13 +428,6 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
option.PacketAddr = false
|
||||
}
|
||||
|
||||
switch option.Network {
|
||||
case "h2", "grpc":
|
||||
if !option.TLS {
|
||||
option.TLS = true
|
||||
}
|
||||
}
|
||||
|
||||
v := &Vmess{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
@ -428,6 +436,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
udp: option.UDP,
|
||||
xudp: option.XUDP,
|
||||
tfo: option.TFO,
|
||||
mpTcp: option.MPTCP,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
@ -464,15 +473,19 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
Host: v.option.ServerName,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
}
|
||||
tlsConfig := &tls.Config{
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
ServerName: v.option.ServerName,
|
||||
if option.ServerName == "" {
|
||||
gunConfig.Host = v.addr
|
||||
}
|
||||
|
||||
if v.option.ServerName == "" {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsConfig.ServerName = host
|
||||
gunConfig.Host = host
|
||||
var tlsConfig *tls.Config
|
||||
if option.TLS {
|
||||
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
ServerName: v.option.ServerName,
|
||||
})
|
||||
if option.ServerName == "" {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsConfig.ServerName = host
|
||||
}
|
||||
}
|
||||
|
||||
v.gunTLSConfig = tlsConfig
|
||||
@ -489,17 +502,6 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
return v, nil
|
||||
}
|
||||
|
||||
type threadSafePacketConn struct {
|
||||
net.PacketConn
|
||||
access sync.Mutex
|
||||
}
|
||||
|
||||
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
c.access.Lock()
|
||||
defer c.access.Unlock()
|
||||
return c.PacketConn.WriteTo(b, addr)
|
||||
}
|
||||
|
||||
type vmessPacketConn struct {
|
||||
net.Conn
|
||||
rAddr net.Addr
|
||||
|
@ -67,7 +67,7 @@ type WireGuardPeerOption struct {
|
||||
PublicKey string `proxy:"public-key,omitempty"`
|
||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||
AllowedIPs []string `proxy:"allowed_ips,omitempty"`
|
||||
AllowedIPs []string `proxy:"allowed-ips,omitempty"`
|
||||
}
|
||||
|
||||
type wgSingDialer struct {
|
||||
@ -374,8 +374,7 @@ func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts
|
||||
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||
} else {
|
||||
port, _ := strconv.Atoi(metadata.DstPort)
|
||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -412,8 +411,7 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
||||
}
|
||||
metadata.DstIP = ip
|
||||
}
|
||||
port, _ := strconv.Atoi(metadata.DstPort)
|
||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -499,9 +497,9 @@ func (r *refProxyAdapter) MarshalJSON() ([]byte, error) {
|
||||
return nil, C.ErrNotSupport
|
||||
}
|
||||
|
||||
func (r *refProxyAdapter) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
func (r *refProxyAdapter) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
if r.proxyAdapter != nil {
|
||||
return r.proxyAdapter.StreamConn(c, metadata)
|
||||
return r.proxyAdapter.StreamConnContext(ctx, c, metadata)
|
||||
}
|
||||
return nil, C.ErrNotSupport
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ import (
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/common/callback"
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/constant/provider"
|
||||
@ -16,9 +17,10 @@ import (
|
||||
|
||||
type Fallback struct {
|
||||
*GroupBase
|
||||
disableUDP bool
|
||||
testUrl string
|
||||
selected string
|
||||
disableUDP bool
|
||||
testUrl string
|
||||
selected string
|
||||
expectedStatus string
|
||||
}
|
||||
|
||||
func (f *Fallback) Now() string {
|
||||
@ -82,9 +84,11 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
"type": f.Type().String(),
|
||||
"now": f.Now(),
|
||||
"all": all,
|
||||
"type": f.Type().String(),
|
||||
"now": f.Now(),
|
||||
"all": all,
|
||||
"testUrl": f.testUrl,
|
||||
"expected": f.expectedStatus,
|
||||
})
|
||||
}
|
||||
|
||||
@ -98,12 +102,14 @@ func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||
proxies := f.GetProxies(touch)
|
||||
for _, proxy := range proxies {
|
||||
if len(f.selected) == 0 {
|
||||
if proxy.Alive() {
|
||||
// if proxy.Alive() {
|
||||
if proxy.AliveForTestUrl(f.testUrl) {
|
||||
return proxy
|
||||
}
|
||||
} else {
|
||||
if proxy.Name() == f.selected {
|
||||
if proxy.Alive() {
|
||||
// if proxy.Alive() {
|
||||
if proxy.AliveForTestUrl(f.testUrl) {
|
||||
return proxy
|
||||
} else {
|
||||
f.selected = ""
|
||||
@ -129,10 +135,12 @@ func (f *Fallback) Set(name string) error {
|
||||
}
|
||||
|
||||
f.selected = name
|
||||
if !p.Alive() {
|
||||
// if !p.Alive() {
|
||||
if !p.AliveForTestUrl(f.testUrl) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
||||
defer cancel()
|
||||
_, _ = p.URLTest(ctx, f.testUrl)
|
||||
expectedStatus, _ := utils.NewIntRanges[uint16](f.expectedStatus)
|
||||
_, _ = p.URLTest(ctx, f.testUrl, expectedStatus, C.ExtraHistory)
|
||||
}
|
||||
|
||||
return nil
|
||||
@ -156,7 +164,8 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
||||
option.ExcludeType,
|
||||
providers,
|
||||
}),
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
expectedStatus: option.ExpectedStatus,
|
||||
}
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/common/atomic"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/constant/provider"
|
||||
types "github.com/Dreamacro/clash/constant/provider"
|
||||
@ -130,10 +131,6 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||
}
|
||||
}
|
||||
|
||||
if len(proxies) == 0 {
|
||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||
}
|
||||
|
||||
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
||||
var newProxies []C.Proxy
|
||||
proxiesSet := map[string]struct{}{}
|
||||
@ -189,10 +186,14 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||
proxies = newProxies
|
||||
}
|
||||
|
||||
if len(proxies) == 0 {
|
||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||
}
|
||||
|
||||
return proxies
|
||||
}
|
||||
|
||||
func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16, error) {
|
||||
func (gb *GroupBase) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (map[string]uint16, error) {
|
||||
var wg sync.WaitGroup
|
||||
var lock sync.Mutex
|
||||
mp := map[string]uint16{}
|
||||
@ -201,7 +202,7 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16
|
||||
proxy := proxy
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
delay, err := proxy.URLTest(ctx, url)
|
||||
delay, err := proxy.URLTest(ctx, url, expectedStatus, C.DropHistory)
|
||||
if err == nil {
|
||||
lock.Lock()
|
||||
mp[proxy.Name()] = delay
|
||||
|
@ -12,8 +12,8 @@ import (
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/common/cache"
|
||||
"github.com/Dreamacro/clash/common/callback"
|
||||
"github.com/Dreamacro/clash/common/murmur3"
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/constant/provider"
|
||||
@ -25,8 +25,10 @@ type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Pr
|
||||
|
||||
type LoadBalance struct {
|
||||
*GroupBase
|
||||
disableUDP bool
|
||||
strategyFn strategyFn
|
||||
disableUDP bool
|
||||
strategyFn strategyFn
|
||||
testUrl string
|
||||
expectedStatus string
|
||||
}
|
||||
|
||||
var errStrategy = errors.New("unsupported strategy")
|
||||
@ -129,7 +131,7 @@ func (lb *LoadBalance) IsL3Protocol(metadata *C.Metadata) bool {
|
||||
return lb.Unwrap(metadata, false).IsL3Protocol(metadata)
|
||||
}
|
||||
|
||||
func strategyRoundRobin() strategyFn {
|
||||
func strategyRoundRobin(url string) strategyFn {
|
||||
idx := 0
|
||||
idxMutex := sync.Mutex{}
|
||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||
@ -148,7 +150,8 @@ func strategyRoundRobin() strategyFn {
|
||||
for ; i < length; i++ {
|
||||
id := (idx + i) % length
|
||||
proxy := proxies[id]
|
||||
if proxy.Alive() {
|
||||
// if proxy.Alive() {
|
||||
if proxy.AliveForTestUrl(url) {
|
||||
i++
|
||||
return proxy
|
||||
}
|
||||
@ -158,22 +161,24 @@ func strategyRoundRobin() strategyFn {
|
||||
}
|
||||
}
|
||||
|
||||
func strategyConsistentHashing() strategyFn {
|
||||
func strategyConsistentHashing(url string) strategyFn {
|
||||
maxRetry := 5
|
||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||
key := utils.MapHash(getKey(metadata))
|
||||
buckets := int32(len(proxies))
|
||||
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||
idx := jumpHash(key, buckets)
|
||||
proxy := proxies[idx]
|
||||
if proxy.Alive() {
|
||||
// if proxy.Alive() {
|
||||
if proxy.AliveForTestUrl(url) {
|
||||
return proxy
|
||||
}
|
||||
}
|
||||
|
||||
// when availability is poor, traverse the entire list to get the available nodes
|
||||
for _, proxy := range proxies {
|
||||
if proxy.Alive() {
|
||||
// if proxy.Alive() {
|
||||
if proxy.AliveForTestUrl(url) {
|
||||
return proxy
|
||||
}
|
||||
}
|
||||
@ -182,14 +187,14 @@ func strategyConsistentHashing() strategyFn {
|
||||
}
|
||||
}
|
||||
|
||||
func strategyStickySessions() strategyFn {
|
||||
func strategyStickySessions(url string) strategyFn {
|
||||
ttl := time.Minute * 10
|
||||
maxRetry := 5
|
||||
lruCache := cache.New[uint64, int](
|
||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||
cache.WithSize[uint64, int](1000))
|
||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
||||
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
|
||||
length := len(proxies)
|
||||
idx, has := lruCache.Get(key)
|
||||
if !has {
|
||||
@ -199,7 +204,8 @@ func strategyStickySessions() strategyFn {
|
||||
nowIdx := idx
|
||||
for i := 1; i < maxRetry; i++ {
|
||||
proxy := proxies[nowIdx]
|
||||
if proxy.Alive() {
|
||||
// if proxy.Alive() {
|
||||
if proxy.AliveForTestUrl(url) {
|
||||
if nowIdx != idx {
|
||||
lruCache.Delete(key)
|
||||
lruCache.Set(key, nowIdx)
|
||||
@ -230,8 +236,10 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
"type": lb.Type().String(),
|
||||
"all": all,
|
||||
"type": lb.Type().String(),
|
||||
"all": all,
|
||||
"testUrl": lb.testUrl,
|
||||
"expectedStatus": lb.expectedStatus,
|
||||
})
|
||||
}
|
||||
|
||||
@ -239,11 +247,11 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
||||
var strategyFn strategyFn
|
||||
switch strategy {
|
||||
case "consistent-hashing":
|
||||
strategyFn = strategyConsistentHashing()
|
||||
strategyFn = strategyConsistentHashing(option.URL)
|
||||
case "round-robin":
|
||||
strategyFn = strategyRoundRobin()
|
||||
strategyFn = strategyRoundRobin(option.URL)
|
||||
case "sticky-sessions":
|
||||
strategyFn = strategyStickySessions()
|
||||
strategyFn = strategyStickySessions(option.URL)
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||
}
|
||||
@ -260,7 +268,9 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
||||
option.ExcludeType,
|
||||
providers,
|
||||
}),
|
||||
strategyFn: strategyFn,
|
||||
disableUDP: option.DisableUDP,
|
||||
strategyFn: strategyFn,
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
expectedStatus: option.ExpectedStatus,
|
||||
}, nil
|
||||
}
|
||||
|
@ -3,35 +3,37 @@ package outboundgroup
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/adapter/provider"
|
||||
"github.com/Dreamacro/clash/common/structure"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
types "github.com/Dreamacro/clash/constant/provider"
|
||||
)
|
||||
|
||||
var (
|
||||
errFormat = errors.New("format error")
|
||||
errType = errors.New("unsupport type")
|
||||
errType = errors.New("unsupported type")
|
||||
errMissProxy = errors.New("`use` or `proxies` missing")
|
||||
errMissHealthCheck = errors.New("`url` or `interval` missing")
|
||||
errDuplicateProvider = errors.New("duplicate provider name")
|
||||
)
|
||||
|
||||
type GroupCommonOption struct {
|
||||
outbound.BasicOption
|
||||
Name string `group:"name"`
|
||||
Type string `group:"type"`
|
||||
Proxies []string `group:"proxies,omitempty"`
|
||||
Use []string `group:"use,omitempty"`
|
||||
URL string `group:"url,omitempty"`
|
||||
Interval int `group:"interval,omitempty"`
|
||||
Lazy bool `group:"lazy,omitempty"`
|
||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||
Filter string `group:"filter,omitempty"`
|
||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||
ExcludeType string `group:"exclude-type,omitempty"`
|
||||
Name string `group:"name"`
|
||||
Type string `group:"type"`
|
||||
Proxies []string `group:"proxies,omitempty"`
|
||||
Use []string `group:"use,omitempty"`
|
||||
URL string `group:"url,omitempty"`
|
||||
Interval int `group:"interval,omitempty"`
|
||||
Lazy bool `group:"lazy,omitempty"`
|
||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||
Filter string `group:"filter,omitempty"`
|
||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||
ExcludeType string `group:"exclude-type,omitempty"`
|
||||
ExpectedStatus string `group:"expected-status,omitempty"`
|
||||
}
|
||||
|
||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||
@ -53,30 +55,36 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
providers := []types.ProxyProvider{}
|
||||
|
||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||
return nil, errMissProxy
|
||||
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
||||
}
|
||||
|
||||
expectedStatus, err := utils.NewIntRanges[uint16](groupOption.ExpectedStatus)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||
}
|
||||
|
||||
status := strings.TrimSpace(groupOption.ExpectedStatus)
|
||||
if status == "" {
|
||||
status = "*"
|
||||
}
|
||||
groupOption.ExpectedStatus = status
|
||||
testUrl := groupOption.URL
|
||||
|
||||
if len(groupOption.Proxies) != 0 {
|
||||
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||
}
|
||||
|
||||
if _, ok := providersMap[groupName]; ok {
|
||||
return nil, errDuplicateProvider
|
||||
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
||||
}
|
||||
|
||||
// select don't need health check
|
||||
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
||||
hc := provider.NewHealthCheck(ps, "", 0, true)
|
||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var url string
|
||||
var interval uint
|
||||
|
||||
providers = append(providers, pd)
|
||||
providersMap[groupName] = pd
|
||||
} else {
|
||||
// select don't need health check
|
||||
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
||||
if groupOption.URL == "" {
|
||||
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
||||
}
|
||||
@ -85,22 +93,29 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
groupOption.Interval = 300
|
||||
}
|
||||
|
||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
providers = append(providers, pd)
|
||||
providersMap[groupName] = pd
|
||||
url = groupOption.URL
|
||||
interval = uint(groupOption.Interval)
|
||||
}
|
||||
|
||||
hc := provider.NewHealthCheck(ps, url, interval, true, expectedStatus)
|
||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||
}
|
||||
|
||||
providers = append(providers, pd)
|
||||
providersMap[groupName] = pd
|
||||
}
|
||||
|
||||
if len(groupOption.Use) != 0 {
|
||||
list, err := getProviders(providersMap, groupOption.Use)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||
}
|
||||
|
||||
// different proxy groups use different test URL
|
||||
addTestUrlToProviders(list, testUrl, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
||||
|
||||
providers = append(providers, list...)
|
||||
} else {
|
||||
groupOption.Filter = ""
|
||||
@ -154,3 +169,13 @@ func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]type
|
||||
}
|
||||
return ps, nil
|
||||
}
|
||||
|
||||
func addTestUrlToProviders(providers []types.ProxyProvider, url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||
if len(providers) == 0 || len(url) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, pd := range providers {
|
||||
pd.RegisterHealthCheckTask(url, expectedStatus, filter, interval)
|
||||
}
|
||||
}
|
||||
|
@ -25,12 +25,13 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
||||
|
||||
type URLTest struct {
|
||||
*GroupBase
|
||||
selected string
|
||||
testUrl string
|
||||
tolerance uint16
|
||||
disableUDP bool
|
||||
fastNode C.Proxy
|
||||
fastSingle *singledo.Single[C.Proxy]
|
||||
selected string
|
||||
testUrl string
|
||||
expectedStatus string
|
||||
tolerance uint16
|
||||
disableUDP bool
|
||||
fastNode C.Proxy
|
||||
fastSingle *singledo.Single[C.Proxy]
|
||||
}
|
||||
|
||||
func (u *URLTest) Now() string {
|
||||
@ -96,44 +97,49 @@ func (u *URLTest) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||
}
|
||||
|
||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||
var s C.Proxy
|
||||
proxies := u.GetProxies(touch)
|
||||
fast := proxies[0]
|
||||
if fast.Name() == u.selected {
|
||||
s = fast
|
||||
|
||||
proxies := u.GetProxies(touch)
|
||||
if u.selected != "" {
|
||||
for _, proxy := range proxies {
|
||||
if !proxy.Alive() {
|
||||
continue
|
||||
}
|
||||
if proxy.Name() == u.selected {
|
||||
u.fastNode = proxy
|
||||
return proxy
|
||||
}
|
||||
}
|
||||
min := fast.LastDelay()
|
||||
}
|
||||
|
||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||
fast := proxies[0]
|
||||
// min := fast.LastDelay()
|
||||
min := fast.LastDelayForTestUrl(u.testUrl)
|
||||
fastNotExist := true
|
||||
|
||||
for _, proxy := range proxies[1:] {
|
||||
|
||||
if u.fastNode != nil && proxy.Name() == u.fastNode.Name() {
|
||||
fastNotExist = false
|
||||
}
|
||||
|
||||
if proxy.Name() == u.selected {
|
||||
s = proxy
|
||||
}
|
||||
if !proxy.Alive() {
|
||||
// if !proxy.Alive() {
|
||||
if !proxy.AliveForTestUrl(u.testUrl) {
|
||||
continue
|
||||
}
|
||||
|
||||
delay := proxy.LastDelay()
|
||||
// delay := proxy.LastDelay()
|
||||
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
||||
if delay < min {
|
||||
fast = proxy
|
||||
min = delay
|
||||
}
|
||||
|
||||
}
|
||||
// tolerance
|
||||
if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
||||
// if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
||||
if u.fastNode == nil || fastNotExist || !u.fastNode.AliveForTestUrl(u.testUrl) || u.fastNode.LastDelayForTestUrl(u.testUrl) > fast.LastDelayForTestUrl(u.testUrl)+u.tolerance {
|
||||
u.fastNode = fast
|
||||
}
|
||||
if s != nil {
|
||||
if s.Alive() && s.LastDelay() < fast.LastDelay()+u.tolerance {
|
||||
u.fastNode = s
|
||||
}
|
||||
}
|
||||
return u.fastNode, nil
|
||||
})
|
||||
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
||||
@ -163,9 +169,11 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
"type": u.Type().String(),
|
||||
"now": u.Now(),
|
||||
"all": all,
|
||||
"type": u.Type().String(),
|
||||
"now": u.Now(),
|
||||
"all": all,
|
||||
"testUrl": u.testUrl,
|
||||
"expected": u.expectedStatus,
|
||||
})
|
||||
}
|
||||
|
||||
@ -197,9 +205,10 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
||||
option.ExcludeType,
|
||||
providers,
|
||||
}),
|
||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
expectedStatus: option.ExpectedStatus,
|
||||
}
|
||||
|
||||
for _, option := range options {
|
||||
|
@ -2,6 +2,8 @@ package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/atomic"
|
||||
@ -10,6 +12,8 @@ import (
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
"github.com/dlclark/regexp2"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -21,18 +25,33 @@ type HealthCheckOption struct {
|
||||
Interval uint
|
||||
}
|
||||
|
||||
type extraOption struct {
|
||||
expectedStatus utils.IntRanges[uint16]
|
||||
filters map[string]struct{}
|
||||
}
|
||||
|
||||
type HealthCheck struct {
|
||||
url string
|
||||
proxies []C.Proxy
|
||||
interval uint
|
||||
lazy bool
|
||||
lastTouch *atomic.Int64
|
||||
done chan struct{}
|
||||
singleDo *singledo.Single[struct{}]
|
||||
url string
|
||||
extra map[string]*extraOption
|
||||
mu sync.Mutex
|
||||
started *atomic.Bool
|
||||
proxies []C.Proxy
|
||||
interval uint
|
||||
lazy bool
|
||||
expectedStatus utils.IntRanges[uint16]
|
||||
lastTouch *atomic.Int64
|
||||
done chan struct{}
|
||||
singleDo *singledo.Single[struct{}]
|
||||
}
|
||||
|
||||
func (hc *HealthCheck) process() {
|
||||
if hc.started.Load() {
|
||||
log.Warnln("Skip start health check timer due to it's started")
|
||||
return
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||
hc.start()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
@ -44,6 +63,7 @@ func (hc *HealthCheck) process() {
|
||||
}
|
||||
case <-hc.done:
|
||||
ticker.Stop()
|
||||
hc.stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
@ -53,6 +73,63 @@ func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||
hc.proxies = proxies
|
||||
}
|
||||
|
||||
func (hc *HealthCheck) registerHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||
url = strings.TrimSpace(url)
|
||||
if len(url) == 0 || url == hc.url {
|
||||
log.Debugln("ignore invalid health check url: %s", url)
|
||||
return
|
||||
}
|
||||
|
||||
hc.mu.Lock()
|
||||
defer hc.mu.Unlock()
|
||||
|
||||
// if the provider has not set up health checks, then modify it to be the same as the group's interval
|
||||
if hc.interval == 0 {
|
||||
hc.interval = interval
|
||||
}
|
||||
|
||||
if hc.extra == nil {
|
||||
hc.extra = make(map[string]*extraOption)
|
||||
}
|
||||
|
||||
// prioritize the use of previously registered configurations, especially those from provider
|
||||
if _, ok := hc.extra[url]; ok {
|
||||
// provider default health check does not set filter
|
||||
if url != hc.url && len(filter) != 0 {
|
||||
splitAndAddFiltersToExtra(filter, hc.extra[url])
|
||||
}
|
||||
|
||||
log.Debugln("health check url: %s exists", url)
|
||||
return
|
||||
}
|
||||
|
||||
// due to the time-consuming nature of health checks, a maximum of defaultMaxTestURLNum URLs can be set for testing
|
||||
if len(hc.extra) > C.DefaultMaxHealthCheckUrlNum {
|
||||
log.Debugln("skip add url: %s to health check because it has reached the maximum limit: %d", url, C.DefaultMaxHealthCheckUrlNum)
|
||||
return
|
||||
}
|
||||
|
||||
option := &extraOption{filters: map[string]struct{}{}, expectedStatus: expectedStatus}
|
||||
splitAndAddFiltersToExtra(filter, option)
|
||||
hc.extra[url] = option
|
||||
|
||||
if hc.auto() && !hc.started.Load() {
|
||||
go hc.process()
|
||||
}
|
||||
}
|
||||
|
||||
func splitAndAddFiltersToExtra(filter string, option *extraOption) {
|
||||
filter = strings.TrimSpace(filter)
|
||||
if len(filter) != 0 {
|
||||
for _, regex := range strings.Split(filter, "`") {
|
||||
regex = strings.TrimSpace(regex)
|
||||
if len(regex) != 0 {
|
||||
option.filters[regex] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (hc *HealthCheck) auto() bool {
|
||||
return hc.interval != 0
|
||||
}
|
||||
@ -61,41 +138,102 @@ func (hc *HealthCheck) touch() {
|
||||
hc.lastTouch.Store(time.Now().Unix())
|
||||
}
|
||||
|
||||
func (hc *HealthCheck) start() {
|
||||
hc.started.Store(true)
|
||||
}
|
||||
|
||||
func (hc *HealthCheck) stop() {
|
||||
hc.started.Store(false)
|
||||
}
|
||||
|
||||
func (hc *HealthCheck) check() {
|
||||
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||
id := utils.NewUUIDV4().String()
|
||||
log.Debugln("Start New Health Checking {%s}", id)
|
||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||
for _, proxy := range hc.proxies {
|
||||
p := proxy
|
||||
b.Go(p.Name(), func() (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||
defer cancel()
|
||||
log.Debugln("Health Checking %s {%s}", p.Name(), id)
|
||||
_, _ = p.URLTest(ctx, hc.url)
|
||||
log.Debugln("Health Checked %s : %t %d ms {%s}", p.Name(), p.Alive(), p.LastDelay(), id)
|
||||
return false, nil
|
||||
})
|
||||
}
|
||||
|
||||
// execute default health check
|
||||
option := &extraOption{filters: nil, expectedStatus: hc.expectedStatus}
|
||||
hc.execute(b, hc.url, id, option)
|
||||
|
||||
// execute extra health check
|
||||
if len(hc.extra) != 0 {
|
||||
for url, option := range hc.extra {
|
||||
hc.execute(b, url, id, option)
|
||||
}
|
||||
}
|
||||
b.Wait()
|
||||
log.Debugln("Finish A Health Checking {%s}", id)
|
||||
return struct{}{}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *extraOption) {
|
||||
url = strings.TrimSpace(url)
|
||||
if len(url) == 0 {
|
||||
log.Debugln("Health Check has been skipped due to testUrl is empty, {%s}", uid)
|
||||
return
|
||||
}
|
||||
|
||||
var filterReg *regexp2.Regexp
|
||||
var store = C.OriginalHistory
|
||||
var expectedStatus utils.IntRanges[uint16]
|
||||
if option != nil {
|
||||
if url != hc.url {
|
||||
store = C.ExtraHistory
|
||||
}
|
||||
|
||||
expectedStatus = option.expectedStatus
|
||||
if len(option.filters) != 0 {
|
||||
filters := make([]string, 0, len(option.filters))
|
||||
for filter := range option.filters {
|
||||
filters = append(filters, filter)
|
||||
}
|
||||
|
||||
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), 0)
|
||||
}
|
||||
}
|
||||
|
||||
for _, proxy := range hc.proxies {
|
||||
// skip proxies that do not require health check
|
||||
if filterReg != nil {
|
||||
if match, _ := filterReg.FindStringMatch(proxy.Name()); match == nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
p := proxy
|
||||
b.Go(p.Name(), func() (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||
defer cancel()
|
||||
log.Debugln("Health Checking, proxy: %s, url: %s, id: {%s}", p.Name(), url, uid)
|
||||
_, _ = p.URLTest(ctx, url, expectedStatus, store)
|
||||
log.Debugln("Health Checked, proxy: %s, url: %s, alive: %t, delay: %d ms uid: {%s}", p.Name(), url, p.AliveForTestUrl(url), p.LastDelayForTestUrl(url), uid)
|
||||
return false, nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (hc *HealthCheck) close() {
|
||||
hc.done <- struct{}{}
|
||||
}
|
||||
|
||||
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *HealthCheck {
|
||||
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
||||
if len(url) == 0 {
|
||||
interval = 0
|
||||
expectedStatus = nil
|
||||
}
|
||||
|
||||
return &HealthCheck{
|
||||
proxies: proxies,
|
||||
url: url,
|
||||
interval: interval,
|
||||
lazy: lazy,
|
||||
lastTouch: atomic.NewInt64(0),
|
||||
done: make(chan struct{}, 1),
|
||||
singleDo: singledo.NewSingle[struct{}](time.Second),
|
||||
proxies: proxies,
|
||||
url: url,
|
||||
extra: map[string]*extraOption{},
|
||||
started: atomic.NewBool(false),
|
||||
interval: interval,
|
||||
lazy: lazy,
|
||||
expectedStatus: expectedStatus,
|
||||
lastTouch: atomic.NewInt64(0),
|
||||
done: make(chan struct{}, 1),
|
||||
singleDo: singledo.NewSingle[struct{}](time.Second),
|
||||
}
|
||||
}
|
||||
|
@ -6,23 +6,28 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/structure"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/component/resource"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
types "github.com/Dreamacro/clash/constant/provider"
|
||||
)
|
||||
|
||||
var errVehicleType = errors.New("unsupport vehicle type")
|
||||
var (
|
||||
errVehicleType = errors.New("unsupport vehicle type")
|
||||
errSubPath = errors.New("path is not subpath of home directory")
|
||||
)
|
||||
|
||||
type healthCheckSchema struct {
|
||||
Enable bool `provider:"enable"`
|
||||
URL string `provider:"url"`
|
||||
Interval int `provider:"interval"`
|
||||
Lazy bool `provider:"lazy,omitempty"`
|
||||
Enable bool `provider:"enable"`
|
||||
URL string `provider:"url"`
|
||||
Interval int `provider:"interval"`
|
||||
Lazy bool `provider:"lazy,omitempty"`
|
||||
ExpectedStatus string `provider:"expected-status,omitempty"`
|
||||
}
|
||||
|
||||
type proxyProviderSchema struct {
|
||||
Type string `provider:"type"`
|
||||
Path string `provider:"path"`
|
||||
Path string `provider:"path,omitempty"`
|
||||
URL string `provider:"url,omitempty"`
|
||||
Interval int `provider:"interval,omitempty"`
|
||||
Filter string `provider:"filter,omitempty"`
|
||||
@ -44,20 +49,33 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
||||
return nil, err
|
||||
}
|
||||
|
||||
expectedStatus, err := utils.NewIntRanges[uint16](schema.HealthCheck.ExpectedStatus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var hcInterval uint
|
||||
if schema.HealthCheck.Enable {
|
||||
hcInterval = uint(schema.HealthCheck.Interval)
|
||||
}
|
||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy)
|
||||
|
||||
path := C.Path.Resolve(schema.Path)
|
||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
||||
|
||||
var vehicle types.Vehicle
|
||||
switch schema.Type {
|
||||
case "file":
|
||||
path := C.Path.Resolve(schema.Path)
|
||||
vehicle = resource.NewFileVehicle(path)
|
||||
case "http":
|
||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
||||
if schema.Path != "" {
|
||||
path := C.Path.Resolve(schema.Path)
|
||||
if !C.Path.IsSafePath(path) {
|
||||
return nil, fmt.Errorf("%w: %s", errSubPath, path)
|
||||
}
|
||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
||||
} else {
|
||||
path := C.Path.GetPathByHash("proxies", schema.URL)
|
||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||
}
|
||||
|
@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/adapter"
|
||||
"github.com/Dreamacro/clash/common/convert"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||
"github.com/Dreamacro/clash/component/resource"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
@ -50,6 +51,7 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||
"type": pp.Type().String(),
|
||||
"vehicleType": pp.VehicleType().String(),
|
||||
"proxies": pp.Proxies(),
|
||||
"testUrl": pp.healthCheck.url,
|
||||
"updatedAt": pp.UpdatedAt,
|
||||
"subscriptionInfo": pp.subscriptionInfo,
|
||||
})
|
||||
@ -98,6 +100,10 @@ func (pp *proxySetProvider) Touch() {
|
||||
pp.healthCheck.touch()
|
||||
}
|
||||
|
||||
func (pp *proxySetProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||
pp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||
}
|
||||
|
||||
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
||||
pp.proxies = proxies
|
||||
pp.healthCheck.setProxy(proxies)
|
||||
@ -141,15 +147,15 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
||||
}
|
||||
|
||||
func (pp *proxySetProvider) closeAllConnections() {
|
||||
snapshot := statistic.DefaultManager.Snapshot()
|
||||
for _, c := range snapshot.Connections {
|
||||
statistic.DefaultManager.Range(func(c statistic.Tracker) bool {
|
||||
for _, chain := range c.Chains() {
|
||||
if chain == pp.Name() {
|
||||
_ = c.Close()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func stopProxyProvider(pd *ProxySetProvider) {
|
||||
@ -210,6 +216,7 @@ func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||
"type": cp.Type().String(),
|
||||
"vehicleType": cp.VehicleType().String(),
|
||||
"proxies": cp.Proxies(),
|
||||
"testUrl": cp.healthCheck.url,
|
||||
})
|
||||
}
|
||||
|
||||
@ -249,6 +256,10 @@ func (cp *compatibleProvider) Touch() {
|
||||
cp.healthCheck.touch()
|
||||
}
|
||||
|
||||
func (cp *compatibleProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||
cp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||
}
|
||||
|
||||
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||
pd.healthCheck.close()
|
||||
}
|
||||
@ -288,7 +299,7 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||
proxies, err1 := convert.ConvertsV2Ray(buf)
|
||||
if err1 != nil {
|
||||
return nil, fmt.Errorf("%s, %w", err.Error(), err1)
|
||||
return nil, fmt.Errorf("%w, %w", err, err1)
|
||||
}
|
||||
schema.Proxies = proxies
|
||||
}
|
||||
|
@ -11,8 +11,6 @@ type Buffer = buf.Buffer
|
||||
|
||||
var New = buf.New
|
||||
var NewSize = buf.NewSize
|
||||
var StackNew = buf.StackNew
|
||||
var StackNewSize = buf.StackNewSize
|
||||
var With = buf.With
|
||||
var As = buf.As
|
||||
|
||||
|
42
common/cache/lrucache.go
vendored
42
common/cache/lrucache.go
vendored
@ -82,6 +82,9 @@ func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
||||
// Get returns the any representation of a cached response and a bool
|
||||
// set to true if the key was found.
|
||||
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
el := c.get(key)
|
||||
if el == nil {
|
||||
return getZero[V](), false
|
||||
@ -91,11 +94,29 @@ func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
||||
return value, true
|
||||
}
|
||||
|
||||
func (c *LruCache[K, V]) GetOrStore(key K, constructor func() V) (V, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
el := c.get(key)
|
||||
if el == nil {
|
||||
value := constructor()
|
||||
c.set(key, value)
|
||||
return value, false
|
||||
}
|
||||
value := el.value
|
||||
|
||||
return value, true
|
||||
}
|
||||
|
||||
// GetWithExpire returns the any representation of a cached response,
|
||||
// a time.Time Give expected expires,
|
||||
// and a bool set to true if the key was found.
|
||||
// This method will NOT check the maxAge of element and will NOT update the expires.
|
||||
func (c *LruCache[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
el := c.get(key)
|
||||
if el == nil {
|
||||
return getZero[V](), time.Time{}, false
|
||||
@ -115,11 +136,18 @@ func (c *LruCache[K, V]) Exist(key K) bool {
|
||||
|
||||
// Set stores the any representation of a response for a given key.
|
||||
func (c *LruCache[K, V]) Set(key K, value V) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
c.set(key, value)
|
||||
}
|
||||
|
||||
func (c *LruCache[K, V]) set(key K, value V) {
|
||||
expires := int64(0)
|
||||
if c.maxAge > 0 {
|
||||
expires = time.Now().Unix() + c.maxAge
|
||||
}
|
||||
c.SetWithExpire(key, value, time.Unix(expires, 0))
|
||||
c.setWithExpire(key, value, time.Unix(expires, 0))
|
||||
}
|
||||
|
||||
// SetWithExpire stores the any representation of a response for a given key and given expires.
|
||||
@ -128,6 +156,10 @@ func (c *LruCache[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
c.setWithExpire(key, value, expires)
|
||||
}
|
||||
|
||||
func (c *LruCache[K, V]) setWithExpire(key K, value V, expires time.Time) {
|
||||
if le, ok := c.cache[key]; ok {
|
||||
c.lru.MoveToBack(le)
|
||||
e := le.Value
|
||||
@ -165,9 +197,6 @@ func (c *LruCache[K, V]) CloneTo(n *LruCache[K, V]) {
|
||||
}
|
||||
|
||||
func (c *LruCache[K, V]) get(key K) *entry[K, V] {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
le, ok := c.cache[key]
|
||||
if !ok {
|
||||
return nil
|
||||
@ -191,12 +220,11 @@ func (c *LruCache[K, V]) get(key K) *entry[K, V] {
|
||||
// Delete removes the value associated with a key.
|
||||
func (c *LruCache[K, V]) Delete(key K) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if le, ok := c.cache[key]; ok {
|
||||
c.deleteElement(le)
|
||||
}
|
||||
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *LruCache[K, V]) maybeDeleteOldest() {
|
||||
@ -219,10 +247,10 @@ func (c *LruCache[K, V]) deleteElement(le *list.Element[*entry[K, V]]) {
|
||||
|
||||
func (c *LruCache[K, V]) Clear() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
c.cache = make(map[K]*list.Element[*entry[K, V]])
|
||||
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -3,34 +3,43 @@ package net
|
||||
import "net"
|
||||
|
||||
type bindPacketConn struct {
|
||||
net.PacketConn
|
||||
EnhancePacketConn
|
||||
rAddr net.Addr
|
||||
}
|
||||
|
||||
func (wpc *bindPacketConn) Read(b []byte) (n int, err error) {
|
||||
n, _, err = wpc.PacketConn.ReadFrom(b)
|
||||
func (c *bindPacketConn) Read(b []byte) (n int, err error) {
|
||||
n, _, err = c.EnhancePacketConn.ReadFrom(b)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (wpc *bindPacketConn) Write(b []byte) (n int, err error) {
|
||||
return wpc.PacketConn.WriteTo(b, wpc.rAddr)
|
||||
func (c *bindPacketConn) WaitRead() (data []byte, put func(), err error) {
|
||||
data, put, _, err = c.EnhancePacketConn.WaitReadFrom()
|
||||
return
|
||||
}
|
||||
|
||||
func (wpc *bindPacketConn) RemoteAddr() net.Addr {
|
||||
return wpc.rAddr
|
||||
func (c *bindPacketConn) Write(b []byte) (n int, err error) {
|
||||
return c.EnhancePacketConn.WriteTo(b, c.rAddr)
|
||||
}
|
||||
|
||||
func (wpc *bindPacketConn) LocalAddr() net.Addr {
|
||||
if wpc.PacketConn.LocalAddr() == nil {
|
||||
func (c *bindPacketConn) RemoteAddr() net.Addr {
|
||||
return c.rAddr
|
||||
}
|
||||
|
||||
func (c *bindPacketConn) LocalAddr() net.Addr {
|
||||
if c.EnhancePacketConn.LocalAddr() == nil {
|
||||
return &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||
} else {
|
||||
return wpc.PacketConn.LocalAddr()
|
||||
return c.EnhancePacketConn.LocalAddr()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *bindPacketConn) Upstream() any {
|
||||
return c.EnhancePacketConn
|
||||
}
|
||||
|
||||
func NewBindPacketConn(pc net.PacketConn, rAddr net.Addr) net.Conn {
|
||||
return &bindPacketConn{
|
||||
PacketConn: pc,
|
||||
rAddr: rAddr,
|
||||
EnhancePacketConn: NewEnhancePacketConn(pc),
|
||||
rAddr: rAddr,
|
||||
}
|
||||
}
|
||||
|
@ -62,7 +62,7 @@ func (c *BufferedConn) Buffered() int {
|
||||
}
|
||||
|
||||
func (c *BufferedConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
||||
if c.r.Buffered() > 0 {
|
||||
if c.r != nil && c.r.Buffered() > 0 {
|
||||
_, err = buffer.ReadOnceFrom(c.r)
|
||||
return
|
||||
}
|
||||
@ -70,10 +70,11 @@ func (c *BufferedConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
||||
}
|
||||
|
||||
func (c *BufferedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.Copy
|
||||
if c.r.Buffered() > 0 {
|
||||
if c.r != nil && c.r.Buffered() > 0 {
|
||||
length := c.r.Buffered()
|
||||
b, _ := c.r.Peek(length)
|
||||
_, _ = c.r.Discard(length)
|
||||
c.r = nil // drop bufio.Reader to let gc can clean up its internal buf
|
||||
return buf.As(b)
|
||||
}
|
||||
return nil
|
||||
@ -84,7 +85,7 @@ func (c *BufferedConn) Upstream() any {
|
||||
}
|
||||
|
||||
func (c *BufferedConn) ReaderReplaceable() bool {
|
||||
if c.r.Buffered() > 0 {
|
||||
if c.r != nil && c.r.Buffered() > 0 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
|
154
common/net/deadline/packet.go
Normal file
154
common/net/deadline/packet.go
Normal file
@ -0,0 +1,154 @@
|
||||
package deadline
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/atomic"
|
||||
"github.com/Dreamacro/clash/common/net/packet"
|
||||
)
|
||||
|
||||
type readResult struct {
|
||||
data []byte
|
||||
addr net.Addr
|
||||
err error
|
||||
}
|
||||
|
||||
type NetPacketConn struct {
|
||||
net.PacketConn
|
||||
deadline atomic.TypedValue[time.Time]
|
||||
pipeDeadline pipeDeadline
|
||||
disablePipe atomic.Bool
|
||||
inRead atomic.Bool
|
||||
resultCh chan any
|
||||
}
|
||||
|
||||
func NewNetPacketConn(pc net.PacketConn) net.PacketConn {
|
||||
npc := &NetPacketConn{
|
||||
PacketConn: pc,
|
||||
pipeDeadline: makePipeDeadline(),
|
||||
resultCh: make(chan any, 1),
|
||||
}
|
||||
npc.resultCh <- nil
|
||||
if enhancePC, isEnhance := pc.(packet.EnhancePacketConn); isEnhance {
|
||||
epc := &EnhancePacketConn{
|
||||
NetPacketConn: npc,
|
||||
enhancePacketConn: enhancePacketConn{
|
||||
netPacketConn: npc,
|
||||
enhancePacketConn: enhancePC,
|
||||
},
|
||||
}
|
||||
if singPC, isSingPC := pc.(packet.SingPacketConn); isSingPC {
|
||||
return &EnhanceSingPacketConn{
|
||||
EnhancePacketConn: epc,
|
||||
singPacketConn: singPacketConn{
|
||||
netPacketConn: npc,
|
||||
singPacketConn: singPC,
|
||||
},
|
||||
}
|
||||
}
|
||||
return epc
|
||||
}
|
||||
if singPC, isSingPC := pc.(packet.SingPacketConn); isSingPC {
|
||||
return &SingPacketConn{
|
||||
NetPacketConn: npc,
|
||||
singPacketConn: singPacketConn{
|
||||
netPacketConn: npc,
|
||||
singPacketConn: singPC,
|
||||
},
|
||||
}
|
||||
}
|
||||
return npc
|
||||
}
|
||||
|
||||
func (c *NetPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||
FOR:
|
||||
for {
|
||||
select {
|
||||
case result := <-c.resultCh:
|
||||
if result != nil {
|
||||
if result, ok := result.(*readResult); ok {
|
||||
n = copy(p, result.data)
|
||||
addr = result.addr
|
||||
err = result.err
|
||||
c.resultCh <- nil // finish cache read
|
||||
return
|
||||
}
|
||||
c.resultCh <- result // another type of read
|
||||
runtime.Gosched() // allowing other goroutines to run
|
||||
continue FOR
|
||||
} else {
|
||||
c.resultCh <- nil
|
||||
break FOR
|
||||
}
|
||||
case <-c.pipeDeadline.wait():
|
||||
return 0, nil, os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
|
||||
if c.disablePipe.Load() {
|
||||
return c.PacketConn.ReadFrom(p)
|
||||
} else if c.deadline.Load().IsZero() {
|
||||
c.inRead.Store(true)
|
||||
defer c.inRead.Store(false)
|
||||
n, addr, err = c.PacketConn.ReadFrom(p)
|
||||
return
|
||||
}
|
||||
|
||||
<-c.resultCh
|
||||
go c.pipeReadFrom(len(p))
|
||||
|
||||
return c.ReadFrom(p)
|
||||
}
|
||||
|
||||
func (c *NetPacketConn) pipeReadFrom(size int) {
|
||||
buffer := make([]byte, size)
|
||||
n, addr, err := c.PacketConn.ReadFrom(buffer)
|
||||
buffer = buffer[:n]
|
||||
result := &readResult{}
|
||||
result.data = buffer
|
||||
result.addr = addr
|
||||
result.err = err
|
||||
c.resultCh <- result
|
||||
}
|
||||
|
||||
func (c *NetPacketConn) SetReadDeadline(t time.Time) error {
|
||||
if c.disablePipe.Load() {
|
||||
return c.PacketConn.SetReadDeadline(t)
|
||||
} else if c.inRead.Load() {
|
||||
c.disablePipe.Store(true)
|
||||
return c.PacketConn.SetReadDeadline(t)
|
||||
}
|
||||
c.deadline.Store(t)
|
||||
c.pipeDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *NetPacketConn) ReaderReplaceable() bool {
|
||||
select {
|
||||
case result := <-c.resultCh:
|
||||
c.resultCh <- result
|
||||
if result != nil {
|
||||
return false // cache reading
|
||||
} else {
|
||||
break
|
||||
}
|
||||
default:
|
||||
return false // pipe reading
|
||||
}
|
||||
return c.disablePipe.Load() || c.deadline.Load().IsZero()
|
||||
}
|
||||
|
||||
func (c *NetPacketConn) WriterReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *NetPacketConn) Upstream() any {
|
||||
return c.PacketConn
|
||||
}
|
||||
|
||||
func (c *NetPacketConn) NeedAdditionalReadDeadline() bool {
|
||||
return false
|
||||
}
|
83
common/net/deadline/packet_enhance.go
Normal file
83
common/net/deadline/packet_enhance.go
Normal file
@ -0,0 +1,83 @@
|
||||
package deadline
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"github.com/Dreamacro/clash/common/net/packet"
|
||||
)
|
||||
|
||||
type EnhancePacketConn struct {
|
||||
*NetPacketConn
|
||||
enhancePacketConn
|
||||
}
|
||||
|
||||
var _ packet.EnhancePacketConn = (*EnhancePacketConn)(nil)
|
||||
|
||||
func NewEnhancePacketConn(pc packet.EnhancePacketConn) packet.EnhancePacketConn {
|
||||
return NewNetPacketConn(pc).(packet.EnhancePacketConn)
|
||||
}
|
||||
|
||||
type enhanceReadResult struct {
|
||||
data []byte
|
||||
put func()
|
||||
addr net.Addr
|
||||
err error
|
||||
}
|
||||
|
||||
type enhancePacketConn struct {
|
||||
netPacketConn *NetPacketConn
|
||||
enhancePacketConn packet.EnhancePacketConn
|
||||
}
|
||||
|
||||
func (c *enhancePacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||
FOR:
|
||||
for {
|
||||
select {
|
||||
case result := <-c.netPacketConn.resultCh:
|
||||
if result != nil {
|
||||
if result, ok := result.(*enhanceReadResult); ok {
|
||||
data = result.data
|
||||
put = result.put
|
||||
addr = result.addr
|
||||
err = result.err
|
||||
c.netPacketConn.resultCh <- nil // finish cache read
|
||||
return
|
||||
}
|
||||
c.netPacketConn.resultCh <- result // another type of read
|
||||
runtime.Gosched() // allowing other goroutines to run
|
||||
continue FOR
|
||||
} else {
|
||||
c.netPacketConn.resultCh <- nil
|
||||
break FOR
|
||||
}
|
||||
case <-c.netPacketConn.pipeDeadline.wait():
|
||||
return nil, nil, nil, os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
|
||||
if c.netPacketConn.disablePipe.Load() {
|
||||
return c.enhancePacketConn.WaitReadFrom()
|
||||
} else if c.netPacketConn.deadline.Load().IsZero() {
|
||||
c.netPacketConn.inRead.Store(true)
|
||||
defer c.netPacketConn.inRead.Store(false)
|
||||
data, put, addr, err = c.enhancePacketConn.WaitReadFrom()
|
||||
return
|
||||
}
|
||||
|
||||
<-c.netPacketConn.resultCh
|
||||
go c.pipeWaitReadFrom()
|
||||
|
||||
return c.WaitReadFrom()
|
||||
}
|
||||
|
||||
func (c *enhancePacketConn) pipeWaitReadFrom() {
|
||||
data, put, addr, err := c.enhancePacketConn.WaitReadFrom()
|
||||
result := &enhanceReadResult{}
|
||||
result.data = data
|
||||
result.put = put
|
||||
result.addr = addr
|
||||
result.err = err
|
||||
c.netPacketConn.resultCh <- result
|
||||
}
|
177
common/net/deadline/packet_sing.go
Normal file
177
common/net/deadline/packet_sing.go
Normal file
@ -0,0 +1,177 @@
|
||||
package deadline
|
||||
|
||||
import (
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"github.com/Dreamacro/clash/common/net/packet"
|
||||
"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 SingPacketConn struct {
|
||||
*NetPacketConn
|
||||
singPacketConn
|
||||
}
|
||||
|
||||
var _ packet.SingPacketConn = (*SingPacketConn)(nil)
|
||||
|
||||
func NewSingPacketConn(pc packet.SingPacketConn) packet.SingPacketConn {
|
||||
return NewNetPacketConn(pc).(packet.SingPacketConn)
|
||||
}
|
||||
|
||||
type EnhanceSingPacketConn struct {
|
||||
*EnhancePacketConn
|
||||
singPacketConn
|
||||
}
|
||||
|
||||
func NewEnhanceSingPacketConn(pc packet.EnhanceSingPacketConn) packet.EnhanceSingPacketConn {
|
||||
return NewNetPacketConn(pc).(packet.EnhanceSingPacketConn)
|
||||
}
|
||||
|
||||
var _ packet.EnhanceSingPacketConn = (*EnhanceSingPacketConn)(nil)
|
||||
|
||||
type singReadResult struct {
|
||||
buffer *buf.Buffer
|
||||
destination M.Socksaddr
|
||||
err error
|
||||
}
|
||||
|
||||
type singPacketConn struct {
|
||||
netPacketConn *NetPacketConn
|
||||
singPacketConn packet.SingPacketConn
|
||||
}
|
||||
|
||||
func (c *singPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
||||
FOR:
|
||||
for {
|
||||
select {
|
||||
case result := <-c.netPacketConn.resultCh:
|
||||
if result != nil {
|
||||
if result, ok := result.(*singReadResult); ok {
|
||||
destination = result.destination
|
||||
err = result.err
|
||||
n, _ := buffer.Write(result.buffer.Bytes())
|
||||
result.buffer.Advance(n)
|
||||
if result.buffer.IsEmpty() {
|
||||
result.buffer.Release()
|
||||
}
|
||||
c.netPacketConn.resultCh <- nil // finish cache read
|
||||
return
|
||||
}
|
||||
c.netPacketConn.resultCh <- result // another type of read
|
||||
runtime.Gosched() // allowing other goroutines to run
|
||||
continue FOR
|
||||
} else {
|
||||
c.netPacketConn.resultCh <- nil
|
||||
break FOR
|
||||
}
|
||||
case <-c.netPacketConn.pipeDeadline.wait():
|
||||
return M.Socksaddr{}, os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
|
||||
if c.netPacketConn.disablePipe.Load() {
|
||||
return c.singPacketConn.ReadPacket(buffer)
|
||||
} else if c.netPacketConn.deadline.Load().IsZero() {
|
||||
c.netPacketConn.inRead.Store(true)
|
||||
defer c.netPacketConn.inRead.Store(false)
|
||||
destination, err = c.singPacketConn.ReadPacket(buffer)
|
||||
return
|
||||
}
|
||||
|
||||
<-c.netPacketConn.resultCh
|
||||
go c.pipeReadPacket(buffer.FreeLen())
|
||||
|
||||
return c.ReadPacket(buffer)
|
||||
}
|
||||
|
||||
func (c *singPacketConn) pipeReadPacket(pLen int) {
|
||||
buffer := buf.NewSize(pLen)
|
||||
destination, err := c.singPacketConn.ReadPacket(buffer)
|
||||
result := &singReadResult{}
|
||||
result.destination = destination
|
||||
result.err = err
|
||||
c.netPacketConn.resultCh <- result
|
||||
}
|
||||
|
||||
func (c *singPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||
return c.singPacketConn.WritePacket(buffer, destination)
|
||||
}
|
||||
|
||||
func (c *singPacketConn) CreateReadWaiter() (N.PacketReadWaiter, bool) {
|
||||
prw, isReadWaiter := bufio.CreatePacketReadWaiter(c.singPacketConn)
|
||||
if isReadWaiter {
|
||||
return &singPacketReadWaiter{
|
||||
netPacketConn: c.netPacketConn,
|
||||
packetReadWaiter: prw,
|
||||
}, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
var _ N.PacketReadWaiter = (*singPacketReadWaiter)(nil)
|
||||
|
||||
type singPacketReadWaiter struct {
|
||||
netPacketConn *NetPacketConn
|
||||
packetReadWaiter N.PacketReadWaiter
|
||||
}
|
||||
|
||||
type singWaitReadResult singReadResult
|
||||
|
||||
func (c *singPacketReadWaiter) InitializeReadWaiter(newBuffer func() *buf.Buffer) {
|
||||
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
||||
}
|
||||
|
||||
func (c *singPacketReadWaiter) WaitReadPacket() (destination M.Socksaddr, err error) {
|
||||
FOR:
|
||||
for {
|
||||
select {
|
||||
case result := <-c.netPacketConn.resultCh:
|
||||
if result != nil {
|
||||
if result, ok := result.(*singWaitReadResult); ok {
|
||||
destination = result.destination
|
||||
err = result.err
|
||||
c.netPacketConn.resultCh <- nil // finish cache read
|
||||
return
|
||||
}
|
||||
c.netPacketConn.resultCh <- result // another type of read
|
||||
runtime.Gosched() // allowing other goroutines to run
|
||||
continue FOR
|
||||
} else {
|
||||
c.netPacketConn.resultCh <- nil
|
||||
break FOR
|
||||
}
|
||||
case <-c.netPacketConn.pipeDeadline.wait():
|
||||
return M.Socksaddr{}, os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
|
||||
if c.netPacketConn.disablePipe.Load() {
|
||||
return c.packetReadWaiter.WaitReadPacket()
|
||||
} else if c.netPacketConn.deadline.Load().IsZero() {
|
||||
c.netPacketConn.inRead.Store(true)
|
||||
defer c.netPacketConn.inRead.Store(false)
|
||||
destination, err = c.packetReadWaiter.WaitReadPacket()
|
||||
return
|
||||
}
|
||||
|
||||
<-c.netPacketConn.resultCh
|
||||
go c.pipeWaitReadPacket()
|
||||
|
||||
return c.WaitReadPacket()
|
||||
}
|
||||
|
||||
func (c *singPacketReadWaiter) pipeWaitReadPacket() {
|
||||
destination, err := c.packetReadWaiter.WaitReadPacket()
|
||||
result := &singWaitReadResult{}
|
||||
result.destination = destination
|
||||
result.err = err
|
||||
c.netPacketConn.resultCh <- result
|
||||
}
|
||||
|
||||
func (c *singPacketReadWaiter) Upstream() any {
|
||||
return c.packetReadWaiter
|
||||
}
|
84
common/net/deadline/pipe.go
Normal file
84
common/net/deadline/pipe.go
Normal file
@ -0,0 +1,84 @@
|
||||
// Copyright 2010 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package deadline
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// pipeDeadline is an abstraction for handling timeouts.
|
||||
type pipeDeadline struct {
|
||||
mu sync.Mutex // Guards timer and cancel
|
||||
timer *time.Timer
|
||||
cancel chan struct{} // Must be non-nil
|
||||
}
|
||||
|
||||
func makePipeDeadline() pipeDeadline {
|
||||
return pipeDeadline{cancel: make(chan struct{})}
|
||||
}
|
||||
|
||||
// set sets the point in time when the deadline will time out.
|
||||
// A timeout event is signaled by closing the channel returned by waiter.
|
||||
// Once a timeout has occurred, the deadline can be refreshed by specifying a
|
||||
// t value in the future.
|
||||
//
|
||||
// A zero value for t prevents timeout.
|
||||
func (d *pipeDeadline) set(t time.Time) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if d.timer != nil && !d.timer.Stop() {
|
||||
<-d.cancel // Wait for the timer callback to finish and close cancel
|
||||
}
|
||||
d.timer = nil
|
||||
|
||||
// Time is zero, then there is no deadline.
|
||||
closed := isClosedChan(d.cancel)
|
||||
if t.IsZero() {
|
||||
if closed {
|
||||
d.cancel = make(chan struct{})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Time in the future, setup a timer to cancel in the future.
|
||||
if dur := time.Until(t); dur > 0 {
|
||||
if closed {
|
||||
d.cancel = make(chan struct{})
|
||||
}
|
||||
d.timer = time.AfterFunc(dur, func() {
|
||||
close(d.cancel)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Time in the past, so close immediately.
|
||||
if !closed {
|
||||
close(d.cancel)
|
||||
}
|
||||
}
|
||||
|
||||
// wait returns a channel that is closed when the deadline is exceeded.
|
||||
func (d *pipeDeadline) wait() chan struct{} {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.cancel
|
||||
}
|
||||
|
||||
func isClosedChan(c <-chan struct{}) bool {
|
||||
select {
|
||||
case <-c:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func makeFilledChan() chan struct{} {
|
||||
ch := make(chan struct{}, 1)
|
||||
ch <- struct{}{}
|
||||
return ch
|
||||
}
|
18
common/net/packet.go
Normal file
18
common/net/packet.go
Normal file
@ -0,0 +1,18 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"github.com/Dreamacro/clash/common/net/deadline"
|
||||
"github.com/Dreamacro/clash/common/net/packet"
|
||||
)
|
||||
|
||||
type EnhancePacketConn = packet.EnhancePacketConn
|
||||
type WaitReadFrom = packet.WaitReadFrom
|
||||
|
||||
var NewEnhancePacketConn = packet.NewEnhancePacketConn
|
||||
var NewThreadSafePacketConn = packet.NewThreadSafePacketConn
|
||||
var NewRefPacketConn = packet.NewRefPacketConn
|
||||
|
||||
var NewDeadlineNetPacketConn = deadline.NewNetPacketConn
|
||||
var NewDeadlineEnhancePacketConn = deadline.NewEnhancePacketConn
|
||||
var NewDeadlineSingPacketConn = deadline.NewSingPacketConn
|
||||
var NewDeadlineEnhanceSingPacketConn = deadline.NewEnhanceSingPacketConn
|
77
common/net/packet/packet.go
Normal file
77
common/net/packet/packet.go
Normal file
@ -0,0 +1,77 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
)
|
||||
|
||||
type WaitReadFrom interface {
|
||||
WaitReadFrom() (data []byte, put func(), addr net.Addr, err error)
|
||||
}
|
||||
|
||||
type EnhancePacketConn interface {
|
||||
net.PacketConn
|
||||
WaitReadFrom
|
||||
}
|
||||
|
||||
func NewEnhancePacketConn(pc net.PacketConn) EnhancePacketConn {
|
||||
if udpConn, isUDPConn := pc.(*net.UDPConn); isUDPConn {
|
||||
return &enhanceUDPConn{UDPConn: udpConn}
|
||||
}
|
||||
if enhancePC, isEnhancePC := pc.(EnhancePacketConn); isEnhancePC {
|
||||
return enhancePC
|
||||
}
|
||||
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
||||
return newEnhanceSingPacketConn(singPC)
|
||||
}
|
||||
return &enhancePacketConn{PacketConn: pc}
|
||||
}
|
||||
|
||||
type enhancePacketConn struct {
|
||||
net.PacketConn
|
||||
}
|
||||
|
||||
func (c *enhancePacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||
return waitReadFrom(c.PacketConn)
|
||||
}
|
||||
|
||||
func (c *enhancePacketConn) Upstream() any {
|
||||
return c.PacketConn
|
||||
}
|
||||
|
||||
func (c *enhancePacketConn) WriterReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *enhancePacketConn) ReaderReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *enhanceUDPConn) Upstream() any {
|
||||
return c.UDPConn
|
||||
}
|
||||
|
||||
func (c *enhanceUDPConn) WriterReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *enhanceUDPConn) ReaderReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func waitReadFrom(pc net.PacketConn) (data []byte, put func(), addr net.Addr, err error) {
|
||||
readBuf := pool.Get(pool.UDPBufferSize)
|
||||
put = func() {
|
||||
_ = pool.Put(readBuf)
|
||||
}
|
||||
var readN int
|
||||
readN, addr, err = pc.ReadFrom(readBuf)
|
||||
if readN > 0 {
|
||||
data = readBuf[:readN]
|
||||
} else {
|
||||
put()
|
||||
put = nil
|
||||
}
|
||||
return
|
||||
}
|
65
common/net/packet/packet_posix.go
Normal file
65
common/net/packet/packet_posix.go
Normal file
@ -0,0 +1,65 @@
|
||||
//go:build !windows
|
||||
|
||||
package packet
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
)
|
||||
|
||||
type enhanceUDPConn struct {
|
||||
*net.UDPConn
|
||||
rawConn syscall.RawConn
|
||||
}
|
||||
|
||||
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||
if c.rawConn == nil {
|
||||
c.rawConn, _ = c.UDPConn.SyscallConn()
|
||||
}
|
||||
var readErr error
|
||||
err = c.rawConn.Read(func(fd uintptr) (done bool) {
|
||||
readBuf := pool.Get(pool.UDPBufferSize)
|
||||
put = func() {
|
||||
_ = pool.Put(readBuf)
|
||||
}
|
||||
var readFrom syscall.Sockaddr
|
||||
var readN int
|
||||
readN, _, _, readFrom, readErr = syscall.Recvmsg(int(fd), readBuf, nil, 0)
|
||||
if readN > 0 {
|
||||
data = readBuf[:readN]
|
||||
} else {
|
||||
put()
|
||||
put = nil
|
||||
data = nil
|
||||
}
|
||||
if readErr == syscall.EAGAIN {
|
||||
return false
|
||||
}
|
||||
if readFrom != nil {
|
||||
switch from := readFrom.(type) {
|
||||
case *syscall.SockaddrInet4:
|
||||
ip := from.Addr // copy from.Addr; ip escapes, so this line allocates 4 bytes
|
||||
addr = &net.UDPAddr{IP: ip[:], Port: from.Port}
|
||||
case *syscall.SockaddrInet6:
|
||||
ip := from.Addr // copy from.Addr; ip escapes, so this line allocates 16 bytes
|
||||
addr = &net.UDPAddr{IP: ip[:], Port: from.Port, Zone: strconv.FormatInt(int64(from.ZoneId), 10)}
|
||||
}
|
||||
}
|
||||
// udp should not convert readN == 0 to io.EOF
|
||||
//if readN == 0 {
|
||||
// readErr = io.EOF
|
||||
//}
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if readErr != nil {
|
||||
err = readErr
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
79
common/net/packet/packet_sing.go
Normal file
79
common/net/packet/packet_sing.go
Normal file
@ -0,0 +1,79 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"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 SingPacketConn = N.NetPacketConn
|
||||
|
||||
type EnhanceSingPacketConn interface {
|
||||
SingPacketConn
|
||||
EnhancePacketConn
|
||||
}
|
||||
|
||||
type enhanceSingPacketConn struct {
|
||||
SingPacketConn
|
||||
packetReadWaiter N.PacketReadWaiter
|
||||
}
|
||||
|
||||
func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||
var buff *buf.Buffer
|
||||
var dest M.Socksaddr
|
||||
newBuffer := func() *buf.Buffer {
|
||||
buff = buf.NewPacket() // do not use stack buffer
|
||||
return buff
|
||||
}
|
||||
if c.packetReadWaiter != nil {
|
||||
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
||||
defer c.packetReadWaiter.InitializeReadWaiter(nil)
|
||||
dest, err = c.packetReadWaiter.WaitReadPacket()
|
||||
} else {
|
||||
dest, err = c.SingPacketConn.ReadPacket(newBuffer())
|
||||
}
|
||||
if dest.IsFqdn() {
|
||||
addr = dest
|
||||
} else {
|
||||
addr = dest.UDPAddr()
|
||||
}
|
||||
if err != nil {
|
||||
if buff != nil {
|
||||
buff.Release()
|
||||
}
|
||||
return
|
||||
}
|
||||
if buff == nil {
|
||||
return
|
||||
}
|
||||
if buff.IsEmpty() {
|
||||
buff.Release()
|
||||
return
|
||||
}
|
||||
data = buff.Bytes()
|
||||
put = buff.Release
|
||||
return
|
||||
}
|
||||
|
||||
func (c *enhanceSingPacketConn) Upstream() any {
|
||||
return c.SingPacketConn
|
||||
}
|
||||
|
||||
func (c *enhanceSingPacketConn) WriterReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *enhanceSingPacketConn) ReaderReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func newEnhanceSingPacketConn(conn SingPacketConn) *enhanceSingPacketConn {
|
||||
epc := &enhanceSingPacketConn{SingPacketConn: conn}
|
||||
if readWaiter, isReadWaiter := bufio.CreatePacketReadWaiter(conn); isReadWaiter {
|
||||
epc.packetReadWaiter = readWaiter
|
||||
}
|
||||
return epc
|
||||
}
|
15
common/net/packet/packet_windows.go
Normal file
15
common/net/packet/packet_windows.go
Normal file
@ -0,0 +1,15 @@
|
||||
//go:build windows
|
||||
|
||||
package packet
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
type enhanceUDPConn struct {
|
||||
*net.UDPConn
|
||||
}
|
||||
|
||||
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||
return waitReadFrom(c.UDPConn)
|
||||
}
|
75
common/net/packet/ref.go
Normal file
75
common/net/packet/ref.go
Normal file
@ -0,0 +1,75 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"net"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
type refPacketConn struct {
|
||||
pc EnhancePacketConn
|
||||
ref any
|
||||
}
|
||||
|
||||
func (c *refPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.pc.WaitReadFrom()
|
||||
}
|
||||
|
||||
func (c *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.pc.ReadFrom(p)
|
||||
}
|
||||
|
||||
func (c *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.pc.WriteTo(p, addr)
|
||||
}
|
||||
|
||||
func (c *refPacketConn) Close() error {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.pc.Close()
|
||||
}
|
||||
|
||||
func (c *refPacketConn) LocalAddr() net.Addr {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.pc.LocalAddr()
|
||||
}
|
||||
|
||||
func (c *refPacketConn) SetDeadline(t time.Time) error {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.pc.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (c *refPacketConn) SetReadDeadline(t time.Time) error {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.pc.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (c *refPacketConn) SetWriteDeadline(t time.Time) error {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.pc.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (c *refPacketConn) Upstream() any {
|
||||
return c.pc
|
||||
}
|
||||
|
||||
func (c *refPacketConn) ReaderReplaceable() bool { // Relay() will handle reference
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *refPacketConn) WriterReplaceable() bool { // Relay() will handle reference
|
||||
return true
|
||||
}
|
||||
|
||||
func NewRefPacketConn(pc net.PacketConn, ref any) EnhancePacketConn {
|
||||
rPC := &refPacketConn{pc: NewEnhancePacketConn(pc), ref: ref}
|
||||
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
||||
return &refSingPacketConn{
|
||||
refPacketConn: rPC,
|
||||
singPacketConn: singPC,
|
||||
}
|
||||
}
|
||||
return rPC
|
||||
}
|
26
common/net/packet/ref_sing.go
Normal file
26
common/net/packet/ref_sing.go
Normal file
@ -0,0 +1,26 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
type refSingPacketConn struct {
|
||||
*refPacketConn
|
||||
singPacketConn SingPacketConn
|
||||
}
|
||||
|
||||
var _ N.NetPacketConn = (*refSingPacketConn)(nil)
|
||||
|
||||
func (c *refSingPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.singPacketConn.WritePacket(buffer, destination)
|
||||
}
|
||||
|
||||
func (c *refSingPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
||||
defer runtime.KeepAlive(c.ref)
|
||||
return c.singPacketConn.ReadPacket(buffer)
|
||||
}
|
36
common/net/packet/thread.go
Normal file
36
common/net/packet/thread.go
Normal file
@ -0,0 +1,36 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type threadSafePacketConn struct {
|
||||
EnhancePacketConn
|
||||
access sync.Mutex
|
||||
}
|
||||
|
||||
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
c.access.Lock()
|
||||
defer c.access.Unlock()
|
||||
return c.EnhancePacketConn.WriteTo(b, addr)
|
||||
}
|
||||
|
||||
func (c *threadSafePacketConn) Upstream() any {
|
||||
return c.EnhancePacketConn
|
||||
}
|
||||
|
||||
func (c *threadSafePacketConn) ReaderReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func NewThreadSafePacketConn(pc net.PacketConn) EnhancePacketConn {
|
||||
tsPC := &threadSafePacketConn{EnhancePacketConn: NewEnhancePacketConn(pc)}
|
||||
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
||||
return &threadSafeSingPacketConn{
|
||||
threadSafePacketConn: tsPC,
|
||||
singPacketConn: singPC,
|
||||
}
|
||||
}
|
||||
return tsPC
|
||||
}
|
24
common/net/packet/thread_sing.go
Normal file
24
common/net/packet/thread_sing.go
Normal file
@ -0,0 +1,24 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
type threadSafeSingPacketConn struct {
|
||||
*threadSafePacketConn
|
||||
singPacketConn SingPacketConn
|
||||
}
|
||||
|
||||
var _ N.NetPacketConn = (*threadSafeSingPacketConn)(nil)
|
||||
|
||||
func (c *threadSafeSingPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||
c.access.Lock()
|
||||
defer c.access.Unlock()
|
||||
return c.singPacketConn.WritePacket(buffer, destination)
|
||||
}
|
||||
|
||||
func (c *threadSafeSingPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
||||
return c.singPacketConn.ReadPacket(buffer)
|
||||
}
|
@ -80,47 +80,3 @@ var _ ExtendedConn = (*refConn)(nil)
|
||||
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
||||
return &refConn{conn: NewExtendedConn(conn), ref: ref}
|
||||
}
|
||||
|
||||
type refPacketConn struct {
|
||||
pc net.PacketConn
|
||||
ref any
|
||||
}
|
||||
|
||||
func (pc *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||
defer runtime.KeepAlive(pc.ref)
|
||||
return pc.pc.ReadFrom(p)
|
||||
}
|
||||
|
||||
func (pc *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||
defer runtime.KeepAlive(pc.ref)
|
||||
return pc.pc.WriteTo(p, addr)
|
||||
}
|
||||
|
||||
func (pc *refPacketConn) Close() error {
|
||||
defer runtime.KeepAlive(pc.ref)
|
||||
return pc.pc.Close()
|
||||
}
|
||||
|
||||
func (pc *refPacketConn) LocalAddr() net.Addr {
|
||||
defer runtime.KeepAlive(pc.ref)
|
||||
return pc.pc.LocalAddr()
|
||||
}
|
||||
|
||||
func (pc *refPacketConn) SetDeadline(t time.Time) error {
|
||||
defer runtime.KeepAlive(pc.ref)
|
||||
return pc.pc.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (pc *refPacketConn) SetReadDeadline(t time.Time) error {
|
||||
defer runtime.KeepAlive(pc.ref)
|
||||
return pc.pc.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (pc *refPacketConn) SetWriteDeadline(t time.Time) error {
|
||||
defer runtime.KeepAlive(pc.ref)
|
||||
return pc.pc.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func NewRefPacketConn(pc net.PacketConn, ref any) net.PacketConn {
|
||||
return &refPacketConn{pc: pc, ref: ref}
|
||||
}
|
||||
|
@ -23,10 +23,6 @@ func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
||||
return deadline.NewFallbackConn(conn)
|
||||
}
|
||||
|
||||
func NewDeadlinePacketConn(pc net.PacketConn) net.PacketConn {
|
||||
return deadline.NewFallbackPacketConn(bufio.NewPacketConn(pc))
|
||||
}
|
||||
|
||||
func NeedHandshake(conn any) bool {
|
||||
if earlyConn, isEarlyConn := common.Cast[network.EarlyConn](conn); isEarlyConn && earlyConn.NeedHandshake() {
|
||||
return true
|
||||
|
@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||
if certificate == "" || privateKey == "" {
|
||||
if certificate == "" && privateKey == "" {
|
||||
return newRandomTLSKeyPair()
|
||||
}
|
||||
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
||||
|
@ -47,6 +47,7 @@ func (p *Picker[T]) Wait() T {
|
||||
p.wg.Wait()
|
||||
if p.cancel != nil {
|
||||
p.cancel()
|
||||
p.cancel = nil
|
||||
}
|
||||
return p.result
|
||||
}
|
||||
@ -69,6 +70,7 @@ func (p *Picker[T]) Go(f func() (T, error)) {
|
||||
p.result = ret
|
||||
if p.cancel != nil {
|
||||
p.cancel()
|
||||
p.cancel = nil
|
||||
}
|
||||
})
|
||||
} else {
|
||||
@ -78,3 +80,13 @@ func (p *Picker[T]) Go(f func() (T, error)) {
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Close cancels the picker context and releases resources associated with it.
|
||||
// If Wait has been called, then there is no need to call Close.
|
||||
func (p *Picker[T]) Close() error {
|
||||
if p.cancel != nil {
|
||||
p.cancel()
|
||||
p.cancel = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -32,23 +32,32 @@ func NewAllocator() *Allocator {
|
||||
|
||||
// Get a []byte from pool with most appropriate cap
|
||||
func (alloc *Allocator) Get(size int) []byte {
|
||||
if size <= 0 || size > 65536 {
|
||||
switch {
|
||||
case size < 0:
|
||||
panic("alloc.Get: len out of range")
|
||||
case size == 0:
|
||||
return nil
|
||||
}
|
||||
case size > 65536:
|
||||
return make([]byte, size)
|
||||
default:
|
||||
bits := msb(size)
|
||||
if size == 1<<bits {
|
||||
return alloc.buffers[bits].Get().([]byte)[:size]
|
||||
}
|
||||
|
||||
bits := msb(size)
|
||||
if size == 1<<bits {
|
||||
return alloc.buffers[bits].Get().([]byte)[:size]
|
||||
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
||||
}
|
||||
|
||||
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
||||
}
|
||||
|
||||
// Put returns a []byte to pool for future use,
|
||||
// which the cap must be exactly 2^n
|
||||
func (alloc *Allocator) Put(buf []byte) error {
|
||||
if cap(buf) == 0 || cap(buf) > 65536 {
|
||||
return nil
|
||||
}
|
||||
|
||||
bits := msb(cap(buf))
|
||||
if cap(buf) == 0 || cap(buf) > 65536 || cap(buf) != 1<<bits {
|
||||
if cap(buf) != 1<<bits {
|
||||
return errors.New("allocator Put() incorrect buffer size")
|
||||
}
|
||||
|
||||
|
@ -19,17 +19,17 @@ func TestAllocGet(t *testing.T) {
|
||||
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
||||
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
||||
assert.Equal(t, 65536, len(alloc.Get(65536)))
|
||||
assert.Nil(t, alloc.Get(65537))
|
||||
assert.Equal(t, 65537, len(alloc.Get(65537)))
|
||||
}
|
||||
|
||||
func TestAllocPut(t *testing.T) {
|
||||
alloc := NewAllocator()
|
||||
assert.NotNil(t, alloc.Put(nil), "put nil misbehavior")
|
||||
assert.Nil(t, alloc.Put(nil), "put nil misbehavior")
|
||||
assert.NotNil(t, alloc.Put(make([]byte, 3)), "put elem:3 []bytes misbehavior")
|
||||
assert.Nil(t, alloc.Put(make([]byte, 4)), "put elem:4 []bytes misbehavior")
|
||||
assert.Nil(t, alloc.Put(make([]byte, 1023, 1024)), "put elem:1024 []bytes misbehavior")
|
||||
assert.Nil(t, alloc.Put(make([]byte, 65536)), "put elem:65536 []bytes misbehavior")
|
||||
assert.NotNil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
|
||||
assert.Nil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
|
||||
}
|
||||
|
||||
func TestAllocPutThenGet(t *testing.T) {
|
||||
|
@ -96,6 +96,11 @@ func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
||||
return d.decodeFloat(name, data, val)
|
||||
}
|
||||
switch kind {
|
||||
case reflect.Pointer:
|
||||
if val.IsNil() {
|
||||
val.Set(reflect.New(val.Type().Elem()))
|
||||
}
|
||||
return d.decode(name, data, val.Elem())
|
||||
case reflect.String:
|
||||
return d.decodeString(name, data, val)
|
||||
case reflect.Bool:
|
||||
@ -282,6 +287,9 @@ func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
||||
}
|
||||
|
||||
valSlice := val
|
||||
// make a new slice with cap(val)==cap(dataVal)
|
||||
// the caller can determine whether the original configuration contains this item by judging whether the value is nil.
|
||||
valSlice = reflect.MakeSlice(valType, 0, dataVal.Len())
|
||||
for i := 0; i < dataVal.Len(); i++ {
|
||||
currentData := dataVal.Index(i).Interface()
|
||||
for valSlice.Len() <= i {
|
||||
|
17
common/utils/global_id.go
Normal file
17
common/utils/global_id.go
Normal file
@ -0,0 +1,17 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"hash/maphash"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var globalSeed = maphash.MakeSeed()
|
||||
|
||||
func GlobalID(material string) (id [8]byte) {
|
||||
*(*uint64)(unsafe.Pointer(&id[0])) = maphash.String(globalSeed, material)
|
||||
return
|
||||
}
|
||||
|
||||
func MapHash(material string) uint64 {
|
||||
return maphash.String(globalSeed, material)
|
||||
}
|
@ -9,36 +9,36 @@ type Range[T constraints.Ordered] struct {
|
||||
end T
|
||||
}
|
||||
|
||||
func NewRange[T constraints.Ordered](start, end T) *Range[T] {
|
||||
func NewRange[T constraints.Ordered](start, end T) Range[T] {
|
||||
if start > end {
|
||||
return &Range[T]{
|
||||
return Range[T]{
|
||||
start: end,
|
||||
end: start,
|
||||
}
|
||||
}
|
||||
|
||||
return &Range[T]{
|
||||
return Range[T]{
|
||||
start: start,
|
||||
end: end,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Range[T]) Contains(t T) bool {
|
||||
func (r Range[T]) Contains(t T) bool {
|
||||
return t >= r.start && t <= r.end
|
||||
}
|
||||
|
||||
func (r *Range[T]) LeftContains(t T) bool {
|
||||
func (r Range[T]) LeftContains(t T) bool {
|
||||
return t >= r.start && t < r.end
|
||||
}
|
||||
|
||||
func (r *Range[T]) RightContains(t T) bool {
|
||||
func (r Range[T]) RightContains(t T) bool {
|
||||
return t > r.start && t <= r.end
|
||||
}
|
||||
|
||||
func (r *Range[T]) Start() T {
|
||||
func (r Range[T]) Start() T {
|
||||
return r.start
|
||||
}
|
||||
|
||||
func (r *Range[T]) End() T {
|
||||
func (r Range[T]) End() T {
|
||||
return r.end
|
||||
}
|
||||
|
77
common/utils/ranges.go
Normal file
77
common/utils/ranges.go
Normal file
@ -0,0 +1,77 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
type IntRanges[T constraints.Integer] []Range[T]
|
||||
|
||||
var errIntRanges = errors.New("intRanges error")
|
||||
|
||||
func NewIntRanges[T constraints.Integer](expected string) (IntRanges[T], error) {
|
||||
// example: 200 or 200/302 or 200-400 or 200/204/401-429/501-503
|
||||
expected = strings.TrimSpace(expected)
|
||||
if len(expected) == 0 || expected == "*" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
list := strings.Split(expected, "/")
|
||||
if len(list) > 28 {
|
||||
return nil, fmt.Errorf("%w, too many ranges to use, maximum support 28 ranges", errIntRanges)
|
||||
}
|
||||
|
||||
return NewIntRangesFromList[T](list)
|
||||
}
|
||||
|
||||
func NewIntRangesFromList[T constraints.Integer](list []string) (IntRanges[T], error) {
|
||||
var ranges IntRanges[T]
|
||||
for _, s := range list {
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
status := strings.Split(s, "-")
|
||||
statusLen := len(status)
|
||||
if statusLen > 2 {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
start, err := strconv.ParseInt(strings.Trim(status[0], "[ ]"), 10, 64)
|
||||
if err != nil {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
switch statusLen {
|
||||
case 1:
|
||||
ranges = append(ranges, NewRange(T(start), T(start)))
|
||||
case 2:
|
||||
end, err := strconv.ParseUint(strings.Trim(status[1], "[ ]"), 10, 64)
|
||||
if err != nil {
|
||||
return nil, errIntRanges
|
||||
}
|
||||
|
||||
ranges = append(ranges, NewRange(T(start), T(end)))
|
||||
}
|
||||
}
|
||||
|
||||
return ranges, nil
|
||||
}
|
||||
|
||||
func (ranges IntRanges[T]) Check(status T) bool {
|
||||
if len(ranges) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
for _, segment := range ranges {
|
||||
if segment.Contains(status) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
21
common/utils/string_unsafe.go
Normal file
21
common/utils/string_unsafe.go
Normal file
@ -0,0 +1,21 @@
|
||||
package utils
|
||||
|
||||
import "unsafe"
|
||||
|
||||
// ImmutableBytesFromString is equivalent to []byte(s), except that it uses the
|
||||
// same memory backing s instead of making a heap-allocated copy. This is only
|
||||
// valid if the returned slice is never mutated.
|
||||
func ImmutableBytesFromString(s string) []byte {
|
||||
b := unsafe.StringData(s)
|
||||
return unsafe.Slice(b, len(s))
|
||||
}
|
||||
|
||||
// StringFromImmutableBytes is equivalent to string(bs), except that it uses
|
||||
// the same memory backing bs instead of making a heap-allocated copy. This is
|
||||
// only valid if bs is never mutated after StringFromImmutableBytes returns.
|
||||
func StringFromImmutableBytes(bs []byte) string {
|
||||
if len(bs) == 0 {
|
||||
return ""
|
||||
}
|
||||
return unsafe.String(&bs[0], len(bs))
|
||||
}
|
51
component/dialer/bind.go
Normal file
51
component/dialer/bind.go
Normal file
@ -0,0 +1,51 @@
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/component/iface"
|
||||
)
|
||||
|
||||
func LookupLocalAddrFromIfaceName(ifaceName string, network string, destination netip.Addr, port int) (net.Addr, error) {
|
||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var addr *netip.Prefix
|
||||
switch network {
|
||||
case "udp4", "tcp4":
|
||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||
case "tcp6", "udp6":
|
||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||
default:
|
||||
if destination.IsValid() {
|
||||
if destination.Is4() || destination.Is4In6() {
|
||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||
} else {
|
||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||
}
|
||||
} else {
|
||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if strings.HasPrefix(network, "tcp") {
|
||||
return &net.TCPAddr{
|
||||
IP: addr.Addr().AsSlice(),
|
||||
Port: port,
|
||||
}, nil
|
||||
} else if strings.HasPrefix(network, "udp") {
|
||||
return &net.UDPAddr{
|
||||
IP: addr.Addr().AsSlice(),
|
||||
Port: port,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, iface.ErrAddrNotFound
|
||||
}
|
@ -7,52 +7,8 @@ import (
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/component/iface"
|
||||
)
|
||||
|
||||
func lookupLocalAddr(ifaceName string, network string, destination netip.Addr, port int) (net.Addr, error) {
|
||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var addr *netip.Prefix
|
||||
switch network {
|
||||
case "udp4", "tcp4":
|
||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||
case "tcp6", "udp6":
|
||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||
default:
|
||||
if destination.IsValid() {
|
||||
if destination.Is4() {
|
||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||
} else {
|
||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||
}
|
||||
} else {
|
||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if strings.HasPrefix(network, "tcp") {
|
||||
return &net.TCPAddr{
|
||||
IP: addr.Addr().AsSlice(),
|
||||
Port: port,
|
||||
}, nil
|
||||
} else if strings.HasPrefix(network, "udp") {
|
||||
return &net.UDPAddr{
|
||||
IP: addr.Addr().AsSlice(),
|
||||
Port: port,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, iface.ErrAddrNotFound
|
||||
}
|
||||
|
||||
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, destination netip.Addr) error {
|
||||
if !destination.IsGlobalUnicast() {
|
||||
return nil
|
||||
@ -66,7 +22,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, des
|
||||
}
|
||||
}
|
||||
|
||||
addr, err := lookupLocalAddr(ifaceName, network, destination, int(local))
|
||||
addr, err := LookupLocalAddrFromIfaceName(ifaceName, network, destination, int(local))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -84,7 +40,7 @@ func bindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, add
|
||||
|
||||
local, _ := strconv.ParseUint(port, 10, 16)
|
||||
|
||||
addr, err := lookupLocalAddr(ifaceName, network, netip.Addr{}, int(local))
|
||||
addr, err := LookupLocalAddrFromIfaceName(ifaceName, network, netip.Addr{}, int(local))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
@ -20,3 +20,20 @@ func addControlToListenConfig(lc *net.ListenConfig, fn controlFn) {
|
||||
return fn(context.Background(), network, address, c)
|
||||
}
|
||||
}
|
||||
|
||||
func addControlToDialer(d *net.Dialer, fn controlFn) {
|
||||
ld := *d
|
||||
d.ControlContext = func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
||||
switch {
|
||||
case ld.ControlContext != nil:
|
||||
if err = ld.ControlContext(ctx, network, address, c); err != nil {
|
||||
return
|
||||
}
|
||||
case ld.Control != nil:
|
||||
if err = ld.Control(network, address, c); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return fn(ctx, network, address, c)
|
||||
}
|
||||
}
|
||||
|
@ -1,22 +0,0 @@
|
||||
//go:build !go1.20
|
||||
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func addControlToDialer(d *net.Dialer, fn controlFn) {
|
||||
ld := *d
|
||||
d.Control = func(network, address string, c syscall.RawConn) (err error) {
|
||||
switch {
|
||||
case ld.Control != nil:
|
||||
if err = ld.Control(network, address, c); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return fn(context.Background(), network, address, c)
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
//go:build go1.20
|
||||
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func addControlToDialer(d *net.Dialer, fn controlFn) {
|
||||
ld := *d
|
||||
d.ControlContext = func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
||||
switch {
|
||||
case ld.ControlContext != nil:
|
||||
if err = ld.ControlContext(ctx, network, address, c); err != nil {
|
||||
return
|
||||
}
|
||||
case ld.Control != nil:
|
||||
if err = ld.Control(network, address, c); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return fn(ctx, network, address, c)
|
||||
}
|
||||
}
|
@ -2,6 +2,7 @@ package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
@ -131,6 +132,9 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
||||
if opt.routingMark != 0 {
|
||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||
}
|
||||
if opt.mpTcp {
|
||||
setMultiPathTCP(dialer)
|
||||
}
|
||||
if opt.tfo {
|
||||
return dialTFO(ctx, *dialer, network, address)
|
||||
}
|
||||
@ -207,7 +211,7 @@ func dualStackDialContext(ctx context.Context, dialFn dialFunc, network string,
|
||||
if fallback.error == nil && fallback.Conn != nil {
|
||||
return fallback.Conn, nil
|
||||
}
|
||||
return nil, errorsJoin(errs...)
|
||||
return nil, errors.Join(errs...)
|
||||
}
|
||||
|
||||
func parallelDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||
@ -244,7 +248,7 @@ func parallelDialContext(ctx context.Context, network string, ips []netip.Addr,
|
||||
}
|
||||
|
||||
if len(errs) > 0 {
|
||||
return nil, errorsJoin(errs...)
|
||||
return nil, errors.Join(errs...)
|
||||
}
|
||||
return nil, os.ErrDeadlineExceeded
|
||||
}
|
||||
@ -261,7 +265,7 @@ func serialDialContext(ctx context.Context, network string, ips []netip.Addr, po
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return nil, errorsJoin(errs...)
|
||||
return nil, errors.Join(errs...)
|
||||
}
|
||||
|
||||
type dialResult struct {
|
||||
|
@ -2,17 +2,9 @@ package dialer
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrorNoIpAddress = errors.New("no ip address")
|
||||
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||
)
|
||||
|
||||
func errorsJoin(errs ...error) error {
|
||||
// compatibility with golang<1.20
|
||||
// maybe use errors.Join(errs...) is better after we drop the old version's support
|
||||
return E.Errors(errs...)
|
||||
}
|
||||
|
12
component/dialer/mptcp_go120.go
Normal file
12
component/dialer/mptcp_go120.go
Normal file
@ -0,0 +1,12 @@
|
||||
//go:build !go1.21
|
||||
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
const multipathTCPAvailable = false
|
||||
|
||||
func setMultiPathTCP(dialer *net.Dialer) {
|
||||
}
|
11
component/dialer/mptcp_go121.go
Normal file
11
component/dialer/mptcp_go121.go
Normal file
@ -0,0 +1,11 @@
|
||||
//go:build go1.21
|
||||
|
||||
package dialer
|
||||
|
||||
import "net"
|
||||
|
||||
const multipathTCPAvailable = true
|
||||
|
||||
func setMultiPathTCP(dialer *net.Dialer) {
|
||||
dialer.SetMultipathTCP(true)
|
||||
}
|
@ -25,6 +25,7 @@ type option struct {
|
||||
network int
|
||||
prefer int
|
||||
tfo bool
|
||||
mpTcp bool
|
||||
resolver resolver.Resolver
|
||||
netDialer NetDialer
|
||||
}
|
||||
@ -83,6 +84,12 @@ func WithTFO(tfo bool) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func WithMPTCP(mpTcp bool) Option {
|
||||
return func(opt *option) {
|
||||
opt.mpTcp = mpTcp
|
||||
}
|
||||
}
|
||||
|
||||
func WithNetDialer(netDialer NetDialer) Option {
|
||||
return func(opt *option) {
|
||||
opt.netDialer = netDialer
|
||||
|
@ -18,10 +18,11 @@ type tfoConn struct {
|
||||
}
|
||||
|
||||
func (c *tfoConn) Dial(earlyData []byte) (err error) {
|
||||
c.Conn, err = c.dialFn(c.ctx, earlyData)
|
||||
conn, err := c.dialFn(c.ctx, earlyData)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.Conn = conn
|
||||
c.dialed <- true
|
||||
return err
|
||||
}
|
||||
|
@ -234,26 +234,26 @@ tail:
|
||||
case s == 0:
|
||||
case s < 4:
|
||||
h ^= uint64(*(*byte)(p))
|
||||
h ^= uint64(*(*byte)(add(p, s>>1))) << 8
|
||||
h ^= uint64(*(*byte)(add(p, s-1))) << 16
|
||||
h ^= uint64(*(*byte)(unsafe.Add(p, s>>1))) << 8
|
||||
h ^= uint64(*(*byte)(unsafe.Add(p, s-1))) << 16
|
||||
h = rotl31(h*m1) * m2
|
||||
case s <= 8:
|
||||
h ^= uint64(readUnaligned32(p))
|
||||
h ^= uint64(readUnaligned32(add(p, s-4))) << 32
|
||||
h ^= uint64(readUnaligned32(unsafe.Add(p, s-4))) << 32
|
||||
h = rotl31(h*m1) * m2
|
||||
case s <= 16:
|
||||
h ^= readUnaligned64(p)
|
||||
h = rotl31(h*m1) * m2
|
||||
h ^= readUnaligned64(add(p, s-8))
|
||||
h ^= readUnaligned64(unsafe.Add(p, s-8))
|
||||
h = rotl31(h*m1) * m2
|
||||
case s <= 32:
|
||||
h ^= readUnaligned64(p)
|
||||
h = rotl31(h*m1) * m2
|
||||
h ^= readUnaligned64(add(p, 8))
|
||||
h ^= readUnaligned64(unsafe.Add(p, 8))
|
||||
h = rotl31(h*m1) * m2
|
||||
h ^= readUnaligned64(add(p, s-16))
|
||||
h ^= readUnaligned64(unsafe.Add(p, s-16))
|
||||
h = rotl31(h*m1) * m2
|
||||
h ^= readUnaligned64(add(p, s-8))
|
||||
h ^= readUnaligned64(unsafe.Add(p, s-8))
|
||||
h = rotl31(h*m1) * m2
|
||||
default:
|
||||
v1 := h
|
||||
@ -263,16 +263,16 @@ tail:
|
||||
for s >= 32 {
|
||||
v1 ^= readUnaligned64(p)
|
||||
v1 = rotl31(v1*m1) * m2
|
||||
p = add(p, 8)
|
||||
p = unsafe.Add(p, 8)
|
||||
v2 ^= readUnaligned64(p)
|
||||
v2 = rotl31(v2*m2) * m3
|
||||
p = add(p, 8)
|
||||
p = unsafe.Add(p, 8)
|
||||
v3 ^= readUnaligned64(p)
|
||||
v3 = rotl31(v3*m3) * m4
|
||||
p = add(p, 8)
|
||||
p = unsafe.Add(p, 8)
|
||||
v4 ^= readUnaligned64(p)
|
||||
v4 = rotl31(v4*m4) * m1
|
||||
p = add(p, 8)
|
||||
p = unsafe.Add(p, 8)
|
||||
s -= 32
|
||||
}
|
||||
h = v1 ^ v2 ^ v3 ^ v4
|
||||
@ -285,10 +285,6 @@ tail:
|
||||
return uintptr(h)
|
||||
}
|
||||
|
||||
func add(p unsafe.Pointer, x uintptr) unsafe.Pointer {
|
||||
return unsafe.Pointer(uintptr(p) + x)
|
||||
}
|
||||
|
||||
func readUnaligned32(p unsafe.Pointer) uint32 {
|
||||
q := (*[4]byte)(p)
|
||||
return uint32(q[0]) | uint32(q[1])<<8 | uint32(q[2])<<16 | uint32(q[3])<<24
|
||||
|
@ -53,8 +53,12 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
conn := inner.HandleTcp(address, "")
|
||||
return conn, nil
|
||||
if conn, err := inner.HandleTcp(address); err == nil {
|
||||
return conn, nil
|
||||
} else {
|
||||
d := net.Dialer{}
|
||||
return d.DialContext(ctx, network, address)
|
||||
}
|
||||
},
|
||||
TLSClientConfig: tls.GetDefaultTLSConfig(),
|
||||
}
|
||||
|
@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/singledo"
|
||||
@ -37,12 +38,21 @@ func ResolveInterface(name string) (*Interface, error) {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
// if not available device like Meta, dummy0, docker0, etc.
|
||||
if (iface.Flags&net.FlagMulticast == 0) || (iface.Flags&net.FlagPointToPoint != 0) || (iface.Flags&net.FlagRunning == 0) {
|
||||
continue
|
||||
}
|
||||
|
||||
ipNets := make([]*netip.Prefix, 0, len(addrs))
|
||||
for _, addr := range addrs {
|
||||
ipNet := addr.(*net.IPNet)
|
||||
ip, _ := netip.AddrFromSlice(ipNet.IP)
|
||||
|
||||
//unavailable IPv6 Address
|
||||
if ip.Is6() && strings.HasPrefix(ip.String(), "fe80") {
|
||||
continue
|
||||
}
|
||||
|
||||
ones, bits := ipNet.Mask.Size()
|
||||
if bits == 32 {
|
||||
ip = ip.Unmap()
|
||||
|
@ -12,42 +12,68 @@ import (
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
"github.com/oschwald/maxminddb-golang"
|
||||
)
|
||||
|
||||
type databaseType = uint8
|
||||
|
||||
const (
|
||||
typeMaxmind databaseType = iota
|
||||
typeSing
|
||||
typeMetaV0
|
||||
)
|
||||
|
||||
var (
|
||||
mmdb *geoip2.Reader
|
||||
once sync.Once
|
||||
reader Reader
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func LoadFromBytes(buffer []byte) {
|
||||
once.Do(func() {
|
||||
var err error
|
||||
mmdb, err = geoip2.FromBytes(buffer)
|
||||
mmdb, err := maxminddb.FromBytes(buffer)
|
||||
if err != nil {
|
||||
log.Fatalln("Can't load mmdb: %s", err.Error())
|
||||
}
|
||||
reader = Reader{Reader: mmdb}
|
||||
switch mmdb.Metadata.DatabaseType {
|
||||
case "sing-geoip":
|
||||
reader.databaseType = typeSing
|
||||
case "Meta-geoip0":
|
||||
reader.databaseType = typeMetaV0
|
||||
default:
|
||||
reader.databaseType = typeMaxmind
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func Verify() bool {
|
||||
instance, err := geoip2.Open(C.Path.MMDB())
|
||||
instance, err := maxminddb.Open(C.Path.MMDB())
|
||||
if err == nil {
|
||||
instance.Close()
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func Instance() *geoip2.Reader {
|
||||
func Instance() Reader {
|
||||
once.Do(func() {
|
||||
var err error
|
||||
mmdb, err = geoip2.Open(C.Path.MMDB())
|
||||
mmdbPath := C.Path.MMDB()
|
||||
log.Debugln("Load MMDB file: %s", mmdbPath)
|
||||
mmdb, err := maxminddb.Open(mmdbPath)
|
||||
if err != nil {
|
||||
log.Fatalln("Can't load mmdb: %s", err.Error())
|
||||
log.Fatalln("Can't load MMDB: %s", err.Error())
|
||||
}
|
||||
reader = Reader{Reader: mmdb}
|
||||
switch mmdb.Metadata.DatabaseType {
|
||||
case "sing-geoip":
|
||||
reader.databaseType = typeSing
|
||||
case "Meta-geoip0":
|
||||
reader.databaseType = typeMetaV0
|
||||
default:
|
||||
reader.databaseType = typeMaxmind
|
||||
}
|
||||
})
|
||||
|
||||
return mmdb
|
||||
return reader
|
||||
}
|
||||
|
||||
func DownloadMMDB(path string) (err error) {
|
||||
|
56
component/mmdb/reader.go
Normal file
56
component/mmdb/reader.go
Normal file
@ -0,0 +1,56 @@
|
||||
package mmdb
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/oschwald/maxminddb-golang"
|
||||
"github.com/sagernet/sing/common"
|
||||
)
|
||||
|
||||
type geoip2Country struct {
|
||||
Country struct {
|
||||
IsoCode string `maxminddb:"iso_code"`
|
||||
} `maxminddb:"country"`
|
||||
}
|
||||
|
||||
type Reader struct {
|
||||
*maxminddb.Reader
|
||||
databaseType
|
||||
}
|
||||
|
||||
func (r Reader) LookupCode(ipAddress net.IP) []string {
|
||||
switch r.databaseType {
|
||||
case typeMaxmind:
|
||||
var country geoip2Country
|
||||
_ = r.Lookup(ipAddress, &country)
|
||||
if country.Country.IsoCode == "" {
|
||||
return []string{}
|
||||
}
|
||||
return []string{country.Country.IsoCode}
|
||||
|
||||
case typeSing:
|
||||
var code string
|
||||
_ = r.Lookup(ipAddress, &code)
|
||||
if code == "" {
|
||||
return []string{}
|
||||
}
|
||||
return []string{code}
|
||||
|
||||
case typeMetaV0:
|
||||
var record any
|
||||
_ = r.Lookup(ipAddress, &record)
|
||||
switch record := record.(type) {
|
||||
case string:
|
||||
return []string{record}
|
||||
case []any: // lookup returned type of slice is []any
|
||||
return common.Map(record, func(it any) string {
|
||||
return it.(string)
|
||||
})
|
||||
}
|
||||
return []string{}
|
||||
|
||||
default:
|
||||
panic(fmt.Sprint("unknown geoip database type:", r.databaseType))
|
||||
}
|
||||
}
|
26
component/nat/proxy.go
Normal file
26
component/nat/proxy.go
Normal file
@ -0,0 +1,26 @@
|
||||
package nat
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/common/atomic"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
type writeBackProxy struct {
|
||||
wb atomic.TypedValue[C.WriteBack]
|
||||
}
|
||||
|
||||
func (w *writeBackProxy) WriteBack(b []byte, addr net.Addr) (n int, err error) {
|
||||
return w.wb.Load().WriteBack(b, addr)
|
||||
}
|
||||
|
||||
func (w *writeBackProxy) UpdateWriteBack(wb C.WriteBack) {
|
||||
w.wb.Store(wb)
|
||||
}
|
||||
|
||||
func NewWriteBackProxy(wb C.WriteBack) C.WriteBackProxy {
|
||||
w := &writeBackProxy{}
|
||||
w.UpdateWriteBack(wb)
|
||||
return w
|
||||
}
|
@ -13,22 +13,24 @@ type Table struct {
|
||||
|
||||
type Entry struct {
|
||||
PacketConn C.PacketConn
|
||||
WriteBackProxy C.WriteBackProxy
|
||||
LocalUDPConnMap sync.Map
|
||||
}
|
||||
|
||||
func (t *Table) Set(key string, e C.PacketConn) {
|
||||
func (t *Table) Set(key string, e C.PacketConn, w C.WriteBackProxy) {
|
||||
t.mapping.Store(key, &Entry{
|
||||
PacketConn: e,
|
||||
WriteBackProxy: w,
|
||||
LocalUDPConnMap: sync.Map{},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *Table) Get(key string) C.PacketConn {
|
||||
func (t *Table) Get(key string) (C.PacketConn, C.WriteBackProxy) {
|
||||
entry, exist := t.getEntry(key)
|
||||
if !exist {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
return entry.PacketConn
|
||||
return entry.PacketConn, entry.WriteBackProxy
|
||||
}
|
||||
|
||||
func (t *Table) GetOrCreateLock(key string) (*sync.Cond, bool) {
|
||||
|
@ -67,7 +67,7 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string
|
||||
err := initWin32API()
|
||||
if err != nil {
|
||||
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
||||
log.Warnln("All PROCESS-NAMES rules will be skiped")
|
||||
log.Warnln("All PROCESS-NAMES rules will be skipped")
|
||||
return
|
||||
}
|
||||
})
|
||||
|
@ -71,7 +71,7 @@ func (p proxyDialer) DialContext(ctx context.Context, network, address string) (
|
||||
|
||||
func (p proxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||
currentMeta := &C.Metadata{Type: C.INNER}
|
||||
if err := currentMeta.SetRemoteAddress(address); err != nil {
|
||||
if err := currentMeta.SetRemoteAddress(rAddrPort.String()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.listenPacket(ctx, currentMeta)
|
||||
|
@ -2,12 +2,14 @@ package resource
|
||||
|
||||
import (
|
||||
"context"
|
||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||
types "github.com/Dreamacro/clash/constant/provider"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||
types "github.com/Dreamacro/clash/constant/provider"
|
||||
)
|
||||
|
||||
type FileVehicle struct {
|
||||
@ -54,8 +56,10 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return nil, errors.New(resp.Status)
|
||||
}
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -10,11 +10,11 @@ import (
|
||||
|
||||
type SnifferConfig struct {
|
||||
OverrideDest bool
|
||||
Ports []utils.Range[uint16]
|
||||
Ports utils.IntRanges[uint16]
|
||||
}
|
||||
|
||||
type BaseSniffer struct {
|
||||
ports []utils.Range[uint16]
|
||||
ports utils.IntRanges[uint16]
|
||||
supportNetworkType constant.NetWork
|
||||
}
|
||||
|
||||
@ -35,15 +35,10 @@ func (bs *BaseSniffer) SupportNetwork() constant.NetWork {
|
||||
|
||||
// SupportPort implements sniffer.Sniffer
|
||||
func (bs *BaseSniffer) SupportPort(port uint16) bool {
|
||||
for _, portRange := range bs.ports {
|
||||
if portRange.Contains(port) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return bs.ports.Check(port)
|
||||
}
|
||||
|
||||
func NewBaseSniffer(ports []utils.Range[uint16], networkType constant.NetWork) *BaseSniffer {
|
||||
func NewBaseSniffer(ports utils.IntRanges[uint16], networkType constant.NetWork) *BaseSniffer {
|
||||
return &BaseSniffer{
|
||||
ports: ports,
|
||||
supportNetworkType: networkType,
|
||||
|
@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@ -26,29 +25,23 @@ var (
|
||||
var Dispatcher *SnifferDispatcher
|
||||
|
||||
type SnifferDispatcher struct {
|
||||
enable bool
|
||||
sniffers map[sniffer.Sniffer]SnifferConfig
|
||||
forceDomain *trie.DomainSet
|
||||
skipSNI *trie.DomainSet
|
||||
skipList *cache.LruCache[string, uint8]
|
||||
rwMux sync.RWMutex
|
||||
forceDnsMapping bool
|
||||
parsePureIp bool
|
||||
enable bool
|
||||
sniffers map[sniffer.Sniffer]SnifferConfig
|
||||
forceDomain *trie.DomainSet
|
||||
skipSNI *trie.DomainSet
|
||||
skipList *cache.LruCache[string, uint8]
|
||||
rwMux sync.RWMutex
|
||||
forceDnsMapping bool
|
||||
parsePureIp bool
|
||||
}
|
||||
|
||||
func (sd *SnifferDispatcher) TCPSniff(conn *N.BufferedConn, metadata *C.Metadata) {
|
||||
if (metadata.Host == "" && sd.parsePureIp) || sd.forceDomain.Has(metadata.Host) || (metadata.DNSMode == C.DNSMapping && sd.forceDnsMapping) {
|
||||
port, err := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||
if err != nil {
|
||||
log.Debugln("[Sniffer] Dst port is error")
|
||||
return
|
||||
}
|
||||
|
||||
inWhitelist := false
|
||||
overrideDest := false
|
||||
for sniffer, config := range sd.sniffers {
|
||||
if sniffer.SupportNetwork() == C.TCP || sniffer.SupportNetwork() == C.ALLNet {
|
||||
inWhitelist = sniffer.SupportPort(uint16(port))
|
||||
inWhitelist = sniffer.SupportPort(metadata.DstPort)
|
||||
if inWhitelist {
|
||||
overrideDest = config.OverrideDest
|
||||
break
|
||||
@ -61,7 +54,7 @@ func (sd *SnifferDispatcher) TCPSniff(conn *N.BufferedConn, metadata *C.Metadata
|
||||
}
|
||||
|
||||
sd.rwMux.RLock()
|
||||
dst := fmt.Sprintf("%s:%s", metadata.DstIP, metadata.DstPort)
|
||||
dst := fmt.Sprintf("%s:%d", 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()
|
||||
@ -71,7 +64,7 @@ func (sd *SnifferDispatcher) TCPSniff(conn *N.BufferedConn, metadata *C.Metadata
|
||||
|
||||
if host, err := sd.sniffDomain(conn, 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:%d] to [%s:%d]", metadata.SrcIP, metadata.SrcPort, metadata.String(), metadata.DstPort)
|
||||
return
|
||||
} else {
|
||||
if sd.skipSNI.Has(host) {
|
||||
@ -149,7 +142,7 @@ func (sd *SnifferDispatcher) sniffDomain(conn *N.BufferedConn, metadata *C.Metad
|
||||
|
||||
func (sd *SnifferDispatcher) cacheSniffFailed(metadata *C.Metadata) {
|
||||
sd.rwMux.Lock()
|
||||
dst := fmt.Sprintf("%s:%s", metadata.DstIP, metadata.DstPort)
|
||||
dst := fmt.Sprintf("%s:%d", metadata.DstIP, metadata.DstPort)
|
||||
count, _ := sd.skipList.Get(dst)
|
||||
if count <= 5 {
|
||||
count++
|
||||
|
@ -34,11 +34,9 @@ type HTTPSniffer struct {
|
||||
var _ sniffer.Sniffer = (*HTTPSniffer)(nil)
|
||||
|
||||
func NewHTTPSniffer(snifferConfig SnifferConfig) (*HTTPSniffer, error) {
|
||||
ports := make([]utils.Range[uint16], 0)
|
||||
if len(snifferConfig.Ports) == 0 {
|
||||
ports = append(ports, *utils.NewRange[uint16](80, 80))
|
||||
} else {
|
||||
ports = append(ports, snifferConfig.Ports...)
|
||||
ports := snifferConfig.Ports
|
||||
if len(ports) == 0 {
|
||||
ports = utils.IntRanges[uint16]{utils.NewRange[uint16](80, 80)}
|
||||
}
|
||||
return &HTTPSniffer{
|
||||
BaseSniffer: NewBaseSniffer(ports, C.TCP),
|
||||
|
@ -22,11 +22,9 @@ type TLSSniffer struct {
|
||||
}
|
||||
|
||||
func NewTLSSniffer(snifferConfig SnifferConfig) (*TLSSniffer, error) {
|
||||
ports := make([]utils.Range[uint16], 0)
|
||||
if len(snifferConfig.Ports) == 0 {
|
||||
ports = append(ports, *utils.NewRange[uint16](443, 443))
|
||||
} else {
|
||||
ports = append(ports, snifferConfig.Ports...)
|
||||
ports := snifferConfig.Ports
|
||||
if len(ports) == 0 {
|
||||
ports = utils.IntRanges[uint16]{utils.NewRange[uint16](443, 443)}
|
||||
}
|
||||
return &TLSSniffer{
|
||||
BaseSniffer: NewBaseSniffer(ports, C.TCP),
|
||||
|
@ -10,14 +10,12 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
xtls "github.com/xtls/go"
|
||||
)
|
||||
|
||||
var trustCerts []*x509.Certificate
|
||||
var certPool *x509.CertPool
|
||||
var mutex sync.RWMutex
|
||||
var errNotMacth error = errors.New("certificate fingerprints do not match")
|
||||
var errNotMatch = errors.New("certificate fingerprints do not match")
|
||||
|
||||
func AddCertificate(certificate string) error {
|
||||
mutex.Lock()
|
||||
@ -33,10 +31,22 @@ func AddCertificate(certificate string) error {
|
||||
}
|
||||
}
|
||||
|
||||
func initializeCertPool() {
|
||||
var err error
|
||||
certPool, err = x509.SystemCertPool()
|
||||
if err != nil {
|
||||
certPool = x509.NewCertPool()
|
||||
}
|
||||
for _, cert := range trustCerts {
|
||||
certPool.AddCert(cert)
|
||||
}
|
||||
}
|
||||
|
||||
func ResetCertificate() {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
trustCerts = nil
|
||||
initializeCertPool()
|
||||
}
|
||||
|
||||
func getCertPool() *x509.CertPool {
|
||||
@ -49,12 +59,7 @@ func getCertPool() *x509.CertPool {
|
||||
if certPool != nil {
|
||||
return certPool
|
||||
}
|
||||
certPool, err := x509.SystemCertPool()
|
||||
if err == nil {
|
||||
for _, cert := range trustCerts {
|
||||
certPool.AddCert(cert)
|
||||
}
|
||||
}
|
||||
initializeCertPool()
|
||||
}
|
||||
return certPool
|
||||
}
|
||||
@ -72,7 +77,7 @@ func verifyFingerprint(fingerprint *[32]byte) func(rawCerts [][]byte, verifiedCh
|
||||
}
|
||||
}
|
||||
}
|
||||
return errNotMacth
|
||||
return errNotMatch
|
||||
}
|
||||
}
|
||||
|
||||
@ -115,27 +120,3 @@ func GetGlobalTLSConfig(tlsConfig *tls.Config) *tls.Config {
|
||||
tlsConfig.RootCAs = certPool
|
||||
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 {
|
||||
tlsConfig = GetGlobalXTLSConfig(tlsConfig)
|
||||
tlsConfig.VerifyPeerCertificate = verifyFingerprint(fingerprintBytes)
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
return tlsConfig, nil
|
||||
}
|
||||
}
|
||||
|
||||
func GetGlobalXTLSConfig(tlsConfig *xtls.Config) *xtls.Config {
|
||||
certPool := getCertPool()
|
||||
if tlsConfig == nil {
|
||||
return &xtls.Config{
|
||||
RootCAs: certPool,
|
||||
}
|
||||
}
|
||||
|
||||
tlsConfig.RootCAs = certPool
|
||||
return tlsConfig
|
||||
}
|
||||
|
@ -25,6 +25,7 @@ import (
|
||||
|
||||
utls "github.com/sagernet/utls"
|
||||
"github.com/zhangyunhao116/fastrand"
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
"golang.org/x/crypto/curve25519"
|
||||
"golang.org/x/crypto/hkdf"
|
||||
"golang.org/x/net/http2"
|
||||
@ -37,6 +38,9 @@ type RealityConfig struct {
|
||||
ShortID [RealityMaxShortIDLen]byte
|
||||
}
|
||||
|
||||
//go:linkname aesgcmPreferred crypto/tls.aesgcmPreferred
|
||||
func aesgcmPreferred(ciphers []uint16) bool
|
||||
|
||||
func GetRealityConn(ctx context.Context, conn net.Conn, ClientFingerprint string, tlsConfig *tls.Config, realityConfig *RealityConfig) (net.Conn, error) {
|
||||
if fingerprint, exists := GetFingerprint(ClientFingerprint); exists {
|
||||
verifier := &realityVerifier{
|
||||
@ -61,17 +65,17 @@ func GetRealityConn(ctx context.Context, conn net.Conn, ClientFingerprint string
|
||||
}
|
||||
|
||||
hello := uConn.HandshakeState.Hello
|
||||
for i := range hello.SessionId { // https://github.com/golang/go/issues/5373
|
||||
hello.SessionId[i] = 0
|
||||
rawSessionID := hello.Raw[39 : 39+32] // the location of session ID
|
||||
for i := range rawSessionID { // https://github.com/golang/go/issues/5373
|
||||
rawSessionID[i] = 0
|
||||
}
|
||||
copy(hello.Raw[39:], hello.SessionId)
|
||||
|
||||
binary.BigEndian.PutUint64(hello.SessionId, uint64(time.Now().Unix()))
|
||||
|
||||
copy(hello.SessionId[8:], realityConfig.ShortID[:])
|
||||
hello.SessionId[0] = 1
|
||||
hello.SessionId[1] = 8
|
||||
hello.SessionId[2] = 0
|
||||
copy(hello.SessionId[8:], realityConfig.ShortID[:])
|
||||
hello.SessionId[2] = 2
|
||||
|
||||
//log.Debugln("REALITY hello.sessionId[:16]: %v", hello.SessionId[:16])
|
||||
|
||||
@ -84,9 +88,14 @@ func GetRealityConn(ctx context.Context, conn net.Conn, ClientFingerprint string
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aesBlock, _ := aes.NewCipher(authKey)
|
||||
aesGcmCipher, _ := cipher.NewGCM(aesBlock)
|
||||
aesGcmCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
|
||||
var aeadCipher cipher.AEAD
|
||||
if aesgcmPreferred(hello.CipherSuites) {
|
||||
aesBlock, _ := aes.NewCipher(authKey)
|
||||
aeadCipher, _ = cipher.NewGCM(aesBlock)
|
||||
} else {
|
||||
aeadCipher, _ = chacha20poly1305.New(authKey)
|
||||
}
|
||||
aeadCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
|
||||
copy(hello.Raw[39:], hello.SessionId)
|
||||
//log.Debugln("REALITY hello.sessionId: %v", hello.SessionId)
|
||||
//log.Debugln("REALITY uConn.AuthKey: %v", authKey)
|
||||
@ -96,7 +105,7 @@ func GetRealityConn(ctx context.Context, conn net.Conn, ClientFingerprint string
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Debugln("REALITY Authentication: %v", verifier.verified)
|
||||
log.Debugln("REALITY Authentication: %v, AEAD: %T", verifier.verified, aeadCipher)
|
||||
|
||||
if !verifier.verified {
|
||||
go realityClientFallback(uConn, uConfig.ServerName, clientID)
|
||||
@ -137,11 +146,11 @@ type realityVerifier struct {
|
||||
verified bool
|
||||
}
|
||||
|
||||
var pOffset = utils.MustOK(reflect.TypeOf((*utls.UConn)(nil)).Elem().FieldByName("peerCertificates")).Offset
|
||||
var pOffset = utils.MustOK(reflect.TypeOf((*utls.Conn)(nil)).Elem().FieldByName("peerCertificates")).Offset
|
||||
|
||||
func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||
//p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
|
||||
certs := *(*[]*x509.Certificate)(unsafe.Pointer(uintptr(unsafe.Pointer(c.Conn)) + pOffset))
|
||||
certs := *(*[]*x509.Certificate)(unsafe.Add(unsafe.Pointer(c.Conn), pOffset))
|
||||
if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
|
||||
h := hmac.New(sha512.New, c.authKey)
|
||||
h.Write(pub)
|
||||
|
@ -23,6 +23,8 @@ type DomainSet struct {
|
||||
ranks, selects []int32
|
||||
}
|
||||
|
||||
type qElt struct{ s, e, col int }
|
||||
|
||||
// NewDomainSet creates a new *DomainSet struct, from a DomainTrie.
|
||||
func (t *DomainTrie[T]) NewDomainSet() *DomainSet {
|
||||
reserveDomains := make([]string, 0)
|
||||
@ -39,7 +41,6 @@ func (t *DomainTrie[T]) NewDomainSet() *DomainSet {
|
||||
ss := &DomainSet{}
|
||||
lIdx := 0
|
||||
|
||||
type qElt struct{ s, e, col int }
|
||||
queue := []qElt{{0, len(keys), 0}}
|
||||
for i := 0; i < len(queue); i++ {
|
||||
elt := queue[i]
|
||||
|
@ -1,8 +1,9 @@
|
||||
package trie
|
||||
|
||||
import (
|
||||
"github.com/Dreamacro/clash/log"
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/log"
|
||||
)
|
||||
|
||||
type IPV6 bool
|
||||
@ -47,11 +48,10 @@ func (trie *IpCidrTrie) AddIpCidrForString(ipCidr string) error {
|
||||
}
|
||||
|
||||
func (trie *IpCidrTrie) IsContain(ip net.IP) bool {
|
||||
ip, isIpv4 := checkAndConverterIp(ip)
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
isIpv4 := len(ip) == net.IPv4len
|
||||
var groupValues []uint32
|
||||
var ipCidrNode *IpCidrNode
|
||||
|
||||
@ -71,7 +71,13 @@ func (trie *IpCidrTrie) IsContain(ip net.IP) bool {
|
||||
}
|
||||
|
||||
func (trie *IpCidrTrie) IsContainForString(ipString string) bool {
|
||||
return trie.IsContain(net.ParseIP(ipString))
|
||||
ip := net.ParseIP(ipString)
|
||||
// deal with 4in6
|
||||
actualIp := ip.To4()
|
||||
if actualIp == nil {
|
||||
actualIp = ip
|
||||
}
|
||||
return trie.IsContain(actualIp)
|
||||
}
|
||||
|
||||
func ipCidrToSubIpCidr(ipNet *net.IPNet) ([]net.IP, int, bool, error) {
|
||||
@ -82,9 +88,8 @@ func ipCidrToSubIpCidr(ipNet *net.IPNet) ([]net.IP, int, bool, error) {
|
||||
isIpv4 bool
|
||||
err error
|
||||
)
|
||||
|
||||
ip, isIpv4 := checkAndConverterIp(ipNet.IP)
|
||||
ipList, newMaskSize, err = subIpCidr(ip, maskSize, isIpv4)
|
||||
isIpv4 = len(ipNet.IP) == net.IPv4len
|
||||
ipList, newMaskSize, err = subIpCidr(ipNet.IP, maskSize, isIpv4)
|
||||
|
||||
return ipList, newMaskSize, isIpv4, err
|
||||
}
|
||||
@ -238,18 +243,3 @@ func search(root *IpCidrNode, groupValues []uint32) *IpCidrNode {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// return net.IP To4 or To16 and is ipv4
|
||||
func checkAndConverterIp(ip net.IP) (net.IP, bool) {
|
||||
ipResult := ip.To4()
|
||||
if ipResult == nil {
|
||||
ipResult = ip.To16()
|
||||
if ipResult == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return ipResult, false
|
||||
}
|
||||
|
||||
return ipResult, true
|
||||
}
|
||||
|
@ -3,8 +3,9 @@ package trie
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
import "github.com/stretchr/testify/assert"
|
||||
|
||||
func TestIpv4AddSuccess(t *testing.T) {
|
||||
trie := NewIpCidrTrie()
|
||||
@ -96,5 +97,11 @@ func TestIpv6Search(t *testing.T) {
|
||||
assert.Equal(t, true, trie.IsContainForString("2001:67c:4e8:9666::1213"))
|
||||
|
||||
assert.Equal(t, false, trie.IsContain(net.ParseIP("22233:22")))
|
||||
|
||||
}
|
||||
|
||||
func TestIpv4InIpv6(t *testing.T) {
|
||||
trie := NewIpCidrTrie()
|
||||
|
||||
// Boundary testing
|
||||
assert.NoError(t, trie.AddIpCidrForString("::ffff:198.18.5.138/128"))
|
||||
}
|
||||
|
109
config/config.go
109
config/config.go
@ -9,7 +9,6 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@ -52,6 +51,7 @@ type General struct {
|
||||
IPv6 bool `json:"ipv6"`
|
||||
Interface string `json:"interface-name"`
|
||||
RoutingMark int `json:"-"`
|
||||
GeoXUrl GeoXUrl `json:"geox-url"`
|
||||
GeodataMode bool `json:"geodata-mode"`
|
||||
GeodataLoader string `json:"geodata-loader"`
|
||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||
@ -76,6 +76,7 @@ type Inbound struct {
|
||||
AllowLan bool `json:"allow-lan"`
|
||||
BindAddress string `json:"bind-address"`
|
||||
InboundTfo bool `json:"inbound-tfo"`
|
||||
InboundMPTCP bool `json:"inbound-mptcp"`
|
||||
}
|
||||
|
||||
// Controller config
|
||||
@ -220,16 +221,18 @@ type RawTun struct {
|
||||
}
|
||||
|
||||
type RawTuicServer struct {
|
||||
Enable bool `yaml:"enable" json:"enable"`
|
||||
Listen string `yaml:"listen" json:"listen"`
|
||||
Token []string `yaml:"token" json:"token"`
|
||||
Certificate string `yaml:"certificate" json:"certificate"`
|
||||
PrivateKey string `yaml:"private-key" json:"private-key"`
|
||||
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
|
||||
MaxIdleTime int `yaml:"max-idle-time" json:"max-idle-time,omitempty"`
|
||||
AuthenticationTimeout int `yaml:"authentication-timeout" json:"authentication-timeout,omitempty"`
|
||||
ALPN []string `yaml:"alpn" json:"alpn,omitempty"`
|
||||
MaxUdpRelayPacketSize int `yaml:"max-udp-relay-packet-size" json:"max-udp-relay-packet-size,omitempty"`
|
||||
Enable bool `yaml:"enable" json:"enable"`
|
||||
Listen string `yaml:"listen" json:"listen"`
|
||||
Token []string `yaml:"token" json:"token"`
|
||||
Users map[string]string `yaml:"users" json:"users,omitempty"`
|
||||
Certificate string `yaml:"certificate" json:"certificate"`
|
||||
PrivateKey string `yaml:"private-key" json:"private-key"`
|
||||
CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"`
|
||||
MaxIdleTime int `yaml:"max-idle-time" json:"max-idle-time,omitempty"`
|
||||
AuthenticationTimeout int `yaml:"authentication-timeout" json:"authentication-timeout,omitempty"`
|
||||
ALPN []string `yaml:"alpn" json:"alpn,omitempty"`
|
||||
MaxUdpRelayPacketSize int `yaml:"max-udp-relay-packet-size" json:"max-udp-relay-packet-size,omitempty"`
|
||||
CWND int `yaml:"cwnd" json:"cwnd,omitempty"`
|
||||
}
|
||||
|
||||
type RawConfig struct {
|
||||
@ -241,6 +244,7 @@ type RawConfig struct {
|
||||
ShadowSocksConfig string `yaml:"ss-config"`
|
||||
VmessConfig string `yaml:"vmess-config"`
|
||||
InboundTfo bool `yaml:"inbound-tfo"`
|
||||
InboundMPTCP bool `yaml:"inbound-mptcp"`
|
||||
Authentication []string `yaml:"authentication"`
|
||||
AllowLan bool `yaml:"allow-lan"`
|
||||
BindAddress string `yaml:"bind-address"`
|
||||
@ -272,7 +276,7 @@ type RawConfig struct {
|
||||
IPTables IPTables `yaml:"iptables"`
|
||||
Experimental Experimental `yaml:"experimental"`
|
||||
Profile Profile `yaml:"profile"`
|
||||
GeoXUrl RawGeoXUrl `yaml:"geox-url"`
|
||||
GeoXUrl GeoXUrl `yaml:"geox-url"`
|
||||
Proxy []map[string]any `yaml:"proxies"`
|
||||
ProxyGroup []map[string]any `yaml:"proxy-groups"`
|
||||
Rule []string `yaml:"rules"`
|
||||
@ -281,7 +285,7 @@ type RawConfig struct {
|
||||
Listeners []map[string]any `yaml:"listeners"`
|
||||
}
|
||||
|
||||
type RawGeoXUrl struct {
|
||||
type GeoXUrl struct {
|
||||
GeoIp string `yaml:"geoip" json:"geoip"`
|
||||
Mmdb string `yaml:"mmdb" json:"mmdb"`
|
||||
GeoSite string `yaml:"geosite" json:"geosite"`
|
||||
@ -356,6 +360,7 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||
TuicServer: RawTuicServer{
|
||||
Enable: false,
|
||||
Token: nil,
|
||||
Users: nil,
|
||||
Certificate: "",
|
||||
PrivateKey: "",
|
||||
Listen: "",
|
||||
@ -416,10 +421,10 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||
Profile: Profile{
|
||||
StoreSelected: true,
|
||||
},
|
||||
GeoXUrl: RawGeoXUrl{
|
||||
Mmdb: "https://testingcf.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/country.mmdb",
|
||||
GeoIp: "https://testingcf.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat",
|
||||
GeoSite: "https://testingcf.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat",
|
||||
GeoXUrl: GeoXUrl{
|
||||
Mmdb: "https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb",
|
||||
GeoIp: "https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat",
|
||||
GeoSite: "https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat",
|
||||
},
|
||||
}
|
||||
|
||||
@ -446,7 +451,7 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
||||
config.General = general
|
||||
|
||||
if len(config.General.GlobalClientFingerprint) != 0 {
|
||||
log.Debugln("GlobalClientFingerprint:%s", config.General.GlobalClientFingerprint)
|
||||
log.Debugln("GlobalClientFingerprint: %s", config.General.GlobalClientFingerprint)
|
||||
tlsC.SetGlobalUtlsClient(config.General.GlobalClientFingerprint)
|
||||
}
|
||||
|
||||
@ -530,6 +535,10 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
||||
func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||
externalUI := cfg.ExternalUI
|
||||
geodata.SetLoader(cfg.GeodataLoader)
|
||||
C.GeoIpUrl = cfg.GeoXUrl.GeoIp
|
||||
C.GeoSiteUrl = cfg.GeoXUrl.GeoSite
|
||||
C.MmdbUrl = cfg.GeoXUrl.Mmdb
|
||||
C.GeodataMode = cfg.GeodataMode
|
||||
// checkout externalUI exist
|
||||
if externalUI != "" {
|
||||
externalUI = C.Path.Resolve(externalUI)
|
||||
@ -550,6 +559,7 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||
AllowLan: cfg.AllowLan,
|
||||
BindAddress: cfg.BindAddress,
|
||||
InboundTfo: cfg.InboundTfo,
|
||||
InboundMPTCP: cfg.InboundMPTCP,
|
||||
},
|
||||
Controller: Controller{
|
||||
ExternalController: cfg.ExternalController,
|
||||
@ -563,6 +573,7 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||
IPv6: cfg.IPv6,
|
||||
Interface: cfg.Interface,
|
||||
RoutingMark: cfg.RoutingMark,
|
||||
GeoXUrl: cfg.GeoXUrl,
|
||||
GeodataMode: cfg.GeodataMode,
|
||||
GeodataLoader: cfg.GeodataLoader,
|
||||
TCPConcurrent: cfg.TCPConcurrent,
|
||||
@ -655,7 +666,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
||||
}
|
||||
ps = append(ps, proxies[v])
|
||||
}
|
||||
hc := provider.NewHealthCheck(ps, "", 0, true)
|
||||
hc := provider.NewHealthCheck(ps, "", 0, true, nil)
|
||||
pd, _ := provider.NewCompatibleProvider(provider.ReservedName, ps, hc)
|
||||
providersMap[provider.ReservedName] = pd
|
||||
|
||||
@ -710,6 +721,9 @@ func parseRuleProviders(cfg *RawConfig) (ruleProviders map[string]providerTypes.
|
||||
|
||||
func parseSubRules(cfg *RawConfig, proxies map[string]C.Proxy) (subRules map[string][]C.Rule, err error) {
|
||||
subRules = map[string][]C.Rule{}
|
||||
for name := range cfg.SubRules {
|
||||
subRules[name] = make([]C.Rule, 0)
|
||||
}
|
||||
for name, rawRules := range cfg.SubRules {
|
||||
if len(name) == 0 {
|
||||
return nil, fmt.Errorf("sub-rule name is empty")
|
||||
@ -841,7 +855,7 @@ func parseHosts(cfg *RawConfig) (*trie.DomainTrie[resolver.HostValue], error) {
|
||||
} else {
|
||||
ips := make([]netip.Addr, 0)
|
||||
for _, addr := range addrs {
|
||||
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback()&&!ipnet.IP.IsLinkLocalUnicast() {
|
||||
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && !ipnet.IP.IsLinkLocalUnicast() {
|
||||
if ip, err := netip.ParseAddr(ipnet.IP.String()); err == nil {
|
||||
ips = append(ips, ip)
|
||||
}
|
||||
@ -914,7 +928,7 @@ func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error)
|
||||
addr, err = hostWithDefaultPort(u.Host, "443")
|
||||
if err == nil {
|
||||
proxyName = ""
|
||||
clearURL := url.URL{Scheme: "https", Host: addr, Path: u.Path}
|
||||
clearURL := url.URL{Scheme: "https", Host: addr, Path: u.Path, User: u.User}
|
||||
addr = clearURL.String()
|
||||
dnsNetType = "https" // DNS over HTTPS
|
||||
if len(u.Fragment) != 0 {
|
||||
@ -938,6 +952,21 @@ func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error)
|
||||
case "quic":
|
||||
addr, err = hostWithDefaultPort(u.Host, "853")
|
||||
dnsNetType = "quic" // DNS over QUIC
|
||||
case "system":
|
||||
dnsNetType = "system" // System DNS
|
||||
case "rcode":
|
||||
dnsNetType = "rcode"
|
||||
addr = u.Host
|
||||
switch addr {
|
||||
case "success",
|
||||
"format_error",
|
||||
"server_failure",
|
||||
"name_error",
|
||||
"not_implemented",
|
||||
"refused":
|
||||
default:
|
||||
err = fmt.Errorf("unsupported RCode type: %s", addr)
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
||||
}
|
||||
@ -972,6 +1001,10 @@ func parsePureDNSServer(server string) string {
|
||||
return "udp://" + server
|
||||
}
|
||||
|
||||
if server == "system" {
|
||||
return "system://"
|
||||
}
|
||||
|
||||
if ip, err := netip.ParseAddr(server); err != nil {
|
||||
if strings.Contains(server, "://") {
|
||||
return server
|
||||
@ -1142,6 +1175,9 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[resolver.HostValue], rul
|
||||
}
|
||||
// check default nameserver is pure ip addr
|
||||
for _, ns := range dnsCfg.DefaultNameserver {
|
||||
if ns.Net == "system" {
|
||||
continue
|
||||
}
|
||||
host, _, err := net.SplitHostPort(ns.Addr)
|
||||
if err != nil || net.ParseIP(host) == nil {
|
||||
u, err := url.Parse(ns.Addr)
|
||||
@ -1273,6 +1309,7 @@ func parseTuicServer(rawTuic RawTuicServer, general *General) error {
|
||||
Enable: rawTuic.Enable,
|
||||
Listen: rawTuic.Listen,
|
||||
Token: rawTuic.Token,
|
||||
Users: rawTuic.Users,
|
||||
Certificate: rawTuic.Certificate,
|
||||
PrivateKey: rawTuic.PrivateKey,
|
||||
CongestionController: rawTuic.CongestionController,
|
||||
@ -1280,6 +1317,7 @@ func parseTuicServer(rawTuic RawTuicServer, general *General) error {
|
||||
AuthenticationTimeout: rawTuic.AuthenticationTimeout,
|
||||
ALPN: rawTuic.ALPN,
|
||||
MaxUdpRelayPacketSize: rawTuic.MaxUdpRelayPacketSize,
|
||||
CWND: rawTuic.CWND,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -1295,7 +1333,7 @@ func parseSniffer(snifferRaw RawSniffer) (*Sniffer, error) {
|
||||
if len(snifferRaw.Sniff) != 0 {
|
||||
for sniffType, sniffConfig := range snifferRaw.Sniff {
|
||||
find := false
|
||||
ports, err := parsePortRange(sniffConfig.Ports)
|
||||
ports, err := utils.NewIntRangesFromList[uint16](sniffConfig.Ports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -1322,7 +1360,7 @@ func parseSniffer(snifferRaw RawSniffer) (*Sniffer, error) {
|
||||
// Deprecated: Use Sniff instead
|
||||
log.Warnln("Deprecated: Use Sniff instead")
|
||||
}
|
||||
globalPorts, err := parsePortRange(snifferRaw.Ports)
|
||||
globalPorts, err := utils.NewIntRangesFromList[uint16](snifferRaw.Ports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -1367,28 +1405,3 @@ func parseSniffer(snifferRaw RawSniffer) (*Sniffer, error) {
|
||||
|
||||
return sniffer, nil
|
||||
}
|
||||
|
||||
func parsePortRange(portRanges []string) ([]utils.Range[uint16], error) {
|
||||
ports := make([]utils.Range[uint16], 0)
|
||||
for _, portRange := range portRanges {
|
||||
portRaws := strings.Split(portRange, "-")
|
||||
p, err := strconv.ParseUint(portRaws[0], 10, 16)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s format error", portRange)
|
||||
}
|
||||
|
||||
start := uint16(p)
|
||||
if len(portRaws) > 1 {
|
||||
p, err = strconv.ParseUint(portRaws[1], 10, 16)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s format error", portRange)
|
||||
}
|
||||
|
||||
end := uint16(p)
|
||||
ports = append(ports, *utils.NewRange(start, end))
|
||||
} else {
|
||||
ports = append(ports, *utils.NewRange(start, start))
|
||||
}
|
||||
}
|
||||
return ports, nil
|
||||
}
|
||||
|
@ -2,7 +2,6 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/Dreamacro/clash/component/geodata"
|
||||
"os"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
@ -28,23 +27,6 @@ func Init(dir string) error {
|
||||
f.Write([]byte(`mixed-port: 7890`))
|
||||
f.Close()
|
||||
}
|
||||
buf, _ := os.ReadFile(C.Path.Config())
|
||||
rawCfg, err := UnmarshalRawConfig(buf)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
fmt.Printf("configuration file %s test failed\n", C.Path.Config())
|
||||
os.Exit(1)
|
||||
}
|
||||
if !C.GeodataMode {
|
||||
C.GeodataMode = rawCfg.GeodataMode
|
||||
}
|
||||
C.GeoIpUrl = rawCfg.GeoXUrl.GeoIp
|
||||
C.GeoSiteUrl = rawCfg.GeoXUrl.GeoSite
|
||||
C.MmdbUrl = rawCfg.GeoXUrl.Mmdb
|
||||
// initial GeoIP
|
||||
if err := geodata.InitGeoIP(); err != nil {
|
||||
return fmt.Errorf("can't initial GeoIP: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@ -14,7 +14,7 @@ import (
|
||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
"github.com/oschwald/maxminddb-golang"
|
||||
)
|
||||
|
||||
func UpdateGeoDatabases() error {
|
||||
@ -44,7 +44,7 @@ func UpdateGeoDatabases() error {
|
||||
return fmt.Errorf("can't download MMDB database file: %w", err)
|
||||
}
|
||||
|
||||
instance, err := geoip2.FromBytes(data)
|
||||
instance, err := maxminddb.FromBytes(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid MMDB database file: %s", err)
|
||||
}
|
||||
|
@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
)
|
||||
|
||||
@ -40,9 +41,10 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultTCPTimeout = 5 * time.Second
|
||||
DefaultUDPTimeout = DefaultTCPTimeout
|
||||
DefaultTLSTimeout = DefaultTCPTimeout
|
||||
DefaultTCPTimeout = 5 * time.Second
|
||||
DefaultUDPTimeout = DefaultTCPTimeout
|
||||
DefaultTLSTimeout = DefaultTCPTimeout
|
||||
DefaultMaxHealthCheckUrlNum = 16
|
||||
)
|
||||
|
||||
var ErrNotSupport = errors.New("no support")
|
||||
@ -81,7 +83,7 @@ type Conn interface {
|
||||
}
|
||||
|
||||
type PacketConn interface {
|
||||
net.PacketConn
|
||||
N.EnhancePacketConn
|
||||
Connection
|
||||
// Deprecate WriteWithMetadata because of remote resolve DNS cause TURN failed
|
||||
// WriteWithMetadata(p []byte, metadata *Metadata) (n int, err error)
|
||||
@ -106,11 +108,11 @@ type ProxyAdapter interface {
|
||||
//
|
||||
// Examples:
|
||||
// conn, _ := net.DialContext(context.Background(), "tcp", "host:port")
|
||||
// conn, _ = adapter.StreamConn(conn, metadata)
|
||||
// conn, _ = adapter.StreamConnContext(context.Background(), conn, metadata)
|
||||
//
|
||||
// It returns a C.Conn with protocol which start with
|
||||
// a new session (if any)
|
||||
StreamConn(c net.Conn, metadata *Metadata) (net.Conn, error)
|
||||
StreamConnContext(ctx context.Context, c net.Conn, metadata *Metadata) (net.Conn, error)
|
||||
|
||||
// DialContext return a C.Conn with protocol which
|
||||
// contains multiplexing-related reuse logic (if any)
|
||||
@ -132,7 +134,7 @@ type ProxyAdapter interface {
|
||||
}
|
||||
|
||||
type Group interface {
|
||||
URLTest(ctx context.Context, url string) (mp map[string]uint16, err error)
|
||||
URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (mp map[string]uint16, err error)
|
||||
GetProxies(touch bool) []Proxy
|
||||
Touch()
|
||||
}
|
||||
@ -142,12 +144,23 @@ type DelayHistory struct {
|
||||
Delay uint16 `json:"delay"`
|
||||
}
|
||||
|
||||
type DelayHistoryStoreType int
|
||||
|
||||
const (
|
||||
OriginalHistory DelayHistoryStoreType = iota
|
||||
ExtraHistory
|
||||
DropHistory
|
||||
)
|
||||
|
||||
type Proxy interface {
|
||||
ProxyAdapter
|
||||
Alive() bool
|
||||
AliveForTestUrl(url string) bool
|
||||
DelayHistory() []DelayHistory
|
||||
ExtraDelayHistory() map[string][]DelayHistory
|
||||
LastDelay() uint16
|
||||
URLTest(ctx context.Context, url string) (uint16, error)
|
||||
LastDelayForTestUrl(url string) uint16
|
||||
URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16], store DelayHistoryStoreType) (uint16, error)
|
||||
|
||||
// Deprecated: use DialContext instead.
|
||||
Dial(metadata *Metadata) (Conn, error)
|
||||
@ -217,7 +230,7 @@ type UDPPacket interface {
|
||||
// - variable source IP/Port is important to STUN
|
||||
// - if addr is not provided, WriteBack will write out UDP packet with SourceIP/Port equals to original Target,
|
||||
// this is important when using Fake-IP.
|
||||
WriteBack(b []byte, addr net.Addr) (n int, err error)
|
||||
WriteBack
|
||||
|
||||
// Drop call after packet is used, could recycle buffer in this function.
|
||||
Drop()
|
||||
@ -236,10 +249,19 @@ type PacketAdapter interface {
|
||||
Metadata() *Metadata
|
||||
}
|
||||
|
||||
type NatTable interface {
|
||||
Set(key string, e PacketConn)
|
||||
type WriteBack interface {
|
||||
WriteBack(b []byte, addr net.Addr) (n int, err error)
|
||||
}
|
||||
|
||||
Get(key string) PacketConn
|
||||
type WriteBackProxy interface {
|
||||
WriteBack
|
||||
UpdateWriteBack(wb WriteBack)
|
||||
}
|
||||
|
||||
type NatTable interface {
|
||||
Set(key string, e PacketConn, w WriteBackProxy)
|
||||
|
||||
Get(key string) (PacketConn, WriteBackProxy)
|
||||
|
||||
GetOrCreateLock(key string) (*sync.Cond, bool)
|
||||
|
||||
|
@ -128,11 +128,12 @@ type Metadata struct {
|
||||
Type Type `json:"type"`
|
||||
SrcIP netip.Addr `json:"sourceIP"`
|
||||
DstIP netip.Addr `json:"destinationIP"`
|
||||
SrcPort string `json:"sourcePort"`
|
||||
DstPort string `json:"destinationPort"`
|
||||
SrcPort uint16 `json:"sourcePort,string"` // `,string` is used to compatible with old version json output
|
||||
DstPort uint16 `json:"destinationPort,string"` // `,string` is used to compatible with old version json output
|
||||
InIP netip.Addr `json:"inboundIP"`
|
||||
InPort string `json:"inboundPort"`
|
||||
InPort uint16 `json:"inboundPort,string"` // `,string` is used to compatible with old version json output
|
||||
InName string `json:"inboundName"`
|
||||
InUser string `json:"inboundUser"`
|
||||
Host string `json:"host"`
|
||||
DNSMode DNSMode `json:"dnsMode"`
|
||||
Uid uint32 `json:"uid"`
|
||||
@ -146,11 +147,11 @@ type Metadata struct {
|
||||
}
|
||||
|
||||
func (m *Metadata) RemoteAddress() string {
|
||||
return net.JoinHostPort(m.String(), m.DstPort)
|
||||
return net.JoinHostPort(m.String(), strconv.FormatUint(uint64(m.DstPort), 10))
|
||||
}
|
||||
|
||||
func (m *Metadata) SourceAddress() string {
|
||||
return net.JoinHostPort(m.SrcIP.String(), m.SrcPort)
|
||||
return net.JoinHostPort(m.SrcIP.String(), strconv.FormatUint(uint64(m.SrcPort), 10))
|
||||
}
|
||||
|
||||
func (m *Metadata) SourceDetail() string {
|
||||
@ -170,6 +171,10 @@ func (m *Metadata) SourceDetail() string {
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Metadata) SourceValid() bool {
|
||||
return m.SrcPort != 0 && m.SrcIP.IsValid()
|
||||
}
|
||||
|
||||
func (m *Metadata) AddrType() int {
|
||||
switch true {
|
||||
case m.Host != "" || !m.DstIP.IsValid():
|
||||
@ -205,15 +210,15 @@ func (m *Metadata) Pure() *Metadata {
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *Metadata) AddrPort() netip.AddrPort {
|
||||
return netip.AddrPortFrom(m.DstIP.Unmap(), m.DstPort)
|
||||
}
|
||||
|
||||
func (m *Metadata) UDPAddr() *net.UDPAddr {
|
||||
if m.NetWork != UDP || !m.DstIP.IsValid() {
|
||||
return nil
|
||||
}
|
||||
port, _ := strconv.ParseUint(m.DstPort, 10, 16)
|
||||
return &net.UDPAddr{
|
||||
IP: m.DstIP.AsSlice(),
|
||||
Port: int(port),
|
||||
}
|
||||
return net.UDPAddrFromAddrPort(m.AddrPort())
|
||||
}
|
||||
|
||||
func (m *Metadata) String() string {
|
||||
@ -236,6 +241,11 @@ func (m *Metadata) SetRemoteAddress(rawAddress string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
var uint16Port uint16
|
||||
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
||||
uint16Port = uint16(port)
|
||||
}
|
||||
|
||||
if ip, err := netip.ParseAddr(host); err != nil {
|
||||
m.Host = host
|
||||
m.DstIP = netip.Addr{}
|
||||
@ -243,7 +253,7 @@ func (m *Metadata) SetRemoteAddress(rawAddress string) error {
|
||||
m.Host = ""
|
||||
m.DstIP = ip.Unmap()
|
||||
}
|
||||
m.DstPort = port
|
||||
m.DstPort = uint16Port
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@ -1,9 +1,12 @@
|
||||
package constant
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
P "path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@ -20,14 +23,15 @@ var Path = func() *path {
|
||||
if err != nil {
|
||||
homeDir, _ = os.Getwd()
|
||||
}
|
||||
|
||||
allowUnsafePath, _ := strconv.ParseBool(os.Getenv("SKIP_SAFE_PATH_CHECK"))
|
||||
homeDir = P.Join(homeDir, ".config", Name)
|
||||
return &path{homeDir: homeDir, configFile: "config.yaml"}
|
||||
return &path{homeDir: homeDir, configFile: "config.yaml", allowUnsafePath: allowUnsafePath}
|
||||
}()
|
||||
|
||||
type path struct {
|
||||
homeDir string
|
||||
configFile string
|
||||
homeDir string
|
||||
configFile string
|
||||
allowUnsafePath bool
|
||||
}
|
||||
|
||||
// SetHomeDir is used to set the configuration path
|
||||
@ -56,6 +60,27 @@ func (p *path) Resolve(path string) string {
|
||||
return path
|
||||
}
|
||||
|
||||
// IsSafePath return true if path is a subpath of homedir
|
||||
func (p *path) IsSafePath(path string) bool {
|
||||
if p.allowUnsafePath {
|
||||
return true
|
||||
}
|
||||
homedir := p.HomeDir()
|
||||
path = p.Resolve(path)
|
||||
rel, err := filepath.Rel(homedir, path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return !strings.Contains(rel, "..")
|
||||
}
|
||||
|
||||
func (p *path) GetPathByHash(prefix, name string) string {
|
||||
hash := md5.Sum([]byte(name))
|
||||
filename := hex.EncodeToString(hash[:])
|
||||
return filepath.Join(p.HomeDir(), prefix, filename)
|
||||
}
|
||||
|
||||
func (p *path) MMDB() string {
|
||||
files, err := os.ReadDir(p.homeDir)
|
||||
if err != nil {
|
||||
@ -66,13 +91,15 @@ func (p *path) MMDB() string {
|
||||
// 目录则直接跳过
|
||||
continue
|
||||
} else {
|
||||
if strings.EqualFold(fi.Name(), "Country.mmdb") {
|
||||
if strings.EqualFold(fi.Name(), "Country.mmdb") ||
|
||||
strings.EqualFold(fi.Name(), "geoip.db") ||
|
||||
strings.EqualFold(fi.Name(), "geoip.metadb") {
|
||||
GeoipName = fi.Name()
|
||||
return P.Join(p.homeDir, fi.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
return P.Join(p.homeDir, "Country.mmdb")
|
||||
return P.Join(p.homeDir, "geoip.metadb")
|
||||
}
|
||||
|
||||
func (p *path) OldCache() string {
|
||||
|
@ -1,6 +1,7 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
@ -71,6 +72,7 @@ type ProxyProvider interface {
|
||||
Touch()
|
||||
HealthCheck()
|
||||
Version() uint32
|
||||
RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint)
|
||||
}
|
||||
|
||||
// RuleProvider interface
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user