mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-03-03 20:27:31 +00:00
Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bda71dbfa1 | ||
|
|
253b023442 | ||
|
|
8293b7fdae | ||
|
|
0ba415866e | ||
|
|
53b41ca166 | ||
|
|
8a75f78e63 | ||
|
|
d9692c6366 | ||
|
|
f4b0062dfc | ||
|
|
b9ffc82e53 | ||
|
|
78aaea6a45 | ||
|
|
3645fbf161 | ||
|
|
a1d0f22132 | ||
|
|
fa73b0f4bf | ||
|
|
3b76a8b839 | ||
|
|
667f42dcdc | ||
|
|
dfbe09860f | ||
|
|
9e20f9c26a | ||
|
|
f968d0cb82 | ||
|
|
2ad84f4379 | ||
|
|
c7aa16426f | ||
|
|
5987f8e3b5 | ||
|
|
3a8eb72de2 | ||
|
|
33abbdfd24 | ||
|
|
0703d6cbff | ||
|
|
10d2d14938 | ||
|
|
691cf1d8d6 | ||
|
|
d1decb8e58 | ||
|
|
7d04904109 | ||
|
|
a5acd3aa97 | ||
|
|
eea9a12560 | ||
|
|
0a4570b55c |
32
.github/genReleaseNote.sh
vendored
32
.github/genReleaseNote.sh
vendored
@@ -1,32 +0,0 @@
|
|||||||
#!/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:"* %h %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:"* %h %s by @%an" --grep="^fix" -i $version_range | sort -f | uniq >> release.md
|
|
||||||
echo "" >> release.md
|
|
||||||
|
|
||||||
echo "## Maintenance" >> release.md
|
|
||||||
git log --pretty=format:"* %h %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/mihomo/compare/$version_range" >> release.md
|
|
||||||
17
.github/mihomo.service
vendored
17
.github/mihomo.service
vendored
@@ -1,17 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=mihomo Daemon, Another Clash Kernel.
|
|
||||||
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
LimitNPROC=500
|
|
||||||
LimitNOFILE=1000000
|
|
||||||
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
|
||||||
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
|
||||||
Restart=always
|
|
||||||
ExecStartPre=/usr/bin/sleep 2s
|
|
||||||
ExecStart=/usr/bin/mihomo -d /etc/mihomo
|
|
||||||
ExecReload=/bin/kill -HUP $MAINPID
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
16
.github/workflows/Delete.yml
vendored
Normal file
16
.github/workflows/Delete.yml
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
name: Delete old workflow runs
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 0 1 * *'
|
||||||
|
# Run monthly, at 00:00 on the 1st day of month.
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
del_runs:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Delete workflow runs
|
||||||
|
uses: GitRML/delete-workflow-runs@main
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.AUTH_PAT }}
|
||||||
|
repository: ${{ github.repository }}
|
||||||
|
retain_days: 30
|
||||||
684
.github/workflows/build.yml
vendored
684
.github/workflows/build.yml
vendored
@@ -1,10 +1,6 @@
|
|||||||
name: Build
|
name: Build
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
|
||||||
version:
|
|
||||||
description: "Tag version to release"
|
|
||||||
required: true
|
|
||||||
push:
|
push:
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- "docs/**"
|
- "docs/**"
|
||||||
@@ -17,476 +13,353 @@ on:
|
|||||||
pull_request_target:
|
pull_request_target:
|
||||||
branches:
|
branches:
|
||||||
- Alpha
|
- Alpha
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: "${{ github.workflow }}-${{ github.ref }}"
|
group: ${{ github.ref }}-${{ github.workflow }}
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: docker.io
|
REGISTRY: ghcr.io
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
Build:
|
||||||
|
permissions: write-all
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
jobs:
|
job:
|
||||||
- { goos: darwin, goarch: arm64, output: arm64 }
|
- {
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
type: "WithoutCGO",
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64 }
|
target: "linux-amd64 linux-amd64-compatible",
|
||||||
|
id: "1",
|
||||||
- { goos: linux, goarch: '386', output: '386' }
|
}
|
||||||
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible, test: test }
|
- {
|
||||||
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64 }
|
type: "WithoutCGO",
|
||||||
- { goos: linux, goarch: arm64, output: arm64 }
|
target: "linux-armv5 linux-armv6 linux-armv7",
|
||||||
- { goos: linux, goarch: arm, goarm: '5', output: armv5 }
|
id: "2",
|
||||||
- { goos: linux, goarch: arm, goarm: '6', output: armv6 }
|
}
|
||||||
- { goos: linux, goarch: arm, goarm: '7', output: armv7 }
|
- {
|
||||||
- { goos: linux, goarch: mips, gomips: hardfloat, output: mips-hardfloat }
|
type: "WithoutCGO",
|
||||||
- { goos: linux, goarch: mips, gomips: softfloat, output: mips-softfloat }
|
target: "linux-arm64 linux-mips64 linux-mips64le",
|
||||||
- { goos: linux, goarch: mipsle, gomips: hardfloat, output: mipsle-hardfloat }
|
id: "3",
|
||||||
- { goos: linux, goarch: mipsle, gomips: softfloat, output: mipsle-softfloat }
|
}
|
||||||
- { goos: linux, goarch: mips64, output: mips64 }
|
- {
|
||||||
- { goos: linux, goarch: mips64le, output: mips64le }
|
type: "WithoutCGO",
|
||||||
- { goos: linux, goarch: loong64, output: loong64-abi1, abi: '1' }
|
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
||||||
- { goos: linux, goarch: loong64, output: loong64-abi2, abi: '2' }
|
id: "4",
|
||||||
- { goos: linux, goarch: riscv64, output: riscv64 }
|
}
|
||||||
- { goos: linux, goarch: s390x, output: s390x }
|
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
||||||
|
- {
|
||||||
- { goos: windows, goarch: '386', output: '386' }
|
type: "WithoutCGO",
|
||||||
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
||||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64 }
|
id: "6",
|
||||||
- { goos: windows, goarch: arm, goarm: '7', output: armv7 }
|
}
|
||||||
- { goos: windows, goarch: arm64, output: arm64 }
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
- { goos: freebsd, goarch: '386', output: '386' }
|
target: "windows-amd64-compatible windows-amd64 windows-386",
|
||||||
- { goos: freebsd, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
id: "7",
|
||||||
- { goos: freebsd, goarch: amd64, goamd64: v3, output: amd64 }
|
}
|
||||||
- { goos: freebsd, goarch: arm64, output: arm64 }
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
- { goos: android, goarch: '386', ndk: i686-linux-android34, output: '386' }
|
target: "windows-arm64 windows-arm32v7",
|
||||||
- { goos: android, goarch: amd64, ndk: x86_64-linux-android34, output: amd64 }
|
id: "8",
|
||||||
- { goos: android, goarch: arm, ndk: armv7a-linux-androideabi34, output: armv7 }
|
}
|
||||||
- { goos: android, goarch: arm64, ndk: aarch64-linux-android34, output: arm64-v8 }
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
# Go 1.22 with special patch can work on Windows 7
|
target: "darwin-amd64 darwin-arm64 android-arm64",
|
||||||
# https://github.com/MetaCubeX/go/commits/release-branch.go1.22/
|
id: "9",
|
||||||
- { goos: windows, goarch: '386', output: '386-go122', goversion: '1.22' }
|
}
|
||||||
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible-go122, goversion: '1.22' }
|
|
||||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-go122, goversion: '1.22' }
|
|
||||||
|
|
||||||
# Go 1.21 can revert commit `9e4385` to work on Windows 7
|
|
||||||
# https://github.com/golang/go/issues/64622#issuecomment-1847475161
|
|
||||||
# (OR we can just use golang1.21.4 which unneeded any patch)
|
|
||||||
- { goos: windows, goarch: '386', output: '386-go121', goversion: '1.21' }
|
|
||||||
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible-go121, goversion: '1.21' }
|
|
||||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-go121, goversion: '1.21' }
|
|
||||||
|
|
||||||
# Go 1.20 is the last release that will run on any release of Windows 7, 8, Server 2008 and Server 2012. Go 1.21 will require at least Windows 10 or Server 2016.
|
|
||||||
- { goos: windows, goarch: '386', output: '386-go120', goversion: '1.20' }
|
|
||||||
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20' }
|
|
||||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
|
||||||
|
|
||||||
# Go 1.22 is the last release that will run on macOS 10.15 Catalina. Go 1.23 will require macOS 11 Big Sur or later.
|
|
||||||
- { goos: darwin, goarch: arm64, output: arm64-go122, goversion: '1.22' }
|
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible-go122, goversion: '1.22' }
|
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-go122, goversion: '1.22' }
|
|
||||||
|
|
||||||
# Go 1.20 is the last release that will run on macOS 10.13 High Sierra or 10.14 Mojave. Go 1.21 will require macOS 10.15 Catalina or later.
|
|
||||||
- { goos: darwin, goarch: arm64, output: arm64-go120, goversion: '1.20' }
|
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20' }
|
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
|
||||||
|
|
||||||
# only for test
|
# only for test
|
||||||
- { goos: linux, goarch: '386', output: '386-go120', goversion: '1.20' }
|
- { type: "WithoutCGO-GO120", target: "linux-amd64 linux-amd64-compatible",id: "1" }
|
||||||
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20', test: test }
|
# Go 1.20 is the last release that will run on any release of Windows 7, 8, Server 2008 and Server 2012. Go 1.21 will require at least Windows 10 or Server 2016.
|
||||||
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
- { type: "WithoutCGO-GO120", target: "windows-amd64-compatible windows-amd64 windows-386",id: "2" }
|
||||||
|
# Go 1.20 is the last release that will run on macOS 10.13 High Sierra or 10.14 Mojave. Go 1.21 will require macOS 10.15 Catalina or later.
|
||||||
|
- { type: "WithoutCGO-GO120", target: "darwin-amd64 darwin-arm64 android-arm64",id: "3" }
|
||||||
|
- { type: "WithCGO", target: "windows/*", id: "1" }
|
||||||
|
- { type: "WithCGO", target: "linux/386", id: "2" }
|
||||||
|
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
||||||
|
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
||||||
|
- { type: "WithCGO", target: "linux/mips64", id: "8" }
|
||||||
|
- { type: "WithCGO", target: "linux/mips64le", id: "9" }
|
||||||
|
- { type: "WithCGO", target: "darwin-10.16/*", id: "10" }
|
||||||
|
- { type: "WithCGO", target: "android", id: "11" }
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set variables
|
||||||
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.abi != '1' }}
|
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
uses: actions/setup-go@v5
|
shell: bash
|
||||||
with:
|
|
||||||
go-version: '1.23'
|
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set variables
|
||||||
if: ${{ matrix.jobs.goversion != '' && matrix.jobs.abi != '1' }}
|
if: ${{github.ref_name=='Alpha'}}
|
||||||
uses: actions/setup-go@v5
|
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
with:
|
shell: bash
|
||||||
go-version: ${{ matrix.jobs.goversion }}
|
|
||||||
|
|
||||||
- name: Set up Go1.23 loongarch abi1
|
- name: Set variables
|
||||||
if: ${{ matrix.jobs.goarch == 'loong64' && matrix.jobs.abi == '1' }}
|
if: ${{github.ref_name=='Beta'}}
|
||||||
run: |
|
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
wget -q https://github.com/MetaCubeX/loongarch64-golang/releases/download/1.23.0/go1.23.0.linux-amd64-abi1.tar.gz
|
shell: bash
|
||||||
sudo tar zxf go1.23.0.linux-amd64-abi1.tar.gz -C /usr/local
|
|
||||||
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
- name: Set variables
|
||||||
# this patch file only works on golang1.23.x
|
if: ${{github.ref_name=='Meta'}}
|
||||||
# that means after golang1.24 release it must be changed
|
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.23/
|
shell: bash
|
||||||
# revert:
|
|
||||||
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
|
||||||
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
|
||||||
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
|
||||||
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
|
||||||
- name: Revert Golang1.23 commit for Windows7/8
|
|
||||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '' }}
|
|
||||||
run: |
|
|
||||||
cd $(go env GOROOT)
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/9ac42137ef6730e8b7daca016ece831297a1d75b.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/21290de8a4c91408de7c2b5b68757b1e90af49dd.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/69e2eed6dd0f6d815ebf15797761c13f31213dd6.diff | patch --verbose -p 1
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
- name: Set variables
|
||||||
# this patch file only works on golang1.22.x
|
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
||||||
# that means after golang1.23 release it must be changed
|
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
||||||
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.22/
|
shell: bash
|
||||||
# revert:
|
|
||||||
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
|
||||||
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
|
||||||
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
|
||||||
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
|
||||||
- name: Revert Golang1.22 commit for Windows7/8
|
|
||||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.22' }}
|
|
||||||
run: |
|
|
||||||
cd $(go env GOROOT)
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/9779155f18b6556a034f7bb79fb7fb2aad1e26a9.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/ef0606261340e608017860b423ffae5c1ce78239.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/7f83badcb925a7e743188041cb6e561fc9b5b642.diff | patch --verbose -p 1
|
|
||||||
curl https://github.com/MetaCubeX/go/commit/83ff9782e024cb328b690cbf0da4e7848a327f4f.diff | patch --verbose -p 1
|
|
||||||
|
|
||||||
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
- name: Set ENV
|
||||||
- name: Revert Golang1.21 commit for Windows7/8
|
run: |
|
||||||
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.21' }}
|
sudo timedatectl set-timezone "Asia/Shanghai"
|
||||||
run: |
|
echo "NAME=mihomo" >> $GITHUB_ENV
|
||||||
cd $(go env GOROOT)
|
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
||||||
curl https://github.com/golang/go/commit/9e43850a3298a9b8b1162ba0033d4c53f8637571.diff | patch --verbose -R -p 1
|
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
||||||
|
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
||||||
|
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set ENV
|
||||||
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
run: |
|
||||||
run: echo "VERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
||||||
shell: bash
|
echo "LDFLAGS=-X 'github.com/metacubex/mihomo/constant.Version=${VERSION}' -X 'github.com/metacubex/mihomo/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
- name: Set variables
|
- name: Setup Go
|
||||||
if: ${{ github.event_name != 'workflow_dispatch' && github.ref_name == 'Alpha' }}
|
if: ${{ matrix.job.type!='WithoutCGO-GO120' }}
|
||||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
uses: actions/setup-go@v4
|
||||||
shell: bash
|
with:
|
||||||
|
go-version: "1.21"
|
||||||
|
check-latest: true
|
||||||
|
|
||||||
- name: Set Time Variable
|
- name: Setup Go
|
||||||
run: |
|
if: ${{ matrix.job.type=='WithoutCGO-GO120' }}
|
||||||
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
uses: actions/setup-go@v4
|
||||||
echo "CGO_ENABLED=0" >> $GITHUB_ENV
|
with:
|
||||||
echo "BUILDTAG=-extldflags --static" >> $GITHUB_ENV
|
go-version: "1.20"
|
||||||
echo "GOTOOLCHAIN=local" >> $GITHUB_ENV
|
check-latest: true
|
||||||
|
|
||||||
- name: Setup NDK
|
- name: Test
|
||||||
if: ${{ matrix.jobs.goos == 'android' }}
|
if: ${{ matrix.job.id=='1' && matrix.job.type!='WithCGO' }}
|
||||||
uses: nttld/setup-ndk@v1
|
run: |
|
||||||
id: setup-ndk
|
go test ./...
|
||||||
with:
|
|
||||||
ndk-version: r28-beta1
|
|
||||||
|
|
||||||
- name: Set NDK path
|
- name: Build WithoutCGO
|
||||||
if: ${{ matrix.jobs.goos == 'android' }}
|
if: ${{ matrix.job.type!='WithCGO' }}
|
||||||
run: |
|
env:
|
||||||
echo "CC=${{steps.setup-ndk.outputs.ndk-path}}/toolchains/llvm/prebuilt/linux-x86_64/bin/${{matrix.jobs.ndk}}-clang" >> $GITHUB_ENV
|
NAME: mihomo
|
||||||
echo "CGO_ENABLED=1" >> $GITHUB_ENV
|
BINDIR: bin
|
||||||
echo "BUILDTAG=" >> $GITHUB_ENV
|
run: make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
||||||
|
|
||||||
- name: Test
|
- uses: nttld/setup-ndk@v1
|
||||||
if: ${{ matrix.jobs.test == 'test' }}
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||||
run: |
|
id: setup-ndk
|
||||||
go test ./...
|
with:
|
||||||
echo "---test with_gvisor---"
|
ndk-version: r26b
|
||||||
go test ./... -tags "with_gvisor" -count=1
|
add-to-path: true
|
||||||
|
|
||||||
- name: Update CA
|
- name: Build Android
|
||||||
run: |
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||||
sudo apt-get install ca-certificates
|
env:
|
||||||
sudo update-ca-certificates
|
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||||
cp -f /etc/ssl/certs/ca-certificates.crt component/ca/ca-certificates.crt
|
run: |
|
||||||
|
mkdir bin
|
||||||
|
CC=${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android33-clang
|
||||||
|
CGO_ENABLED=1 CC=${CC} GOARCH=arm64 GOOS=android go build -tags ${TAGS} -trimpath -ldflags "${LDFLAGS}" -o bin/${NAME}-android-arm64
|
||||||
|
|
||||||
- name: Build core
|
- name: Set up xgo
|
||||||
env:
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
||||||
GOOS: ${{matrix.jobs.goos}}
|
run: |
|
||||||
GOARCH: ${{matrix.jobs.goarch}}
|
docker pull techknowlogick/xgo:latest
|
||||||
GOAMD64: ${{matrix.jobs.goamd64}}
|
go install src.techknowlogick.com/xgo@latest
|
||||||
GOARM: ${{matrix.jobs.goarm}}
|
|
||||||
GOMIPS: ${{matrix.jobs.gomips}}
|
|
||||||
run: |
|
|
||||||
go env
|
|
||||||
go build -v -tags "with_gvisor" -trimpath -ldflags "${BUILDTAG} -X 'github.com/metacubex/mihomo/constant.Version=${VERSION}' -X 'github.com/metacubex/mihomo/constant.BuildTime=${BUILDTIME}' -w -s -buildid="
|
|
||||||
if [ "${{matrix.jobs.goos}}" = "windows" ]; then
|
|
||||||
cp mihomo.exe mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}.exe
|
|
||||||
zip -r mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.zip mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}.exe
|
|
||||||
else
|
|
||||||
cp mihomo mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}
|
|
||||||
gzip -c mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}} > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.gz
|
|
||||||
rm mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Create DEB package
|
- name: Build by xgo
|
||||||
if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') }}
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
||||||
run: |
|
env:
|
||||||
sudo apt-get install dpkg
|
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||||
if [ "${{matrix.jobs.abi}}" = "1" ]; then
|
run: |
|
||||||
ARCH=loongarch64
|
mkdir bin
|
||||||
elif [ "${{matrix.jobs.goarm}}" = "7" ]; then
|
xgo --targets="${{ matrix.job.target }}" --tags="${TAGS}" -ldflags="${LDFLAGS}" --out bin/${NAME} ./
|
||||||
ARCH=armhf
|
|
||||||
elif [ "${{matrix.jobs.goarch}}" = "arm" ]; then
|
|
||||||
ARCH=armel
|
|
||||||
else
|
|
||||||
ARCH=${{matrix.jobs.goarch}}
|
|
||||||
fi
|
|
||||||
PackageVersion=$(curl -s "https://api.github.com/repos/MetaCubeX/mihomo/releases/latest" | grep -o '"tag_name": "[^"]*' | grep -o '[^"]*$' | sed 's/v//g' )
|
|
||||||
if [ $(git branch | awk -F ' ' '{print $2}') = "Alpha" ]; then
|
|
||||||
PackageVersion="$(echo "${PackageVersion}" | awk -F '.' '{$NF = $NF + 1; print}' OFS='.')-${VERSION}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/DEBIAN
|
- name: Rename
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/bin
|
if: ${{ matrix.job.type=='WithCGO' }}
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/mihomo
|
run: |
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/systemd/system/
|
cd bin
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/share/licenses/mihomo
|
ls -la
|
||||||
|
cp ../.github/rename-cgo.sh ./
|
||||||
|
bash ./rename-cgo.sh
|
||||||
|
rm ./rename-cgo.sh
|
||||||
|
ls -la
|
||||||
|
cd ..
|
||||||
|
|
||||||
cp mihomo mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/bin/mihomo
|
- name: Rename
|
||||||
cp LICENSE mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/share/licenses/mihomo/
|
if: ${{ matrix.job.type=='WithoutCGO-GO120' }}
|
||||||
cp .github/mihomo.service mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/systemd/system/
|
run: |
|
||||||
|
cd bin
|
||||||
|
ls -la
|
||||||
|
cp ../.github/rename-go120.sh ./
|
||||||
|
bash ./rename-go120.sh
|
||||||
|
rm ./rename-go120.sh
|
||||||
|
ls -la
|
||||||
|
cd ..
|
||||||
|
|
||||||
cat > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/mihomo/config.yaml <<EOF
|
- name: Zip
|
||||||
mixed-port: 7890
|
if: ${{ success() }}
|
||||||
external-controller: 127.0.0.1:9090
|
run: |
|
||||||
EOF
|
cd bin
|
||||||
|
ls -la
|
||||||
|
chmod +x *
|
||||||
|
cp ../.github/release.sh ./
|
||||||
|
bash ./release.sh
|
||||||
|
rm ./release.sh
|
||||||
|
ls -la
|
||||||
|
cd ..
|
||||||
|
|
||||||
cat > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/DEBIAN/control <<EOF
|
- name: Save version
|
||||||
Package: mihomo
|
run: echo ${VERSION} > bin/version.txt
|
||||||
Version: ${PackageVersion}
|
shell: bash
|
||||||
Section:
|
|
||||||
Priority: extra
|
|
||||||
Architecture: ${ARCH}
|
|
||||||
Maintainer: MetaCubeX <none@example.com>
|
|
||||||
Homepage: https://wiki.metacubex.one/
|
|
||||||
Description: The universal proxy platform.
|
|
||||||
EOF
|
|
||||||
|
|
||||||
dpkg-deb -Z gzip --build mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}
|
- uses: actions/upload-artifact@v3
|
||||||
|
if: ${{ success() }}
|
||||||
- name: Convert DEB to RPM
|
with:
|
||||||
if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') }}
|
name: artifact
|
||||||
run: |
|
path: bin/
|
||||||
sudo apt-get install -y alien
|
|
||||||
alien --to-rpm --scripts mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.deb
|
|
||||||
mv mihomo*.rpm mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.rpm
|
|
||||||
|
|
||||||
# - name: Convert DEB to PKG
|
|
||||||
# if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') && !contains(matrix.jobs.goarch, 'loong64') }}
|
|
||||||
# run: |
|
|
||||||
# docker pull archlinux
|
|
||||||
# docker run --rm -v ./:/mnt archlinux bash -c "
|
|
||||||
# pacman -Syu pkgfile base-devel --noconfirm
|
|
||||||
# curl -L https://github.com/helixarch/debtap/raw/master/debtap > /usr/bin/debtap
|
|
||||||
# chmod 755 /usr/bin/debtap
|
|
||||||
# debtap -u
|
|
||||||
# debtap -Q /mnt/mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.deb
|
|
||||||
# "
|
|
||||||
# mv mihomo*.pkg.tar.zst mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.pkg.tar.zst
|
|
||||||
|
|
||||||
- name: Save version
|
|
||||||
run: |
|
|
||||||
echo ${VERSION} > version.txt
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Archive production artifacts
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: "${{ matrix.jobs.goos }}-${{ matrix.jobs.output }}"
|
|
||||||
path: |
|
|
||||||
mihomo*.gz
|
|
||||||
mihomo*.deb
|
|
||||||
mihomo*.rpm
|
|
||||||
mihomo*.zip
|
|
||||||
version.txt
|
|
||||||
|
|
||||||
Upload-Prerelease:
|
Upload-Prerelease:
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
if: ${{ github.event_name != 'workflow_dispatch' && github.ref_type == 'branch' && !startsWith(github.event_name, 'pull_request') }}
|
if: ${{ github.ref_type=='branch' && github.event_name != 'pull_request' }}
|
||||||
needs: [build]
|
needs: [Build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Download all workflow run artifacts
|
- uses: actions/download-artifact@v3
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
path: bin/
|
|
||||||
merge-multiple: true
|
|
||||||
|
|
||||||
- name: Delete current release assets
|
|
||||||
uses: 8Mi-Tech/delete-release-assets-action@main
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag: Prerelease-${{ github.ref_name }}
|
|
||||||
deleteOnlyFromDrafts: false
|
|
||||||
- name: Set Env
|
|
||||||
run: |
|
|
||||||
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- run: |
|
|
||||||
cat > release.txt << 'EOF'
|
|
||||||
Release created at ${{ env.BUILDTIME }}
|
|
||||||
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
|
||||||
<br>
|
|
||||||
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/mihomo/wiki/FAQ)
|
|
||||||
[二进制文件筛选 / Binary file selector](https://metacubex.github.io/Meta-Docs/startup/#_1)
|
|
||||||
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Upload Prerelease
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: |
|
|
||||||
bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
||||||
body_path: release.txt
|
|
||||||
|
|
||||||
Upload-Release:
|
|
||||||
permissions: write-all
|
|
||||||
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
|
||||||
needs: [build]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: Meta
|
|
||||||
fetch-depth: '0'
|
|
||||||
fetch-tags: 'true'
|
|
||||||
|
|
||||||
- name: Get tags
|
|
||||||
run: |
|
|
||||||
echo "CURRENTVERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
|
||||||
git fetch --tags
|
|
||||||
echo "PREVERSION=$(git describe --tags --abbrev=0 HEAD)" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Force push Alpha branch to Meta
|
|
||||||
run: |
|
|
||||||
git config --global user.email "github-actions[bot]@users.noreply.github.com"
|
|
||||||
git config --global user.name "github-actions[bot]"
|
|
||||||
git fetch origin Alpha:Alpha
|
|
||||||
git push origin Alpha:Meta --force
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Tag the commit on Alpha
|
|
||||||
run: |
|
|
||||||
git checkout Alpha
|
|
||||||
git tag ${{ github.event.inputs.version }}
|
|
||||||
git push origin ${{ github.event.inputs.version }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Generate release notes
|
|
||||||
run: |
|
|
||||||
cp ./.github/genReleaseNote.sh ./
|
|
||||||
bash ./genReleaseNote.sh -v ${PREVERSION}...${CURRENTVERSION}
|
|
||||||
rm ./genReleaseNote.sh
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
|
||||||
with:
|
with:
|
||||||
|
name: artifact
|
||||||
path: bin/
|
path: bin/
|
||||||
merge-multiple: true
|
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
- name: Display structure of downloaded files
|
||||||
run: ls -R
|
run: ls -R
|
||||||
working-directory: bin
|
working-directory: bin
|
||||||
|
|
||||||
- name: Upload Release
|
- name: Delete current release assets
|
||||||
uses: softprops/action-gh-release@v2
|
uses: 8Mi-Tech/delete-release-assets-action@main
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ github.event.inputs.version }}
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
|
- name: Set Env
|
||||||
|
run: |
|
||||||
|
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Tag Repo
|
||||||
|
uses: richardsimko/update-tag@v1.0.6
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- run: |
|
||||||
|
cat > release.txt << 'EOF'
|
||||||
|
Release created at ${{ env.BUILDTIME }}
|
||||||
|
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
||||||
|
<br>
|
||||||
|
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/mihomo/wiki/FAQ)
|
||||||
|
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Upload Prerelease
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
files: |
|
||||||
|
bin/*
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
||||||
|
body_path: release.txt
|
||||||
|
|
||||||
|
Upload-Release:
|
||||||
|
permissions: write-all
|
||||||
|
if: ${{ github.ref_type=='tag' }}
|
||||||
|
needs: [Build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: bin/
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R
|
||||||
|
working-directory: bin
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag_name: ${{ github.ref_name }}
|
||||||
files: bin/*
|
files: bin/*
|
||||||
body_path: release.md
|
generate_release_notes: true
|
||||||
|
|
||||||
Docker:
|
Docker:
|
||||||
if: ${{ !startsWith(github.event_name, 'pull_request') }}
|
if: ${{ github.event_name != 'pull_request' }}
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
needs: [build]
|
needs: [Build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
- uses: actions/download-artifact@v3
|
||||||
with:
|
with:
|
||||||
|
name: artifact
|
||||||
path: bin/
|
path: bin/
|
||||||
merge-multiple: true
|
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
- name: Display structure of downloaded files
|
||||||
run: ls -R
|
run: ls -R
|
||||||
working-directory: bin
|
working-directory: bin
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3
|
uses: docker/setup-qemu-action@v2
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
- name: Setup Docker buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v2
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: latest
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
# Extract metadata (tags, labels) for Docker
|
||||||
# https://github.com/docker/metadata-action
|
# https://github.com/docker/metadata-action
|
||||||
- name: Extract Docker metadata
|
- name: Extract Docker metadata
|
||||||
if: ${{ github.event_name != 'workflow_dispatch' }}
|
id: meta
|
||||||
id: meta_alpha
|
uses: docker/metadata-action@v4
|
||||||
uses: docker/metadata-action@v5
|
|
||||||
with:
|
with:
|
||||||
images: '${{ env.REGISTRY }}/${{ github.repository }}'
|
images: ${{ env.REGISTRY }}/${{ github.repository }}
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
|
||||||
# https://github.com/docker/metadata-action
|
|
||||||
- name: Extract Docker metadata
|
|
||||||
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
|
||||||
id: meta_release
|
|
||||||
uses: docker/metadata-action@v5
|
|
||||||
with:
|
|
||||||
images: '${{ env.REGISTRY }}/${{ github.repository }}'
|
|
||||||
tags: |
|
|
||||||
${{ github.event.inputs.version }}
|
|
||||||
flavor: |
|
|
||||||
latest=true
|
|
||||||
labels: org.opencontainers.image.version=${{ github.event.inputs.version }}
|
|
||||||
|
|
||||||
- name: Show files
|
- name: Show files
|
||||||
run: |
|
run: |
|
||||||
ls .
|
ls .
|
||||||
ls bin/
|
ls bin/
|
||||||
|
|
||||||
- name: login to docker REGISTRY
|
- name: login to ghcr.io
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ghcr.io
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
# Build and push Docker image with Buildx (don't push on PR)
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
# https://github.com/docker/build-push-action
|
# https://github.com/docker/build-push-action
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
if: ${{ github.event_name != 'workflow_dispatch' }}
|
id: build-and-push
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
@@ -497,20 +370,5 @@ jobs:
|
|||||||
linux/amd64
|
linux/amd64
|
||||||
linux/arm64
|
linux/arm64
|
||||||
linux/arm/v7
|
linux/arm/v7
|
||||||
tags: ${{ steps.meta_alpha.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta_alpha.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
||||||
- name: Build and push Docker image
|
|
||||||
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
|
||||||
uses: docker/build-push-action@v5
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
platforms: |
|
|
||||||
linux/386
|
|
||||||
linux/amd64
|
|
||||||
linux/arm64
|
|
||||||
linux/arm/v7
|
|
||||||
tags: ${{ steps.meta_release.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta_release.outputs.labels }}
|
|
||||||
|
|||||||
6
.github/workflows/trigger-cmfa-update.yml
vendored
6
.github/workflows/trigger-cmfa-update.yml
vendored
@@ -15,7 +15,7 @@ on:
|
|||||||
- Alpha
|
- Alpha
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Send "core-updated" to MetaCubeX/ClashMetaForAndroid to trigger update-dependencies
|
# Send "core-updated" to MetaCubeX/MihomoForAndroid to trigger update-dependencies
|
||||||
trigger-CMFA-update:
|
trigger-CMFA-update:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -27,7 +27,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Trigger update-dependencies
|
- name: Trigger update-dependencies
|
||||||
run: |
|
run: |
|
||||||
curl -X POST https://api.github.com/repos/MetaCubeX/ClashMetaForAndroid/dispatches \
|
curl -X POST https://api.github.com/repos/MetaCubeX/MihomoForAndroid/dispatches \
|
||||||
-H "Accept: application/vnd.github.everest-preview+json" \
|
-H "Accept: application/vnd.github.everest-preview+json" \
|
||||||
-H "Authorization: token ${{ steps.generate-token.outputs.token }}" \
|
-H "Authorization: token ${{ steps.generate-token.outputs.token }}" \
|
||||||
-d '{"event_type": "core-updated"}'
|
-d '{"event_type": "core-updated"}'
|
||||||
@@ -12,8 +12,8 @@ COPY docker/file-name.sh /mihomo/file-name.sh
|
|||||||
WORKDIR /mihomo
|
WORKDIR /mihomo
|
||||||
COPY bin/ bin/
|
COPY bin/ bin/
|
||||||
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
||||||
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.gz"|awk NR==1` && echo $FILE_NAME && \
|
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && echo $FILE_NAME && \
|
||||||
mv bin/$FILE_NAME mihomo.gz && gzip -d mihomo.gz && chmod +x mihomo && echo "$FILE_NAME" > /mihomo-config/test
|
mv bin/$FILE_NAME mihomo.gz && gzip -d mihomo.gz && echo "$FILE_NAME" > /mihomo-config/test
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/mihomo"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/mihomo"
|
||||||
|
|
||||||
@@ -23,4 +23,5 @@ VOLUME ["/root/.config/mihomo/"]
|
|||||||
|
|
||||||
COPY --from=builder /mihomo-config/ /root/.config/mihomo/
|
COPY --from=builder /mihomo-config/ /root/.config/mihomo/
|
||||||
COPY --from=builder /mihomo/mihomo /mihomo
|
COPY --from=builder /mihomo/mihomo /mihomo
|
||||||
|
RUN chmod +x /mihomo
|
||||||
ENTRYPOINT [ "/mihomo" ]
|
ENTRYPOINT [ "/mihomo" ]
|
||||||
|
|||||||
5
Makefile
5
Makefile
@@ -17,7 +17,6 @@ GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.
|
|||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64-compatible \
|
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64-compatible \
|
linux-amd64-compatible \
|
||||||
@@ -163,3 +162,7 @@ clean:
|
|||||||
CLANG ?= clang-14
|
CLANG ?= clang-14
|
||||||
CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
||||||
|
|
||||||
|
ebpf: export BPF_CLANG := $(CLANG)
|
||||||
|
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
||||||
|
ebpf:
|
||||||
|
cd component/ebpf/ && go generate ./...
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
<a href="https://goreportcard.com/report/github.com/MetaCubeX/mihomo">
|
<a href="https://goreportcard.com/report/github.com/MetaCubeX/mihomo">
|
||||||
<img src="https://goreportcard.com/badge/github.com/MetaCubeX/mihomo?style=flat-square">
|
<img src="https://goreportcard.com/badge/github.com/MetaCubeX/mihomo?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<img src="https://img.shields.io/github/go-mod/go-version/MetaCubeX/mihomo/Alpha?style=flat-square">
|
<img src="https://img.shields.io/github/go-mod/go-version/MetaCubeX/mihomo?style=flat-square">
|
||||||
<a href="https://github.com/MetaCubeX/mihomo/releases">
|
<a href="https://github.com/MetaCubeX/mihomo/releases">
|
||||||
<img src="https://img.shields.io/github/release/MetaCubeX/mihomo/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/MetaCubeX/mihomo/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
@@ -98,3 +98,4 @@ API.
|
|||||||
|
|
||||||
This software is released under the GPL-3.0 license.
|
This software is released under the GPL-3.0 license.
|
||||||
|
|
||||||
|
[](https://app.fossa.io/projects/git%2Bgithub.com%2FMetaCubeX%2Fmihomo?ref=badge_large)
|
||||||
|
|||||||
@@ -2,24 +2,21 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/metacubex/mihomo/common/queue"
|
"github.com/metacubex/mihomo/common/queue"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
|
||||||
"github.com/puzpuzpuz/xsync/v3"
|
"github.com/puzpuzpuz/xsync/v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -29,21 +26,17 @@ const (
|
|||||||
defaultHistoriesNum = 10
|
defaultHistoriesNum = 10
|
||||||
)
|
)
|
||||||
|
|
||||||
type internalProxyState struct {
|
type extraProxyState struct {
|
||||||
alive atomic.Bool
|
|
||||||
history *queue.Queue[C.DelayHistory]
|
history *queue.Queue[C.DelayHistory]
|
||||||
|
alive atomic.Bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
alive atomic.Bool
|
|
||||||
history *queue.Queue[C.DelayHistory]
|
history *queue.Queue[C.DelayHistory]
|
||||||
extra *xsync.MapOf[string, *internalProxyState]
|
alive atomic.Bool
|
||||||
}
|
url string
|
||||||
|
extra *xsync.MapOf[string, *extraProxyState]
|
||||||
// Adapter implements C.Proxy
|
|
||||||
func (p *Proxy) Adapter() C.ProxyAdapter {
|
|
||||||
return p.ProxyAdapter
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AliveForTestUrl implements C.Proxy
|
// AliveForTestUrl implements C.Proxy
|
||||||
@@ -88,6 +81,7 @@ func (p *Proxy) DelayHistory() []C.DelayHistory {
|
|||||||
for _, item := range queueM {
|
for _, item := range queueM {
|
||||||
histories = append(histories, item)
|
histories = append(histories, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
return histories
|
return histories
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,6 +92,11 @@ func (p *Proxy) DelayHistoryForTestUrl(url string) []C.DelayHistory {
|
|||||||
if state, ok := p.extra.Load(url); ok {
|
if state, ok := p.extra.Load(url); ok {
|
||||||
queueM = state.history.Copy()
|
queueM = state.history.Copy()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if queueM == nil {
|
||||||
|
queueM = p.history.Copy()
|
||||||
|
}
|
||||||
|
|
||||||
histories := []C.DelayHistory{}
|
histories := []C.DelayHistory{}
|
||||||
for _, item := range queueM {
|
for _, item := range queueM {
|
||||||
histories = append(histories, item)
|
histories = append(histories, item)
|
||||||
@@ -105,46 +104,61 @@ func (p *Proxy) DelayHistoryForTestUrl(url string) []C.DelayHistory {
|
|||||||
return histories
|
return histories
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExtraDelayHistories return all delay histories for each test URL
|
func (p *Proxy) ExtraDelayHistory() map[string][]C.DelayHistory {
|
||||||
// implements C.Proxy
|
extraHistory := map[string][]C.DelayHistory{}
|
||||||
func (p *Proxy) ExtraDelayHistories() map[string]C.ProxyState {
|
|
||||||
histories := map[string]C.ProxyState{}
|
p.extra.Range(func(k string, v *extraProxyState) bool {
|
||||||
|
|
||||||
p.extra.Range(func(k string, v *internalProxyState) bool {
|
|
||||||
testUrl := k
|
testUrl := k
|
||||||
state := v
|
state := v
|
||||||
|
|
||||||
|
histories := []C.DelayHistory{}
|
||||||
queueM := state.history.Copy()
|
queueM := state.history.Copy()
|
||||||
var history []C.DelayHistory
|
|
||||||
|
|
||||||
for _, item := range queueM {
|
for _, item := range queueM {
|
||||||
history = append(history, item)
|
histories = append(histories, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
histories[testUrl] = C.ProxyState{
|
extraHistory[testUrl] = histories
|
||||||
Alive: state.alive.Load(),
|
|
||||||
History: history,
|
|
||||||
}
|
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
return histories
|
return extraHistory
|
||||||
}
|
}
|
||||||
|
|
||||||
// LastDelayForTestUrl return last history record of the specified URL. if proxy is not alive, return the max value of uint16.
|
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) LastDelayForTestUrl(url string) (delay uint16) {
|
func (p *Proxy) LastDelay() (delay uint16) {
|
||||||
var maxDelay uint16 = 0xffff
|
var max uint16 = 0xffff
|
||||||
|
if !p.alive.Load() {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
|
||||||
alive := false
|
history := p.history.Last()
|
||||||
var history C.DelayHistory
|
if history.Delay == 0 {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
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 state, ok := p.extra.Load(url); ok {
|
if state, ok := p.extra.Load(url); ok {
|
||||||
alive = state.alive.Load()
|
alive = state.alive.Load()
|
||||||
history = state.history.Last()
|
history = state.history.Last()
|
||||||
}
|
}
|
||||||
|
|
||||||
if !alive || history.Delay == 0 {
|
if !alive {
|
||||||
return maxDelay
|
return max
|
||||||
|
}
|
||||||
|
|
||||||
|
if history.Delay == 0 {
|
||||||
|
return max
|
||||||
}
|
}
|
||||||
return history.Delay
|
return history.Delay
|
||||||
}
|
}
|
||||||
@@ -159,62 +173,61 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping := map[string]any{}
|
mapping := map[string]any{}
|
||||||
_ = json.Unmarshal(inner, &mapping)
|
_ = json.Unmarshal(inner, &mapping)
|
||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["extra"] = p.ExtraDelayHistories()
|
mapping["extra"] = p.ExtraDelayHistory()
|
||||||
mapping["alive"] = p.alive.Load()
|
mapping["alive"] = p.AliveForTestUrl(p.url)
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
mapping["uot"] = p.SupportUOT()
|
mapping["xudp"] = p.SupportXUDP()
|
||||||
|
mapping["tfo"] = p.SupportTFO()
|
||||||
proxyInfo := p.ProxyInfo()
|
|
||||||
mapping["xudp"] = proxyInfo.XUDP
|
|
||||||
mapping["tfo"] = proxyInfo.TFO
|
|
||||||
mapping["mptcp"] = proxyInfo.MPTCP
|
|
||||||
mapping["smux"] = proxyInfo.SMUX
|
|
||||||
mapping["interface"] = proxyInfo.Interface
|
|
||||||
mapping["dialer-proxy"] = proxyInfo.DialerProxy
|
|
||||||
mapping["routing-mark"] = proxyInfo.RoutingMark
|
|
||||||
|
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
// URLTest get the delay for the specified URL
|
// URLTest get the delay for the specified URL
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (t uint16, err error) {
|
func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (t uint16, err error) {
|
||||||
var satisfied bool
|
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
alive := err == nil
|
alive := err == nil
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
|
||||||
if alive {
|
|
||||||
record.Delay = t
|
|
||||||
}
|
|
||||||
|
|
||||||
p.alive.Store(alive)
|
if len(p.url) == 0 || url == p.url {
|
||||||
p.history.Put(record)
|
p.alive.Store(alive)
|
||||||
if p.history.Len() > defaultHistoriesNum {
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
p.history.Pop()
|
if alive {
|
||||||
}
|
record.Delay = t
|
||||||
|
}
|
||||||
state, ok := p.extra.Load(url)
|
p.history.Put(record)
|
||||||
if !ok {
|
if p.history.Len() > defaultHistoriesNum {
|
||||||
state = &internalProxyState{
|
p.history.Pop()
|
||||||
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
|
||||||
alive: atomic.NewBool(true),
|
|
||||||
}
|
}
|
||||||
p.extra.Store(url, state)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !satisfied {
|
// test URL configured by the proxy provider
|
||||||
record.Delay = 0
|
if len(p.url) == 0 {
|
||||||
alive = false
|
p.url = url
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
|
if alive {
|
||||||
|
record.Delay = t
|
||||||
|
}
|
||||||
|
p.history.Put(record)
|
||||||
|
if p.history.Len() > defaultHistoriesNum {
|
||||||
|
p.history.Pop()
|
||||||
|
}
|
||||||
|
|
||||||
state.alive.Store(alive)
|
state, ok := p.extra.Load(url)
|
||||||
state.history.Put(record)
|
if !ok {
|
||||||
if state.history.Len() > defaultHistoriesNum {
|
state = &extraProxyState{
|
||||||
state.history.Pop()
|
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
||||||
}
|
alive: atomic.NewBool(true),
|
||||||
|
}
|
||||||
|
p.extra.Store(url, state)
|
||||||
|
}
|
||||||
|
|
||||||
|
state.alive.Store(alive)
|
||||||
|
state.history.Put(record)
|
||||||
|
if state.history.Len() > defaultHistoriesNum {
|
||||||
|
state.history.Pop()
|
||||||
|
}
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
unifiedDelay := UnifiedDelay.Load()
|
unifiedDelay := UnifiedDelay.Load()
|
||||||
@@ -248,7 +261,6 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
|
|||||||
IdleConnTimeout: 90 * time.Second,
|
IdleConnTimeout: 90 * time.Second,
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
TLSClientConfig: ca.GetGlobalTLSConfig(&tls.Config{}),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{
|
client := http.Client{
|
||||||
@@ -271,31 +283,29 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
|
|||||||
|
|
||||||
if unifiedDelay {
|
if unifiedDelay {
|
||||||
second := time.Now()
|
second := time.Now()
|
||||||
var ignoredErr error
|
resp, err = client.Do(req)
|
||||||
var secondResp *http.Response
|
if err == nil {
|
||||||
secondResp, ignoredErr = client.Do(req)
|
|
||||||
if ignoredErr == nil {
|
|
||||||
resp = secondResp
|
|
||||||
_ = resp.Body.Close()
|
_ = resp.Body.Close()
|
||||||
start = second
|
start = second
|
||||||
} else {
|
|
||||||
if strings.HasPrefix(url, "http://") {
|
|
||||||
log.Errorln("%s failed to get the second response from %s: %v", p.Name(), url, ignoredErr)
|
|
||||||
log.Warnln("It is recommended to use HTTPS for provider.health-check.url and group.url to ensure better reliability. Due to some proxy providers hijacking test addresses and not being compatible with repeated HEAD requests, using HTTP may result in failed tests.")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
satisfied = resp != nil && (expectedStatus == nil || expectedStatus.Check(uint16(resp.StatusCode)))
|
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)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||||
return &Proxy{
|
return &Proxy{
|
||||||
ProxyAdapter: adapter,
|
ProxyAdapter: adapter,
|
||||||
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
||||||
alive: atomic.NewBool(true),
|
alive: atomic.NewBool(true),
|
||||||
extra: xsync.NewMapOf[string, *internalProxyState]()}
|
url: "",
|
||||||
|
extra: xsync.NewMapOf[string, *extraProxyState]()}
|
||||||
}
|
}
|
||||||
|
|
||||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ func WithDstAddr(addr net.Addr) Addition {
|
|||||||
func WithSrcAddr(addr net.Addr) Addition {
|
func WithSrcAddr(addr net.Addr) Addition {
|
||||||
return func(metadata *C.Metadata) {
|
return func(metadata *C.Metadata) {
|
||||||
m := C.Metadata{}
|
m := C.Metadata{}
|
||||||
if err := m.SetRemoteAddr(addr); err == nil {
|
if err := m.SetRemoteAddr(addr);err ==nil{
|
||||||
metadata.SrcIP = m.DstIP
|
metadata.SrcIP = m.DstIP
|
||||||
metadata.SrcPort = m.DstPort
|
metadata.SrcPort = m.DstPort
|
||||||
}
|
}
|
||||||
@@ -57,17 +57,9 @@ func WithSrcAddr(addr net.Addr) Addition {
|
|||||||
func WithInAddr(addr net.Addr) Addition {
|
func WithInAddr(addr net.Addr) Addition {
|
||||||
return func(metadata *C.Metadata) {
|
return func(metadata *C.Metadata) {
|
||||||
m := C.Metadata{}
|
m := C.Metadata{}
|
||||||
if err := m.SetRemoteAddr(addr); err == nil {
|
if err := m.SetRemoteAddr(addr);err ==nil{
|
||||||
metadata.InIP = m.DstIP
|
metadata.InIP = m.DstIP
|
||||||
metadata.InPort = m.DstPort
|
metadata.InPort = m.DstPort
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithDSCP(dscp uint8) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.DSCP = dscp
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Placeholder(metadata *C.Metadata) {}
|
|
||||||
|
|||||||
@@ -34,5 +34,12 @@ func SkipAuthRemoteAddress(addr string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func skipAuth(addr netip.Addr) bool {
|
func skipAuth(addr netip.Addr) bool {
|
||||||
return prefixesContains(skipAuthPrefixes, addr)
|
if addr.IsValid() {
|
||||||
|
for _, prefix := range skipAuthPrefixes {
|
||||||
|
if prefix.Contains(addr.Unmap()) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ func NewHTTP(target socks5.Addr, srcConn net.Conn, conn net.Conn, additions ...A
|
|||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
metadata.RawSrcAddr = srcConn.RemoteAddr()
|
metadata.RawSrcAddr = srcConn.RemoteAddr()
|
||||||
metadata.RawDstAddr = srcConn.LocalAddr()
|
metadata.RawDstAddr = srcConn.LocalAddr()
|
||||||
ApplyAdditions(metadata, WithSrcAddr(srcConn.RemoteAddr()), WithInAddr(srcConn.LocalAddr()))
|
ApplyAdditions(metadata, WithSrcAddr(srcConn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
||||||
ApplyAdditions(metadata, additions...)
|
ApplyAdditions(metadata, additions...)
|
||||||
return conn, metadata
|
return conn, metadata
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,6 @@ import (
|
|||||||
func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) (net.Conn, *C.Metadata) {
|
func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) (net.Conn, *C.Metadata) {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPS
|
metadata.Type = C.HTTPS
|
||||||
metadata.RawSrcAddr = conn.RemoteAddr()
|
|
||||||
metadata.RawDstAddr = conn.LocalAddr()
|
|
||||||
ApplyAdditions(metadata, WithSrcAddr(conn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
ApplyAdditions(metadata, WithSrcAddr(conn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
||||||
ApplyAdditions(metadata, additions...)
|
ApplyAdditions(metadata, additions...)
|
||||||
return conn, metadata
|
return conn, metadata
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
var lanAllowedIPs []netip.Prefix
|
|
||||||
var lanDisAllowedIPs []netip.Prefix
|
|
||||||
|
|
||||||
func SetAllowedIPs(prefixes []netip.Prefix) {
|
|
||||||
lanAllowedIPs = prefixes
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetDisAllowedIPs(prefixes []netip.Prefix) {
|
|
||||||
lanDisAllowedIPs = prefixes
|
|
||||||
}
|
|
||||||
|
|
||||||
func AllowedIPs() []netip.Prefix {
|
|
||||||
return lanAllowedIPs
|
|
||||||
}
|
|
||||||
|
|
||||||
func DisAllowedIPs() []netip.Prefix {
|
|
||||||
return lanDisAllowedIPs
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsRemoteAddrDisAllowed(addr net.Addr) bool {
|
|
||||||
m := C.Metadata{}
|
|
||||||
if err := m.SetRemoteAddr(addr); err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
ipAddr := m.AddrPort().Addr()
|
|
||||||
if ipAddr.IsValid() {
|
|
||||||
return isAllowed(ipAddr) && !isDisAllowed(ipAddr)
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func isAllowed(addr netip.Addr) bool {
|
|
||||||
return prefixesContains(lanAllowedIPs, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func isDisAllowed(addr netip.Addr) bool {
|
|
||||||
return prefixesContains(lanDisAllowedIPs, addr)
|
|
||||||
}
|
|
||||||
@@ -2,82 +2,29 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/keepalive"
|
"github.com/sagernet/tfo-go"
|
||||||
|
|
||||||
"github.com/metacubex/tfo-go"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
lc = tfo.ListenConfig{
|
lc = tfo.ListenConfig{
|
||||||
DisableTFO: true,
|
DisableTFO: true,
|
||||||
}
|
}
|
||||||
mutex sync.RWMutex
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func SetTfo(open bool) {
|
func SetTfo(open bool) {
|
||||||
mutex.Lock()
|
|
||||||
defer mutex.Unlock()
|
|
||||||
lc.DisableTFO = !open
|
lc.DisableTFO = !open
|
||||||
}
|
}
|
||||||
|
|
||||||
func Tfo() bool {
|
|
||||||
mutex.RLock()
|
|
||||||
defer mutex.RUnlock()
|
|
||||||
return !lc.DisableTFO
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetMPTCP(open bool) {
|
func SetMPTCP(open bool) {
|
||||||
mutex.Lock()
|
|
||||||
defer mutex.Unlock()
|
|
||||||
setMultiPathTCP(&lc.ListenConfig, open)
|
setMultiPathTCP(&lc.ListenConfig, open)
|
||||||
}
|
}
|
||||||
|
|
||||||
func MPTCP() bool {
|
|
||||||
mutex.RLock()
|
|
||||||
defer mutex.RUnlock()
|
|
||||||
return getMultiPathTCP(&lc.ListenConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
||||||
switch network { // like net.Resolver.internetAddrList but filter domain to avoid call net.Resolver.lookupIPAddr
|
|
||||||
case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "ip", "ip4", "ip6":
|
|
||||||
if host, port, err := net.SplitHostPort(address); err == nil {
|
|
||||||
switch host {
|
|
||||||
case "localhost":
|
|
||||||
switch network {
|
|
||||||
case "tcp6", "udp6", "ip6":
|
|
||||||
address = net.JoinHostPort("::1", port)
|
|
||||||
default:
|
|
||||||
address = net.JoinHostPort("127.0.0.1", port)
|
|
||||||
}
|
|
||||||
case "": // internetAddrList can handle this special case
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
if _, err := netip.ParseAddr(host); err != nil { // not ip
|
|
||||||
return nil, fmt.Errorf("invalid network address: %s", address)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mutex.RLock()
|
|
||||||
defer mutex.RUnlock()
|
|
||||||
return lc.Listen(ctx, network, address)
|
return lc.Listen(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Listen(network, address string) (net.Listener, error) {
|
func Listen(network, address string) (net.Listener, error) {
|
||||||
return ListenContext(context.Background(), network, address)
|
return ListenContext(context.Background(), network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
|
||||||
keepalive.SetDisableKeepAliveCallback.Register(func(b bool) {
|
|
||||||
mutex.Lock()
|
|
||||||
defer mutex.Unlock()
|
|
||||||
keepalive.SetNetListenConfig(&lc.ListenConfig)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
//go:build !windows
|
|
||||||
|
|
||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
const SupportNamedPipe = false
|
|
||||||
|
|
||||||
func ListenNamedPipe(path string) (net.Listener, error) {
|
|
||||||
return nil, os.ErrInvalid
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/metacubex/wireguard-go/ipc/namedpipe"
|
|
||||||
"golang.org/x/sys/windows"
|
|
||||||
)
|
|
||||||
|
|
||||||
const SupportNamedPipe = true
|
|
||||||
|
|
||||||
// windowsSDDL is the Security Descriptor set on the namedpipe.
|
|
||||||
// It provides read/write access to all users and the local system.
|
|
||||||
const windowsSDDL = "D:PAI(A;OICI;GWGR;;;BU)(A;OICI;GWGR;;;SY)"
|
|
||||||
|
|
||||||
func ListenNamedPipe(path string) (net.Listener, error) {
|
|
||||||
sddl := os.Getenv("LISTEN_NAMEDPIPE_SDDL")
|
|
||||||
if sddl == "" {
|
|
||||||
sddl = windowsSDDL
|
|
||||||
}
|
|
||||||
securityDescriptor, err := windows.SecurityDescriptorFromString(sddl)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
namedpipeLC := namedpipe.ListenConfig{
|
|
||||||
SecurityDescriptor: securityDescriptor,
|
|
||||||
InputBufferSize: 256 * 1024,
|
|
||||||
OutputBufferSize: 256 * 1024,
|
|
||||||
}
|
|
||||||
return namedpipeLC.Listen(path)
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,3 @@ const multipathTCPAvailable = false
|
|||||||
|
|
||||||
func setMultiPathTCP(listenConfig *net.ListenConfig, open bool) {
|
func setMultiPathTCP(listenConfig *net.ListenConfig, open bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func getMultiPathTCP(listenConfig *net.ListenConfig) bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,7 +9,3 @@ const multipathTCPAvailable = true
|
|||||||
func setMultiPathTCP(listenConfig *net.ListenConfig, open bool) {
|
func setMultiPathTCP(listenConfig *net.ListenConfig, open bool) {
|
||||||
listenConfig.SetMultipathTCP(open)
|
listenConfig.SetMultipathTCP(open)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getMultiPathTCP(listenConfig *net.ListenConfig) bool {
|
|
||||||
return listenConfig.MultipathTCP()
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -61,19 +61,3 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func prefixesContains(prefixes []netip.Prefix, addr netip.Addr) bool {
|
|
||||||
if len(prefixes) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !addr.IsValid() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
addr = addr.Unmap().WithZone("") // netip.Prefix.Contains returns false if ip has an IPv6 zone
|
|
||||||
for _, prefix := range prefixes {
|
|
||||||
if prefix.Contains(addr) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -85,15 +85,14 @@ func (b *Base) SupportUDP() bool {
|
|||||||
return b.udp
|
return b.udp
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
// SupportXUDP implements C.ProxyAdapter
|
||||||
func (b *Base) ProxyInfo() (info C.ProxyInfo) {
|
func (b *Base) SupportXUDP() bool {
|
||||||
info.XUDP = b.xudp
|
return b.xudp
|
||||||
info.TFO = b.tfo
|
}
|
||||||
info.MPTCP = b.mpTcp
|
|
||||||
info.SMUX = false
|
// SupportTFO implements C.ProxyAdapter
|
||||||
info.Interface = b.iface
|
func (b *Base) SupportTFO() bool {
|
||||||
info.RoutingMark = b.rmark
|
return b.tfo
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsL3Protocol implements C.ProxyAdapter
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
|||||||
@@ -3,15 +3,16 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/loopback"
|
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Direct struct {
|
type Direct struct {
|
||||||
*Base
|
*Base
|
||||||
loopBack *loopback.Detector
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type DirectOption struct {
|
type DirectOption struct {
|
||||||
@@ -21,39 +22,30 @@ type DirectOption struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
if err := d.loopBack.CheckConn(metadata); err != nil {
|
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DirectHostResolver))
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return d.loopBack.NewConn(NewConn(c, d)), nil
|
N.TCPKeepAlive(c)
|
||||||
|
return NewConn(c, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
if err := d.loopBack.CheckPacketConn(metadata); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
// net.UDPConn.WriteTo only working with *net.UDPAddr, so we need a net.UDPAddr
|
// net.UDPConn.WriteTo only working with *net.UDPAddr, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DirectHostResolver)
|
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DefaultResolver)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("can't resolve ip")
|
return nil, errors.New("can't resolve ip")
|
||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
pc, err := dialer.NewDialer(d.Base.DialOptions(opts...)...).ListenPacket(ctx, "udp", "", metadata.AddrPort())
|
pc, err := dialer.NewDialer(d.Base.DialOptions(opts...)...).ListenPacket(ctx, "udp", "", netip.AddrPortFrom(metadata.DstIP, metadata.DstPort))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return d.loopBack.NewPacketConn(newPacketConn(pc, d)), nil
|
return newPacketConn(pc, d), nil
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Direct) IsL3Protocol(metadata *C.Metadata) bool {
|
|
||||||
return true // tell DNSDialer don't send domain to DialContext, avoid lookback to DefaultResolver
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirectWithOption(option DirectOption) *Direct {
|
func NewDirectWithOption(option DirectOption) *Direct {
|
||||||
@@ -68,7 +60,6 @@ func NewDirectWithOption(option DirectOption) *Direct {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
loopBack: loopback.NewDetector(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +71,6 @@ func NewDirect() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
loopBack: loopback.NewDetector(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,6 +82,5 @@ func NewCompatible() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
loopBack: loopback.NewDetector(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,159 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
|
||||||
"github.com/metacubex/mihomo/common/pool"
|
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
"github.com/metacubex/mihomo/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Dns struct {
|
|
||||||
*Base
|
|
||||||
}
|
|
||||||
|
|
||||||
type DnsOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
|
||||||
func (d *Dns) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
|
||||||
left, right := N.Pipe()
|
|
||||||
go resolver.RelayDnsConn(context.Background(), right, 0)
|
|
||||||
return NewConn(left, d), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
|
||||||
func (d *Dns) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
|
||||||
log.Debugln("[DNS] hijack udp:%s from %s", metadata.RemoteAddress(), metadata.SourceAddrPort())
|
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
|
|
||||||
return newPacketConn(&dnsPacketConn{
|
|
||||||
response: make(chan dnsPacket, 1),
|
|
||||||
ctx: ctx,
|
|
||||||
cancel: cancel,
|
|
||||||
}, d), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type dnsPacket struct {
|
|
||||||
data []byte
|
|
||||||
put func()
|
|
||||||
addr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
// dnsPacketConn implements net.PacketConn
|
|
||||||
type dnsPacketConn struct {
|
|
||||||
response chan dnsPacket
|
|
||||||
ctx context.Context
|
|
||||||
cancel context.CancelFunc
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *dnsPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
select {
|
|
||||||
case packet := <-d.response:
|
|
||||||
return packet.data, packet.put, packet.addr, nil
|
|
||||||
case <-d.ctx.Done():
|
|
||||||
return nil, nil, nil, net.ErrClosed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *dnsPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|
||||||
select {
|
|
||||||
case packet := <-d.response:
|
|
||||||
n = copy(p, packet.data)
|
|
||||||
if packet.put != nil {
|
|
||||||
packet.put()
|
|
||||||
}
|
|
||||||
return n, packet.addr, nil
|
|
||||||
case <-d.ctx.Done():
|
|
||||||
return 0, nil, net.ErrClosed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *dnsPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|
||||||
select {
|
|
||||||
case <-d.ctx.Done():
|
|
||||||
return 0, net.ErrClosed
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(p) > resolver.SafeDnsPacketSize {
|
|
||||||
// wtf???
|
|
||||||
return len(p), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
buf := pool.Get(resolver.SafeDnsPacketSize)
|
|
||||||
put := func() { _ = pool.Put(buf) }
|
|
||||||
copy(buf, p) // avoid p be changed after WriteTo returned
|
|
||||||
|
|
||||||
go func() { // don't block the WriteTo function
|
|
||||||
ctx, cancel := context.WithTimeout(d.ctx, resolver.DefaultDnsRelayTimeout)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
buf, err = resolver.RelayDnsPacket(ctx, buf[:len(p)], buf)
|
|
||||||
if err != nil {
|
|
||||||
put()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
packet := dnsPacket{
|
|
||||||
data: buf,
|
|
||||||
put: put,
|
|
||||||
addr: addr,
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case d.response <- packet:
|
|
||||||
break
|
|
||||||
case <-d.ctx.Done():
|
|
||||||
put()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return len(p), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *dnsPacketConn) Close() error {
|
|
||||||
d.cancel()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*dnsPacketConn) LocalAddr() net.Addr {
|
|
||||||
return &net.UDPAddr{
|
|
||||||
IP: net.IPv4(127, 0, 0, 1),
|
|
||||||
Port: 53,
|
|
||||||
Zone: "",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*dnsPacketConn) SetDeadline(t time.Time) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*dnsPacketConn) SetReadDeadline(t time.Time) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*dnsPacketConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDnsWithOption(option DnsOption) *Dns {
|
|
||||||
return &Dns{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Dns,
|
|
||||||
udp: true,
|
|
||||||
tfo: option.TFO,
|
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,11 +7,13 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
@@ -74,6 +76,7 @@ func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metad
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
@@ -92,13 +95,6 @@ func (h *Http) SupportWithDialer() C.NetWork {
|
|||||||
return C.TCP
|
return C.TCP
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (h *Http) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := h.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = h.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
addr := metadata.RemoteAddress()
|
addr := metadata.RemoteAddress()
|
||||||
HeaderString := "CONNECT " + addr + " HTTP/1.1\r\n"
|
HeaderString := "CONNECT " + addr + " HTTP/1.1\r\n"
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"runtime"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -15,7 +14,6 @@ import (
|
|||||||
"github.com/metacubex/quic-go/congestion"
|
"github.com/metacubex/quic-go/congestion"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
CN "github.com/metacubex/mihomo/common/net"
|
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
@@ -45,8 +43,6 @@ type Hysteria struct {
|
|||||||
|
|
||||||
option *HysteriaOption
|
option *HysteriaOption
|
||||||
client *core.Client
|
client *core.Client
|
||||||
|
|
||||||
closeCh chan struct{} // for test
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
@@ -55,7 +51,7 @@ func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(CN.NewRefConn(tcpConn, h), h), nil
|
return NewConn(tcpConn, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
@@ -63,13 +59,13 @@ func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(CN.NewRefPacketConn(&hyPacketConn{udpConn}, h), h), nil
|
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) genHdc(ctx context.Context, opts ...dialer.Option) utils.PacketDialer {
|
func (h *Hysteria) genHdc(ctx context.Context, opts ...dialer.Option) utils.PacketDialer {
|
||||||
return &hyDialerWithContext{
|
return &hyDialerWithContext{
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
hyDialer: func(network string, rAddr net.Addr) (net.PacketConn, error) {
|
hyDialer: func(network string) (net.PacketConn, error) {
|
||||||
var err error
|
var err error
|
||||||
var cDialer C.Dialer = dialer.NewDialer(h.Base.DialOptions(opts...)...)
|
var cDialer C.Dialer = dialer.NewDialer(h.Base.DialOptions(opts...)...)
|
||||||
if len(h.option.DialerProxy) > 0 {
|
if len(h.option.DialerProxy) > 0 {
|
||||||
@@ -78,7 +74,7 @@ func (h *Hysteria) genHdc(ctx context.Context, opts ...dialer.Option) utils.Pack
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
rAddrPort, _ := netip.ParseAddrPort(rAddr.String())
|
rAddrPort, _ := netip.ParseAddrPort(h.Addr())
|
||||||
return cDialer.ListenPacket(ctx, network, "", rAddrPort)
|
return cDialer.ListenPacket(ctx, network, "", rAddrPort)
|
||||||
},
|
},
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
@@ -87,13 +83,6 @@ func (h *Hysteria) genHdc(ctx context.Context, opts ...dialer.Option) utils.Pack
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (h *Hysteria) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := h.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = h.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
type HysteriaOption struct {
|
type HysteriaOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
@@ -138,7 +127,11 @@ func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
||||||
clientTransport := &transport.ClientTransport{}
|
clientTransport := &transport.ClientTransport{
|
||||||
|
Dialer: &net.Dialer{
|
||||||
|
Timeout: 8 * time.Second,
|
||||||
|
},
|
||||||
|
}
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
ports := option.Ports
|
ports := option.Ports
|
||||||
|
|
||||||
@@ -225,7 +218,7 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||||
}
|
}
|
||||||
outbound := &Hysteria{
|
return &Hysteria{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
@@ -238,19 +231,7 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
},
|
},
|
||||||
option: &option,
|
option: &option,
|
||||||
client: client,
|
client: client,
|
||||||
}
|
}, nil
|
||||||
runtime.SetFinalizer(outbound, closeHysteria)
|
|
||||||
|
|
||||||
return outbound, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeHysteria(h *Hysteria) {
|
|
||||||
if h.client != nil {
|
|
||||||
_ = h.client.Close()
|
|
||||||
}
|
|
||||||
if h.closeCh != nil {
|
|
||||||
close(h.closeCh)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type hyPacketConn struct {
|
type hyPacketConn struct {
|
||||||
@@ -287,7 +268,7 @@ func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type hyDialerWithContext struct {
|
type hyDialerWithContext struct {
|
||||||
hyDialer func(network string, rAddr net.Addr) (net.PacketConn, error)
|
hyDialer func(network string) (net.PacketConn, error)
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
remoteAddr func(host string) (net.Addr, error)
|
remoteAddr func(host string) (net.Addr, error)
|
||||||
}
|
}
|
||||||
@@ -297,7 +278,7 @@ func (h *hyDialerWithContext) ListenPacket(rAddr net.Addr) (net.PacketConn, erro
|
|||||||
if addrPort, err := netip.ParseAddrPort(rAddr.String()); err == nil {
|
if addrPort, err := netip.ParseAddrPort(rAddr.String()); err == nil {
|
||||||
network = dialer.ParseNetwork(network, addrPort.Addr())
|
network = dialer.ParseNetwork(network, addrPort.Addr())
|
||||||
}
|
}
|
||||||
return h.hyDialer(network, rAddr)
|
return h.hyDialer(network)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *hyDialerWithContext) Context() context.Context {
|
func (h *hyDialerWithContext) Context() context.Context {
|
||||||
|
|||||||
@@ -8,20 +8,16 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
|
||||||
|
|
||||||
CN "github.com/metacubex/mihomo/common/net"
|
CN "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
|
||||||
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
||||||
|
|
||||||
"github.com/metacubex/sing-quic/hysteria2"
|
"github.com/metacubex/sing-quic/hysteria2"
|
||||||
|
|
||||||
"github.com/metacubex/randv2"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -29,26 +25,19 @@ func init() {
|
|||||||
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
||||||
}
|
}
|
||||||
|
|
||||||
const minHopInterval = 5
|
|
||||||
const defaultHopInterval = 30
|
|
||||||
|
|
||||||
type Hysteria2 struct {
|
type Hysteria2 struct {
|
||||||
*Base
|
*Base
|
||||||
|
|
||||||
option *Hysteria2Option
|
option *Hysteria2Option
|
||||||
client *hysteria2.Client
|
client *hysteria2.Client
|
||||||
dialer proxydialer.SingDialer
|
dialer proxydialer.SingDialer
|
||||||
|
|
||||||
closeCh chan struct{} // for test
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Hysteria2Option struct {
|
type Hysteria2Option struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port,omitempty"`
|
Port int `proxy:"port"`
|
||||||
Ports string `proxy:"ports,omitempty"`
|
|
||||||
HopInterval int `proxy:"hop-interval,omitempty"`
|
|
||||||
Up string `proxy:"up,omitempty"`
|
Up string `proxy:"up,omitempty"`
|
||||||
Down string `proxy:"down,omitempty"`
|
Down string `proxy:"down,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
@@ -61,7 +50,6 @@ type Hysteria2Option struct {
|
|||||||
CustomCA string `proxy:"ca,omitempty"`
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
CustomCAString string `proxy:"ca-str,omitempty"`
|
||||||
CWND int `proxy:"cwnd,omitempty"`
|
CWND int `proxy:"cwnd,omitempty"`
|
||||||
UdpMTU int `proxy:"udp-mtu,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria2) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (h *Hysteria2) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
@@ -91,16 +79,6 @@ func closeHysteria2(h *Hysteria2) {
|
|||||||
if h.client != nil {
|
if h.client != nil {
|
||||||
_ = h.client.CloseWithError(errors.New("proxy removed"))
|
_ = h.client.CloseWithError(errors.New("proxy removed"))
|
||||||
}
|
}
|
||||||
if h.closeCh != nil {
|
|
||||||
close(h.closeCh)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (h *Hysteria2) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := h.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = h.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||||
@@ -139,18 +117,12 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|||||||
tlsConfig.NextProtos = option.ALPN
|
tlsConfig.NextProtos = option.ALPN
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.UdpMTU == 0 {
|
|
||||||
// "1200" from quic-go's MaxDatagramSize
|
|
||||||
// "-3" from quic-go's DatagramFrame.MaxDataLen
|
|
||||||
option.UdpMTU = 1200 - 3
|
|
||||||
}
|
|
||||||
|
|
||||||
singDialer := proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer())
|
singDialer := proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer())
|
||||||
|
|
||||||
clientOptions := hysteria2.ClientOptions{
|
clientOptions := hysteria2.ClientOptions{
|
||||||
Context: context.TODO(),
|
Context: context.TODO(),
|
||||||
Dialer: singDialer,
|
Dialer: singDialer,
|
||||||
Logger: log.SingLogger,
|
ServerAddress: M.ParseSocksaddrHostPort(option.Server, uint16(option.Port)),
|
||||||
SendBPS: StringToBps(option.Up),
|
SendBPS: StringToBps(option.Up),
|
||||||
ReceiveBPS: StringToBps(option.Down),
|
ReceiveBPS: StringToBps(option.Down),
|
||||||
SalamanderPassword: salamanderPassword,
|
SalamanderPassword: salamanderPassword,
|
||||||
@@ -158,38 +130,6 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|||||||
TLSConfig: tlsConfig,
|
TLSConfig: tlsConfig,
|
||||||
UDPDisabled: false,
|
UDPDisabled: false,
|
||||||
CWND: option.CWND,
|
CWND: option.CWND,
|
||||||
UdpMTU: option.UdpMTU,
|
|
||||||
ServerAddress: func(ctx context.Context) (*net.UDPAddr, error) {
|
|
||||||
return resolveUDPAddrWithPrefer(ctx, "udp", addr, C.NewDNSPrefer(option.IPVersion))
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var ranges utils.IntRanges[uint16]
|
|
||||||
var serverAddress []string
|
|
||||||
if option.Ports != "" {
|
|
||||||
ranges, err = utils.NewUnsignedRanges[uint16](option.Ports)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ranges.Range(func(port uint16) bool {
|
|
||||||
serverAddress = append(serverAddress, net.JoinHostPort(option.Server, strconv.Itoa(int(port))))
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
if len(serverAddress) > 0 {
|
|
||||||
clientOptions.ServerAddress = func(ctx context.Context) (*net.UDPAddr, error) {
|
|
||||||
return resolveUDPAddrWithPrefer(ctx, "udp", serverAddress[randv2.IntN(len(serverAddress))], C.NewDNSPrefer(option.IPVersion))
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.HopInterval == 0 {
|
|
||||||
option.HopInterval = defaultHopInterval
|
|
||||||
} else if option.HopInterval < minHopInterval {
|
|
||||||
option.HopInterval = minHopInterval
|
|
||||||
}
|
|
||||||
clientOptions.HopInterval = time.Duration(option.HopInterval) * time.Second
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if option.Port == 0 && len(serverAddress) == 0 {
|
|
||||||
return nil, errors.New("invalid port")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
client, err := hysteria2.NewClient(clientOptions)
|
client, err := hysteria2.NewClient(clientOptions)
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestHysteria2GC(t *testing.T) {
|
|
||||||
option := Hysteria2Option{}
|
|
||||||
option.Server = "127.0.0.1"
|
|
||||||
option.Ports = "200,204,401-429,501-503"
|
|
||||||
option.HopInterval = 30
|
|
||||||
option.Password = "password"
|
|
||||||
option.Obfs = "salamander"
|
|
||||||
option.ObfsPassword = "password"
|
|
||||||
option.SNI = "example.com"
|
|
||||||
option.ALPN = []string{"h3"}
|
|
||||||
hy, err := NewHysteria2(option)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
closeCh := make(chan struct{})
|
|
||||||
hy.closeCh = closeCh
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
hy = nil
|
|
||||||
runtime.GC()
|
|
||||||
select {
|
|
||||||
case <-closeCh:
|
|
||||||
return
|
|
||||||
case <-ctx.Done():
|
|
||||||
t.Error("timeout not GC")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestHysteriaGC(t *testing.T) {
|
|
||||||
option := HysteriaOption{}
|
|
||||||
option.Server = "127.0.0.1"
|
|
||||||
option.Ports = "200,204,401-429,501-503"
|
|
||||||
option.Protocol = "udp"
|
|
||||||
option.Up = "1Mbps"
|
|
||||||
option.Down = "1Mbps"
|
|
||||||
option.HopInterval = 30
|
|
||||||
option.Obfs = "salamander"
|
|
||||||
option.SNI = "example.com"
|
|
||||||
option.ALPN = []string{"h3"}
|
|
||||||
hy, err := NewHysteria(option)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
closeCh := make(chan struct{})
|
|
||||||
hy.closeCh = closeCh
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
hy = nil
|
|
||||||
runtime.GC()
|
|
||||||
select {
|
|
||||||
case <-closeCh:
|
|
||||||
return
|
|
||||||
case <-ctx.Done():
|
|
||||||
t.Error("timeout not GC")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,268 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
mieruclient "github.com/enfein/mieru/v3/apis/client"
|
|
||||||
mierumodel "github.com/enfein/mieru/v3/apis/model"
|
|
||||||
mierupb "github.com/enfein/mieru/v3/pkg/appctl/appctlpb"
|
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
"google.golang.org/protobuf/proto"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Mieru struct {
|
|
||||||
*Base
|
|
||||||
option *MieruOption
|
|
||||||
client mieruclient.Client
|
|
||||||
mu sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
type MieruOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port,omitempty"`
|
|
||||||
PortRange string `proxy:"port-range,omitempty"`
|
|
||||||
Transport string `proxy:"transport"`
|
|
||||||
UserName string `proxy:"username"`
|
|
||||||
Password string `proxy:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
|
||||||
func (m *Mieru) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
|
||||||
if err := m.ensureClientIsRunning(opts...); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
addr := metadataToMieruNetAddrSpec(metadata)
|
|
||||||
c, err := m.client.DialContext(ctx, addr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("dial to %s failed: %w", addr, err)
|
|
||||||
}
|
|
||||||
return NewConn(c, m), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (m *Mieru) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := m.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = m.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Mieru) ensureClientIsRunning(opts ...dialer.Option) error {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
if m.client.IsRunning() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a dialer and add it to the client config, before starting the client.
|
|
||||||
var dialer C.Dialer = dialer.NewDialer(m.Base.DialOptions(opts...)...)
|
|
||||||
var err error
|
|
||||||
if len(m.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(m.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
config, err := m.client.Load()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
config.Dialer = dialer
|
|
||||||
if err := m.client.Store(config); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := m.client.Start(); err != nil {
|
|
||||||
return fmt.Errorf("failed to start mieru client: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMieru(option MieruOption) (*Mieru, error) {
|
|
||||||
config, err := buildMieruClientConfig(option)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to build mieru client config: %w", err)
|
|
||||||
}
|
|
||||||
c := mieruclient.NewClient()
|
|
||||||
if err := c.Store(config); err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to store mieru client config: %w", err)
|
|
||||||
}
|
|
||||||
// Client is started lazily on the first use.
|
|
||||||
|
|
||||||
var addr string
|
|
||||||
if option.Port != 0 {
|
|
||||||
addr = net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
} else {
|
|
||||||
beginPort, _, _ := beginAndEndPortFromPortRange(option.PortRange)
|
|
||||||
addr = net.JoinHostPort(option.Server, strconv.Itoa(beginPort))
|
|
||||||
}
|
|
||||||
outbound := &Mieru{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: addr,
|
|
||||||
iface: option.Interface,
|
|
||||||
tp: C.Mieru,
|
|
||||||
udp: false,
|
|
||||||
xudp: false,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
option: &option,
|
|
||||||
client: c,
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeMieru)
|
|
||||||
return outbound, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeMieru(m *Mieru) {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
if m.client != nil && m.client.IsRunning() {
|
|
||||||
m.client.Stop()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func metadataToMieruNetAddrSpec(metadata *C.Metadata) mierumodel.NetAddrSpec {
|
|
||||||
if metadata.Host != "" {
|
|
||||||
return mierumodel.NetAddrSpec{
|
|
||||||
AddrSpec: mierumodel.AddrSpec{
|
|
||||||
FQDN: metadata.Host,
|
|
||||||
Port: int(metadata.DstPort),
|
|
||||||
},
|
|
||||||
Net: "tcp",
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return mierumodel.NetAddrSpec{
|
|
||||||
AddrSpec: mierumodel.AddrSpec{
|
|
||||||
IP: metadata.DstIP.AsSlice(),
|
|
||||||
Port: int(metadata.DstPort),
|
|
||||||
},
|
|
||||||
Net: "tcp",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildMieruClientConfig(option MieruOption) (*mieruclient.ClientConfig, error) {
|
|
||||||
if err := validateMieruOption(option); err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to validate mieru option: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
transportProtocol := mierupb.TransportProtocol_TCP.Enum()
|
|
||||||
var server *mierupb.ServerEndpoint
|
|
||||||
if net.ParseIP(option.Server) != nil {
|
|
||||||
// server is an IP address
|
|
||||||
if option.PortRange != "" {
|
|
||||||
server = &mierupb.ServerEndpoint{
|
|
||||||
IpAddress: proto.String(option.Server),
|
|
||||||
PortBindings: []*mierupb.PortBinding{
|
|
||||||
{
|
|
||||||
PortRange: proto.String(option.PortRange),
|
|
||||||
Protocol: transportProtocol,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
server = &mierupb.ServerEndpoint{
|
|
||||||
IpAddress: proto.String(option.Server),
|
|
||||||
PortBindings: []*mierupb.PortBinding{
|
|
||||||
{
|
|
||||||
Port: proto.Int32(int32(option.Port)),
|
|
||||||
Protocol: transportProtocol,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// server is a domain name
|
|
||||||
if option.PortRange != "" {
|
|
||||||
server = &mierupb.ServerEndpoint{
|
|
||||||
DomainName: proto.String(option.Server),
|
|
||||||
PortBindings: []*mierupb.PortBinding{
|
|
||||||
{
|
|
||||||
PortRange: proto.String(option.PortRange),
|
|
||||||
Protocol: transportProtocol,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
server = &mierupb.ServerEndpoint{
|
|
||||||
DomainName: proto.String(option.Server),
|
|
||||||
PortBindings: []*mierupb.PortBinding{
|
|
||||||
{
|
|
||||||
Port: proto.Int32(int32(option.Port)),
|
|
||||||
Protocol: transportProtocol,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &mieruclient.ClientConfig{
|
|
||||||
Profile: &mierupb.ClientProfile{
|
|
||||||
ProfileName: proto.String(option.Name),
|
|
||||||
User: &mierupb.User{
|
|
||||||
Name: proto.String(option.UserName),
|
|
||||||
Password: proto.String(option.Password),
|
|
||||||
},
|
|
||||||
Servers: []*mierupb.ServerEndpoint{server},
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateMieruOption(option MieruOption) error {
|
|
||||||
if option.Name == "" {
|
|
||||||
return fmt.Errorf("name is empty")
|
|
||||||
}
|
|
||||||
if option.Server == "" {
|
|
||||||
return fmt.Errorf("server is empty")
|
|
||||||
}
|
|
||||||
if option.Port == 0 && option.PortRange == "" {
|
|
||||||
return fmt.Errorf("either port or port-range must be set")
|
|
||||||
}
|
|
||||||
if option.Port != 0 && option.PortRange != "" {
|
|
||||||
return fmt.Errorf("port and port-range cannot be set at the same time")
|
|
||||||
}
|
|
||||||
if option.Port != 0 && (option.Port < 1 || option.Port > 65535) {
|
|
||||||
return fmt.Errorf("port must be between 1 and 65535")
|
|
||||||
}
|
|
||||||
if option.PortRange != "" {
|
|
||||||
begin, end, err := beginAndEndPortFromPortRange(option.PortRange)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("invalid port-range format")
|
|
||||||
}
|
|
||||||
if begin < 1 || begin > 65535 {
|
|
||||||
return fmt.Errorf("begin port must be between 1 and 65535")
|
|
||||||
}
|
|
||||||
if end < 1 || end > 65535 {
|
|
||||||
return fmt.Errorf("end port must be between 1 and 65535")
|
|
||||||
}
|
|
||||||
if begin > end {
|
|
||||||
return fmt.Errorf("begin port must be less than or equal to end port")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.Transport != "TCP" {
|
|
||||||
return fmt.Errorf("transport must be TCP")
|
|
||||||
}
|
|
||||||
if option.UserName == "" {
|
|
||||||
return fmt.Errorf("username is empty")
|
|
||||||
}
|
|
||||||
if option.Password == "" {
|
|
||||||
return fmt.Errorf("password is empty")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func beginAndEndPortFromPortRange(portRange string) (int, int, error) {
|
|
||||||
var begin, end int
|
|
||||||
_, err := fmt.Sscanf(portRange, "%d-%d", &begin, &end)
|
|
||||||
return begin, end, err
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestNewMieru(t *testing.T) {
|
|
||||||
testCases := []struct {
|
|
||||||
option MieruOption
|
|
||||||
wantBaseAddr string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
option: MieruOption{
|
|
||||||
Name: "test",
|
|
||||||
Server: "1.2.3.4",
|
|
||||||
Port: 10000,
|
|
||||||
Transport: "TCP",
|
|
||||||
UserName: "test",
|
|
||||||
Password: "test",
|
|
||||||
},
|
|
||||||
wantBaseAddr: "1.2.3.4:10000",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
option: MieruOption{
|
|
||||||
Name: "test",
|
|
||||||
Server: "2001:db8::1",
|
|
||||||
PortRange: "10001-10002",
|
|
||||||
Transport: "TCP",
|
|
||||||
UserName: "test",
|
|
||||||
Password: "test",
|
|
||||||
},
|
|
||||||
wantBaseAddr: "[2001:db8::1]:10001",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
option: MieruOption{
|
|
||||||
Name: "test",
|
|
||||||
Server: "example.com",
|
|
||||||
Port: 10003,
|
|
||||||
Transport: "TCP",
|
|
||||||
UserName: "test",
|
|
||||||
Password: "test",
|
|
||||||
},
|
|
||||||
wantBaseAddr: "example.com:10003",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, testCase := range testCases {
|
|
||||||
mieru, err := NewMieru(testCase.option)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
if mieru.addr != testCase.wantBaseAddr {
|
|
||||||
t.Errorf("got addr %q, want %q", mieru.addr, testCase.wantBaseAddr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBeginAndEndPortFromPortRange(t *testing.T) {
|
|
||||||
testCases := []struct {
|
|
||||||
input string
|
|
||||||
begin int
|
|
||||||
end int
|
|
||||||
hasErr bool
|
|
||||||
}{
|
|
||||||
{"1-10", 1, 10, false},
|
|
||||||
{"1000-2000", 1000, 2000, false},
|
|
||||||
{"65535-65535", 65535, 65535, false},
|
|
||||||
{"1", 0, 0, true},
|
|
||||||
{"1-", 0, 0, true},
|
|
||||||
{"-10", 0, 0, true},
|
|
||||||
{"a-b", 0, 0, true},
|
|
||||||
{"1-b", 0, 0, true},
|
|
||||||
{"a-10", 0, 0, true},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, testCase := range testCases {
|
|
||||||
begin, end, err := beginAndEndPortFromPortRange(testCase.input)
|
|
||||||
if testCase.hasErr {
|
|
||||||
if err == nil {
|
|
||||||
t.Errorf("beginAndEndPortFromPortRange(%s) should return an error", testCase.input)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("beginAndEndPortFromPortRange(%s) should not return an error, but got %v", testCase.input, err)
|
|
||||||
}
|
|
||||||
if begin != testCase.begin {
|
|
||||||
t.Errorf("beginAndEndPortFromPortRange(%s) begin port mismatch, got %d, want %d", testCase.input, begin, testCase.begin)
|
|
||||||
}
|
|
||||||
if end != testCase.end {
|
|
||||||
t.Errorf("beginAndEndPortFromPortRange(%s) end port mismatch, got %d, want %d", testCase.input, end, testCase.end)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
package outbound
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/ecdh"
|
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
|
|
||||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/curve25519"
|
||||||
)
|
)
|
||||||
|
|
||||||
type RealityOptions struct {
|
type RealityOptions struct {
|
||||||
@@ -19,16 +19,10 @@ func (o RealityOptions) Parse() (*tlsC.RealityConfig, error) {
|
|||||||
if o.PublicKey != "" {
|
if o.PublicKey != "" {
|
||||||
config := new(tlsC.RealityConfig)
|
config := new(tlsC.RealityConfig)
|
||||||
|
|
||||||
const x25519ScalarSize = 32
|
n, err := base64.RawURLEncoding.Decode(config.PublicKey[:], []byte(o.PublicKey))
|
||||||
var publicKey [x25519ScalarSize]byte
|
if err != nil || n != curve25519.ScalarSize {
|
||||||
n, err := base64.RawURLEncoding.Decode(publicKey[:], []byte(o.PublicKey))
|
|
||||||
if err != nil || n != x25519ScalarSize {
|
|
||||||
return nil, errors.New("invalid REALITY public key")
|
return nil, errors.New("invalid REALITY public key")
|
||||||
}
|
}
|
||||||
config.PublicKey, err = ecdh.X25519().NewPublicKey(publicKey[:])
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("fail to create REALITY public key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err = hex.Decode(config.ShortID[:], []byte(o.ShortID))
|
n, err = hex.Decode(config.ShortID[:], []byte(o.ShortID))
|
||||||
if err != nil || n > tlsC.RealityMaxShortIDLen {
|
if err != nil || n > tlsC.RealityMaxShortIDLen {
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
if r.drop {
|
||||||
|
return newPacketConn(&dropPacketConn{}, r), nil
|
||||||
|
}
|
||||||
return newPacketConn(&nopPacketConn{}, r), nil
|
return newPacketConn(&nopPacketConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,7 +40,7 @@ func NewRejectWithOption(option RejectOption) *Reject {
|
|||||||
return &Reject{
|
return &Reject{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
tp: C.Reject,
|
tp: C.Direct,
|
||||||
udp: true,
|
udp: true,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -126,3 +129,22 @@ func (rw dropConn) RemoteAddr() net.Addr { return nil }
|
|||||||
func (rw dropConn) SetDeadline(time.Time) error { return nil }
|
func (rw dropConn) SetDeadline(time.Time) error { return nil }
|
||||||
func (rw dropConn) SetReadDeadline(time.Time) error { return nil }
|
func (rw dropConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (rw dropConn) SetWriteDeadline(time.Time) error { return nil }
|
func (rw dropConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
|
type dropPacketConn struct{}
|
||||||
|
|
||||||
|
func (npc dropPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
time.Sleep(C.DefaultDropTime)
|
||||||
|
return len(b), nil
|
||||||
|
}
|
||||||
|
func (npc dropPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
time.Sleep(C.DefaultDropTime)
|
||||||
|
return 0, nil, io.EOF
|
||||||
|
}
|
||||||
|
func (npc dropPacketConn) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
||||||
|
return nil, nil, nil, io.EOF
|
||||||
|
}
|
||||||
|
func (npc dropPacketConn) Close() error { return nil }
|
||||||
|
func (npc dropPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
||||||
|
func (npc dropPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (npc dropPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (npc dropPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ import (
|
|||||||
|
|
||||||
restlsC "github.com/3andne/restls-client-go"
|
restlsC "github.com/3andne/restls-client-go"
|
||||||
shadowsocks "github.com/metacubex/sing-shadowsocks2"
|
shadowsocks "github.com/metacubex/sing-shadowsocks2"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
"github.com/sagernet/sing/common/uot"
|
"github.com/sagernet/sing/common/uot"
|
||||||
)
|
)
|
||||||
@@ -149,6 +148,7 @@ func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Diale
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
@@ -165,6 +165,12 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if len(ss.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -172,12 +178,6 @@ func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dial
|
|||||||
}
|
}
|
||||||
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
||||||
}
|
}
|
||||||
if len(ss.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -187,7 +187,7 @@ func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dial
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pc = ss.method.DialPacketConn(bufio.NewBindPacketConn(pc, addr))
|
pc = ss.method.DialPacketConn(N.NewBindPacketConn(pc, addr))
|
||||||
return newPacketConn(pc, ss), nil
|
return newPacketConn(pc, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,13 +196,6 @@ func (ss *ShadowSocks) SupportWithDialer() C.NetWork {
|
|||||||
return C.ALLNet
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := ss.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = ss.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ss *ShadowSocks) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
@@ -217,9 +210,9 @@ func (ss *ShadowSocks) ListenPacketOnStreamConn(ctx context.Context, c net.Conn,
|
|||||||
|
|
||||||
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||||
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
||||||
return newPacketConn(N.NewThreadSafePacketConn(uot.NewConn(c, uot.Request{Destination: destination})), ss), nil
|
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), ss), nil
|
||||||
} else {
|
} else {
|
||||||
return newPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), ss), nil
|
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), ss), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, C.ErrNotSupport
|
return nil, C.ErrNotSupport
|
||||||
@@ -279,7 +272,6 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
if opts.TLS {
|
if opts.TLS {
|
||||||
v2rayOption.TLS = true
|
v2rayOption.TLS = true
|
||||||
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
v2rayOption.Fingerprint = opts.Fingerprint
|
|
||||||
}
|
}
|
||||||
} else if option.Plugin == shadowtls.Mode {
|
} else if option.Plugin == shadowtls.Mode {
|
||||||
obfsMode = shadowtls.Mode
|
obfsMode = shadowtls.Mode
|
||||||
|
|||||||
@@ -80,6 +80,7 @@ func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dia
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
@@ -122,13 +123,6 @@ func (ssr *ShadowSocksR) SupportWithDialer() C.NetWork {
|
|||||||
return C.ALLNet
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (ssr *ShadowSocksR) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := ssr.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = ssr.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
// SSR protocol compatibility
|
// SSR protocol compatibility
|
||||||
// https://github.com/metacubex/mihomo/pull/2056
|
// https://github.com/metacubex/mihomo/pull/2056
|
||||||
|
|||||||
@@ -97,12 +97,6 @@ func (s *SingMux) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SingMux) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := s.ProxyAdapter.ProxyInfo()
|
|
||||||
info.SMUX = true
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeSingMux(s *SingMux) {
|
func closeSingMux(s *SingMux) {
|
||||||
_ = s.client.Close()
|
_ = s.client.Close()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
@@ -93,6 +94,7 @@ func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
@@ -120,6 +122,7 @@ func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
|
||||||
err = snell.WriteUDPHeader(c, s.version)
|
err = snell.WriteUDPHeader(c, s.version)
|
||||||
@@ -141,13 +144,6 @@ func (s *Snell) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (s *Snell) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := s.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = s.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSnell(option SnellOption) (*Snell, error) {
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
psk := []byte(option.Psk)
|
psk := []byte(option.Psk)
|
||||||
@@ -212,6 +208,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
return streamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
return streamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
@@ -81,6 +82,7 @@ func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
@@ -126,6 +128,7 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
if ss.user != "" {
|
if ss.user != "" {
|
||||||
user = &socks5.User{
|
user = &socks5.User{
|
||||||
@@ -171,13 +174,6 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (ss *Socks5) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := ss.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = ss.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) (*Socks5, error) {
|
func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
|
|||||||
@@ -1,214 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/base64"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
|
|
||||||
"github.com/metacubex/randv2"
|
|
||||||
"golang.org/x/crypto/ssh"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Ssh struct {
|
|
||||||
*Base
|
|
||||||
|
|
||||||
option *SshOption
|
|
||||||
client *sshClient // using a standalone struct to avoid its inner loop invalidate the Finalizer
|
|
||||||
}
|
|
||||||
|
|
||||||
type SshOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
UserName string `proxy:"username"`
|
|
||||||
Password string `proxy:"password,omitempty"`
|
|
||||||
PrivateKey string `proxy:"private-key,omitempty"`
|
|
||||||
PrivateKeyPassphrase string `proxy:"private-key-passphrase,omitempty"`
|
|
||||||
HostKey []string `proxy:"host-key,omitempty"`
|
|
||||||
HostKeyAlgorithms []string `proxy:"host-key-algorithms,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Ssh) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
|
||||||
var cDialer C.Dialer = dialer.NewDialer(s.Base.DialOptions(opts...)...)
|
|
||||||
if len(s.option.DialerProxy) > 0 {
|
|
||||||
cDialer, err = proxydialer.NewByName(s.option.DialerProxy, cDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
client, err := s.client.connect(ctx, cDialer, s.addr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
c, err := client.DialContext(ctx, "tcp", metadata.RemoteAddress())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(N.NewRefConn(c, s), s), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type sshClient struct {
|
|
||||||
config *ssh.ClientConfig
|
|
||||||
client *ssh.Client
|
|
||||||
cMutex sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *sshClient) connect(ctx context.Context, cDialer C.Dialer, addr string) (client *ssh.Client, err error) {
|
|
||||||
s.cMutex.Lock()
|
|
||||||
defer s.cMutex.Unlock()
|
|
||||||
if s.client != nil {
|
|
||||||
return s.client, nil
|
|
||||||
}
|
|
||||||
c, err := cDialer.DialContext(ctx, "tcp", addr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
if ctx.Done() != nil {
|
|
||||||
done := N.SetupContextForConn(ctx, c)
|
|
||||||
defer done(&err)
|
|
||||||
}
|
|
||||||
|
|
||||||
clientConn, chans, reqs, err := ssh.NewClientConn(c, addr, s.config)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
client = ssh.NewClient(clientConn, chans, reqs)
|
|
||||||
|
|
||||||
s.client = client
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
_ = client.Wait() // wait shutdown
|
|
||||||
_ = client.Close()
|
|
||||||
s.cMutex.Lock()
|
|
||||||
defer s.cMutex.Unlock()
|
|
||||||
if s.client == client {
|
|
||||||
s.client = nil
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return client, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *sshClient) Close() error {
|
|
||||||
s.cMutex.Lock()
|
|
||||||
defer s.cMutex.Unlock()
|
|
||||||
if s.client != nil {
|
|
||||||
return s.client.Close()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeSsh(s *Ssh) {
|
|
||||||
_ = s.client.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (s *Ssh) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := s.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = s.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSsh(option SshOption) (*Ssh, error) {
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
|
|
||||||
config := ssh.ClientConfig{
|
|
||||||
User: option.UserName,
|
|
||||||
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
|
||||||
HostKeyAlgorithms: option.HostKeyAlgorithms,
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.PrivateKey != "" {
|
|
||||||
var b []byte
|
|
||||||
var err error
|
|
||||||
if strings.Contains(option.PrivateKey, "PRIVATE KEY") {
|
|
||||||
b = []byte(option.PrivateKey)
|
|
||||||
} else {
|
|
||||||
b, err = os.ReadFile(C.Path.Resolve(option.PrivateKey))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var pKey ssh.Signer
|
|
||||||
if option.PrivateKeyPassphrase != "" {
|
|
||||||
pKey, err = ssh.ParsePrivateKeyWithPassphrase(b, []byte(option.PrivateKeyPassphrase))
|
|
||||||
} else {
|
|
||||||
pKey, err = ssh.ParsePrivateKey(b)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
config.Auth = append(config.Auth, ssh.PublicKeys(pKey))
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.Password != "" {
|
|
||||||
config.Auth = append(config.Auth, ssh.Password(option.Password))
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.HostKey) != 0 {
|
|
||||||
keys := make([]ssh.PublicKey, len(option.HostKey))
|
|
||||||
for i, hostKey := range option.HostKey {
|
|
||||||
key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(hostKey))
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("parse host key :%s", key)
|
|
||||||
}
|
|
||||||
keys[i] = key
|
|
||||||
}
|
|
||||||
config.HostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
|
||||||
serverKey := key.Marshal()
|
|
||||||
for _, hostKey := range keys {
|
|
||||||
if bytes.Equal(serverKey, hostKey.Marshal()) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fmt.Errorf("host key mismatch, server send :%s %s", key.Type(), base64.StdEncoding.EncodeToString(serverKey))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
version := "SSH-2.0-OpenSSH_"
|
|
||||||
if randv2.IntN(2) == 0 {
|
|
||||||
version += "7." + strconv.Itoa(randv2.IntN(10))
|
|
||||||
} else {
|
|
||||||
version += "8." + strconv.Itoa(randv2.IntN(9))
|
|
||||||
}
|
|
||||||
config.ClientVersion = version
|
|
||||||
|
|
||||||
outbound := &Ssh{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: addr,
|
|
||||||
tp: C.Ssh,
|
|
||||||
udp: false,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
option: &option,
|
|
||||||
client: &sshClient{
|
|
||||||
config: &config,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeSsh)
|
|
||||||
|
|
||||||
return outbound, nil
|
|
||||||
}
|
|
||||||
@@ -3,19 +3,18 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/transport/gun"
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
"github.com/metacubex/mihomo/transport/shadowsocks/core"
|
|
||||||
"github.com/metacubex/mihomo/transport/trojan"
|
"github.com/metacubex/mihomo/transport/trojan"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -30,8 +29,6 @@ type Trojan struct {
|
|||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
realityConfig *tlsC.RealityConfig
|
realityConfig *tlsC.RealityConfig
|
||||||
|
|
||||||
ssCipher core.Cipher
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
@@ -49,17 +46,9 @@ type TrojanOption struct {
|
|||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
SSOpts TrojanSSOption `proxy:"ss-opts,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TrojanSSOption from https://github.com/p4gefau1t/trojan-go/blob/v0.10.6/tunnel/shadowsocks/config.go#L5
|
|
||||||
type TrojanSSOption struct {
|
|
||||||
Enabled bool `proxy:"enabled,omitempty"`
|
|
||||||
Method string `proxy:"method,omitempty"`
|
|
||||||
Password string `proxy:"password,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error) {
|
func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error) {
|
||||||
if t.option.Network == "ws" {
|
if t.option.Network == "ws" {
|
||||||
host, port, _ := net.SplitHostPort(t.addr)
|
host, port, _ := net.SplitHostPort(t.addr)
|
||||||
@@ -106,10 +95,6 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.ssCipher != nil {
|
|
||||||
c = t.ssCipher.StreamConn(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return c, err
|
||||||
@@ -127,10 +112,6 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.ssCipher != nil {
|
|
||||||
c = t.ssCipher.StreamConn(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||||
c.Close()
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -153,6 +134,7 @@ func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
@@ -179,11 +161,6 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
if t.ssCipher != nil {
|
|
||||||
c = t.ssCipher.StreamConn(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -210,15 +187,12 @@ func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
c, err = t.plainStream(ctx, c)
|
c, err = t.plainStream(ctx, c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.ssCipher != nil {
|
|
||||||
c = t.ssCipher.StreamConn(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -244,13 +218,6 @@ func (t *Trojan) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := t.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = t.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
@@ -290,20 +257,6 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
}
|
}
|
||||||
tOption.Reality = t.realityConfig
|
tOption.Reality = t.realityConfig
|
||||||
|
|
||||||
if option.SSOpts.Enabled {
|
|
||||||
if option.SSOpts.Password == "" {
|
|
||||||
return nil, errors.New("empty password")
|
|
||||||
}
|
|
||||||
if option.SSOpts.Method == "" {
|
|
||||||
option.SSOpts.Method = "AES-128-GCM"
|
|
||||||
}
|
|
||||||
ciph, err := core.PickCipher(option.SSOpts.Method, nil, option.SSOpts.Password)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
t.ssCipher = ciph
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.Network == "grpc" {
|
if option.Network == "grpc" {
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
@@ -318,6 +271,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -146,13 +146,6 @@ func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (transport *
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := t.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = t.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTuic(option TuicOption) (*Tuic, error) {
|
func NewTuic(option TuicOption) (*Tuic, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
serverName := option.Server
|
serverName := option.Server
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ func resolveUDPAddr(ctx context.Context, network, address string) (*net.UDPAddr,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := resolver.ResolveIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
ip, err := resolver.ResolveProxyServerHost(ctx, host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -71,12 +71,12 @@ func resolveUDPAddrWithPrefer(ctx context.Context, network, address string, pref
|
|||||||
var fallback netip.Addr
|
var fallback netip.Addr
|
||||||
switch prefer {
|
switch prefer {
|
||||||
case C.IPv4Only:
|
case C.IPv4Only:
|
||||||
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
ip, err = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
||||||
case C.IPv6Only:
|
case C.IPv6Only:
|
||||||
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
ip, err = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
||||||
case C.IPv6Prefer:
|
case C.IPv6Prefer:
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
ips, err = resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for _, addr := range ips {
|
for _, addr := range ips {
|
||||||
if addr.Is6() {
|
if addr.Is6() {
|
||||||
@@ -92,7 +92,7 @@ func resolveUDPAddrWithPrefer(ctx context.Context, network, address string, pref
|
|||||||
default:
|
default:
|
||||||
// C.IPv4Prefer, C.DualStack and other
|
// C.IPv4Prefer, C.DualStack and other
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
ips, err = resolver.LookupIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for _, addr := range ips {
|
for _, addr := range ips {
|
||||||
if addr.Is4() {
|
if addr.Is4() {
|
||||||
@@ -140,25 +140,24 @@ func StringToBps(s string) uint64 {
|
|||||||
if m == nil {
|
if m == nil {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
var n uint64 = 1
|
var n uint64
|
||||||
switch m[2] {
|
switch m[2] {
|
||||||
case "T":
|
|
||||||
n *= 1000
|
|
||||||
fallthrough
|
|
||||||
case "G":
|
|
||||||
n *= 1000
|
|
||||||
fallthrough
|
|
||||||
case "M":
|
|
||||||
n *= 1000
|
|
||||||
fallthrough
|
|
||||||
case "K":
|
case "K":
|
||||||
n *= 1000
|
n = 1 << 10
|
||||||
|
case "M":
|
||||||
|
n = 1 << 20
|
||||||
|
case "G":
|
||||||
|
n = 1 << 30
|
||||||
|
case "T":
|
||||||
|
n = 1 << 40
|
||||||
|
default:
|
||||||
|
n = 1
|
||||||
}
|
}
|
||||||
v, _ := strconv.ParseUint(m[1], 10, 64)
|
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||||
n *= v
|
n = v * n
|
||||||
if m[3] == "b" {
|
if m[3] == "b" {
|
||||||
// Bits, need to convert to bytes
|
// Bits, need to convert to bytes
|
||||||
n /= 8
|
n = n >> 3
|
||||||
}
|
}
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -262,6 +262,7 @@ func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
@@ -326,6 +327,7 @@ func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
@@ -371,7 +373,7 @@ func (v *Vless) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metada
|
|||||||
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||||
), v), nil
|
), v), nil
|
||||||
}
|
}
|
||||||
return newPacketConn(N.NewThreadSafePacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), v), nil
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@@ -379,13 +381,6 @@ func (v *Vless) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (v *Vless) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := v.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = v.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
||||||
var addrType byte
|
var addrType byte
|
||||||
var addr []byte
|
var addr []byte
|
||||||
@@ -510,14 +505,17 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
var addons *vless.Addons
|
var addons *vless.Addons
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
option.Flow = option.Flow[:16]
|
option.Flow = option.Flow[:16]
|
||||||
if option.Flow != vless.XRV {
|
switch option.Flow {
|
||||||
|
case vless.XRV:
|
||||||
|
log.Warnln("To use %s, ensure your server is upgrade to Xray-core v1.8.0+", vless.XRV)
|
||||||
|
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)
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Warnln("To use %s, ensure your server is upgrade to Xray-core v1.8.0+", vless.XRV)
|
|
||||||
addons = &vless.Addons{
|
|
||||||
Flow: option.Flow,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.PacketEncoding {
|
switch option.PacketEncoding {
|
||||||
@@ -579,6 +577,7 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -179,7 +179,6 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
tlsOpts := mihomoVMess.TLSConfig{
|
tlsOpts := mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
@@ -209,7 +208,6 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
tlsOpts := &mihomoVMess.TLSConfig{
|
tlsOpts := &mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
NextProtos: v.option.ALPN,
|
NextProtos: v.option.ALPN,
|
||||||
@@ -312,6 +310,7 @@ func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
@@ -372,6 +371,7 @@ func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
@@ -388,13 +388,6 @@ func (v *Vmess) SupportWithDialer() C.NetWork {
|
|||||||
return C.ALLNet
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyInfo implements C.ProxyAdapter
|
|
||||||
func (v *Vmess) ProxyInfo() C.ProxyInfo {
|
|
||||||
info := v.Base.ProxyInfo()
|
|
||||||
info.DialerProxy = v.option.DialerProxy
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
@@ -478,6 +471,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,98 +12,63 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
|
||||||
CN "github.com/metacubex/mihomo/common/net"
|
CN "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
"github.com/metacubex/mihomo/component/slowdown"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/dns"
|
"github.com/metacubex/mihomo/dns"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
amnezia "github.com/metacubex/amneziawg-go/device"
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
"github.com/metacubex/wireguard-go/device"
|
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
"github.com/sagernet/sing/common/debug"
|
"github.com/sagernet/sing/common/debug"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
"github.com/sagernet/wireguard-go/device"
|
||||||
)
|
)
|
||||||
|
|
||||||
type wireguardGoDevice interface {
|
|
||||||
Close()
|
|
||||||
IpcSet(uapiConf string) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type WireGuard struct {
|
type WireGuard struct {
|
||||||
*Base
|
*Base
|
||||||
bind *wireguard.ClientBind
|
bind *wireguard.ClientBind
|
||||||
device wireguardGoDevice
|
device *device.Device
|
||||||
tunDevice wireguard.Device
|
tunDevice wireguard.Device
|
||||||
dialer proxydialer.SingDialer
|
dialer proxydialer.SingDialer
|
||||||
resolver resolver.Resolver
|
startOnce sync.Once
|
||||||
|
startErr error
|
||||||
|
resolver *dns.Resolver
|
||||||
refP *refProxyAdapter
|
refP *refProxyAdapter
|
||||||
|
|
||||||
initOk atomic.Bool
|
|
||||||
initMutex sync.Mutex
|
|
||||||
initErr error
|
|
||||||
option WireGuardOption
|
|
||||||
connectAddr M.Socksaddr
|
|
||||||
localPrefixes []netip.Prefix
|
|
||||||
|
|
||||||
serverAddrMap map[M.Socksaddr]netip.AddrPort
|
|
||||||
serverAddrTime atomic.TypedValue[time.Time]
|
|
||||||
serverAddrMutex sync.Mutex
|
|
||||||
|
|
||||||
closeCh chan struct{} // for test
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardOption struct {
|
type WireGuardOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
WireGuardPeerOption
|
WireGuardPeerOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Ip string `proxy:"ip,omitempty"`
|
|
||||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
|
||||||
PrivateKey string `proxy:"private-key"`
|
PrivateKey string `proxy:"private-key"`
|
||||||
Workers int `proxy:"workers,omitempty"`
|
Workers int `proxy:"workers,omitempty"`
|
||||||
MTU int `proxy:"mtu,omitempty"`
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
||||||
|
|
||||||
AmneziaWGOption *AmneziaWGOption `proxy:"amnezia-wg-option,omitempty"`
|
|
||||||
|
|
||||||
Peers []WireGuardPeerOption `proxy:"peers,omitempty"`
|
Peers []WireGuardPeerOption `proxy:"peers,omitempty"`
|
||||||
|
|
||||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||||
Dns []string `proxy:"dns,omitempty"`
|
Dns []string `proxy:"dns,omitempty"`
|
||||||
|
|
||||||
RefreshServerIPInterval int `proxy:"refresh-server-ip-interval,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardPeerOption struct {
|
type WireGuardPeerOption struct {
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
PublicKey string `proxy:"public-key,omitempty"`
|
PublicKey string `proxy:"public-key,omitempty"`
|
||||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||||
AllowedIPs []string `proxy:"allowed-ips,omitempty"`
|
AllowedIPs []string `proxy:"allowed-ips,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AmneziaWGOption struct {
|
|
||||||
JC int `proxy:"jc"`
|
|
||||||
JMin int `proxy:"jmin"`
|
|
||||||
JMax int `proxy:"jmax"`
|
|
||||||
S1 int `proxy:"s1"`
|
|
||||||
S2 int `proxy:"s2"`
|
|
||||||
H1 uint32 `proxy:"h1"`
|
|
||||||
H2 uint32 `proxy:"h2"`
|
|
||||||
H3 uint32 `proxy:"h3"`
|
|
||||||
H4 uint32 `proxy:"h4"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type wgSingErrorHandler struct {
|
type wgSingErrorHandler struct {
|
||||||
name string
|
name string
|
||||||
}
|
}
|
||||||
@@ -132,7 +97,7 @@ func (option WireGuardPeerOption) Addr() M.Socksaddr {
|
|||||||
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (option WireGuardOption) Prefixes() ([]netip.Prefix, error) {
|
func (option WireGuardPeerOption) Prefixes() ([]netip.Prefix, error) {
|
||||||
localPrefixes := make([]netip.Prefix, 0, 2)
|
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||||
if len(option.Ip) > 0 {
|
if len(option.Ip) > 0 {
|
||||||
if !strings.Contains(option.Ip, "/") {
|
if !strings.Contains(option.Ip, "/") {
|
||||||
@@ -171,7 +136,7 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
dialer: proxydialer.NewSlowDownSingDialer(proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer()), slowdown.New()),
|
dialer: proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer()),
|
||||||
}
|
}
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
runtime.SetFinalizer(outbound, closeWireGuard)
|
||||||
|
|
||||||
@@ -183,103 +148,147 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
copy(reserved[:], option.Reserved)
|
copy(reserved[:], option.Reserved)
|
||||||
}
|
}
|
||||||
var isConnect bool
|
var isConnect bool
|
||||||
|
var connectAddr M.Socksaddr
|
||||||
if len(option.Peers) < 2 {
|
if len(option.Peers) < 2 {
|
||||||
isConnect = true
|
isConnect = true
|
||||||
if len(option.Peers) == 1 {
|
if len(option.Peers) == 1 {
|
||||||
outbound.connectAddr = option.Peers[0].Addr()
|
connectAddr = option.Peers[0].Addr()
|
||||||
} else {
|
} else {
|
||||||
outbound.connectAddr = option.Addr()
|
connectAddr = option.Addr()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, outbound.connectAddr.AddrPort(), reserved)
|
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, connectAddr, reserved)
|
||||||
|
|
||||||
var err error
|
var localPrefixes []netip.Prefix
|
||||||
outbound.localPrefixes, err = option.Prefixes()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
|
var privateKey string
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode private key")
|
return nil, E.Cause(err, "decode private key")
|
||||||
}
|
}
|
||||||
option.PrivateKey = hex.EncodeToString(bytes)
|
privateKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
|
ipcConf := "private_key=" + privateKey
|
||||||
if len(option.Peers) > 0 {
|
if peersLen := len(option.Peers); peersLen > 0 {
|
||||||
for i := range option.Peers {
|
localPrefixes = make([]netip.Prefix, 0, peersLen*2)
|
||||||
peer := &option.Peers[i] // we need modify option here
|
for i, peer := range option.Peers {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
var peerPublicKey, preSharedKey string
|
||||||
if err != nil {
|
{
|
||||||
return nil, E.Cause(err, "decode public key for peer ", i)
|
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode public key for peer ", i)
|
||||||
|
}
|
||||||
|
peerPublicKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
peer.PublicKey = hex.EncodeToString(bytes)
|
|
||||||
|
|
||||||
if peer.PreSharedKey != "" {
|
if peer.PreSharedKey != "" {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
||||||
}
|
}
|
||||||
peer.PreSharedKey = hex.EncodeToString(bytes)
|
preSharedKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
destination := peer.Addr()
|
||||||
|
ipcConf += "\npublic_key=" + peerPublicKey
|
||||||
|
ipcConf += "\nendpoint=" + destination.String()
|
||||||
|
if preSharedKey != "" {
|
||||||
|
ipcConf += "\npreshared_key=" + preSharedKey
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(peer.AllowedIPs) == 0 {
|
if len(peer.AllowedIPs) == 0 {
|
||||||
return nil, E.New("missing allowed_ips for peer ", i)
|
return nil, E.New("missing allowed_ips for peer ", i)
|
||||||
}
|
}
|
||||||
|
for _, allowedIP := range peer.AllowedIPs {
|
||||||
|
ipcConf += "\nallowed_ip=" + allowedIP
|
||||||
|
}
|
||||||
if len(peer.Reserved) > 0 {
|
if len(peer.Reserved) > 0 {
|
||||||
if len(peer.Reserved) != 3 {
|
if len(peer.Reserved) != 3 {
|
||||||
return nil, E.New("invalid reserved value for peer ", i, ", required 3 bytes, got ", len(peer.Reserved))
|
return nil, E.New("invalid reserved value for peer ", i, ", required 3 bytes, got ", len(peer.Reserved))
|
||||||
}
|
}
|
||||||
|
copy(reserved[:], option.Reserved)
|
||||||
|
outbound.bind.SetReservedForEndpoint(destination, reserved)
|
||||||
}
|
}
|
||||||
|
prefixes, err := peer.Prefixes()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
localPrefixes = append(localPrefixes, prefixes...)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
var peerPublicKey, preSharedKey string
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode peer public key")
|
return nil, E.Cause(err, "decode peer public key")
|
||||||
}
|
}
|
||||||
option.PublicKey = hex.EncodeToString(bytes)
|
peerPublicKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
if option.PreSharedKey != "" {
|
if option.PreSharedKey != "" {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode pre shared key")
|
return nil, E.Cause(err, "decode pre shared key")
|
||||||
}
|
}
|
||||||
option.PreSharedKey = hex.EncodeToString(bytes)
|
preSharedKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
ipcConf += "\npublic_key=" + peerPublicKey
|
||||||
|
ipcConf += "\nendpoint=" + connectAddr.String()
|
||||||
|
if preSharedKey != "" {
|
||||||
|
ipcConf += "\npreshared_key=" + preSharedKey
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
localPrefixes, err = option.Prefixes()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var has4, has6 bool
|
||||||
|
for _, address := range localPrefixes {
|
||||||
|
if address.Addr().Is4() {
|
||||||
|
has4 = true
|
||||||
|
} else {
|
||||||
|
has6 = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if has4 {
|
||||||
|
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
||||||
|
}
|
||||||
|
if has6 {
|
||||||
|
ipcConf += "\nallowed_ip=::/0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outbound.option = option
|
|
||||||
|
|
||||||
|
if option.PersistentKeepalive != 0 {
|
||||||
|
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
||||||
|
}
|
||||||
mtu := option.MTU
|
mtu := option.MTU
|
||||||
if mtu == 0 {
|
if mtu == 0 {
|
||||||
mtu = 1408
|
mtu = 1408
|
||||||
}
|
}
|
||||||
if len(outbound.localPrefixes) == 0 {
|
if len(localPrefixes) == 0 {
|
||||||
return nil, E.New("missing local address")
|
return nil, E.New("missing local address")
|
||||||
}
|
}
|
||||||
outbound.tunDevice, err = wireguard.NewStackDevice(outbound.localPrefixes, uint32(mtu))
|
var err error
|
||||||
|
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create WireGuard device")
|
return nil, E.Cause(err, "create WireGuard device")
|
||||||
}
|
}
|
||||||
logger := &device.Logger{
|
outbound.device = device.NewDevice(context.Background(), outbound.tunDevice, outbound.bind, &device.Logger{
|
||||||
Verbosef: func(format string, args ...interface{}) {
|
Verbosef: func(format string, args ...interface{}) {
|
||||||
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
||||||
},
|
},
|
||||||
Errorf: func(format string, args ...interface{}) {
|
Errorf: func(format string, args ...interface{}) {
|
||||||
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
||||||
},
|
},
|
||||||
|
}, option.Workers)
|
||||||
|
if debug.Enabled {
|
||||||
|
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", option.Name, ipcConf))
|
||||||
}
|
}
|
||||||
if option.AmneziaWGOption != nil {
|
err = outbound.device.IpcSet(ipcConf)
|
||||||
outbound.bind.SetParseReserved(false) // AmneziaWG don't need parse reserved
|
if err != nil {
|
||||||
outbound.device = amnezia.NewDevice(outbound.tunDevice, outbound.bind, logger, option.Workers)
|
return nil, E.Cause(err, "setup wireguard")
|
||||||
} else {
|
|
||||||
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, logger, option.Workers)
|
|
||||||
}
|
}
|
||||||
|
//err = outbound.tunDevice.Start()
|
||||||
|
|
||||||
var has6 bool
|
var has6 bool
|
||||||
for _, address := range outbound.localPrefixes {
|
for _, address := range localPrefixes {
|
||||||
if !address.Addr().Unmap().Is4() {
|
if !address.Addr().Unmap().Is4() {
|
||||||
has6 = true
|
has6 = true
|
||||||
break
|
break
|
||||||
@@ -305,204 +314,22 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
return outbound, nil
|
return outbound, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) resolve(ctx context.Context, address M.Socksaddr) (netip.AddrPort, error) {
|
|
||||||
if address.Addr.IsValid() {
|
|
||||||
return address.AddrPort(), nil
|
|
||||||
}
|
|
||||||
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", address.String(), w.prefer)
|
|
||||||
if err != nil {
|
|
||||||
return netip.AddrPort{}, err
|
|
||||||
}
|
|
||||||
// net.ResolveUDPAddr maybe return 4in6 address, so unmap at here
|
|
||||||
addrPort := udpAddr.AddrPort()
|
|
||||||
return netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port()), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WireGuard) init(ctx context.Context) error {
|
|
||||||
err := w.init0(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.updateServerAddr(ctx)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WireGuard) init0(ctx context.Context) error {
|
|
||||||
if w.initOk.Load() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
w.initMutex.Lock()
|
|
||||||
defer w.initMutex.Unlock()
|
|
||||||
// double check like sync.Once
|
|
||||||
if w.initOk.Load() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if w.initErr != nil {
|
|
||||||
return w.initErr
|
|
||||||
}
|
|
||||||
|
|
||||||
w.bind.ResetReservedForEndpoint()
|
|
||||||
w.serverAddrMap = make(map[M.Socksaddr]netip.AddrPort)
|
|
||||||
ipcConf, err := w.genIpcConf(ctx, false)
|
|
||||||
if err != nil {
|
|
||||||
// !!! do not set initErr here !!!
|
|
||||||
// let us can retry domain resolve in next time
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if debug.Enabled {
|
|
||||||
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", w.option.Name, ipcConf))
|
|
||||||
}
|
|
||||||
err = w.device.IpcSet(ipcConf)
|
|
||||||
if err != nil {
|
|
||||||
w.initErr = E.Cause(err, "setup wireguard")
|
|
||||||
return w.initErr
|
|
||||||
}
|
|
||||||
w.serverAddrTime.Store(time.Now())
|
|
||||||
|
|
||||||
err = w.tunDevice.Start()
|
|
||||||
if err != nil {
|
|
||||||
w.initErr = err
|
|
||||||
return w.initErr
|
|
||||||
}
|
|
||||||
|
|
||||||
w.initOk.Store(true)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WireGuard) updateServerAddr(ctx context.Context) {
|
|
||||||
if w.option.RefreshServerIPInterval != 0 && time.Since(w.serverAddrTime.Load()) > time.Second*time.Duration(w.option.RefreshServerIPInterval) {
|
|
||||||
if w.serverAddrMutex.TryLock() {
|
|
||||||
defer w.serverAddrMutex.Unlock()
|
|
||||||
ipcConf, err := w.genIpcConf(ctx, true)
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("[WG](%s)UpdateServerAddr failed to generate wireguard ipc conf: %s", w.option.Name, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = w.device.IpcSet(ipcConf)
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("[WG](%s)UpdateServerAddr failed to update wireguard ipc conf: %s", w.option.Name, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.serverAddrTime.Store(time.Now())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WireGuard) genIpcConf(ctx context.Context, updateOnly bool) (string, error) {
|
|
||||||
ipcConf := ""
|
|
||||||
if !updateOnly {
|
|
||||||
ipcConf += "private_key=" + w.option.PrivateKey + "\n"
|
|
||||||
if w.option.AmneziaWGOption != nil {
|
|
||||||
ipcConf += "jc=" + strconv.Itoa(w.option.AmneziaWGOption.JC) + "\n"
|
|
||||||
ipcConf += "jmin=" + strconv.Itoa(w.option.AmneziaWGOption.JMin) + "\n"
|
|
||||||
ipcConf += "jmax=" + strconv.Itoa(w.option.AmneziaWGOption.JMax) + "\n"
|
|
||||||
ipcConf += "s1=" + strconv.Itoa(w.option.AmneziaWGOption.S1) + "\n"
|
|
||||||
ipcConf += "s2=" + strconv.Itoa(w.option.AmneziaWGOption.S2) + "\n"
|
|
||||||
ipcConf += "h1=" + strconv.FormatUint(uint64(w.option.AmneziaWGOption.H1), 10) + "\n"
|
|
||||||
ipcConf += "h2=" + strconv.FormatUint(uint64(w.option.AmneziaWGOption.H2), 10) + "\n"
|
|
||||||
ipcConf += "h3=" + strconv.FormatUint(uint64(w.option.AmneziaWGOption.H3), 10) + "\n"
|
|
||||||
ipcConf += "h4=" + strconv.FormatUint(uint64(w.option.AmneziaWGOption.H4), 10) + "\n"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(w.option.Peers) > 0 {
|
|
||||||
for i, peer := range w.option.Peers {
|
|
||||||
peerAddr := peer.Addr()
|
|
||||||
destination, err := w.resolve(ctx, peerAddr)
|
|
||||||
if err != nil {
|
|
||||||
return "", E.Cause(err, "resolve endpoint domain for peer ", i)
|
|
||||||
}
|
|
||||||
if w.serverAddrMap[peerAddr] != destination {
|
|
||||||
w.serverAddrMap[peerAddr] = destination
|
|
||||||
} else if updateOnly {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(w.option.Peers) == 1 { // must call SetConnectAddr if isConnect == true
|
|
||||||
w.bind.SetConnectAddr(destination)
|
|
||||||
}
|
|
||||||
ipcConf += "public_key=" + peer.PublicKey + "\n"
|
|
||||||
if updateOnly {
|
|
||||||
ipcConf += "update_only=true\n"
|
|
||||||
}
|
|
||||||
ipcConf += "endpoint=" + destination.String() + "\n"
|
|
||||||
if len(peer.Reserved) > 0 {
|
|
||||||
var reserved [3]uint8
|
|
||||||
copy(reserved[:], w.option.Reserved)
|
|
||||||
w.bind.SetReservedForEndpoint(destination, reserved)
|
|
||||||
}
|
|
||||||
if updateOnly {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if peer.PreSharedKey != "" {
|
|
||||||
ipcConf += "preshared_key=" + peer.PreSharedKey + "\n"
|
|
||||||
}
|
|
||||||
for _, allowedIP := range peer.AllowedIPs {
|
|
||||||
ipcConf += "allowed_ip=" + allowedIP + "\n"
|
|
||||||
}
|
|
||||||
if w.option.PersistentKeepalive != 0 {
|
|
||||||
ipcConf += fmt.Sprintf("persistent_keepalive_interval=%d\n", w.option.PersistentKeepalive)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
destination, err := w.resolve(ctx, w.connectAddr)
|
|
||||||
if err != nil {
|
|
||||||
return "", E.Cause(err, "resolve endpoint domain")
|
|
||||||
}
|
|
||||||
if w.serverAddrMap[w.connectAddr] != destination {
|
|
||||||
w.serverAddrMap[w.connectAddr] = destination
|
|
||||||
} else if updateOnly {
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
w.bind.SetConnectAddr(destination) // must call SetConnectAddr if isConnect == true
|
|
||||||
ipcConf += "public_key=" + w.option.PublicKey + "\n"
|
|
||||||
if updateOnly {
|
|
||||||
ipcConf += "update_only=true\n"
|
|
||||||
}
|
|
||||||
ipcConf += "endpoint=" + destination.String() + "\n"
|
|
||||||
if updateOnly {
|
|
||||||
return ipcConf, nil
|
|
||||||
}
|
|
||||||
if w.option.PreSharedKey != "" {
|
|
||||||
ipcConf += "preshared_key=" + w.option.PreSharedKey + "\n"
|
|
||||||
}
|
|
||||||
var has4, has6 bool
|
|
||||||
for _, address := range w.localPrefixes {
|
|
||||||
if address.Addr().Is4() {
|
|
||||||
has4 = true
|
|
||||||
} else {
|
|
||||||
has6 = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if has4 {
|
|
||||||
ipcConf += "allowed_ip=0.0.0.0/0\n"
|
|
||||||
}
|
|
||||||
if has6 {
|
|
||||||
ipcConf += "allowed_ip=::/0\n"
|
|
||||||
}
|
|
||||||
|
|
||||||
if w.option.PersistentKeepalive != 0 {
|
|
||||||
ipcConf += fmt.Sprintf("persistent_keepalive_interval=%d\n", w.option.PersistentKeepalive)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ipcConf, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeWireGuard(w *WireGuard) {
|
func closeWireGuard(w *WireGuard) {
|
||||||
if w.device != nil {
|
if w.device != nil {
|
||||||
w.device.Close()
|
w.device.Close()
|
||||||
}
|
}
|
||||||
if w.closeCh != nil {
|
_ = common.Close(w.tunDevice)
|
||||||
close(w.closeCh)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
options := w.Base.DialOptions(opts...)
|
options := w.Base.DialOptions(opts...)
|
||||||
w.dialer.SetDialer(dialer.NewDialer(options...))
|
w.dialer.SetDialer(dialer.NewDialer(options...))
|
||||||
var conn net.Conn
|
var conn net.Conn
|
||||||
if err = w.init(ctx); err != nil {
|
w.startOnce.Do(func() {
|
||||||
return nil, err
|
w.startErr = w.tunDevice.Start()
|
||||||
|
})
|
||||||
|
if w.startErr != nil {
|
||||||
|
return nil, w.startErr
|
||||||
}
|
}
|
||||||
if !metadata.Resolved() || w.resolver != nil {
|
if !metadata.Resolved() || w.resolver != nil {
|
||||||
r := resolver.DefaultResolver
|
r := resolver.DefaultResolver
|
||||||
@@ -530,7 +357,13 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
|||||||
options := w.Base.DialOptions(opts...)
|
options := w.Base.DialOptions(opts...)
|
||||||
w.dialer.SetDialer(dialer.NewDialer(options...))
|
w.dialer.SetDialer(dialer.NewDialer(options...))
|
||||||
var pc net.PacketConn
|
var pc net.PacketConn
|
||||||
if err = w.init(ctx); err != nil {
|
w.startOnce.Do(func() {
|
||||||
|
w.startErr = w.tunDevice.Start()
|
||||||
|
})
|
||||||
|
if w.startErr != nil {
|
||||||
|
return nil, w.startErr
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
||||||
@@ -611,11 +444,18 @@ func (r *refProxyAdapter) SupportUDP() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *refProxyAdapter) ProxyInfo() C.ProxyInfo {
|
func (r *refProxyAdapter) SupportXUDP() bool {
|
||||||
if r.proxyAdapter != nil {
|
if r.proxyAdapter != nil {
|
||||||
return r.proxyAdapter.ProxyInfo()
|
return r.proxyAdapter.SupportXUDP()
|
||||||
}
|
}
|
||||||
return C.ProxyInfo{}
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) SupportTFO() bool {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.SupportTFO()
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *refProxyAdapter) MarshalJSON() ([]byte, error) {
|
func (r *refProxyAdapter) MarshalJSON() ([]byte, error) {
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
//go:build with_gvisor
|
|
||||||
|
|
||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestWireGuardGC(t *testing.T) {
|
|
||||||
option := WireGuardOption{}
|
|
||||||
option.Server = "162.159.192.1"
|
|
||||||
option.Port = 2408
|
|
||||||
option.PrivateKey = "iOx7749AdqH3IqluG7+0YbGKd0m1mcEXAfGRzpy9rG8="
|
|
||||||
option.PublicKey = "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo="
|
|
||||||
option.Ip = "172.16.0.2"
|
|
||||||
option.Ipv6 = "2606:4700:110:8d29:be92:3a6a:f4:c437"
|
|
||||||
option.Reserved = []uint8{51, 69, 125}
|
|
||||||
wg, err := NewWireGuard(option)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
closeCh := make(chan struct{})
|
|
||||||
wg.closeCh = closeCh
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
|
||||||
defer cancel()
|
|
||||||
err = wg.init(ctx)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// must do a small sleep before test GC
|
|
||||||
// because it maybe deadlocks if w.device.Close call too fast after w.device.Start
|
|
||||||
time.Sleep(10 * time.Millisecond)
|
|
||||||
wg = nil
|
|
||||||
runtime.GC()
|
|
||||||
select {
|
|
||||||
case <-closeCh:
|
|
||||||
return
|
|
||||||
case <-ctx.Done():
|
|
||||||
t.Error("timeout not GC")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -21,8 +21,6 @@ type Fallback struct {
|
|||||||
testUrl string
|
testUrl string
|
||||||
selected string
|
selected string
|
||||||
expectedStatus string
|
expectedStatus string
|
||||||
Hidden bool
|
|
||||||
Icon string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@@ -91,9 +89,6 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": f.testUrl,
|
"testUrl": f.testUrl,
|
||||||
"expectedStatus": f.expectedStatus,
|
"expectedStatus": f.expectedStatus,
|
||||||
"fixed": f.selected,
|
|
||||||
"hidden": f.Hidden,
|
|
||||||
"icon": f.Icon,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +136,7 @@ func (f *Fallback) Set(name string) error {
|
|||||||
if !p.AliveForTestUrl(f.testUrl) {
|
if !p.AliveForTestUrl(f.testUrl) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
||||||
defer cancel()
|
defer cancel()
|
||||||
expectedStatus, _ := utils.NewUnsignedRanges[uint16](f.expectedStatus)
|
expectedStatus, _ := utils.NewIntRanges[uint16](f.expectedStatus)
|
||||||
_, _ = p.URLTest(ctx, f.testUrl, expectedStatus)
|
_, _ = p.URLTest(ctx, f.testUrl, expectedStatus)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -164,14 +159,10 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
option.TestTimeout,
|
|
||||||
option.MaxFailedTimes,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
testUrl: option.URL,
|
||||||
expectedStatus: option.ExpectedStatus,
|
expectedStatus: option.ExpectedStatus,
|
||||||
Hidden: option.Hidden,
|
|
||||||
Icon: option.Icon,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,24 +31,20 @@ type GroupBase struct {
|
|||||||
failedTesting atomic.Bool
|
failedTesting atomic.Bool
|
||||||
proxies [][]C.Proxy
|
proxies [][]C.Proxy
|
||||||
versions []atomic.Uint32
|
versions []atomic.Uint32
|
||||||
TestTimeout int
|
|
||||||
maxFailedTimes int
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type GroupBaseOption struct {
|
type GroupBaseOption struct {
|
||||||
outbound.BaseOption
|
outbound.BaseOption
|
||||||
filter string
|
filter string
|
||||||
excludeFilter string
|
excludeFilter string
|
||||||
excludeType string
|
excludeType string
|
||||||
TestTimeout int
|
providers []provider.ProxyProvider
|
||||||
maxFailedTimes int
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
var excludeFilterReg *regexp2.Regexp
|
var excludeFilterReg *regexp2.Regexp
|
||||||
if opt.excludeFilter != "" {
|
if opt.excludeFilter != "" {
|
||||||
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, regexp2.None)
|
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
||||||
}
|
}
|
||||||
var excludeTypeArray []string
|
var excludeTypeArray []string
|
||||||
if opt.excludeType != "" {
|
if opt.excludeType != "" {
|
||||||
@@ -58,7 +54,7 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
if opt.filter != "" {
|
if opt.filter != "" {
|
||||||
for _, filter := range strings.Split(opt.filter, "`") {
|
for _, filter := range strings.Split(opt.filter, "`") {
|
||||||
filterReg := regexp2.MustCompile(filter, regexp2.None)
|
filterReg := regexp2.MustCompile(filter, 0)
|
||||||
filterRegs = append(filterRegs, filterReg)
|
filterRegs = append(filterRegs, filterReg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,15 +66,6 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
excludeTypeArray: excludeTypeArray,
|
excludeTypeArray: excludeTypeArray,
|
||||||
providers: opt.providers,
|
providers: opt.providers,
|
||||||
failedTesting: atomic.NewBool(false),
|
failedTesting: atomic.NewBool(false),
|
||||||
TestTimeout: opt.TestTimeout,
|
|
||||||
maxFailedTimes: opt.maxFailedTimes,
|
|
||||||
}
|
|
||||||
|
|
||||||
if gb.TestTimeout == 0 {
|
|
||||||
gb.TestTimeout = 5000
|
|
||||||
}
|
|
||||||
if gb.maxFailedTimes == 0 {
|
|
||||||
gb.maxFailedTimes = 5
|
|
||||||
}
|
}
|
||||||
|
|
||||||
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
||||||
@@ -126,7 +113,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
for _, filterReg := range gb.filterRegs {
|
for _, filterReg := range gb.filterRegs {
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := filterReg.MatchString(name); mat {
|
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
proxiesSet[name] = struct{}{}
|
proxiesSet[name] = struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -150,7 +137,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
for _, filterReg := range gb.filterRegs {
|
for _, filterReg := range gb.filterRegs {
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := filterReg.MatchString(name); mat {
|
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
proxiesSet[name] = struct{}{}
|
proxiesSet[name] = struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -191,7 +178,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
var newProxies []C.Proxy
|
var newProxies []C.Proxy
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := gb.excludeFilterReg.MatchString(name); mat {
|
if mat, _ := gb.excludeFilterReg.FindStringMatch(name); mat != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -253,13 +240,13 @@ func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
|||||||
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
||||||
gb.failedTime = time.Now()
|
gb.failedTime = time.Now()
|
||||||
} else {
|
} else {
|
||||||
if time.Since(gb.failedTime) > time.Duration(gb.TestTimeout)*time.Millisecond {
|
if time.Since(gb.failedTime) > gb.failedTimeoutInterval() {
|
||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
if gb.failedTimes >= gb.maxFailedTimes {
|
if gb.failedTimes >= gb.maxFailedTimes() {
|
||||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||||
gb.healthCheck()
|
gb.healthCheck()
|
||||||
}
|
}
|
||||||
@@ -288,8 +275,20 @@ func (gb *GroupBase) healthCheck() {
|
|||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) failedIntervalTime() int64 {
|
||||||
|
return 5 * time.Second.Milliseconds()
|
||||||
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) onDialSuccess() {
|
func (gb *GroupBase) onDialSuccess() {
|
||||||
if !gb.failedTesting.Load() {
|
if !gb.failedTesting.Load() {
|
||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) maxFailedTimes() int {
|
||||||
|
return 5
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) failedTimeoutInterval() time.Duration {
|
||||||
|
return 5 * time.Second
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,8 +29,6 @@ type LoadBalance struct {
|
|||||||
strategyFn strategyFn
|
strategyFn strategyFn
|
||||||
testUrl string
|
testUrl string
|
||||||
expectedStatus string
|
expectedStatus string
|
||||||
Hidden bool
|
|
||||||
Icon string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var errStrategy = errors.New("unsupported strategy")
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
@@ -152,6 +150,7 @@ func strategyRoundRobin(url string) strategyFn {
|
|||||||
for ; i < length; i++ {
|
for ; i < length; i++ {
|
||||||
id := (idx + i) % length
|
id := (idx + i) % length
|
||||||
proxy := proxies[id]
|
proxy := proxies[id]
|
||||||
|
// if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(url) {
|
if proxy.AliveForTestUrl(url) {
|
||||||
i++
|
i++
|
||||||
return proxy
|
return proxy
|
||||||
@@ -170,6 +169,7 @@ func strategyConsistentHashing(url string) strategyFn {
|
|||||||
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
idx := jumpHash(key, buckets)
|
idx := jumpHash(key, buckets)
|
||||||
proxy := proxies[idx]
|
proxy := proxies[idx]
|
||||||
|
// if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(url) {
|
if proxy.AliveForTestUrl(url) {
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
@@ -177,6 +177,7 @@ func strategyConsistentHashing(url string) strategyFn {
|
|||||||
|
|
||||||
// when availability is poor, traverse the entire list to get the available nodes
|
// when availability is poor, traverse the entire list to get the available nodes
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
|
// if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(url) {
|
if proxy.AliveForTestUrl(url) {
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
@@ -203,8 +204,10 @@ func strategyStickySessions(url string) strategyFn {
|
|||||||
nowIdx := idx
|
nowIdx := idx
|
||||||
for i := 1; i < maxRetry; i++ {
|
for i := 1; i < maxRetry; i++ {
|
||||||
proxy := proxies[nowIdx]
|
proxy := proxies[nowIdx]
|
||||||
|
// if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(url) {
|
if proxy.AliveForTestUrl(url) {
|
||||||
if !has || nowIdx != idx {
|
if nowIdx != idx {
|
||||||
|
lruCache.Delete(key)
|
||||||
lruCache.Set(key, nowIdx)
|
lruCache.Set(key, nowIdx)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,6 +217,7 @@ func strategyStickySessions(url string) strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lruCache.Delete(key)
|
||||||
lruCache.Set(key, 0)
|
lruCache.Set(key, 0)
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
@@ -236,8 +240,6 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
|||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": lb.testUrl,
|
"testUrl": lb.testUrl,
|
||||||
"expectedStatus": lb.expectedStatus,
|
"expectedStatus": lb.expectedStatus,
|
||||||
"hidden": lb.Hidden,
|
|
||||||
"icon": lb.Icon,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,15 +266,11 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
option.TestTimeout,
|
|
||||||
option.MaxFailedTimes,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
testUrl: option.URL,
|
||||||
expectedStatus: option.ExpectedStatus,
|
expectedStatus: option.ExpectedStatus,
|
||||||
Hidden: option.Hidden,
|
|
||||||
Icon: option.Icon,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/adapter/provider"
|
"github.com/metacubex/mihomo/adapter/provider"
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
@@ -30,22 +28,16 @@ type GroupCommonOption struct {
|
|||||||
Use []string `group:"use,omitempty"`
|
Use []string `group:"use,omitempty"`
|
||||||
URL string `group:"url,omitempty"`
|
URL string `group:"url,omitempty"`
|
||||||
Interval int `group:"interval,omitempty"`
|
Interval int `group:"interval,omitempty"`
|
||||||
TestTimeout int `group:"timeout,omitempty"`
|
|
||||||
MaxFailedTimes int `group:"max-failed-times,omitempty"`
|
|
||||||
Lazy bool `group:"lazy,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||||
ExcludeType string `group:"exclude-type,omitempty"`
|
ExcludeType string `group:"exclude-type,omitempty"`
|
||||||
ExpectedStatus string `group:"expected-status,omitempty"`
|
ExpectedStatus string `group:"expected-status,omitempty"`
|
||||||
IncludeAll bool `group:"include-all,omitempty"`
|
|
||||||
IncludeAllProxies bool `group:"include-all-proxies,omitempty"`
|
|
||||||
IncludeAllProviders bool `group:"include-all-providers,omitempty"`
|
IncludeAllProviders bool `group:"include-all-providers,omitempty"`
|
||||||
Hidden bool `group:"hidden,omitempty"`
|
|
||||||
Icon string `group:"icon,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
groupOption := &GroupCommonOption{
|
groupOption := &GroupCommonOption{
|
||||||
@@ -63,41 +55,22 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
|
|
||||||
providers := []types.ProxyProvider{}
|
providers := []types.ProxyProvider{}
|
||||||
|
|
||||||
if groupOption.IncludeAll {
|
var GroupUse []string
|
||||||
groupOption.IncludeAllProviders = true
|
visited := make(map[string]bool)
|
||||||
groupOption.IncludeAllProxies = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if groupOption.IncludeAllProviders {
|
if groupOption.IncludeAllProviders {
|
||||||
groupOption.Use = AllProviders
|
for name := range provider.ProxyProviderName {
|
||||||
}
|
GroupUse = append(GroupUse, name)
|
||||||
if groupOption.IncludeAllProxies {
|
visited[name] = true
|
||||||
if groupOption.Filter != "" {
|
|
||||||
var filterRegs []*regexp2.Regexp
|
|
||||||
for _, filter := range strings.Split(groupOption.Filter, "`") {
|
|
||||||
filterReg := regexp2.MustCompile(filter, regexp2.None)
|
|
||||||
filterRegs = append(filterRegs, filterReg)
|
|
||||||
}
|
|
||||||
for _, p := range AllProxies {
|
|
||||||
for _, filterReg := range filterRegs {
|
|
||||||
if mat, _ := filterReg.MatchString(p); mat {
|
|
||||||
groupOption.Proxies = append(groupOption.Proxies, p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
groupOption.Proxies = append(groupOption.Proxies, AllProxies...)
|
|
||||||
}
|
|
||||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
|
||||||
groupOption.Proxies = []string{"COMPATIBLE"}
|
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
GroupUse = groupOption.Use
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
if len(groupOption.Proxies) == 0 && len(GroupUse) == 0 {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedStatus, err := utils.NewUnsignedRanges[uint16](groupOption.ExpectedStatus)
|
expectedStatus, err := utils.NewIntRanges[uint16](groupOption.ExpectedStatus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
@@ -107,29 +80,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
status = "*"
|
status = "*"
|
||||||
}
|
}
|
||||||
groupOption.ExpectedStatus = status
|
groupOption.ExpectedStatus = status
|
||||||
|
testUrl := groupOption.URL
|
||||||
if len(groupOption.Use) != 0 {
|
|
||||||
PDs, err := getProviders(providersMap, groupOption.Use)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// if test URL is empty, use the first health check URL of providers
|
|
||||||
if groupOption.URL == "" {
|
|
||||||
for _, pd := range PDs {
|
|
||||||
if pd.HealthCheckURL() != "" {
|
|
||||||
groupOption.URL = pd.HealthCheckURL()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if groupOption.URL == "" {
|
|
||||||
groupOption.URL = C.DefaultTestURL
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
addTestUrlToProviders(PDs, groupOption.URL, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
|
||||||
}
|
|
||||||
providers = append(providers, PDs...)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(groupOption.Proxies) != 0 {
|
if len(groupOption.Proxies) != 0 {
|
||||||
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
@@ -141,28 +92,43 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
||||||
}
|
}
|
||||||
|
|
||||||
if groupOption.URL == "" {
|
// select don't need health check
|
||||||
groupOption.URL = C.DefaultTestURL
|
|
||||||
}
|
|
||||||
|
|
||||||
// select don't need auto health check
|
|
||||||
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
||||||
|
if groupOption.URL == "" {
|
||||||
|
groupOption.URL = C.DefaultTestURL
|
||||||
|
testUrl = groupOption.URL
|
||||||
|
}
|
||||||
|
|
||||||
if groupOption.Interval == 0 {
|
if groupOption.Interval == 0 {
|
||||||
groupOption.Interval = 300
|
groupOption.Interval = 300
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.TestTimeout), uint(groupOption.Interval), groupOption.Lazy, expectedStatus)
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), true, expectedStatus)
|
||||||
|
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
providers = append([]types.ProxyProvider{pd}, providers...)
|
providers = append(providers, pd)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(GroupUse) != 0 {
|
||||||
|
list, err := getProviders(providersMap, GroupUse)
|
||||||
|
if err != nil {
|
||||||
|
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 = ""
|
||||||
|
}
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
switch groupOption.Type {
|
switch groupOption.Type {
|
||||||
case "url-test":
|
case "url-test":
|
||||||
|
|||||||
@@ -3,19 +3,15 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
"github.com/metacubex/mihomo/log"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Relay struct {
|
type Relay struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
Hidden bool
|
|
||||||
Icon string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@@ -110,10 +106,8 @@ func (r *Relay) MarshalJSON() ([]byte, error) {
|
|||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": r.Type().String(),
|
"type": r.Type().String(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"hidden": r.Hidden,
|
|
||||||
"icon": r.Icon,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,7 +144,6 @@ func (r *Relay) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
||||||
log.Warnln("The group [%s] with relay type is deprecated, please using dialer-proxy instead", option.Name)
|
|
||||||
return &Relay{
|
return &Relay{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
outbound.BaseOption{
|
outbound.BaseOption{
|
||||||
@@ -162,11 +155,7 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
5000,
|
|
||||||
5,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
Hidden: option.Hidden,
|
|
||||||
Icon: option.Icon,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ type Selector struct {
|
|||||||
*GroupBase
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
selected string
|
selected string
|
||||||
Hidden bool
|
|
||||||
Icon string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@@ -59,11 +57,9 @@ func (s *Selector) MarshalJSON() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": s.Type().String(),
|
"type": s.Type().String(),
|
||||||
"now": s.Now(),
|
"now": s.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"hidden": s.Hidden,
|
|
||||||
"icon": s.Icon,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,13 +110,9 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
option.TestTimeout,
|
|
||||||
option.MaxFailedTimes,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
Hidden: option.Hidden,
|
|
||||||
Icon: option.Icon,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,15 +4,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/common/callback"
|
"github.com/metacubex/mihomo/common/callback"
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/metacubex/mihomo/common/singledo"
|
"github.com/metacubex/mihomo/common/singledo"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
@@ -33,8 +30,6 @@ type URLTest struct {
|
|||||||
expectedStatus string
|
expectedStatus string
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
Hidden bool
|
|
||||||
Icon string
|
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
fastSingle *singledo.Single[C.Proxy]
|
fastSingle *singledo.Single[C.Proxy]
|
||||||
}
|
}
|
||||||
@@ -118,7 +113,7 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
|
|
||||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
minDelay := fast.LastDelayForTestUrl(u.testUrl)
|
min := fast.LastDelayForTestUrl(u.testUrl)
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
|
|
||||||
for _, proxy := range proxies[1:] {
|
for _, proxy := range proxies[1:] {
|
||||||
@@ -131,9 +126,9 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
||||||
if delay < minDelay {
|
if delay < min {
|
||||||
fast = proxy
|
fast = proxy
|
||||||
minDelay = delay
|
min = delay
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -175,40 +170,9 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": u.testUrl,
|
"testUrl": u.testUrl,
|
||||||
"expectedStatus": u.expectedStatus,
|
"expectedStatus": u.expectedStatus,
|
||||||
"fixed": u.selected,
|
|
||||||
"hidden": u.Hidden,
|
|
||||||
"icon": u.Icon,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) 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{}
|
|
||||||
proxies := u.GetProxies(false)
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
proxy := proxy
|
|
||||||
wg.Add(1)
|
|
||||||
go func() {
|
|
||||||
delay, err := proxy.URLTest(ctx, u.testUrl, expectedStatus)
|
|
||||||
if err == nil {
|
|
||||||
lock.Lock()
|
|
||||||
mp[proxy.Name()] = delay
|
|
||||||
lock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Done()
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
if len(mp) == 0 {
|
|
||||||
return mp, fmt.Errorf("get delay: all proxies timeout")
|
|
||||||
} else {
|
|
||||||
return mp, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseURLTestOption(config map[string]any) []urlTestOption {
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
opts := []urlTestOption{}
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
@@ -235,16 +199,12 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
option.TestTimeout,
|
|
||||||
option.MaxFailedTimes,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
testUrl: option.URL,
|
||||||
expectedStatus: option.ExpectedStatus,
|
expectedStatus: option.ExpectedStatus,
|
||||||
Hidden: option.Hidden,
|
|
||||||
Icon: option.Icon,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
|||||||
@@ -4,7 +4,3 @@ type SelectAble interface {
|
|||||||
Set(string) error
|
Set(string) error
|
||||||
ForceSet(name string)
|
ForceSet(name string)
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ SelectAble = (*Fallback)(nil)
|
|
||||||
var _ SelectAble = (*URLTest)(nil)
|
|
||||||
var _ SelectAble = (*Selector)(nil)
|
|
||||||
|
|||||||
@@ -120,13 +120,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewDirectWithOption(*directOption)
|
proxy = outbound.NewDirectWithOption(*directOption)
|
||||||
case "dns":
|
|
||||||
dnsOptions := &outbound.DnsOption{}
|
|
||||||
err = decoder.Decode(mapping, dnsOptions)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy = outbound.NewDnsWithOption(*dnsOptions)
|
|
||||||
case "reject":
|
case "reject":
|
||||||
rejectOption := &outbound.RejectOption{}
|
rejectOption := &outbound.RejectOption{}
|
||||||
err = decoder.Decode(mapping, rejectOption)
|
err = decoder.Decode(mapping, rejectOption)
|
||||||
@@ -134,20 +127,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewRejectWithOption(*rejectOption)
|
proxy = outbound.NewRejectWithOption(*rejectOption)
|
||||||
case "ssh":
|
|
||||||
sshOption := &outbound.SshOption{}
|
|
||||||
err = decoder.Decode(mapping, sshOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewSsh(*sshOption)
|
|
||||||
case "mieru":
|
|
||||||
mieruOption := &outbound.MieruOption{}
|
|
||||||
err = decoder.Decode(mapping, mieruOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewMieru(*mieruOption)
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ import (
|
|||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultURLTestTimeout = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
type HealthCheckOption struct {
|
type HealthCheckOption struct {
|
||||||
URL string
|
URL string
|
||||||
Interval uint
|
Interval uint
|
||||||
@@ -27,8 +31,6 @@ type extraOption struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type HealthCheck struct {
|
type HealthCheck struct {
|
||||||
ctx context.Context
|
|
||||||
ctxCancel context.CancelFunc
|
|
||||||
url string
|
url string
|
||||||
extra map[string]*extraOption
|
extra map[string]*extraOption
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
@@ -38,8 +40,8 @@ type HealthCheck struct {
|
|||||||
lazy bool
|
lazy bool
|
||||||
expectedStatus utils.IntRanges[uint16]
|
expectedStatus utils.IntRanges[uint16]
|
||||||
lastTouch atomic.TypedValue[time.Time]
|
lastTouch atomic.TypedValue[time.Time]
|
||||||
|
done chan struct{}
|
||||||
singleDo *singledo.Single[struct{}]
|
singleDo *singledo.Single[struct{}]
|
||||||
timeout time.Duration
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
@@ -60,7 +62,7 @@ func (hc *HealthCheck) process() {
|
|||||||
} else {
|
} else {
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
log.Debugln("Skip once health check because we are lazy")
|
||||||
}
|
}
|
||||||
case <-hc.ctx.Done():
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
hc.stop()
|
hc.stop()
|
||||||
return
|
return
|
||||||
@@ -147,7 +149,7 @@ func (hc *HealthCheck) check() {
|
|||||||
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
id := utils.NewUUIDV4().String()
|
id := utils.NewUUIDV4().String()
|
||||||
log.Debugln("Start New Health Checking {%s}", id)
|
log.Debugln("Start New Health Checking {%s}", id)
|
||||||
b, _ := batch.New[bool](hc.ctx, batch.WithConcurrencyNum[bool](10))
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
|
|
||||||
// execute default health check
|
// execute default health check
|
||||||
option := &extraOption{filters: nil, expectedStatus: hc.expectedStatus}
|
option := &extraOption{filters: nil, expectedStatus: hc.expectedStatus}
|
||||||
@@ -182,21 +184,21 @@ func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *ex
|
|||||||
filters = append(filters, filter)
|
filters = append(filters, filter)
|
||||||
}
|
}
|
||||||
|
|
||||||
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), regexp2.None)
|
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
// skip proxies that do not require health check
|
// skip proxies that do not require health check
|
||||||
if filterReg != nil {
|
if filterReg != nil {
|
||||||
if match, _ := filterReg.MatchString(proxy.Name()); !match {
|
if match, _ := filterReg.FindStringMatch(proxy.Name()); match == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
ctx, cancel := context.WithTimeout(hc.ctx, hc.timeout)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
log.Debugln("Health Checking, proxy: %s, url: %s, id: {%s}", p.Name(), url, uid)
|
log.Debugln("Health Checking, proxy: %s, url: %s, id: {%s}", p.Name(), url, uid)
|
||||||
_, _ = p.URLTest(ctx, url, expectedStatus)
|
_, _ = p.URLTest(ctx, url, expectedStatus)
|
||||||
@@ -207,29 +209,24 @@ func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *ex
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
func (hc *HealthCheck) close() {
|
||||||
hc.ctxCancel()
|
hc.done <- struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHealthCheck(proxies []C.Proxy, url string, timeout uint, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
||||||
if url == "" {
|
if len(url) == 0 {
|
||||||
expectedStatus = nil
|
|
||||||
interval = 0
|
interval = 0
|
||||||
|
expectedStatus = nil
|
||||||
|
url = C.DefaultTestURL
|
||||||
}
|
}
|
||||||
if timeout == 0 {
|
|
||||||
timeout = 5000
|
|
||||||
}
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
|
|
||||||
return &HealthCheck{
|
return &HealthCheck{
|
||||||
ctx: ctx,
|
|
||||||
ctxCancel: cancel,
|
|
||||||
proxies: proxies,
|
proxies: proxies,
|
||||||
url: url,
|
url: url,
|
||||||
timeout: time.Duration(timeout) * time.Millisecond,
|
|
||||||
extra: map[string]*extraOption{},
|
extra: map[string]*extraOption{},
|
||||||
interval: time.Duration(interval) * time.Second,
|
interval: time.Duration(interval) * time.Second,
|
||||||
lazy: lazy,
|
lazy: lazy,
|
||||||
expectedStatus: expectedStatus,
|
expectedStatus: expectedStatus,
|
||||||
|
done: make(chan struct{}, 1),
|
||||||
singleDo: singledo.NewSingle[struct{}](time.Second),
|
singleDo: singledo.NewSingle[struct{}](time.Second),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
@@ -10,9 +9,8 @@ import (
|
|||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/resource"
|
"github.com/metacubex/mihomo/component/resource"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/constant/features"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
types "github.com/metacubex/mihomo/constant/provider"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -24,53 +22,30 @@ type healthCheckSchema struct {
|
|||||||
Enable bool `provider:"enable"`
|
Enable bool `provider:"enable"`
|
||||||
URL string `provider:"url"`
|
URL string `provider:"url"`
|
||||||
Interval int `provider:"interval"`
|
Interval int `provider:"interval"`
|
||||||
TestTimeout int `provider:"timeout,omitempty"`
|
|
||||||
Lazy bool `provider:"lazy,omitempty"`
|
Lazy bool `provider:"lazy,omitempty"`
|
||||||
ExpectedStatus string `provider:"expected-status,omitempty"`
|
ExpectedStatus string `provider:"expected-status,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type OverrideProxyNameSchema struct {
|
|
||||||
// matching expression for regex replacement
|
|
||||||
Pattern *regexp2.Regexp `provider:"pattern"`
|
|
||||||
// the new content after regex matching
|
|
||||||
Target string `provider:"target"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ encoding.TextUnmarshaler = (*regexp2.Regexp)(nil) // ensure *regexp2.Regexp can decode direct by structure package
|
|
||||||
|
|
||||||
type OverrideSchema struct {
|
type OverrideSchema struct {
|
||||||
TFO *bool `provider:"tfo,omitempty"`
|
UDP *bool `provider:"udp,omitempty"`
|
||||||
MPTcp *bool `provider:"mptcp,omitempty"`
|
Up *string `provider:"up,omitempty"`
|
||||||
UDP *bool `provider:"udp,omitempty"`
|
Down *string `provider:"down,omitempty"`
|
||||||
UDPOverTCP *bool `provider:"udp-over-tcp,omitempty"`
|
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
||||||
Up *string `provider:"up,omitempty"`
|
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
||||||
Down *string `provider:"down,omitempty"`
|
|
||||||
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
|
||||||
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
|
||||||
Interface *string `provider:"interface-name,omitempty"`
|
|
||||||
RoutingMark *int `provider:"routing-mark,omitempty"`
|
|
||||||
IPVersion *string `provider:"ip-version,omitempty"`
|
|
||||||
AdditionalPrefix *string `provider:"additional-prefix,omitempty"`
|
|
||||||
AdditionalSuffix *string `provider:"additional-suffix,omitempty"`
|
|
||||||
|
|
||||||
ProxyName []OverrideProxyNameSchema `provider:"proxy-name,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path,omitempty"`
|
Path string `provider:"path,omitempty"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Proxy string `provider:"proxy,omitempty"`
|
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
ExcludeType string `provider:"exclude-type,omitempty"`
|
ExcludeType string `provider:"exclude-type,omitempty"`
|
||||||
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
||||||
SizeLimit int64 `provider:"size-limit,omitempty"`
|
|
||||||
|
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
Override OverrideSchema `provider:"override,omitempty"`
|
Override OverrideSchema `provider:"override,omitempty"`
|
||||||
Header map[string][]string `provider:"header,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
@@ -85,19 +60,16 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedStatus, err := utils.NewUnsignedRanges[uint16](schema.HealthCheck.ExpectedStatus)
|
expectedStatus, err := utils.NewIntRanges[uint16](schema.HealthCheck.ExpectedStatus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var hcInterval uint
|
var hcInterval uint
|
||||||
if schema.HealthCheck.Enable {
|
if schema.HealthCheck.Enable {
|
||||||
if schema.HealthCheck.Interval == 0 {
|
|
||||||
schema.HealthCheck.Interval = 300
|
|
||||||
}
|
|
||||||
hcInterval = uint(schema.HealthCheck.Interval)
|
hcInterval = uint(schema.HealthCheck.Interval)
|
||||||
}
|
}
|
||||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, uint(schema.HealthCheck.TestTimeout), hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
||||||
|
|
||||||
var vehicle types.Vehicle
|
var vehicle types.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
@@ -105,14 +77,16 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
path := C.Path.Resolve(schema.Path)
|
path := C.Path.Resolve(schema.Path)
|
||||||
vehicle = resource.NewFileVehicle(path)
|
vehicle = resource.NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
path := C.Path.GetPathByHash("proxies", schema.URL)
|
|
||||||
if schema.Path != "" {
|
if schema.Path != "" {
|
||||||
path = C.Path.Resolve(schema.Path)
|
path := C.Path.Resolve(schema.Path)
|
||||||
if !C.Path.IsSafePath(path) {
|
if !features.CMFA && !C.Path.IsSafePath(path) {
|
||||||
return nil, fmt.Errorf("%w: %s", errSubPath, 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)
|
||||||
}
|
}
|
||||||
vehicle = resource.NewHTTPVehicle(schema.URL, path, schema.Proxy, schema.Header, resource.DefaultHttpTimeout, schema.SizeLimit)
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
}
|
}
|
||||||
|
|||||||
36
adapter/provider/patch_android.go
Normal file
36
adapter/provider/patch_android.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
//go:build android && cmfa
|
||||||
|
|
||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
suspended bool
|
||||||
|
)
|
||||||
|
|
||||||
|
type UpdatableProvider interface {
|
||||||
|
UpdatedAt() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) UpdatedAt() time.Time {
|
||||||
|
return pp.Fetcher.UpdatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Close() error {
|
||||||
|
pp.healthCheck.close()
|
||||||
|
pp.Fetcher.Destroy()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Close() error {
|
||||||
|
cp.healthCheck.close()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Suspend(s bool) {
|
||||||
|
suspended = s
|
||||||
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -12,16 +13,19 @@ import (
|
|||||||
"github.com/metacubex/mihomo/adapter"
|
"github.com/metacubex/mihomo/adapter"
|
||||||
"github.com/metacubex/mihomo/common/convert"
|
"github.com/metacubex/mihomo/common/convert"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
||||||
"github.com/metacubex/mihomo/component/resource"
|
"github.com/metacubex/mihomo/component/resource"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
types "github.com/metacubex/mihomo/constant/provider"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
"github.com/metacubex/mihomo/tunnel/statistic"
|
"github.com/metacubex/mihomo/tunnel/statistic"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ProxyProviderName = make(map[string]struct{})
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ReservedName = "default"
|
ReservedName = "default"
|
||||||
)
|
)
|
||||||
@@ -44,14 +48,19 @@ type proxySetProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
expectedStatus := "*"
|
||||||
|
if pp.healthCheck.expectedStatus != nil {
|
||||||
|
expectedStatus = pp.healthCheck.expectedStatus.ToString()
|
||||||
|
}
|
||||||
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"name": pp.Name(),
|
"name": pp.Name(),
|
||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"testUrl": pp.healthCheck.url,
|
"testUrl": pp.healthCheck.url,
|
||||||
"expectedStatus": pp.healthCheck.expectedStatus.String(),
|
"expectedStatus": expectedStatus,
|
||||||
"updatedAt": pp.UpdatedAt(),
|
"updatedAt": pp.UpdatedAt,
|
||||||
"subscriptionInfo": pp.subscriptionInfo,
|
"subscriptionInfo": pp.subscriptionInfo,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -69,18 +78,20 @@ func (pp *proxySetProvider) HealthCheck() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Update() error {
|
func (pp *proxySetProvider) Update() error {
|
||||||
_, _, err := pp.Fetcher.Update()
|
elm, same, err := pp.Fetcher.Update()
|
||||||
|
if err == nil && !same {
|
||||||
|
pp.OnUpdate(elm)
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Initial() error {
|
func (pp *proxySetProvider) Initial() error {
|
||||||
_, err := pp.Fetcher.Initial()
|
elm, err := pp.Fetcher.Initial()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if subscriptionInfo := cachefile.Cache().GetSubscriptionInfo(pp.Name()); subscriptionInfo != "" {
|
pp.OnUpdate(elm)
|
||||||
pp.SetSubscriptionInfo(subscriptionInfo)
|
pp.getSubscriptionInfo()
|
||||||
}
|
|
||||||
pp.closeAllConnections()
|
pp.closeAllConnections()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -93,18 +104,10 @@ func (pp *proxySetProvider) Proxies() []C.Proxy {
|
|||||||
return pp.proxies
|
return pp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Count() int {
|
|
||||||
return len(pp.proxies)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) Touch() {
|
func (pp *proxySetProvider) Touch() {
|
||||||
pp.healthCheck.touch()
|
pp.healthCheck.touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) HealthCheckURL() string {
|
|
||||||
return pp.healthCheck.url
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
func (pp *proxySetProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
pp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
pp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||||
}
|
}
|
||||||
@@ -117,14 +120,38 @@ func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) SetSubscriptionInfo(userInfo string) {
|
func (pp *proxySetProvider) getSubscriptionInfo() {
|
||||||
pp.subscriptionInfo = NewSubscriptionInfo(userInfo)
|
if pp.VehicleType() != types.HTTP {
|
||||||
}
|
return
|
||||||
|
|
||||||
func (pp *proxySetProvider) SetProvider(provider types.ProxyProvider) {
|
|
||||||
if httpVehicle, ok := pp.Vehicle().(*resource.HTTPVehicle); ok {
|
|
||||||
httpVehicle.SetProvider(provider)
|
|
||||||
}
|
}
|
||||||
|
go func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
||||||
|
defer cancel()
|
||||||
|
resp, err := mihomoHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
|
http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
||||||
|
if userInfoStr == "" {
|
||||||
|
resp2, err := mihomoHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
|
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp2.Body.Close()
|
||||||
|
userInfoStr = strings.TrimSpace(resp2.Header.Get("subscription-userinfo"))
|
||||||
|
if userInfoStr == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pp.subscriptionInfo, err = NewSubscriptionInfo(userInfoStr)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[Provider] get subscription-userinfo: %e", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) closeAllConnections() {
|
func (pp *proxySetProvider) closeAllConnections() {
|
||||||
@@ -139,13 +166,13 @@ func (pp *proxySetProvider) closeAllConnections() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Close() error {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pp.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
return pp.Fetcher.Close()
|
_ = pd.Fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, regexp2.None)
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
}
|
}
|
||||||
@@ -156,7 +183,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
for _, filter := range strings.Split(filter, "`") {
|
for _, filter := range strings.Split(filter, "`") {
|
||||||
filterReg, err := regexp2.Compile(filter, regexp2.None)
|
filterReg, err := regexp2.Compile(filter, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
@@ -174,44 +201,37 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
|
|
||||||
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg, dialerProxy, override), proxiesOnUpdate(pd))
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg, dialerProxy, override), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
|
ProxyProviderName[name] = struct{}{}
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
if httpVehicle, ok := vehicle.(*resource.HTTPVehicle); ok {
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
httpVehicle.SetProvider(wrapper)
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(wrapper, (*ProxySetProvider).Close)
|
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *ProxySetProvider) Close() error {
|
|
||||||
runtime.SetFinalizer(pp, nil)
|
|
||||||
return pp.proxySetProvider.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) SetProvider(provider types.ProxyProvider) {
|
|
||||||
pp.proxySetProvider.SetProvider(provider)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CompatibleProvider for auto gc
|
// CompatibleProvider for auto gc
|
||||||
type CompatibleProvider struct {
|
type CompatibleProvider struct {
|
||||||
*compatibleProvider
|
*compatibleProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
type compatibleProvider struct {
|
type compatibleProvider struct {
|
||||||
name string
|
name string
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
subscriptionInfo *SubscriptionInfo
|
proxies []C.Proxy
|
||||||
proxies []C.Proxy
|
version uint32
|
||||||
version uint32
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
expectedStatus := "*"
|
||||||
|
if cp.healthCheck.expectedStatus != nil {
|
||||||
|
expectedStatus = cp.healthCheck.expectedStatus.ToString()
|
||||||
|
}
|
||||||
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"name": cp.Name(),
|
"name": cp.Name(),
|
||||||
"type": cp.Type().String(),
|
"type": cp.Type().String(),
|
||||||
"vehicleType": cp.VehicleType().String(),
|
"vehicleType": cp.VehicleType().String(),
|
||||||
"proxies": cp.Proxies(),
|
"proxies": cp.Proxies(),
|
||||||
"testUrl": cp.healthCheck.url,
|
"testUrl": cp.healthCheck.url,
|
||||||
"expectedStatus": cp.healthCheck.expectedStatus.String(),
|
"expectedStatus": expectedStatus,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,9 +252,6 @@ func (cp *compatibleProvider) Update() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Initial() error {
|
func (cp *compatibleProvider) Initial() error {
|
||||||
if cp.healthCheck.interval != 0 && cp.healthCheck.url != "" {
|
|
||||||
cp.HealthCheck()
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,29 +267,16 @@ func (cp *compatibleProvider) Proxies() []C.Proxy {
|
|||||||
return cp.proxies
|
return cp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Count() int {
|
|
||||||
return len(cp.proxies)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Touch() {
|
func (cp *compatibleProvider) Touch() {
|
||||||
cp.healthCheck.touch()
|
cp.healthCheck.touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) HealthCheckURL() string {
|
|
||||||
return cp.healthCheck.url
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
func (cp *compatibleProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
cp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
cp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Close() error {
|
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||||
cp.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) SetSubscriptionInfo(userInfo string) {
|
|
||||||
cp.subscriptionInfo = NewSubscriptionInfo(userInfo)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
||||||
@@ -291,19 +295,15 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
}
|
}
|
||||||
|
|
||||||
wrapper := &CompatibleProvider{pd}
|
wrapper := &CompatibleProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, (*CompatibleProvider).Close)
|
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *CompatibleProvider) Close() error {
|
|
||||||
runtime.SetFinalizer(cp, nil)
|
|
||||||
return cp.compatibleProvider.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
||||||
return func(elm []C.Proxy) {
|
return func(elm []C.Proxy) {
|
||||||
pd.setProxies(elm)
|
pd.setProxies(elm)
|
||||||
pd.version += 1
|
pd.version += 1
|
||||||
|
pd.getSubscriptionInfo()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -358,12 +358,12 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if len(excludeFilter) > 0 {
|
if len(excludeFilter) > 0 {
|
||||||
if mat, _ := excludeFilterReg.MatchString(name); mat {
|
if mat, _ := excludeFilterReg.FindStringMatch(name); mat != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(filter) > 0 {
|
if len(filter) > 0 {
|
||||||
if mat, _ := filterReg.MatchString(name); !mat {
|
if mat, _ := filterReg.FindStringMatch(name); mat == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -375,33 +375,20 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
mapping["dialer-proxy"] = dialerProxy
|
mapping["dialer-proxy"] = dialerProxy
|
||||||
}
|
}
|
||||||
|
|
||||||
val := reflect.ValueOf(override)
|
if override.UDP != nil {
|
||||||
for i := 0; i < val.NumField(); i++ {
|
mapping["udp"] = *override.UDP
|
||||||
field := val.Field(i)
|
}
|
||||||
if field.IsNil() {
|
if override.Up != nil {
|
||||||
continue
|
mapping["up"] = *override.Up
|
||||||
}
|
}
|
||||||
fieldName := strings.Split(val.Type().Field(i).Tag.Get("provider"), ",")[0]
|
if override.Down != nil {
|
||||||
switch fieldName {
|
mapping["down"] = *override.Down
|
||||||
case "additional-prefix":
|
}
|
||||||
name := mapping["name"].(string)
|
if override.DialerProxy != nil {
|
||||||
mapping["name"] = *field.Interface().(*string) + name
|
mapping["dialer-proxy"] = *override.DialerProxy
|
||||||
case "additional-suffix":
|
}
|
||||||
name := mapping["name"].(string)
|
if override.SkipCertVerify != nil {
|
||||||
mapping["name"] = name + *field.Interface().(*string)
|
mapping["skip-cert-verify"] = *override.SkipCertVerify
|
||||||
case "proxy-name":
|
|
||||||
// Iterate through all naming replacement rules and perform the replacements.
|
|
||||||
for _, expr := range override.ProxyName {
|
|
||||||
name := mapping["name"].(string)
|
|
||||||
newName, err := expr.Pattern.Replace(name, expr.Target, 0, -1)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("proxy name replace error: %w", err)
|
|
||||||
}
|
|
||||||
mapping["name"] = newName
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
mapping[fieldName] = field.Elem().Interface()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/log"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type SubscriptionInfo struct {
|
type SubscriptionInfo struct {
|
||||||
@@ -15,45 +12,28 @@ type SubscriptionInfo struct {
|
|||||||
Expire int64
|
Expire int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo) {
|
func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo, err error) {
|
||||||
userinfo = strings.ReplaceAll(strings.ToLower(userinfo), " ", "")
|
userinfo = strings.ToLower(userinfo)
|
||||||
|
userinfo = strings.ReplaceAll(userinfo, " ", "")
|
||||||
si = new(SubscriptionInfo)
|
si = new(SubscriptionInfo)
|
||||||
|
|
||||||
for _, field := range strings.Split(userinfo, ";") {
|
for _, field := range strings.Split(userinfo, ";") {
|
||||||
name, value, ok := strings.Cut(field, "=")
|
switch name, value, _ := strings.Cut(field, "="); name {
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := parseValue(value)
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("[Provider] get subscription-userinfo: %e", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
switch name {
|
|
||||||
case "upload":
|
case "upload":
|
||||||
si.Upload = intValue
|
si.Upload, err = strconv.ParseInt(value, 10, 64)
|
||||||
case "download":
|
case "download":
|
||||||
si.Download = intValue
|
si.Download, err = strconv.ParseInt(value, 10, 64)
|
||||||
case "total":
|
case "total":
|
||||||
si.Total = intValue
|
si.Total, err = strconv.ParseInt(value, 10, 64)
|
||||||
case "expire":
|
case "expire":
|
||||||
si.Expire = intValue
|
if value == "" {
|
||||||
|
si.Expire = 0
|
||||||
|
} else {
|
||||||
|
si.Expire, err = strconv.ParseInt(value, 10, 64)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return
|
||||||
return si
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseValue(value string) (int64, error) {
|
|
||||||
if intValue, err := strconv.ParseInt(value, 10, 64); err == nil {
|
|
||||||
return intValue, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if floatValue, err := strconv.ParseFloat(value, 64); err == nil {
|
|
||||||
return int64(floatValue), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0, fmt.Errorf("failed to parse value '%s'", value)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
// Copyright 2014 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.
|
|
||||||
|
|
||||||
// kanged from https://github.com/golang/mobile/blob/c713f31d574bb632a93f169b2cc99c9e753fef0e/app/android.go#L89
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
// #include <time.h>
|
|
||||||
import "C"
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
var currentT C.time_t
|
|
||||||
var currentTM C.struct_tm
|
|
||||||
C.time(¤tT)
|
|
||||||
C.localtime_r(¤tT, ¤tTM)
|
|
||||||
tzOffset := int(currentTM.tm_gmtoff)
|
|
||||||
tz := C.GoString(currentTM.tm_zone)
|
|
||||||
time.Local = time.FixedZone(tz, tzOffset)
|
|
||||||
}
|
|
||||||
@@ -20,21 +20,29 @@ func WithSize[K comparable, V any](maxSize int) Option[K, V] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ARC[K comparable, V any] struct {
|
type ARC[K comparable, V any] struct {
|
||||||
p int
|
p int
|
||||||
c int
|
c int
|
||||||
t1 *list.List[*entry[K, V]]
|
t1 *list.List[*entry[K, V]]
|
||||||
b1 *list.List[*entry[K, V]]
|
b1 *list.List[*entry[K, V]]
|
||||||
t2 *list.List[*entry[K, V]]
|
t2 *list.List[*entry[K, V]]
|
||||||
b2 *list.List[*entry[K, V]]
|
b2 *list.List[*entry[K, V]]
|
||||||
mutex sync.Mutex
|
mutex sync.Mutex
|
||||||
len int
|
len int
|
||||||
cache map[K]*entry[K, V]
|
cache map[K]*entry[K, V]
|
||||||
|
staleReturn bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// New returns a new Adaptive Replacement Cache (ARC).
|
// New returns a new Adaptive Replacement Cache (ARC).
|
||||||
func New[K comparable, V any](options ...Option[K, V]) *ARC[K, V] {
|
func New[K comparable, V any](options ...Option[K, V]) *ARC[K, V] {
|
||||||
arc := &ARC[K, V]{}
|
arc := &ARC[K, V]{
|
||||||
arc.Clear()
|
p: 0,
|
||||||
|
t1: list.New[*entry[K, V]](),
|
||||||
|
b1: list.New[*entry[K, V]](),
|
||||||
|
t2: list.New[*entry[K, V]](),
|
||||||
|
b2: list.New[*entry[K, V]](),
|
||||||
|
len: 0,
|
||||||
|
cache: make(map[K]*entry[K, V]),
|
||||||
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
option(arc)
|
option(arc)
|
||||||
@@ -42,19 +50,6 @@ func New[K comparable, V any](options ...Option[K, V]) *ARC[K, V] {
|
|||||||
return arc
|
return arc
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *ARC[K, V]) Clear() {
|
|
||||||
a.mutex.Lock()
|
|
||||||
defer a.mutex.Unlock()
|
|
||||||
|
|
||||||
a.p = 0
|
|
||||||
a.t1 = list.New[*entry[K, V]]()
|
|
||||||
a.b1 = list.New[*entry[K, V]]()
|
|
||||||
a.t2 = list.New[*entry[K, V]]()
|
|
||||||
a.b2 = list.New[*entry[K, V]]()
|
|
||||||
a.len = 0
|
|
||||||
a.cache = make(map[K]*entry[K, V])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set inserts a new key-value pair into the cache.
|
// Set inserts a new key-value pair into the cache.
|
||||||
// This optimizes future access to this entry (side effect).
|
// This optimizes future access to this entry (side effect).
|
||||||
func (a *ARC[K, V]) Set(key K, value V) {
|
func (a *ARC[K, V]) Set(key K, value V) {
|
||||||
@@ -79,22 +74,20 @@ func (a *ARC[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
|||||||
|
|
||||||
func (a *ARC[K, V]) setWithExpire(key K, value V, expires time.Time) {
|
func (a *ARC[K, V]) setWithExpire(key K, value V, expires time.Time) {
|
||||||
ent, ok := a.cache[key]
|
ent, ok := a.cache[key]
|
||||||
if !ok {
|
if ok != true {
|
||||||
a.len++
|
a.len++
|
||||||
ent := &entry[K, V]{key: key, value: value, ghost: false, expires: expires.Unix()}
|
ent := &entry[K, V]{key: key, value: value, ghost: false, expires: expires.Unix()}
|
||||||
a.req(ent)
|
a.req(ent)
|
||||||
a.cache[key] = ent
|
a.cache[key] = ent
|
||||||
return
|
} else {
|
||||||
|
if ent.ghost {
|
||||||
|
a.len++
|
||||||
|
}
|
||||||
|
ent.value = value
|
||||||
|
ent.ghost = false
|
||||||
|
ent.expires = expires.Unix()
|
||||||
|
a.req(ent)
|
||||||
}
|
}
|
||||||
|
|
||||||
if ent.ghost {
|
|
||||||
a.len++
|
|
||||||
}
|
|
||||||
|
|
||||||
ent.value = value
|
|
||||||
ent.ghost = false
|
|
||||||
ent.expires = expires.Unix()
|
|
||||||
a.req(ent)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get retrieves a previously via Set inserted entry.
|
// Get retrieves a previously via Set inserted entry.
|
||||||
@@ -104,25 +97,25 @@ func (a *ARC[K, V]) Get(key K) (value V, ok bool) {
|
|||||||
defer a.mutex.Unlock()
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
ent, ok := a.get(key)
|
ent, ok := a.get(key)
|
||||||
if !ok {
|
if ok {
|
||||||
return lo.Empty[V](), false
|
return ent.value, true
|
||||||
}
|
}
|
||||||
return ent.value, true
|
return lo.Empty[V](), false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *ARC[K, V]) get(key K) (e *entry[K, V], ok bool) {
|
func (a *ARC[K, V]) get(key K) (e *entry[K, V], ok bool) {
|
||||||
ent, ok := a.cache[key]
|
ent, ok := a.cache[key]
|
||||||
if !ok {
|
if ok {
|
||||||
return ent, false
|
a.req(ent)
|
||||||
|
return ent, !ent.ghost
|
||||||
}
|
}
|
||||||
a.req(ent)
|
return ent, false
|
||||||
return ent, !ent.ghost
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetWithExpire returns any representation of a cached response,
|
// GetWithExpire returns any representation of a cached response,
|
||||||
// a time.Time Give expected expires,
|
// a time.Time Give expected expires,
|
||||||
// and a bool set to true if the key was found.
|
// and a bool set to true if the key was found.
|
||||||
// This method will NOT update the expires.
|
// This method will NOT check the maxAge of element and will NOT update the expires.
|
||||||
func (a *ARC[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
func (a *ARC[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
||||||
a.mutex.Lock()
|
a.mutex.Lock()
|
||||||
defer a.mutex.Unlock()
|
defer a.mutex.Unlock()
|
||||||
@@ -145,11 +138,10 @@ func (a *ARC[K, V]) Len() int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *ARC[K, V]) req(ent *entry[K, V]) {
|
func (a *ARC[K, V]) req(ent *entry[K, V]) {
|
||||||
switch {
|
if ent.ll == a.t1 || ent.ll == a.t2 {
|
||||||
case ent.ll == a.t1 || ent.ll == a.t2:
|
|
||||||
// Case I
|
// Case I
|
||||||
ent.setMRU(a.t2)
|
ent.setMRU(a.t2)
|
||||||
case ent.ll == a.b1:
|
} else if ent.ll == a.b1 {
|
||||||
// Case II
|
// Case II
|
||||||
// Cache Miss in t1 and t2
|
// Cache Miss in t1 and t2
|
||||||
|
|
||||||
@@ -160,11 +152,16 @@ func (a *ARC[K, V]) req(ent *entry[K, V]) {
|
|||||||
} else {
|
} else {
|
||||||
d = a.b2.Len() / a.b1.Len()
|
d = a.b2.Len() / a.b1.Len()
|
||||||
}
|
}
|
||||||
a.p = min(a.p+d, a.c)
|
|
||||||
|
// a.p = min(a.p+d, a.c)
|
||||||
|
a.p = a.p + d
|
||||||
|
if a.c < a.p {
|
||||||
|
a.p = a.c
|
||||||
|
}
|
||||||
|
|
||||||
a.replace(ent)
|
a.replace(ent)
|
||||||
ent.setMRU(a.t2)
|
ent.setMRU(a.t2)
|
||||||
case ent.ll == a.b2:
|
} else if ent.ll == a.b2 {
|
||||||
// Case III
|
// Case III
|
||||||
// Cache Miss in t1 and t2
|
// Cache Miss in t1 and t2
|
||||||
|
|
||||||
@@ -175,30 +172,35 @@ func (a *ARC[K, V]) req(ent *entry[K, V]) {
|
|||||||
} else {
|
} else {
|
||||||
d = a.b1.Len() / a.b2.Len()
|
d = a.b1.Len() / a.b2.Len()
|
||||||
}
|
}
|
||||||
a.p = max(a.p-d, 0)
|
//a.p = max(a.p-d, 0)
|
||||||
|
a.p = a.p - d
|
||||||
|
if a.p < 0 {
|
||||||
|
a.p = 0
|
||||||
|
}
|
||||||
|
|
||||||
a.replace(ent)
|
a.replace(ent)
|
||||||
ent.setMRU(a.t2)
|
ent.setMRU(a.t2)
|
||||||
case ent.ll == nil && a.t1.Len()+a.b1.Len() == a.c:
|
} else if ent.ll == nil {
|
||||||
// Case IV A
|
// Case IV
|
||||||
if a.t1.Len() < a.c {
|
|
||||||
a.delLRU(a.b1)
|
if a.t1.Len()+a.b1.Len() == a.c {
|
||||||
a.replace(ent)
|
// Case A
|
||||||
} else {
|
if a.t1.Len() < a.c {
|
||||||
a.delLRU(a.t1)
|
a.delLRU(a.b1)
|
||||||
}
|
a.replace(ent)
|
||||||
ent.setMRU(a.t1)
|
} else {
|
||||||
case ent.ll == nil && a.t1.Len()+a.b1.Len() < a.c:
|
a.delLRU(a.t1)
|
||||||
// Case IV B
|
}
|
||||||
if a.t1.Len()+a.t2.Len()+a.b1.Len()+a.b2.Len() >= a.c {
|
} else if a.t1.Len()+a.b1.Len() < a.c {
|
||||||
if a.t1.Len()+a.t2.Len()+a.b1.Len()+a.b2.Len() == 2*a.c {
|
// Case B
|
||||||
a.delLRU(a.b2)
|
if a.t1.Len()+a.t2.Len()+a.b1.Len()+a.b2.Len() >= a.c {
|
||||||
|
if a.t1.Len()+a.t2.Len()+a.b1.Len()+a.b2.Len() == 2*a.c {
|
||||||
|
a.delLRU(a.b2)
|
||||||
|
}
|
||||||
|
a.replace(ent)
|
||||||
}
|
}
|
||||||
a.replace(ent)
|
|
||||||
}
|
}
|
||||||
ent.setMRU(a.t1)
|
|
||||||
case ent.ll == nil:
|
|
||||||
// Case IV, not A nor B
|
|
||||||
ent.setMRU(a.t1)
|
ent.setMRU(a.t1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -225,17 +227,3 @@ func (a *ARC[K, V]) replace(ent *entry[K, V]) {
|
|||||||
lru.setMRU(a.b2)
|
lru.setMRU(a.b2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func min(a, b int) int {
|
|
||||||
if a < b {
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func max(a int, b int) int {
|
|
||||||
if a < b {
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,105 +1,59 @@
|
|||||||
package arc
|
package arc
|
||||||
|
|
||||||
import (
|
import "testing"
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestInsertion(t *testing.T) {
|
func TestBasic(t *testing.T) {
|
||||||
cache := New[string, string](WithSize[string, string](3))
|
cache := New[string, string](WithSize[string, string](3))
|
||||||
if got, want := cache.Len(), 0; got != want {
|
if cache.Len() != 0 {
|
||||||
t.Errorf("empty cache.Len(): got %d want %d", cache.Len(), want)
|
t.Error("Empty cache should have length 0")
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
cache.Set("Hello", "World")
|
||||||
k1 = "Hello"
|
if cache.Len() != 1 {
|
||||||
k2 = "Hallo"
|
t.Error("Cache should have length 1")
|
||||||
k3 = "Ciao"
|
|
||||||
k4 = "Salut"
|
|
||||||
|
|
||||||
v1 = "World"
|
|
||||||
v2 = "Worlds"
|
|
||||||
v3 = "Welt"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Insert the first value
|
|
||||||
cache.Set(k1, v1)
|
|
||||||
if got, want := cache.Len(), 1; got != want {
|
|
||||||
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
|
||||||
}
|
|
||||||
if got, ok := cache.Get(k1); !ok || got != v1 {
|
|
||||||
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace existing value for a given key
|
var val interface{}
|
||||||
cache.Set(k1, v2)
|
var ok bool
|
||||||
if got, want := cache.Len(), 1; got != want {
|
|
||||||
t.Errorf("re-insertion: cache.Len(): got %d want %d", cache.Len(), want)
|
if val, ok = cache.Get("Hello"); val != "World" || ok != true {
|
||||||
}
|
t.Error("Didn't set \"Hello\" to \"World\"")
|
||||||
if got, ok := cache.Get(k1); !ok || got != v2 {
|
|
||||||
t.Errorf("re-insertion: cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v2)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add a second different key
|
cache.Set("Hello", "World1")
|
||||||
cache.Set(k2, v3)
|
if cache.Len() != 1 {
|
||||||
if got, want := cache.Len(), 2; got != want {
|
t.Error("Inserting the same entry multiple times shouldn't increase cache size")
|
||||||
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
|
||||||
}
|
|
||||||
if got, ok := cache.Get(k1); !ok || got != v2 {
|
|
||||||
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v2)
|
|
||||||
}
|
|
||||||
if got, ok := cache.Get(k2); !ok || got != v3 {
|
|
||||||
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k2, got, ok, v3)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fill cache
|
if val, ok = cache.Get("Hello"); val != "World1" || ok != true {
|
||||||
cache.Set(k3, v1)
|
t.Error("Didn't update \"Hello\" to \"World1\"")
|
||||||
if got, want := cache.Len(), 3; got != want {
|
|
||||||
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exceed size, this should not exceed size:
|
cache.Set("Hallo", "Welt")
|
||||||
cache.Set(k4, v1)
|
if cache.Len() != 2 {
|
||||||
if got, want := cache.Len(), 3; got != want {
|
t.Error("Inserting two different entries should result into lenght=2")
|
||||||
t.Errorf("insertion of key out of size: cache.Len(): got %d want %d", cache.Len(), want)
|
}
|
||||||
|
|
||||||
|
if val, ok = cache.Get("Hallo"); val != "Welt" || ok != true {
|
||||||
|
t.Error("Didn't set \"Hallo\" to \"Welt\"")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEviction(t *testing.T) {
|
func TestBasicReplace(t *testing.T) {
|
||||||
size := 3
|
cache := New[string, string](WithSize[string, string](3))
|
||||||
cache := New[string, string](WithSize[string, string](size))
|
|
||||||
if got, want := cache.Len(), 0; got != want {
|
cache.Set("Hello", "Hallo")
|
||||||
t.Errorf("empty cache.Len(): got %d want %d", cache.Len(), want)
|
cache.Set("World", "Welt")
|
||||||
|
cache.Get("World")
|
||||||
|
cache.Set("Cache", "Cache")
|
||||||
|
cache.Set("Replace", "Ersetzen")
|
||||||
|
|
||||||
|
value, ok := cache.Get("World")
|
||||||
|
if !ok || value != "Welt" {
|
||||||
|
t.Error("ARC should have replaced \"Hello\"")
|
||||||
}
|
}
|
||||||
|
|
||||||
tests := []struct {
|
if cache.Len() != 3 {
|
||||||
k, v string
|
t.Error("ARC should have a maximum size of 3")
|
||||||
}{
|
|
||||||
{"k1", "v1"},
|
|
||||||
{"k2", "v2"},
|
|
||||||
{"k3", "v3"},
|
|
||||||
{"k4", "v4"},
|
|
||||||
}
|
|
||||||
for i, tt := range tests[:size] {
|
|
||||||
cache.Set(tt.k, tt.v)
|
|
||||||
if got, want := cache.Len(), i+1; got != want {
|
|
||||||
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exceed size and check we don't outgrow it:
|
|
||||||
cache.Set(tests[size].k, tests[size].v)
|
|
||||||
if got := cache.Len(); got != size {
|
|
||||||
t.Errorf("insertion of overflow key #%d: cache.Len(): got %d want %d", 4, cache.Len(), size)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check that LRU got evicted:
|
|
||||||
if got, ok := cache.Get(tests[0].k); ok || got != "" {
|
|
||||||
t.Errorf("cache.Get(%v): got (%v,%t) want (<nil>,true)", tests[0].k, got, ok)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests[1:] {
|
|
||||||
if got, ok := cache.Get(tt.k); !ok || got != tt.v {
|
|
||||||
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", tt.k, got, ok, tt.v)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,39 +15,28 @@ type TypedValue[T any] struct {
|
|||||||
value atomic.Value
|
value atomic.Value
|
||||||
}
|
}
|
||||||
|
|
||||||
// tValue is a struct with determined type to resolve atomic.Value usages with interface types
|
|
||||||
// https://github.com/golang/go/issues/22550
|
|
||||||
//
|
|
||||||
// The intention to have an atomic value store for errors. However, running this code panics:
|
|
||||||
// panic: sync/atomic: store of inconsistently typed value into Value
|
|
||||||
// This is because atomic.Value requires that the underlying concrete type be the same (which is a reasonable expectation for its implementation).
|
|
||||||
// When going through the atomic.Value.Store method call, the fact that both these are of the error interface is lost.
|
|
||||||
type tValue[T any] struct {
|
|
||||||
value T
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TypedValue[T]) Load() T {
|
func (t *TypedValue[T]) Load() T {
|
||||||
value := t.value.Load()
|
value := t.value.Load()
|
||||||
if value == nil {
|
if value == nil {
|
||||||
return DefaultValue[T]()
|
return DefaultValue[T]()
|
||||||
}
|
}
|
||||||
return value.(tValue[T]).value
|
return value.(T)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Store(value T) {
|
func (t *TypedValue[T]) Store(value T) {
|
||||||
t.value.Store(tValue[T]{value})
|
t.value.Store(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Swap(new T) T {
|
func (t *TypedValue[T]) Swap(new T) T {
|
||||||
old := t.value.Swap(tValue[T]{new})
|
old := t.value.Swap(new)
|
||||||
if old == nil {
|
if old == nil {
|
||||||
return DefaultValue[T]()
|
return DefaultValue[T]()
|
||||||
}
|
}
|
||||||
return old.(tValue[T]).value
|
return old.(T)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
||||||
return t.value.CompareAndSwap(tValue[T]{old}, tValue[T]{new})
|
return t.value.CompareAndSwap(old, new)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
package callback
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type closeCallbackConn struct {
|
|
||||||
C.Conn
|
|
||||||
closeFunc func()
|
|
||||||
closeOnce sync.Once
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *closeCallbackConn) Close() error {
|
|
||||||
w.closeOnce.Do(w.closeFunc)
|
|
||||||
return w.Conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *closeCallbackConn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *closeCallbackConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *closeCallbackConn) Upstream() any {
|
|
||||||
return w.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCloseCallbackConn(conn C.Conn, callback func()) C.Conn {
|
|
||||||
return &closeCallbackConn{Conn: conn, closeFunc: callback}
|
|
||||||
}
|
|
||||||
|
|
||||||
type closeCallbackPacketConn struct {
|
|
||||||
C.PacketConn
|
|
||||||
closeFunc func()
|
|
||||||
closeOnce sync.Once
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *closeCallbackPacketConn) Close() error {
|
|
||||||
w.closeOnce.Do(w.closeFunc)
|
|
||||||
return w.PacketConn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *closeCallbackPacketConn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *closeCallbackPacketConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *closeCallbackPacketConn) Upstream() any {
|
|
||||||
return w.PacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCloseCallbackPacketConn(conn C.PacketConn, callback func()) C.PacketConn {
|
|
||||||
return &closeCallbackPacketConn{PacketConn: conn, closeFunc: callback}
|
|
||||||
}
|
|
||||||
@@ -68,8 +68,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
||||||
|
|
||||||
proxies = append(proxies, hysteria)
|
proxies = append(proxies, hysteria)
|
||||||
|
case "hysteria2":
|
||||||
case "hysteria2", "hy2":
|
|
||||||
urlHysteria2, err := url.Parse(line)
|
urlHysteria2, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
@@ -80,7 +79,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria2 := make(map[string]any, 20)
|
hysteria2 := make(map[string]any, 20)
|
||||||
|
|
||||||
hysteria2["name"] = name
|
hysteria2["name"] = name
|
||||||
hysteria2["type"] = "hysteria2"
|
hysteria2["type"] = scheme
|
||||||
hysteria2["server"] = urlHysteria2.Hostname()
|
hysteria2["server"] = urlHysteria2.Hostname()
|
||||||
if port := urlHysteria2.Port(); port != "" {
|
if port := urlHysteria2.Port(); port != "" {
|
||||||
hysteria2["port"] = port
|
hysteria2["port"] = port
|
||||||
@@ -102,7 +101,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria2["up"] = query.Get("up")
|
hysteria2["up"] = query.Get("up")
|
||||||
|
|
||||||
proxies = append(proxies, hysteria2)
|
proxies = append(proxies, hysteria2)
|
||||||
|
|
||||||
case "tuic":
|
case "tuic":
|
||||||
// A temporary unofficial TUIC share link standard
|
// A temporary unofficial TUIC share link standard
|
||||||
// Modified from https://github.com/daeuniverse/dae/discussions/182
|
// Modified from https://github.com/daeuniverse/dae/discussions/182
|
||||||
@@ -145,7 +143,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, tuic)
|
proxies = append(proxies, tuic)
|
||||||
|
|
||||||
case "trojan":
|
case "trojan":
|
||||||
urlTrojan, err := url.Parse(line)
|
urlTrojan, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -330,38 +328,15 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
|
|
||||||
vmess["h2-opts"] = h2Opts
|
vmess["h2-opts"] = h2Opts
|
||||||
|
|
||||||
case "ws", "httpupgrade":
|
case "ws":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
wsOpts["path"] = "/"
|
wsOpts["path"] = []string{"/"}
|
||||||
if host, ok := values["host"]; ok && host != "" {
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
headers["Host"] = host.(string)
|
headers["Host"] = host.(string)
|
||||||
}
|
}
|
||||||
if path, ok := values["path"]; ok && path != "" {
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
path := path.(string)
|
wsOpts["path"] = path.(string)
|
||||||
pathURL, err := url.Parse(path)
|
|
||||||
if err == nil {
|
|
||||||
query := pathURL.Query()
|
|
||||||
if earlyData := query.Get("ed"); earlyData != "" {
|
|
||||||
med, err := strconv.Atoi(earlyData)
|
|
||||||
if err == nil {
|
|
||||||
switch network {
|
|
||||||
case "ws":
|
|
||||||
wsOpts["max-early-data"] = med
|
|
||||||
wsOpts["early-data-header-name"] = "Sec-WebSocket-Protocol"
|
|
||||||
case "httpupgrade":
|
|
||||||
wsOpts["v2ray-http-upgrade-fast-open"] = true
|
|
||||||
}
|
|
||||||
query.Del("ed")
|
|
||||||
pathURL.RawQuery = query.Encode()
|
|
||||||
path = pathURL.String()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
|
||||||
wsOpts["early-data-header-name"] = earlyDataHeader
|
|
||||||
}
|
|
||||||
}
|
|
||||||
wsOpts["path"] = path
|
|
||||||
}
|
}
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
vmess["ws-opts"] = wsOpts
|
vmess["ws-opts"] = wsOpts
|
||||||
@@ -430,27 +405,14 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
if query.Get("udp-over-tcp") == "true" || query.Get("uot") == "1" {
|
if query.Get("udp-over-tcp") == "true" || query.Get("uot") == "1" {
|
||||||
ss["udp-over-tcp"] = true
|
ss["udp-over-tcp"] = true
|
||||||
}
|
}
|
||||||
plugin := query.Get("plugin")
|
if strings.Contains(query.Get("plugin"), "obfs") {
|
||||||
if strings.Contains(plugin, ";") {
|
obfsParams := strings.Split(query.Get("plugin"), ";")
|
||||||
pluginInfo, _ := url.ParseQuery("pluginName=" + strings.ReplaceAll(plugin, ";", "&"))
|
ss["plugin"] = "obfs"
|
||||||
pluginName := pluginInfo.Get("pluginName")
|
ss["plugin-opts"] = map[string]any{
|
||||||
if strings.Contains(pluginName, "obfs") {
|
"host": obfsParams[2][10:],
|
||||||
ss["plugin"] = "obfs"
|
"mode": obfsParams[1][5:],
|
||||||
ss["plugin-opts"] = map[string]any{
|
|
||||||
"mode": pluginInfo.Get("obfs"),
|
|
||||||
"host": pluginInfo.Get("obfs-host"),
|
|
||||||
}
|
|
||||||
} else if strings.Contains(pluginName, "v2ray-plugin") {
|
|
||||||
ss["plugin"] = "v2ray-plugin"
|
|
||||||
ss["plugin-opts"] = map[string]any{
|
|
||||||
"mode": pluginInfo.Get("mode"),
|
|
||||||
"host": pluginInfo.Get("host"),
|
|
||||||
"path": pluginInfo.Get("path"),
|
|
||||||
"tls": strings.Contains(plugin, "tls"),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, ss)
|
proxies = append(proxies, ss)
|
||||||
|
|
||||||
case "ssr":
|
case "ssr":
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import (
|
|||||||
|
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
|
||||||
"github.com/metacubex/randv2"
|
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
var hostsSuffix = []string{
|
var hostsSuffix = []string{
|
||||||
@@ -302,11 +302,11 @@ func RandHost() string {
|
|||||||
prefix += string(buf[6:8]) + "-"
|
prefix += string(buf[6:8]) + "-"
|
||||||
prefix += string(buf[len(buf)-8:])
|
prefix += string(buf[len(buf)-8:])
|
||||||
|
|
||||||
return prefix + hostsSuffix[randv2.IntN(hostsLen)]
|
return prefix + hostsSuffix[fastrand.Intn(hostsLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func RandUserAgent() string {
|
func RandUserAgent() string {
|
||||||
return userAgents[randv2.IntN(uaLen)]
|
return userAgents[fastrand.Intn(uaLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetUserAgent(header http.Header) {
|
func SetUserAgent(header http.Header) {
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
h2Opts["headers"] = headers
|
h2Opts["headers"] = headers
|
||||||
proxy["h2-opts"] = h2Opts
|
proxy["h2-opts"] = h2Opts
|
||||||
|
|
||||||
case "ws", "httpupgrade":
|
case "ws":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
headers["User-Agent"] = RandUserAgent()
|
headers["User-Agent"] = RandUserAgent()
|
||||||
@@ -113,13 +113,7 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
||||||
}
|
}
|
||||||
switch network {
|
wsOpts["max-early-data"] = med
|
||||||
case "ws":
|
|
||||||
wsOpts["max-early-data"] = med
|
|
||||||
wsOpts["early-data-header-name"] = "Sec-WebSocket-Protocol"
|
|
||||||
case "httpupgrade":
|
|
||||||
wsOpts["v2ray-http-upgrade-fast-open"] = true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
||||||
wsOpts["early-data-header-name"] = earlyDataHeader
|
wsOpts["early-data-header-name"] = earlyDataHeader
|
||||||
|
|||||||
@@ -68,8 +68,10 @@ type LruCache[K comparable, V any] struct {
|
|||||||
|
|
||||||
// New creates an LruCache
|
// New creates an LruCache
|
||||||
func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
||||||
lc := &LruCache[K, V]{}
|
lc := &LruCache[K, V]{
|
||||||
lc.Clear()
|
lru: list.New[*entry[K, V]](),
|
||||||
|
cache: make(map[K]*list.Element[*entry[K, V]]),
|
||||||
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
option(lc)
|
option(lc)
|
||||||
@@ -78,15 +80,7 @@ func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
|||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *LruCache[K, V]) Clear() {
|
// Get returns the any representation of a cached response and a bool
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
c.lru = list.New[*entry[K, V]]()
|
|
||||||
c.cache = make(map[K]*list.Element[*entry[K, V]])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns any representation of a cached response and a bool
|
|
||||||
// set to true if the key was found.
|
// set to true if the key was found.
|
||||||
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@@ -116,7 +110,7 @@ func (c *LruCache[K, V]) GetOrStore(key K, constructor func() V) (V, bool) {
|
|||||||
return value, true
|
return value, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetWithExpire returns any representation of a cached response,
|
// GetWithExpire returns the any representation of a cached response,
|
||||||
// a time.Time Give expected expires,
|
// a time.Time Give expected expires,
|
||||||
// and a bool set to true if the key was found.
|
// and a bool set to true if the key was found.
|
||||||
// This method will NOT check the maxAge of element and will NOT update the expires.
|
// This method will NOT check the maxAge of element and will NOT update the expires.
|
||||||
@@ -141,7 +135,7 @@ func (c *LruCache[K, V]) Exist(key K) bool {
|
|||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set stores any representation of a response for a given key.
|
// Set stores the any representation of a response for a given key.
|
||||||
func (c *LruCache[K, V]) Set(key K, value V) {
|
func (c *LruCache[K, V]) Set(key K, value V) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
@@ -157,7 +151,7 @@ func (c *LruCache[K, V]) set(key K, value V) {
|
|||||||
c.setWithExpire(key, value, time.Unix(expires, 0))
|
c.setWithExpire(key, value, time.Unix(expires, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetWithExpire stores any representation of a response for a given key and given expires.
|
// SetWithExpire stores the any representation of a response for a given key and given expires.
|
||||||
// The expires time will round to second.
|
// The expires time will round to second.
|
||||||
func (c *LruCache[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
func (c *LruCache[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@@ -229,10 +223,6 @@ func (c *LruCache[K, V]) Delete(key K) {
|
|||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
c.delete(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *LruCache[K, V]) delete(key K) {
|
|
||||||
if le, ok := c.cache[key]; ok {
|
if le, ok := c.cache[key]; ok {
|
||||||
c.deleteElement(le)
|
c.deleteElement(le)
|
||||||
}
|
}
|
||||||
@@ -256,32 +246,13 @@ func (c *LruCache[K, V]) deleteElement(le *list.Element[*entry[K, V]]) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compute either sets the computed new value for the key or deletes
|
func (c *LruCache[K, V]) Clear() error {
|
||||||
// the value for the key. When the delete result of the valueFn function
|
|
||||||
// is set to true, the value will be deleted, if it exists. When delete
|
|
||||||
// is set to false, the value is updated to the newValue.
|
|
||||||
// The ok result indicates whether value was computed and stored, thus, is
|
|
||||||
// present in the map. The actual result contains the new value in cases where
|
|
||||||
// the value was computed and stored.
|
|
||||||
func (c *LruCache[K, V]) Compute(
|
|
||||||
key K,
|
|
||||||
valueFn func(oldValue V, loaded bool) (newValue V, delete bool),
|
|
||||||
) (actual V, ok bool) {
|
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
if el := c.get(key); el != nil {
|
c.cache = make(map[K]*list.Element[*entry[K, V]])
|
||||||
actual, ok = el.value, true
|
|
||||||
}
|
return nil
|
||||||
if newValue, del := valueFn(actual, ok); del {
|
|
||||||
if ok { // data not in cache, so needn't delete
|
|
||||||
c.delete(key)
|
|
||||||
}
|
|
||||||
return lo.Empty[V](), false
|
|
||||||
} else {
|
|
||||||
c.set(key, newValue)
|
|
||||||
return newValue, true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type entry[K comparable, V any] struct {
|
type entry[K comparable, V any] struct {
|
||||||
|
|||||||
@@ -1,154 +0,0 @@
|
|||||||
package deadline
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
"github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type connReadResult struct {
|
|
||||||
buffer []byte
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
type Conn struct {
|
|
||||||
network.ExtendedConn
|
|
||||||
deadline atomic.TypedValue[time.Time]
|
|
||||||
pipeDeadline pipeDeadline
|
|
||||||
disablePipe atomic.Bool
|
|
||||||
inRead atomic.Bool
|
|
||||||
resultCh chan *connReadResult
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsConn(conn any) bool {
|
|
||||||
_, ok := conn.(*Conn)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConn(conn net.Conn) *Conn {
|
|
||||||
c := &Conn{
|
|
||||||
ExtendedConn: bufio.NewExtendedConn(conn),
|
|
||||||
pipeDeadline: makePipeDeadline(),
|
|
||||||
resultCh: make(chan *connReadResult, 1),
|
|
||||||
}
|
|
||||||
c.resultCh <- nil
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Conn) Read(p []byte) (n int, err error) {
|
|
||||||
select {
|
|
||||||
case result := <-c.resultCh:
|
|
||||||
if result != nil {
|
|
||||||
n = copy(p, result.buffer)
|
|
||||||
err = result.err
|
|
||||||
if n >= len(result.buffer) {
|
|
||||||
c.resultCh <- nil // finish cache read
|
|
||||||
} else {
|
|
||||||
result.buffer = result.buffer[n:]
|
|
||||||
c.resultCh <- result // push back for next call
|
|
||||||
}
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
c.resultCh <- nil
|
|
||||||
break
|
|
||||||
}
|
|
||||||
case <-c.pipeDeadline.wait():
|
|
||||||
return 0, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.disablePipe.Load() {
|
|
||||||
return c.ExtendedConn.Read(p)
|
|
||||||
} else if c.deadline.Load().IsZero() {
|
|
||||||
c.inRead.Store(true)
|
|
||||||
defer c.inRead.Store(false)
|
|
||||||
return c.ExtendedConn.Read(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
<-c.resultCh
|
|
||||||
go c.pipeRead(len(p))
|
|
||||||
|
|
||||||
return c.Read(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Conn) pipeRead(size int) {
|
|
||||||
buffer := make([]byte, size)
|
|
||||||
n, err := c.ExtendedConn.Read(buffer)
|
|
||||||
buffer = buffer[:n]
|
|
||||||
c.resultCh <- &connReadResult{
|
|
||||||
buffer: buffer,
|
|
||||||
err: err,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Conn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
|
||||||
select {
|
|
||||||
case result := <-c.resultCh:
|
|
||||||
if result != nil {
|
|
||||||
n, _ := buffer.Write(result.buffer)
|
|
||||||
err = result.err
|
|
||||||
|
|
||||||
if n >= len(result.buffer) {
|
|
||||||
c.resultCh <- nil // finish cache read
|
|
||||||
} else {
|
|
||||||
result.buffer = result.buffer[n:]
|
|
||||||
c.resultCh <- result // push back for next call
|
|
||||||
}
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
c.resultCh <- nil
|
|
||||||
break
|
|
||||||
}
|
|
||||||
case <-c.pipeDeadline.wait():
|
|
||||||
return os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.disablePipe.Load() {
|
|
||||||
return c.ExtendedConn.ReadBuffer(buffer)
|
|
||||||
} else if c.deadline.Load().IsZero() {
|
|
||||||
c.inRead.Store(true)
|
|
||||||
defer c.inRead.Store(false)
|
|
||||||
return c.ExtendedConn.ReadBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
<-c.resultCh
|
|
||||||
go c.pipeRead(buffer.FreeLen())
|
|
||||||
|
|
||||||
return c.ReadBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Conn) SetReadDeadline(t time.Time) error {
|
|
||||||
if c.disablePipe.Load() {
|
|
||||||
return c.ExtendedConn.SetReadDeadline(t)
|
|
||||||
} else if c.inRead.Load() {
|
|
||||||
c.disablePipe.Store(true)
|
|
||||||
return c.ExtendedConn.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
c.deadline.Store(t)
|
|
||||||
c.pipeDeadline.set(t)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Conn) 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 *Conn) Upstream() any {
|
|
||||||
return c.ExtendedConn
|
|
||||||
}
|
|
||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/net/packet"
|
"github.com/metacubex/mihomo/common/net/packet"
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
"github.com/sagernet/sing/common/buf"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
@@ -122,18 +121,17 @@ type singPacketReadWaiter struct {
|
|||||||
|
|
||||||
type singWaitReadResult singReadResult
|
type singWaitReadResult singReadResult
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool) {
|
func (c *singPacketReadWaiter) InitializeReadWaiter(newBuffer func() *buf.Buffer) {
|
||||||
return c.packetReadWaiter.InitializeReadWaiter(options)
|
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) WaitReadPacket() (buffer *buf.Buffer, destination M.Socksaddr, err error) {
|
func (c *singPacketReadWaiter) WaitReadPacket() (destination M.Socksaddr, err error) {
|
||||||
FOR:
|
FOR:
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case result := <-c.netPacketConn.resultCh:
|
case result := <-c.netPacketConn.resultCh:
|
||||||
if result != nil {
|
if result != nil {
|
||||||
if result, ok := result.(*singWaitReadResult); ok {
|
if result, ok := result.(*singWaitReadResult); ok {
|
||||||
buffer = result.buffer
|
|
||||||
destination = result.destination
|
destination = result.destination
|
||||||
err = result.err
|
err = result.err
|
||||||
c.netPacketConn.resultCh <- nil // finish cache read
|
c.netPacketConn.resultCh <- nil // finish cache read
|
||||||
@@ -147,7 +145,7 @@ FOR:
|
|||||||
break FOR
|
break FOR
|
||||||
}
|
}
|
||||||
case <-c.netPacketConn.pipeDeadline.wait():
|
case <-c.netPacketConn.pipeDeadline.wait():
|
||||||
return nil, M.Socksaddr{}, os.ErrDeadlineExceeded
|
return M.Socksaddr{}, os.ErrDeadlineExceeded
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,7 +154,8 @@ FOR:
|
|||||||
} else if c.netPacketConn.deadline.Load().IsZero() {
|
} else if c.netPacketConn.deadline.Load().IsZero() {
|
||||||
c.netPacketConn.inRead.Store(true)
|
c.netPacketConn.inRead.Store(true)
|
||||||
defer c.netPacketConn.inRead.Store(false)
|
defer c.netPacketConn.inRead.Store(false)
|
||||||
return c.packetReadWaiter.WaitReadPacket()
|
destination, err = c.packetReadWaiter.WaitReadPacket()
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
<-c.netPacketConn.resultCh
|
<-c.netPacketConn.resultCh
|
||||||
@@ -166,9 +165,8 @@ FOR:
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) pipeWaitReadPacket() {
|
func (c *singPacketReadWaiter) pipeWaitReadPacket() {
|
||||||
buffer, destination, err := c.packetReadWaiter.WaitReadPacket()
|
destination, err := c.packetReadWaiter.WaitReadPacket()
|
||||||
result := &singWaitReadResult{}
|
result := &singWaitReadResult{}
|
||||||
result.buffer = buffer
|
|
||||||
result.destination = destination
|
result.destination = destination
|
||||||
result.err = err
|
result.err = err
|
||||||
c.netPacketConn.resultCh <- result
|
c.netPacketConn.resultCh <- result
|
||||||
|
|||||||
@@ -1,222 +0,0 @@
|
|||||||
package deadline
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type pipeAddr struct{}
|
|
||||||
|
|
||||||
func (pipeAddr) Network() string { return "pipe" }
|
|
||||||
func (pipeAddr) String() string { return "pipe" }
|
|
||||||
|
|
||||||
type pipe struct {
|
|
||||||
wrMu sync.Mutex // Serialize Write operations
|
|
||||||
|
|
||||||
// Used by local Read to interact with remote Write.
|
|
||||||
// Successful receive on rdRx is always followed by send on rdTx.
|
|
||||||
rdRx <-chan []byte
|
|
||||||
rdTx chan<- int
|
|
||||||
|
|
||||||
// Used by local Write to interact with remote Read.
|
|
||||||
// Successful send on wrTx is always followed by receive on wrRx.
|
|
||||||
wrTx chan<- []byte
|
|
||||||
wrRx <-chan int
|
|
||||||
|
|
||||||
once sync.Once // Protects closing localDone
|
|
||||||
localDone chan struct{}
|
|
||||||
remoteDone <-chan struct{}
|
|
||||||
|
|
||||||
readDeadline pipeDeadline
|
|
||||||
writeDeadline pipeDeadline
|
|
||||||
|
|
||||||
readWaitOptions N.ReadWaitOptions
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pipe creates a synchronous, in-memory, full duplex
|
|
||||||
// network connection; both ends implement the Conn interface.
|
|
||||||
// Reads on one end are matched with writes on the other,
|
|
||||||
// copying data directly between the two; there is no internal
|
|
||||||
// buffering.
|
|
||||||
func Pipe() (net.Conn, net.Conn) {
|
|
||||||
cb1 := make(chan []byte)
|
|
||||||
cb2 := make(chan []byte)
|
|
||||||
cn1 := make(chan int)
|
|
||||||
cn2 := make(chan int)
|
|
||||||
done1 := make(chan struct{})
|
|
||||||
done2 := make(chan struct{})
|
|
||||||
|
|
||||||
p1 := &pipe{
|
|
||||||
rdRx: cb1, rdTx: cn1,
|
|
||||||
wrTx: cb2, wrRx: cn2,
|
|
||||||
localDone: done1, remoteDone: done2,
|
|
||||||
readDeadline: makePipeDeadline(),
|
|
||||||
writeDeadline: makePipeDeadline(),
|
|
||||||
}
|
|
||||||
p2 := &pipe{
|
|
||||||
rdRx: cb2, rdTx: cn2,
|
|
||||||
wrTx: cb1, wrRx: cn1,
|
|
||||||
localDone: done2, remoteDone: done1,
|
|
||||||
readDeadline: makePipeDeadline(),
|
|
||||||
writeDeadline: makePipeDeadline(),
|
|
||||||
}
|
|
||||||
return p1, p2
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*pipe) LocalAddr() net.Addr { return pipeAddr{} }
|
|
||||||
func (*pipe) RemoteAddr() net.Addr { return pipeAddr{} }
|
|
||||||
|
|
||||||
func (p *pipe) Read(b []byte) (int, error) {
|
|
||||||
n, err := p.read(b)
|
|
||||||
if err != nil && err != io.EOF && err != io.ErrClosedPipe {
|
|
||||||
err = &net.OpError{Op: "read", Net: "pipe", Err: err}
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) read(b []byte) (n int, err error) {
|
|
||||||
switch {
|
|
||||||
case isClosedChan(p.localDone):
|
|
||||||
return 0, io.ErrClosedPipe
|
|
||||||
case isClosedChan(p.remoteDone):
|
|
||||||
return 0, io.EOF
|
|
||||||
case isClosedChan(p.readDeadline.wait()):
|
|
||||||
return 0, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
|
|
||||||
select {
|
|
||||||
case bw := <-p.rdRx:
|
|
||||||
nr := copy(b, bw)
|
|
||||||
p.rdTx <- nr
|
|
||||||
return nr, nil
|
|
||||||
case <-p.localDone:
|
|
||||||
return 0, io.ErrClosedPipe
|
|
||||||
case <-p.remoteDone:
|
|
||||||
return 0, io.EOF
|
|
||||||
case <-p.readDeadline.wait():
|
|
||||||
return 0, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) Write(b []byte) (int, error) {
|
|
||||||
n, err := p.write(b)
|
|
||||||
if err != nil && err != io.ErrClosedPipe {
|
|
||||||
err = &net.OpError{Op: "write", Net: "pipe", Err: err}
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) write(b []byte) (n int, err error) {
|
|
||||||
switch {
|
|
||||||
case isClosedChan(p.localDone):
|
|
||||||
return 0, io.ErrClosedPipe
|
|
||||||
case isClosedChan(p.remoteDone):
|
|
||||||
return 0, io.ErrClosedPipe
|
|
||||||
case isClosedChan(p.writeDeadline.wait()):
|
|
||||||
return 0, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
|
|
||||||
p.wrMu.Lock() // Ensure entirety of b is written together
|
|
||||||
defer p.wrMu.Unlock()
|
|
||||||
for once := true; once || len(b) > 0; once = false {
|
|
||||||
select {
|
|
||||||
case p.wrTx <- b:
|
|
||||||
nw := <-p.wrRx
|
|
||||||
b = b[nw:]
|
|
||||||
n += nw
|
|
||||||
case <-p.localDone:
|
|
||||||
return n, io.ErrClosedPipe
|
|
||||||
case <-p.remoteDone:
|
|
||||||
return n, io.ErrClosedPipe
|
|
||||||
case <-p.writeDeadline.wait():
|
|
||||||
return n, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return n, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) SetDeadline(t time.Time) error {
|
|
||||||
if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
|
|
||||||
return io.ErrClosedPipe
|
|
||||||
}
|
|
||||||
p.readDeadline.set(t)
|
|
||||||
p.writeDeadline.set(t)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) SetReadDeadline(t time.Time) error {
|
|
||||||
if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
|
|
||||||
return io.ErrClosedPipe
|
|
||||||
}
|
|
||||||
p.readDeadline.set(t)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) SetWriteDeadline(t time.Time) error {
|
|
||||||
if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
|
|
||||||
return io.ErrClosedPipe
|
|
||||||
}
|
|
||||||
p.writeDeadline.set(t)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) Close() error {
|
|
||||||
p.once.Do(func() { close(p.localDone) })
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ N.ReadWaiter = (*pipe)(nil)
|
|
||||||
|
|
||||||
func (p *pipe) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool) {
|
|
||||||
p.readWaitOptions = options
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) WaitReadBuffer() (buffer *buf.Buffer, err error) {
|
|
||||||
buffer, err = p.waitReadBuffer()
|
|
||||||
if err != nil && err != io.EOF && err != io.ErrClosedPipe {
|
|
||||||
err = &net.OpError{Op: "read", Net: "pipe", Err: err}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *pipe) waitReadBuffer() (buffer *buf.Buffer, err error) {
|
|
||||||
switch {
|
|
||||||
case isClosedChan(p.localDone):
|
|
||||||
return nil, io.ErrClosedPipe
|
|
||||||
case isClosedChan(p.remoteDone):
|
|
||||||
return nil, io.EOF
|
|
||||||
case isClosedChan(p.readDeadline.wait()):
|
|
||||||
return nil, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case bw := <-p.rdRx:
|
|
||||||
buffer = p.readWaitOptions.NewBuffer()
|
|
||||||
var nr int
|
|
||||||
nr, err = buffer.Write(bw)
|
|
||||||
if err != nil {
|
|
||||||
buffer.Release()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
p.readWaitOptions.PostReturn(buffer)
|
|
||||||
p.rdTx <- nr
|
|
||||||
return
|
|
||||||
case <-p.localDone:
|
|
||||||
return nil, io.ErrClosedPipe
|
|
||||||
case <-p.remoteDone:
|
|
||||||
return nil, io.EOF
|
|
||||||
case <-p.readDeadline.wait():
|
|
||||||
return nil, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsPipe(conn any) bool {
|
|
||||||
_, ok := conn.(*pipe)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
@@ -3,9 +3,10 @@ package net
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/buf"
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
"github.com/metacubex/mihomo/common/once"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type earlyConn struct {
|
type earlyConn struct {
|
||||||
@@ -43,7 +44,8 @@ func (conn *earlyConn) Upstream() any {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (conn *earlyConn) Success() bool {
|
func (conn *earlyConn) Success() bool {
|
||||||
return once.Done(&conn.resOnce) && conn.resErr == nil
|
// atomic visit sync.Once.done
|
||||||
|
return atomic.LoadUint32((*uint32)(unsafe.Pointer(&conn.resOnce))) == 1 && conn.resErr == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (conn *earlyConn) ReaderReplaceable() bool {
|
func (conn *earlyConn) ReaderReplaceable() bool {
|
||||||
|
|||||||
@@ -24,16 +24,16 @@ type enhanceSingPacketConn struct {
|
|||||||
func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
var buff *buf.Buffer
|
var buff *buf.Buffer
|
||||||
var dest M.Socksaddr
|
var dest M.Socksaddr
|
||||||
rwOptions := N.ReadWaitOptions{}
|
newBuffer := func() *buf.Buffer {
|
||||||
|
buff = buf.NewPacket() // do not use stack buffer
|
||||||
|
return buff
|
||||||
|
}
|
||||||
if c.packetReadWaiter != nil {
|
if c.packetReadWaiter != nil {
|
||||||
c.packetReadWaiter.InitializeReadWaiter(rwOptions)
|
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
||||||
buff, dest, err = c.packetReadWaiter.WaitReadPacket()
|
defer c.packetReadWaiter.InitializeReadWaiter(nil)
|
||||||
|
dest, err = c.packetReadWaiter.WaitReadPacket()
|
||||||
} else {
|
} else {
|
||||||
buff = rwOptions.NewPacketBuffer()
|
dest, err = c.SingPacketConn.ReadPacket(newBuffer())
|
||||||
dest, err = c.SingPacketConn.ReadPacket(buff)
|
|
||||||
if buff != nil {
|
|
||||||
rwOptions.PostReturn(buff)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if dest.IsFqdn() {
|
if dest.IsFqdn() {
|
||||||
addr = dest
|
addr = dest
|
||||||
@@ -41,7 +41,9 @@ func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr ne
|
|||||||
addr = dest.UDPAddr()
|
addr = dest.UDPAddr()
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
buff.Release()
|
if buff != nil {
|
||||||
|
buff.Release()
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if buff == nil {
|
if buff == nil {
|
||||||
|
|||||||
@@ -4,72 +4,12 @@ package packet
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/pool"
|
|
||||||
|
|
||||||
"golang.org/x/sys/windows"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type enhanceUDPConn struct {
|
type enhanceUDPConn struct {
|
||||||
*net.UDPConn
|
*net.UDPConn
|
||||||
rawConn syscall.RawConn
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
if c.rawConn == nil {
|
return waitReadFrom(c.UDPConn)
|
||||||
c.rawConn, _ = c.UDPConn.SyscallConn()
|
|
||||||
}
|
|
||||||
var readErr error
|
|
||||||
hasData := false
|
|
||||||
err = c.rawConn.Read(func(fd uintptr) (done bool) {
|
|
||||||
if !hasData {
|
|
||||||
hasData = true
|
|
||||||
// golang's internal/poll.FD.RawRead will Use a zero-byte read as a way to get notified when this
|
|
||||||
// socket is readable if we return false. So the `recvfrom` syscall will not block the system thread.
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
readBuf := pool.Get(pool.UDPBufferSize)
|
|
||||||
put = func() {
|
|
||||||
_ = pool.Put(readBuf)
|
|
||||||
}
|
|
||||||
var readFrom windows.Sockaddr
|
|
||||||
var readN int
|
|
||||||
readN, readFrom, readErr = windows.Recvfrom(windows.Handle(fd), readBuf, 0)
|
|
||||||
if readN > 0 {
|
|
||||||
data = readBuf[:readN]
|
|
||||||
} else {
|
|
||||||
put()
|
|
||||||
put = nil
|
|
||||||
data = nil
|
|
||||||
}
|
|
||||||
if readErr == windows.WSAEWOULDBLOCK {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if readFrom != nil {
|
|
||||||
switch from := readFrom.(type) {
|
|
||||||
case *windows.SockaddrInet4:
|
|
||||||
ip := from.Addr // copy from.Addr; ip escapes, so this line allocates 4 bytes
|
|
||||||
addr = &net.UDPAddr{IP: ip[:], Port: from.Port}
|
|
||||||
case *windows.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
|
|
||||||
//}
|
|
||||||
hasData = false
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if readErr != nil {
|
|
||||||
err = readErr
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,9 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/net/deadline"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
"github.com/sagernet/sing/common/bufio/deadline"
|
||||||
"github.com/sagernet/sing/common/network"
|
"github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,16 +19,8 @@ type ExtendedConn = network.ExtendedConn
|
|||||||
type ExtendedWriter = network.ExtendedWriter
|
type ExtendedWriter = network.ExtendedWriter
|
||||||
type ExtendedReader = network.ExtendedReader
|
type ExtendedReader = network.ExtendedReader
|
||||||
|
|
||||||
var WriteBuffer = bufio.WriteBuffer
|
|
||||||
|
|
||||||
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
||||||
if deadline.IsPipe(conn) || deadline.IsPipe(network.UnwrapReader(conn)) {
|
return deadline.NewFallbackConn(conn)
|
||||||
return NewExtendedConn(conn) // pipe always have correctly deadline implement
|
|
||||||
}
|
|
||||||
if deadline.IsConn(conn) || deadline.IsConn(network.UnwrapReader(conn)) {
|
|
||||||
return NewExtendedConn(conn) // was a *deadline.Conn
|
|
||||||
}
|
|
||||||
return deadline.NewConn(conn)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NeedHandshake(conn any) bool {
|
func NeedHandshake(conn any) bool {
|
||||||
@@ -41,8 +32,6 @@ func NeedHandshake(conn any) bool {
|
|||||||
|
|
||||||
type CountFunc = network.CountFunc
|
type CountFunc = network.CountFunc
|
||||||
|
|
||||||
var Pipe = deadline.Pipe
|
|
||||||
|
|
||||||
// Relay copies between left and right bidirectionally.
|
// Relay copies between left and right bidirectionally.
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
defer runtime.KeepAlive(leftConn)
|
defer runtime.KeepAlive(leftConn)
|
||||||
|
|||||||
@@ -4,8 +4,11 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var KeepAliveInterval = 15 * time.Second
|
||||||
|
|
||||||
func SplitNetworkType(s string) (string, string, error) {
|
func SplitNetworkType(s string) (string, string, error) {
|
||||||
var (
|
var (
|
||||||
shecme string
|
shecme string
|
||||||
@@ -44,3 +47,10 @@ func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
|
|||||||
host, port, err = net.SplitHostPort(temp)
|
host, port, err = net.SplitHostPort(temp)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TCPKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
_ = tcp.SetKeepAlive(true)
|
||||||
|
_ = tcp.SetKeepAlivePeriod(KeepAliveInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -51,23 +51,3 @@ func UnMasked(p netip.Prefix) netip.Addr {
|
|||||||
}
|
}
|
||||||
return addr
|
return addr
|
||||||
}
|
}
|
||||||
|
|
||||||
// PrefixCompare returns an integer comparing two prefixes.
|
|
||||||
// The result will be 0 if p == p2, -1 if p < p2, and +1 if p > p2.
|
|
||||||
// modify from https://github.com/golang/go/issues/61642#issuecomment-1848587909
|
|
||||||
func PrefixCompare(p, p2 netip.Prefix) int {
|
|
||||||
// compare by validity, address family and prefix base address
|
|
||||||
if c := p.Masked().Addr().Compare(p2.Masked().Addr()); c != 0 {
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
// compare by prefix length
|
|
||||||
f1, f2 := p.Bits(), p2.Bits()
|
|
||||||
if f1 < f2 {
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
if f1 > f2 {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
// compare by prefix address
|
|
||||||
return p.Addr().Compare(p2.Addr())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
//go:build !go1.22
|
|
||||||
|
|
||||||
package once
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Once struct {
|
|
||||||
done uint32
|
|
||||||
m sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func Done(once *sync.Once) bool {
|
|
||||||
// atomic visit sync.Once.done
|
|
||||||
return atomic.LoadUint32((*uint32)(unsafe.Pointer(once))) == 1
|
|
||||||
}
|
|
||||||
|
|
||||||
func Reset(once *sync.Once) {
|
|
||||||
o := (*Once)(unsafe.Pointer(once))
|
|
||||||
o.m.Lock()
|
|
||||||
defer o.m.Unlock()
|
|
||||||
atomic.StoreUint32(&o.done, 0)
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
//go:build go1.22
|
|
||||||
|
|
||||||
package once
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Once struct {
|
|
||||||
done atomic.Uint32
|
|
||||||
m sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func Done(once *sync.Once) bool {
|
|
||||||
// atomic visit sync.Once.done
|
|
||||||
return (*atomic.Uint32)(unsafe.Pointer(once)).Load() == 1
|
|
||||||
}
|
|
||||||
|
|
||||||
func Reset(once *sync.Once) {
|
|
||||||
o := (*Once)(unsafe.Pointer(once))
|
|
||||||
o.m.Lock()
|
|
||||||
defer o.m.Unlock()
|
|
||||||
o.done.Store(0)
|
|
||||||
}
|
|
||||||
@@ -3,8 +3,8 @@ package pool
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/metacubex/randv2"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAllocGet(t *testing.T) {
|
func TestAllocGet(t *testing.T) {
|
||||||
@@ -43,6 +43,6 @@ func TestAllocPutThenGet(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkMSB(b *testing.B) {
|
func BenchmarkMSB(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
msb(randv2.Int())
|
msb(fastrand.Int())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,8 +59,8 @@ func (q *Queue[T]) Copy() []T {
|
|||||||
|
|
||||||
// Len returns the number of items in this queue.
|
// Len returns the number of items in this queue.
|
||||||
func (q *Queue[T]) Len() int64 {
|
func (q *Queue[T]) Len() int64 {
|
||||||
q.lock.RLock()
|
q.lock.Lock()
|
||||||
defer q.lock.RUnlock()
|
defer q.lock.Unlock()
|
||||||
|
|
||||||
return int64(len(q.items))
|
return int64(len(q.items))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
// copy and modify from "golang.org/x/sync/singleflight"
|
|
||||||
|
|
||||||
// Copyright 2013 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 singleflight provides a duplicate function call suppression
|
|
||||||
// mechanism.
|
|
||||||
package singleflight
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"runtime"
|
|
||||||
"runtime/debug"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// errGoexit indicates the runtime.Goexit was called in
|
|
||||||
// the user given function.
|
|
||||||
var errGoexit = errors.New("runtime.Goexit was called")
|
|
||||||
|
|
||||||
// A panicError is an arbitrary value recovered from a panic
|
|
||||||
// with the stack trace during the execution of given function.
|
|
||||||
type panicError struct {
|
|
||||||
value interface{}
|
|
||||||
stack []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// Error implements error interface.
|
|
||||||
func (p *panicError) Error() string {
|
|
||||||
return fmt.Sprintf("%v\n\n%s", p.value, p.stack)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *panicError) Unwrap() error {
|
|
||||||
err, ok := p.value.(error)
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func newPanicError(v interface{}) error {
|
|
||||||
stack := debug.Stack()
|
|
||||||
|
|
||||||
// The first line of the stack trace is of the form "goroutine N [status]:"
|
|
||||||
// but by the time the panic reaches Do the goroutine may no longer exist
|
|
||||||
// and its status will have changed. Trim out the misleading line.
|
|
||||||
if line := bytes.IndexByte(stack[:], '\n'); line >= 0 {
|
|
||||||
stack = stack[line+1:]
|
|
||||||
}
|
|
||||||
return &panicError{value: v, stack: stack}
|
|
||||||
}
|
|
||||||
|
|
||||||
// call is an in-flight or completed singleflight.Do call
|
|
||||||
type call[T any] struct {
|
|
||||||
wg sync.WaitGroup
|
|
||||||
|
|
||||||
// These fields are written once before the WaitGroup is done
|
|
||||||
// and are only read after the WaitGroup is done.
|
|
||||||
val T
|
|
||||||
err error
|
|
||||||
|
|
||||||
// These fields are read and written with the singleflight
|
|
||||||
// mutex held before the WaitGroup is done, and are read but
|
|
||||||
// not written after the WaitGroup is done.
|
|
||||||
dups int
|
|
||||||
chans []chan<- Result[T]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Group represents a class of work and forms a namespace in
|
|
||||||
// which units of work can be executed with duplicate suppression.
|
|
||||||
type Group[T any] struct {
|
|
||||||
mu sync.Mutex // protects m
|
|
||||||
m map[string]*call[T] // lazily initialized
|
|
||||||
|
|
||||||
StoreResult bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// Result holds the results of Do, so they can be passed
|
|
||||||
// on a channel.
|
|
||||||
type Result[T any] struct {
|
|
||||||
Val T
|
|
||||||
Err error
|
|
||||||
Shared bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do executes and returns the results of the given function, making
|
|
||||||
// sure that only one execution is in-flight for a given key at a
|
|
||||||
// time. If a duplicate comes in, the duplicate caller waits for the
|
|
||||||
// original to complete and receives the same results.
|
|
||||||
// The return value shared indicates whether v was given to multiple callers.
|
|
||||||
func (g *Group[T]) Do(key string, fn func() (T, error)) (v T, err error, shared bool) {
|
|
||||||
g.mu.Lock()
|
|
||||||
if g.m == nil {
|
|
||||||
g.m = make(map[string]*call[T])
|
|
||||||
}
|
|
||||||
if c, ok := g.m[key]; ok {
|
|
||||||
c.dups++
|
|
||||||
g.mu.Unlock()
|
|
||||||
c.wg.Wait()
|
|
||||||
|
|
||||||
if e, ok := c.err.(*panicError); ok {
|
|
||||||
panic(e)
|
|
||||||
} else if c.err == errGoexit {
|
|
||||||
runtime.Goexit()
|
|
||||||
}
|
|
||||||
return c.val, c.err, true
|
|
||||||
}
|
|
||||||
c := new(call[T])
|
|
||||||
c.wg.Add(1)
|
|
||||||
g.m[key] = c
|
|
||||||
g.mu.Unlock()
|
|
||||||
|
|
||||||
g.doCall(c, key, fn)
|
|
||||||
return c.val, c.err, c.dups > 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoChan is like Do but returns a channel that will receive the
|
|
||||||
// results when they are ready.
|
|
||||||
//
|
|
||||||
// The returned channel will not be closed.
|
|
||||||
func (g *Group[T]) DoChan(key string, fn func() (T, error)) <-chan Result[T] {
|
|
||||||
ch := make(chan Result[T], 1)
|
|
||||||
g.mu.Lock()
|
|
||||||
if g.m == nil {
|
|
||||||
g.m = make(map[string]*call[T])
|
|
||||||
}
|
|
||||||
if c, ok := g.m[key]; ok {
|
|
||||||
c.dups++
|
|
||||||
c.chans = append(c.chans, ch)
|
|
||||||
g.mu.Unlock()
|
|
||||||
return ch
|
|
||||||
}
|
|
||||||
c := &call[T]{chans: []chan<- Result[T]{ch}}
|
|
||||||
c.wg.Add(1)
|
|
||||||
g.m[key] = c
|
|
||||||
g.mu.Unlock()
|
|
||||||
|
|
||||||
go g.doCall(c, key, fn)
|
|
||||||
|
|
||||||
return ch
|
|
||||||
}
|
|
||||||
|
|
||||||
// doCall handles the single call for a key.
|
|
||||||
func (g *Group[T]) doCall(c *call[T], key string, fn func() (T, error)) {
|
|
||||||
normalReturn := false
|
|
||||||
recovered := false
|
|
||||||
|
|
||||||
// use double-defer to distinguish panic from runtime.Goexit,
|
|
||||||
// more details see https://golang.org/cl/134395
|
|
||||||
defer func() {
|
|
||||||
// the given function invoked runtime.Goexit
|
|
||||||
if !normalReturn && !recovered {
|
|
||||||
c.err = errGoexit
|
|
||||||
}
|
|
||||||
|
|
||||||
g.mu.Lock()
|
|
||||||
defer g.mu.Unlock()
|
|
||||||
c.wg.Done()
|
|
||||||
if g.m[key] == c && !g.StoreResult {
|
|
||||||
delete(g.m, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
if e, ok := c.err.(*panicError); ok {
|
|
||||||
// In order to prevent the waiting channels from being blocked forever,
|
|
||||||
// needs to ensure that this panic cannot be recovered.
|
|
||||||
if len(c.chans) > 0 {
|
|
||||||
go panic(e)
|
|
||||||
select {} // Keep this goroutine around so that it will appear in the crash dump.
|
|
||||||
} else {
|
|
||||||
panic(e)
|
|
||||||
}
|
|
||||||
} else if c.err == errGoexit {
|
|
||||||
// Already in the process of goexit, no need to call again
|
|
||||||
} else {
|
|
||||||
// Normal return
|
|
||||||
for _, ch := range c.chans {
|
|
||||||
ch <- Result[T]{c.val, c.err, c.dups > 0}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
func() {
|
|
||||||
defer func() {
|
|
||||||
if !normalReturn {
|
|
||||||
// Ideally, we would wait to take a stack trace until we've determined
|
|
||||||
// whether this is a panic or a runtime.Goexit.
|
|
||||||
//
|
|
||||||
// Unfortunately, the only way we can distinguish the two is to see
|
|
||||||
// whether the recover stopped the goroutine from terminating, and by
|
|
||||||
// the time we know that, the part of the stack trace relevant to the
|
|
||||||
// panic has been discarded.
|
|
||||||
if r := recover(); r != nil {
|
|
||||||
c.err = newPanicError(r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
c.val, c.err = fn()
|
|
||||||
normalReturn = true
|
|
||||||
}()
|
|
||||||
|
|
||||||
if !normalReturn {
|
|
||||||
recovered = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Forget tells the singleflight to forget about a key. Future calls
|
|
||||||
// to Do for this key will call the function rather than waiting for
|
|
||||||
// an earlier call to complete.
|
|
||||||
func (g *Group[T]) Forget(key string) {
|
|
||||||
g.mu.Lock()
|
|
||||||
delete(g.m, key)
|
|
||||||
g.mu.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *Group[T]) Reset() {
|
|
||||||
g.mu.Lock()
|
|
||||||
g.m = nil
|
|
||||||
g.mu.Unlock()
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ package structure
|
|||||||
// references: https://github.com/mitchellh/mapstructure
|
// references: https://github.com/mitchellh/mapstructure
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding"
|
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
@@ -87,41 +86,35 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
||||||
for {
|
kind := val.Kind()
|
||||||
kind := val.Kind()
|
switch {
|
||||||
if kind == reflect.Pointer && val.IsNil() {
|
case isInt(kind):
|
||||||
|
return d.decodeInt(name, data, val)
|
||||||
|
case isUint(kind):
|
||||||
|
return d.decodeUint(name, data, val)
|
||||||
|
case isFloat(kind):
|
||||||
|
return d.decodeFloat(name, data, val)
|
||||||
|
}
|
||||||
|
switch kind {
|
||||||
|
case reflect.Pointer:
|
||||||
|
if val.IsNil() {
|
||||||
val.Set(reflect.New(val.Type().Elem()))
|
val.Set(reflect.New(val.Type().Elem()))
|
||||||
}
|
}
|
||||||
if ok, err := d.decodeTextUnmarshaller(name, data, val); ok {
|
return d.decode(name, data, val.Elem())
|
||||||
return err
|
case reflect.String:
|
||||||
}
|
return d.decodeString(name, data, val)
|
||||||
switch {
|
case reflect.Bool:
|
||||||
case isInt(kind):
|
return d.decodeBool(name, data, val)
|
||||||
return d.decodeInt(name, data, val)
|
case reflect.Slice:
|
||||||
case isUint(kind):
|
return d.decodeSlice(name, data, val)
|
||||||
return d.decodeUint(name, data, val)
|
case reflect.Map:
|
||||||
case isFloat(kind):
|
return d.decodeMap(name, data, val)
|
||||||
return d.decodeFloat(name, data, val)
|
case reflect.Interface:
|
||||||
}
|
return d.setInterface(name, data, val)
|
||||||
switch kind {
|
case reflect.Struct:
|
||||||
case reflect.Pointer:
|
return d.decodeStruct(name, data, val)
|
||||||
val = val.Elem()
|
default:
|
||||||
continue
|
return fmt.Errorf("type %s not support", val.Kind().String())
|
||||||
case reflect.String:
|
|
||||||
return d.decodeString(name, data, val)
|
|
||||||
case reflect.Bool:
|
|
||||||
return d.decodeBool(name, data, val)
|
|
||||||
case reflect.Slice:
|
|
||||||
return d.decodeSlice(name, data, val)
|
|
||||||
case reflect.Map:
|
|
||||||
return d.decodeMap(name, data, val)
|
|
||||||
case reflect.Interface:
|
|
||||||
return d.setInterface(name, data, val)
|
|
||||||
case reflect.Struct:
|
|
||||||
return d.decodeStruct(name, data, val)
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("type %s not support", val.Kind().String())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -560,25 +553,3 @@ func (d *Decoder) setInterface(name string, data any, val reflect.Value) (err er
|
|||||||
val.Set(dataVal)
|
val.Set(dataVal)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeTextUnmarshaller(name string, data any, val reflect.Value) (bool, error) {
|
|
||||||
if !val.CanAddr() {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
valAddr := val.Addr()
|
|
||||||
if !valAddr.CanInterface() {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
unmarshaller, ok := valAddr.Interface().(encoding.TextUnmarshaler)
|
|
||||||
if !ok {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
var str string
|
|
||||||
if err := d.decodeString(name, data, reflect.Indirect(reflect.ValueOf(&str))); err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
if err := unmarshaller.UnmarshalText([]byte(str)); err != nil {
|
|
||||||
return true, fmt.Errorf("cannot parse '%s' as %s: %s", name, val.Type(), err)
|
|
||||||
}
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package structure
|
package structure
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"strconv"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -180,90 +179,3 @@ func TestStructure_SliceNilValueComplex(t *testing.T) {
|
|||||||
err = decoder.Decode(rawMap, ss)
|
err = decoder.Decode(rawMap, ss)
|
||||||
assert.NotNil(t, err)
|
assert.NotNil(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_SliceCap(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"foo": []string{},
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &struct {
|
|
||||||
Foo []string `test:"foo,omitempty"`
|
|
||||||
Bar []string `test:"bar,omitempty"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err := decoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.NotNil(t, s.Foo) // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
|
||||||
assert.Nil(t, s.Bar)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStructure_Base64(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"foo": "AQID",
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &struct {
|
|
||||||
Foo []byte `test:"foo"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err := decoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, []byte{1, 2, 3}, s.Foo)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStructure_Pointer(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"foo": "foo",
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &struct {
|
|
||||||
Foo *string `test:"foo,omitempty"`
|
|
||||||
Bar *string `test:"bar,omitempty"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err := decoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.NotNil(t, s.Foo)
|
|
||||||
assert.Equal(t, "foo", *s.Foo)
|
|
||||||
assert.Nil(t, s.Bar)
|
|
||||||
}
|
|
||||||
|
|
||||||
type num struct {
|
|
||||||
a int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *num) UnmarshalText(text []byte) (err error) {
|
|
||||||
n.a, err = strconv.Atoi(string(text))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStructure_TextUnmarshaller(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"num": "255",
|
|
||||||
"num_p": "127",
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &struct {
|
|
||||||
Num num `test:"num"`
|
|
||||||
NumP *num `test:"num_p"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err := decoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, 255, s.Num.a)
|
|
||||||
assert.NotNil(t, s.NumP)
|
|
||||||
assert.Equal(t, s.NumP.a, 127)
|
|
||||||
|
|
||||||
// test WeaklyTypedInput
|
|
||||||
rawMap["num"] = 256
|
|
||||||
err = decoder.Decode(rawMap, s)
|
|
||||||
assert.NotNilf(t, err, "should throw error: %#v", s)
|
|
||||||
err = weakTypeDecoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, 256, s.Num.a)
|
|
||||||
|
|
||||||
// test invalid input
|
|
||||||
rawMap["num_p"] = "abc"
|
|
||||||
err = decoder.Decode(rawMap, s)
|
|
||||||
assert.NotNilf(t, err, "should throw error: %#v", s)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
list "github.com/bahlo/generic-list-go"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Callback[T any] struct {
|
|
||||||
list list.List[func(T)]
|
|
||||||
mutex sync.RWMutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCallback[T any]() *Callback[T] {
|
|
||||||
return &Callback[T]{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Callback[T]) Register(item func(T)) io.Closer {
|
|
||||||
c.mutex.Lock()
|
|
||||||
defer c.mutex.Unlock()
|
|
||||||
element := c.list.PushBack(item)
|
|
||||||
return &callbackCloser[T]{
|
|
||||||
element: element,
|
|
||||||
callback: c,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Callback[T]) Emit(item T) {
|
|
||||||
c.mutex.RLock()
|
|
||||||
defer c.mutex.RUnlock()
|
|
||||||
for element := c.list.Front(); element != nil; element = element.Next() {
|
|
||||||
go element.Value(item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type callbackCloser[T any] struct {
|
|
||||||
element *list.Element[func(T)]
|
|
||||||
callback *Callback[T]
|
|
||||||
once sync.Once
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *callbackCloser[T]) Close() error {
|
|
||||||
c.once.Do(func() {
|
|
||||||
c.callback.mutex.Lock()
|
|
||||||
defer c.callback.mutex.Unlock()
|
|
||||||
c.callback.list.Remove(c.element)
|
|
||||||
})
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/md5"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// HashType warps hash array inside struct
|
|
||||||
// someday can change to other hash algorithm simply
|
|
||||||
type HashType struct {
|
|
||||||
md5 [md5.Size]byte // MD5
|
|
||||||
}
|
|
||||||
|
|
||||||
func MakeHash(data []byte) HashType {
|
|
||||||
return HashType{md5.Sum(data)}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h HashType) Equal(hash HashType) bool {
|
|
||||||
return h.md5 == hash.md5
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h HashType) Bytes() []byte {
|
|
||||||
return h.md5[:]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h HashType) String() string {
|
|
||||||
return hex.EncodeToString(h.Bytes())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h HashType) MarshalText() ([]byte, error) {
|
|
||||||
return []byte(h.String()), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HashType) UnmarshalText(data []byte) error {
|
|
||||||
if hex.DecodedLen(len(data)) != md5.Size {
|
|
||||||
return errors.New("invalid hash length")
|
|
||||||
}
|
|
||||||
_, err := hex.Decode(h.md5[:], data)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h HashType) MarshalBinary() ([]byte, error) {
|
|
||||||
return h.md5[:], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HashType) UnmarshalBinary(data []byte) error {
|
|
||||||
if len(data) != md5.Size {
|
|
||||||
return errors.New("invalid hash length")
|
|
||||||
}
|
|
||||||
copy(h.md5[:], data)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h HashType) Len() int {
|
|
||||||
return len(h.md5)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h HashType) IsValid() bool {
|
|
||||||
var zero HashType
|
|
||||||
return h != zero
|
|
||||||
}
|
|
||||||
@@ -13,24 +13,22 @@ type IntRanges[T constraints.Integer] []Range[T]
|
|||||||
|
|
||||||
var errIntRanges = errors.New("intRanges error")
|
var errIntRanges = errors.New("intRanges error")
|
||||||
|
|
||||||
func newIntRanges[T constraints.Integer](expected string, parseFn func(string) (T, error)) (IntRanges[T], 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
|
// example: 200 or 200/302 or 200-400 or 200/204/401-429/501-503
|
||||||
expected = strings.TrimSpace(expected)
|
expected = strings.TrimSpace(expected)
|
||||||
if len(expected) == 0 || expected == "*" {
|
if len(expected) == 0 || expected == "*" {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// support: 200,302 or 200,204,401-429,501-503
|
|
||||||
expected = strings.ReplaceAll(expected, ",", "/")
|
|
||||||
list := strings.Split(expected, "/")
|
list := strings.Split(expected, "/")
|
||||||
if len(list) > 28 {
|
if len(list) > 28 {
|
||||||
return nil, fmt.Errorf("%w, too many ranges to use, maximum support 28 ranges", errIntRanges)
|
return nil, fmt.Errorf("%w, too many ranges to use, maximum support 28 ranges", errIntRanges)
|
||||||
}
|
}
|
||||||
|
|
||||||
return newIntRangesFromList[T](list, parseFn)
|
return NewIntRangesFromList[T](list)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newIntRangesFromList[T constraints.Integer](list []string, parseFn func(string) (T, error)) (IntRanges[T], error) {
|
func NewIntRangesFromList[T constraints.Integer](list []string) (IntRanges[T], error) {
|
||||||
var ranges IntRanges[T]
|
var ranges IntRanges[T]
|
||||||
for _, s := range list {
|
for _, s := range list {
|
||||||
if s == "" {
|
if s == "" {
|
||||||
@@ -43,16 +41,16 @@ func newIntRangesFromList[T constraints.Integer](list []string, parseFn func(str
|
|||||||
return nil, errIntRanges
|
return nil, errIntRanges
|
||||||
}
|
}
|
||||||
|
|
||||||
start, err := parseFn(strings.Trim(status[0], "[ ]"))
|
start, err := strconv.ParseInt(strings.Trim(status[0], "[ ]"), 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errIntRanges
|
return nil, errIntRanges
|
||||||
}
|
}
|
||||||
|
|
||||||
switch statusLen {
|
switch statusLen {
|
||||||
case 1: // Port range
|
case 1:
|
||||||
ranges = append(ranges, NewRange(T(start), T(start)))
|
ranges = append(ranges, NewRange(T(start), T(start)))
|
||||||
case 2: // Single port
|
case 2:
|
||||||
end, err := parseFn(strings.Trim(status[1], "[ ]"))
|
end, err := strconv.ParseUint(strings.Trim(status[1], "[ ]"), 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errIntRanges
|
return nil, errIntRanges
|
||||||
}
|
}
|
||||||
@@ -64,38 +62,6 @@ func newIntRangesFromList[T constraints.Integer](list []string, parseFn func(str
|
|||||||
return ranges, nil
|
return ranges, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseUnsigned[T constraints.Unsigned](s string) (T, error) {
|
|
||||||
if val, err := strconv.ParseUint(s, 10, 64); err == nil {
|
|
||||||
return T(val), nil
|
|
||||||
} else {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUnsignedRanges[T constraints.Unsigned](expected string) (IntRanges[T], error) {
|
|
||||||
return newIntRanges(expected, parseUnsigned[T])
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUnsignedRangesFromList[T constraints.Unsigned](list []string) (IntRanges[T], error) {
|
|
||||||
return newIntRangesFromList(list, parseUnsigned[T])
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseSigned[T constraints.Signed](s string) (T, error) {
|
|
||||||
if val, err := strconv.ParseInt(s, 10, 64); err == nil {
|
|
||||||
return T(val), nil
|
|
||||||
} else {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSignedRanges[T constraints.Signed](expected string) (IntRanges[T], error) {
|
|
||||||
return newIntRanges(expected, parseSigned[T])
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSignedRangesFromList[T constraints.Signed](list []string) (IntRanges[T], error) {
|
|
||||||
return newIntRangesFromList(list, parseSigned[T])
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ranges IntRanges[T]) Check(status T) bool {
|
func (ranges IntRanges[T]) Check(status T) bool {
|
||||||
if len(ranges) == 0 {
|
if len(ranges) == 0 {
|
||||||
return true
|
return true
|
||||||
@@ -110,7 +76,7 @@ func (ranges IntRanges[T]) Check(status T) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ranges IntRanges[T]) String() string {
|
func (ranges IntRanges[T]) ToString() string {
|
||||||
if len(ranges) == 0 {
|
if len(ranges) == 0 {
|
||||||
return "*"
|
return "*"
|
||||||
}
|
}
|
||||||
@@ -132,17 +98,3 @@ func (ranges IntRanges[T]) String() string {
|
|||||||
|
|
||||||
return strings.Join(terms, "/")
|
return strings.Join(terms, "/")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ranges IntRanges[T]) Range(f func(t T) bool) {
|
|
||||||
if len(ranges) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, r := range ranges {
|
|
||||||
for i := r.Start(); i <= r.End(); i++ {
|
|
||||||
if !f(i) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,39 +2,19 @@ package utils
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gofrs/uuid/v5"
|
"github.com/gofrs/uuid/v5"
|
||||||
"github.com/metacubex/randv2"
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
type unsafeRandReader struct{}
|
type fastRandReader struct{}
|
||||||
|
|
||||||
func (r unsafeRandReader) Read(p []byte) (n int, err error) {
|
func (r fastRandReader) Read(p []byte) (int, error) {
|
||||||
// modify from https://github.com/golang/go/blob/587c3847da81aa7cfc3b3db2677c8586c94df13a/src/runtime/rand.go#L70-L89
|
return fastrand.Read(p)
|
||||||
// Inspired by wyrand.
|
|
||||||
n = len(p)
|
|
||||||
v := randv2.Uint64()
|
|
||||||
for len(p) > 0 {
|
|
||||||
v ^= 0xa0761d6478bd642f
|
|
||||||
v *= 0xe7037ed1a0b428db
|
|
||||||
size := 8
|
|
||||||
if len(p) < 8 {
|
|
||||||
size = len(p)
|
|
||||||
}
|
|
||||||
for i := 0; i < size; i++ {
|
|
||||||
p[i] ^= byte(v >> (8 * i))
|
|
||||||
}
|
|
||||||
p = p[size:]
|
|
||||||
v = v>>32 | v<<32
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var UnsafeRandReader = unsafeRandReader{}
|
var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(fastRandReader{}))
|
||||||
|
|
||||||
var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(UnsafeRandReader))
|
|
||||||
|
|
||||||
func NewUUIDV1() uuid.UUID {
|
func NewUUIDV1() uuid.UUID {
|
||||||
u, _ := UnsafeUUIDGenerator.NewV1() // unsafeRandReader wouldn't cause error, so ignore err is safe
|
u, _ := UnsafeUUIDGenerator.NewV1() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,7 +23,7 @@ func NewUUIDV3(ns uuid.UUID, name string) uuid.UUID {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewUUIDV4() uuid.UUID {
|
func NewUUIDV4() uuid.UUID {
|
||||||
u, _ := UnsafeUUIDGenerator.NewV4() // unsafeRandReader wouldn't cause error, so ignore err is safe
|
u, _ := UnsafeUUIDGenerator.NewV4() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,12 +32,12 @@ func NewUUIDV5(ns uuid.UUID, name string) uuid.UUID {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewUUIDV6() uuid.UUID {
|
func NewUUIDV6() uuid.UUID {
|
||||||
u, _ := UnsafeUUIDGenerator.NewV6() // unsafeRandReader wouldn't cause error, so ignore err is safe
|
u, _ := UnsafeUUIDGenerator.NewV6() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUUIDV7() uuid.UUID {
|
func NewUUIDV7() uuid.UUID {
|
||||||
u, _ := UnsafeUUIDGenerator.NewV7() // unsafeRandReader wouldn't cause error, so ignore err is safe
|
u, _ := UnsafeUUIDGenerator.NewV7() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,11 +5,6 @@ type Authenticator interface {
|
|||||||
Users() []string
|
Users() []string
|
||||||
}
|
}
|
||||||
|
|
||||||
type AuthStore interface {
|
|
||||||
Authenticator() Authenticator
|
|
||||||
SetAuthenticator(Authenticator)
|
|
||||||
}
|
|
||||||
|
|
||||||
type AuthUser struct {
|
type AuthUser struct {
|
||||||
User string
|
User string
|
||||||
Pass string
|
Pass string
|
||||||
|
|||||||
@@ -5,16 +5,12 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
_ "embed"
|
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var trustCerts []*x509.Certificate
|
var trustCerts []*x509.Certificate
|
||||||
@@ -22,11 +18,6 @@ var globalCertPool *x509.CertPool
|
|||||||
var mutex sync.RWMutex
|
var mutex sync.RWMutex
|
||||||
var errNotMatch = errors.New("certificate fingerprints do not match")
|
var errNotMatch = errors.New("certificate fingerprints do not match")
|
||||||
|
|
||||||
//go:embed ca-certificates.crt
|
|
||||||
var _CaCertificates []byte
|
|
||||||
var DisableEmbedCa, _ = strconv.ParseBool(os.Getenv("DISABLE_EMBED_CA"))
|
|
||||||
var DisableSystemCa, _ = strconv.ParseBool(os.Getenv("DISABLE_SYSTEM_CA"))
|
|
||||||
|
|
||||||
func AddCertificate(certificate string) error {
|
func AddCertificate(certificate string) error {
|
||||||
mutex.Lock()
|
mutex.Lock()
|
||||||
defer mutex.Unlock()
|
defer mutex.Unlock()
|
||||||
@@ -43,20 +34,13 @@ func AddCertificate(certificate string) error {
|
|||||||
|
|
||||||
func initializeCertPool() {
|
func initializeCertPool() {
|
||||||
var err error
|
var err error
|
||||||
if DisableSystemCa {
|
globalCertPool, err = x509.SystemCertPool()
|
||||||
|
if err != nil {
|
||||||
globalCertPool = x509.NewCertPool()
|
globalCertPool = x509.NewCertPool()
|
||||||
} else {
|
|
||||||
globalCertPool, err = x509.SystemCertPool()
|
|
||||||
if err != nil {
|
|
||||||
globalCertPool = x509.NewCertPool()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
for _, cert := range trustCerts {
|
for _, cert := range trustCerts {
|
||||||
globalCertPool.AddCert(cert)
|
globalCertPool.AddCert(cert)
|
||||||
}
|
}
|
||||||
if !DisableEmbedCa {
|
|
||||||
globalCertPool.AppendCertsFromPEM(_CaCertificates)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResetCertificate() {
|
func ResetCertificate() {
|
||||||
@@ -67,6 +51,9 @@ func ResetCertificate() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getCertPool() *x509.CertPool {
|
func getCertPool() *x509.CertPool {
|
||||||
|
if len(trustCerts) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if globalCertPool == nil {
|
if globalCertPool == nil {
|
||||||
mutex.Lock()
|
mutex.Lock()
|
||||||
defer mutex.Unlock()
|
defer mutex.Unlock()
|
||||||
@@ -116,7 +103,7 @@ func GetTLSConfig(tlsConfig *tls.Config, fingerprint string, customCA string, cu
|
|||||||
var certificate []byte
|
var certificate []byte
|
||||||
var err error
|
var err error
|
||||||
if len(customCA) > 0 {
|
if len(customCA) > 0 {
|
||||||
certificate, err = os.ReadFile(C.Path.Resolve(customCA))
|
certificate, err = os.ReadFile(customCA)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("load ca error: %w", err)
|
return nil, fmt.Errorf("load ca error: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
package ca
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/metacubex/mihomo/constant/features"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
// crypto/x509: certificate validation in Windows fails to validate IP in SAN
|
|
||||||
// https://github.com/golang/go/issues/37176
|
|
||||||
// As far as I can tell this is still the case on most older versions of Windows (but seems to be fixed in 10)
|
|
||||||
if features.WindowsMajorVersion < 10 && len(_CaCertificates) > 0 {
|
|
||||||
DisableSystemCa = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
package cidr
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"go4.org/netipx"
|
|
||||||
)
|
|
||||||
|
|
||||||
type IpCidrSet struct {
|
|
||||||
// must same with netipx.IPSet
|
|
||||||
rr []netipx.IPRange
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewIpCidrSet() *IpCidrSet {
|
|
||||||
return &IpCidrSet{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (set *IpCidrSet) AddIpCidrForString(ipCidr string) error {
|
|
||||||
prefix, err := netip.ParsePrefix(ipCidr)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return set.AddIpCidr(prefix)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (set *IpCidrSet) AddIpCidr(ipCidr netip.Prefix) (err error) {
|
|
||||||
if r := netipx.RangeOfPrefix(ipCidr); r.IsValid() {
|
|
||||||
set.rr = append(set.rr, r)
|
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("not valid ipcidr range: %s", ipCidr)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (set *IpCidrSet) IsContainForString(ipString string) bool {
|
|
||||||
ip, err := netip.ParseAddr(ipString)
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return set.IsContain(ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (set *IpCidrSet) IsContain(ip netip.Addr) bool {
|
|
||||||
return set.ToIPSet().Contains(ip.WithZone(""))
|
|
||||||
}
|
|
||||||
|
|
||||||
// MatchIp implements C.IpMatcher
|
|
||||||
func (set *IpCidrSet) MatchIp(ip netip.Addr) bool {
|
|
||||||
if set.IsEmpty() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return set.IsContain(ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (set *IpCidrSet) Merge() error {
|
|
||||||
var b netipx.IPSetBuilder
|
|
||||||
b.AddSet(set.ToIPSet())
|
|
||||||
i, err := b.IPSet()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
set.fromIPSet(i)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (set *IpCidrSet) IsEmpty() bool {
|
|
||||||
return set == nil || len(set.rr) == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (set *IpCidrSet) Foreach(f func(prefix netip.Prefix) bool) {
|
|
||||||
for _, r := range set.rr {
|
|
||||||
for _, prefix := range r.Prefixes() {
|
|
||||||
if !f(prefix) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ToIPSet not safe convert to *netipx.IPSet
|
|
||||||
// be careful, must be used after Merge
|
|
||||||
func (set *IpCidrSet) ToIPSet() *netipx.IPSet {
|
|
||||||
return (*netipx.IPSet)(unsafe.Pointer(set))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (set *IpCidrSet) fromIPSet(i *netipx.IPSet) {
|
|
||||||
*set = *(*IpCidrSet)(unsafe.Pointer(i))
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package cidr
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"go4.org/netipx"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (ss *IpCidrSet) WriteBin(w io.Writer) (err error) {
|
|
||||||
// version
|
|
||||||
_, err = w.Write([]byte{1})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// rr
|
|
||||||
err = binary.Write(w, binary.BigEndian, int64(len(ss.rr)))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, r := range ss.rr {
|
|
||||||
err = binary.Write(w, binary.BigEndian, r.From().As16())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = binary.Write(w, binary.BigEndian, r.To().As16())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ReadIpCidrSet(r io.Reader) (ss *IpCidrSet, err error) {
|
|
||||||
// version
|
|
||||||
version := make([]byte, 1)
|
|
||||||
_, err = io.ReadFull(r, version)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if version[0] != 1 {
|
|
||||||
return nil, errors.New("version is invalid")
|
|
||||||
}
|
|
||||||
|
|
||||||
ss = NewIpCidrSet()
|
|
||||||
var length int64
|
|
||||||
|
|
||||||
// rr
|
|
||||||
err = binary.Read(r, binary.BigEndian, &length)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if length < 1 {
|
|
||||||
return nil, errors.New("length is invalid")
|
|
||||||
}
|
|
||||||
ss.rr = make([]netipx.IPRange, length)
|
|
||||||
for i := int64(0); i < length; i++ {
|
|
||||||
var a16 [16]byte
|
|
||||||
err = binary.Read(r, binary.BigEndian, &a16)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
from := netip.AddrFrom16(a16).Unmap()
|
|
||||||
err = binary.Read(r, binary.BigEndian, &a16)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
to := netip.AddrFrom16(a16).Unmap()
|
|
||||||
ss.rr[i] = netipx.IPRangeFrom(from, to)
|
|
||||||
}
|
|
||||||
|
|
||||||
return ss, nil
|
|
||||||
}
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
package cidr
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestIpv4(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
ipCidr string
|
|
||||||
ip string
|
|
||||||
expected bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Test Case 1",
|
|
||||||
ipCidr: "149.154.160.0/20",
|
|
||||||
ip: "149.154.160.0",
|
|
||||||
expected: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test Case 2",
|
|
||||||
ipCidr: "192.168.0.0/16",
|
|
||||||
ip: "10.0.0.1",
|
|
||||||
expected: false,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
set := &IpCidrSet{}
|
|
||||||
set.AddIpCidrForString(test.ipCidr)
|
|
||||||
|
|
||||||
result := set.IsContainForString(test.ip)
|
|
||||||
if result != test.expected {
|
|
||||||
t.Errorf("Expected result: %v, got: %v", test.expected, result)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIpv6(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
ipCidr string
|
|
||||||
ip string
|
|
||||||
expected bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Test Case 1",
|
|
||||||
ipCidr: "2409:8000::/20",
|
|
||||||
ip: "2409:8087:1e03:21::27",
|
|
||||||
expected: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Test Case 2",
|
|
||||||
ipCidr: "240e::/16",
|
|
||||||
ip: "240e:964:ea02:100:1800::71",
|
|
||||||
expected: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
// Add more test cases as needed
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
set := &IpCidrSet{}
|
|
||||||
set.AddIpCidrForString(test.ipCidr)
|
|
||||||
|
|
||||||
result := set.IsContainForString(test.ip)
|
|
||||||
if result != test.expected {
|
|
||||||
t.Errorf("Expected result: %v, got: %v", test.expected, result)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMerge(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
ipCidr1 string
|
|
||||||
ipCidr2 string
|
|
||||||
ipCidr3 string
|
|
||||||
expectedLen int
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Test Case 1",
|
|
||||||
ipCidr1: "2409:8000::/20",
|
|
||||||
ipCidr2: "2409:8000::/21",
|
|
||||||
ipCidr3: "2409:8000::/48",
|
|
||||||
expectedLen: 1,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
set := &IpCidrSet{}
|
|
||||||
set.AddIpCidrForString(test.ipCidr1)
|
|
||||||
set.AddIpCidrForString(test.ipCidr2)
|
|
||||||
set.Merge()
|
|
||||||
|
|
||||||
rangesLen := len(set.rr)
|
|
||||||
|
|
||||||
if rangesLen != test.expectedLen {
|
|
||||||
t.Errorf("Expected len: %v, got: %v", test.expectedLen, rangesLen)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ package dhcp
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
@@ -25,5 +24,5 @@ func ListenDHCPClient(ctx context.Context, ifaceName string) (net.PacketConn, er
|
|||||||
options = append(options, dialer.WithFallbackBind(true))
|
options = append(options, dialer.WithFallbackBind(true))
|
||||||
}
|
}
|
||||||
|
|
||||||
return dialer.ListenPacket(ctx, "udp4", listenAddr, netip.AddrPortFrom(netip.AddrFrom4([4]byte{255, 255, 255, 255}), 67), options...)
|
return dialer.ListenPacket(ctx, "udp4", listenAddr, options...)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ func LookupLocalAddrFromIfaceName(ifaceName string, network string, destination
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
destination = destination.Unmap()
|
|
||||||
|
|
||||||
var addr netip.Prefix
|
var addr netip.Prefix
|
||||||
switch network {
|
switch network {
|
||||||
@@ -24,7 +23,7 @@ func LookupLocalAddrFromIfaceName(ifaceName string, network string, destination
|
|||||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||||
default:
|
default:
|
||||||
if destination.IsValid() {
|
if destination.IsValid() {
|
||||||
if destination.Is4() {
|
if destination.Is4() || destination.Is4In6() {
|
||||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||||
} else {
|
} else {
|
||||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||||
@@ -75,7 +74,7 @@ func fallbackBindIfaceToDialer(ifaceName string, dialer *net.Dialer, network str
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func fallbackBindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, address string, rAddrPort netip.AddrPort) (string, error) {
|
func fallbackBindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, address string) (string, error) {
|
||||||
_, port, err := net.SplitHostPort(address)
|
_, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
port = "0"
|
port = "0"
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.A
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string, rAddrPort netip.AddrPort) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
||||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.A
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string, rAddrPort netip.AddrPort) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
||||||
addControlToListenConfig(lc, bindControl(ifaceName))
|
addControlToListenConfig(lc, bindControl(ifaceName))
|
||||||
|
|
||||||
return address, nil
|
return address, nil
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, des
|
|||||||
return fallbackBindIfaceToDialer(ifaceName, dialer, network, destination)
|
return fallbackBindIfaceToDialer(ifaceName, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, network, address string, rAddrPort netip.AddrPort) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, network, address string) (string, error) {
|
||||||
return fallbackBindIfaceToListenConfig(ifaceName, lc, network, address, rAddrPort)
|
return fallbackBindIfaceToListenConfig(ifaceName, lc, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseNetwork(network string, addr netip.Addr) string {
|
func ParseNetwork(network string, addr netip.Addr) string {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user