mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-02-28 09:39:54 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0fd6cfeea | ||
|
|
1f7a883bfc | ||
|
|
3fd954d185 | ||
|
|
2092a481b3 |
83
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
83
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -1,83 +0,0 @@
|
|||||||
name: Bug report
|
|
||||||
description: Create a report to help us improve
|
|
||||||
title: "[Bug] "
|
|
||||||
labels: ["bug"]
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
确保你使用的是**本仓库**最新的的 mihomo 或 mihomo Alpha 版本
|
|
||||||
Ensure you are using the latest version of Mihomo or Mihomo Alpha from **this repository**.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
如果你可以自己 debug 并解决的话,提交 PR 吧
|
|
||||||
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
|
||||||
"
|
|
||||||
required: false
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
|
||||||
I have searched on the [issue tracker](……/) for a related issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经使用 Alpha 分支版本测试过,问题依旧存在
|
|
||||||
I have tested using the dev branch, and the issue still exists.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://wiki.metacubex.one/) 并无法自行解决问题
|
|
||||||
I have read the [documentation](https://wiki.metacubex.one/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
这是 Mihomo 核心的问题,并非我所使用的 Mihomo 衍生版本(如 OpenMihomo、KoolMihomo 等)的特定问题
|
|
||||||
This is an issue of the Mihomo core *per se*, not to the derivatives of Mihomo, like OpenMihomo or KoolMihomo.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
attributes:
|
|
||||||
label: Mihomo version
|
|
||||||
description: "use `mihomo -v`"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: os
|
|
||||||
attributes:
|
|
||||||
label: What OS are you seeing the problem on?
|
|
||||||
multiple: true
|
|
||||||
options:
|
|
||||||
- macOS
|
|
||||||
- Windows
|
|
||||||
- Linux
|
|
||||||
- OpenBSD/FreeBSD
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: yaml
|
|
||||||
label: "Mihomo config"
|
|
||||||
description: "
|
|
||||||
在下方附上 Mihomo core 配置文件,请确保配置文件中没有敏感信息(比如:服务器地址,密码,端口等)
|
|
||||||
Paste the Mihomo core configuration file below, please make sure that there is no sensitive information in the configuration file (e.g., server address/url, password, port)
|
|
||||||
"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: shell
|
|
||||||
label: Mihomo log
|
|
||||||
description: "
|
|
||||||
在下方附上 Mihomo Core 的日志,log level 使用 DEBUG
|
|
||||||
Paste the Mihomo core log below with the log level set to `DEBUG`.
|
|
||||||
"
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
5
.github/ISSUE_TEMPLATE/config.yml
vendored
5
.github/ISSUE_TEMPLATE/config.yml
vendored
@@ -1,5 +0,0 @@
|
|||||||
blank_issues_enabled: false
|
|
||||||
contact_links:
|
|
||||||
- name: mihomo Community Support
|
|
||||||
url: https://github.com/MetaCubeX/mihomo/discussions
|
|
||||||
about: Please ask and answer questions about mihomo here.
|
|
||||||
37
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
37
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -1,37 +0,0 @@
|
|||||||
name: Feature request
|
|
||||||
description: Suggest an idea for this project
|
|
||||||
title: "[Feature] "
|
|
||||||
labels: ["enhancement"]
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
|
||||||
I have searched on the [issue tracker](……/) for a related feature request.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://wiki.metacubex.one/) 并无法找到这个功能
|
|
||||||
I have read the [documentation](https://wiki.metacubex.one/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Mihomo Core 的行为是什麽?
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Possible Solution
|
|
||||||
description: "
|
|
||||||
此项非必须,但是如果你有想法的话欢迎提出。
|
|
||||||
Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
|
|
||||||
"
|
|
||||||
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
|
|
||||||
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH
|
|
||||||
Restart=always
|
|
||||||
ExecStartPre=/usr/bin/sleep 2s
|
|
||||||
ExecStart=/usr/bin/mihomo -d /etc/mihomo
|
|
||||||
ExecReload=/bin/kill -HUP $MAINPID
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
26
.github/rename-cgo.sh
vendored
26
.github/rename-cgo.sh
vendored
@@ -5,25 +5,25 @@ for FILENAME in $FILENAMES
|
|||||||
do
|
do
|
||||||
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
||||||
echo "rename darwin-10.16-arm64 $FILENAME"
|
echo "rename darwin-10.16-arm64 $FILENAME"
|
||||||
mv $FILENAME mihomo-darwin-arm64-cgo
|
mv $FILENAME clash.meta-darwin-arm64-cgo
|
||||||
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
||||||
echo "rename darwin-10.16-amd64 $FILENAME"
|
echo "rename darwin-10.16-amd64 $FILENAME"
|
||||||
mv $FILENAME mihomo-darwin-amd64-cgo
|
mv $FILENAME clash.meta-darwin-amd64-cgo
|
||||||
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
||||||
echo "rename windows 386 $FILENAME"
|
echo "rename windows 386 $FILENAME"
|
||||||
mv $FILENAME mihomo-windows-386-cgo.exe
|
mv $FILENAME clash.meta-windows-386-cgo.exe
|
||||||
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
||||||
echo "rename windows amd64 $FILENAME"
|
echo "rename windows amd64 $FILENAME"
|
||||||
mv $FILENAME mihomo-windows-amd64-cgo.exe
|
mv $FILENAME clash.meta-windows-amd64-cgo.exe
|
||||||
elif [[ $FILENAME =~ "mihomo-linux-arm-5" ]];then
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-5" ]];then
|
||||||
echo "rename mihomo-linux-arm-5 $FILENAME"
|
echo "rename clash.meta-linux-arm-5 $FILENAME"
|
||||||
mv $FILENAME mihomo-linux-armv5-cgo
|
mv $FILENAME clash.meta-linux-armv5-cgo
|
||||||
elif [[ $FILENAME =~ "mihomo-linux-arm-6" ]];then
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-6" ]];then
|
||||||
echo "rename mihomo-linux-arm-6 $FILENAME"
|
echo "rename clash.meta-linux-arm-6 $FILENAME"
|
||||||
mv $FILENAME mihomo-linux-armv6-cgo
|
mv $FILENAME clash.meta-linux-armv6-cgo
|
||||||
elif [[ $FILENAME =~ "mihomo-linux-arm-7" ]];then
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-7" ]];then
|
||||||
echo "rename mihomo-linux-arm-7 $FILENAME"
|
echo "rename clash.meta-linux-arm-7 $FILENAME"
|
||||||
mv $FILENAME mihomo-linux-armv7-cgo
|
mv $FILENAME clash.meta-linux-armv7-cgo
|
||||||
elif [[ $FILENAME =~ "linux" ]];then
|
elif [[ $FILENAME =~ "linux" ]];then
|
||||||
echo "rename linux $FILENAME"
|
echo "rename linux $FILENAME"
|
||||||
mv $FILENAME $FILENAME-cgo
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
|||||||
12
.github/rename-go120.sh
vendored
12
.github/rename-go120.sh
vendored
@@ -1,12 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
FILENAMES=$(ls)
|
|
||||||
for FILENAME in $FILENAMES
|
|
||||||
do
|
|
||||||
if [[ ! ($FILENAME =~ ".exe" || $FILENAME =~ ".sh")]];then
|
|
||||||
mv $FILENAME ${FILENAME}-go120
|
|
||||||
elif [[ $FILENAME =~ ".exe" ]];then
|
|
||||||
mv $FILENAME ${FILENAME%.*}-go120.exe
|
|
||||||
else echo "skip $FILENAME"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
16
.github/workflows/Delete.yml
vendored
16
.github/workflows/Delete.yml
vendored
@@ -1,16 +0,0 @@
|
|||||||
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
|
|
||||||
525
.github/workflows/build.yml
vendored
525
.github/workflows/build.yml
vendored
@@ -15,347 +15,300 @@ on:
|
|||||||
- 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: docker.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: '7', output: armv7 }
|
id: "2",
|
||||||
- { goos: linux, goarch: mips, mips: hardfloat, output: mips-hardfloat }
|
}
|
||||||
- { goos: linux, goarch: mips, mips: softfloat, output: mips-softfloat }
|
- {
|
||||||
- { goos: linux, goarch: mipsle, mips: hardfloat, output: mipsle-hardfloat }
|
type: "WithoutCGO",
|
||||||
- { goos: linux, goarch: mipsle, mips: softfloat, output: mipsle-softfloat }
|
target: "linux-arm64 linux-mips64 linux-mips64le",
|
||||||
- { goos: linux, goarch: mips64, output: mips64 }
|
id: "3",
|
||||||
- { goos: linux, goarch: mips64le, output: mips64le }
|
}
|
||||||
- { goos: linux, goarch: loong64, output: loong64-abi1, abi: '1' }
|
- {
|
||||||
- { goos: linux, goarch: loong64, output: loong64-abi2, abi: '2' }
|
type: "WithoutCGO",
|
||||||
- { goos: linux, goarch: riscv64, output: riscv64 }
|
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
||||||
- { goos: linux, goarch: s390x, output: s390x }
|
id: "4",
|
||||||
|
}
|
||||||
- { goos: windows, goarch: '386', output: '386' }
|
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
||||||
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
- {
|
||||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64 }
|
type: "WithoutCGO",
|
||||||
- { goos: windows, goarch: arm, goarm: '7', output: armv7 }
|
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
||||||
- { goos: windows, goarch: arm64, output: arm64 }
|
id: "6",
|
||||||
|
}
|
||||||
- { goos: freebsd, goarch: '386', output: '386' }
|
- {
|
||||||
- { goos: freebsd, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
type: "WithoutCGO",
|
||||||
- { goos: freebsd, goarch: amd64, goamd64: v3, output: amd64 }
|
target: "windows-amd64-compatible windows-amd64 windows-386",
|
||||||
- { goos: freebsd, goarch: arm64, output: arm64 }
|
id: "7",
|
||||||
|
}
|
||||||
- { goos: android, goarch: '386', ndk: i686-linux-android34, output: '386' }
|
- {
|
||||||
- { goos: android, goarch: amd64, ndk: x86_64-linux-android34, output: amd64 }
|
type: "WithoutCGO",
|
||||||
- { goos: android, goarch: arm, ndk: armv7a-linux-androideabi34, output: armv7 }
|
target: "windows-arm64 windows-arm32v7",
|
||||||
- { goos: android, goarch: arm64, ndk: aarch64-linux-android34, output: arm64-v8 }
|
id: "8",
|
||||||
|
}
|
||||||
# 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' }
|
type: "WithoutCGO",
|
||||||
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20' }
|
target: "darwin-amd64 darwin-arm64 android-arm64",
|
||||||
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
id: "9",
|
||||||
|
}
|
||||||
# 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: "WithCGO", target: "windows/*", id: "1" }
|
||||||
- { goos: darwin, goarch: arm64, output: arm64-go120, goversion: '1.20' }
|
- { type: "WithCGO", target: "linux/386", id: "2" }
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20' }
|
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
||||||
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
||||||
# only for test
|
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
||||||
- { goos: linux, goarch: '386', output: '386-go120', goversion: '1.20' }
|
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
||||||
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20', test: test }
|
- { type: "WithCGO", target: "linux/mips64", id: "8" }
|
||||||
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
- { 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.goarch != 'loong64' }}
|
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
uses: actions/setup-go@v5
|
shell: bash
|
||||||
with:
|
|
||||||
go-version: '1.22'
|
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set variables
|
||||||
if: ${{ matrix.jobs.goversion != '' && matrix.jobs.goarch != 'loong64' }}
|
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.21 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/xishang0128/loongarch64-golang/releases/download/1.21.5/go1.21.5.linux-amd64-abi1.tar.gz
|
shell: bash
|
||||||
sudo tar zxf go1.21.5.linux-amd64-abi1.tar.gz -C /usr/local
|
|
||||||
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
|
||||||
|
|
||||||
- name: Set up Go1.21 loongarch abi2
|
- name: Set variables
|
||||||
if: ${{ matrix.jobs.goarch == 'loong64' && matrix.jobs.abi == '2' }}
|
if: ${{github.ref_name=='Meta'}}
|
||||||
run: |
|
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
wget -q https://github.com/xishang0128/loongarch64-golang/releases/download/1.21.5/go1.21.5.linux-amd64-abi2.tar.gz
|
shell: bash
|
||||||
sudo tar zxf go1.21.5.linux-amd64-abi2.tar.gz -C /usr/local
|
|
||||||
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set variables
|
||||||
if: ${{github.ref_name=='Alpha'}}
|
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
||||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set ENV
|
||||||
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
run: |
|
||||||
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
sudo timedatectl set-timezone "Asia/Shanghai"
|
||||||
shell: bash
|
echo "NAME=clash.meta" >> $GITHUB_ENV
|
||||||
|
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
||||||
|
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 Time Variable
|
- name: Set ENV
|
||||||
run: |
|
run: |
|
||||||
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
||||||
echo "CGO_ENABLED=0" >> $GITHUB_ENV
|
echo "LDFLAGS=-X 'github.com/Dreamacro/clash/constant.Version=${VERSION}' -X 'github.com/Dreamacro/clash/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
||||||
echo "BUILDTAG=-extldflags --static" >> $GITHUB_ENV
|
shell: bash
|
||||||
|
|
||||||
- name: Setup NDK
|
- name: Setup Go
|
||||||
if: ${{ matrix.jobs.goos == 'android' }}
|
uses: actions/setup-go@v4
|
||||||
uses: nttld/setup-ndk@v1
|
with:
|
||||||
id: setup-ndk
|
go-version: "1.21"
|
||||||
with:
|
check-latest: true
|
||||||
ndk-version: r26c
|
|
||||||
|
|
||||||
- name: Set NDK path
|
- name: Test
|
||||||
if: ${{ matrix.jobs.goos == 'android' }}
|
if: ${{ matrix.job.id=='1' && matrix.job.type=='WithoutCGO' }}
|
||||||
run: |
|
run: |
|
||||||
echo "CC=${{steps.setup-ndk.outputs.ndk-path}}/toolchains/llvm/prebuilt/linux-x86_64/bin/${{matrix.jobs.ndk}}-clang" >> $GITHUB_ENV
|
go test ./...
|
||||||
echo "CGO_ENABLED=1" >> $GITHUB_ENV
|
|
||||||
echo "BUILDTAG=" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Test
|
- name: Build WithoutCGO
|
||||||
if: ${{ matrix.jobs.test == 'test' }}
|
if: ${{ matrix.job.type=='WithoutCGO' }}
|
||||||
run: |
|
env:
|
||||||
go test ./...
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
||||||
|
|
||||||
- name: Update UA
|
- uses: nttld/setup-ndk@v1
|
||||||
run: |
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||||
sudo apt-get install ca-certificates
|
id: setup-ndk
|
||||||
sudo update-ca-certificates
|
with:
|
||||||
cp -f /etc/ssl/certs/ca-certificates.crt component/ca/ca-certificates.crt
|
ndk-version: r25b
|
||||||
|
add-to-path: false
|
||||||
|
local-cache: true
|
||||||
|
|
||||||
- name: Build core
|
- name: Build Android
|
||||||
env:
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||||
GOOS: ${{matrix.jobs.goos}}
|
env:
|
||||||
GOARCH: ${{matrix.jobs.goarch}}
|
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||||
GOAMD64: ${{matrix.jobs.goamd64}}
|
run: |
|
||||||
GOARM: ${{matrix.jobs.arm}}
|
mkdir bin
|
||||||
GOMIPS: ${{matrix.jobs.mips}}
|
CC=${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android33-clang
|
||||||
run: |
|
CGO_ENABLED=1 CC=${CC} GOARCH=arm64 GOOS=android go build -tags ${TAGS} -trimpath -ldflags "${LDFLAGS}" -o bin/${NAME}-android-arm64
|
||||||
echo $CGO_ENABLED
|
|
||||||
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: Set up xgo
|
||||||
if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') }}
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get install dpkg
|
docker pull techknowlogick/xgo:latest
|
||||||
if [ "${{matrix.jobs.abi}}" = "1" ]; then
|
go install src.techknowlogick.com/xgo@latest
|
||||||
ARCH=loongarch64
|
|
||||||
else
|
|
||||||
ARCH=${{matrix.jobs.goarch}}
|
|
||||||
fi
|
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/DEBIAN
|
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/bin
|
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/mihomo
|
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/systemd/system/
|
|
||||||
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/share/licenses/mihomo
|
|
||||||
|
|
||||||
cp mihomo mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/bin/mihomo
|
- name: Build by xgo
|
||||||
cp LICENSE mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/share/licenses/mihomo/
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
||||||
cp .github/mihomo.service mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/systemd/system/
|
env:
|
||||||
|
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||||
|
run: |
|
||||||
|
mkdir bin
|
||||||
|
xgo --targets="${{ matrix.job.target }}" --tags="${TAGS}" -ldflags="${LDFLAGS}" --out bin/${NAME} ./
|
||||||
|
|
||||||
cat > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/mihomo/config.yaml <<EOF
|
- name: Rename
|
||||||
mixed-port: 7890
|
if: ${{ matrix.job.type=='WithCGO' }}
|
||||||
external-controller: 127.0.0.1:9090
|
run: |
|
||||||
EOF
|
cd bin
|
||||||
|
ls -la
|
||||||
|
cp ../.github/rename-cgo.sh ./
|
||||||
|
bash ./rename-cgo.sh
|
||||||
|
rm ./rename-cgo.sh
|
||||||
|
ls -la
|
||||||
|
cd ..
|
||||||
|
|
||||||
cat > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/DEBIAN/control <<EOF
|
- name: Zip
|
||||||
Package: mihomo
|
if: ${{ success() }}
|
||||||
Version: 1.18.2-${VERSION}
|
run: |
|
||||||
Section:
|
cd bin
|
||||||
Priority: extra
|
ls -la
|
||||||
Architecture: ${ARCH}
|
chmod +x *
|
||||||
Maintainer: MetaCubeX <none@example.com>
|
cp ../.github/release.sh ./
|
||||||
Homepage: https://wiki.metacubex.one/
|
bash ./release.sh
|
||||||
Description: The universal proxy platform.
|
rm ./release.sh
|
||||||
EOF
|
ls -la
|
||||||
|
cd ..
|
||||||
|
|
||||||
dpkg-deb -Z gzip --build mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}
|
- name: Save version
|
||||||
|
run: echo ${VERSION} > bin/version.txt
|
||||||
|
shell: bash
|
||||||
|
|
||||||
- name: Convert DEB to RPM
|
- uses: actions/upload-artifact@v3
|
||||||
if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') }}
|
if: ${{ success() }}
|
||||||
run: |
|
with:
|
||||||
sudo apt-get install -y alien
|
name: artifact
|
||||||
alien --to-rpm --scripts mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.deb
|
path: bin/
|
||||||
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.ref_type == 'branch' && !startsWith(github.event_name, 'pull_request') }}
|
if: ${{ github.ref_type=='branch' }}
|
||||||
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:
|
||||||
with:
|
name: artifact
|
||||||
path: bin/
|
path: bin/
|
||||||
merge-multiple: true
|
|
||||||
|
|
||||||
- name: Delete current release assets
|
- name: Display structure of downloaded files
|
||||||
uses: 8Mi-Tech/delete-release-assets-action@main
|
run: ls -R
|
||||||
with:
|
working-directory: bin
|
||||||
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
|
- name: Delete current release assets
|
||||||
uses: richardsimko/update-tag@v1
|
uses: 8Mi-Tech/delete-release-assets-action@main
|
||||||
with:
|
with:
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
env:
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
- 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
|
- name: Set Env
|
||||||
uses: softprops/action-gh-release@v1
|
run: |
|
||||||
if: ${{ success() }}
|
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
||||||
with:
|
shell: bash
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: |
|
- name: Tag Repo
|
||||||
bin/*
|
uses: richardsimko/update-tag@v1.0.6
|
||||||
prerelease: true
|
with:
|
||||||
generate_release_notes: true
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
body_path: release.txt
|
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/Clash.Meta/wiki/FAQ)
|
||||||
|
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Upload Prerelease
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
files: |
|
||||||
|
bin/*
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
||||||
|
body_path: release.txt
|
||||||
|
|
||||||
Upload-Release:
|
Upload-Release:
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
if: ${{ github.ref_type=='tag' }}
|
if: ${{ github.ref_type=='tag' }}
|
||||||
needs: [build]
|
needs: [Build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- uses: actions/download-artifact@v3
|
||||||
uses: actions/checkout@v4
|
with:
|
||||||
with:
|
name: artifact
|
||||||
fetch-depth: 0
|
path: bin/
|
||||||
|
|
||||||
- name: Get tags
|
- name: Display structure of downloaded files
|
||||||
run: |
|
run: ls -R
|
||||||
echo "CURRENTVERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
|
working-directory: bin
|
||||||
git fetch --tags
|
|
||||||
echo "PREVERSION=$(git describe --tags --abbrev=0 HEAD^)" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Generate release notes
|
- name: Upload Release
|
||||||
run: |
|
uses: softprops/action-gh-release@v1
|
||||||
cp ./.github/genReleaseNote.sh ./
|
if: ${{ success() }}
|
||||||
bash ./genReleaseNote.sh -v ${PREVERSION}...${CURRENTVERSION}
|
with:
|
||||||
rm ./genReleaseNote.sh
|
tag_name: ${{ github.ref_name }}
|
||||||
|
files: bin/*
|
||||||
- uses: actions/download-artifact@v4
|
generate_release_notes: true
|
||||||
with:
|
|
||||||
path: bin/
|
|
||||||
merge-multiple: true
|
|
||||||
|
|
||||||
- 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/*
|
|
||||||
generate_release_notes: true
|
|
||||||
body_path: release.md
|
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
@@ -363,17 +316,16 @@ jobs:
|
|||||||
# https://github.com/docker/metadata-action
|
# https://github.com/docker/metadata-action
|
||||||
- name: Extract Docker metadata
|
- name: Extract Docker metadata
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v5
|
uses: docker/metadata-action@v4
|
||||||
with:
|
with:
|
||||||
images: ${{ env.REGISTRY }}/${{ github.repository }}
|
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
||||||
|
|
||||||
- name: Show files
|
- name: Show files
|
||||||
run: |
|
run: |
|
||||||
ls .
|
ls .
|
||||||
ls bin/
|
ls bin/
|
||||||
|
- name: Log into registry
|
||||||
- name: login to docker REGISTRY
|
if: github.event_name != 'pull_request'
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||||
@@ -383,7 +335,7 @@ jobs:
|
|||||||
# 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
|
||||||
id: build-and-push
|
id: build-and-push
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v4
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./Dockerfile
|
file: ./Dockerfile
|
||||||
@@ -391,7 +343,8 @@ jobs:
|
|||||||
platforms: |
|
platforms: |
|
||||||
linux/386
|
linux/386
|
||||||
linux/amd64
|
linux/amd64
|
||||||
linux/arm64
|
linux/arm64/v8
|
||||||
linux/arm/v7
|
linux/arm/v7
|
||||||
|
# linux/riscv64
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|||||||
33
.github/workflows/trigger-cmfa-update.yml
vendored
33
.github/workflows/trigger-cmfa-update.yml
vendored
@@ -1,33 +0,0 @@
|
|||||||
name: Trigger CMFA Update
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
paths-ignore:
|
|
||||||
- "docs/**"
|
|
||||||
- "README.md"
|
|
||||||
- ".github/ISSUE_TEMPLATE/**"
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
pull_request_target:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
# Send "core-updated" to MetaCubeX/ClashMetaForAndroid to trigger update-dependencies
|
|
||||||
trigger-CMFA-update:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: tibdex/github-app-token@v1
|
|
||||||
id: generate-token
|
|
||||||
with:
|
|
||||||
app_id: ${{ secrets.MAINTAINER_APPID }}
|
|
||||||
private_key: ${{ secrets.MAINTAINER_APP_PRIVATE_KEY }}
|
|
||||||
|
|
||||||
- name: Trigger update-dependencies
|
|
||||||
run: |
|
|
||||||
curl -X POST https://api.github.com/repos/MetaCubeX/ClashMetaForAndroid/dispatches \
|
|
||||||
-H "Accept: application/vnd.github.everest-preview+json" \
|
|
||||||
-H "Authorization: token ${{ steps.generate-token.outputs.token }}" \
|
|
||||||
-d '{"event_type": "core-updated"}'
|
|
||||||
@@ -11,7 +11,7 @@ linters-settings:
|
|||||||
custom-order: true
|
custom-order: true
|
||||||
sections:
|
sections:
|
||||||
- standard
|
- standard
|
||||||
- prefix(github.com/metacubex/mihomo)
|
- prefix(github.com/Dreamacro/clash)
|
||||||
- default
|
- default
|
||||||
staticcheck:
|
staticcheck:
|
||||||
go: '1.19'
|
go: '1.19'
|
||||||
|
|||||||
28
Dockerfile
28
Dockerfile
@@ -3,25 +3,25 @@ ARG TARGETPLATFORM
|
|||||||
RUN echo "I'm building for $TARGETPLATFORM"
|
RUN echo "I'm building for $TARGETPLATFORM"
|
||||||
|
|
||||||
RUN apk add --no-cache gzip && \
|
RUN apk add --no-cache gzip && \
|
||||||
mkdir /mihomo-config && \
|
mkdir /clash-config && \
|
||||||
wget -O /mihomo-config/geoip.metadb https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb && \
|
wget -O /clash-config/geoip.metadb https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb && \
|
||||||
wget -O /mihomo-config/geosite.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat && \
|
wget -O /clash-config/geosite.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat && \
|
||||||
wget -O /mihomo-config/geoip.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat
|
wget -O /clash-config/geoip.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat
|
||||||
|
|
||||||
COPY docker/file-name.sh /mihomo/file-name.sh
|
COPY docker/file-name.sh /clash/file-name.sh
|
||||||
WORKDIR /mihomo
|
WORKDIR /clash
|
||||||
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 && echo "$FILE_NAME" > /mihomo-config/test
|
mv bin/$FILE_NAME clash.gz && gzip -d clash.gz && echo "$FILE_NAME" > /clash-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/Clash.Meta"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata iptables
|
RUN apk add --no-cache ca-certificates tzdata iptables
|
||||||
|
|
||||||
VOLUME ["/root/.config/mihomo/"]
|
VOLUME ["/root/.config/clash/"]
|
||||||
|
|
||||||
COPY --from=builder /mihomo-config/ /root/.config/mihomo/
|
COPY --from=builder /clash-config/ /root/.config/clash/
|
||||||
COPY --from=builder /mihomo/mihomo /mihomo
|
COPY --from=builder /clash/clash /clash
|
||||||
RUN chmod +x /mihomo
|
RUN chmod +x /clash
|
||||||
ENTRYPOINT [ "/mihomo" ]
|
ENTRYPOINT [ "/clash" ]
|
||||||
|
|||||||
7
Makefile
7
Makefile
@@ -1,4 +1,4 @@
|
|||||||
NAME=mihomo
|
NAME=clash.meta
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
BRANCH=$(shell git branch --show-current)
|
BRANCH=$(shell git branch --show-current)
|
||||||
ifeq ($(BRANCH),Alpha)
|
ifeq ($(BRANCH),Alpha)
|
||||||
@@ -12,12 +12,11 @@ VERSION=$(shell git rev-parse --short HEAD)
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/metacubex/mihomo/constant.Version=$(VERSION)" \
|
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/metacubex/mihomo/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-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 \
|
||||||
|
|||||||
342
README.md
342
README.md
@@ -3,17 +3,17 @@
|
|||||||
<br>Meta Kernel<br>
|
<br>Meta Kernel<br>
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<h3 align="center">Another Mihomo Kernel.</h3>
|
<h3 align="center">Another Clash Kernel.</h3>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://goreportcard.com/report/github.com/MetaCubeX/mihomo">
|
<a href="https://goreportcard.com/report/github.com/Clash-Mini/Clash.Meta">
|
||||||
<img src="https://goreportcard.com/badge/github.com/MetaCubeX/mihomo?style=flat-square">
|
<img src="https://goreportcard.com/badge/github.com/Clash-Mini/Clash.Meta?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/Dreamacro/clash?style=flat-square">
|
||||||
<a href="https://github.com/MetaCubeX/mihomo/releases">
|
<a href="https://github.com/Clash-Mini/Clash.Meta/releases">
|
||||||
<img src="https://img.shields.io/github/release/MetaCubeX/mihomo/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/Clash-Mini/Clash.Meta/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/MetaCubeX/mihomo">
|
<a href="https://github.com/Clash-Mini/Clash.Meta">
|
||||||
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
@@ -21,52 +21,261 @@
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Local HTTP/HTTPS/SOCKS server with authentication support
|
- Local HTTP/HTTPS/SOCKS server with authentication support
|
||||||
- VMess, VLESS, Shadowsocks, Trojan, Snell, TUIC, Hysteria protocol support
|
- VMess, Shadowsocks, Trojan, Snell protocol support for remote connections
|
||||||
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
||||||
- Rules based off domains, GEOIP, IPCIDR or Process to forward packets to different nodes
|
- Rules based off domains, GEOIP, IPCIDR or Process to forward packets to different nodes
|
||||||
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node
|
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node based off latency
|
||||||
based off latency
|
- Remote providers, allowing users to get node lists remotely instead of hardcoding in config
|
||||||
- Remote providers, allowing users to get node lists remotely instead of hard-coding in config
|
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||||
- Netfilter TCP redirecting. Deploy Mihomo on your Internet gateway with `iptables`.
|
|
||||||
- Comprehensive HTTP RESTful API controller
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Dashboard
|
## Wiki
|
||||||
|
Configuration examples can be found at [/docs/config.yaml](https://github.com/MetaCubeX/Clash.Meta/blob/Alpha/docs/config.yaml), while documentation can be found [Clash.Meta Wiki](https://clash-meta.wiki).
|
||||||
|
|
||||||
A web dashboard with first-class support for this project has been created; it can be checked out at [metacubexd](https://github.com/MetaCubeX/metacubexd).
|
## Build
|
||||||
|
|
||||||
## Configration example
|
You should install [golang](https://go.dev) first.
|
||||||
|
|
||||||
Configuration example is located at [/docs/config.yaml](https://github.com/MetaCubeX/mihomo/blob/Alpha/docs/config.yaml).
|
Then get the source code of Clash.Meta:
|
||||||
|
|
||||||
## Docs
|
|
||||||
|
|
||||||
Documentation can be found in [mihomo Docs](https://wiki.metacubex.one/).
|
|
||||||
|
|
||||||
## For development
|
|
||||||
|
|
||||||
Requirements:
|
|
||||||
[Go 1.20 or newer](https://go.dev/dl/)
|
|
||||||
|
|
||||||
Build mihomo:
|
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
git clone https://github.com/MetaCubeX/mihomo.git
|
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
||||||
cd mihomo && go mod download
|
cd Clash.Meta && go mod download
|
||||||
go build
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Set go proxy if a connection to GitHub is not possible:
|
If you can't visit github,you should set proxy first:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
go env -w GOPROXY=https://goproxy.io,direct
|
go env -w GOPROXY=https://goproxy.io,direct
|
||||||
```
|
```
|
||||||
|
|
||||||
Build with gvisor tun stack:
|
Now you can build it:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
go build
|
||||||
|
```
|
||||||
|
|
||||||
|
If you need gvisor for tun stack, build with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
go build -tags with_gvisor
|
go build -tags with_gvisor
|
||||||
```
|
```
|
||||||
|
|
||||||
|
<!-- ## Advanced usage of this fork -->
|
||||||
|
|
||||||
|
<!-- ### DNS configuration
|
||||||
|
|
||||||
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
|
Restore `Redir remote resolution`.
|
||||||
|
|
||||||
|
Support resolve ip with a `Proxy Tunnel`.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
proxy-groups:
|
||||||
|
- name: DNS
|
||||||
|
type: url-test
|
||||||
|
use:
|
||||||
|
- HK
|
||||||
|
url: http://cp.cloudflare.com
|
||||||
|
interval: 180
|
||||||
|
lazy: true
|
||||||
|
```
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
dns:
|
||||||
|
enable: true
|
||||||
|
use-hosts: true
|
||||||
|
ipv6: false
|
||||||
|
enhanced-mode: redir-host
|
||||||
|
fake-ip-range: 198.18.0.1/16
|
||||||
|
listen: 127.0.0.1:6868
|
||||||
|
default-nameserver:
|
||||||
|
- 119.29.29.29
|
||||||
|
- 114.114.114.114
|
||||||
|
nameserver:
|
||||||
|
- https://doh.pub/dns-query
|
||||||
|
- tls://223.5.5.5:853
|
||||||
|
fallback:
|
||||||
|
- "https://1.0.0.1/dns-query#DNS" # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
||||||
|
- "tls://8.8.4.4:853#DNS"
|
||||||
|
fallback-filter:
|
||||||
|
geoip: false
|
||||||
|
geosite:
|
||||||
|
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
||||||
|
domain:
|
||||||
|
- +.example.com
|
||||||
|
ipcidr:
|
||||||
|
- 0.0.0.0/32
|
||||||
|
```
|
||||||
|
|
||||||
|
### TUN configuration
|
||||||
|
|
||||||
|
Supports macOS, Linux and Windows.
|
||||||
|
|
||||||
|
Built-in [Wintun](https://www.wintun.net) driver.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Enable the TUN listener
|
||||||
|
tun:
|
||||||
|
enable: true
|
||||||
|
stack: system # system/gvisor
|
||||||
|
dns-hijack:
|
||||||
|
- 0.0.0.0:53 # additional dns server listen on TUN
|
||||||
|
auto-route: true # auto set global route
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rules configuration
|
||||||
|
|
||||||
|
- Support rule `GEOSITE`.
|
||||||
|
- Support rule-providers `RULE-SET`.
|
||||||
|
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
||||||
|
- Support `network` condition for all rules.
|
||||||
|
- Support source IPCIDR condition for all rules, just append to the end.
|
||||||
|
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
rules:
|
||||||
|
# network(tcp/udp) condition for all rules
|
||||||
|
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
||||||
|
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
||||||
|
|
||||||
|
# multiport condition for rules SRC-PORT and DST-PORT
|
||||||
|
- DST-PORT,123/136/137-139,DIRECT,udp
|
||||||
|
|
||||||
|
# rule GEOSITE
|
||||||
|
- GEOSITE,category-ads-all,REJECT
|
||||||
|
- GEOSITE,icloud@cn,DIRECT
|
||||||
|
- GEOSITE,apple@cn,DIRECT
|
||||||
|
- GEOSITE,apple-cn,DIRECT
|
||||||
|
- GEOSITE,microsoft@cn,DIRECT
|
||||||
|
- GEOSITE,facebook,PROXY
|
||||||
|
- GEOSITE,youtube,PROXY
|
||||||
|
- GEOSITE,geolocation-cn,DIRECT
|
||||||
|
- GEOSITE,geolocation-!cn,PROXY
|
||||||
|
|
||||||
|
# source IPCIDR condition for all rules in gateway proxy
|
||||||
|
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
||||||
|
|
||||||
|
- GEOIP,telegram,PROXY,no-resolve
|
||||||
|
- GEOIP,private,DIRECT,no-resolve
|
||||||
|
- GEOIP,cn,DIRECT
|
||||||
|
|
||||||
|
- MATCH,PROXY
|
||||||
|
```
|
||||||
|
|
||||||
|
### Proxies configuration
|
||||||
|
|
||||||
|
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
||||||
|
|
||||||
|
Support `Policy Group Filter`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
proxy-groups:
|
||||||
|
- name: 🚀 HK Group
|
||||||
|
type: select
|
||||||
|
use:
|
||||||
|
- ALL
|
||||||
|
filter: "HK"
|
||||||
|
|
||||||
|
- name: 🚀 US Group
|
||||||
|
type: select
|
||||||
|
use:
|
||||||
|
- ALL
|
||||||
|
filter: "US"
|
||||||
|
|
||||||
|
proxy-providers:
|
||||||
|
ALL:
|
||||||
|
type: http
|
||||||
|
url: "xxxxx"
|
||||||
|
interval: 3600
|
||||||
|
path: "xxxxx"
|
||||||
|
health-check:
|
||||||
|
enable: true
|
||||||
|
interval: 600
|
||||||
|
url: http://www.gstatic.com/generate_204
|
||||||
|
```
|
||||||
|
|
||||||
|
Support outbound transport protocol `VLESS`.
|
||||||
|
|
||||||
|
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
proxies:
|
||||||
|
- name: "vless"
|
||||||
|
type: vless
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
|
servername: example.com # AKA SNI
|
||||||
|
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
||||||
|
# skip-cert-verify: true
|
||||||
|
|
||||||
|
- name: "vless-ws"
|
||||||
|
type: vless
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
|
tls: true
|
||||||
|
udp: true
|
||||||
|
network: ws
|
||||||
|
servername: example.com # priority over wss host
|
||||||
|
# skip-cert-verify: true
|
||||||
|
ws-opts:
|
||||||
|
path: /path
|
||||||
|
headers: { Host: example.com, Edge: "12a00c4.fm.huawei.com:82897" }
|
||||||
|
|
||||||
|
- name: "vless-grpc"
|
||||||
|
type: vless
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
|
tls: true
|
||||||
|
udp: true
|
||||||
|
network: grpc
|
||||||
|
servername: example.com # priority over wss host
|
||||||
|
# skip-cert-verify: true
|
||||||
|
grpc-opts:
|
||||||
|
grpc-service-name: grpcname
|
||||||
|
```
|
||||||
|
|
||||||
|
Support outbound transport protocol `Wireguard`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
proxies:
|
||||||
|
- name: "wg"
|
||||||
|
type: wireguard
|
||||||
|
server: 162.159.192.1
|
||||||
|
port: 2480
|
||||||
|
ip: 172.16.0.2
|
||||||
|
ipv6: fd01:5ca1:ab1e:80fa:ab85:6eea:213f:f4a5
|
||||||
|
private-key: eCtXsJZ27+4PbhDkHnB923tkUn2Gj59wZw5wFA75MnU=
|
||||||
|
public-key: Cr8hWlKvtDt7nrvf+f0brNQQzabAqrjfBvas9pmowjo=
|
||||||
|
udp: true
|
||||||
|
```
|
||||||
|
|
||||||
|
Support outbound transport protocol `Tuic`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
proxies:
|
||||||
|
- name: "tuic"
|
||||||
|
server: www.example.com
|
||||||
|
port: 10443
|
||||||
|
type: tuic
|
||||||
|
token: TOKEN
|
||||||
|
# ip: 127.0.0.1 # for overwriting the DNS lookup result of the server address set in option 'server'
|
||||||
|
# heartbeat-interval: 10000
|
||||||
|
# alpn: [h3]
|
||||||
|
# disable-sni: true
|
||||||
|
reduce-rtt: true
|
||||||
|
# request-timeout: 8000
|
||||||
|
udp-relay-mode: native # Available: "native", "quic". Default: "native"
|
||||||
|
# congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic"
|
||||||
|
# max-udp-relay-packet-size: 1500
|
||||||
|
# fast-open: true
|
||||||
|
# skip-cert-verify: true
|
||||||
|
``` -->
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
|
|
||||||
Work on Linux OS which supported `iptables`
|
Work on Linux OS which supported `iptables`
|
||||||
@@ -80,10 +289,71 @@ iptables:
|
|||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Debugging
|
### General installation guide for Linux
|
||||||
|
|
||||||
|
- Create user given name `clash-meta`
|
||||||
|
|
||||||
|
- Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||||
|
|
||||||
|
- Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
||||||
|
|
||||||
|
- Create folder `/etc/Clash-Meta/` as working directory
|
||||||
|
|
||||||
|
Run Meta Kernel by user `clash-meta` as a daemon.
|
||||||
|
|
||||||
|
Create the systemd configuration file at `/etc/systemd/system/Clash-Meta.service`:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Unit]
|
||||||
|
Description=Clash-Meta Daemon, Another Clash Kernel.
|
||||||
|
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=clash-meta
|
||||||
|
Group=clash-meta
|
||||||
|
LimitNPROC=500
|
||||||
|
LimitNOFILE=1000000
|
||||||
|
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
|
||||||
|
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
|
||||||
|
Restart=always
|
||||||
|
ExecStartPre=/usr/bin/sleep 1s
|
||||||
|
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
Launch clashd on system startup with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
$ systemctl enable Clash-Meta
|
||||||
|
```
|
||||||
|
|
||||||
|
Launch clashd immediately with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
$ systemctl start Clash-Meta
|
||||||
|
```
|
||||||
|
|
||||||
|
### Display Process name
|
||||||
|
|
||||||
|
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
||||||
|
|
||||||
|
To display process name in GUI please use [Razord-meta](https://github.com/MetaCubeX/Razord-meta).
|
||||||
|
|
||||||
|
### Dashboard
|
||||||
|
|
||||||
|
We also made a custom fork of yacd provide better support for this project, check it out at [Yacd-meta](https://github.com/MetaCubeX/Yacd-meta)
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
If you want to build an application that uses clash as a library, check out the
|
||||||
|
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
||||||
|
|
||||||
|
## Debugging
|
||||||
|
Check [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki/How-to-use-debug-api) to get an instruction on using debug API.
|
||||||
|
|
||||||
Check [wiki](https://wiki.metacubex.one/api/#debug) to get an instruction on using debug
|
|
||||||
API.
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
@@ -98,4 +368,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)
|
[](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package adapter
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -11,12 +12,14 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
"github.com/metacubex/mihomo/common/queue"
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/puzpuzpuz/xsync/v3"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"github.com/puzpuzpuz/xsync/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
var UnifiedDelay = atomic.NewBool(false)
|
var UnifiedDelay = atomic.NewBool(false)
|
||||||
@@ -25,16 +28,22 @@ 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]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alive implements C.Proxy
|
||||||
|
func (p *Proxy) Alive() bool {
|
||||||
|
return p.alive.Load()
|
||||||
}
|
}
|
||||||
|
|
||||||
// AliveForTestUrl implements C.Proxy
|
// AliveForTestUrl implements C.Proxy
|
||||||
@@ -79,6 +88,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +99,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)
|
||||||
@@ -96,46 +111,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
|
||||||
}
|
}
|
||||||
@@ -150,8 +180,8 @@ 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.Alive()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
mapping["xudp"] = p.SupportXUDP()
|
mapping["xudp"] = p.SupportXUDP()
|
||||||
@@ -161,42 +191,50 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
|
|
||||||
// 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], store C.DelayHistoryStoreType) (t uint16, err error) {
|
||||||
var satisfied bool
|
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
alive := err == nil
|
alive := err == nil
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
store = p.determineFinalStoreType(store, url)
|
||||||
if alive {
|
|
||||||
record.Delay = t
|
|
||||||
}
|
|
||||||
|
|
||||||
p.alive.Store(alive)
|
switch store {
|
||||||
p.history.Put(record)
|
case C.OriginalHistory:
|
||||||
if p.history.Len() > defaultHistoriesNum {
|
p.alive.Store(alive)
|
||||||
p.history.Pop()
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
}
|
if alive {
|
||||||
|
record.Delay = t
|
||||||
state, ok := p.extra.Load(url)
|
}
|
||||||
if !ok {
|
p.history.Put(record)
|
||||||
state = &internalProxyState{
|
if p.history.Len() > defaultHistoriesNum {
|
||||||
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
p.history.Pop()
|
||||||
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
|
||||||
}
|
}
|
||||||
|
case C.ExtraHistory:
|
||||||
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
|
if alive {
|
||||||
|
record.Delay = t
|
||||||
|
}
|
||||||
|
|
||||||
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()
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
log.Debugln("health check result will be discarded, url: %s alive: %t, delay: %d", url, alive, t)
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
unifiedDelay := UnifiedDelay.Load()
|
unifiedDelay := UnifiedDelay.Load()
|
||||||
@@ -259,16 +297,22 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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[*extraProxyState]()}
|
||||||
}
|
}
|
||||||
|
|
||||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||||
@@ -301,3 +345,24 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *Proxy) determineFinalStoreType(store C.DelayHistoryStoreType, url string) C.DelayHistoryStoreType {
|
||||||
|
if store != C.DropHistory {
|
||||||
|
return store
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(p.url) == 0 || url == p.url {
|
||||||
|
return C.OriginalHistory
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.extra.Size() < 2*C.DefaultMaxHealthCheckUrlNum {
|
||||||
|
return C.ExtraHistory
|
||||||
|
}
|
||||||
|
|
||||||
|
_, ok := p.extra.Load(url)
|
||||||
|
if ok {
|
||||||
|
return C.ExtraHistory
|
||||||
|
}
|
||||||
|
|
||||||
|
return store
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,17 +1,13 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Addition func(metadata *C.Metadata)
|
type Addition func(metadata *C.Metadata)
|
||||||
|
|
||||||
func ApplyAdditions(metadata *C.Metadata, additions ...Addition) {
|
func (a Addition) Apply(metadata *C.Metadata) {
|
||||||
for _, addition := range additions {
|
a(metadata)
|
||||||
addition(metadata)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithInName(name string) Addition {
|
func WithInName(name string) Addition {
|
||||||
@@ -37,35 +33,3 @@ func WithSpecialProxy(specialProxy string) Addition {
|
|||||||
metadata.SpecialProxy = specialProxy
|
metadata.SpecialProxy = specialProxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithDstAddr(addr net.Addr) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
_ = metadata.SetRemoteAddr(addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithSrcAddr(addr net.Addr) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
m := C.Metadata{}
|
|
||||||
if err := m.SetRemoteAddr(addr);err ==nil{
|
|
||||||
metadata.SrcIP = m.DstIP
|
|
||||||
metadata.SrcPort = m.DstPort
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithInAddr(addr net.Addr) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
m := C.Metadata{}
|
|
||||||
if err := m.SetRemoteAddr(addr);err ==nil{
|
|
||||||
metadata.InIP = m.DstIP
|
|
||||||
metadata.InPort = m.DstPort
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithDSCP(dscp uint8) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.DSCP = dscp
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
var skipAuthPrefixes []netip.Prefix
|
|
||||||
|
|
||||||
func SetSkipAuthPrefixes(prefixes []netip.Prefix) {
|
|
||||||
skipAuthPrefixes = prefixes
|
|
||||||
}
|
|
||||||
|
|
||||||
func SkipAuthPrefixes() []netip.Prefix {
|
|
||||||
return skipAuthPrefixes
|
|
||||||
}
|
|
||||||
|
|
||||||
func SkipAuthRemoteAddr(addr net.Addr) bool {
|
|
||||||
m := C.Metadata{}
|
|
||||||
if err := m.SetRemoteAddr(addr); err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return skipAuth(m.AddrPort().Addr())
|
|
||||||
}
|
|
||||||
|
|
||||||
func SkipAuthRemoteAddress(addr string) bool {
|
|
||||||
m := C.Metadata{}
|
|
||||||
if err := m.SetRemoteAddress(addr); err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return skipAuth(m.AddrPort().Addr())
|
|
||||||
}
|
|
||||||
|
|
||||||
func skipAuth(addr netip.Addr) bool {
|
|
||||||
if addr.IsValid() {
|
|
||||||
for _, prefix := range skipAuthPrefixes {
|
|
||||||
if prefix.Contains(addr.Unmap()) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -3,18 +3,26 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/socks5"
|
"github.com/Dreamacro/clash/context"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTP receive normal http request and return HTTPContext
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
func NewHTTP(target socks5.Addr, srcConn net.Conn, conn net.Conn, additions ...Addition) (net.Conn, *C.Metadata) {
|
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn, additions ...Addition) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
metadata.RawSrcAddr = srcConn.RemoteAddr()
|
for _, addition := range additions {
|
||||||
metadata.RawDstAddr = srcConn.LocalAddr()
|
addition.Apply(metadata)
|
||||||
ApplyAdditions(metadata, WithSrcAddr(srcConn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
}
|
||||||
ApplyAdditions(metadata, additions...)
|
if ip, port, err := parseAddr(source); err == nil {
|
||||||
return conn, metadata
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,14 +4,24 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS receive CONNECT request and return ConnContext
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) (net.Conn, *C.Metadata) {
|
func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) *context.ConnContext {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPS
|
metadata.Type = C.HTTPS
|
||||||
ApplyAdditions(metadata, WithSrcAddr(conn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
for _, addition := range additions {
|
||||||
ApplyAdditions(metadata, additions...)
|
addition.Apply(metadata)
|
||||||
return conn, metadata
|
}
|
||||||
|
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,57 +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
|
|
||||||
}
|
|
||||||
return isAllowed(m.AddrPort().Addr().Unmap()) && !isDisAllowed(m.AddrPort().Addr().Unmap())
|
|
||||||
}
|
|
||||||
|
|
||||||
func isAllowed(addr netip.Addr) bool {
|
|
||||||
if addr.IsValid() {
|
|
||||||
for _, prefix := range lanAllowedIPs {
|
|
||||||
if prefix.Contains(addr) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func isDisAllowed(addr netip.Addr) bool {
|
|
||||||
if addr.IsValid() {
|
|
||||||
for _, prefix := range lanDisAllowedIPs {
|
|
||||||
if prefix.Contains(addr) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/metacubex/tfo-go"
|
"github.com/sagernet/tfo-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|||||||
22
adapter/inbound/mitm.go
Normal file
22
adapter/inbound/mitm.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewMitm receive mitm request and return MitmContext
|
||||||
|
func NewMitm(target socks5.Addr, source net.Addr, userAgent string, conn net.Conn) *context.ConnContext {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = C.TCP
|
||||||
|
metadata.Type = C.MITM
|
||||||
|
metadata.UserAgent = userAgent
|
||||||
|
if ip, port, err := parseAddr(source); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
||||||
@@ -1,22 +1,42 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
||||||
|
type PacketAdapter struct {
|
||||||
|
C.UDPPacket
|
||||||
|
metadata *C.Metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata returns destination metadata
|
||||||
|
func (s *PacketAdapter) Metadata() *C.Metadata {
|
||||||
|
return s.metadata
|
||||||
|
}
|
||||||
|
|
||||||
// NewPacket is PacketAdapter generator
|
// NewPacket is PacketAdapter generator
|
||||||
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions ...Addition) (C.UDPPacket, *C.Metadata) {
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions ...Addition) C.PacketAdapter {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.UDP
|
metadata.NetWork = C.UDP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
metadata.RawSrcAddr = packet.LocalAddr()
|
for _, addition := range additions {
|
||||||
metadata.RawDstAddr = metadata.UDPAddr()
|
addition.Apply(metadata)
|
||||||
ApplyAdditions(metadata, WithSrcAddr(packet.LocalAddr()))
|
}
|
||||||
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
if ip, port, err := parseAddr(packet.LocalAddr()); err == nil {
|
||||||
ApplyAdditions(metadata, WithInAddr(p.InAddr()))
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
||||||
|
if ip, port, err := parseAddr(p.InAddr()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ApplyAdditions(metadata, additions...)
|
|
||||||
|
|
||||||
return packet, metadata
|
return &PacketAdapter{
|
||||||
|
packet,
|
||||||
|
metadata,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,51 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/socks5"
|
"github.com/Dreamacro/clash/context"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewSocket receive TCP inbound and return ConnContext
|
// NewSocket receive TCP inbound and return ConnContext
|
||||||
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Addition) (net.Conn, *C.Metadata) {
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Addition) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
ApplyAdditions(metadata, WithSrcAddr(conn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
for _, addition := range additions {
|
||||||
ApplyAdditions(metadata, additions...)
|
addition.Apply(metadata)
|
||||||
return conn, metadata
|
}
|
||||||
|
|
||||||
|
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInner(conn net.Conn, address string) *context.ConnContext {
|
||||||
|
metadata := &C.Metadata{}
|
||||||
|
metadata.NetWork = C.TCP
|
||||||
|
metadata.Type = C.INNER
|
||||||
|
metadata.DNSMode = C.DNSNormal
|
||||||
|
metadata.Process = C.ClashName
|
||||||
|
if h, port, err := net.SplitHostPort(address); err == nil {
|
||||||
|
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
||||||
|
metadata.DstPort = uint16(port)
|
||||||
|
}
|
||||||
|
if ip, err := netip.ParseAddr(h); err == nil {
|
||||||
|
metadata.DstIP = ip
|
||||||
|
} else {
|
||||||
|
metadata.Host = h
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/nnip"
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
@@ -61,3 +62,29 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parseAddr(addr net.Addr) (netip.Addr, uint16, error) {
|
||||||
|
// Filter when net.Addr interface is nil
|
||||||
|
if addr == nil {
|
||||||
|
return netip.Addr{}, 0, errors.New("nil addr")
|
||||||
|
}
|
||||||
|
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
|
||||||
|
ip, port, err := parseAddr(rawAddr.RawAddr())
|
||||||
|
if err == nil {
|
||||||
|
return ip, port, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addrStr := addr.String()
|
||||||
|
host, port, err := net.SplitHostPort(addrStr)
|
||||||
|
if err != nil {
|
||||||
|
return netip.Addr{}, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var uint16Port uint16
|
||||||
|
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
||||||
|
uint16Port = uint16(port)
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := netip.ParseAddr(host)
|
||||||
|
return ip, uint16Port, err
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
|
|||||||
@@ -3,18 +3,15 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Direct struct {
|
type Direct struct {
|
||||||
*Base
|
*Base
|
||||||
loopBack *loopBackDetector
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type DirectOption struct {
|
type DirectOption struct {
|
||||||
@@ -24,23 +21,17 @@ 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 d.loopBack.CheckConn(metadata.SourceAddrPort()) {
|
|
||||||
return nil, fmt.Errorf("reject loopback connection to: %s", metadata.RemoteAddress())
|
|
||||||
}
|
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
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
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
N.TCPKeepAlive(c)
|
||||||
return d.loopBack.NewConn(NewConn(c, d)), nil
|
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 d.loopBack.CheckPacketConn(metadata.SourceAddrPort()) {
|
|
||||||
return nil, fmt.Errorf("reject loopback connection to: %s", metadata.RemoteAddress())
|
|
||||||
}
|
|
||||||
// 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.DefaultResolver)
|
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DefaultResolver)
|
||||||
@@ -49,11 +40,11 @@ func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
pc, err := dialer.NewDialer(d.Base.DialOptions(opts...)...).ListenPacket(ctx, "udp", "", netip.AddrPortFrom(metadata.DstIP, metadata.DstPort))
|
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", metadata.DstIP), "", d.Base.DialOptions(opts...)...)
|
||||||
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 NewDirectWithOption(option DirectOption) *Direct {
|
func NewDirectWithOption(option DirectOption) *Direct {
|
||||||
@@ -68,7 +59,6 @@ func NewDirectWithOption(option DirectOption) *Direct {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
loopBack: newLoopBackDetector(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +70,6 @@ func NewDirect() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
loopBack: newLoopBackDetector(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,6 +81,5 @@ func NewCompatible() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
loopBack: newLoopBackDetector(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/callback"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
|
|
||||||
"github.com/puzpuzpuz/xsync/v3"
|
|
||||||
)
|
|
||||||
|
|
||||||
type loopBackDetector struct {
|
|
||||||
connMap *xsync.MapOf[netip.AddrPort, struct{}]
|
|
||||||
packetConnMap *xsync.MapOf[netip.AddrPort, struct{}]
|
|
||||||
}
|
|
||||||
|
|
||||||
func newLoopBackDetector() *loopBackDetector {
|
|
||||||
return &loopBackDetector{
|
|
||||||
connMap: xsync.NewMapOf[netip.AddrPort, struct{}](),
|
|
||||||
packetConnMap: xsync.NewMapOf[netip.AddrPort, struct{}](),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loopBackDetector) NewConn(conn C.Conn) C.Conn {
|
|
||||||
metadata := C.Metadata{}
|
|
||||||
if metadata.SetRemoteAddr(conn.LocalAddr()) != nil {
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
connAddr := metadata.AddrPort()
|
|
||||||
if !connAddr.IsValid() {
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
l.connMap.Store(connAddr, struct{}{})
|
|
||||||
return callback.NewCloseCallbackConn(conn, func() {
|
|
||||||
l.connMap.Delete(connAddr)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loopBackDetector) NewPacketConn(conn C.PacketConn) C.PacketConn {
|
|
||||||
metadata := C.Metadata{}
|
|
||||||
if metadata.SetRemoteAddr(conn.LocalAddr()) != nil {
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
connAddr := metadata.AddrPort()
|
|
||||||
if !connAddr.IsValid() {
|
|
||||||
return conn
|
|
||||||
}
|
|
||||||
l.packetConnMap.Store(connAddr, struct{}{})
|
|
||||||
return callback.NewCloseCallbackPacketConn(conn, func() {
|
|
||||||
l.packetConnMap.Delete(connAddr)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loopBackDetector) CheckConn(connAddr netip.AddrPort) bool {
|
|
||||||
if !connAddr.IsValid() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := l.connMap.Load(connAddr)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loopBackDetector) CheckPacketConn(connAddr netip.AddrPort) bool {
|
|
||||||
if !connAddr.IsValid() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := l.packetConnMap.Load(connAddr)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(d.ctx, resolver.DefaultDnsRelayTimeout)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
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
|
|
||||||
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),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -13,11 +13,11 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Http struct {
|
type Http struct {
|
||||||
@@ -113,6 +113,10 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
tempHeaders["Proxy-Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
|
tempHeaders["Proxy-Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if metadata.Type == C.MITM {
|
||||||
|
tempHeaders["Origin-Request-Source-Address"] = metadata.SourceAddress()
|
||||||
|
}
|
||||||
|
|
||||||
for key, value := range tempHeaders {
|
for key, value := range tempHeaders {
|
||||||
HeaderString += key + ": " + value + "\r\n"
|
HeaderString += key + ": " + value + "\r\n"
|
||||||
}
|
}
|
||||||
@@ -157,13 +161,19 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
var err error
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: sni,
|
ServerName: sni,
|
||||||
}, option.Fingerprint)
|
})
|
||||||
if err != nil {
|
} else {
|
||||||
return nil, err
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
}, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,16 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -14,17 +19,17 @@ 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"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
hyCongestion "github.com/metacubex/mihomo/transport/hysteria/congestion"
|
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
||||||
"github.com/metacubex/mihomo/transport/hysteria/core"
|
"github.com/Dreamacro/clash/transport/hysteria/core"
|
||||||
"github.com/metacubex/mihomo/transport/hysteria/obfs"
|
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
||||||
"github.com/metacubex/mihomo/transport/hysteria/pmtud_fix"
|
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
||||||
"github.com/metacubex/mihomo/transport/hysteria/transport"
|
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
||||||
"github.com/metacubex/mihomo/transport/hysteria/utils"
|
"github.com/Dreamacro/clash/transport/hysteria/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -38,6 +43,8 @@ const (
|
|||||||
DefaultHopInterval = 10
|
DefaultHopInterval = 10
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||||
|
|
||||||
type Hysteria struct {
|
type Hysteria struct {
|
||||||
*Base
|
*Base
|
||||||
|
|
||||||
@@ -46,7 +53,7 @@ type Hysteria struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
tcpConn, err := h.client.DialTCP(metadata.String(), metadata.DstPort, h.genHdc(ctx, opts...))
|
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), h.genHdc(ctx, opts...))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -113,12 +120,12 @@ type HysteriaOption struct {
|
|||||||
|
|
||||||
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||||
var up, down uint64
|
var up, down uint64
|
||||||
up = StringToBps(c.Up)
|
up = stringToBps(c.Up)
|
||||||
if up == 0 {
|
if up == 0 {
|
||||||
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
||||||
}
|
}
|
||||||
|
|
||||||
down = StringToBps(c.Down)
|
down = stringToBps(c.Down)
|
||||||
if down == 0 {
|
if down == 0 {
|
||||||
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
||||||
}
|
}
|
||||||
@@ -146,10 +153,37 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
MinVersion: tls.VersionTLS13,
|
MinVersion: tls.VersionTLS13,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var bs []byte
|
||||||
var err error
|
var err error
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
if len(option.CustomCA) > 0 {
|
||||||
if err != nil {
|
bs, err = os.ReadFile(option.CustomCA)
|
||||||
return nil, err
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
|
||||||
|
}
|
||||||
|
} else if option.CustomCAString != "" {
|
||||||
|
bs = []byte(option.CustomCAString)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(bs) > 0 {
|
||||||
|
block, _ := pem.Decode(bs)
|
||||||
|
if block == nil {
|
||||||
|
return nil, fmt.Errorf("CA cert is not PEM")
|
||||||
|
}
|
||||||
|
|
||||||
|
fpBytes := sha256.Sum256(block.Bytes)
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) != 0 {
|
||||||
|
var err error
|
||||||
|
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if len(option.ALPN) > 0 {
|
||||||
@@ -234,6 +268,42 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func stringToBps(s string) uint64 {
|
||||||
|
if s == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// when have not unit, use Mbps
|
||||||
|
if v, err := strconv.Atoi(s); err == nil {
|
||||||
|
return stringToBps(fmt.Sprintf("%d Mbps", v))
|
||||||
|
}
|
||||||
|
|
||||||
|
m := rateStringRegexp.FindStringSubmatch(s)
|
||||||
|
if m == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var n uint64
|
||||||
|
switch m[2] {
|
||||||
|
case "K":
|
||||||
|
n = 1 << 10
|
||||||
|
case "M":
|
||||||
|
n = 1 << 20
|
||||||
|
case "G":
|
||||||
|
n = 1 << 30
|
||||||
|
case "T":
|
||||||
|
n = 1 << 40
|
||||||
|
default:
|
||||||
|
n = 1
|
||||||
|
}
|
||||||
|
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||||
|
n = v * n
|
||||||
|
if m[3] == "b" {
|
||||||
|
// Bits, need to convert to bytes
|
||||||
|
n = n >> 3
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
type hyPacketConn struct {
|
type hyPacketConn struct {
|
||||||
core.UDPConn
|
core.UDPConn
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,205 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
CN "github.com/metacubex/mihomo/common/net"
|
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
"github.com/metacubex/mihomo/log"
|
|
||||||
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
|
||||||
|
|
||||||
"github.com/metacubex/sing-quic/hysteria2"
|
|
||||||
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
|
||||||
}
|
|
||||||
|
|
||||||
const minHopInterval = 5
|
|
||||||
const defaultHopInterval = 30
|
|
||||||
|
|
||||||
type Hysteria2 struct {
|
|
||||||
*Base
|
|
||||||
|
|
||||||
option *Hysteria2Option
|
|
||||||
client *hysteria2.Client
|
|
||||||
dialer proxydialer.SingDialer
|
|
||||||
}
|
|
||||||
|
|
||||||
type Hysteria2Option struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port,omitempty"`
|
|
||||||
Ports string `proxy:"ports,omitempty"`
|
|
||||||
HopInterval int `proxy:"hop-interval,omitempty"`
|
|
||||||
Up string `proxy:"up,omitempty"`
|
|
||||||
Down string `proxy:"down,omitempty"`
|
|
||||||
Password string `proxy:"password,omitempty"`
|
|
||||||
Obfs string `proxy:"obfs,omitempty"`
|
|
||||||
ObfsPassword string `proxy:"obfs-password,omitempty"`
|
|
||||||
SNI string `proxy:"sni,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
|
||||||
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) {
|
|
||||||
options := h.Base.DialOptions(opts...)
|
|
||||||
h.dialer.SetDialer(dialer.NewDialer(options...))
|
|
||||||
c, err := h.client.DialConn(ctx, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return NewConn(CN.NewRefConn(c, h), h), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hysteria2) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
options := h.Base.DialOptions(opts...)
|
|
||||||
h.dialer.SetDialer(dialer.NewDialer(options...))
|
|
||||||
pc, err := h.client.ListenPacket(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if pc == nil {
|
|
||||||
return nil, errors.New("packetConn is nil")
|
|
||||||
}
|
|
||||||
return newPacketConn(CN.NewRefPacketConn(CN.NewThreadSafePacketConn(pc), h), h), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeHysteria2(h *Hysteria2) {
|
|
||||||
if h.client != nil {
|
|
||||||
_ = h.client.CloseWithError(errors.New("proxy removed"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
var salamanderPassword string
|
|
||||||
if len(option.Obfs) > 0 {
|
|
||||||
if option.ObfsPassword == "" {
|
|
||||||
return nil, errors.New("missing obfs password")
|
|
||||||
}
|
|
||||||
switch option.Obfs {
|
|
||||||
case hysteria2.ObfsTypeSalamander:
|
|
||||||
salamanderPassword = option.ObfsPassword
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unknown obfs type: %s", option.Obfs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
serverName := option.Server
|
|
||||||
if option.SNI != "" {
|
|
||||||
serverName = option.SNI
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
ServerName: serverName,
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
MinVersion: tls.VersionTLS13,
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
|
||||||
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())
|
|
||||||
|
|
||||||
clientOptions := hysteria2.ClientOptions{
|
|
||||||
Context: context.TODO(),
|
|
||||||
Dialer: singDialer,
|
|
||||||
Logger: log.SingLogger,
|
|
||||||
SendBPS: StringToBps(option.Up),
|
|
||||||
ReceiveBPS: StringToBps(option.Down),
|
|
||||||
SalamanderPassword: salamanderPassword,
|
|
||||||
Password: option.Password,
|
|
||||||
TLSConfig: tlsConfig,
|
|
||||||
UDPDisabled: false,
|
|
||||||
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[fastrand.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)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
outbound := &Hysteria2{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: addr,
|
|
||||||
tp: C.Hysteria2,
|
|
||||||
udp: true,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
option: &option,
|
|
||||||
client: client,
|
|
||||||
dialer: singDialer,
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeHysteria2)
|
|
||||||
|
|
||||||
return outbound, nil
|
|
||||||
}
|
|
||||||
50
adapter/outbound/mitm.go
Normal file
50
adapter/outbound/mitm.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Mitm struct {
|
||||||
|
*Base
|
||||||
|
serverAddr *net.TCPAddr
|
||||||
|
httpProxyClient *Http
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (m *Mitm) DialContext(ctx context.Context, metadata *C.Metadata, _ ...dialer.Option) (C.Conn, error) {
|
||||||
|
c, err := net.DialTCP("tcp", nil, m.serverAddr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = c.SetKeepAlive(true)
|
||||||
|
_ = c.SetKeepAlivePeriod(60 * time.Second)
|
||||||
|
|
||||||
|
metadata.Type = C.MITM
|
||||||
|
|
||||||
|
hc, err := m.httpProxyClient.StreamConnContext(ctx, c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
_ = c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(hc, m), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMitm(serverAddr string) *Mitm {
|
||||||
|
tcpAddr, _ := net.ResolveTCPAddr("tcp", serverAddr)
|
||||||
|
http, _ := NewHttp(HttpOption{})
|
||||||
|
return &Mitm{
|
||||||
|
Base: &Base{
|
||||||
|
name: "Mitm",
|
||||||
|
tp: C.Mitm,
|
||||||
|
},
|
||||||
|
serverAddr: tcpAddr,
|
||||||
|
httpProxyClient: http,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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/Dreamacro/clash/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 {
|
||||||
|
|||||||
@@ -6,41 +6,23 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/buf"
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Reject struct {
|
type Reject struct {
|
||||||
*Base
|
*Base
|
||||||
drop bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type RejectOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
if r.drop {
|
|
||||||
return NewConn(dropConn{}, r), nil
|
|
||||||
}
|
|
||||||
return NewConn(nopConn{}, r), nil
|
return NewConn(nopConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
return newPacketConn(&nopPacketConn{}, r), nil
|
return newPacketConn(nopPacketConn{}, r), nil
|
||||||
}
|
|
||||||
|
|
||||||
func NewRejectWithOption(option RejectOption) *Reject {
|
|
||||||
return &Reject{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Direct,
|
|
||||||
udp: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
@@ -54,18 +36,6 @@ func NewReject() *Reject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRejectDrop() *Reject {
|
|
||||||
return &Reject{
|
|
||||||
Base: &Base{
|
|
||||||
name: "REJECT-DROP",
|
|
||||||
tp: C.RejectDrop,
|
|
||||||
udp: true,
|
|
||||||
prefer: C.DualStack,
|
|
||||||
},
|
|
||||||
drop: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPass() *Reject {
|
func NewPass() *Reject {
|
||||||
return &Reject{
|
return &Reject{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
@@ -79,29 +49,35 @@ func NewPass() *Reject {
|
|||||||
|
|
||||||
type nopConn struct{}
|
type nopConn struct{}
|
||||||
|
|
||||||
func (rw nopConn) Read(b []byte) (int, error) { return 0, io.EOF }
|
func (rw nopConn) Read(b []byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error { return io.EOF }
|
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error {
|
||||||
|
return io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
func (rw nopConn) Write(b []byte) (int, error) { return 0, io.EOF }
|
func (rw nopConn) Write(b []byte) (int, error) {
|
||||||
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error { return io.EOF }
|
return 0, io.EOF
|
||||||
func (rw nopConn) Close() error { return nil }
|
}
|
||||||
func (rw nopConn) LocalAddr() net.Addr { return nil }
|
|
||||||
func (rw nopConn) RemoteAddr() net.Addr { return nil }
|
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||||
func (rw nopConn) SetDeadline(time.Time) error { return nil }
|
return io.EOF
|
||||||
func (rw nopConn) SetReadDeadline(time.Time) error { return nil }
|
}
|
||||||
func (rw nopConn) SetWriteDeadline(time.Time) error { return nil }
|
|
||||||
|
func (rw nopConn) Close() error { return nil }
|
||||||
|
func (rw nopConn) LocalAddr() net.Addr { return nil }
|
||||||
|
func (rw nopConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
func (rw nopConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (rw nopConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (rw nopConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
var udpAddrIPv4Unspecified = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
var udpAddrIPv4Unspecified = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||||
|
|
||||||
type nopPacketConn struct{}
|
type nopPacketConn struct{}
|
||||||
|
|
||||||
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
||||||
return len(b), nil
|
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
||||||
}
|
|
||||||
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
return 0, nil, io.EOF
|
|
||||||
}
|
|
||||||
func (npc nopPacketConn) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
func (npc nopPacketConn) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
||||||
return nil, nil, nil, io.EOF
|
return nil, nil, nil, io.EOF
|
||||||
}
|
}
|
||||||
@@ -110,19 +86,3 @@ func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4U
|
|||||||
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
type dropConn struct{}
|
|
||||||
|
|
||||||
func (rw dropConn) Read(b []byte) (int, error) { return 0, io.EOF }
|
|
||||||
func (rw dropConn) ReadBuffer(buffer *buf.Buffer) error {
|
|
||||||
time.Sleep(C.DefaultDropTime)
|
|
||||||
return io.EOF
|
|
||||||
}
|
|
||||||
func (rw dropConn) Write(b []byte) (int, error) { return 0, io.EOF }
|
|
||||||
func (rw dropConn) WriteBuffer(buffer *buf.Buffer) error { return io.EOF }
|
|
||||||
func (rw dropConn) Close() error { return nil }
|
|
||||||
func (rw dropConn) LocalAddr() net.Addr { return nil }
|
|
||||||
func (rw dropConn) RemoteAddr() net.Addr { return nil }
|
|
||||||
func (rw dropConn) SetDeadline(time.Time) error { return nil }
|
|
||||||
func (rw dropConn) SetReadDeadline(time.Time) error { return nil }
|
|
||||||
func (rw dropConn) SetWriteDeadline(time.Time) error { return nil }
|
|
||||||
|
|||||||
@@ -7,20 +7,19 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/restls"
|
"github.com/Dreamacro/clash/transport/restls"
|
||||||
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
|
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
||||||
v2rayObfs "github.com/metacubex/mihomo/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
|
||||||
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"
|
||||||
)
|
)
|
||||||
@@ -59,16 +58,14 @@ type simpleObfsOption struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type v2rayObfsOption struct {
|
type v2rayObfsOption struct {
|
||||||
Mode string `obfs:"mode"`
|
Mode string `obfs:"mode"`
|
||||||
Host string `obfs:"host,omitempty"`
|
Host string `obfs:"host,omitempty"`
|
||||||
Path string `obfs:"path,omitempty"`
|
Path string `obfs:"path,omitempty"`
|
||||||
TLS bool `obfs:"tls,omitempty"`
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
Headers map[string]string `obfs:"headers,omitempty"`
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
V2rayHttpUpgrade bool `obfs:"v2ray-http-upgrade,omitempty"`
|
|
||||||
V2rayHttpUpgradeFastOpen bool `obfs:"v2ray-http-upgrade-fast-open,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type shadowTLSOption struct {
|
type shadowTLSOption struct {
|
||||||
@@ -126,9 +123,9 @@ func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metada
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if useEarly {
|
if useEarly {
|
||||||
return ss.method.DialEarlyConn(c, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort)), nil
|
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
} else {
|
} else {
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,7 +185,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,9 +208,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
|
||||||
@@ -262,12 +259,10 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
}
|
}
|
||||||
obfsMode = opts.Mode
|
obfsMode = opts.Mode
|
||||||
v2rayOption = &v2rayObfs.Option{
|
v2rayOption = &v2rayObfs.Option{
|
||||||
Host: opts.Host,
|
Host: opts.Host,
|
||||||
Path: opts.Path,
|
Path: opts.Path,
|
||||||
Headers: opts.Headers,
|
Headers: opts.Headers,
|
||||||
Mux: opts.Mux,
|
Mux: opts.Mux,
|
||||||
V2rayHttpUpgrade: opts.V2rayHttpUpgrade,
|
|
||||||
V2rayHttpUpgradeFastOpen: opts.V2rayHttpUpgradeFastOpen,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.TLS {
|
if opts.TLS {
|
||||||
|
|||||||
@@ -7,16 +7,16 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/shadowsocks/core"
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
||||||
"github.com/metacubex/mihomo/transport/shadowsocks/shadowstream"
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
||||||
"github.com/metacubex/mihomo/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/metacubex/mihomo/transport/ssr/obfs"
|
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||||
"github.com/metacubex/mihomo/transport/ssr/protocol"
|
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocksR struct {
|
type ShadowSocksR struct {
|
||||||
@@ -125,7 +125,7 @@ func (ssr *ShadowSocksR) SupportWithDialer() C.NetWork {
|
|||||||
|
|
||||||
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/Dreamacro/clash/pull/2056
|
||||||
if option.Cipher == "none" {
|
if option.Cipher == "none" {
|
||||||
option.Cipher = "dummy"
|
option.Cipher = "dummy"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,54 +3,66 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"net"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
CN "github.com/metacubex/mihomo/common/net"
|
CN "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
|
||||||
|
|
||||||
mux "github.com/sagernet/sing-mux"
|
mux "github.com/sagernet/sing-mux"
|
||||||
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"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
type SingMux struct {
|
type SingMux struct {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
base ProxyBase
|
base ProxyBase
|
||||||
client *mux.Client
|
client *mux.Client
|
||||||
dialer proxydialer.SingDialer
|
dialer *muxSingDialer
|
||||||
onlyTcp bool
|
onlyTcp bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type SingMuxOption struct {
|
type SingMuxOption struct {
|
||||||
Enabled bool `proxy:"enabled,omitempty"`
|
Enabled bool `proxy:"enabled,omitempty"`
|
||||||
Protocol string `proxy:"protocol,omitempty"`
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
MaxConnections int `proxy:"max-connections,omitempty"`
|
MaxConnections int `proxy:"max-connections,omitempty"`
|
||||||
MinStreams int `proxy:"min-streams,omitempty"`
|
MinStreams int `proxy:"min-streams,omitempty"`
|
||||||
MaxStreams int `proxy:"max-streams,omitempty"`
|
MaxStreams int `proxy:"max-streams,omitempty"`
|
||||||
Padding bool `proxy:"padding,omitempty"`
|
Padding bool `proxy:"padding,omitempty"`
|
||||||
Statistic bool `proxy:"statistic,omitempty"`
|
Statistic bool `proxy:"statistic,omitempty"`
|
||||||
OnlyTcp bool `proxy:"only-tcp,omitempty"`
|
OnlyTcp bool `proxy:"only-tcp,omitempty"`
|
||||||
BrutalOpts BrutalOption `proxy:"brutal-opts,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type BrutalOption struct {
|
|
||||||
Enabled bool `proxy:"enabled,omitempty"`
|
|
||||||
Up string `proxy:"up,omitempty"`
|
|
||||||
Down string `proxy:"down,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ProxyBase interface {
|
type ProxyBase interface {
|
||||||
DialOptions(opts ...dialer.Option) []dialer.Option
|
DialOptions(opts ...dialer.Option) []dialer.Option
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type muxSingDialer struct {
|
||||||
|
dialer dialer.Dialer
|
||||||
|
proxy C.ProxyAdapter
|
||||||
|
statistic bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.Dialer = (*muxSingDialer)(nil)
|
||||||
|
|
||||||
|
func (d *muxSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
var cDialer C.Dialer = proxydialer.New(d.proxy, d.dialer, d.statistic)
|
||||||
|
return cDialer.DialContext(ctx, network, destination.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *muxSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
var cDialer C.Dialer = proxydialer.New(d.proxy, d.dialer, d.statistic)
|
||||||
|
return cDialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
||||||
|
}
|
||||||
|
|
||||||
func (s *SingMux) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (s *SingMux) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
options := s.base.DialOptions(opts...)
|
options := s.base.DialOptions(opts...)
|
||||||
s.dialer.SetDialer(dialer.NewDialer(options...))
|
s.dialer.dialer = dialer.NewDialer(options...)
|
||||||
c, err := s.client.DialContext(ctx, "tcp", M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
c, err := s.client.DialContext(ctx, "tcp", M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -62,7 +74,7 @@ func (s *SingMux) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
return s.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
return s.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
||||||
}
|
}
|
||||||
options := s.base.DialOptions(opts...)
|
options := s.base.DialOptions(opts...)
|
||||||
s.dialer.SetDialer(dialer.NewDialer(options...))
|
s.dialer.dialer = dialer.NewDialer(options...)
|
||||||
|
|
||||||
// sing-mux use stream-oriented udp with a special address, so we need a net.UDPAddr
|
// sing-mux use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
@@ -102,23 +114,14 @@ func closeSingMux(s *SingMux) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewSingMux(option SingMuxOption, proxy C.ProxyAdapter, base ProxyBase) (C.ProxyAdapter, error) {
|
func NewSingMux(option SingMuxOption, proxy C.ProxyAdapter, base ProxyBase) (C.ProxyAdapter, error) {
|
||||||
// TODO
|
singDialer := &muxSingDialer{dialer: dialer.NewDialer(), proxy: proxy, statistic: option.Statistic}
|
||||||
// "TCP Brutal is only supported on Linux-based systems"
|
|
||||||
|
|
||||||
singDialer := proxydialer.NewSingDialer(proxy, dialer.NewDialer(), option.Statistic)
|
|
||||||
client, err := mux.NewClient(mux.Options{
|
client, err := mux.NewClient(mux.Options{
|
||||||
Dialer: singDialer,
|
Dialer: singDialer,
|
||||||
Logger: log.SingLogger,
|
|
||||||
Protocol: option.Protocol,
|
Protocol: option.Protocol,
|
||||||
MaxConnections: option.MaxConnections,
|
MaxConnections: option.MaxConnections,
|
||||||
MinStreams: option.MinStreams,
|
MinStreams: option.MinStreams,
|
||||||
MaxStreams: option.MaxStreams,
|
MaxStreams: option.MaxStreams,
|
||||||
Padding: option.Padding,
|
Padding: option.Padding,
|
||||||
Brutal: mux.BrutalOptions{
|
|
||||||
Enabled: option.BrutalOpts.Enabled,
|
|
||||||
SendBPS: StringToBps(option.BrutalOpts.Up),
|
|
||||||
ReceiveBPS: StringToBps(option.BrutalOpts.Down),
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
"github.com/metacubex/mihomo/transport/snell"
|
"github.com/Dreamacro/clash/transport/snell"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Snell struct {
|
type Snell struct {
|
||||||
|
|||||||
@@ -7,15 +7,14 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Socks5 struct {
|
type Socks5 struct {
|
||||||
@@ -137,8 +136,7 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
udpAssocateAddr := socks5.AddrFromStdAddrPort(netip.AddrPortFrom(netip.IPv4Unspecified(), 0))
|
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
||||||
bindAddr, err := socks5.ClientHandshake(c, udpAssocateAddr, socks5.CmdUDPAssociate, user)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("client hanshake error: %w", err)
|
err = fmt.Errorf("client hanshake error: %w", err)
|
||||||
return
|
return
|
||||||
@@ -158,7 +156,7 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
bindUDPAddr.IP = serverAddr.IP
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := cDialer.ListenPacket(ctx, "udp", "", bindUDPAddr.AddrPort())
|
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", bindUDPAddr.AddrPort().Addr()), "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -182,10 +180,13 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
if err != nil {
|
} else {
|
||||||
return nil, err
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,208 +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/zhangyunhao116/fastrand"
|
|
||||||
"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
|
|
||||||
}
|
|
||||||
N.TCPKeepAlive(c)
|
|
||||||
|
|
||||||
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()
|
|
||||||
}
|
|
||||||
|
|
||||||
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 fastrand.Intn(2) == 0 {
|
|
||||||
version += "7." + strconv.Itoa(fastrand.Intn(10))
|
|
||||||
} else {
|
|
||||||
version += "8." + strconv.Itoa(fastrand.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
|
|
||||||
}
|
|
||||||
@@ -8,14 +8,13 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/metacubex/mihomo/transport/gun"
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
"github.com/metacubex/mihomo/transport/trojan"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Trojan struct {
|
type Trojan struct {
|
||||||
@@ -53,12 +52,9 @@ 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)
|
||||||
wsOpts := &trojan.WebsocketOption{
|
wsOpts := &trojan.WebsocketOption{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: t.option.WSOpts.Path,
|
Path: t.option.WSOpts.Path,
|
||||||
V2rayHttpUpgrade: t.option.WSOpts.V2rayHttpUpgrade,
|
|
||||||
V2rayHttpUpgradeFastOpen: t.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
|
||||||
Headers: http.Header{},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.option.SNI != "" {
|
if t.option.SNI != "" {
|
||||||
@@ -66,9 +62,11 @@ func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(t.option.WSOpts.Headers) != 0 {
|
if len(t.option.WSOpts.Headers) != 0 {
|
||||||
|
header := http.Header{}
|
||||||
for key, value := range t.option.WSOpts.Headers {
|
for key, value := range t.option.WSOpts.Headers {
|
||||||
wsOpts.Headers.Add(key, value)
|
header.Add(key, value)
|
||||||
}
|
}
|
||||||
|
wsOpts.Headers = header
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.instance.StreamWebsocketConn(ctx, c, wsOpts)
|
return t.instance.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
@@ -282,10 +280,13 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: tOption.ServerName,
|
ServerName: tOption.ServerName,
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
if err != nil {
|
} else {
|
||||||
return nil, err
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint, t.realityConfig)
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint, t.realityConfig)
|
||||||
|
|||||||
@@ -2,20 +2,24 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/tuic"
|
"github.com/Dreamacro/clash/transport/tuic"
|
||||||
|
|
||||||
"github.com/gofrs/uuid/v5"
|
"github.com/gofrs/uuid/v5"
|
||||||
"github.com/metacubex/quic-go"
|
"github.com/metacubex/quic-go"
|
||||||
@@ -158,10 +162,37 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
tlsConfig.ServerName = option.SNI
|
tlsConfig.ServerName = option.SNI
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var bs []byte
|
||||||
var err error
|
var err error
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
if len(option.CustomCA) > 0 {
|
||||||
if err != nil {
|
bs, err = os.ReadFile(option.CustomCA)
|
||||||
return nil, err
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("tuic %s load ca error: %w", addr, err)
|
||||||
|
}
|
||||||
|
} else if option.CustomCAString != "" {
|
||||||
|
bs = []byte(option.CustomCAString)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(bs) > 0 {
|
||||||
|
block, _ := pem.Decode(bs)
|
||||||
|
if block == nil {
|
||||||
|
return nil, fmt.Errorf("CA cert is not PEM")
|
||||||
|
}
|
||||||
|
|
||||||
|
fpBytes := sha256.Sum256(block.Bytes)
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) != 0 {
|
||||||
|
var err error
|
||||||
|
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
@@ -292,10 +323,6 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
|
|
||||||
t.client = tuic.NewPoolClientV4(clientOption)
|
t.client = tuic.NewPoolClientV4(clientOption)
|
||||||
} else {
|
} else {
|
||||||
maxUdpRelayPacketSize := option.MaxUdpRelayPacketSize
|
|
||||||
if maxUdpRelayPacketSize > tuic.MaxFragSizeV5 {
|
|
||||||
maxUdpRelayPacketSize = tuic.MaxFragSizeV5
|
|
||||||
}
|
|
||||||
clientOption := &tuic.ClientOptionV5{
|
clientOption := &tuic.ClientOptionV5{
|
||||||
TlsConfig: tlsConfig,
|
TlsConfig: tlsConfig,
|
||||||
QuicConfig: quicConfig,
|
QuicConfig: quicConfig,
|
||||||
@@ -304,7 +331,7 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
UdpRelayMode: udpRelayMode,
|
UdpRelayMode: udpRelayMode,
|
||||||
CongestionController: option.CongestionController,
|
CongestionController: option.CongestionController,
|
||||||
ReduceRtt: option.ReduceRtt,
|
ReduceRtt: option.ReduceRtt,
|
||||||
MaxUdpRelayPacketSize: maxUdpRelayPacketSize,
|
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||||
MaxOpenStreams: clientMaxOpenStreams,
|
MaxOpenStreams: clientMaxOpenStreams,
|
||||||
CWND: option.CWND,
|
CWND: option.CWND,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,16 +4,13 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"regexp"
|
|
||||||
"strconv"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -123,42 +120,3 @@ func safeConnClose(c net.Conn, err error) {
|
|||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
|
||||||
|
|
||||||
func StringToBps(s string) uint64 {
|
|
||||||
if s == "" {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// when have not unit, use Mbps
|
|
||||||
if v, err := strconv.Atoi(s); err == nil {
|
|
||||||
return StringToBps(fmt.Sprintf("%d Mbps", v))
|
|
||||||
}
|
|
||||||
|
|
||||||
m := rateStringRegexp.FindStringSubmatch(s)
|
|
||||||
if m == nil {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
var n uint64 = 1
|
|
||||||
switch m[2] {
|
|
||||||
case "T":
|
|
||||||
n *= 1000
|
|
||||||
fallthrough
|
|
||||||
case "G":
|
|
||||||
n *= 1000
|
|
||||||
fallthrough
|
|
||||||
case "M":
|
|
||||||
n *= 1000
|
|
||||||
fallthrough
|
|
||||||
case "K":
|
|
||||||
n *= 1000
|
|
||||||
}
|
|
||||||
v, _ := strconv.ParseUint(m[1], 10, 64)
|
|
||||||
n *= v
|
|
||||||
if m[3] == "b" {
|
|
||||||
// Bits, need to convert to bytes
|
|
||||||
n /= 8
|
|
||||||
}
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -12,20 +12,19 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/convert"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/metacubex/mihomo/transport/gun"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/metacubex/mihomo/transport/socks5"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/metacubex/mihomo/transport/vless"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
"github.com/metacubex/mihomo/transport/vmess"
|
|
||||||
|
|
||||||
vmessSing "github.com/metacubex/sing-vmess"
|
vmessSing "github.com/metacubex/sing-vmess"
|
||||||
"github.com/metacubex/sing-vmess/packetaddr"
|
"github.com/metacubex/sing-vmess/packetaddr"
|
||||||
@@ -88,15 +87,13 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
case "ws":
|
case "ws":
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
V2rayHttpUpgrade: v.option.WSOpts.V2rayHttpUpgrade,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
V2rayHttpUpgradeFastOpen: v.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
Headers: http.Header{},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Headers: http.Header{},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
@@ -113,9 +110,13 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
NextProtos: []string{"http/1.1"},
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
wsOpts.TLSConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
if len(v.option.Fingerprint) == 0 {
|
||||||
if err != nil {
|
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
return nil, err
|
} else {
|
||||||
|
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@@ -373,7 +374,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
|
||||||
@@ -591,7 +592,7 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig = ca.GetGlobalTLSConfig(&tls.Config{
|
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -11,17 +11,16 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/ca"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
"github.com/Dreamacro/clash/ntp"
|
||||||
"github.com/metacubex/mihomo/ntp"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/metacubex/mihomo/transport/gun"
|
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||||
mihomoVMess "github.com/metacubex/mihomo/transport/vmess"
|
|
||||||
|
|
||||||
vmess "github.com/metacubex/sing-vmess"
|
vmess "github.com/metacubex/sing-vmess"
|
||||||
"github.com/metacubex/sing-vmess/packetaddr"
|
"github.com/metacubex/sing-vmess/packetaddr"
|
||||||
@@ -87,12 +86,10 @@ type GrpcOptions struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type WSOptions struct {
|
type WSOptions struct {
|
||||||
Path string `proxy:"path,omitempty"`
|
Path string `proxy:"path,omitempty"`
|
||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
||||||
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||||
V2rayHttpUpgrade bool `proxy:"v2ray-http-upgrade,omitempty"`
|
|
||||||
V2rayHttpUpgradeFastOpen bool `proxy:"v2ray-http-upgrade-fast-open,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
@@ -106,16 +103,14 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &mihomoVMess.WebsocketConfig{
|
wsOpts := &clashVMess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
V2rayHttpUpgrade: v.option.WSOpts.V2rayHttpUpgrade,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
V2rayHttpUpgradeFastOpen: v.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
Headers: http.Header{},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Headers: http.Header{},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
@@ -132,9 +127,12 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
NextProtos: []string{"http/1.1"},
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
wsOpts.TLSConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
if len(v.option.Fingerprint) == 0 {
|
||||||
if err != nil {
|
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
return nil, err
|
} else {
|
||||||
|
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@@ -143,12 +141,12 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = mihomoVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
c, err = clashVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &mihomoVMess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
@@ -159,24 +157,24 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
c, err = mihomoVMess.StreamTLSConn(ctx, c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
httpOpts := &mihomoVMess.HTTPConfig{
|
httpOpts := &clashVMess.HTTPConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Method: v.option.HTTPOpts.Method,
|
Method: v.option.HTTPOpts.Method,
|
||||||
Path: v.option.HTTPOpts.Path,
|
Path: v.option.HTTPOpts.Path,
|
||||||
Headers: v.option.HTTPOpts.Headers,
|
Headers: v.option.HTTPOpts.Headers,
|
||||||
}
|
}
|
||||||
|
|
||||||
c = mihomoVMess.StreamHTTPConn(c, httpOpts)
|
c = clashVMess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := mihomoVMess.TLSConfig{
|
tlsOpts := clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
@@ -188,24 +186,24 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = mihomoVMess.StreamTLSConn(ctx, c, &tlsOpts)
|
c, err = clashVMess.StreamTLSConn(ctx, c, &tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
h2Opts := &mihomoVMess.H2Config{
|
h2Opts := &clashVMess.H2Config{
|
||||||
Hosts: v.option.HTTP2Opts.Host,
|
Hosts: v.option.HTTP2Opts.Host,
|
||||||
Path: v.option.HTTP2Opts.Path,
|
Path: v.option.HTTP2Opts.Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = mihomoVMess.StreamH2Conn(c, h2Opts)
|
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
||||||
default:
|
default:
|
||||||
// handle TLS
|
// handle TLS
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &mihomoVMess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
@@ -217,7 +215,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = mihomoVMess.StreamTLSConn(ctx, c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,10 +262,10 @@ func (v *Vmess) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err
|
|||||||
} else {
|
} else {
|
||||||
if N.NeedHandshake(c) {
|
if N.NeedHandshake(c) {
|
||||||
conn = v.client.DialEarlyConn(c,
|
conn = v.client.DialEarlyConn(c,
|
||||||
M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
} else {
|
} else {
|
||||||
conn, err = v.client.DialConn(c,
|
conn, err = v.client.DialConn(c,
|
||||||
M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -288,7 +286,7 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.DialConn(c, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
c, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -485,7 +483,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
}
|
}
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig = ca.GetGlobalTLSConfig(&tls.Config{
|
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -13,15 +13,13 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
CN "github.com/Dreamacro/clash/common/net"
|
||||||
CN "github.com/metacubex/mihomo/common/net"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
"github.com/metacubex/mihomo/component/resolver"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/component/slowdown"
|
"github.com/Dreamacro/clash/dns"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/metacubex/mihomo/dns"
|
|
||||||
"github.com/metacubex/mihomo/log"
|
|
||||||
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
|
||||||
@@ -29,6 +27,7 @@ import (
|
|||||||
"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"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/wireguard-go/device"
|
"github.com/sagernet/wireguard-go/device"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -37,8 +36,9 @@ type WireGuard struct {
|
|||||||
bind *wireguard.ClientBind
|
bind *wireguard.ClientBind
|
||||||
device *device.Device
|
device *device.Device
|
||||||
tunDevice wireguard.Device
|
tunDevice wireguard.Device
|
||||||
dialer proxydialer.SingDialer
|
dialer *wgSingDialer
|
||||||
init func(ctx context.Context) error
|
startOnce sync.Once
|
||||||
|
startErr error
|
||||||
resolver *dns.Resolver
|
resolver *dns.Resolver
|
||||||
refP *refProxyAdapter
|
refP *refProxyAdapter
|
||||||
}
|
}
|
||||||
@@ -47,8 +47,6 @@ 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"`
|
||||||
@@ -64,12 +62,45 @@ type WireGuardOption struct {
|
|||||||
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 wgSingDialer struct {
|
||||||
|
dialer dialer.Dialer
|
||||||
|
proxyName string
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.Dialer = (*wgSingDialer)(nil)
|
||||||
|
|
||||||
|
func (d *wgSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
var cDialer C.Dialer = d.dialer
|
||||||
|
if len(d.proxyName) > 0 {
|
||||||
|
pd, err := proxydialer.NewByName(d.proxyName, d.dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cDialer = pd
|
||||||
|
}
|
||||||
|
return cDialer.DialContext(ctx, network, destination.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *wgSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
var cDialer C.Dialer = d.dialer
|
||||||
|
if len(d.proxyName) > 0 {
|
||||||
|
pd, err := proxydialer.NewByName(d.proxyName, d.dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cDialer = pd
|
||||||
|
}
|
||||||
|
return cDialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
||||||
|
}
|
||||||
|
|
||||||
type wgSingErrorHandler struct {
|
type wgSingErrorHandler struct {
|
||||||
name string
|
name string
|
||||||
}
|
}
|
||||||
@@ -98,7 +129,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, "/") {
|
||||||
@@ -137,23 +168,10 @@ 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: &wgSingDialer{dialer: dialer.NewDialer(), proxyName: option.DialerProxy},
|
||||||
}
|
}
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
runtime.SetFinalizer(outbound, closeWireGuard)
|
||||||
|
|
||||||
resolv := func(ctx context.Context, address M.Socksaddr) (netip.AddrPort, error) {
|
|
||||||
if address.Addr.IsValid() {
|
|
||||||
return address.AddrPort(), nil
|
|
||||||
}
|
|
||||||
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", address.String(), outbound.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
|
|
||||||
}
|
|
||||||
|
|
||||||
var reserved [3]uint8
|
var reserved [3]uint8
|
||||||
if len(option.Reserved) > 0 {
|
if len(option.Reserved) > 0 {
|
||||||
if len(option.Reserved) != 3 {
|
if len(option.Reserved) != 3 {
|
||||||
@@ -171,12 +189,9 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
connectAddr = option.Addr()
|
connectAddr = option.Addr()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, connectAddr.AddrPort(), reserved)
|
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, connectAddr, reserved)
|
||||||
|
|
||||||
localPrefixes, err := option.Prefixes()
|
var localPrefixes []netip.Prefix
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var privateKey string
|
var privateKey string
|
||||||
{
|
{
|
||||||
@@ -186,146 +201,95 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
}
|
}
|
||||||
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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
if option.PersistentKeepalive != 0 {
|
||||||
initOk atomic.Bool
|
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
||||||
initMutex sync.Mutex
|
|
||||||
initErr error
|
|
||||||
)
|
|
||||||
|
|
||||||
outbound.init = func(ctx context.Context) error {
|
|
||||||
if initOk.Load() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
initMutex.Lock()
|
|
||||||
defer initMutex.Unlock()
|
|
||||||
// double check like sync.Once
|
|
||||||
if initOk.Load() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if initErr != nil {
|
|
||||||
return initErr
|
|
||||||
}
|
|
||||||
|
|
||||||
outbound.bind.ResetReservedForEndpoint()
|
|
||||||
ipcConf := "private_key=" + privateKey
|
|
||||||
if len(option.Peers) > 0 {
|
|
||||||
for i, peer := range option.Peers {
|
|
||||||
destination, err := resolv(ctx, peer.Addr())
|
|
||||||
if err != nil {
|
|
||||||
// !!! do not set initErr here !!!
|
|
||||||
// let us can retry domain resolve in next time
|
|
||||||
return E.Cause(err, "resolve endpoint domain for peer ", i)
|
|
||||||
}
|
|
||||||
ipcConf += "\npublic_key=" + peer.PublicKey
|
|
||||||
ipcConf += "\nendpoint=" + destination.String()
|
|
||||||
if peer.PreSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + peer.PreSharedKey
|
|
||||||
}
|
|
||||||
for _, allowedIP := range peer.AllowedIPs {
|
|
||||||
ipcConf += "\nallowed_ip=" + allowedIP
|
|
||||||
}
|
|
||||||
if len(peer.Reserved) > 0 {
|
|
||||||
copy(reserved[:], option.Reserved)
|
|
||||||
outbound.bind.SetReservedForEndpoint(destination, reserved)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ipcConf += "\npublic_key=" + option.PublicKey
|
|
||||||
destination, err := resolv(ctx, connectAddr)
|
|
||||||
if err != nil {
|
|
||||||
// !!! do not set initErr here !!!
|
|
||||||
// let us can retry domain resolve in next time
|
|
||||||
return E.Cause(err, "resolve endpoint domain")
|
|
||||||
}
|
|
||||||
outbound.bind.SetConnectAddr(destination)
|
|
||||||
ipcConf += "\nendpoint=" + destination.String()
|
|
||||||
if option.PreSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + option.PreSharedKey
|
|
||||||
}
|
|
||||||
var has4, has6 bool
|
|
||||||
for _, address := range localPrefixes {
|
|
||||||
if address.Addr().Is4() {
|
|
||||||
has4 = true
|
|
||||||
} else {
|
|
||||||
has6 = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if has4 {
|
|
||||||
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
|
||||||
}
|
|
||||||
if has6 {
|
|
||||||
ipcConf += "\nallowed_ip=::/0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.PersistentKeepalive != 0 {
|
|
||||||
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
|
||||||
}
|
|
||||||
|
|
||||||
if debug.Enabled {
|
|
||||||
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", option.Name, ipcConf))
|
|
||||||
}
|
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
|
||||||
if err != nil {
|
|
||||||
initErr = E.Cause(err, "setup wireguard")
|
|
||||||
return initErr
|
|
||||||
}
|
|
||||||
|
|
||||||
err = outbound.tunDevice.Start()
|
|
||||||
if err != nil {
|
|
||||||
initErr = err
|
|
||||||
return initErr
|
|
||||||
}
|
|
||||||
|
|
||||||
initOk.Store(true)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mtu := option.MTU
|
mtu := option.MTU
|
||||||
if mtu == 0 {
|
if mtu == 0 {
|
||||||
mtu = 1408
|
mtu = 1408
|
||||||
@@ -333,6 +297,7 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
if len(localPrefixes) == 0 {
|
if len(localPrefixes) == 0 {
|
||||||
return nil, E.New("missing local address")
|
return nil, E.New("missing local address")
|
||||||
}
|
}
|
||||||
|
var err error
|
||||||
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
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")
|
||||||
@@ -345,6 +310,14 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
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)
|
}, option.Workers)
|
||||||
|
if debug.Enabled {
|
||||||
|
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", option.Name, ipcConf))
|
||||||
|
}
|
||||||
|
err = outbound.device.IpcSet(ipcConf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "setup wireguard")
|
||||||
|
}
|
||||||
|
//err = outbound.tunDevice.Start()
|
||||||
|
|
||||||
var has6 bool
|
var has6 bool
|
||||||
for _, address := range localPrefixes {
|
for _, address := range localPrefixes {
|
||||||
@@ -382,10 +355,13 @@ func closeWireGuard(w *WireGuard) {
|
|||||||
|
|
||||||
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.dialer = 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
|
||||||
@@ -411,10 +387,13 @@ func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts
|
|||||||
|
|
||||||
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
options := w.Base.DialOptions(opts...)
|
options := w.Base.DialOptions(opts...)
|
||||||
w.dialer.SetDialer(dialer.NewDialer(options...))
|
w.dialer.dialer = dialer.NewDialer(options...)
|
||||||
var pc net.PacketConn
|
var pc net.PacketConn
|
||||||
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 err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/common/callback"
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
@@ -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 {
|
||||||
@@ -86,14 +84,11 @@ func (f *Fallback) 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": f.Type().String(),
|
"type": f.Type().String(),
|
||||||
"now": f.Now(),
|
"now": f.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": f.testUrl,
|
"testUrl": f.testUrl,
|
||||||
"expectedStatus": f.expectedStatus,
|
"expected": f.expectedStatus,
|
||||||
"fixed": f.selected,
|
|
||||||
"hidden": f.Hidden,
|
|
||||||
"icon": f.Icon,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,11 +102,13 @@ func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
|||||||
proxies := f.GetProxies(touch)
|
proxies := f.GetProxies(touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if len(f.selected) == 0 {
|
if len(f.selected) == 0 {
|
||||||
|
// if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(f.testUrl) {
|
if proxy.AliveForTestUrl(f.testUrl) {
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if proxy.Name() == f.selected {
|
if proxy.Name() == f.selected {
|
||||||
|
// if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(f.testUrl) {
|
if proxy.AliveForTestUrl(f.testUrl) {
|
||||||
return proxy
|
return proxy
|
||||||
} else {
|
} else {
|
||||||
@@ -138,11 +135,12 @@ func (f *Fallback) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
f.selected = name
|
f.selected = name
|
||||||
|
// if !p.Alive() {
|
||||||
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, C.ExtraHistory)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -164,14 +162,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,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,14 +7,14 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/metacubex/mihomo/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
)
|
)
|
||||||
@@ -28,21 +28,17 @@ type GroupBase struct {
|
|||||||
failedTestMux sync.Mutex
|
failedTestMux sync.Mutex
|
||||||
failedTimes int
|
failedTimes int
|
||||||
failedTime time.Time
|
failedTime time.Time
|
||||||
failedTesting atomic.Bool
|
failedTesting *atomic.Bool
|
||||||
proxies [][]C.Proxy
|
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 {
|
||||||
@@ -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))
|
||||||
@@ -215,7 +202,7 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string, expectedStatus uti
|
|||||||
proxy := proxy
|
proxy := proxy
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
delay, err := proxy.URLTest(ctx, url, expectedStatus)
|
delay, err := proxy.URLTest(ctx, url, expectedStatus, C.DropHistory)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
lock.Lock()
|
lock.Lock()
|
||||||
mp[proxy.Name()] = delay
|
mp[proxy.Name()] = delay
|
||||||
@@ -235,7 +222,7 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string, expectedStatus uti
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
||||||
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass || adapterType == C.RejectDrop {
|
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,14 +9,14 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/common/callback"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
"github.com/metacubex/mihomo/common/lru"
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
@@ -189,9 +190,9 @@ func strategyConsistentHashing(url string) strategyFn {
|
|||||||
func strategyStickySessions(url string) strategyFn {
|
func strategyStickySessions(url string) strategyFn {
|
||||||
ttl := time.Minute * 10
|
ttl := time.Minute * 10
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
lruCache := lru.New[uint64, int](
|
lruCache := cache.New[uint64, int](
|
||||||
lru.WithAge[uint64, int](int64(ttl.Seconds())),
|
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
lru.WithSize[uint64, int](1000))
|
cache.WithSize[uint64, int](1000))
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
|
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
@@ -203,6 +204,7 @@ 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 nowIdx != idx {
|
if nowIdx != idx {
|
||||||
lruCache.Delete(key)
|
lruCache.Delete(key)
|
||||||
@@ -238,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,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -266,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,12 +5,12 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/adapter/provider"
|
"github.com/Dreamacro/clash/adapter/provider"
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -22,28 +22,21 @@ var (
|
|||||||
|
|
||||||
type GroupCommonOption struct {
|
type GroupCommonOption struct {
|
||||||
outbound.BasicOption
|
outbound.BasicOption
|
||||||
Name string `group:"name"`
|
Name string `group:"name"`
|
||||||
Type string `group:"type"`
|
Type string `group:"type"`
|
||||||
Proxies []string `group:"proxies,omitempty"`
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
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"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
MaxFailedTimes int `group:"max-failed-times,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
Lazy bool `group:"lazy,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
ExcludeType string `group:"exclude-type,omitempty"`
|
||||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
ExpectedStatus string `group:"expected-status,omitempty"`
|
||||||
ExcludeType string `group:"exclude-type,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"`
|
|
||||||
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{
|
||||||
@@ -61,23 +54,11 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
|
|
||||||
providers := []types.ProxyProvider{}
|
providers := []types.ProxyProvider{}
|
||||||
|
|
||||||
if groupOption.IncludeAll {
|
|
||||||
groupOption.IncludeAllProviders = true
|
|
||||||
groupOption.IncludeAllProxies = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if groupOption.IncludeAllProviders {
|
|
||||||
groupOption.Use = append(groupOption.Use, AllProviders...)
|
|
||||||
}
|
|
||||||
if groupOption.IncludeAllProxies {
|
|
||||||
groupOption.Proxies = append(groupOption.Proxies, AllProxies...)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 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)
|
||||||
}
|
}
|
||||||
@@ -87,6 +68,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.Proxies) != 0 {
|
if len(groupOption.Proxies) != 0 {
|
||||||
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
@@ -98,18 +80,24 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var url string
|
||||||
|
var interval uint
|
||||||
|
|
||||||
// select don't need health check
|
// select don't need health check
|
||||||
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
||||||
|
if groupOption.URL == "" {
|
||||||
|
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
||||||
|
}
|
||||||
|
|
||||||
if groupOption.Interval == 0 {
|
if groupOption.Interval == 0 {
|
||||||
groupOption.Interval = 300
|
groupOption.Interval = 300
|
||||||
}
|
}
|
||||||
if groupOption.URL == "" {
|
|
||||||
groupOption.URL = C.DefaultTestURL
|
url = groupOption.URL
|
||||||
}
|
interval = uint(groupOption.Interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.TestTimeout), uint(groupOption.Interval), groupOption.Lazy, expectedStatus)
|
hc := provider.NewHealthCheck(ps, url, 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)
|
||||||
@@ -125,22 +113,12 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if groupOption.URL == "" {
|
|
||||||
for _, p := range list {
|
|
||||||
if p.HealthCheckURL() != "" {
|
|
||||||
groupOption.URL = p.HealthCheckURL()
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if groupOption.URL == "" {
|
|
||||||
groupOption.URL = C.DefaultTestURL
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// different proxy groups use different test URL
|
// different proxy groups use different test URL
|
||||||
addTestUrlToProviders(list, groupOption.URL, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
addTestUrlToProviders(list, testUrl, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
||||||
|
|
||||||
providers = append(providers, list...)
|
providers = append(providers, list...)
|
||||||
|
} else {
|
||||||
|
groupOption.Filter = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
//go:build android && cmfa
|
|
||||||
|
|
||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
C "github.com/metacubex/mihomo/constant"
|
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ProxyGroup interface {
|
|
||||||
C.ProxyAdapter
|
|
||||||
|
|
||||||
Providers() []provider.ProxyProvider
|
|
||||||
Proxies() []C.Proxy
|
|
||||||
Now() string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Providers() []provider.ProxyProvider {
|
|
||||||
return f.providers
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) Providers() []provider.ProxyProvider {
|
|
||||||
return lb.providers
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Proxies() []C.Proxy {
|
|
||||||
return f.GetProxies(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) Proxies() []C.Proxy {
|
|
||||||
return lb.GetProxies(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) Now() string {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Relay) Providers() []provider.ProxyProvider {
|
|
||||||
return r.providers
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Relay) Proxies() []C.Proxy {
|
|
||||||
return r.GetProxies(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Relay) Now() string {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Providers() []provider.ProxyProvider {
|
|
||||||
return s.providers
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Proxies() []C.Proxy {
|
|
||||||
return s.GetProxies(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Providers() []provider.ProxyProvider {
|
|
||||||
return u.providers
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Proxies() []C.Proxy {
|
|
||||||
return u.GetProxies(false)
|
|
||||||
}
|
|
||||||
@@ -3,18 +3,15 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/metacubex/mihomo/component/proxydialer"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Relay struct {
|
type Relay struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
Hidden bool
|
|
||||||
Icon string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@@ -109,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,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,11 +155,7 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
5000,
|
|
||||||
5,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
Hidden: option.Hidden,
|
|
||||||
Icon: option.Icon,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,18 +5,16 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Selector struct {
|
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,18 +4,15 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/common/callback"
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/metacubex/mihomo/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/metacubex/mihomo/component/dialer"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/metacubex/mihomo/constant/provider"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type urlTestOption func(*URLTest)
|
type urlTestOption func(*URLTest)
|
||||||
@@ -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]
|
||||||
}
|
}
|
||||||
@@ -106,7 +101,7 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
proxies := u.GetProxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
if u.selected != "" {
|
if u.selected != "" {
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if !proxy.AliveForTestUrl(u.testUrl) {
|
if !proxy.Alive() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if proxy.Name() == u.selected {
|
if proxy.Name() == u.selected {
|
||||||
@@ -118,7 +113,8 @@ 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.LastDelay()
|
||||||
|
min := fast.LastDelayForTestUrl(u.testUrl)
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
|
|
||||||
for _, proxy := range proxies[1:] {
|
for _, proxy := range proxies[1:] {
|
||||||
@@ -126,18 +122,21 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
fastNotExist = false
|
fastNotExist = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// if !proxy.Alive() {
|
||||||
if !proxy.AliveForTestUrl(u.testUrl) {
|
if !proxy.AliveForTestUrl(u.testUrl) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// delay := proxy.LastDelay()
|
||||||
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
||||||
if delay < minDelay {
|
if delay < min {
|
||||||
fast = proxy
|
fast = proxy
|
||||||
minDelay = delay
|
min = delay
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
// tolerance
|
// tolerance
|
||||||
|
// if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
||||||
if u.fastNode == nil || fastNotExist || !u.fastNode.AliveForTestUrl(u.testUrl) || u.fastNode.LastDelayForTestUrl(u.testUrl) > fast.LastDelayForTestUrl(u.testUrl)+u.tolerance {
|
if u.fastNode == nil || fastNotExist || !u.fastNode.AliveForTestUrl(u.testUrl) || u.fastNode.LastDelayForTestUrl(u.testUrl) > fast.LastDelayForTestUrl(u.testUrl)+u.tolerance {
|
||||||
u.fastNode = fast
|
u.fastNode = fast
|
||||||
}
|
}
|
||||||
@@ -170,45 +169,14 @@ func (u *URLTest) 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": u.Type().String(),
|
"type": u.Type().String(),
|
||||||
"now": u.Now(),
|
"now": u.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": u.testUrl,
|
"testUrl": u.testUrl,
|
||||||
"expectedStatus": u.expectedStatus,
|
"expected": 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 +203,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 {
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ package adapter
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
tlsC "github.com/metacubex/mihomo/component/tls"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
@@ -92,13 +92,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewHysteria(*hyOption)
|
proxy, err = outbound.NewHysteria(*hyOption)
|
||||||
case "hysteria2":
|
|
||||||
hyOption := &outbound.Hysteria2Option{}
|
|
||||||
err = decoder.Decode(mapping, hyOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewHysteria2(*hyOption)
|
|
||||||
case "wireguard":
|
case "wireguard":
|
||||||
wgOption := &outbound.WireGuardOption{}
|
wgOption := &outbound.WireGuardOption{}
|
||||||
err = decoder.Decode(mapping, wgOption)
|
err = decoder.Decode(mapping, wgOption)
|
||||||
@@ -120,27 +113,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":
|
|
||||||
rejectOption := &outbound.RejectOption{}
|
|
||||||
err = decoder.Decode(mapping, rejectOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy = outbound.NewRejectWithOption(*rejectOption)
|
|
||||||
case "ssh":
|
|
||||||
sshOption := &outbound.SshOption{}
|
|
||||||
err = decoder.Decode(mapping, sshOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewSsh(*sshOption)
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,16 +6,20 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
"github.com/metacubex/mihomo/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
"github.com/metacubex/mihomo/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"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
|
||||||
@@ -30,15 +34,14 @@ type HealthCheck struct {
|
|||||||
url string
|
url string
|
||||||
extra map[string]*extraOption
|
extra map[string]*extraOption
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
started atomic.Bool
|
started *atomic.Bool
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
interval time.Duration
|
interval uint
|
||||||
lazy bool
|
lazy bool
|
||||||
expectedStatus utils.IntRanges[uint16]
|
expectedStatus utils.IntRanges[uint16]
|
||||||
lastTouch atomic.TypedValue[time.Time]
|
lastTouch *atomic.Int64
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
singleDo *singledo.Single[struct{}]
|
singleDo *singledo.Single[struct{}]
|
||||||
timeout time.Duration
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
@@ -47,14 +50,13 @@ func (hc *HealthCheck) process() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ticker := time.NewTicker(hc.interval)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
hc.start()
|
hc.start()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
lastTouch := hc.lastTouch.Load()
|
now := time.Now().Unix()
|
||||||
since := time.Since(lastTouch)
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
if !hc.lazy || since < hc.interval {
|
|
||||||
hc.check()
|
hc.check()
|
||||||
} else {
|
} else {
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
log.Debugln("Skip once health check because we are lazy")
|
||||||
@@ -83,7 +85,7 @@ func (hc *HealthCheck) registerHealthCheckTask(url string, expectedStatus utils.
|
|||||||
|
|
||||||
// if the provider has not set up health checks, then modify it to be the same as the group's interval
|
// if the provider has not set up health checks, then modify it to be the same as the group's interval
|
||||||
if hc.interval == 0 {
|
if hc.interval == 0 {
|
||||||
hc.interval = time.Duration(interval) * time.Second
|
hc.interval = interval
|
||||||
}
|
}
|
||||||
|
|
||||||
if hc.extra == nil {
|
if hc.extra == nil {
|
||||||
@@ -101,6 +103,12 @@ func (hc *HealthCheck) registerHealthCheckTask(url string, expectedStatus utils.
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// due to the time-consuming nature of health checks, a maximum of defaultMaxTestURLNum URLs can be set for testing
|
||||||
|
if len(hc.extra) > C.DefaultMaxHealthCheckUrlNum {
|
||||||
|
log.Debugln("skip add url: %s to health check because it has reached the maximum limit: %d", url, C.DefaultMaxHealthCheckUrlNum)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
option := &extraOption{filters: map[string]struct{}{}, expectedStatus: expectedStatus}
|
option := &extraOption{filters: map[string]struct{}{}, expectedStatus: expectedStatus}
|
||||||
splitAndAddFiltersToExtra(filter, option)
|
splitAndAddFiltersToExtra(filter, option)
|
||||||
hc.extra[url] = option
|
hc.extra[url] = option
|
||||||
@@ -127,7 +135,7 @@ func (hc *HealthCheck) auto() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) touch() {
|
func (hc *HealthCheck) touch() {
|
||||||
hc.lastTouch.Store(time.Now())
|
hc.lastTouch.Store(time.Now().Unix())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) start() {
|
func (hc *HealthCheck) start() {
|
||||||
@@ -139,10 +147,6 @@ func (hc *HealthCheck) stop() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
if len(hc.proxies) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
_, _, _ = 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)
|
||||||
@@ -172,8 +176,13 @@ func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *ex
|
|||||||
}
|
}
|
||||||
|
|
||||||
var filterReg *regexp2.Regexp
|
var filterReg *regexp2.Regexp
|
||||||
|
var store = C.OriginalHistory
|
||||||
var expectedStatus utils.IntRanges[uint16]
|
var expectedStatus utils.IntRanges[uint16]
|
||||||
if option != nil {
|
if option != nil {
|
||||||
|
if url != hc.url {
|
||||||
|
store = C.ExtraHistory
|
||||||
|
}
|
||||||
|
|
||||||
expectedStatus = option.expectedStatus
|
expectedStatus = option.expectedStatus
|
||||||
if len(option.filters) != 0 {
|
if len(option.filters) != 0 {
|
||||||
filters := make([]string, 0, len(option.filters))
|
filters := make([]string, 0, len(option.filters))
|
||||||
@@ -195,10 +204,10 @@ func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *ex
|
|||||||
|
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 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, store)
|
||||||
log.Debugln("Health Checked, proxy: %s, url: %s, alive: %t, delay: %d ms uid: {%s}", p.Name(), url, p.AliveForTestUrl(url), p.LastDelayForTestUrl(url), uid)
|
log.Debugln("Health Checked, proxy: %s, url: %s, alive: %t, delay: %d ms uid: {%s}", p.Name(), url, p.AliveForTestUrl(url), p.LastDelayForTestUrl(url), uid)
|
||||||
return false, nil
|
return false, nil
|
||||||
})
|
})
|
||||||
@@ -209,23 +218,21 @@ func (hc *HealthCheck) close() {
|
|||||||
hc.done <- struct{}{}
|
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
|
||||||
if timeout == 0 {
|
|
||||||
timeout = 5000
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &HealthCheck{
|
return &HealthCheck{
|
||||||
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,
|
started: atomic.NewBool(false),
|
||||||
|
interval: interval,
|
||||||
lazy: lazy,
|
lazy: lazy,
|
||||||
expectedStatus: expectedStatus,
|
expectedStatus: expectedStatus,
|
||||||
|
lastTouch: atomic.NewInt64(0),
|
||||||
done: make(chan struct{}, 1),
|
done: make(chan struct{}, 1),
|
||||||
singleDo: singledo.NewSingle[struct{}](time.Second),
|
singleDo: singledo.NewSingle[struct{}](time.Second),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,12 +5,11 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/metacubex/mihomo/component/resource"
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/metacubex/mihomo/constant/features"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -22,36 +21,20 @@ 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 OverrideSchema struct {
|
|
||||||
UDP *bool `provider:"udp,omitempty"`
|
|
||||||
Up *string `provider:"up,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"`
|
|
||||||
}
|
|
||||||
|
|
||||||
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"`
|
||||||
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"`
|
||||||
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
|
||||||
Override OverrideSchema `provider:"override,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
@@ -66,19 +49,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 {
|
||||||
@@ -88,7 +68,7 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
case "http":
|
case "http":
|
||||||
if schema.Path != "" {
|
if schema.Path != "" {
|
||||||
path := C.Path.Resolve(schema.Path)
|
path := C.Path.Resolve(schema.Path)
|
||||||
if !features.CMFA && !C.Path.IsSafePath(path) {
|
if !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)
|
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
||||||
@@ -105,7 +85,6 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
excludeFilter := schema.ExcludeFilter
|
excludeFilter := schema.ExcludeFilter
|
||||||
excludeType := schema.ExcludeType
|
excludeType := schema.ExcludeType
|
||||||
dialerProxy := schema.DialerProxy
|
dialerProxy := schema.DialerProxy
|
||||||
override := schema.Override
|
|
||||||
|
|
||||||
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, dialerProxy, override, vehicle, hc)
|
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, dialerProxy, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
//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
|
|
||||||
}
|
|
||||||
@@ -10,15 +10,15 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/metacubex/mihomo/common/convert"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||||
"github.com/metacubex/mihomo/component/resource"
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/metacubex/mihomo/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/metacubex/mihomo/tunnel/statistic"
|
"github.com/Dreamacro/clash/tunnel/statistic"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
@@ -52,7 +52,6 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"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(),
|
|
||||||
"updatedAt": pp.UpdatedAt,
|
"updatedAt": pp.UpdatedAt,
|
||||||
"subscriptionInfo": pp.subscriptionInfo,
|
"subscriptionInfo": pp.subscriptionInfo,
|
||||||
})
|
})
|
||||||
@@ -101,10 +100,6 @@ 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)
|
||||||
}
|
}
|
||||||
@@ -124,8 +119,8 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
resp, err := mihomoHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
resp, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil)
|
http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -133,7 +128,7 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
|
|
||||||
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
||||||
if userInfoStr == "" {
|
if userInfoStr == "" {
|
||||||
resp2, err := mihomoHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
resp2, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -168,7 +163,7 @@ func stopProxyProvider(pd *ProxySetProvider) {
|
|||||||
_ = pd.Fetcher.Destroy()
|
_ = 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, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
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)
|
||||||
@@ -196,7 +191,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
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), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
@@ -217,12 +212,11 @@ type compatibleProvider struct {
|
|||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
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(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,9 +237,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,10 +256,6 @@ 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)
|
||||||
}
|
}
|
||||||
@@ -305,7 +292,7 @@ func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp, dialerProxy string, override OverrideSchema) resource.Parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp, dialerProxy string) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
@@ -368,49 +355,13 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
if _, ok := proxiesSet[name]; ok {
|
if _, ok := proxiesSet[name]; ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(dialerProxy) > 0 {
|
if len(dialerProxy) > 0 {
|
||||||
mapping["dialer-proxy"] = dialerProxy
|
mapping["dialer-proxy"] = dialerProxy
|
||||||
}
|
}
|
||||||
|
|
||||||
if override.UDP != nil {
|
|
||||||
mapping["udp"] = *override.UDP
|
|
||||||
}
|
|
||||||
if override.Up != nil {
|
|
||||||
mapping["up"] = *override.Up
|
|
||||||
}
|
|
||||||
if override.Down != nil {
|
|
||||||
mapping["down"] = *override.Down
|
|
||||||
}
|
|
||||||
if override.DialerProxy != nil {
|
|
||||||
mapping["dialer-proxy"] = *override.DialerProxy
|
|
||||||
}
|
|
||||||
if override.SkipCertVerify != nil {
|
|
||||||
mapping["skip-cert-verify"] = *override.SkipCertVerify
|
|
||||||
}
|
|
||||||
if override.Interface != nil {
|
|
||||||
mapping["interface-name"] = *override.Interface
|
|
||||||
}
|
|
||||||
if override.RoutingMark != nil {
|
|
||||||
mapping["routing-mark"] = *override.RoutingMark
|
|
||||||
}
|
|
||||||
if override.IPVersion != nil {
|
|
||||||
mapping["ip-version"] = *override.IPVersion
|
|
||||||
}
|
|
||||||
if override.AdditionalPrefix != nil {
|
|
||||||
name := mapping["name"].(string)
|
|
||||||
mapping["name"] = *override.AdditionalPrefix + name
|
|
||||||
}
|
|
||||||
if override.AdditionalSuffix != nil {
|
|
||||||
name := mapping["name"].(string)
|
|
||||||
mapping["name"] = name + *override.AdditionalSuffix
|
|
||||||
}
|
|
||||||
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
proxiesSet[name] = struct{}{}
|
proxiesSet[name] = struct{}{}
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@@ -12,28 +13,45 @@ type SubscriptionInfo struct {
|
|||||||
Expire int64
|
Expire int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo, err error) {
|
func NewSubscriptionInfo(str string) (si *SubscriptionInfo, err error) {
|
||||||
userinfo = strings.ToLower(userinfo)
|
si = &SubscriptionInfo{}
|
||||||
userinfo = strings.ReplaceAll(userinfo, " ", "")
|
str = strings.ToLower(str)
|
||||||
si = new(SubscriptionInfo)
|
reTraffic := regexp2.MustCompile("upload=(\\d+); download=(\\d+); total=(\\d+)", 0)
|
||||||
for _, field := range strings.Split(userinfo, ";") {
|
reExpire := regexp2.MustCompile("expire=(\\d+)", 0)
|
||||||
switch name, value, _ := strings.Cut(field, "="); name {
|
|
||||||
case "upload":
|
match, err := reTraffic.FindStringMatch(str)
|
||||||
si.Upload, err = strconv.ParseInt(value, 10, 64)
|
if err != nil || match == nil {
|
||||||
case "download":
|
return nil, err
|
||||||
si.Download, err = strconv.ParseInt(value, 10, 64)
|
}
|
||||||
case "total":
|
group := match.Groups()
|
||||||
si.Total, err = strconv.ParseInt(value, 10, 64)
|
si.Upload, err = str2uint64(group[1].String())
|
||||||
case "expire":
|
if err != nil {
|
||||||
if value == "" {
|
return nil, err
|
||||||
si.Expire = 0
|
}
|
||||||
} else {
|
|
||||||
si.Expire, err = strconv.ParseInt(value, 10, 64)
|
si.Download, err = str2uint64(group[2].String())
|
||||||
}
|
if err != nil {
|
||||||
}
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
si.Total, err = str2uint64(group[3].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
match, _ = reExpire.FindStringMatch(str)
|
||||||
|
if match != nil {
|
||||||
|
group = match.Groups()
|
||||||
|
si.Expire, err = str2uint64(group[1].String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func str2uint64(str string) (int64, error) {
|
||||||
|
i, err := strconv.ParseInt(str, 10, 64)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -1,235 +0,0 @@
|
|||||||
package arc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
list "github.com/bahlo/generic-list-go"
|
|
||||||
"github.com/samber/lo"
|
|
||||||
)
|
|
||||||
|
|
||||||
//modify from https://github.com/alexanderGugel/arc
|
|
||||||
|
|
||||||
// Option is part of Functional Options Pattern
|
|
||||||
type Option[K comparable, V any] func(*ARC[K, V])
|
|
||||||
|
|
||||||
func WithSize[K comparable, V any](maxSize int) Option[K, V] {
|
|
||||||
return func(a *ARC[K, V]) {
|
|
||||||
a.c = maxSize
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type ARC[K comparable, V any] struct {
|
|
||||||
p int
|
|
||||||
c int
|
|
||||||
t1 *list.List[*entry[K, V]]
|
|
||||||
b1 *list.List[*entry[K, V]]
|
|
||||||
t2 *list.List[*entry[K, V]]
|
|
||||||
b2 *list.List[*entry[K, V]]
|
|
||||||
mutex sync.Mutex
|
|
||||||
len int
|
|
||||||
cache map[K]*entry[K, V]
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns a new Adaptive Replacement Cache (ARC).
|
|
||||||
func New[K comparable, V any](options ...Option[K, V]) *ARC[K, V] {
|
|
||||||
arc := &ARC[K, V]{
|
|
||||||
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 {
|
|
||||||
option(arc)
|
|
||||||
}
|
|
||||||
return arc
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set inserts a new key-value pair into the cache.
|
|
||||||
// This optimizes future access to this entry (side effect).
|
|
||||||
func (a *ARC[K, V]) Set(key K, value V) {
|
|
||||||
a.mutex.Lock()
|
|
||||||
defer a.mutex.Unlock()
|
|
||||||
|
|
||||||
a.set(key, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *ARC[K, V]) set(key K, value V) {
|
|
||||||
a.setWithExpire(key, value, time.Unix(0, 0))
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetWithExpire stores any representation of a response for a given key and given expires.
|
|
||||||
// The expires time will round to second.
|
|
||||||
func (a *ARC[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
|
||||||
a.mutex.Lock()
|
|
||||||
defer a.mutex.Unlock()
|
|
||||||
|
|
||||||
a.setWithExpire(key, value, expires)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *ARC[K, V]) setWithExpire(key K, value V, expires time.Time) {
|
|
||||||
ent, ok := a.cache[key]
|
|
||||||
if !ok {
|
|
||||||
a.len++
|
|
||||||
ent := &entry[K, V]{key: key, value: value, ghost: false, expires: expires.Unix()}
|
|
||||||
a.req(ent)
|
|
||||||
a.cache[key] = ent
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
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.
|
|
||||||
// This optimizes future access to this entry (side effect).
|
|
||||||
func (a *ARC[K, V]) Get(key K) (value V, ok bool) {
|
|
||||||
a.mutex.Lock()
|
|
||||||
defer a.mutex.Unlock()
|
|
||||||
|
|
||||||
ent, ok := a.get(key)
|
|
||||||
if !ok {
|
|
||||||
return lo.Empty[V](), false
|
|
||||||
}
|
|
||||||
return ent.value, true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *ARC[K, V]) get(key K) (e *entry[K, V], ok bool) {
|
|
||||||
ent, ok := a.cache[key]
|
|
||||||
if !ok {
|
|
||||||
return ent, false
|
|
||||||
}
|
|
||||||
a.req(ent)
|
|
||||||
return ent, !ent.ghost
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetWithExpire returns any representation of a cached response,
|
|
||||||
// a time.Time Give expected expires,
|
|
||||||
// and a bool set to true if the key was found.
|
|
||||||
// This method will NOT update the expires.
|
|
||||||
func (a *ARC[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
|
||||||
a.mutex.Lock()
|
|
||||||
defer a.mutex.Unlock()
|
|
||||||
|
|
||||||
ent, ok := a.get(key)
|
|
||||||
if !ok {
|
|
||||||
return lo.Empty[V](), time.Time{}, false
|
|
||||||
}
|
|
||||||
|
|
||||||
return ent.value, time.Unix(ent.expires, 0), true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Len determines the number of currently cached entries.
|
|
||||||
// This method is side-effect free in the sense that it does not attempt to optimize random cache access.
|
|
||||||
func (a *ARC[K, V]) Len() int {
|
|
||||||
a.mutex.Lock()
|
|
||||||
defer a.mutex.Unlock()
|
|
||||||
|
|
||||||
return a.len
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *ARC[K, V]) req(ent *entry[K, V]) {
|
|
||||||
switch {
|
|
||||||
case ent.ll == a.t1 || ent.ll == a.t2:
|
|
||||||
// Case I
|
|
||||||
ent.setMRU(a.t2)
|
|
||||||
case ent.ll == a.b1:
|
|
||||||
// Case II
|
|
||||||
// Cache Miss in t1 and t2
|
|
||||||
|
|
||||||
// Adaptation
|
|
||||||
var d int
|
|
||||||
if a.b1.Len() >= a.b2.Len() {
|
|
||||||
d = 1
|
|
||||||
} else {
|
|
||||||
d = a.b2.Len() / a.b1.Len()
|
|
||||||
}
|
|
||||||
a.p = min(a.p+d, a.c)
|
|
||||||
|
|
||||||
a.replace(ent)
|
|
||||||
ent.setMRU(a.t2)
|
|
||||||
case ent.ll == a.b2:
|
|
||||||
// Case III
|
|
||||||
// Cache Miss in t1 and t2
|
|
||||||
|
|
||||||
// Adaptation
|
|
||||||
var d int
|
|
||||||
if a.b2.Len() >= a.b1.Len() {
|
|
||||||
d = 1
|
|
||||||
} else {
|
|
||||||
d = a.b1.Len() / a.b2.Len()
|
|
||||||
}
|
|
||||||
a.p = max(a.p-d, 0)
|
|
||||||
|
|
||||||
a.replace(ent)
|
|
||||||
ent.setMRU(a.t2)
|
|
||||||
case ent.ll == nil && a.t1.Len()+a.b1.Len() == a.c:
|
|
||||||
// Case IV A
|
|
||||||
if a.t1.Len() < a.c {
|
|
||||||
a.delLRU(a.b1)
|
|
||||||
a.replace(ent)
|
|
||||||
} else {
|
|
||||||
a.delLRU(a.t1)
|
|
||||||
}
|
|
||||||
ent.setMRU(a.t1)
|
|
||||||
case ent.ll == nil && a.t1.Len()+a.b1.Len() < a.c:
|
|
||||||
// Case IV B
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
ent.setMRU(a.t1)
|
|
||||||
case ent.ll == nil:
|
|
||||||
// Case IV, not A nor B
|
|
||||||
ent.setMRU(a.t1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *ARC[K, V]) delLRU(list *list.List[*entry[K, V]]) {
|
|
||||||
lru := list.Back()
|
|
||||||
list.Remove(lru)
|
|
||||||
a.len--
|
|
||||||
delete(a.cache, lru.Value.key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *ARC[K, V]) replace(ent *entry[K, V]) {
|
|
||||||
if a.t1.Len() > 0 && ((a.t1.Len() > a.p) || (ent.ll == a.b2 && a.t1.Len() == a.p)) {
|
|
||||||
lru := a.t1.Back().Value
|
|
||||||
lru.value = lo.Empty[V]()
|
|
||||||
lru.ghost = true
|
|
||||||
a.len--
|
|
||||||
lru.setMRU(a.b1)
|
|
||||||
} else {
|
|
||||||
lru := a.t2.Back().Value
|
|
||||||
lru.value = lo.Empty[V]()
|
|
||||||
lru.ghost = true
|
|
||||||
a.len--
|
|
||||||
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 +0,0 @@
|
|||||||
package arc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestInsertion(t *testing.T) {
|
|
||||||
cache := New[string, string](WithSize[string, string](3))
|
|
||||||
if got, want := cache.Len(), 0; got != want {
|
|
||||||
t.Errorf("empty cache.Len(): got %d want %d", cache.Len(), want)
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
k1 = "Hello"
|
|
||||||
k2 = "Hallo"
|
|
||||||
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
|
|
||||||
cache.Set(k1, v2)
|
|
||||||
if got, want := cache.Len(), 1; got != want {
|
|
||||||
t.Errorf("re-insertion: cache.Len(): got %d want %d", cache.Len(), want)
|
|
||||||
}
|
|
||||||
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(k2, v3)
|
|
||||||
if got, want := cache.Len(), 2; 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 != 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
|
|
||||||
cache.Set(k3, v1)
|
|
||||||
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(k4, v1)
|
|
||||||
if got, want := cache.Len(), 3; got != want {
|
|
||||||
t.Errorf("insertion of key out of size: cache.Len(): got %d want %d", cache.Len(), want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEviction(t *testing.T) {
|
|
||||||
size := 3
|
|
||||||
cache := New[string, string](WithSize[string, string](size))
|
|
||||||
if got, want := cache.Len(), 0; got != want {
|
|
||||||
t.Errorf("empty cache.Len(): got %d want %d", cache.Len(), want)
|
|
||||||
}
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
k, v string
|
|
||||||
}{
|
|
||||||
{"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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
package arc
|
|
||||||
|
|
||||||
import (
|
|
||||||
list "github.com/bahlo/generic-list-go"
|
|
||||||
)
|
|
||||||
|
|
||||||
type entry[K comparable, V any] struct {
|
|
||||||
key K
|
|
||||||
value V
|
|
||||||
ll *list.List[*entry[K, V]]
|
|
||||||
el *list.Element[*entry[K, V]]
|
|
||||||
ghost bool
|
|
||||||
expires int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *entry[K, V]) setLRU(list *list.List[*entry[K, V]]) {
|
|
||||||
e.detach()
|
|
||||||
e.ll = list
|
|
||||||
e.el = e.ll.PushBack(e)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *entry[K, V]) setMRU(list *list.List[*entry[K, V]]) {
|
|
||||||
e.detach()
|
|
||||||
e.ll = list
|
|
||||||
e.el = e.ll.PushFront(e)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *entry[K, V]) detach() {
|
|
||||||
if e.ll != nil {
|
|
||||||
e.ll.Remove(e.el)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,9 +11,10 @@ type Bool struct {
|
|||||||
atomic.Bool
|
atomic.Bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBool(val bool) (i Bool) {
|
func NewBool(val bool) *Bool {
|
||||||
|
i := &Bool{}
|
||||||
i.Store(val)
|
i.Store(val)
|
||||||
return
|
return i
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Bool) MarshalJSON() ([]byte, error) {
|
func (i *Bool) MarshalJSON() ([]byte, error) {
|
||||||
@@ -38,11 +39,12 @@ type Pointer[T any] struct {
|
|||||||
atomic.Pointer[T]
|
atomic.Pointer[T]
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPointer[T any](v *T) (p Pointer[T]) {
|
func NewPointer[T any](v *T) *Pointer[T] {
|
||||||
|
var p Pointer[T]
|
||||||
if v != nil {
|
if v != nil {
|
||||||
p.Store(v)
|
p.Store(v)
|
||||||
}
|
}
|
||||||
return
|
return &p
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pointer[T]) MarshalJSON() ([]byte, error) {
|
func (p *Pointer[T]) MarshalJSON() ([]byte, error) {
|
||||||
@@ -66,9 +68,10 @@ type Int32 struct {
|
|||||||
atomic.Int32
|
atomic.Int32
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInt32(val int32) (i Int32) {
|
func NewInt32(val int32) *Int32 {
|
||||||
|
i := &Int32{}
|
||||||
i.Store(val)
|
i.Store(val)
|
||||||
return
|
return i
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Int32) MarshalJSON() ([]byte, error) {
|
func (i *Int32) MarshalJSON() ([]byte, error) {
|
||||||
@@ -93,9 +96,10 @@ type Int64 struct {
|
|||||||
atomic.Int64
|
atomic.Int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInt64(val int64) (i Int64) {
|
func NewInt64(val int64) *Int64 {
|
||||||
|
i := &Int64{}
|
||||||
i.Store(val)
|
i.Store(val)
|
||||||
return
|
return i
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Int64) MarshalJSON() ([]byte, error) {
|
func (i *Int64) MarshalJSON() ([]byte, error) {
|
||||||
@@ -120,9 +124,10 @@ type Uint32 struct {
|
|||||||
atomic.Uint32
|
atomic.Uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUint32(val uint32) (i Uint32) {
|
func NewUint32(val uint32) *Uint32 {
|
||||||
|
i := &Uint32{}
|
||||||
i.Store(val)
|
i.Store(val)
|
||||||
return
|
return i
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Uint32) MarshalJSON() ([]byte, error) {
|
func (i *Uint32) MarshalJSON() ([]byte, error) {
|
||||||
@@ -147,9 +152,10 @@ type Uint64 struct {
|
|||||||
atomic.Uint64
|
atomic.Uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUint64(val uint64) (i Uint64) {
|
func NewUint64(val uint64) *Uint64 {
|
||||||
|
i := &Uint64{}
|
||||||
i.Store(val)
|
i.Store(val)
|
||||||
return
|
return i
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Uint64) MarshalJSON() ([]byte, error) {
|
func (i *Uint64) MarshalJSON() ([]byte, error) {
|
||||||
@@ -174,9 +180,10 @@ type Uintptr struct {
|
|||||||
atomic.Uintptr
|
atomic.Uintptr
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUintptr(val uintptr) (i Uintptr) {
|
func NewUintptr(val uintptr) *Uintptr {
|
||||||
|
i := &Uintptr{}
|
||||||
i.Store(val)
|
i.Store(val)
|
||||||
return
|
return i
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Uintptr) MarshalJSON() ([]byte, error) {
|
func (i *Uintptr) MarshalJSON() ([]byte, error) {
|
||||||
|
|||||||
@@ -11,43 +11,31 @@ func DefaultValue[T any]() T {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type TypedValue[T any] struct {
|
type TypedValue[T any] struct {
|
||||||
_ noCopy
|
|
||||||
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) {
|
||||||
@@ -63,13 +51,8 @@ func (t *TypedValue[T]) UnmarshalJSON(b []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTypedValue[T any](t T) (v TypedValue[T]) {
|
func NewTypedValue[T any](t T) *TypedValue[T] {
|
||||||
|
v := &TypedValue[T]{}
|
||||||
v.Store(t)
|
v.Store(t)
|
||||||
return
|
return v
|
||||||
}
|
}
|
||||||
|
|
||||||
type noCopy struct{}
|
|
||||||
|
|
||||||
// Lock is a no-op used by -copylocks checker from `go vet`.
|
|
||||||
func (*noCopy) Lock() {}
|
|
||||||
func (*noCopy) Unlock() {}
|
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ const BufferSize = buf.BufferSize
|
|||||||
type Buffer = buf.Buffer
|
type Buffer = buf.Buffer
|
||||||
|
|
||||||
var New = buf.New
|
var New = buf.New
|
||||||
var NewPacket = buf.NewPacket
|
|
||||||
var NewSize = buf.NewSize
|
var NewSize = buf.NewSize
|
||||||
var With = buf.With
|
var With = buf.With
|
||||||
var As = buf.As
|
var As = buf.As
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package lru
|
package cache
|
||||||
|
|
||||||
// Modified by https://github.com/die-net/lrucache
|
// Modified by https://github.com/die-net/lrucache
|
||||||
|
|
||||||
@@ -6,7 +6,8 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
list "github.com/bahlo/generic-list-go"
|
"github.com/Dreamacro/clash/common/generics/list"
|
||||||
|
|
||||||
"github.com/samber/lo"
|
"github.com/samber/lo"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -80,7 +81,7 @@ func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
|||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns any representation of a cached response and a bool
|
// Get returns the any representation of a cached response and a bool
|
||||||
// set to true if the key was found.
|
// set to true if the key was found.
|
||||||
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@@ -110,7 +111,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.
|
||||||
@@ -135,7 +136,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()
|
||||||
@@ -151,7 +152,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()
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package lru
|
package cache
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
package callback
|
package callback
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/metacubex/mihomo/common/buf"
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
N "github.com/metacubex/mihomo/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
C "github.com/metacubex/mihomo/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type firstWriteCallBackConn struct {
|
type firstWriteCallBackConn struct {
|
||||||
|
|||||||
@@ -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}
|
|
||||||
}
|
|
||||||
303
common/cert/cert.go
Normal file
303
common/cert/cert.go
Normal file
@@ -0,0 +1,303 @@
|
|||||||
|
package cert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/sha1"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"math/big"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var currentSerialNumber = time.Now().Unix()
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
ca *x509.Certificate
|
||||||
|
caPrivateKey *rsa.PrivateKey
|
||||||
|
|
||||||
|
roots *x509.CertPool
|
||||||
|
|
||||||
|
privateKey *rsa.PrivateKey
|
||||||
|
|
||||||
|
validity time.Duration
|
||||||
|
keyID []byte
|
||||||
|
organization string
|
||||||
|
|
||||||
|
certsStorage CertsStorage
|
||||||
|
}
|
||||||
|
|
||||||
|
type CertsStorage interface {
|
||||||
|
Get(key string) (*tls.Certificate, bool)
|
||||||
|
|
||||||
|
Set(key string, cert *tls.Certificate)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAuthority(name, organization string, validity time.Duration) (*x509.Certificate, *rsa.PrivateKey, error) {
|
||||||
|
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
pub := privateKey.Public()
|
||||||
|
|
||||||
|
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
h := sha1.New()
|
||||||
|
_, err = h.Write(pkixPub)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
keyID := h.Sum(nil)
|
||||||
|
|
||||||
|
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
||||||
|
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(serial),
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: name,
|
||||||
|
Organization: []string{organization},
|
||||||
|
},
|
||||||
|
SubjectKeyId: keyID,
|
||||||
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
NotBefore: time.Now().Add(-validity),
|
||||||
|
NotAfter: time.Now().Add(validity),
|
||||||
|
DNSNames: []string{name},
|
||||||
|
IsCA: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, privateKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
x509c, err := x509.ParseCertificate(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return x509c, privateKey, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConfig(ca *x509.Certificate, caPrivateKey *rsa.PrivateKey) (*Config, error) {
|
||||||
|
roots := x509.NewCertPool()
|
||||||
|
roots.AddCert(ca)
|
||||||
|
|
||||||
|
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pub := privateKey.Public()
|
||||||
|
|
||||||
|
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
h := sha1.New()
|
||||||
|
_, err = h.Write(pkixPub)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
keyID := h.Sum(nil)
|
||||||
|
|
||||||
|
return &Config{
|
||||||
|
ca: ca,
|
||||||
|
caPrivateKey: caPrivateKey,
|
||||||
|
privateKey: privateKey,
|
||||||
|
keyID: keyID,
|
||||||
|
validity: time.Hour,
|
||||||
|
organization: "Clash",
|
||||||
|
certsStorage: NewDomainTrieCertsStorage(),
|
||||||
|
roots: roots,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) GetCA() *x509.Certificate {
|
||||||
|
return c.ca
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) SetOrganization(organization string) {
|
||||||
|
c.organization = organization
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) SetValidity(validity time.Duration) {
|
||||||
|
c.validity = validity
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) NewTLSConfigForHost(hostname string) *tls.Config {
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||||
|
host := clientHello.ServerName
|
||||||
|
if host == "" {
|
||||||
|
host = hostname
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.GetOrCreateCert(host)
|
||||||
|
},
|
||||||
|
NextProtos: []string{"http/1.1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig.InsecureSkipVerify = true
|
||||||
|
|
||||||
|
return tlsConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) GetOrCreateCert(hostname string, ips ...net.IP) (*tls.Certificate, error) {
|
||||||
|
var leaf *x509.Certificate
|
||||||
|
tlsCertificate, ok := c.certsStorage.Get(hostname)
|
||||||
|
if ok {
|
||||||
|
leaf = tlsCertificate.Leaf
|
||||||
|
if _, err := leaf.Verify(x509.VerifyOptions{
|
||||||
|
DNSName: hostname,
|
||||||
|
Roots: c.roots,
|
||||||
|
}); err == nil {
|
||||||
|
return tlsCertificate, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
key = hostname
|
||||||
|
topHost = hostname
|
||||||
|
wildcardHost = "*." + hostname
|
||||||
|
dnsNames []string
|
||||||
|
)
|
||||||
|
|
||||||
|
if ip := net.ParseIP(hostname); ip != nil {
|
||||||
|
ips = append(ips, ip)
|
||||||
|
} else {
|
||||||
|
parts := strings.Split(hostname, ".")
|
||||||
|
l := len(parts)
|
||||||
|
|
||||||
|
if leaf != nil {
|
||||||
|
dnsNames = append(dnsNames, leaf.DNSNames...)
|
||||||
|
}
|
||||||
|
|
||||||
|
if l > 2 {
|
||||||
|
topIndex := l - 2
|
||||||
|
topHost = strings.Join(parts[topIndex:], ".")
|
||||||
|
|
||||||
|
for i := topIndex; i > 0; i-- {
|
||||||
|
wildcardHost = "*." + strings.Join(parts[i:], ".")
|
||||||
|
|
||||||
|
if i == topIndex && (len(dnsNames) == 0 || dnsNames[0] != topHost) {
|
||||||
|
dnsNames = append(dnsNames, topHost, wildcardHost)
|
||||||
|
} else if !hasDnsNames(dnsNames, wildcardHost) {
|
||||||
|
dnsNames = append(dnsNames, wildcardHost)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dnsNames = append(dnsNames, topHost, wildcardHost)
|
||||||
|
}
|
||||||
|
|
||||||
|
key = "+." + topHost
|
||||||
|
}
|
||||||
|
|
||||||
|
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
||||||
|
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(serial),
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: topHost,
|
||||||
|
Organization: []string{c.organization},
|
||||||
|
},
|
||||||
|
SubjectKeyId: c.keyID,
|
||||||
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
NotBefore: time.Now().Add(-c.validity),
|
||||||
|
NotAfter: time.Now().Add(c.validity),
|
||||||
|
DNSNames: dnsNames,
|
||||||
|
IPAddresses: ips,
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := x509.CreateCertificate(rand.Reader, tmpl, c.ca, c.privateKey.Public(), c.caPrivateKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
x509c, err := x509.ParseCertificate(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsCertificate = &tls.Certificate{
|
||||||
|
Certificate: [][]byte{raw, c.ca.Raw},
|
||||||
|
PrivateKey: c.privateKey,
|
||||||
|
Leaf: x509c,
|
||||||
|
}
|
||||||
|
|
||||||
|
c.certsStorage.Set(key, tlsCertificate)
|
||||||
|
return tlsCertificate, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateAndSave generate CA private key and CA certificate and dump them to file
|
||||||
|
func GenerateAndSave(caPath string, caKeyPath string) error {
|
||||||
|
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(time.Now().Unix()),
|
||||||
|
Subject: pkix.Name{
|
||||||
|
Country: []string{"US"},
|
||||||
|
CommonName: "Clash Root CA",
|
||||||
|
Organization: []string{"Clash Trust Services"},
|
||||||
|
},
|
||||||
|
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
NotBefore: time.Now().Add(-(time.Hour * 24 * 60)),
|
||||||
|
NotAfter: time.Now().Add(time.Hour * 24 * 365 * 25),
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
IsCA: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
caRaw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, privateKey.Public(), privateKey)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
caOut, err := os.OpenFile(caPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func(caOut *os.File) {
|
||||||
|
_ = caOut.Close()
|
||||||
|
}(caOut)
|
||||||
|
|
||||||
|
if err = pem.Encode(caOut, &pem.Block{Type: "CERTIFICATE", Bytes: caRaw}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
caKeyOut, err := os.OpenFile(caKeyPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func(caKeyOut *os.File) {
|
||||||
|
_ = caKeyOut.Close()
|
||||||
|
}(caKeyOut)
|
||||||
|
|
||||||
|
if err = pem.Encode(caKeyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasDnsNames(dnsNames []string, hostname string) bool {
|
||||||
|
for _, name := range dnsNames {
|
||||||
|
if name == hostname {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
32
common/cert/storage.go
Normal file
32
common/cert/storage.go
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
package cert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DomainTrieCertsStorage cache wildcard certificates
|
||||||
|
type DomainTrieCertsStorage struct {
|
||||||
|
certsCache *trie.DomainTrie[*tls.Certificate]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get gets the certificate from the storage
|
||||||
|
func (c *DomainTrieCertsStorage) Get(key string) (*tls.Certificate, bool) {
|
||||||
|
ca := c.certsCache.Search(key)
|
||||||
|
if ca == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return ca.Data(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set saves the certificate to the storage
|
||||||
|
func (c *DomainTrieCertsStorage) Set(key string, cert *tls.Certificate) {
|
||||||
|
_ = c.certsCache.Insert(key, cert)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDomainTrieCertsStorage() *DomainTrieCertsStorage {
|
||||||
|
return &DomainTrieCertsStorage{
|
||||||
|
certsCache: trie.New[*tls.Certificate](),
|
||||||
|
}
|
||||||
|
}
|
||||||
56
common/collections/stack.go
Normal file
56
common/collections/stack.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package collections
|
||||||
|
|
||||||
|
import "sync"
|
||||||
|
|
||||||
|
type (
|
||||||
|
stack struct {
|
||||||
|
top *node
|
||||||
|
length int
|
||||||
|
lock *sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
node struct {
|
||||||
|
value interface{}
|
||||||
|
prev *node
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewStack Create a new stack
|
||||||
|
func NewStack() *stack {
|
||||||
|
return &stack{nil, 0, &sync.RWMutex{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Len Return the number of items in the stack
|
||||||
|
func (this *stack) Len() int {
|
||||||
|
return this.length
|
||||||
|
}
|
||||||
|
|
||||||
|
// Peek View the top item on the stack
|
||||||
|
func (this *stack) Peek() interface{} {
|
||||||
|
if this.length == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return this.top.value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pop the top item of the stack and return it
|
||||||
|
func (this *stack) Pop() interface{} {
|
||||||
|
this.lock.Lock()
|
||||||
|
defer this.lock.Unlock()
|
||||||
|
if this.length == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
n := this.top
|
||||||
|
this.top = n.prev
|
||||||
|
this.length--
|
||||||
|
return n.value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push a value onto the top of the stack
|
||||||
|
func (this *stack) Push(value interface{}) {
|
||||||
|
this.lock.Lock()
|
||||||
|
defer this.lock.Unlock()
|
||||||
|
n := &node{value, this.top}
|
||||||
|
this.top = n
|
||||||
|
this.length++
|
||||||
|
}
|
||||||
@@ -9,10 +9,10 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to mihomo proxies config
|
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
||||||
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||||
data := DecodeBase64(buf)
|
data := DecodeBase64(buf)
|
||||||
|
|
||||||
@@ -69,40 +69,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
|
|
||||||
proxies = append(proxies, hysteria)
|
proxies = append(proxies, hysteria)
|
||||||
|
|
||||||
case "hysteria2", "hy2":
|
|
||||||
urlHysteria2, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
query := urlHysteria2.Query()
|
|
||||||
name := uniqueName(names, urlHysteria2.Fragment)
|
|
||||||
hysteria2 := make(map[string]any, 20)
|
|
||||||
|
|
||||||
hysteria2["name"] = name
|
|
||||||
hysteria2["type"] = "hysteria2"
|
|
||||||
hysteria2["server"] = urlHysteria2.Hostname()
|
|
||||||
if port := urlHysteria2.Port(); port != "" {
|
|
||||||
hysteria2["port"] = port
|
|
||||||
} else {
|
|
||||||
hysteria2["port"] = "443"
|
|
||||||
}
|
|
||||||
hysteria2["obfs"] = query.Get("obfs")
|
|
||||||
hysteria2["obfs-password"] = query.Get("obfs-password")
|
|
||||||
hysteria2["sni"] = query.Get("sni")
|
|
||||||
hysteria2["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
|
||||||
if alpn := query.Get("alpn"); alpn != "" {
|
|
||||||
hysteria2["alpn"] = strings.Split(alpn, ",")
|
|
||||||
}
|
|
||||||
if auth := urlHysteria2.User.String(); auth != "" {
|
|
||||||
hysteria2["password"] = auth
|
|
||||||
}
|
|
||||||
hysteria2["fingerprint"] = query.Get("pinSHA256")
|
|
||||||
hysteria2["down"] = query.Get("down")
|
|
||||||
hysteria2["up"] = query.Get("up")
|
|
||||||
|
|
||||||
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
|
||||||
@@ -144,8 +110,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
tuic["udp-relay-mode"] = udpRelayMode
|
tuic["udp-relay-mode"] = udpRelayMode
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, tuic)
|
|
||||||
|
|
||||||
case "trojan":
|
case "trojan":
|
||||||
urlTrojan, err := url.Parse(line)
|
urlTrojan, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -407,27 +371,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":
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
// https://v2.hysteria.network/zh/docs/developers/URI-Scheme/
|
|
||||||
func TestConvertsV2Ray_normal(t *testing.T) {
|
|
||||||
hy2test := "hysteria2://letmein@example.com:8443/?insecure=1&obfs=salamander&obfs-password=gawrgura&pinSHA256=deadbeef&sni=real.example.com&up=114&down=514&alpn=h3,h4#hy2test"
|
|
||||||
|
|
||||||
expected := []map[string]interface{}{
|
|
||||||
{
|
|
||||||
"name": "hy2test",
|
|
||||||
"type": "hysteria2",
|
|
||||||
"server": "example.com",
|
|
||||||
"port": "8443",
|
|
||||||
"sni": "real.example.com",
|
|
||||||
"obfs": "salamander",
|
|
||||||
"obfs-password": "gawrgura",
|
|
||||||
"alpn": []string{"h3", "h4"},
|
|
||||||
"password": "letmein",
|
|
||||||
"up": "114",
|
|
||||||
"down": "514",
|
|
||||||
"skip-cert-verify": true,
|
|
||||||
"fingerprint": "deadbeef",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err := ConvertsV2Ray([]byte(hy2test))
|
|
||||||
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, expected, proxies)
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/utils"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
|
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
"github.com/zhangyunhao116/fastrand"
|
||||||
|
|||||||
235
common/generics/list/list.go
Normal file
235
common/generics/list/list.go
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
// Copyright 2009 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 list implements a doubly linked list.
|
||||||
|
//
|
||||||
|
// To iterate over a list (where l is a *List):
|
||||||
|
//
|
||||||
|
// for e := l.Front(); e != nil; e = e.Next() {
|
||||||
|
// // do something with e.Value
|
||||||
|
// }
|
||||||
|
package list
|
||||||
|
|
||||||
|
// Element is an element of a linked list.
|
||||||
|
type Element[T any] struct {
|
||||||
|
// Next and previous pointers in the doubly-linked list of elements.
|
||||||
|
// To simplify the implementation, internally a list l is implemented
|
||||||
|
// as a ring, such that &l.root is both the next element of the last
|
||||||
|
// list element (l.Back()) and the previous element of the first list
|
||||||
|
// element (l.Front()).
|
||||||
|
next, prev *Element[T]
|
||||||
|
|
||||||
|
// The list to which this element belongs.
|
||||||
|
list *List[T]
|
||||||
|
|
||||||
|
// The value stored with this element.
|
||||||
|
Value T
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next returns the next list element or nil.
|
||||||
|
func (e *Element[T]) Next() *Element[T] {
|
||||||
|
if p := e.next; e.list != nil && p != &e.list.root {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prev returns the previous list element or nil.
|
||||||
|
func (e *Element[T]) Prev() *Element[T] {
|
||||||
|
if p := e.prev; e.list != nil && p != &e.list.root {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// List represents a doubly linked list.
|
||||||
|
// The zero value for List is an empty list ready to use.
|
||||||
|
type List[T any] struct {
|
||||||
|
root Element[T] // sentinel list element, only &root, root.prev, and root.next are used
|
||||||
|
len int // current list length excluding (this) sentinel element
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init initializes or clears list l.
|
||||||
|
func (l *List[T]) Init() *List[T] {
|
||||||
|
l.root.next = &l.root
|
||||||
|
l.root.prev = &l.root
|
||||||
|
l.len = 0
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns an initialized list.
|
||||||
|
func New[T any]() *List[T] { return new(List[T]).Init() }
|
||||||
|
|
||||||
|
// Len returns the number of elements of list l.
|
||||||
|
// The complexity is O(1).
|
||||||
|
func (l *List[T]) Len() int { return l.len }
|
||||||
|
|
||||||
|
// Front returns the first element of list l or nil if the list is empty.
|
||||||
|
func (l *List[T]) Front() *Element[T] {
|
||||||
|
if l.len == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return l.root.next
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back returns the last element of list l or nil if the list is empty.
|
||||||
|
func (l *List[T]) Back() *Element[T] {
|
||||||
|
if l.len == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return l.root.prev
|
||||||
|
}
|
||||||
|
|
||||||
|
// lazyInit lazily initializes a zero List value.
|
||||||
|
func (l *List[T]) lazyInit() {
|
||||||
|
if l.root.next == nil {
|
||||||
|
l.Init()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert inserts e after at, increments l.len, and returns e.
|
||||||
|
func (l *List[T]) insert(e, at *Element[T]) *Element[T] {
|
||||||
|
e.prev = at
|
||||||
|
e.next = at.next
|
||||||
|
e.prev.next = e
|
||||||
|
e.next.prev = e
|
||||||
|
e.list = l
|
||||||
|
l.len++
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
// insertValue is a convenience wrapper for insert(&Element{Value: v}, at).
|
||||||
|
func (l *List[T]) insertValue(v T, at *Element[T]) *Element[T] {
|
||||||
|
return l.insert(&Element[T]{Value: v}, at)
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove removes e from its list, decrements l.len
|
||||||
|
func (l *List[T]) remove(e *Element[T]) {
|
||||||
|
e.prev.next = e.next
|
||||||
|
e.next.prev = e.prev
|
||||||
|
e.next = nil // avoid memory leaks
|
||||||
|
e.prev = nil // avoid memory leaks
|
||||||
|
e.list = nil
|
||||||
|
l.len--
|
||||||
|
}
|
||||||
|
|
||||||
|
// move moves e to next to at.
|
||||||
|
func (l *List[T]) move(e, at *Element[T]) {
|
||||||
|
if e == at {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.prev.next = e.next
|
||||||
|
e.next.prev = e.prev
|
||||||
|
|
||||||
|
e.prev = at
|
||||||
|
e.next = at.next
|
||||||
|
e.prev.next = e
|
||||||
|
e.next.prev = e
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove removes e from l if e is an element of list l.
|
||||||
|
// It returns the element value e.Value.
|
||||||
|
// The element must not be nil.
|
||||||
|
func (l *List[T]) Remove(e *Element[T]) T {
|
||||||
|
if e.list == l {
|
||||||
|
// if e.list == l, l must have been initialized when e was inserted
|
||||||
|
// in l or l == nil (e is a zero Element) and l.remove will crash
|
||||||
|
l.remove(e)
|
||||||
|
}
|
||||||
|
return e.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushFront inserts a new element e with value v at the front of list l and returns e.
|
||||||
|
func (l *List[T]) PushFront(v T) *Element[T] {
|
||||||
|
l.lazyInit()
|
||||||
|
return l.insertValue(v, &l.root)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushBack inserts a new element e with value v at the back of list l and returns e.
|
||||||
|
func (l *List[T]) PushBack(v T) *Element[T] {
|
||||||
|
l.lazyInit()
|
||||||
|
return l.insertValue(v, l.root.prev)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InsertBefore inserts a new element e with value v immediately before mark and returns e.
|
||||||
|
// If mark is not an element of l, the list is not modified.
|
||||||
|
// The mark must not be nil.
|
||||||
|
func (l *List[T]) InsertBefore(v T, mark *Element[T]) *Element[T] {
|
||||||
|
if mark.list != l {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// see comment in List.Remove about initialization of l
|
||||||
|
return l.insertValue(v, mark.prev)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InsertAfter inserts a new element e with value v immediately after mark and returns e.
|
||||||
|
// If mark is not an element of l, the list is not modified.
|
||||||
|
// The mark must not be nil.
|
||||||
|
func (l *List[T]) InsertAfter(v T, mark *Element[T]) *Element[T] {
|
||||||
|
if mark.list != l {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// see comment in List.Remove about initialization of l
|
||||||
|
return l.insertValue(v, mark)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveToFront moves element e to the front of list l.
|
||||||
|
// If e is not an element of l, the list is not modified.
|
||||||
|
// The element must not be nil.
|
||||||
|
func (l *List[T]) MoveToFront(e *Element[T]) {
|
||||||
|
if e.list != l || l.root.next == e {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// see comment in List.Remove about initialization of l
|
||||||
|
l.move(e, &l.root)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveToBack moves element e to the back of list l.
|
||||||
|
// If e is not an element of l, the list is not modified.
|
||||||
|
// The element must not be nil.
|
||||||
|
func (l *List[T]) MoveToBack(e *Element[T]) {
|
||||||
|
if e.list != l || l.root.prev == e {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// see comment in List.Remove about initialization of l
|
||||||
|
l.move(e, l.root.prev)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveBefore moves element e to its new position before mark.
|
||||||
|
// If e or mark is not an element of l, or e == mark, the list is not modified.
|
||||||
|
// The element and mark must not be nil.
|
||||||
|
func (l *List[T]) MoveBefore(e, mark *Element[T]) {
|
||||||
|
if e.list != l || e == mark || mark.list != l {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.move(e, mark.prev)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveAfter moves element e to its new position after mark.
|
||||||
|
// If e or mark is not an element of l, or e == mark, the list is not modified.
|
||||||
|
// The element and mark must not be nil.
|
||||||
|
func (l *List[T]) MoveAfter(e, mark *Element[T]) {
|
||||||
|
if e.list != l || e == mark || mark.list != l {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.move(e, mark)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushBackList inserts a copy of another list at the back of list l.
|
||||||
|
// The lists l and other may be the same. They must not be nil.
|
||||||
|
func (l *List[T]) PushBackList(other *List[T]) {
|
||||||
|
l.lazyInit()
|
||||||
|
for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() {
|
||||||
|
l.insertValue(e.Value, l.root.prev)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushFrontList inserts a copy of another list at the front of list l.
|
||||||
|
// The lists l and other may be the same. They must not be nil.
|
||||||
|
func (l *List[T]) PushFrontList(other *List[T]) {
|
||||||
|
l.lazyInit()
|
||||||
|
for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {
|
||||||
|
l.insertValue(e.Value, &l.root)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/buf"
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ ExtendedConn = (*BufferedConn)(nil)
|
var _ ExtendedConn = (*BufferedConn)(nil)
|
||||||
@@ -22,16 +22,6 @@ func NewBufferedConn(c net.Conn) *BufferedConn {
|
|||||||
return &BufferedConn{bufio.NewReader(c), NewExtendedConn(c), false}
|
return &BufferedConn{bufio.NewReader(c), NewExtendedConn(c), false}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WarpConnWithBioReader(c net.Conn, br *bufio.Reader) net.Conn {
|
|
||||||
if br != nil && br.Buffered() > 0 {
|
|
||||||
if bc, ok := c.(*BufferedConn); ok && bc.r == br {
|
|
||||||
return bc
|
|
||||||
}
|
|
||||||
return &BufferedConn{br, NewExtendedConn(c), true}
|
|
||||||
}
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reader returns the internal bufio.Reader.
|
// Reader returns the internal bufio.Reader.
|
||||||
func (c *BufferedConn) Reader() *bufio.Reader {
|
func (c *BufferedConn) Reader() *bufio.Reader {
|
||||||
return c.r
|
return c.r
|
||||||
@@ -84,9 +74,9 @@ func (c *BufferedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.C
|
|||||||
length := c.r.Buffered()
|
length := c.r.Buffered()
|
||||||
b, _ := c.r.Peek(length)
|
b, _ := c.r.Peek(length)
|
||||||
_, _ = c.r.Discard(length)
|
_, _ = c.r.Discard(length)
|
||||||
|
c.r = nil // drop bufio.Reader to let gc can clean up its internal buf
|
||||||
return buf.As(b)
|
return buf.As(b)
|
||||||
}
|
}
|
||||||
c.r = nil // drop bufio.Reader to let gc can clean up its internal buf
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
// bufioReader copy from stdlib bufio/bufio.go
|
|
||||||
// This structure has remained unchanged from go1.5 to go1.21.
|
|
||||||
type bufioReader struct {
|
|
||||||
buf []byte
|
|
||||||
rd io.Reader // reader provided by the client
|
|
||||||
r, w int // buf read and write positions
|
|
||||||
err error
|
|
||||||
lastByte int // last byte read for UnreadByte; -1 means invalid
|
|
||||||
lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) AppendData(buf []byte) (ok bool) {
|
|
||||||
b := (*bufioReader)(unsafe.Pointer(c.r))
|
|
||||||
pos := len(b.buf) - b.w - len(buf)
|
|
||||||
if pos >= -b.r { // len(b.buf)-(b.w - b.r) >= len(buf)
|
|
||||||
if pos < 0 { // len(b.buf)-b.w < len(buf)
|
|
||||||
// Slide existing data to beginning.
|
|
||||||
copy(b.buf, b.buf[b.r:b.w])
|
|
||||||
b.w -= b.r
|
|
||||||
b.r = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
b.w += copy(b.buf[b.w:], buf)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/buf"
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ ExtendedConn = (*CachedConn)(nil)
|
|
||||||
|
|
||||||
type CachedConn struct {
|
|
||||||
ExtendedConn
|
|
||||||
data []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCachedConn(c net.Conn, data []byte) *CachedConn {
|
|
||||||
return &CachedConn{NewExtendedConn(c), data}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *CachedConn) Read(b []byte) (n int, err error) {
|
|
||||||
if len(c.data) > 0 {
|
|
||||||
n = copy(b, c.data)
|
|
||||||
c.data = c.data[n:]
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return c.ExtendedConn.Read(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *CachedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.Copy
|
|
||||||
if len(c.data) > 0 {
|
|
||||||
return buf.As(c.data)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *CachedConn) Upstream() any {
|
|
||||||
return c.ExtendedConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *CachedConn) ReaderReplaceable() bool {
|
|
||||||
if len(c.data) > 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *CachedConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SetupContextForConn is a helper function that starts connection I/O interrupter goroutine.
|
|
||||||
func SetupContextForConn(ctx context.Context, conn net.Conn) (done func(*error)) {
|
|
||||||
var (
|
|
||||||
quit = make(chan struct{})
|
|
||||||
interrupt = make(chan error, 1)
|
|
||||||
)
|
|
||||||
go func() {
|
|
||||||
select {
|
|
||||||
case <-quit:
|
|
||||||
interrupt <- nil
|
|
||||||
case <-ctx.Done():
|
|
||||||
// Close the connection, discarding the error
|
|
||||||
_ = conn.Close()
|
|
||||||
interrupt <- ctx.Err()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return func(inputErr *error) {
|
|
||||||
close(quit)
|
|
||||||
if ctxErr := <-interrupt; ctxErr != nil && inputErr != nil {
|
|
||||||
// Return context error to user.
|
|
||||||
inputErr = &ctxErr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
"github.com/metacubex/mihomo/common/net/packet"
|
"github.com/Dreamacro/clash/common/net/packet"
|
||||||
)
|
)
|
||||||
|
|
||||||
type readResult struct {
|
type readResult struct {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/net/packet"
|
"github.com/Dreamacro/clash/common/net/packet"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EnhancePacketConn struct {
|
type EnhancePacketConn struct {
|
||||||
|
|||||||
@@ -4,8 +4,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/net/packet"
|
"github.com/Dreamacro/clash/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
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/buf"
|
|
||||||
"github.com/metacubex/mihomo/common/once"
|
|
||||||
)
|
|
||||||
|
|
||||||
type earlyConn struct {
|
|
||||||
ExtendedConn // only expose standard N.ExtendedConn function to outside
|
|
||||||
resFunc func() error
|
|
||||||
resOnce sync.Once
|
|
||||||
resErr error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *earlyConn) Response() error {
|
|
||||||
conn.resOnce.Do(func() {
|
|
||||||
conn.resErr = conn.resFunc()
|
|
||||||
})
|
|
||||||
return conn.resErr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *earlyConn) Read(b []byte) (n int, err error) {
|
|
||||||
err = conn.Response()
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return conn.ExtendedConn.Read(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *earlyConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
|
||||||
err = conn.Response()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return conn.ExtendedConn.ReadBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *earlyConn) Upstream() any {
|
|
||||||
return conn.ExtendedConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *earlyConn) Success() bool {
|
|
||||||
return once.Done(&conn.resOnce) && conn.resErr == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *earlyConn) ReaderReplaceable() bool {
|
|
||||||
return conn.Success()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *earlyConn) ReaderPossiblyReplaceable() bool {
|
|
||||||
return !conn.Success()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *earlyConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ ExtendedConn = (*earlyConn)(nil)
|
|
||||||
|
|
||||||
func NewEarlyConn(c net.Conn, f func() error) net.Conn {
|
|
||||||
return &earlyConn{ExtendedConn: NewExtendedConn(c), resFunc: f}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/metacubex/mihomo/common/net/deadline"
|
"github.com/Dreamacro/clash/common/net/deadline"
|
||||||
"github.com/metacubex/mihomo/common/net/packet"
|
"github.com/Dreamacro/clash/common/net/packet"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EnhancePacketConn = packet.EnhancePacketConn
|
type EnhancePacketConn = packet.EnhancePacketConn
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package packet
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/pool"
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
type WaitReadFrom interface {
|
type WaitReadFrom interface {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/pool"
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
type enhanceUDPConn struct {
|
type enhanceUDPConn struct {
|
||||||
|
|||||||
@@ -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,7 +5,7 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/buf"
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
)
|
)
|
||||||
|
|
||||||
type refConn struct {
|
type refConn struct {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ package net
|
|||||||
//
|
//
|
||||||
// go func() {
|
// go func() {
|
||||||
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// // See also https://github.com/metacubex/mihomo/pull/1209
|
// // See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||||
// leftConn.SetReadDeadline(time.Now())
|
// leftConn.SetReadDeadline(time.Now())
|
||||||
// ch <- err
|
// ch <- err
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
var KeepAliveInterval = 15 * time.Second
|
var KeepAliveInterval time.Duration
|
||||||
|
|
||||||
func SplitNetworkType(s string) (string, string, error) {
|
func SplitNetworkType(s string) (string, string, error) {
|
||||||
var (
|
var (
|
||||||
@@ -51,6 +51,6 @@ func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
|
|||||||
func TCPKeepAlive(c net.Conn) {
|
func TCPKeepAlive(c net.Conn) {
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
_ = tcp.SetKeepAlive(true)
|
_ = tcp.SetKeepAlive(true)
|
||||||
_ = tcp.SetKeepAlivePeriod(KeepAliveInterval)
|
_ = tcp.SetKeepAlivePeriod(KeepAliveInterval * time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,11 +10,7 @@ import (
|
|||||||
"math/big"
|
"math/big"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Path interface {
|
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||||
Resolve(path string) string
|
|
||||||
}
|
|
||||||
|
|
||||||
func ParseCert(certificate, privateKey string, path Path) (tls.Certificate, error) {
|
|
||||||
if certificate == "" && privateKey == "" {
|
if certificate == "" && privateKey == "" {
|
||||||
return newRandomTLSKeyPair()
|
return newRandomTLSKeyPair()
|
||||||
}
|
}
|
||||||
@@ -23,8 +19,6 @@ func ParseCert(certificate, privateKey string, path Path) (tls.Certificate, erro
|
|||||||
return cert, nil
|
return cert, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
certificate = path.Resolve(certificate)
|
|
||||||
privateKey = path.Resolve(privateKey)
|
|
||||||
cert, loadErr := tls.LoadX509KeyPair(certificate, privateKey)
|
cert, loadErr := tls.LoadX509KeyPair(certificate, privateKey)
|
||||||
if loadErr != nil {
|
if loadErr != nil {
|
||||||
return tls.Certificate{}, fmt.Errorf("parse certificate failed, maybe format error:%s, or path error: %s", painTextErr.Error(), loadErr.Error())
|
return tls.Certificate{}, fmt.Errorf("parse certificate failed, maybe format error:%s, or path error: %s", painTextErr.Error(), loadErr.Error())
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/mihomo/common/atomic"
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user