mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-25 19:11:45 +00:00
Compare commits
51
Commits
utls
...
findprocess
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73a3beff39 | ||
|
|
e17392a96e | ||
|
|
15b2499d34 | ||
|
|
d9131d381c | ||
|
|
8c7447fd2d | ||
|
|
4dac768567 | ||
|
|
dfad7776ee | ||
|
|
e00dbb963c | ||
|
|
a9c42c1bd7 | ||
|
|
74cbdf46d8 | ||
|
|
3dee8518c1 | ||
|
|
8f0bb9fbfa | ||
|
|
5225121aab | ||
|
|
02cf0f60ea | ||
|
|
f73471e6b4 | ||
|
|
8e07407486 | ||
|
|
febc082f03 | ||
|
|
09b1b0701f | ||
|
|
ce074ce572 | ||
|
|
b1dfdf25e7 | ||
|
|
1c5a1fbf70 | ||
|
|
b983473390 | ||
|
|
5e861653c2 | ||
|
|
36112cd886 | ||
|
|
b1905088c3 | ||
|
|
381e450943 | ||
|
|
7daa8e4b6a | ||
|
|
a32023be5f | ||
|
|
82b5b76bc5 | ||
|
|
f781c68715 | ||
|
|
5d17b872ed | ||
|
|
c456141815 | ||
|
|
f082058590 | ||
|
|
e184d774a2 | ||
|
|
14df0738f3 | ||
|
|
36cc9ff510 | ||
|
|
c43ee98ec7 | ||
|
|
676eaf66f8 | ||
|
|
af8f9673af | ||
|
|
924a5e7814 | ||
|
|
2a773ffb3d | ||
|
|
3a88ccb2d3 | ||
|
|
a5d52d2d95 | ||
|
|
3d3a504159 | ||
|
|
2d287bbdee | ||
|
|
5745dea2b4 | ||
|
|
2e4c13d8c4 | ||
|
|
bb335c6b0c | ||
|
|
043d2e47fc | ||
|
|
36756ad672 | ||
|
|
abecd7d9f1 |
@@ -0,0 +1,5 @@
|
||||
<!--
|
||||
Read CONTRIBUTING.md before opening a pull request.
|
||||
Human-led pull requests can use a normal description.
|
||||
For agent-led pull requests, disclose each AI tool and model, then paste the complete conversation directly in a collapsed <details> block in this PR body. External transcript links are not accepted.
|
||||
-->
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"android-arm64": { "friendlyName": "android-arm64-v8a" },
|
||||
"android-amd64": { "friendlyName": "android-amd64" },
|
||||
"darwin-amd64": { "friendlyName": "macos-64" },
|
||||
"darwin-arm64": { "friendlyName": "macos-arm64-v8a" },
|
||||
"freebsd-386": { "friendlyName": "freebsd-32" },
|
||||
@@ -14,9 +15,7 @@
|
||||
"linux-arm7": { "friendlyName": "linux-arm32-v7a" },
|
||||
"linux-mips64le": { "friendlyName": "linux-mips64le" },
|
||||
"linux-mips64": { "friendlyName": "linux-mips64" },
|
||||
"linux-mipslesoftfloat": { "friendlyName": "linux-mips32le-softfloat" },
|
||||
"linux-mipsle": { "friendlyName": "linux-mips32le" },
|
||||
"linux-mipssoftfloat": { "friendlyName": "linux-mips32-softfloat" },
|
||||
"linux-mips": { "friendlyName": "linux-mips32" },
|
||||
"linux-ppc64le": { "friendlyName": "linux-ppc64le" },
|
||||
"linux-ppc64": { "friendlyName": "linux-ppc64" },
|
||||
|
||||
@@ -9,8 +9,8 @@ ARG TARGETARCH
|
||||
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags "-s -w -buildid=" ./main
|
||||
|
||||
# Download geodat into a staging directory
|
||||
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geoip/geoip-full.dat /tmp/geodat/geoip.dat
|
||||
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geosite/geosite-expand.dat /tmp/geodat/geosite.dat
|
||||
ADD https://github.com/XTLS/Xray-rules-dat/releases/latest/download/geoip-full.dat /tmp/geodat/geoip.dat
|
||||
ADD https://github.com/XTLS/Xray-rules-dat/releases/latest/download/geosite-expand.dat /tmp/geodat/geosite.dat
|
||||
|
||||
RUN mkdir -p /tmp/empty
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ ARG TARGETARCH
|
||||
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags "-s -w -buildid=" ./main
|
||||
|
||||
# Download geodat into a staging directory
|
||||
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geoip/geoip-full.dat /tmp/geodat/geoip.dat
|
||||
ADD https://raw.githubusercontent.com/XTLS/Xray-rules-dat/release/geosite/geosite-expand.dat /tmp/geodat/geosite.dat
|
||||
ADD https://github.com/XTLS/Xray-rules-dat/releases/latest/download/geoip-full.dat /tmp/geodat/geoip.dat
|
||||
ADD https://github.com/XTLS/Xray-rules-dat/releases/latest/download/geosite-expand.dat /tmp/geodat/geosite.dat
|
||||
|
||||
RUN mkdir -p /tmp/empty
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v4.7.0
|
||||
uses: docker/login-action@v4.8.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
name: Build and Release for Windows 7
|
||||
# Pre-compiling support removal since 1.29
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [published]
|
||||
push:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
jobs:
|
||||
check-assets:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||
steps:
|
||||
- name: Restore Geodat Cache
|
||||
uses: actions/cache/restore@v6
|
||||
@@ -115,8 +112,6 @@ jobs:
|
||||
COMMID=$(git describe --always --dirty)
|
||||
echo 'Building Xray for Windows 7...'
|
||||
go build -o build_assets/xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
# The line below is for without running conhost.exe version. Commented for not being used. Provided for reference.
|
||||
# go build -o build_assets/wxray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-H windowsgui -X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
|
||||
- name: Restore Geodat Cache
|
||||
uses: actions/cache/restore@v6
|
||||
@@ -152,6 +147,13 @@ jobs:
|
||||
cp ${GITHUB_WORKSPACE}/README.md ./build_assets/README.md
|
||||
cp ${GITHUB_WORKSPACE}/LICENSE ./build_assets/LICENSE
|
||||
|
||||
- name: Upload files to Artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: Xray-${{ env.ASSET_NAME }}
|
||||
path: |
|
||||
./build_assets/*
|
||||
|
||||
- name: Create ZIP archive
|
||||
if: github.event_name == 'release'
|
||||
shell: bash
|
||||
@@ -175,10 +177,3 @@ jobs:
|
||||
file: ./Xray-${{ env.ASSET_NAME }}.zip*
|
||||
tag: ${{ github.ref }}
|
||||
file_glob: true
|
||||
|
||||
- name: Upload files to Artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: Xray-${{ env.ASSET_NAME }}
|
||||
path: |
|
||||
./build_assets/*
|
||||
|
||||
+179
-86
@@ -79,86 +79,23 @@ jobs:
|
||||
contents: write
|
||||
strategy:
|
||||
matrix:
|
||||
# Include amd64 on all platforms.
|
||||
goos: [windows, freebsd, openbsd, linux, darwin]
|
||||
goarch: [amd64, 386]
|
||||
# Include amd64 and arm64 on all platforms.
|
||||
goos: [windows, freebsd, openbsd, linux, darwin, android]
|
||||
goarch: [amd64, arm64]
|
||||
patch-assetname: [""]
|
||||
exclude:
|
||||
# Exclude i386 on darwin
|
||||
- goarch: 386
|
||||
goos: darwin
|
||||
include:
|
||||
# BEGIN MacOS ARM64
|
||||
- goos: darwin
|
||||
goarch: arm64
|
||||
# END MacOS ARM64
|
||||
# BEGIN Linux ARM 5 6 7
|
||||
- goos: linux
|
||||
goarch: arm
|
||||
goarm: 7
|
||||
- goos: linux
|
||||
goarch: arm
|
||||
goarm: 6
|
||||
- goos: linux
|
||||
goarch: arm
|
||||
goarm: 5
|
||||
# END Linux ARM 5 6 7
|
||||
# BEGIN Android ARM 8
|
||||
- goos: android
|
||||
goarch: arm64
|
||||
# END Android ARM 8
|
||||
# BEGIN Android AMD64
|
||||
- goos: android
|
||||
goarch: amd64
|
||||
patch-assetname: android-amd64
|
||||
# END Android AMD64
|
||||
# Windows ARM
|
||||
- goos: windows
|
||||
goarch: arm64
|
||||
# BEGIN Other architectures
|
||||
# BEGIN riscv64 & ARM64 & LOONG64
|
||||
- goos: linux
|
||||
goarch: arm64
|
||||
- goos: linux
|
||||
goarch: riscv64
|
||||
- goos: linux
|
||||
goarch: loong64
|
||||
# END riscv64 & ARM64 & LOONG64
|
||||
# BEGIN MIPS
|
||||
- goos: linux
|
||||
goarch: mips64
|
||||
- goos: linux
|
||||
goarch: mips64le
|
||||
- goos: linux
|
||||
goarch: mipsle
|
||||
- goos: linux
|
||||
goarch: mips
|
||||
# END MIPS
|
||||
# BEGIN PPC
|
||||
# BEGIN Linux specified
|
||||
- goos: linux
|
||||
goarch: ppc64
|
||||
- goos: linux
|
||||
goarch: ppc64le
|
||||
# END PPC
|
||||
# BEGIN FreeBSD ARM
|
||||
- goos: freebsd
|
||||
goarch: arm64
|
||||
- goos: freebsd
|
||||
goarch: arm
|
||||
goarm: 7
|
||||
# END FreeBSD ARM
|
||||
# BEGIN S390X
|
||||
- goos: linux
|
||||
goarch: s390x
|
||||
# END S390X
|
||||
# END Other architectures
|
||||
# BEGIN OPENBSD ARM
|
||||
- goos: openbsd
|
||||
goarch: arm64
|
||||
- goos: openbsd
|
||||
goarch: arm
|
||||
goarm: 7
|
||||
# END OPENBSD ARM
|
||||
- goos: linux
|
||||
goarch: riscv64
|
||||
- goos: linux
|
||||
goarch: loong64
|
||||
# END Linux specified
|
||||
fail-fast: false
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
@@ -166,7 +103,6 @@ jobs:
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
CGO_ENABLED: 0
|
||||
steps:
|
||||
- name: Checkout codebase
|
||||
@@ -188,8 +124,8 @@ jobs:
|
||||
- name: Show workflow information
|
||||
run: |
|
||||
_NAME=${{ matrix.patch-assetname }}
|
||||
[ -n "$_NAME" ] || _NAME=$(jq ".[\"$GOOS-$GOARCH$GOARM$GOMIPS\"].friendlyName" -r < .github/build/friendly-filenames.json)
|
||||
echo "GOOS: $GOOS, GOARCH: $GOARCH, GOARM: $GOARM, GOMIPS: $GOMIPS, RELEASE_NAME: $_NAME"
|
||||
[ -n "$_NAME" ] || _NAME=$(jq ".[\"$GOOS-$GOARCH\"].friendlyName" -r < .github/build/friendly-filenames.json)
|
||||
echo "GOOS: $GOOS, GOARCH: $GOARCH, RELEASE_NAME: $_NAME"
|
||||
echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
|
||||
|
||||
- name: Set up Go
|
||||
@@ -203,6 +139,18 @@ jobs:
|
||||
|
||||
- name: Build Xray
|
||||
run: |
|
||||
case "${GOARCH}:${GOOS}" in
|
||||
# Special processing for x86-64 and ARM64
|
||||
amd64:windows|amd64:darwin)
|
||||
GOAMD64="v2"
|
||||
;;
|
||||
arm64:windows)
|
||||
GOARM64="v8.2"
|
||||
;;
|
||||
arm64:darwin)
|
||||
GOARM64="v8.4"
|
||||
;;
|
||||
esac
|
||||
mkdir -p build_assets
|
||||
COMMID=$(git describe --always --dirty)
|
||||
if [[ ${GOOS} == 'windows' ]]; then
|
||||
@@ -212,16 +160,10 @@ jobs:
|
||||
# go build -o build_assets/wxray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-H windowsgui -X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
elif [[ ${GOOS} == 'android' ]]; then
|
||||
echo 'Building Xray for Android...'
|
||||
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid= -checklinkname=0" -v ./main
|
||||
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid= -checklinkname=0 -extldflags=-Wl,--pack-dyn-relocs=android" -v ./main
|
||||
else
|
||||
echo 'Building Xray...'
|
||||
if [[ ${GOARCH} == 'mips' || ${GOARCH} == 'mipsle' ]]; then
|
||||
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
echo 'Building soft-float Xray for MIPS/MIPSLE 32-bit...'
|
||||
GOMIPS=softfloat go build -o build_assets/xray_softfloat -trimpath -buildvcs=false -gcflags="-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
else
|
||||
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
fi
|
||||
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
fi
|
||||
|
||||
- name: Restore Geodat Cache
|
||||
@@ -248,9 +190,6 @@ jobs:
|
||||
if [[ ${GOARCH} == 'amd64' ]]; then
|
||||
mv resources/wintun/bin/amd64/wintun.dll build_assets/
|
||||
fi
|
||||
if [[ ${GOARCH} == '386' ]]; then
|
||||
mv resources/wintun/bin/x86/wintun.dll build_assets/
|
||||
fi
|
||||
if [[ ${GOARCH} == 'arm64' ]]; then
|
||||
mv resources/wintun/bin/arm64/wintun.dll build_assets/
|
||||
fi
|
||||
@@ -262,6 +201,13 @@ jobs:
|
||||
cp ${GITHUB_WORKSPACE}/README.md ./build_assets/README.md
|
||||
cp ${GITHUB_WORKSPACE}/LICENSE ./build_assets/LICENSE
|
||||
|
||||
- name: Upload files to Artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: Xray-${{ env.ASSET_NAME }}
|
||||
path: |
|
||||
./build_assets/*
|
||||
|
||||
- name: Create ZIP archive
|
||||
if: github.event_name == 'release'
|
||||
shell: bash
|
||||
@@ -286,9 +232,156 @@ jobs:
|
||||
tag: ${{ github.ref }}
|
||||
file_glob: true
|
||||
|
||||
build-release-only:
|
||||
needs: check-assets
|
||||
permissions:
|
||||
contents: write
|
||||
strategy:
|
||||
matrix:
|
||||
# First batch (since Go 1.29) of removal:
|
||||
# x86: windows, linux, freebsd, openbsd
|
||||
# arm: linux(v5), linux(v6)
|
||||
# other: linux(mips), linux(mips64), linux(mips64le)
|
||||
# Second batch (needs discussion) of removal
|
||||
# arm(v7): freebsd, openbsd, linux
|
||||
# other: linux(mipsle)
|
||||
goos: [windows, freebsd, openbsd, linux]
|
||||
goarch: [arm, 386]
|
||||
goarm: [7]
|
||||
exclude:
|
||||
- goos: windows
|
||||
goarch: arm
|
||||
include:
|
||||
# Second batch of removal [In the future]
|
||||
- goos: linux
|
||||
goarch: mipsle
|
||||
# END of second batch
|
||||
# First batch of removal [Go 1.29]
|
||||
- goos: linux
|
||||
goarch: arm
|
||||
goarm: 5
|
||||
- goos: linux
|
||||
goarch: arm
|
||||
goarm: 6
|
||||
- goos: linux
|
||||
goarch: mips
|
||||
- goos: linux
|
||||
goarch: mips64
|
||||
- goos: linux
|
||||
goarch: mips64le
|
||||
# END of first batch
|
||||
fail-fast: false
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'release' || github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
CGO_ENABLED: 0
|
||||
steps:
|
||||
- name: Checkout codebase
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Show workflow information
|
||||
run: |
|
||||
_NAME=${{ matrix.patch-assetname }}
|
||||
if [[ ${GOARCH} == 'arm' ]]; then
|
||||
[ -n "$_NAME" ] || _NAME=$(jq ".[\"$GOOS-$GOARCH$GOARM\"].friendlyName" -r < .github/build/friendly-filenames.json)
|
||||
echo "GOOS: $GOOS, GOARCH: $GOARCH, GOARM: $GOARM, RELEASE_NAME: $_NAME"
|
||||
else
|
||||
echo "GOARM=''" >> $GITHUB_ENV
|
||||
[ -n "$_NAME" ] || _NAME=$(jq ".[\"$GOOS-$GOARCH\"].friendlyName" -r < .github/build/friendly-filenames.json)
|
||||
echo "GOOS: $GOOS, GOARCH: $GOARCH, RELEASE_NAME: $_NAME"
|
||||
fi
|
||||
echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
check-latest: true
|
||||
|
||||
- name: Get project dependencies
|
||||
run: go mod download
|
||||
|
||||
- name: Build Xray
|
||||
run: |
|
||||
mkdir -p build_assets
|
||||
COMMID=$(git describe --always --dirty)
|
||||
if [[ ${GOOS} == 'windows' ]]; then
|
||||
echo 'Building Xray for Windows...'
|
||||
go build -o build_assets/xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
else
|
||||
echo 'Building Xray...'
|
||||
if [[ ${GOARCH} == 'mips' || ${GOARCH} == 'mipsle' ]]; then
|
||||
go build -o build_assets/xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
echo 'Building soft-float Xray for MIPS/MIPSLE 32-bit...'
|
||||
GOMIPS=softfloat go build -o build_assets/xray_softfloat -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
else
|
||||
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Restore Geodat Cache
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: resources
|
||||
key: xray-geodat-
|
||||
|
||||
- name: Restore Wintun Cache
|
||||
if: matrix.goos == 'windows'
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: resources
|
||||
key: xray-wintun-
|
||||
|
||||
- name: Add additional assets into package
|
||||
run: |
|
||||
mv -f resources/geo* build_assets/
|
||||
if [[ ${GOOS} == 'windows' ]]; then
|
||||
cp .github/build/windows/* build_assets/
|
||||
fi
|
||||
if [[ ${GOOS} == 'windows' ]]; then
|
||||
echo 'Adding Wintun into packages'
|
||||
if [[ ${GOARCH} == '386' ]]; then
|
||||
mv resources/wintun/bin/x86/wintun.dll build_assets/
|
||||
fi
|
||||
mv resources/wintun/LICENSE.txt build_assets/LICENSE-Wintun
|
||||
fi
|
||||
|
||||
- name: Copy README.md & LICENSE
|
||||
run: |
|
||||
cp ${GITHUB_WORKSPACE}/README.md ./build_assets/README.md
|
||||
cp ${GITHUB_WORKSPACE}/LICENSE ./build_assets/LICENSE
|
||||
|
||||
- name: Upload files to Artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: Xray-${{ env.ASSET_NAME }}
|
||||
path: |
|
||||
./build_assets/*
|
||||
|
||||
- name: Create ZIP archive
|
||||
if: github.event_name == 'release'
|
||||
shell: bash
|
||||
run: |
|
||||
pushd build_assets || exit 1
|
||||
touch -mt $(date +%Y01010000) *
|
||||
zip -9vr ../Xray-${{ env.ASSET_NAME }}.zip .
|
||||
popd || exit 1
|
||||
FILE=./Xray-${{ env.ASSET_NAME }}.zip
|
||||
DGST=$FILE.dgst
|
||||
for METHOD in {"md5","sha1","sha256","sha512"}
|
||||
do
|
||||
openssl dgst -$METHOD $FILE | sed 's/([^)]*)//g' >>$DGST
|
||||
done
|
||||
|
||||
- name: Upload binaries to release
|
||||
uses: svenstaro/upload-release-action@v2
|
||||
if: github.event_name == 'release'
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ./Xray-${{ env.ASSET_NAME }}.zip*
|
||||
tag: ${{ github.ref }}
|
||||
file_glob: true
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Contributing to Xray-core
|
||||
|
||||
We review pull requests that address a concrete problem or an agreed proposal. Please keep each change focused and provide evidence that maintainers can check.
|
||||
|
||||
## Bug fixes
|
||||
|
||||
A bug-fix pull request must link an existing issue filed using the issue template. Summarize the code change and verification in the pull request, and add a regression test when practical. A speculative fix without a demonstrated problem is not ready for a pull request.
|
||||
|
||||
## Features
|
||||
|
||||
Propose the use case and intended design in an issue before implementing it. Wait for a maintainer to accept the proposal. Explain how the change fits the existing architecture and any compatibility impact.
|
||||
|
||||
## Refactors
|
||||
|
||||
Propose the scope in an issue and wait for maintainer acceptance before implementing it. Show which complexity the change removes and why the resulting design is easier to understand. Prefer a reduction in code and moving parts, but line count alone is not the review criterion. Preserve observable behavior and test both old-to-new and new-to-old client/server connections when protocol or network behavior is affected.
|
||||
|
||||
## AI involvement and author responsibility
|
||||
|
||||
AI assistance does not require a conversation record when the author selects or verifies the problem, directs the approach, reviews every changed line, verifies the result, and personally responds to review feedback. The author must be able to explain every changed line and maintain the change. A pull request meeting these conditions is considered human-led, regardless of whether AI wrote the code or who pushed the commits. Such pull requests may ignore the agent-led requirements below.
|
||||
|
||||
If an AI agent independently selected the task or made key implementation decisions without ongoing human direction, the pull request is agent-led even if a person submits it manually. Disclose each tool and model and paste the complete prompt-and-response record for every session used for the pull request, including retries and changes after review feedback, inside a collapsed `<details>` block in the pull request description. External links, summaries, and selected excerpts are insufficient. A transcript does not replace the author's review, verification, or responsibility for responding to maintainers.
|
||||
|
||||
In agent-led pull requests, commits containing AI-generated changes must credit the specific LLM as their author or co-author.
|
||||
|
||||
We do not oppose the use of AI, but agent-led pull requests must have a human author who responds to maintainer feedback for several weeks after submission. Dishonest declarations, fabricated verification, intentionally incomplete records, or abandoning an agent-led pull request are prohibited and may result in being blocked from contributing to Xray-core.
|
||||
|
||||
## Review
|
||||
|
||||
Maintainers may ask for missing evidence before reviewing code or close a pull request that is outside the agreed scope. The contributor is responsible for understanding, testing, and explaining the change, regardless of the tools used to produce it.
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
[Project X](https://github.com/XTLS) originates from XTLS protocol, providing a set of network tools such as [Xray-core](https://github.com/XTLS/Xray-core) and [REALITY](https://github.com/XTLS/REALITY).
|
||||
|
||||
[README](https://github.com/XTLS/Xray-core#readme) is open, so feel free to submit your project [here](https://github.com/XTLS/Xray-core/pulls).
|
||||
|
||||
## Sponsors
|
||||
|
||||
[](https://docs.rw)
|
||||
@@ -41,10 +39,10 @@
|
||||
|
||||
## Telegram
|
||||
|
||||
[Project X](https://t.me/projectXray)
|
||||
|
||||
[Project X Channel](https://t.me/projectXtls)
|
||||
|
||||
[Project X](https://t.me/projectXray) (中文 / English)
|
||||
|
||||
[Project VLESS](https://t.me/projectVless) (Русский)
|
||||
|
||||
[Project XHTTP](https://t.me/projectXhttp) (Persian)
|
||||
@@ -53,7 +51,6 @@
|
||||
|
||||
- Linux Script
|
||||
- [XTLS/Xray-install](https://github.com/XTLS/Xray-install) (**Official**)
|
||||
- [tempest](https://github.com/team-cloudchaser/tempest) (supports [`systemd`](https://systemd.io) and [OpenRC](https://github.com/OpenRC/openrc); Linux-only)
|
||||
- Docker
|
||||
- [ghcr.io/xtls/xray-core](https://ghcr.io/xtls/xray-core) (**Official**)
|
||||
- [teddysun/xray](https://hub.docker.com/r/teddysun/xray)
|
||||
@@ -69,12 +66,10 @@
|
||||
- [TX-UI](https://github.com/AghayeCoder/tx-ui)
|
||||
- [CELERITY](https://github.com/ClickDevTech/CELERITY-panel)
|
||||
- One Click
|
||||
- [Xray-REALITY](https://github.com/zxcvos/Xray-script), [xray-reality](https://github.com/sajjaddg/xray-reality), [reality-ezpz](https://github.com/aleskxyz/reality-ezpz)
|
||||
- [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey), [XTool](https://github.com/LordPenguin666/XTool), [VPainLess](https://github.com/vpainless/vpainless)
|
||||
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey), [ProxySU](https://github.com/proxysu/ProxySU)
|
||||
- [xray-reality](https://github.com/sajjaddg/xray-reality), [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey)
|
||||
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey)
|
||||
- Magisk
|
||||
- [Magic_V2Ray](https://github.com/vincentng295/Magic_V2Ray)
|
||||
- [Xray_For_Magisk](https://github.com/E7KMbb/Xray_For_Magisk)
|
||||
- Homebrew
|
||||
- `brew install xray`
|
||||
|
||||
@@ -86,14 +81,7 @@
|
||||
- [All-in-One-fallbacks-Nginx](https://github.com/XTLS/Xray-examples/tree/main/All-in-One-fallbacks-Nginx)
|
||||
- Xray-examples
|
||||
- [XTLS/Xray-examples](https://github.com/XTLS/Xray-examples)
|
||||
- [chika0801/Xray-examples](https://github.com/chika0801/Xray-examples)
|
||||
- [lxhao61/integrated-examples](https://github.com/lxhao61/integrated-examples)
|
||||
- Tutorial
|
||||
- [XTLS Vision](https://github.com/chika0801/Xray-install)
|
||||
- [REALITY (English)](https://cscot.pages.dev/2023/03/02/Xray-REALITY-tutorial/)
|
||||
- [XTLS-Iran-Reality (English)](https://github.com/SasukeFreestyle/XTLS-Iran-Reality)
|
||||
- [Xray REALITY with 'steal oneself' (English)](https://computerscot.github.io/vless-xtls-utls-reality-steal-oneself.html)
|
||||
- [Xray with WireGuard inbound (English)](https://g800.pages.dev/wireguard)
|
||||
|
||||
## GUI Clients
|
||||
|
||||
@@ -106,49 +94,52 @@
|
||||
- [fancyss](https://github.com/hq450/fancyss)
|
||||
- Windows
|
||||
- [v2rayN](https://github.com/2dust/v2rayN)
|
||||
- [Furious](https://github.com/LorenEteval/Furious)
|
||||
- [Invisible Man - Xray](https://github.com/InvisibleManVPN/InvisibleMan-XRayClient)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev)
|
||||
- [keqdroid](https://github.com/Lemonochka/keqdroid)
|
||||
- Android
|
||||
- [v2rayNG](https://github.com/2dust/v2rayNG)
|
||||
- [X-flutter](https://github.com/XTLS/X-flutter)
|
||||
- [SaeedDev94/Xray](https://github.com/SaeedDev94/Xray)
|
||||
- [SimpleXray](https://github.com/lhear/SimpleXray)
|
||||
- [XrayFA](https://github.com/Q7DF1/XrayFA)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG)
|
||||
- [keqdroid](https://github.com/Lemonochka/keqdroid)
|
||||
- iOS & macOS arm64 & tvOS
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
|
||||
- [Streisand](https://apps.apple.com/app/streisand/id6450534064)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [INCY](https://apps.apple.com/en/app/incy/id6756943388)
|
||||
- macOS arm64 & x64
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973)
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215)
|
||||
- [V2rayU](https://github.com/yanue/V2rayU)
|
||||
- [V2RayXS](https://github.com/tzmax/V2RayXS)
|
||||
- [Furious](https://github.com/LorenEteval/Furious)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [GoXRay](https://github.com/goxray/desktop)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [v2rayN](https://github.com/2dust/v2rayN)
|
||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||
- [INCY](https://apps.apple.com/en/app/incy/id6756943388)
|
||||
- Linux
|
||||
- [v2rayA](https://github.com/v2rayA/v2rayA)
|
||||
- [Furious](https://github.com/LorenEteval/Furious)
|
||||
- [GorzRay](https://github.com/ketetefid/GorzRay)
|
||||
- [GoXRay](https://github.com/goxray/desktop)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [v2rayN](https://github.com/2dust/v2rayN)
|
||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [keqdroid](https://github.com/Lemonochka/keqdroid)
|
||||
- HarmonyOS
|
||||
- [Hey](https://github.com/popsiclelmlm/Hey)
|
||||
|
||||
<details>
|
||||
<summary>Project listing criteria</summary>
|
||||
|
||||
To submit a project to the [README](https://github.com/XTLS/Xray-core#readme), open a [pull request](https://github.com/XTLS/Xray-core/pulls). Projects are listed under these rules:
|
||||
|
||||
- Only submit projects that build their core experience on Xray-core and follow Xray's protocol choices and security requirements; merely offering it as an interchangeable core does not qualify.
|
||||
- Projects must have been maintained for at least one month and have at least 30 stars.
|
||||
- Projects with no activity for three months will be removed.
|
||||
- Closed-source iOS clients must be submitted by their developers.
|
||||
|
||||
</details>
|
||||
|
||||
## Others that support VLESS, XTLS, REALITY, XUDP, PLUX...
|
||||
|
||||
- iOS & macOS arm64 & tvOS
|
||||
@@ -163,14 +154,8 @@
|
||||
- Xray Wrapper
|
||||
- [XTLS/libXray](https://github.com/XTLS/libXray)
|
||||
- [xtls-sdk](https://github.com/remnawave/xtls-sdk)
|
||||
- [xtlsapi](https://github.com/hiddify/xtlsapi)
|
||||
- [AndroidLibXrayLite](https://github.com/2dust/AndroidLibXrayLite)
|
||||
- [flutter_vless](https://github.com/XIIIFOX/flutter_vless)
|
||||
- [Xray-core-python](https://github.com/LorenEteval/Xray-core-python)
|
||||
- [xray-api](https://github.com/XVGuardian/xray-api)
|
||||
- [XrayR](https://github.com/XrayR-project/XrayR)
|
||||
- [XrayR-release](https://github.com/XrayR-project/XrayR-release)
|
||||
- [XrayR-V2Board](https://github.com/missuo/XrayR-V2Board)
|
||||
- Cores
|
||||
- [Amnezia VPN](https://github.com/amnezia-vpn)
|
||||
- [mihomo](https://github.com/MetaCubeX/mihomo)
|
||||
@@ -178,9 +163,9 @@
|
||||
|
||||
## Contributing
|
||||
|
||||
[Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md)
|
||||
For code contributions, please read [CONTRIBUTING.md](CONTRIBUTING.md) and [Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md) before opening a pull request.
|
||||
|
||||
[](https://deepwiki.com/XTLS/Xray-core)
|
||||
[Ask DeepWiki](https://deepwiki.com/XTLS/Xray-core) might be helpful.
|
||||
|
||||
## Credits
|
||||
|
||||
@@ -231,19 +216,40 @@ Make sure that you are using the same Go version, and remember to set the git co
|
||||
CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
```
|
||||
|
||||
For Windows (x86-64 and AArch64, not win7):
|
||||
|
||||
```bash
|
||||
GOOS=windows GOARCH=amd64 GOAMD64=v2 CGO_ENABLED=0 go build -o xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
GOOS=windows GOARCH=arm64 GOARM64=v8.2 CGO_ENABLED=0 go build -o xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
```
|
||||
|
||||
For macOS:
|
||||
|
||||
```bash
|
||||
GOOS=darwin GOARCH=amd64 GOAMD64=v2 CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
GOOS=darwin GOARCH=arm64 GOARM64=v8.4 CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
```
|
||||
|
||||
For Android:
|
||||
|
||||
```bash
|
||||
GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=/path/to/aarch64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0" -v ./main
|
||||
GOOS=android GOARCH=amd64 CGO_ENABLED=1 CC=/path/to/x86_64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0" -v ./main
|
||||
GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=/path/to/aarch64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0 -extldflags=-Wl,--pack-dyn-relocs=android" -v ./main
|
||||
GOOS=android GOARCH=amd64 CGO_ENABLED=1 CC=/path/to/x86_64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0 -extldflags=-Wl,--pack-dyn-relocs=android" -v ./main
|
||||
```
|
||||
|
||||
If you are compiling a 32-bit MIPS/MIPSLE target, use this command instead:
|
||||
For Linux (MIPS32 and MIPS32LE):
|
||||
|
||||
```bash
|
||||
CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
GOOS=linux GOARCH=mips GOMIPS=hardfloat CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
GOOS=linux GOARCH=mips GOMIPS=softfloat CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
GOOS=linux GOARCH=mipsle GOMIPS=hardfloat CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||
```
|
||||
|
||||
## Stargazers over time
|
||||
|
||||
[](https://starchart.cc/XTLS/Xray-core)
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&theme=dark&legend=top-left" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
|
||||
</picture>
|
||||
|
||||
@@ -2,4 +2,10 @@
|
||||
|
||||
If you found an issue related to security vulnerability or protocol-identification problem, please report it to us via "[Report a vulnerability](https://github.com/XTLS/Xray-core/security/advisories/new)" privately, instead of publish it publicly before we release the fixed version.
|
||||
|
||||
Exceptions:
|
||||
|
||||
- ANY crash/panic bugs, memory/goroutine leaks, they should be reported via public [Issues](https://github.com/XTLS/Xray-core/issues) regardless of the cause
|
||||
- existing publicly discussed issues (known issues), or upstream problems such as uTLS browser fingerprints
|
||||
- undocumented/unexpected configs, low-impact vulnerabilities in the real world, they can be discussed publicly
|
||||
|
||||
Thanks for your contribution to the FREE Internet!
|
||||
|
||||
@@ -26,9 +26,16 @@ import (
|
||||
|
||||
var errSniffingTimeout = errors.New("timeout on sniffing")
|
||||
|
||||
// Native readers own attempted-input accounting, timeout and interruption.
|
||||
type nativeReader interface {
|
||||
buf.TimeoutReader
|
||||
common.Interruptible
|
||||
SetUplinkCounter(stats.Counter)
|
||||
}
|
||||
|
||||
type cachedReader struct {
|
||||
sync.Mutex
|
||||
reader buf.TimeoutReader // *pipe.Reader or *buf.TimeoutWrapperReader
|
||||
reader buf.TimeoutReader
|
||||
cache buf.MultiBuffer
|
||||
}
|
||||
|
||||
@@ -86,9 +93,7 @@ func (r *cachedReader) Interrupt() {
|
||||
r.cache = buf.ReleaseMulti(r.cache)
|
||||
}
|
||||
r.Unlock()
|
||||
if p, ok := r.reader.(*pipe.Reader); ok {
|
||||
p.Interrupt()
|
||||
}
|
||||
common.Interrupt(r.reader)
|
||||
}
|
||||
|
||||
// DefaultDispatcher is a default implementation of Dispatcher.
|
||||
@@ -194,15 +199,13 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
|
||||
user = sessionInbound.User
|
||||
}
|
||||
|
||||
link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader}
|
||||
var uplinkCounter stats.Counter
|
||||
|
||||
if user != nil && len(user.Email) > 0 {
|
||||
p := policyManager.ForLevel(user.Level)
|
||||
if p.Stats.UserUplink {
|
||||
name := "user>>>" + user.Email + ">>>traffic>>>uplink"
|
||||
if c, _ := statsManager.GetOrRegisterCounter(name); c != nil {
|
||||
link.Reader.(*buf.TimeoutWrapperReader).Counter = c
|
||||
}
|
||||
uplinkCounter, _ = statsManager.GetOrRegisterCounter(name)
|
||||
}
|
||||
if p.Stats.UserDownlink {
|
||||
name := "user>>>" + user.Email + ">>>traffic>>>downlink"
|
||||
@@ -218,6 +221,11 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
|
||||
}
|
||||
}
|
||||
|
||||
if reader, ok := link.Reader.(nativeReader); ok {
|
||||
reader.SetUplinkCounter(uplinkCounter)
|
||||
} else {
|
||||
link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader, Counter: uplinkCounter}
|
||||
}
|
||||
return link
|
||||
}
|
||||
|
||||
|
||||
@@ -124,14 +124,17 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
|
||||
if rec == nil {
|
||||
continue
|
||||
}
|
||||
if rec.A != nil && rec.A.Expire.Before(now) {
|
||||
rec.A = nil
|
||||
a, aaaa := rec.A, rec.AAAA
|
||||
if a != nil && a.Expire.Before(now) {
|
||||
a = nil
|
||||
}
|
||||
if rec.AAAA != nil && rec.AAAA.Expire.Before(now) {
|
||||
rec.AAAA = nil
|
||||
if aaaa != nil && aaaa.Expire.Before(now) {
|
||||
aaaa = nil
|
||||
}
|
||||
if rec.A == nil && rec.AAAA == nil {
|
||||
if a == nil && aaaa == nil {
|
||||
delete(c.ips, domain)
|
||||
} else if a != rec.A || aaaa != rec.AAAA {
|
||||
c.ips[domain] = &record{A: a, AAAA: aaaa}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+8
-8
@@ -148,7 +148,7 @@ func TestUDPServerSubnet(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -210,7 +210,7 @@ func TestUDPServer(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -350,7 +350,7 @@ func TestPrioritizedDomain(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -421,7 +421,7 @@ func TestUDPServerIPv6(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -490,7 +490,7 @@ func TestStaticHostDomain(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -577,7 +577,7 @@ func TestIPMatch(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -696,7 +696,7 @@ func TestLocalDomain(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -953,7 +953,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -68,6 +68,10 @@ func NewServer(ctx context.Context, dest net.Destination, dispatcher routing.Dis
|
||||
return NewTCPNameServer(u, dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
|
||||
case strings.EqualFold(u.Scheme, "tcp+local"): // DNS-over-TCP Local mode
|
||||
return NewTCPLocalNameServer(u, disableCache, serveStale, serveExpiredTTL, clientIP)
|
||||
case strings.EqualFold(u.Scheme, "udp"): // UDP DNS Remote mode
|
||||
return NewUDPNameServer(u, dispatcher, false, disableCache, serveStale, serveExpiredTTL, clientIP)
|
||||
case strings.EqualFold(u.Scheme, "udp+local"): // UDP DNS Local mode
|
||||
return NewUDPNameServer(u, dispatcher, true, disableCache, serveStale, serveExpiredTTL, clientIP)
|
||||
case strings.EqualFold(u.String(), "fakedns"):
|
||||
var fd dns.FakeDNSEngine
|
||||
err = core.RequireFeatures(ctx, func(fdns dns.FakeDNSEngine) {
|
||||
|
||||
@@ -2,12 +2,15 @@ package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol/dns"
|
||||
@@ -15,6 +18,8 @@ import (
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
dns_feature "github.com/xtls/xray-core/features/dns"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/udp"
|
||||
"golang.org/x/net/dns/dnsmessage"
|
||||
)
|
||||
@@ -59,6 +64,46 @@ func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher
|
||||
return s
|
||||
}
|
||||
|
||||
// NewUDPNameServer creates a UDP DNS client from a URL.
|
||||
func NewUDPNameServer(url *url.URL, dispatcher routing.Dispatcher, local bool, disableCache bool, serveStale bool, serveExpiredTTL uint32, clientIP net.IP) (*ClassicNameServer, error) {
|
||||
if url.Hostname() == "" {
|
||||
return nil, errors.New("missing UDP nameserver host")
|
||||
}
|
||||
port := net.Port(53)
|
||||
if url.Port() != "" {
|
||||
var err error
|
||||
if port, err = net.PortFromString(url.Port()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if local {
|
||||
dispatcher = &localUDPDispatcher{dispatcher}
|
||||
}
|
||||
s := NewClassicNameServer(net.UDPDestination(net.ParseAddress(url.Hostname()), port), dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
|
||||
if local {
|
||||
s.cacheController.name = "UDPL//" + s.address.NetAddr()
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
type localUDPDispatcher struct {
|
||||
routing.Dispatcher
|
||||
}
|
||||
|
||||
func (*localUDPDispatcher) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
conn, err := internet.DialSystem(ctx, dest, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transport.Link{
|
||||
Reader: &struct {
|
||||
buf.Reader
|
||||
io.Closer
|
||||
}{buf.NewPacketReader(conn), conn},
|
||||
Writer: buf.NewWriter(conn),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name implements Server.
|
||||
func (s *ClassicNameServer) Name() string {
|
||||
return s.cacheController.name
|
||||
|
||||
+13
-5
@@ -29,6 +29,7 @@ type MetricsHandler struct {
|
||||
listen string
|
||||
tcpListener xnet.Listener
|
||||
listener *OutboundListener
|
||||
server *http.Server
|
||||
}
|
||||
|
||||
// NewMetricsHandler creates a new MetricsHandler based on the given config.
|
||||
@@ -50,7 +51,8 @@ func (p *MetricsHandler) Type() interface{} {
|
||||
}
|
||||
|
||||
func (p *MetricsHandler) Start() error {
|
||||
handler := p.httpHandler()
|
||||
server := &http.Server{Handler: p.httpHandler()}
|
||||
p.server = server
|
||||
|
||||
// direct listen a port if listen is set
|
||||
if p.listen != "" {
|
||||
@@ -61,7 +63,7 @@ func (p *MetricsHandler) Start() error {
|
||||
p.tcpListener = TCPlistener
|
||||
errors.LogInfo(context.Background(), "Metrics server listening on ", p.listen)
|
||||
|
||||
go p.serve(TCPlistener, handler)
|
||||
go p.serve(TCPlistener, server)
|
||||
}
|
||||
|
||||
if p.tag == "" {
|
||||
@@ -77,7 +79,7 @@ func (p *MetricsHandler) Start() error {
|
||||
}
|
||||
p.listener = listener
|
||||
|
||||
go p.serve(listener, handler)
|
||||
go p.serve(listener, server)
|
||||
|
||||
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
|
||||
errors.LogInfo(context.Background(), "failed to remove existing handler")
|
||||
@@ -106,6 +108,12 @@ func (p *MetricsHandler) Close() error {
|
||||
errs = append(errs, p.listener.Close())
|
||||
p.listener = nil
|
||||
}
|
||||
if p.server != nil {
|
||||
if err := p.server.Close(); !isClosedListenerError(err) {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
p.server = nil
|
||||
}
|
||||
if p.ohm != nil && p.tag != "" {
|
||||
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
|
||||
errors.LogInfo(context.Background(), "failed to remove metrics handler")
|
||||
@@ -114,8 +122,8 @@ func (p *MetricsHandler) Close() error {
|
||||
return errors.Combine(errs...)
|
||||
}
|
||||
|
||||
func (p *MetricsHandler) serve(listener xnet.Listener, handler http.Handler) {
|
||||
if err := http.Serve(listener, handler); err != nil && !isClosedListenerError(err) {
|
||||
func (p *MetricsHandler) serve(listener xnet.Listener, server *http.Server) {
|
||||
if err := server.Serve(listener); err != nil && !isClosedListenerError(err) {
|
||||
errors.LogErrorInner(context.Background(), err, "failed to start metrics server")
|
||||
}
|
||||
}
|
||||
|
||||
+33
-121
@@ -328,13 +328,12 @@ func (*OutboundConfig) Descriptor() ([]byte, []int) {
|
||||
type SenderConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// Send traffic through the given IP. Only IP is allowed.
|
||||
Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"`
|
||||
StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"`
|
||||
MultiplexSettings *MultiplexingConfig `protobuf:"bytes,4,opt,name=multiplex_settings,json=multiplexSettings,proto3" json:"multiplex_settings,omitempty"`
|
||||
ViaCidr string `protobuf:"bytes,5,opt,name=via_cidr,json=viaCidr,proto3" json:"via_cidr,omitempty"`
|
||||
TargetStrategy internet.DomainStrategy `protobuf:"varint,6,opt,name=target_strategy,json=targetStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"target_strategy,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"`
|
||||
StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"`
|
||||
ViaCidr string `protobuf:"bytes,5,opt,name=via_cidr,json=viaCidr,proto3" json:"via_cidr,omitempty"`
|
||||
TargetStrategy internet.DomainStrategy `protobuf:"varint,6,opt,name=target_strategy,json=targetStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"target_strategy,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *SenderConfig) Reset() {
|
||||
@@ -381,13 +380,6 @@ func (x *SenderConfig) GetStreamSettings() *internet.StreamConfig {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *SenderConfig) GetMultiplexSettings() *MultiplexingConfig {
|
||||
if x != nil {
|
||||
return x.MultiplexSettings
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *SenderConfig) GetViaCidr() string {
|
||||
if x != nil {
|
||||
return x.ViaCidr
|
||||
@@ -402,78 +394,6 @@ func (x *SenderConfig) GetTargetStrategy() internet.DomainStrategy {
|
||||
return internet.DomainStrategy(0)
|
||||
}
|
||||
|
||||
type MultiplexingConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// Whether or not Mux is enabled.
|
||||
Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
|
||||
// Max number of concurrent connections that one Mux connection can handle.
|
||||
Concurrency int32 `protobuf:"varint,2,opt,name=concurrency,proto3" json:"concurrency,omitempty"`
|
||||
// Transport XUDP in another Mux.
|
||||
XudpConcurrency int32 `protobuf:"varint,3,opt,name=xudpConcurrency,proto3" json:"xudpConcurrency,omitempty"`
|
||||
// "reject" (default), "allow" or "skip".
|
||||
XudpProxyUDP443 string `protobuf:"bytes,4,opt,name=xudpProxyUDP443,proto3" json:"xudpProxyUDP443,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) Reset() {
|
||||
*x = MultiplexingConfig{}
|
||||
mi := &file_app_proxyman_config_proto_msgTypes[6]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*MultiplexingConfig) ProtoMessage() {}
|
||||
|
||||
func (x *MultiplexingConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_proxyman_config_proto_msgTypes[6]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use MultiplexingConfig.ProtoReflect.Descriptor instead.
|
||||
func (*MultiplexingConfig) Descriptor() ([]byte, []int) {
|
||||
return file_app_proxyman_config_proto_rawDescGZIP(), []int{6}
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) GetEnabled() bool {
|
||||
if x != nil {
|
||||
return x.Enabled
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) GetConcurrency() int32 {
|
||||
if x != nil {
|
||||
return x.Concurrency
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) GetXudpConcurrency() int32 {
|
||||
if x != nil {
|
||||
return x.XudpConcurrency
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *MultiplexingConfig) GetXudpProxyUDP443() string {
|
||||
if x != nil {
|
||||
return x.XudpProxyUDP443
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_app_proxyman_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_app_proxyman_config_proto_rawDesc = "" +
|
||||
@@ -498,18 +418,12 @@ const file_app_proxyman_config_proto_rawDesc = "" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12M\n" +
|
||||
"\x11receiver_settings\x18\x02 \x01(\v2 .xray.common.serial.TypedMessageR\x10receiverSettings\x12G\n" +
|
||||
"\x0eproxy_settings\x18\x03 \x01(\v2 .xray.common.serial.TypedMessageR\rproxySettings\"\x10\n" +
|
||||
"\x0eOutboundConfig\"\xd6\x02\n" +
|
||||
"\x0eOutboundConfig\"\x9a\x02\n" +
|
||||
"\fSenderConfig\x12-\n" +
|
||||
"\x03via\x18\x01 \x01(\v2\x1b.xray.common.net.IPOrDomainR\x03via\x12N\n" +
|
||||
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12T\n" +
|
||||
"\x12multiplex_settings\x18\x04 \x01(\v2%.xray.app.proxyman.MultiplexingConfigR\x11multiplexSettings\x12\x19\n" +
|
||||
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12\x19\n" +
|
||||
"\bvia_cidr\x18\x05 \x01(\tR\aviaCidr\x12P\n" +
|
||||
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04\"\xa4\x01\n" +
|
||||
"\x12MultiplexingConfig\x12\x18\n" +
|
||||
"\aenabled\x18\x01 \x01(\bR\aenabled\x12 \n" +
|
||||
"\vconcurrency\x18\x02 \x01(\x05R\vconcurrency\x12(\n" +
|
||||
"\x0fxudpConcurrency\x18\x03 \x01(\x05R\x0fxudpConcurrency\x12(\n" +
|
||||
"\x0fxudpProxyUDP443\x18\x04 \x01(\tR\x0fxudpProxyUDP443BU\n" +
|
||||
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\x12multiplex_settingsBU\n" +
|
||||
"\x15com.xray.app.proxymanP\x01Z&github.com/xtls/xray-core/app/proxyman\xaa\x02\x11Xray.App.Proxymanb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -524,7 +438,7 @@ func file_app_proxyman_config_proto_rawDescGZIP() []byte {
|
||||
return file_app_proxyman_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
|
||||
var file_app_proxyman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
|
||||
var file_app_proxyman_config_proto_goTypes = []any{
|
||||
(*InboundConfig)(nil), // 0: xray.app.proxyman.InboundConfig
|
||||
(*SniffingConfig)(nil), // 1: xray.app.proxyman.SniffingConfig
|
||||
@@ -532,33 +446,31 @@ var file_app_proxyman_config_proto_goTypes = []any{
|
||||
(*InboundHandlerConfig)(nil), // 3: xray.app.proxyman.InboundHandlerConfig
|
||||
(*OutboundConfig)(nil), // 4: xray.app.proxyman.OutboundConfig
|
||||
(*SenderConfig)(nil), // 5: xray.app.proxyman.SenderConfig
|
||||
(*MultiplexingConfig)(nil), // 6: xray.app.proxyman.MultiplexingConfig
|
||||
(*geodata.DomainRule)(nil), // 7: xray.common.geodata.DomainRule
|
||||
(*geodata.IPRule)(nil), // 8: xray.common.geodata.IPRule
|
||||
(*net.PortList)(nil), // 9: xray.common.net.PortList
|
||||
(*net.IPOrDomain)(nil), // 10: xray.common.net.IPOrDomain
|
||||
(*internet.StreamConfig)(nil), // 11: xray.transport.internet.StreamConfig
|
||||
(*serial.TypedMessage)(nil), // 12: xray.common.serial.TypedMessage
|
||||
(internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy
|
||||
(*geodata.DomainRule)(nil), // 6: xray.common.geodata.DomainRule
|
||||
(*geodata.IPRule)(nil), // 7: xray.common.geodata.IPRule
|
||||
(*net.PortList)(nil), // 8: xray.common.net.PortList
|
||||
(*net.IPOrDomain)(nil), // 9: xray.common.net.IPOrDomain
|
||||
(*internet.StreamConfig)(nil), // 10: xray.transport.internet.StreamConfig
|
||||
(*serial.TypedMessage)(nil), // 11: xray.common.serial.TypedMessage
|
||||
(internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy
|
||||
}
|
||||
var file_app_proxyman_config_proto_depIdxs = []int32{
|
||||
7, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
|
||||
8, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule
|
||||
9, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList
|
||||
10, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain
|
||||
11, // 4: xray.app.proxyman.ReceiverConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
6, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
|
||||
7, // 1: xray.app.proxyman.SniffingConfig.ips_excluded:type_name -> xray.common.geodata.IPRule
|
||||
8, // 2: xray.app.proxyman.ReceiverConfig.port_list:type_name -> xray.common.net.PortList
|
||||
9, // 3: xray.app.proxyman.ReceiverConfig.listen:type_name -> xray.common.net.IPOrDomain
|
||||
10, // 4: xray.app.proxyman.ReceiverConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
1, // 5: xray.app.proxyman.ReceiverConfig.sniffing_settings:type_name -> xray.app.proxyman.SniffingConfig
|
||||
12, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage
|
||||
12, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
|
||||
10, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
|
||||
11, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
6, // 10: xray.app.proxyman.SenderConfig.multiplex_settings:type_name -> xray.app.proxyman.MultiplexingConfig
|
||||
13, // 11: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||
12, // [12:12] is the sub-list for method output_type
|
||||
12, // [12:12] is the sub-list for method input_type
|
||||
12, // [12:12] is the sub-list for extension type_name
|
||||
12, // [12:12] is the sub-list for extension extendee
|
||||
0, // [0:12] is the sub-list for field type_name
|
||||
11, // 6: xray.app.proxyman.InboundHandlerConfig.receiver_settings:type_name -> xray.common.serial.TypedMessage
|
||||
11, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
|
||||
9, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
|
||||
10, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||
12, // 10: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||
11, // [11:11] is the sub-list for method output_type
|
||||
11, // [11:11] is the sub-list for method input_type
|
||||
11, // [11:11] is the sub-list for extension type_name
|
||||
11, // [11:11] is the sub-list for extension extendee
|
||||
0, // [0:11] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_app_proxyman_config_proto_init() }
|
||||
@@ -572,7 +484,7 @@ func file_app_proxyman_config_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_proxyman_config_proto_rawDesc), len(file_app_proxyman_config_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 7,
|
||||
NumMessages: 6,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
|
||||
@@ -57,19 +57,8 @@ message SenderConfig {
|
||||
// Send traffic through the given IP. Only IP is allowed.
|
||||
xray.common.net.IPOrDomain via = 1;
|
||||
xray.transport.internet.StreamConfig stream_settings = 2;
|
||||
reserved 3;
|
||||
MultiplexingConfig multiplex_settings = 4;
|
||||
reserved 3, 4;
|
||||
reserved "multiplex_settings";
|
||||
string via_cidr = 5;
|
||||
xray.transport.internet.DomainStrategy target_strategy = 6;
|
||||
}
|
||||
|
||||
message MultiplexingConfig {
|
||||
// Whether or not Mux is enabled.
|
||||
bool enabled = 1;
|
||||
// Max number of concurrent connections that one Mux connection can handle.
|
||||
int32 concurrency = 2;
|
||||
// Transport XUDP in another Mux.
|
||||
int32 xudpConcurrency = 3;
|
||||
// "reject" (default), "allow" or "skip".
|
||||
string xudpProxyUDP443 = 4;
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/features/stats"
|
||||
"github.com/xtls/xray-core/proxy"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
@@ -48,7 +48,6 @@ type AlwaysOnInboundHandler struct {
|
||||
receiverConfig *proxyman.ReceiverConfig
|
||||
proxy proxy.Inbound
|
||||
workers []worker
|
||||
mux *mux.Server
|
||||
tag string
|
||||
}
|
||||
|
||||
@@ -82,11 +81,14 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
return nil, errors.New("not an inbound proxy.")
|
||||
}
|
||||
|
||||
dispatcher := new(struct{ routing.Dispatcher })
|
||||
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher) { dispatcher.Dispatcher = d }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := &AlwaysOnInboundHandler{
|
||||
receiverConfig: receiverConfig,
|
||||
proxyConfig: proxyConfig,
|
||||
proxy: p,
|
||||
mux: mux.NewServer(ctx),
|
||||
tag: tag,
|
||||
}
|
||||
|
||||
@@ -117,7 +119,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
proxy: p,
|
||||
stream: mss,
|
||||
tag: tag,
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -139,7 +141,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
stream: mss,
|
||||
recvOrigDest: receiverConfig.ReceiveOriginalDestination,
|
||||
tag: tag,
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -154,7 +156,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
||||
proxy: p,
|
||||
address: address,
|
||||
port: net.Port(port),
|
||||
dispatcher: h.mux,
|
||||
dispatcher: dispatcher,
|
||||
sniffingRequest: sniffingRequest,
|
||||
uplinkCounter: uplinkCounter,
|
||||
downlinkCounter: downlinkCounter,
|
||||
@@ -192,7 +194,6 @@ func (h *AlwaysOnInboundHandler) Close() error {
|
||||
for _, worker := range h.workers {
|
||||
errs = append(errs, worker.Close())
|
||||
}
|
||||
errs = append(errs, h.mux.Close())
|
||||
errs = append(errs, common.Close(h.proxy))
|
||||
if err := errors.Combine(errs...); err != nil {
|
||||
return errors.New("failed to close all resources").Base(err)
|
||||
|
||||
@@ -51,7 +51,17 @@ func (m *Manager) AddHandler(ctx context.Context, handler inbound.Handler) error
|
||||
}
|
||||
|
||||
if m.running {
|
||||
return handler.Start()
|
||||
if err := handler.Start(); err != nil {
|
||||
if len(tag) > 0 {
|
||||
delete(m.taggedHandlers, tag)
|
||||
} else {
|
||||
m.untaggedHandlers = m.untaggedHandlers[:len(m.untaggedHandlers)-1]
|
||||
}
|
||||
if err := handler.Close(); err != nil {
|
||||
errors.LogWarningInner(ctx, err, "failed to close handler ", tag)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -273,8 +273,7 @@ type udpWorker struct {
|
||||
checker *task.Periodic
|
||||
activeConn map[connID]*udpConn
|
||||
|
||||
ctx context.Context
|
||||
cone bool
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
|
||||
@@ -316,9 +315,6 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest
|
||||
src: source,
|
||||
}
|
||||
if originalDest.IsValid() {
|
||||
if !w.cone {
|
||||
id.dest = originalDest
|
||||
}
|
||||
b.UDP = &originalDest
|
||||
}
|
||||
conn, existing := w.getConnection(id)
|
||||
@@ -418,8 +414,6 @@ func (w *udpWorker) Start() error {
|
||||
return err
|
||||
}
|
||||
|
||||
w.cone = w.ctx.Value("cone").(bool)
|
||||
|
||||
w.checker = &task.Periodic{
|
||||
Interval: time.Minute,
|
||||
Execute: w.clean,
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
@@ -60,9 +59,6 @@ type Handler struct {
|
||||
streamSettings *internet.MemoryStreamConfig
|
||||
proxyConfig proto.Message
|
||||
proxy proxy.Outbound
|
||||
mux *mux.ClientManager
|
||||
xudp *mux.ClientManager
|
||||
udp443 string
|
||||
uplinkCounter stats.Counter
|
||||
downlinkCounter stats.Counter
|
||||
}
|
||||
@@ -117,54 +113,6 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
|
||||
return nil, errors.New("not an outbound handler")
|
||||
}
|
||||
|
||||
if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
|
||||
if config := h.senderSettings.MultiplexSettings; config.Enabled {
|
||||
if config.Concurrency < 0 {
|
||||
h.mux = &mux.ClientManager{Enabled: false}
|
||||
}
|
||||
if config.Concurrency == 0 {
|
||||
config.Concurrency = 8 // same as before
|
||||
}
|
||||
if config.Concurrency > 0 {
|
||||
h.mux = &mux.ClientManager{
|
||||
Enabled: true,
|
||||
Picker: &mux.IncrementalWorkerPicker{
|
||||
Factory: &mux.DialingWorkerFactory{
|
||||
Proxy: proxyHandler,
|
||||
Dialer: h,
|
||||
Strategy: mux.ClientStrategy{
|
||||
MaxConcurrency: uint32(config.Concurrency),
|
||||
MaxConnection: 128,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
if config.XudpConcurrency < 0 {
|
||||
h.xudp = &mux.ClientManager{Enabled: false}
|
||||
}
|
||||
if config.XudpConcurrency == 0 {
|
||||
h.xudp = nil // same as before
|
||||
}
|
||||
if config.XudpConcurrency > 0 {
|
||||
h.xudp = &mux.ClientManager{
|
||||
Enabled: true,
|
||||
Picker: &mux.IncrementalWorkerPicker{
|
||||
Factory: &mux.DialingWorkerFactory{
|
||||
Proxy: proxyHandler,
|
||||
Dialer: h,
|
||||
Strategy: mux.ClientStrategy{
|
||||
MaxConcurrency: uint32(config.XudpConcurrency),
|
||||
MaxConnection: 128,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
h.udp443 = config.XudpProxyUDP443
|
||||
}
|
||||
}
|
||||
|
||||
h.proxy = proxyHandler
|
||||
return h, nil
|
||||
}
|
||||
@@ -178,65 +126,44 @@ func (h *Handler) Tag() string {
|
||||
func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
content := session.ContentFromContext(ctx)
|
||||
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) {
|
||||
strategy := h.senderSettings.TargetStrategy
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
|
||||
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
|
||||
}
|
||||
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
|
||||
if err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
|
||||
if h.senderSettings.TargetStrategy.ForceIP() {
|
||||
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
return
|
||||
}
|
||||
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() {
|
||||
if session.SkipDNSResolveFromContext(ctx) {
|
||||
errors.LogInfo(ctx, "bypassing targetStrategy ", h.senderSettings.TargetStrategy, " for ", ob.Target, "; preserving target domain")
|
||||
} else {
|
||||
unchangedDomain := ob.Target.Address.Domain()
|
||||
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
||||
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
|
||||
strategy := h.senderSettings.TargetStrategy
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
|
||||
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
|
||||
}
|
||||
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
|
||||
if err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
|
||||
if h.senderSettings.TargetStrategy.ForceIP() {
|
||||
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
unchangedDomain := ob.Target.Address.Domain()
|
||||
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
||||
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
reader, writer := link.Reader, link.Writer
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
}
|
||||
if h.mux != nil {
|
||||
test := func(err error) {
|
||||
if err != nil {
|
||||
err := errors.New("failed to process mux outbound traffic").Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
errors.LogInfo(ctx, err.Error())
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
}
|
||||
}
|
||||
if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 {
|
||||
switch h.udp443 {
|
||||
case "reject":
|
||||
test(errors.New("XUDP rejected UDP/443 traffic"))
|
||||
return
|
||||
case "skip":
|
||||
goto out
|
||||
}
|
||||
}
|
||||
if h.xudp != nil && ob.Target.Network == net.Network_UDP {
|
||||
if !h.xudp.Enabled {
|
||||
goto out
|
||||
}
|
||||
test(h.xudp.Dispatch(ctx, link))
|
||||
return
|
||||
}
|
||||
if h.mux.Enabled {
|
||||
test(h.mux.Dispatch(ctx, link))
|
||||
return
|
||||
}
|
||||
}
|
||||
out:
|
||||
|
||||
err := h.proxy.Process(ctx, link, h)
|
||||
var completion interface{ DeferWriterClose() bool }
|
||||
if goerrors.As(err, &completion) && completion.DeferWriterClose() {
|
||||
go common.Close(writer)
|
||||
common.Interrupt(reader)
|
||||
return
|
||||
}
|
||||
var errC error
|
||||
if err != nil {
|
||||
errC = errors.Cause(err)
|
||||
@@ -249,15 +176,15 @@ out:
|
||||
err := errors.New("failed to process outbound traffic").Base(err)
|
||||
session.SubmitOutboundErrorToOriginator(ctx, err)
|
||||
errors.LogInfo(ctx, err.Error())
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(writer)
|
||||
} else {
|
||||
if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) {
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(writer)
|
||||
} else {
|
||||
common.Close(link.Writer)
|
||||
common.Close(writer)
|
||||
}
|
||||
}
|
||||
common.Interrupt(link.Reader)
|
||||
common.Interrupt(reader)
|
||||
}
|
||||
|
||||
func (h *Handler) DestIpAddress() net.IP {
|
||||
@@ -329,7 +256,6 @@ func (h *Handler) Start() error {
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (h *Handler) Close() error {
|
||||
common.Close(h.mux)
|
||||
common.Close(h.proxy)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestOutboundWithoutStatCounter(t *testing.T) {
|
||||
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}})
|
||||
h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{
|
||||
Tag: "tag",
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||
})
|
||||
conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146))
|
||||
_, ok := conn.(*stat.CounterConnection)
|
||||
@@ -78,7 +78,7 @@ func TestOutboundWithStatCounter(t *testing.T) {
|
||||
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}})
|
||||
h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{
|
||||
Tag: "tag",
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||
})
|
||||
conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146))
|
||||
_, ok := conn.(*stat.CounterConnection)
|
||||
@@ -117,7 +117,7 @@ func TestTagsCache(t *testing.T) {
|
||||
tag := fmt.Sprintf("%s%d", tags_prefix, idx)
|
||||
cfg := &core.OutboundHandlerConfig{
|
||||
Tag: tag,
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||
}
|
||||
if h, err := NewHandler(ctx, cfg); err == nil {
|
||||
if err := ohm.AddHandler(ctx, h); err == nil {
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Bridge is a component in reverse proxy, that relays connections from Portal to local address.
|
||||
type Bridge struct {
|
||||
dispatcher routing.Dispatcher
|
||||
tag string
|
||||
domain string
|
||||
workers []*BridgeWorker
|
||||
monitorTask *task.Periodic
|
||||
}
|
||||
|
||||
// NewBridge creates a new Bridge instance.
|
||||
func NewBridge(config *BridgeConfig, dispatcher routing.Dispatcher) (*Bridge, error) {
|
||||
if config.Tag == "" {
|
||||
return nil, errors.New("bridge tag is empty")
|
||||
}
|
||||
if config.Domain == "" {
|
||||
return nil, errors.New("bridge domain is empty")
|
||||
}
|
||||
|
||||
b := &Bridge{
|
||||
dispatcher: dispatcher,
|
||||
tag: config.Tag,
|
||||
domain: config.Domain,
|
||||
}
|
||||
b.monitorTask = &task.Periodic{
|
||||
Execute: b.monitor,
|
||||
Interval: time.Second * 2,
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (b *Bridge) cleanup() {
|
||||
var activeWorkers []*BridgeWorker
|
||||
|
||||
for _, w := range b.workers {
|
||||
if w.IsActive() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
}
|
||||
if w.Closed() {
|
||||
if w.Timer != nil {
|
||||
w.Timer.SetTimeout(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(activeWorkers) != len(b.workers) {
|
||||
b.workers = activeWorkers
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bridge) monitor() error {
|
||||
b.cleanup()
|
||||
|
||||
var numConnections uint32
|
||||
var numWorker uint32
|
||||
|
||||
for _, w := range b.workers {
|
||||
if w.IsActive() {
|
||||
numConnections += w.Connections()
|
||||
numWorker++
|
||||
}
|
||||
}
|
||||
|
||||
if numWorker == 0 || numConnections/numWorker > 16 {
|
||||
worker, err := NewBridgeWorker(b.domain, b.tag, b.dispatcher)
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "failed to create bridge worker")
|
||||
return nil
|
||||
}
|
||||
b.workers = append(b.workers, worker)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bridge) Start() error {
|
||||
return b.monitorTask.Start()
|
||||
}
|
||||
|
||||
func (b *Bridge) Close() error {
|
||||
return b.monitorTask.Close()
|
||||
}
|
||||
|
||||
type BridgeWorker struct {
|
||||
Tag string
|
||||
Worker *mux.ServerWorker
|
||||
Dispatcher routing.Dispatcher
|
||||
State Control_State
|
||||
Timer *signal.ActivityTimer
|
||||
}
|
||||
|
||||
func NewBridgeWorker(domain string, tag string, d routing.Dispatcher) (*BridgeWorker, error) {
|
||||
ctx := context.Background()
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: tag,
|
||||
})
|
||||
link, err := d.Dispatch(ctx, net.Destination{
|
||||
Network: net.Network_TCP,
|
||||
Address: net.DomainAddress(domain),
|
||||
Port: 0,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w := &BridgeWorker{
|
||||
Dispatcher: d,
|
||||
Tag: tag,
|
||||
}
|
||||
|
||||
worker, err := mux.NewServerWorker(context.Background(), w, link)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.Worker = worker
|
||||
|
||||
terminate := func() {
|
||||
worker.Close()
|
||||
}
|
||||
w.Timer = signal.CancelAfterInactivity(ctx, terminate, 60*time.Second)
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Type() interface{} {
|
||||
return routing.DispatcherType()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) IsActive() bool {
|
||||
return w.State == Control_ACTIVE && !w.Worker.Closed()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Closed() bool {
|
||||
return w.Worker.Closed()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Connections() uint32 {
|
||||
return w.Worker.ActiveConnections()
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) handleInternalConn(link *transport.Link) {
|
||||
reader := link.Reader
|
||||
for {
|
||||
mb, err := reader.ReadMultiBuffer()
|
||||
if err != nil {
|
||||
if w.Timer != nil {
|
||||
if w.Closed() {
|
||||
w.Timer.SetTimeout(0)
|
||||
} else {
|
||||
w.Timer.SetTimeout(24 * time.Hour)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if w.Timer != nil {
|
||||
w.Timer.Update()
|
||||
}
|
||||
for _, b := range mb {
|
||||
var ctl Control
|
||||
if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to parse proto message")
|
||||
if w.Timer != nil {
|
||||
w.Timer.SetTimeout(0)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ctl.State != w.State {
|
||||
w.State = ctl.State
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
if !isInternalDomain(dest) {
|
||||
if session.InboundFromContext(ctx) == nil {
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: w.Tag,
|
||||
})
|
||||
}
|
||||
return w.Dispatcher.Dispatch(ctx, dest)
|
||||
}
|
||||
|
||||
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
|
||||
uplinkReader, uplinkWriter := pipe.New(opt...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opt...)
|
||||
|
||||
go w.handleInternalConn(&transport.Link{
|
||||
Reader: downlinkReader,
|
||||
Writer: uplinkWriter,
|
||||
})
|
||||
|
||||
return &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (w *BridgeWorker) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
if !isInternalDomain(dest) {
|
||||
if session.InboundFromContext(ctx) == nil {
|
||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{
|
||||
Tag: w.Tag,
|
||||
})
|
||||
}
|
||||
return w.Dispatcher.DispatchLink(ctx, dest, link)
|
||||
}
|
||||
w.handleInternalConn(link)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,356 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.12
|
||||
// protoc (unknown)
|
||||
// source: app/reverse/config.proto
|
||||
|
||||
package reverse
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Control_State int32
|
||||
|
||||
const (
|
||||
Control_ACTIVE Control_State = 0
|
||||
Control_DRAIN Control_State = 1
|
||||
)
|
||||
|
||||
// Enum value maps for Control_State.
|
||||
var (
|
||||
Control_State_name = map[int32]string{
|
||||
0: "ACTIVE",
|
||||
1: "DRAIN",
|
||||
}
|
||||
Control_State_value = map[string]int32{
|
||||
"ACTIVE": 0,
|
||||
"DRAIN": 1,
|
||||
}
|
||||
)
|
||||
|
||||
func (x Control_State) Enum() *Control_State {
|
||||
p := new(Control_State)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x Control_State) String() string {
|
||||
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
|
||||
}
|
||||
|
||||
func (Control_State) Descriptor() protoreflect.EnumDescriptor {
|
||||
return file_app_reverse_config_proto_enumTypes[0].Descriptor()
|
||||
}
|
||||
|
||||
func (Control_State) Type() protoreflect.EnumType {
|
||||
return &file_app_reverse_config_proto_enumTypes[0]
|
||||
}
|
||||
|
||||
func (x Control_State) Number() protoreflect.EnumNumber {
|
||||
return protoreflect.EnumNumber(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Control_State.Descriptor instead.
|
||||
func (Control_State) EnumDescriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{0, 0}
|
||||
}
|
||||
|
||||
type Control struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
State Control_State `protobuf:"varint,1,opt,name=state,proto3,enum=xray.app.reverse.Control_State" json:"state,omitempty"`
|
||||
Random []byte `protobuf:"bytes,99,opt,name=random,proto3" json:"random,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Control) Reset() {
|
||||
*x = Control{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Control) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Control) ProtoMessage() {}
|
||||
|
||||
func (x *Control) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Control.ProtoReflect.Descriptor instead.
|
||||
func (*Control) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Control) GetState() Control_State {
|
||||
if x != nil {
|
||||
return x.State
|
||||
}
|
||||
return Control_ACTIVE
|
||||
}
|
||||
|
||||
func (x *Control) GetRandom() []byte {
|
||||
if x != nil {
|
||||
return x.Random
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type BridgeConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
|
||||
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) Reset() {
|
||||
*x = BridgeConfig{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*BridgeConfig) ProtoMessage() {}
|
||||
|
||||
func (x *BridgeConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use BridgeConfig.ProtoReflect.Descriptor instead.
|
||||
func (*BridgeConfig) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) GetTag() string {
|
||||
if x != nil {
|
||||
return x.Tag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *BridgeConfig) GetDomain() string {
|
||||
if x != nil {
|
||||
return x.Domain
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type PortalConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
|
||||
Domain string `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *PortalConfig) Reset() {
|
||||
*x = PortalConfig{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *PortalConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*PortalConfig) ProtoMessage() {}
|
||||
|
||||
func (x *PortalConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use PortalConfig.ProtoReflect.Descriptor instead.
|
||||
func (*PortalConfig) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *PortalConfig) GetTag() string {
|
||||
if x != nil {
|
||||
return x.Tag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *PortalConfig) GetDomain() string {
|
||||
if x != nil {
|
||||
return x.Domain
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
BridgeConfig []*BridgeConfig `protobuf:"bytes,1,rep,name=bridge_config,json=bridgeConfig,proto3" json:"bridge_config,omitempty"`
|
||||
PortalConfig []*PortalConfig `protobuf:"bytes,2,rep,name=portal_config,json=portalConfig,proto3" json:"portal_config,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
*x = Config{}
|
||||
mi := &file_app_reverse_config_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Config) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Config) ProtoMessage() {}
|
||||
|
||||
func (x *Config) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_app_reverse_config_proto_msgTypes[3]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
|
||||
func (*Config) Descriptor() ([]byte, []int) {
|
||||
return file_app_reverse_config_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *Config) GetBridgeConfig() []*BridgeConfig {
|
||||
if x != nil {
|
||||
return x.BridgeConfig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetPortalConfig() []*PortalConfig {
|
||||
if x != nil {
|
||||
return x.PortalConfig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_app_reverse_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_app_reverse_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x18app/reverse/config.proto\x12\x10xray.app.reverse\"x\n" +
|
||||
"\aControl\x125\n" +
|
||||
"\x05state\x18\x01 \x01(\x0e2\x1f.xray.app.reverse.Control.StateR\x05state\x12\x16\n" +
|
||||
"\x06random\x18c \x01(\fR\x06random\"\x1e\n" +
|
||||
"\x05State\x12\n" +
|
||||
"\n" +
|
||||
"\x06ACTIVE\x10\x00\x12\t\n" +
|
||||
"\x05DRAIN\x10\x01\"8\n" +
|
||||
"\fBridgeConfig\x12\x10\n" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
|
||||
"\x06domain\x18\x02 \x01(\tR\x06domain\"8\n" +
|
||||
"\fPortalConfig\x12\x10\n" +
|
||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12\x16\n" +
|
||||
"\x06domain\x18\x02 \x01(\tR\x06domain\"\x92\x01\n" +
|
||||
"\x06Config\x12C\n" +
|
||||
"\rbridge_config\x18\x01 \x03(\v2\x1e.xray.app.reverse.BridgeConfigR\fbridgeConfig\x12C\n" +
|
||||
"\rportal_config\x18\x02 \x03(\v2\x1e.xray.app.reverse.PortalConfigR\fportalConfigBV\n" +
|
||||
"\x16com.xray.proxy.reverseP\x01Z%github.com/xtls/xray-core/app/reverse\xaa\x02\x12Xray.Proxy.Reverseb\x06proto3"
|
||||
|
||||
var (
|
||||
file_app_reverse_config_proto_rawDescOnce sync.Once
|
||||
file_app_reverse_config_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_app_reverse_config_proto_rawDescGZIP() []byte {
|
||||
file_app_reverse_config_proto_rawDescOnce.Do(func() {
|
||||
file_app_reverse_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)))
|
||||
})
|
||||
return file_app_reverse_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_app_reverse_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||
var file_app_reverse_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
|
||||
var file_app_reverse_config_proto_goTypes = []any{
|
||||
(Control_State)(0), // 0: xray.app.reverse.Control.State
|
||||
(*Control)(nil), // 1: xray.app.reverse.Control
|
||||
(*BridgeConfig)(nil), // 2: xray.app.reverse.BridgeConfig
|
||||
(*PortalConfig)(nil), // 3: xray.app.reverse.PortalConfig
|
||||
(*Config)(nil), // 4: xray.app.reverse.Config
|
||||
}
|
||||
var file_app_reverse_config_proto_depIdxs = []int32{
|
||||
0, // 0: xray.app.reverse.Control.state:type_name -> xray.app.reverse.Control.State
|
||||
2, // 1: xray.app.reverse.Config.bridge_config:type_name -> xray.app.reverse.BridgeConfig
|
||||
3, // 2: xray.app.reverse.Config.portal_config:type_name -> xray.app.reverse.PortalConfig
|
||||
3, // [3:3] is the sub-list for method output_type
|
||||
3, // [3:3] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_app_reverse_config_proto_init() }
|
||||
func file_app_reverse_config_proto_init() {
|
||||
if File_app_reverse_config_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_reverse_config_proto_rawDesc), len(file_app_reverse_config_proto_rawDesc)),
|
||||
NumEnums: 1,
|
||||
NumMessages: 4,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_app_reverse_config_proto_goTypes,
|
||||
DependencyIndexes: file_app_reverse_config_proto_depIdxs,
|
||||
EnumInfos: file_app_reverse_config_proto_enumTypes,
|
||||
MessageInfos: file_app_reverse_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_app_reverse_config_proto = out.File
|
||||
file_app_reverse_config_proto_goTypes = nil
|
||||
file_app_reverse_config_proto_depIdxs = nil
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package xray.app.reverse;
|
||||
option csharp_namespace = "Xray.Proxy.Reverse";
|
||||
option go_package = "github.com/xtls/xray-core/app/reverse";
|
||||
option java_package = "com.xray.proxy.reverse";
|
||||
option java_multiple_files = true;
|
||||
|
||||
message Control {
|
||||
enum State {
|
||||
ACTIVE = 0;
|
||||
DRAIN = 1;
|
||||
}
|
||||
|
||||
State state = 1;
|
||||
bytes random = 99;
|
||||
}
|
||||
|
||||
message BridgeConfig {
|
||||
string tag = 1;
|
||||
string domain = 2;
|
||||
}
|
||||
|
||||
message PortalConfig {
|
||||
string tag = 1;
|
||||
string domain = 2;
|
||||
}
|
||||
|
||||
message Config {
|
||||
repeated BridgeConfig bridge_config = 1;
|
||||
repeated PortalConfig portal_config = 2;
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type Portal struct {
|
||||
ohm outbound.Manager
|
||||
tag string
|
||||
domain string
|
||||
picker *StaticMuxPicker
|
||||
client *mux.ClientManager
|
||||
}
|
||||
|
||||
func NewPortal(config *PortalConfig, ohm outbound.Manager) (*Portal, error) {
|
||||
if config.Tag == "" {
|
||||
return nil, errors.New("portal tag is empty")
|
||||
}
|
||||
|
||||
if config.Domain == "" {
|
||||
return nil, errors.New("portal domain is empty")
|
||||
}
|
||||
|
||||
picker, err := NewStaticMuxPicker()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Portal{
|
||||
ohm: ohm,
|
||||
tag: config.Tag,
|
||||
domain: config.Domain,
|
||||
picker: picker,
|
||||
client: &mux.ClientManager{
|
||||
Picker: picker,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Portal) Start() error {
|
||||
return p.ohm.AddHandler(context.Background(), &Outbound{
|
||||
portal: p,
|
||||
tag: p.tag,
|
||||
})
|
||||
}
|
||||
|
||||
func (p *Portal) Close() error {
|
||||
return p.ohm.RemoveHandler(context.Background(), p.tag)
|
||||
}
|
||||
|
||||
func (p *Portal) HandleConnection(ctx context.Context, link *transport.Link) error {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
if ob == nil {
|
||||
return errors.New("outbound metadata not found")
|
||||
}
|
||||
|
||||
if isDomain(ob.Target, p.domain) {
|
||||
muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
|
||||
if err != nil {
|
||||
return errors.New("failed to create mux client worker").Base(err)
|
||||
}
|
||||
|
||||
worker, err := NewPortalWorker(muxClient)
|
||||
if err != nil {
|
||||
return errors.New("failed to create portal worker").Base(err)
|
||||
}
|
||||
|
||||
p.picker.AddWorker(worker)
|
||||
|
||||
if _, ok := link.Reader.(*pipe.Reader); !ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-muxClient.WaitClosed():
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
|
||||
link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
|
||||
}
|
||||
|
||||
return p.client.Dispatch(ctx, link)
|
||||
}
|
||||
|
||||
type Outbound struct {
|
||||
portal *Portal
|
||||
tag string
|
||||
}
|
||||
|
||||
func (o *Outbound) Tag() string {
|
||||
return o.tag
|
||||
}
|
||||
|
||||
func (o *Outbound) Dispatch(ctx context.Context, link *transport.Link) {
|
||||
if err := o.portal.HandleConnection(ctx, link); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to process reverse connection")
|
||||
common.Interrupt(link.Writer)
|
||||
common.Interrupt(link.Reader)
|
||||
}
|
||||
}
|
||||
|
||||
func (o *Outbound) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Outbound) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SenderSettings implements outbound.Handler.
|
||||
func (o *Outbound) SenderSettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProxySettings implements outbound.Handler.
|
||||
func (o *Outbound) ProxySettings() *serial.TypedMessage {
|
||||
return nil
|
||||
}
|
||||
|
||||
type StaticMuxPicker struct {
|
||||
access sync.Mutex
|
||||
workers []*PortalWorker
|
||||
cTask *task.Periodic
|
||||
}
|
||||
|
||||
func NewStaticMuxPicker() (*StaticMuxPicker, error) {
|
||||
p := &StaticMuxPicker{}
|
||||
p.cTask = &task.Periodic{
|
||||
Execute: p.cleanup,
|
||||
Interval: time.Second * 30,
|
||||
}
|
||||
p.cTask.Start()
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) cleanup() error {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
var activeWorkers []*PortalWorker
|
||||
for _, w := range p.workers {
|
||||
if !w.Closed() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
} else {
|
||||
w.timer.SetTimeout(0)
|
||||
}
|
||||
}
|
||||
|
||||
if len(activeWorkers) != len(p.workers) {
|
||||
p.workers = activeWorkers
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
if len(p.workers) == 0 {
|
||||
return nil, errors.New("empty worker list")
|
||||
}
|
||||
|
||||
var minIdx int = -1
|
||||
var minConn uint32 = 9999
|
||||
for i, w := range p.workers {
|
||||
if w.draining {
|
||||
continue
|
||||
}
|
||||
if w.IsFull() {
|
||||
continue
|
||||
}
|
||||
if w.client.ActiveConnections() < minConn {
|
||||
minConn = w.client.ActiveConnections()
|
||||
minIdx = i
|
||||
}
|
||||
}
|
||||
|
||||
if minIdx == -1 {
|
||||
for i, w := range p.workers {
|
||||
if w.IsFull() {
|
||||
continue
|
||||
}
|
||||
if w.client.ActiveConnections() < minConn {
|
||||
minConn = w.client.ActiveConnections()
|
||||
minIdx = i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if minIdx != -1 {
|
||||
return p.workers[minIdx].client, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("no mux client worker available")
|
||||
}
|
||||
|
||||
func (p *StaticMuxPicker) AddWorker(worker *PortalWorker) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
p.workers = append(p.workers, worker)
|
||||
}
|
||||
|
||||
type PortalWorker struct {
|
||||
client *mux.ClientWorker
|
||||
control *task.Periodic
|
||||
writer buf.Writer
|
||||
reader buf.Reader
|
||||
draining bool
|
||||
counter uint32
|
||||
timer *signal.ActivityTimer
|
||||
}
|
||||
|
||||
func NewPortalWorker(client *mux.ClientWorker) (*PortalWorker, error) {
|
||||
opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
|
||||
uplinkReader, uplinkWriter := pipe.New(opt...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opt...)
|
||||
|
||||
ctx := context.Background()
|
||||
outbounds := []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.DomainAddress(internalDomain), 0),
|
||||
}}
|
||||
ctx = session.ContextWithOutbounds(ctx, outbounds)
|
||||
f := client.Dispatch(ctx, &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
})
|
||||
if !f {
|
||||
return nil, errors.New("unable to dispatch control connection")
|
||||
}
|
||||
terminate := func() {
|
||||
client.Close()
|
||||
}
|
||||
w := &PortalWorker{
|
||||
client: client,
|
||||
reader: downlinkReader,
|
||||
writer: uplinkWriter,
|
||||
timer: signal.CancelAfterInactivity(ctx, terminate, 24*time.Hour), // // prevent leak
|
||||
}
|
||||
w.control = &task.Periodic{
|
||||
Execute: w.heartbeat,
|
||||
Interval: time.Second * 2,
|
||||
}
|
||||
w.control.Start()
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *PortalWorker) heartbeat() error {
|
||||
if w.Closed() {
|
||||
return errors.New("client worker stopped")
|
||||
}
|
||||
|
||||
if w.draining || w.writer == nil {
|
||||
return errors.New("already disposed")
|
||||
}
|
||||
|
||||
msg := &Control{}
|
||||
msg.FillInRandom()
|
||||
|
||||
if w.client.TotalConnections() > 256 {
|
||||
w.draining = true
|
||||
msg.State = Control_DRAIN
|
||||
|
||||
defer func() {
|
||||
common.Close(w.writer)
|
||||
common.Interrupt(w.reader)
|
||||
w.writer = nil
|
||||
}()
|
||||
}
|
||||
|
||||
w.counter = (w.counter + 1) % 5
|
||||
if w.draining || w.counter == 1 {
|
||||
b, err := proto.Marshal(msg)
|
||||
common.Must(err)
|
||||
mb := buf.MergeBytes(nil, b)
|
||||
w.timer.Update()
|
||||
return w.writer.WriteMultiBuffer(mb)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *PortalWorker) IsFull() bool {
|
||||
return w.client.IsFull()
|
||||
}
|
||||
|
||||
func (w *PortalWorker) Closed() bool {
|
||||
return w.client.Closed()
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package reverse_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/common"
|
||||
)
|
||||
|
||||
func TestStaticPickerEmpty(t *testing.T) {
|
||||
picker, err := reverse.NewStaticMuxPicker()
|
||||
common.Must(err)
|
||||
worker, err := picker.PickAvailable()
|
||||
if err == nil {
|
||||
t.Error("expected error, but nil")
|
||||
}
|
||||
if worker != nil {
|
||||
t.Error("expected nil worker, but not nil")
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package reverse
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
)
|
||||
|
||||
const (
|
||||
internalDomain = "reverse"
|
||||
)
|
||||
|
||||
func isDomain(dest net.Destination, domain string) bool {
|
||||
return dest.Address.Family().IsDomain() && dest.Address.Domain() == domain
|
||||
}
|
||||
|
||||
func isInternalDomain(dest net.Destination) bool {
|
||||
return isDomain(dest, internalDomain)
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
r := new(Reverse)
|
||||
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher, om outbound.Manager) error {
|
||||
return r.Init(config.(*Config), d, om)
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}))
|
||||
}
|
||||
|
||||
type Reverse struct {
|
||||
bridges []*Bridge
|
||||
portals []*Portal
|
||||
}
|
||||
|
||||
func (r *Reverse) Init(config *Config, d routing.Dispatcher, ohm outbound.Manager) error {
|
||||
for _, bConfig := range config.BridgeConfig {
|
||||
b, err := NewBridge(bConfig, d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.bridges = append(r.bridges, b)
|
||||
}
|
||||
|
||||
for _, pConfig := range config.PortalConfig {
|
||||
p, err := NewPortal(pConfig, ohm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.portals = append(r.portals, p)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Type() interface{} {
|
||||
return (*Reverse)(nil)
|
||||
}
|
||||
|
||||
func (r *Reverse) Start() error {
|
||||
for _, b := range r.bridges {
|
||||
if err := b.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, p := range r.portals {
|
||||
if err := p.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reverse) Close() error {
|
||||
var errs []error
|
||||
for _, b := range r.bridges {
|
||||
errs = append(errs, b.Close())
|
||||
}
|
||||
|
||||
for _, p := range r.portals {
|
||||
errs = append(errs, p.Close())
|
||||
}
|
||||
|
||||
return errors.Combine(errs...)
|
||||
}
|
||||
@@ -44,9 +44,8 @@ func (c routingContext) GetRuleTag() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetSkipDNSResolve is a mock implementation here to match the interface,
|
||||
// SkipDNSResolve is set from dns module, no use if coming from a protobuf object?
|
||||
// TODO: please confirm @Vigilans
|
||||
// GetSkipDNSResolve implements routing.Context.
|
||||
// The protobuf RoutingContext has no skip flag, so API contexts use false.
|
||||
func (c routingContext) GetSkipDNSResolve() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
"github.com/xtls/xray-core/features/outbound"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
routing_session "github.com/xtls/xray-core/features/routing/session"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
@@ -397,9 +396,9 @@ end`)
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
},
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "default", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})},
|
||||
{Tag: "default", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
})},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !windows && !wasm && !illumos && !openbsd
|
||||
// +build !windows,!wasm,!illumos,!openbsd
|
||||
//go:build !windows && !openbsd
|
||||
|
||||
package buf
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !wasm && !openbsd
|
||||
// +build !wasm,!openbsd
|
||||
//go:build !openbsd
|
||||
|
||||
package buf
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build wasm || openbsd
|
||||
// +build wasm openbsd
|
||||
//go:build openbsd
|
||||
|
||||
package buf
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !wasm && !openbsd
|
||||
// +build !wasm,!openbsd
|
||||
//go:build !openbsd
|
||||
|
||||
package buf_test
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
//go:build illumos
|
||||
// +build illumos
|
||||
|
||||
package buf
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
type unixReader struct {
|
||||
iovs [][]byte
|
||||
}
|
||||
|
||||
func (r *unixReader) Init(bs []*Buffer) {
|
||||
iovs := r.iovs
|
||||
if iovs == nil {
|
||||
iovs = make([][]byte, 0, len(bs))
|
||||
}
|
||||
for _, b := range bs {
|
||||
iovs = append(iovs, b.v)
|
||||
}
|
||||
r.iovs = iovs
|
||||
}
|
||||
|
||||
func (r *unixReader) Read(fd uintptr) int32 {
|
||||
n, e := unix.Readv(int(fd), r.iovs)
|
||||
if e != nil {
|
||||
return -1
|
||||
}
|
||||
return int32(n)
|
||||
}
|
||||
|
||||
func (r *unixReader) Clear() {
|
||||
r.iovs = r.iovs[:0]
|
||||
}
|
||||
|
||||
func newMultiReader() multiReader {
|
||||
return &unixReader{}
|
||||
}
|
||||
@@ -236,6 +236,10 @@ func (w *BufferedWriter) Close() error {
|
||||
return common.Close(w.writer)
|
||||
}
|
||||
|
||||
func (w *BufferedWriter) Interrupt() {
|
||||
common.Interrupt(w.writer)
|
||||
}
|
||||
|
||||
// SequentialWriter is a Writer that writes MultiBuffer sequentially into the underlying io.Writer.
|
||||
type SequentialWriter struct {
|
||||
io.Writer
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build generate
|
||||
// +build generate
|
||||
|
||||
package main
|
||||
|
||||
|
||||
@@ -1,417 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
goerrors "errors"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
"github.com/xtls/xray-core/proxy"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type ClientManager struct {
|
||||
Enabled bool // whether mux is enabled from user config
|
||||
Picker WorkerPicker
|
||||
}
|
||||
|
||||
func (m *ClientManager) Dispatch(ctx context.Context, link *transport.Link) error {
|
||||
for i := 0; i < 16; i++ {
|
||||
worker, err := m.Picker.PickAvailable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if worker.Dispatch(ctx, link) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New("unable to find an available mux client")
|
||||
}
|
||||
|
||||
type WorkerPicker interface {
|
||||
PickAvailable() (*ClientWorker, error)
|
||||
}
|
||||
|
||||
type IncrementalWorkerPicker struct {
|
||||
Factory ClientWorkerFactory
|
||||
|
||||
access sync.Mutex
|
||||
workers []*ClientWorker
|
||||
cleanupTask *task.Periodic
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) cleanupFunc() error {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
if len(p.workers) == 0 {
|
||||
return errors.New("no worker")
|
||||
}
|
||||
|
||||
p.cleanup()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) cleanup() {
|
||||
var activeWorkers []*ClientWorker
|
||||
for _, w := range p.workers {
|
||||
if !w.Closed() {
|
||||
activeWorkers = append(activeWorkers, w)
|
||||
}
|
||||
}
|
||||
p.workers = activeWorkers
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) findAvailable() int {
|
||||
for idx, w := range p.workers {
|
||||
if !w.IsFull() {
|
||||
return idx
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) pickInternal() (*ClientWorker, bool, error) {
|
||||
p.access.Lock()
|
||||
defer p.access.Unlock()
|
||||
|
||||
idx := p.findAvailable()
|
||||
if idx >= 0 {
|
||||
n := len(p.workers)
|
||||
if n > 1 && idx != n-1 {
|
||||
p.workers[n-1], p.workers[idx] = p.workers[idx], p.workers[n-1]
|
||||
}
|
||||
return p.workers[idx], false, nil
|
||||
}
|
||||
|
||||
p.cleanup()
|
||||
|
||||
worker, err := p.Factory.Create()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
p.workers = append(p.workers, worker)
|
||||
|
||||
if p.cleanupTask == nil {
|
||||
p.cleanupTask = &task.Periodic{
|
||||
Interval: time.Second * 30,
|
||||
Execute: p.cleanupFunc,
|
||||
}
|
||||
}
|
||||
|
||||
return worker, true, nil
|
||||
}
|
||||
|
||||
func (p *IncrementalWorkerPicker) PickAvailable() (*ClientWorker, error) {
|
||||
worker, start, err := p.pickInternal()
|
||||
if start {
|
||||
common.Must(p.cleanupTask.Start())
|
||||
}
|
||||
|
||||
return worker, err
|
||||
}
|
||||
|
||||
type ClientWorkerFactory interface {
|
||||
Create() (*ClientWorker, error)
|
||||
}
|
||||
|
||||
type DialingWorkerFactory struct {
|
||||
Proxy proxy.Outbound
|
||||
Dialer internet.Dialer
|
||||
Strategy ClientStrategy
|
||||
}
|
||||
|
||||
func (f *DialingWorkerFactory) Create() (*ClientWorker, error) {
|
||||
opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)}
|
||||
uplinkReader, upLinkWriter := pipe.New(opts...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opts...)
|
||||
|
||||
c, err := NewClientWorker(transport.Link{
|
||||
Reader: downlinkReader,
|
||||
Writer: upLinkWriter,
|
||||
}, f.Strategy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go func(p proxy.Outbound, d internet.Dialer, c common.Closable) {
|
||||
outbounds := []*session.Outbound{{
|
||||
Target: net.TCPDestination(muxCoolAddress, muxCoolPort),
|
||||
}}
|
||||
ctx := session.ContextWithOutbounds(context.Background(), outbounds)
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
if errP := p.Process(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter}, d); errP != nil {
|
||||
errC := errors.Cause(errP)
|
||||
if !(goerrors.Is(errC, io.EOF) || goerrors.Is(errC, io.ErrClosedPipe) || goerrors.Is(errC, context.Canceled)) {
|
||||
errors.LogInfoInner(ctx, errP, "failed to handler mux client connection")
|
||||
}
|
||||
}
|
||||
common.Must(c.Close())
|
||||
cancel()
|
||||
}(f.Proxy, f.Dialer, c.done)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type ClientStrategy struct {
|
||||
MaxConcurrency uint32
|
||||
MaxConnection uint32
|
||||
}
|
||||
|
||||
type ClientWorker struct {
|
||||
sessionManager *SessionManager
|
||||
link transport.Link
|
||||
done *done.Instance
|
||||
timer *time.Ticker
|
||||
strategy ClientStrategy
|
||||
}
|
||||
|
||||
var (
|
||||
muxCoolAddress = net.DomainAddress("v1.mux.cool")
|
||||
muxCoolPort = net.Port(9527)
|
||||
)
|
||||
|
||||
// NewClientWorker creates a new mux.Client.
|
||||
func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) {
|
||||
c := &ClientWorker{
|
||||
sessionManager: NewSessionManager(),
|
||||
link: stream,
|
||||
done: done.New(),
|
||||
timer: time.NewTicker(time.Second * 16),
|
||||
strategy: s,
|
||||
}
|
||||
|
||||
go c.fetchOutput()
|
||||
go c.monitor()
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) TotalConnections() uint32 {
|
||||
return uint32(m.sessionManager.Count())
|
||||
}
|
||||
|
||||
func (m *ClientWorker) ActiveConnections() uint32 {
|
||||
return uint32(m.sessionManager.Size())
|
||||
}
|
||||
|
||||
// Closed returns true if this Client is closed.
|
||||
func (m *ClientWorker) Closed() bool {
|
||||
return m.done.Done()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) WaitClosed() <-chan struct{} {
|
||||
return m.done.Wait()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) Close() error {
|
||||
return m.done.Close()
|
||||
}
|
||||
|
||||
func (m *ClientWorker) monitor() {
|
||||
defer m.timer.Stop()
|
||||
|
||||
for {
|
||||
checkSize := m.sessionManager.Size()
|
||||
checkCount := m.sessionManager.Count()
|
||||
select {
|
||||
case <-m.done.Wait():
|
||||
m.sessionManager.Close()
|
||||
common.Interrupt(m.link.Writer)
|
||||
common.Interrupt(m.link.Reader)
|
||||
return
|
||||
case <-m.timer.C:
|
||||
if m.sessionManager.CloseIfNoSessionAndIdle(checkSize, checkCount) {
|
||||
common.Must(m.done.Close())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeFirstPayload(reader buf.Reader, writer *Writer) error {
|
||||
err := buf.CopyOnceTimeout(reader, writer, time.Millisecond*100)
|
||||
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
|
||||
return writer.WriteMultiBuffer(buf.MultiBuffer{})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
transferType := protocol.TransferTypeStream
|
||||
if ob.Target.Network == net.Network_UDP {
|
||||
transferType = protocol.TransferTypePacket
|
||||
}
|
||||
s.transferType = transferType
|
||||
var inbound *session.Inbound
|
||||
if session.IsReverseMuxFromContext(ctx) {
|
||||
inbound = session.InboundFromContext(ctx)
|
||||
}
|
||||
writer := NewWriter(s.ID, ob.Target, output, transferType, xudp.GetGlobalID(ctx), inbound)
|
||||
defer s.Close(false)
|
||||
defer writer.Close()
|
||||
|
||||
errors.LogInfo(ctx, "dispatching request to ", ob.Target)
|
||||
if err := writeFirstPayload(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to write first payload")
|
||||
writer.hasError = true
|
||||
return
|
||||
}
|
||||
|
||||
if err := buf.Copy(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to fetch all input")
|
||||
writer.hasError = true
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ClientWorker) IsClosing() bool {
|
||||
sm := m.sessionManager
|
||||
if m.strategy.MaxConnection > 0 && sm.Count() >= int(m.strategy.MaxConnection) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsFull returns true if this ClientWorker is unable to accept more connections.
|
||||
// it might be because it is closing, or the number of connections has reached the limit.
|
||||
func (m *ClientWorker) IsFull() bool {
|
||||
if m.IsClosing() || m.Closed() {
|
||||
return true
|
||||
}
|
||||
|
||||
sm := m.sessionManager
|
||||
if m.strategy.MaxConcurrency > 0 && sm.Size() >= int(m.strategy.MaxConcurrency) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *ClientWorker) Dispatch(ctx context.Context, link *transport.Link) bool {
|
||||
if m.IsFull() {
|
||||
return false
|
||||
}
|
||||
|
||||
sm := m.sessionManager
|
||||
s := sm.Allocate(&m.strategy, link.Reader, link.Writer)
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
go fetchInput(ctx, s, m.link.Writer)
|
||||
if _, ok := link.Reader.(*pipe.Reader); !ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-s.done.Wait():
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatueKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusNew(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
s, found := m.sessionManager.Get(meta.SessionID)
|
||||
if !found {
|
||||
// Notify remote peer to close this session.
|
||||
closingWriter := NewResponseWriter(meta.SessionID, m.link.Writer, protocol.TransferTypeStream)
|
||||
closingWriter.Close()
|
||||
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err := buf.Copy(rr, s.output)
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to write to downstream. closing session ", s.ID)
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *ClientWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if s, found := m.sessionManager.Get(meta.SessionID); found {
|
||||
s.Close(false)
|
||||
}
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ClientWorker) fetchOutput() {
|
||||
defer func() {
|
||||
common.Must(m.done.Close())
|
||||
}()
|
||||
|
||||
reader := &buf.BufferedReader{Reader: m.link.Reader}
|
||||
|
||||
var meta FrameMetadata
|
||||
for {
|
||||
err := meta.Unmarshal(reader, false)
|
||||
if err != nil {
|
||||
if errors.Cause(err) != io.EOF {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to read metadata")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusKeepAlive:
|
||||
err = m.handleStatueKeepAlive(&meta, reader)
|
||||
case SessionStatusEnd:
|
||||
err = m.handleStatusEnd(&meta, reader)
|
||||
case SessionStatusNew:
|
||||
err = m.handleStatusNew(&meta, reader)
|
||||
case SessionStatusKeep:
|
||||
err = m.handleStatusKeep(&meta, reader)
|
||||
default:
|
||||
status := meta.SessionStatus
|
||||
errors.LogError(context.Background(), "unknown status: ", status)
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to process data")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/testing/mocks"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestIncrementalPickerFailure(t *testing.T) {
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
mockWorkerFactory := mocks.NewMuxClientWorkerFactory(mockCtl)
|
||||
mockWorkerFactory.EXPECT().Create().Return(nil, errors.New("test"))
|
||||
|
||||
picker := mux.IncrementalWorkerPicker{
|
||||
Factory: mockWorkerFactory,
|
||||
}
|
||||
|
||||
_, err := picker.PickAvailable()
|
||||
if err == nil {
|
||||
t.Error("expected error, but nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerEOF(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
common.Must(writer.Close())
|
||||
|
||||
worker, err := mux.NewClientWorker(transport.Link{Reader: reader, Writer: writer}, mux.ClientStrategy{})
|
||||
common.Must(err)
|
||||
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
|
||||
f := worker.Dispatch(context.Background(), nil)
|
||||
if f {
|
||||
t.Error("expected failed dispatching, but actually not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerClose(t *testing.T) {
|
||||
mockCtl := gomock.NewController(t)
|
||||
defer mockCtl.Finish()
|
||||
|
||||
r1, w1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker1, err := mux.NewClientWorker(transport.Link{
|
||||
Reader: r1,
|
||||
Writer: w1,
|
||||
}, mux.ClientStrategy{
|
||||
MaxConcurrency: 4,
|
||||
MaxConnection: 4,
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
r2, w2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker2, err := mux.NewClientWorker(transport.Link{
|
||||
Reader: r2,
|
||||
Writer: w2,
|
||||
}, mux.ClientStrategy{
|
||||
MaxConcurrency: 4,
|
||||
MaxConnection: 4,
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
factory := mocks.NewMuxClientWorkerFactory(mockCtl)
|
||||
gomock.InOrder(
|
||||
factory.EXPECT().Create().Return(worker1, nil),
|
||||
factory.EXPECT().Create().Return(worker2, nil),
|
||||
)
|
||||
|
||||
picker := &mux.IncrementalWorkerPicker{
|
||||
Factory: factory,
|
||||
}
|
||||
manager := &mux.ClientManager{
|
||||
Picker: picker,
|
||||
}
|
||||
|
||||
tr1, tw1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx1 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
common.Must(manager.Dispatch(ctx1, &transport.Link{
|
||||
Reader: tr1,
|
||||
Writer: tw1,
|
||||
}))
|
||||
defer tw1.Close()
|
||||
|
||||
common.Must(w1.Close())
|
||||
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
if !worker1.Closed() {
|
||||
t.Error("worker1 is not finished")
|
||||
}
|
||||
|
||||
tr2, tw2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx2 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
common.Must(manager.Dispatch(ctx2, &transport.Link{
|
||||
Reader: tr2,
|
||||
Writer: tw2,
|
||||
}))
|
||||
defer tw2.Close()
|
||||
|
||||
common.Must(w2.Close())
|
||||
}
|
||||
|
||||
func TestClientWorkerUDPSource(t *testing.T) {
|
||||
downR, downW := pipe.New(pipe.WithoutSizeLimit())
|
||||
upR, upW := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker, err := mux.NewClientWorker(transport.Link{Reader: downR, Writer: upW}, mux.ClientStrategy{})
|
||||
common.Must(err)
|
||||
|
||||
inR, inW := pipe.New(pipe.WithoutSizeLimit())
|
||||
outR, outW := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.ParseAddress("8.8.8.8"), 53),
|
||||
}})
|
||||
if !worker.Dispatch(ctx, &transport.Link{Reader: inR, Writer: outW}) {
|
||||
t.Fatal("failed to dispatch")
|
||||
}
|
||||
b := buf.New()
|
||||
b.WriteString("query")
|
||||
common.Must(inW.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
mb, err := upR.ReadMultiBuffer() // New frame, the session is UDP from now on
|
||||
common.Must(err)
|
||||
buf.ReleaseMulti(mb)
|
||||
|
||||
srcs := []net.Destination{
|
||||
net.UDPDestination(net.ParseAddress("1.1.1.1"), 1111),
|
||||
net.UDPDestination(net.DomainAddress("example.com"), 2222),
|
||||
net.UDPDestination(net.ParseAddress("3.3.3.3"), 3333),
|
||||
}
|
||||
w := mux.NewResponseWriter(1, downW, protocol.TransferTypePacket)
|
||||
var got buf.MultiBuffer
|
||||
for i := range srcs {
|
||||
b := buf.New()
|
||||
b.WriteString("reply")
|
||||
b.UDP = &srcs[i]
|
||||
common.Must(w.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
// keep earlier replies around while the next frame is parsed
|
||||
mb, err := outR.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
got = append(got, mb...)
|
||||
}
|
||||
for i, b := range got {
|
||||
if b.UDP == nil || *b.UDP != srcs[i] {
|
||||
t.Errorf("reply %d: source = %v, want %v", i, b.UDP, srcs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/mux"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
func BenchmarkFrameWrite(b *testing.B) {
|
||||
frame := mux.FrameMetadata{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), net.Port(80)),
|
||||
SessionID: 1,
|
||||
SessionStatus: mux.SessionStatusNew,
|
||||
}
|
||||
writer := buf.New()
|
||||
defer writer.Release()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
common.Must(frame.WriteTo(writer))
|
||||
writer.Clear()
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
package mux
|
||||
@@ -1,60 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/crypto"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
)
|
||||
|
||||
// PacketReader is an io.Reader that reads whole chunk of Mux frames every time.
|
||||
type PacketReader struct {
|
||||
reader io.Reader
|
||||
eof bool
|
||||
dest net.Destination
|
||||
}
|
||||
|
||||
// NewPacketReader creates a new PacketReader.
|
||||
// dest is copied because the caller reuses it for the next frame.
|
||||
func NewPacketReader(reader io.Reader, dest *net.Destination) *PacketReader {
|
||||
return &PacketReader{
|
||||
reader: reader,
|
||||
eof: false,
|
||||
dest: *dest,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadMultiBuffer implements buf.Reader.
|
||||
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
if r.eof {
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
size, err := serial.ReadUint16(r.reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if size > buf.Size {
|
||||
return nil, errors.New("packet size too large: ", size)
|
||||
}
|
||||
|
||||
b := buf.New()
|
||||
if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil {
|
||||
b.Release()
|
||||
return nil, err
|
||||
}
|
||||
r.eof = true
|
||||
if r.dest.Network == net.Network_UDP {
|
||||
b.UDP = &r.dest // only one packet is read, so b owns r.dest
|
||||
}
|
||||
return buf.MultiBuffer{b}, nil
|
||||
}
|
||||
|
||||
// NewStreamReader creates a new StreamReader.
|
||||
func NewStreamReader(reader *buf.BufferedReader) buf.Reader {
|
||||
return crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, reader, 1)
|
||||
}
|
||||
@@ -1,384 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
dispatcher routing.Dispatcher
|
||||
}
|
||||
|
||||
// NewServer creates a new mux.Server.
|
||||
func NewServer(ctx context.Context) *Server {
|
||||
s := &Server{}
|
||||
core.RequireFeatures(ctx, func(d routing.Dispatcher) {
|
||||
s.dispatcher = d
|
||||
})
|
||||
return s
|
||||
}
|
||||
|
||||
// Type implements common.HasType.
|
||||
func (s *Server) Type() interface{} {
|
||||
return s.dispatcher.Type()
|
||||
}
|
||||
|
||||
// Dispatch implements routing.Dispatcher
|
||||
func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
|
||||
if dest.Address != muxCoolAddress {
|
||||
return s.dispatcher.Dispatch(ctx, dest)
|
||||
}
|
||||
|
||||
opts := pipe.OptionsFromContext(ctx)
|
||||
uplinkReader, uplinkWriter := pipe.New(opts...)
|
||||
downlinkReader, downlinkWriter := pipe.New(opts...)
|
||||
|
||||
_, err := NewServerWorker(ctx, s.dispatcher, &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &transport.Link{Reader: downlinkReader, Writer: uplinkWriter}, nil
|
||||
}
|
||||
|
||||
// DispatchLink implements routing.Dispatcher
|
||||
func (s *Server) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
if dest.Address != muxCoolAddress {
|
||||
return s.dispatcher.DispatchLink(ctx, dest, link)
|
||||
}
|
||||
worker, err := NewServerWorker(ctx, s.dispatcher, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-worker.done.Wait():
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start implements common.Runnable.
|
||||
func (s *Server) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (s *Server) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type ServerWorker struct {
|
||||
dispatcher routing.Dispatcher
|
||||
link *transport.Link
|
||||
sessionManager *SessionManager
|
||||
done *done.Instance
|
||||
timer *time.Ticker
|
||||
}
|
||||
|
||||
func NewServerWorker(ctx context.Context, d routing.Dispatcher, link *transport.Link) (*ServerWorker, error) {
|
||||
worker := &ServerWorker{
|
||||
dispatcher: d,
|
||||
link: link,
|
||||
sessionManager: NewSessionManager(),
|
||||
done: done.New(),
|
||||
timer: time.NewTicker(60 * time.Second),
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||
inbound.CanSpliceCopy = 3
|
||||
}
|
||||
go worker.run(ctx)
|
||||
go worker.monitor()
|
||||
return worker, nil
|
||||
}
|
||||
|
||||
func handle(ctx context.Context, s *Session, output buf.Writer) {
|
||||
writer := NewResponseWriter(s.ID, output, s.transferType)
|
||||
if err := buf.Copy(s.input, writer); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "session ", s.ID, " ends.")
|
||||
writer.hasError = true
|
||||
}
|
||||
|
||||
writer.Close()
|
||||
s.Close(false)
|
||||
}
|
||||
|
||||
func (w *ServerWorker) monitor() {
|
||||
defer w.timer.Stop()
|
||||
|
||||
for {
|
||||
checkSize := w.sessionManager.Size()
|
||||
checkCount := w.sessionManager.Count()
|
||||
select {
|
||||
case <-w.done.Wait():
|
||||
w.sessionManager.Close()
|
||||
common.Interrupt(w.link.Writer)
|
||||
common.Interrupt(w.link.Reader)
|
||||
return
|
||||
case <-w.timer.C:
|
||||
if w.sessionManager.CloseIfNoSessionAndIdle(checkSize, checkCount) {
|
||||
common.Must(w.done.Close())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ServerWorker) ActiveConnections() uint32 {
|
||||
return uint32(w.sessionManager.Size())
|
||||
}
|
||||
|
||||
func (w *ServerWorker) Closed() bool {
|
||||
return w.done.Done()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) WaitClosed() <-chan struct{} {
|
||||
return w.done.Wait()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) Close() error {
|
||||
return w.done.Close()
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
ctx = session.SubContextFromMuxInbound(ctx)
|
||||
if meta.Inbound != nil && meta.Inbound.Source.IsValid() && meta.Inbound.Local.IsValid() {
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||
newInbound := *inbound
|
||||
newInbound.Source = meta.Inbound.Source
|
||||
newInbound.Local = meta.Inbound.Local
|
||||
ctx = session.ContextWithInbound(ctx, &newInbound)
|
||||
}
|
||||
}
|
||||
errors.LogInfo(ctx, "received request for ", meta.Target)
|
||||
{
|
||||
msg := &log.AccessMessage{
|
||||
To: meta.Target,
|
||||
Status: log.AccessAccepted,
|
||||
Reason: "",
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
|
||||
msg.From = inbound.Source
|
||||
msg.Email = inbound.User.Email
|
||||
}
|
||||
ctx = log.ContextWithAccessMessage(ctx, msg)
|
||||
}
|
||||
|
||||
if network := session.AllowedNetworkFromContext(ctx); network != net.Network_Unknown {
|
||||
if meta.Target.Network != network {
|
||||
return errors.New("unexpected network ", meta.Target.Network) // it will break the whole Mux connection
|
||||
}
|
||||
}
|
||||
|
||||
if meta.GlobalID != [8]byte{} { // MUST ignore empty Global ID
|
||||
mb, err := NewPacketReader(reader, &meta.Target).ReadMultiBuffer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
XUDPManager.Lock()
|
||||
x := XUDPManager.Map[meta.GlobalID]
|
||||
if x == nil {
|
||||
x = &XUDP{GlobalID: meta.GlobalID}
|
||||
XUDPManager.Map[meta.GlobalID] = x
|
||||
XUDPManager.Unlock()
|
||||
} else {
|
||||
if x.Status == Initializing { // nearly impossible
|
||||
XUDPManager.Unlock()
|
||||
errors.LogWarningInner(ctx, errors.New("conflict"), "XUDP hit ", meta.GlobalID)
|
||||
// It's not a good idea to return an err here, so just let client wait.
|
||||
// Client will receive an End frame after sending a Keep frame.
|
||||
return nil
|
||||
}
|
||||
x.Status = Initializing
|
||||
XUDPManager.Unlock()
|
||||
x.Mux.Close(false) // detach from previous Mux
|
||||
b := buf.New()
|
||||
b.Write(mb[0].Bytes())
|
||||
b.UDP = mb[0].UDP
|
||||
if err = x.Mux.output.WriteMultiBuffer(mb); err != nil {
|
||||
x.Interrupt()
|
||||
mb = buf.MultiBuffer{b}
|
||||
} else {
|
||||
b.Release()
|
||||
mb = nil
|
||||
}
|
||||
errors.LogInfoInner(ctx, err, "XUDP hit ", meta.GlobalID)
|
||||
}
|
||||
if mb != nil {
|
||||
ctx = session.ContextWithTimeoutOnly(ctx, true)
|
||||
// Actually, it won't return an error in Xray-core's implementations.
|
||||
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
|
||||
if err != nil {
|
||||
XUDPManager.Lock()
|
||||
delete(XUDPManager.Map, x.GlobalID)
|
||||
XUDPManager.Unlock()
|
||||
err = errors.New("XUDP new ", meta.GlobalID).Base(errors.New("failed to dispatch request to ", meta.Target).Base(err))
|
||||
return err // it will break the whole Mux connection
|
||||
}
|
||||
link.Writer.WriteMultiBuffer(mb) // it's meaningless to test a new pipe
|
||||
x.Mux = &Session{
|
||||
input: link.Reader,
|
||||
output: link.Writer,
|
||||
}
|
||||
errors.LogInfoInner(ctx, err, "XUDP new ", meta.GlobalID)
|
||||
}
|
||||
x.Mux = &Session{
|
||||
input: x.Mux.input,
|
||||
output: x.Mux.output,
|
||||
parent: w.sessionManager,
|
||||
ID: meta.SessionID,
|
||||
transferType: protocol.TransferTypePacket,
|
||||
XUDP: x,
|
||||
}
|
||||
x.Status = Active
|
||||
if !w.sessionManager.Add(x.Mux) {
|
||||
x.Mux.Close(false)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
go handle(ctx, x.Mux, w.link.Writer)
|
||||
return nil
|
||||
}
|
||||
|
||||
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
|
||||
if err != nil {
|
||||
if meta.Option.Has(OptionData) {
|
||||
buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return errors.New("failed to dispatch request.").Base(err)
|
||||
}
|
||||
s := &Session{
|
||||
input: link.Reader,
|
||||
output: link.Writer,
|
||||
parent: w.sessionManager,
|
||||
ID: meta.SessionID,
|
||||
transferType: protocol.TransferTypeStream,
|
||||
}
|
||||
if meta.Target.Network == net.Network_UDP {
|
||||
s.transferType = protocol.TransferTypePacket
|
||||
}
|
||||
if !w.sessionManager.Add(s) {
|
||||
s.Close(false)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
go handle(ctx, s, w.link.Writer)
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err = buf.Copy(rr, s.output)
|
||||
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
s, found := w.sessionManager.Get(meta.SessionID)
|
||||
if !found {
|
||||
// Notify remote peer to close this session.
|
||||
closingWriter := NewResponseWriter(meta.SessionID, w.link.Writer, protocol.TransferTypeStream)
|
||||
closingWriter.Close()
|
||||
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
|
||||
rr := s.NewReader(reader, &meta.Target)
|
||||
err := buf.Copy(rr, s.output)
|
||||
|
||||
if err != nil && buf.IsWriteError(err) {
|
||||
errors.LogInfoInner(context.Background(), err, "failed to write to downstream writer. closing session ", s.ID)
|
||||
s.Close(false)
|
||||
return buf.Copy(rr, buf.Discard)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
if s, found := w.sessionManager.Get(meta.SessionID); found {
|
||||
s.Close(false)
|
||||
}
|
||||
if meta.Option.Has(OptionData) {
|
||||
return buf.Copy(NewStreamReader(reader), buf.Discard)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleFrame(ctx context.Context, reader *buf.BufferedReader) error {
|
||||
var meta FrameMetadata
|
||||
err := meta.Unmarshal(reader, session.IsReverseMuxFromContext(ctx))
|
||||
if err != nil {
|
||||
return errors.New("failed to read metadata").Base(err)
|
||||
}
|
||||
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusKeepAlive:
|
||||
err = w.handleStatusKeepAlive(&meta, reader)
|
||||
case SessionStatusEnd:
|
||||
err = w.handleStatusEnd(&meta, reader)
|
||||
case SessionStatusNew:
|
||||
err = w.handleStatusNew(session.ContextWithIsReverseMux(ctx, false), &meta, reader)
|
||||
case SessionStatusKeep:
|
||||
err = w.handleStatusKeep(&meta, reader)
|
||||
default:
|
||||
status := meta.SessionStatus
|
||||
return errors.New("unknown status: ", status)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.New("failed to process data").Base(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ServerWorker) run(ctx context.Context) {
|
||||
defer func() {
|
||||
common.Must(w.done.Close())
|
||||
}()
|
||||
|
||||
reader := &buf.BufferedReader{Reader: w.link.Reader}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
err := w.handleFrame(ctx, reader)
|
||||
if err != nil {
|
||||
if errors.Cause(err) != io.EOF {
|
||||
errors.LogInfoInner(ctx, err, "unexpected EOF")
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
type SessionManager struct {
|
||||
sync.RWMutex
|
||||
sessions map[uint16]*Session
|
||||
count uint16
|
||||
closed bool
|
||||
}
|
||||
|
||||
func NewSessionManager() *SessionManager {
|
||||
return &SessionManager{
|
||||
count: 0,
|
||||
sessions: make(map[uint16]*Session, 16),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *SessionManager) Closed() bool {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return m.closed
|
||||
}
|
||||
|
||||
func (m *SessionManager) Size() int {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return len(m.sessions)
|
||||
}
|
||||
|
||||
func (m *SessionManager) Count() int {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
return int(m.count)
|
||||
}
|
||||
|
||||
func (m *SessionManager) Allocate(Strategy *ClientStrategy, input buf.Reader, output buf.Writer) *Session {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
MaxConcurrency := int(Strategy.MaxConcurrency)
|
||||
MaxConnection := uint16(Strategy.MaxConnection)
|
||||
|
||||
if m.closed || (MaxConcurrency > 0 && len(m.sessions) >= MaxConcurrency) || (MaxConnection > 0 && m.count >= MaxConnection) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.count++
|
||||
s := &Session{
|
||||
input: input,
|
||||
output: output,
|
||||
ID: m.count,
|
||||
parent: m,
|
||||
done: done.New(),
|
||||
}
|
||||
m.sessions[s.ID] = s
|
||||
return s
|
||||
}
|
||||
|
||||
func (m *SessionManager) Add(s *Session) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return false
|
||||
}
|
||||
|
||||
m.count++
|
||||
m.sessions[s.ID] = s
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *SessionManager) Remove(locked bool, id uint16) {
|
||||
if !locked {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
}
|
||||
locked = true
|
||||
|
||||
if m.closed {
|
||||
return
|
||||
}
|
||||
|
||||
delete(m.sessions, id)
|
||||
|
||||
/*
|
||||
if len(m.sessions) == 0 {
|
||||
m.sessions = make(map[uint16]*Session, 16)
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
func (m *SessionManager) Get(id uint16) (*Session, bool) {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
if m.closed {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
s, found := m.sessions[id]
|
||||
return s, found
|
||||
}
|
||||
|
||||
func (m *SessionManager) CloseIfNoSessionAndIdle(checkSize int, checkCount int) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return true
|
||||
}
|
||||
|
||||
if len(m.sessions) != 0 || checkSize != 0 || checkCount != int(m.count) {
|
||||
return false
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
m.sessions = nil
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *SessionManager) Close() error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
for _, s := range m.sessions {
|
||||
s.Close(true)
|
||||
}
|
||||
|
||||
m.sessions = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// Session represents a client connection in a Mux connection.
|
||||
type Session struct {
|
||||
input buf.Reader
|
||||
output buf.Writer
|
||||
parent *SessionManager
|
||||
ID uint16
|
||||
transferType protocol.TransferType
|
||||
closed bool
|
||||
done *done.Instance
|
||||
XUDP *XUDP
|
||||
}
|
||||
|
||||
// Close closes all resources associated with this session.
|
||||
func (s *Session) Close(locked bool) error {
|
||||
if !locked {
|
||||
s.parent.Lock()
|
||||
defer s.parent.Unlock()
|
||||
}
|
||||
locked = true
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
s.closed = true
|
||||
if s.done != nil {
|
||||
s.done.Close()
|
||||
}
|
||||
if s.XUDP == nil {
|
||||
common.Interrupt(s.input)
|
||||
common.Close(s.output)
|
||||
} else {
|
||||
// Stop existing handle(), then trigger writer.Close().
|
||||
// Note that s.output may be dispatcher.SizeStatWriter.
|
||||
s.input.(*pipe.Reader).ReturnAnError(io.EOF)
|
||||
runtime.Gosched()
|
||||
// If the error set by ReturnAnError still exists, clear it.
|
||||
s.input.(*pipe.Reader).Recover()
|
||||
XUDPManager.Lock()
|
||||
if s.XUDP.Status == Active {
|
||||
s.XUDP.Expire = time.Now().Add(time.Minute)
|
||||
s.XUDP.Status = Expiring
|
||||
errors.LogDebug(context.Background(), "XUDP put ", s.XUDP.GlobalID)
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
s.parent.Remove(locked, s.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewReader creates a buf.Reader based on the transfer type of this Session.
|
||||
func (s *Session) NewReader(reader *buf.BufferedReader, dest *net.Destination) buf.Reader {
|
||||
if s.transferType == protocol.TransferTypeStream {
|
||||
return NewStreamReader(reader)
|
||||
}
|
||||
return NewPacketReader(reader, dest)
|
||||
}
|
||||
|
||||
const (
|
||||
Initializing = 0
|
||||
Active = 1
|
||||
Expiring = 2
|
||||
)
|
||||
|
||||
type XUDP struct {
|
||||
GlobalID [8]byte
|
||||
Status uint64
|
||||
Expire time.Time
|
||||
Mux *Session
|
||||
}
|
||||
|
||||
func (x *XUDP) Interrupt() {
|
||||
common.Interrupt(x.Mux.input)
|
||||
common.Close(x.Mux.output)
|
||||
}
|
||||
|
||||
var XUDPManager struct {
|
||||
sync.Mutex
|
||||
Map map[[8]byte]*XUDP
|
||||
}
|
||||
|
||||
func init() {
|
||||
XUDPManager.Map = make(map[[8]byte]*XUDP)
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(time.Minute)
|
||||
now := time.Now()
|
||||
XUDPManager.Lock()
|
||||
for id, x := range XUDPManager.Map {
|
||||
if x.Status == Expiring && now.After(x.Expire) {
|
||||
x.Interrupt()
|
||||
delete(XUDPManager.Map, id)
|
||||
errors.LogDebug(context.Background(), "XUDP del ", id)
|
||||
}
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/xtls/xray-core/common/mux"
|
||||
)
|
||||
|
||||
func TestSessionManagerAdd(t *testing.T) {
|
||||
m := NewSessionManager()
|
||||
|
||||
s := m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
if s.ID != 1 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 1 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
|
||||
s = m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
if s.ID != 2 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 2 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
|
||||
s = &Session{
|
||||
ID: 4,
|
||||
}
|
||||
m.Add(s)
|
||||
if s.ID != 4 {
|
||||
t.Error("id: ", s.ID)
|
||||
}
|
||||
if m.Size() != 3 {
|
||||
t.Error("size: ", m.Size())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionManagerClose(t *testing.T) {
|
||||
m := NewSessionManager()
|
||||
s := m.Allocate(&ClientStrategy{}, nil, nil)
|
||||
|
||||
if m.CloseIfNoSessionAndIdle(m.Size(), m.Count()) {
|
||||
t.Error("able to close")
|
||||
}
|
||||
m.Remove(false, s.ID)
|
||||
if !m.CloseIfNoSessionAndIdle(m.Size(), m.Count()) {
|
||||
t.Error("not able to close")
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
)
|
||||
|
||||
type Writer struct {
|
||||
dest net.Destination
|
||||
writer buf.Writer
|
||||
id uint16
|
||||
followup bool
|
||||
hasError bool
|
||||
transferType protocol.TransferType
|
||||
globalID [8]byte
|
||||
inbound *session.Inbound
|
||||
}
|
||||
|
||||
func NewWriter(id uint16, dest net.Destination, writer buf.Writer, transferType protocol.TransferType, globalID [8]byte, inbound *session.Inbound) *Writer {
|
||||
return &Writer{
|
||||
id: id,
|
||||
dest: dest,
|
||||
writer: writer,
|
||||
followup: false,
|
||||
transferType: transferType,
|
||||
globalID: globalID,
|
||||
inbound: inbound,
|
||||
}
|
||||
}
|
||||
|
||||
func NewResponseWriter(id uint16, writer buf.Writer, transferType protocol.TransferType) *Writer {
|
||||
return &Writer{
|
||||
id: id,
|
||||
writer: writer,
|
||||
followup: true,
|
||||
transferType: transferType,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Writer) getNextFrameMeta() FrameMetadata {
|
||||
meta := FrameMetadata{
|
||||
SessionID: w.id,
|
||||
Target: w.dest,
|
||||
GlobalID: w.globalID,
|
||||
Inbound: w.inbound,
|
||||
}
|
||||
|
||||
if w.followup {
|
||||
meta.SessionStatus = SessionStatusKeep
|
||||
} else {
|
||||
w.followup = true
|
||||
meta.SessionStatus = SessionStatusNew
|
||||
}
|
||||
|
||||
return meta
|
||||
}
|
||||
|
||||
func (w *Writer) writeMetaOnly() error {
|
||||
meta := w.getNextFrameMeta()
|
||||
b := buf.New()
|
||||
if err := meta.WriteTo(b); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.writer.WriteMultiBuffer(buf.MultiBuffer{b})
|
||||
}
|
||||
|
||||
func writeMetaWithFrame(writer buf.Writer, meta FrameMetadata, data buf.MultiBuffer) error {
|
||||
frame := buf.New()
|
||||
if len(data) == 1 {
|
||||
frame.UDP = data[0].UDP
|
||||
}
|
||||
if err := meta.WriteTo(frame); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := serial.WriteUint16(frame, uint16(data.Len())); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mb2 := make(buf.MultiBuffer, 0, len(data)+1)
|
||||
mb2 = append(mb2, frame)
|
||||
mb2 = append(mb2, data...)
|
||||
return writer.WriteMultiBuffer(mb2)
|
||||
}
|
||||
|
||||
func (w *Writer) writeData(mb buf.MultiBuffer) error {
|
||||
meta := w.getNextFrameMeta()
|
||||
meta.Option.Set(OptionData)
|
||||
|
||||
return writeMetaWithFrame(w.writer, meta, mb)
|
||||
}
|
||||
|
||||
// WriteMultiBuffer implements buf.Writer.
|
||||
func (w *Writer) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
defer buf.ReleaseMulti(mb)
|
||||
|
||||
if mb.IsEmpty() {
|
||||
return w.writeMetaOnly()
|
||||
}
|
||||
|
||||
for !mb.IsEmpty() {
|
||||
var chunk buf.MultiBuffer
|
||||
if w.transferType == protocol.TransferTypeStream {
|
||||
mb, chunk = buf.SplitSize(mb, 8*1024)
|
||||
} else {
|
||||
mb2, b := buf.SplitFirst(mb)
|
||||
mb = mb2
|
||||
chunk = buf.MultiBuffer{b}
|
||||
}
|
||||
if err := w.writeData(chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
func (w *Writer) Close() error {
|
||||
meta := FrameMetadata{
|
||||
SessionID: w.id,
|
||||
SessionStatus: SessionStatusEnd,
|
||||
}
|
||||
if w.hasError {
|
||||
meta.Option.Set(OptionError)
|
||||
}
|
||||
|
||||
frame := buf.New()
|
||||
common.Must(meta.WriteTo(frame))
|
||||
|
||||
w.writer.WriteMultiBuffer(buf.MultiBuffer{frame})
|
||||
return nil
|
||||
}
|
||||
@@ -3,13 +3,17 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/vishvananda/netlink/nl"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
@@ -26,46 +30,20 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
||||
panic("Unsupported network type for process lookup.")
|
||||
}
|
||||
|
||||
var procFiles []string
|
||||
|
||||
switch network {
|
||||
case "tcp":
|
||||
if net.ParseIP(srcIP).To4() != nil {
|
||||
procFiles = []string{"/proc/net/tcp"}
|
||||
} else {
|
||||
procFiles = []string{"/proc/net/tcp6"}
|
||||
}
|
||||
case "udp":
|
||||
if net.ParseIP(srcIP).To4() != nil {
|
||||
procFiles = []string{"/proc/net/udp", "/proc/net/udp6"}
|
||||
} else {
|
||||
procFiles = []string{"/proc/net/udp6", "/proc/net/udp"}
|
||||
}
|
||||
default:
|
||||
panic("Unsupported network type for process lookup.")
|
||||
}
|
||||
|
||||
targetHexAddr := formatProcNetAddress(net.ParseIP(srcIP), Port(srcPort))
|
||||
|
||||
portFallback := ""
|
||||
if network == "udp" {
|
||||
portFallback = fmt.Sprintf(":%04X", srcPort)
|
||||
}
|
||||
|
||||
inode, err := findInodeInFiles(procFiles, targetHexAddr, portFallback)
|
||||
socket, err := findSocketInode(network, net.ParseIP(srcIP), srcPort)
|
||||
if err != nil {
|
||||
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
|
||||
return 0, "", "", errors.New("could not query sockets using netlink").Base(err)
|
||||
}
|
||||
if inode == "" {
|
||||
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found in ", strings.Join(procFiles, " or "))
|
||||
if socket == nil {
|
||||
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found")
|
||||
}
|
||||
|
||||
pidStr, err := findPidByInode(inode)
|
||||
pidStr, err := findPidByInode(socket.inode, socket.uid)
|
||||
if err != nil {
|
||||
return 0, "", "", errors.New("could not find PID for inode ", inode, ": ", err)
|
||||
return 0, "", "", errors.New("could not find PID for inode ", socket.inode, ": ", err)
|
||||
}
|
||||
if pidStr == "" {
|
||||
return 0, "", "", errors.New("no process found for inode ", inode)
|
||||
return 0, "", "", errors.New("no process found for inode ", socket.inode)
|
||||
}
|
||||
|
||||
absPath, err := getAbsPath(pidStr)
|
||||
@@ -84,63 +62,93 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
||||
return pid, procName, absPath, nil
|
||||
}
|
||||
|
||||
func formatProcNetAddress(addr net.IP, port Port) string {
|
||||
var ipBytes []byte
|
||||
if ipv4 := addr.To4(); ipv4 != nil {
|
||||
ipBytes = ipv4
|
||||
} else {
|
||||
ipBytes = addr.To16()
|
||||
}
|
||||
|
||||
var formatted strings.Builder
|
||||
formatted.Grow(len(ipBytes)*2 + 5)
|
||||
for i := 0; i < len(ipBytes); i += 4 {
|
||||
fmt.Fprintf(&formatted, "%08X", binary.NativeEndian.Uint32(ipBytes[i:i+4]))
|
||||
}
|
||||
fmt.Fprintf(&formatted, ":%04X", uint16(port))
|
||||
return formatted.String()
|
||||
type processSocket struct {
|
||||
inode string
|
||||
uid uint32
|
||||
}
|
||||
|
||||
func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (string, error) {
|
||||
onlyMatchedPort := ""
|
||||
// Layouts are defined by Linux's inet_diag_req_v2 and inet_diag_msg.
|
||||
const (
|
||||
inetDiagRequestSize = 56
|
||||
inetDiagResponseSize = 72
|
||||
tcpBoundInactive = 13
|
||||
)
|
||||
|
||||
for i, filePath := range filePaths {
|
||||
file, err := os.Open(filePath)
|
||||
func findSocketInode(network string, ip net.IP, port uint16) (*processSocket, error) {
|
||||
families := []uint8{unix.AF_INET6}
|
||||
if ip.To4() != nil {
|
||||
families = []uint8{unix.AF_INET, unix.AF_INET6}
|
||||
} else if network == "udp" {
|
||||
families = append(families, unix.AF_INET)
|
||||
}
|
||||
|
||||
protocol := byte(unix.IPPROTO_UDP)
|
||||
if network == "tcp" {
|
||||
protocol = unix.IPPROTO_TCP
|
||||
}
|
||||
|
||||
var wildcard *processSocket
|
||||
for _, family := range families {
|
||||
request := make([]byte, inetDiagRequestSize)
|
||||
request[0], request[1] = family, protocol
|
||||
states := ^uint32(0)
|
||||
if network == "tcp" {
|
||||
states &^= 1 << tcpBoundInactive
|
||||
}
|
||||
binary.NativeEndian.PutUint32(request[4:8], states)
|
||||
binary.BigEndian.PutUint16(request[8:10], port)
|
||||
if family == unix.AF_INET {
|
||||
copy(request[12:28], ip.To4())
|
||||
} else {
|
||||
copy(request[12:28], ip.To16())
|
||||
}
|
||||
binary.NativeEndian.PutUint32(request[48:52], ^uint32(0))
|
||||
binary.NativeEndian.PutUint32(request[52:56], ^uint32(0))
|
||||
|
||||
req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, unix.NLM_F_DUMP)
|
||||
req.AddRawData(request)
|
||||
var exact *processSocket
|
||||
var parseErr error
|
||||
err := req.ExecuteIter(unix.NETLINK_INET_DIAG, nl.SOCK_DIAG_BY_FAMILY, func(msg []byte) bool {
|
||||
if len(msg) < inetDiagResponseSize {
|
||||
parseErr = fmt.Errorf("short inet_diag response: %d bytes", len(msg))
|
||||
return false
|
||||
}
|
||||
if msg[0] != family || binary.BigEndian.Uint16(msg[4:6]) != port {
|
||||
return true
|
||||
}
|
||||
source := net.IP(msg[8:24])
|
||||
if family == unix.AF_INET {
|
||||
source = source[:4]
|
||||
}
|
||||
if !source.Equal(ip) && !(network == "udp" && source.IsUnspecified()) {
|
||||
return true
|
||||
}
|
||||
socket := &processSocket{
|
||||
uid: binary.NativeEndian.Uint32(msg[64:68]),
|
||||
inode: strconv.FormatUint(uint64(binary.NativeEndian.Uint32(msg[68:72])), 10),
|
||||
}
|
||||
if source.Equal(ip) {
|
||||
exact = socket
|
||||
return false
|
||||
}
|
||||
wildcard = socket
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
if i > 0 && os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
return "", err
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
fields := strings.Fields(scanner.Text())
|
||||
if len(fields) < 10 {
|
||||
continue
|
||||
}
|
||||
|
||||
localAddress := fields[1]
|
||||
if localAddress == targetHexAddr {
|
||||
return fields[9], nil
|
||||
}
|
||||
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
|
||||
wildcardIP := strings.TrimSuffix(localAddress, portFallback)
|
||||
if (len(wildcardIP) == 8 || len(wildcardIP) == 32) && strings.Trim(wildcardIP, "0") == "" {
|
||||
onlyMatchedPort = fields[9]
|
||||
}
|
||||
}
|
||||
if parseErr != nil {
|
||||
return nil, parseErr
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return "", err
|
||||
if exact != nil {
|
||||
return exact, nil
|
||||
}
|
||||
}
|
||||
|
||||
return onlyMatchedPort, nil
|
||||
return wildcard, nil
|
||||
}
|
||||
|
||||
func findPidByInode(inode string) (string, error) {
|
||||
func findPidByInode(inode string, uid uint32) (string, error) {
|
||||
procDir, err := os.ReadDir("/proc")
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -157,26 +165,44 @@ func findPidByInode(inode string) (string, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
fdPath := fmt.Sprintf("/proc/%s/fd", pid)
|
||||
fdDir, err := os.ReadDir(fdPath)
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, fdEntry := range fdDir {
|
||||
linkPath := fmt.Sprintf("%s/%s", fdPath, fdEntry.Name())
|
||||
linkTarget, err := os.Readlink(linkPath)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if linkTarget == targetLink {
|
||||
return pid, nil
|
||||
}
|
||||
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("unexpected stat data for process %s", pid)
|
||||
}
|
||||
if stat.Uid != uid {
|
||||
continue
|
||||
}
|
||||
if processHasSocket(pid, targetLink) {
|
||||
return pid, nil
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func processHasSocket(pid, targetLink string) bool {
|
||||
fdPath := filepath.Join("/proc", pid, "fd")
|
||||
fdDir, err := os.ReadDir(fdPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
buffer := make([]byte, unix.PathMax)
|
||||
for _, fdEntry := range fdDir {
|
||||
n, err := unix.Readlink(filepath.Join(fdPath, fdEntry.Name()), buffer)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if string(buffer[:n]) == targetLink {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func getAbsPath(pid string) (string, error) {
|
||||
path := fmt.Sprintf("/proc/%s/exe", pid)
|
||||
return os.Readlink(path)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//go:build linux && !android
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"errors"
|
||||
stdnet "net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFindProcessIPv4Mapped(t *testing.T) {
|
||||
listener, err := stdnet.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
peer, err := stdnet.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer peer.Close()
|
||||
|
||||
// an IPv6 socket that connects to an IPv4 address, as the sockets of Java and .NET are
|
||||
for _, c := range []struct{ local, remote stdnet.Addr }{
|
||||
{&stdnet.TCPAddr{IP: stdnet.IPv6zero}, listener.Addr()},
|
||||
{&stdnet.UDPAddr{IP: stdnet.IPv6zero}, peer.LocalAddr()},
|
||||
} {
|
||||
network := c.remote.Network()
|
||||
conn, err := (&stdnet.Dialer{LocalAddr: c.local}).Dial(network, c.remote.String())
|
||||
if errors.Is(err, syscall.EAFNOSUPPORT) {
|
||||
t.Skip("no IPv6 sockets here")
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
local := netip.MustParseAddrPort(conn.LocalAddr().String())
|
||||
remote := netip.MustParseAddrPort(c.remote.String())
|
||||
pid, _, _, err := FindProcess(network, "127.0.0.1", local.Port(), "127.0.0.1", remote.Port())
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", network, err)
|
||||
} else if pid != os.Getpid() {
|
||||
t.Errorf("%s: found PID %d, want %d", network, pid, os.Getpid())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package platform
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ const (
|
||||
UseReadV = "xray.buf.readv"
|
||||
UseFreedomSplice = "xray.buf.splice"
|
||||
UseVmessPadding = "xray.vmess.padding"
|
||||
UseCone = "xray.cone.disabled"
|
||||
UseStrictJSON = "xray.json.strict"
|
||||
|
||||
BufferSize = "xray.ray.buffer.size"
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package platform
|
||||
|
||||
|
||||
@@ -128,6 +128,7 @@ func (w *UDPWriter) WriteMessage(b *buf.Buffer) error {
|
||||
|
||||
type TCPWriter struct {
|
||||
buf.Writer
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (w *TCPWriter) WriteMessage(b *buf.Buffer) error {
|
||||
@@ -140,5 +141,7 @@ func (w *TCPWriter) WriteMessage(b *buf.Buffer) error {
|
||||
size := buf.New()
|
||||
binary.BigEndian.PutUint16(size.Extend(2), uint16(b.Len()))
|
||||
mb = append(mb, size, b)
|
||||
w.Lock()
|
||||
defer w.Unlock()
|
||||
return w.WriteMultiBuffer(mb)
|
||||
}
|
||||
|
||||
@@ -77,6 +77,11 @@ func ContentFromContext(ctx context.Context) *Content {
|
||||
return nil
|
||||
}
|
||||
|
||||
func SkipDNSResolveFromContext(ctx context.Context) bool {
|
||||
content := ContentFromContext(ctx)
|
||||
return content != nil && content.SkipDNSResolve
|
||||
}
|
||||
|
||||
func ContextWithIsReverseMux(ctx context.Context, isReverseMux bool) context.Context {
|
||||
return context.WithValue(ctx, isReverseMuxKey, isReverseMux)
|
||||
}
|
||||
|
||||
@@ -63,9 +63,6 @@ func init() {
|
||||
}
|
||||
|
||||
func GetGlobalID(ctx context.Context) (globalID [8]byte) {
|
||||
if cone := ctx.Value("cone"); cone == nil || !cone.(bool) { // cone is nil only in some unit tests
|
||||
return
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.Network == net.Network_UDP &&
|
||||
(inbound.Name == "dokodemo-door" || inbound.Name == "socks" || inbound.Name == "shadowsocks" || inbound.Name == "tun") {
|
||||
h := blake3.New(8, ensureBaseKey())
|
||||
|
||||
+2
-2
@@ -19,8 +19,8 @@ import (
|
||||
|
||||
var (
|
||||
Version_x byte = 26
|
||||
Version_y byte = 10
|
||||
Version_z byte = 31
|
||||
Version_y byte = 11
|
||||
Version_z byte = 9
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestXrayDial(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -105,7 +105,7 @@ func TestXrayDialUDPConn(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -174,7 +174,7 @@ func TestXrayDialUDP(t *testing.T) {
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{
|
||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
|
||||
}),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -2,7 +2,6 @@ package core
|
||||
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/io.go -mock_names Reader=Reader,Writer=Writer io Reader,Writer
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/log.go -mock_names Handler=LogHandler github.com/xtls/xray-core/common/log Handler
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/mux.go -mock_names ClientWorkerFactory=MuxClientWorkerFactory github.com/xtls/xray-core/common/mux ClientWorkerFactory
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/dns.go -mock_names Client=DNSClient github.com/xtls/xray-core/features/dns Client
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/outbound.go -mock_names Manager=OutboundManager,HandlerSelector=OutboundHandlerSelector github.com/xtls/xray-core/features/outbound Manager,HandlerSelector
|
||||
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination ../testing/mocks/proxy.go -mock_names Inbound=ProxyInbound,Outbound=ProxyOutbound github.com/xtls/xray-core/proxy Inbound,Outbound
|
||||
|
||||
@@ -192,8 +192,6 @@ func initInstanceWithConfig(config *Config, server *Instance) (bool, error) {
|
||||
if err := platform.ReloadEnvSettings(); err != nil {
|
||||
return true, errors.New("failed to reload environment settings").Base(err)
|
||||
}
|
||||
server.ctx = context.WithValue(server.ctx, "cone",
|
||||
platform.NewEnvFlag(platform.UseCone).GetValue(func() string { return "" }) != "true")
|
||||
|
||||
for _, appSettings := range config.App {
|
||||
settings, err := appSettings.GetInstance()
|
||||
|
||||
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
|
||||
github.com/bufbuild/protocompile v0.14.1
|
||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
|
||||
github.com/golang/mock v1.7.0-rc.1
|
||||
@@ -16,19 +16,19 @@ require (
|
||||
github.com/pelletier/go-toml v1.9.5
|
||||
github.com/pion/stun/v3 v3.1.7
|
||||
github.com/pires/go-proxyproto v0.16.0
|
||||
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af
|
||||
github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/vishvananda/netlink v1.3.1
|
||||
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8
|
||||
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b
|
||||
github.com/yuin/gopher-lua v1.1.2
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
|
||||
golang.org/x/net v0.62.0
|
||||
golang.org/x/sync v0.24.0
|
||||
golang.org/x/sys v0.49.0
|
||||
golang.org/x/net v0.63.0
|
||||
golang.org/x/sync v0.25.0
|
||||
golang.org/x/sys v0.50.0
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
|
||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb
|
||||
golang.zx2c4.com/wireguard/windows v1.1.1
|
||||
@@ -36,19 +36,19 @@ require (
|
||||
google.golang.org/protobuf v1.36.12
|
||||
h12.io/socks v1.0.3
|
||||
layeh.com/gopher-luar v1.0.11
|
||||
lukechampine.com/blake3 v1.4.1
|
||||
lukechampine.com/blake3 v1.5.1
|
||||
mvdan.cc/gofumpt v0.12.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.2.3 // indirect
|
||||
github.com/google/gopacket v1.1.19 // indirect
|
||||
github.com/huin/goupnp v1.2.0 // indirect
|
||||
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
|
||||
github.com/juju/ratelimit v1.0.2 // indirect
|
||||
github.com/klauspost/compress v1.20.0 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/koron/go-ssdp v0.0.4 // indirect
|
||||
github.com/libp2p/go-netroute v0.2.1 // indirect
|
||||
github.com/molecule-man/go-brrr v1.2.0 // indirect
|
||||
github.com/pion/dtls/v3 v3.1.5 // indirect
|
||||
github.com/pion/logging v0.2.4 // indirect
|
||||
github.com/pion/transport/v4 v4.1.0 // indirect
|
||||
@@ -56,8 +56,8 @@ require (
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
github.com/wlynxg/anet v0.0.5 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
golang.org/x/tools v0.51.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
golang.org/x/tools v0.52.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect
|
||||
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.2 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
github.com/andybalholm/brotli v1.2.3 h1:8H1qwOkl2LPfjf3YezB90JnCliZb6SInJ/OJkEbA5NQ=
|
||||
github.com/andybalholm/brotli v1.2.3/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e h1:5mgtR5gwIgBKMiGI1QdXldZZ+SNor06Nbu1wCBulQBg=
|
||||
github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e/go.mod h1:x7qxEvX6MCVtDuBKHj3E+88+BtrbEMuAL5qGUKItjW8=
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
||||
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
|
||||
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
@@ -33,8 +31,8 @@ github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7Bd
|
||||
github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
|
||||
github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
|
||||
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
|
||||
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
|
||||
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
|
||||
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
|
||||
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0=
|
||||
@@ -49,6 +47,8 @@ github.com/libp2p/go-netroute v0.2.1 h1:V8kVrpD8GK0Riv15/7VN6RbUQ3URNZVosw7H2v9t
|
||||
github.com/libp2p/go-netroute v0.2.1/go.mod h1:hraioZr0fhBjG0ZRXJJ6Zj2IVEVNx6tDTFQfSmcq7mQ=
|
||||
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
|
||||
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
|
||||
github.com/molecule-man/go-brrr v1.2.0 h1:dOJU45BC3Gc2WXoxAW0rgCAgVuu2gruAOGncfieA0Jw=
|
||||
github.com/molecule-man/go-brrr v1.2.0/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4=
|
||||
github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
|
||||
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
|
||||
github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2 h1:JhzVVoYvbOACxoUmOs6V/G4D5nPVUW73rKvXxP4XUJc=
|
||||
@@ -67,8 +67,8 @@ github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4
|
||||
github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af h1:er2acxbi3N1nvEq6HXHUAR1nTWEJmQfqiGR8EVT9rfs=
|
||||
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
|
||||
github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b h1:Mi/DuaTxHeNIQ9g1ylZicAqa6Cb9wkHRiNtQH9uZ7Ts=
|
||||
github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b/go.mod h1:rc/ctWeKlh9LSk5k90KlSPcwF7P6D31mn/9GI2NAfBI=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g=
|
||||
@@ -81,10 +81,8 @@ github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zd
|
||||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
||||
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
||||
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8 h1:RjLnVvlzK4q6zWaSBPNRGsrgx2fbJDeUWffjw574uzs=
|
||||
github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8/go.mod h1:ptlSkJ8k/7IDauNH0SA96JPOo+nYGLTv2Y3UMpwvAsY=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b h1:fAn11r21QiUY2oAGwENWb5ummjhWwMcs2WzkbjDMh+k=
|
||||
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b/go.mod h1:ptlSkJ8k/7IDauNH0SA96JPOo+nYGLTv2Y3UMpwvAsY=
|
||||
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
|
||||
github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA=
|
||||
@@ -97,8 +95,8 @@ go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBs
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a h1:V5oicZXS0oqZx30gY/apgSVD7YvNBfrIOdcMnlelJY4=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
|
||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
|
||||
@@ -109,12 +107,12 @@ golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -123,22 +121,22 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
|
||||
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
|
||||
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
|
||||
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
|
||||
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@@ -170,7 +168,7 @@ h12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo=
|
||||
h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck=
|
||||
layeh.com/gopher-luar v1.0.11 h1:8zJudpKI6HWkoh9eyyNFaTM79PY6CAPcIr6X/KTiliw=
|
||||
layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk=
|
||||
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
|
||||
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
lukechampine.com/blake3 v1.5.1 h1:ITRyxe0LlLZcPUWOZ3Taz8mbug/ptn7jbbeeij5ZiPo=
|
||||
lukechampine.com/blake3 v1.5.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
|
||||
mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
|
||||
|
||||
+12
-6
@@ -5,7 +5,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -19,24 +20,29 @@ type BlackholeConfig struct {
|
||||
}
|
||||
|
||||
func (v *BlackholeConfig) Build() (proto.Message, error) {
|
||||
config := new(blackhole.Config)
|
||||
errors.PrintDeprecatedFeatureWarning(`"blackhole" outbound`, `"freedom" outbound with a blocking "firewall" rule`)
|
||||
rule := &freedom.FirewallConfig{
|
||||
Action: freedom.RuleAction_Block,
|
||||
Delay: &freedom.Range{},
|
||||
LogLevel: log.Severity_Unknown.Enum(),
|
||||
}
|
||||
if v.Response != nil {
|
||||
responseName := strings.ToLower(v.Response.Type)
|
||||
switch responseName {
|
||||
case "none", "":
|
||||
config.Response = &blackhole.Response{Type: "none"}
|
||||
rule.Reply = &freedom.Reply{Type: "none"}
|
||||
case "http":
|
||||
config.Response = &blackhole.Response{Type: "http"}
|
||||
rule.Reply = &freedom.Reply{Type: "http"}
|
||||
case "custom":
|
||||
data, err := base64.StdEncoding.DecodeString(v.Response.CustomResponseData)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode custom response data: " + err.Error())
|
||||
}
|
||||
config.Response = &blackhole.Response{Type: "custom", CustomResponseData: data}
|
||||
rule.Reply = &freedom.Reply{Type: "custom", CustomResponseData: data}
|
||||
default:
|
||||
return nil, errors.New("unknown blackhole response: " + responseName)
|
||||
}
|
||||
}
|
||||
|
||||
return config, nil
|
||||
return &freedom.Config{Firewall: []*freedom.FirewallConfig{rule}}, nil
|
||||
}
|
||||
|
||||
@@ -3,8 +3,9 @@ package conf_test
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
func TestHTTPResponseJSON(t *testing.T) {
|
||||
@@ -20,14 +21,25 @@ func TestHTTPResponseJSON(t *testing.T) {
|
||||
}
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &blackhole.Config{
|
||||
Response: &blackhole.Response{Type: "http"},
|
||||
Output: &freedom.Config{
|
||||
Firewall: []*freedom.FirewallConfig{{
|
||||
Action: freedom.RuleAction_Block,
|
||||
Delay: &freedom.Range{},
|
||||
LogLevel: log.Severity_Unknown.Enum(),
|
||||
Reply: &freedom.Reply{Type: "http"},
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &blackhole.Config{},
|
||||
Output: &freedom.Config{
|
||||
Firewall: []*freedom.FirewallConfig{{
|
||||
Action: freedom.RuleAction_Block,
|
||||
Delay: &freedom.Range{},
|
||||
LogLevel: log.Severity_Unknown.Enum(),
|
||||
}},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -46,11 +58,16 @@ func TestCustomResponseJSON(t *testing.T) {
|
||||
}
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &blackhole.Config{
|
||||
Response: &blackhole.Response{
|
||||
Type: "custom",
|
||||
CustomResponseData: []byte("custom response"),
|
||||
},
|
||||
Output: &freedom.Config{
|
||||
Firewall: []*freedom.FirewallConfig{{
|
||||
Action: freedom.RuleAction_Block,
|
||||
Delay: &freedom.Range{},
|
||||
LogLevel: log.Severity_Unknown.Enum(),
|
||||
Reply: &freedom.Reply{
|
||||
Type: "custom",
|
||||
CustomResponseData: []byte("custom response"),
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
+68
-28
@@ -18,16 +18,17 @@ import (
|
||||
)
|
||||
|
||||
type FreedomConfig struct {
|
||||
TargetStrategy string `json:"targetStrategy"`
|
||||
DomainStrategy string `json:"domainStrategy"`
|
||||
Redirect string `json:"redirect"`
|
||||
UserLevel uint32 `json:"userLevel"`
|
||||
Fragment *Fragment `json:"fragment"`
|
||||
Noise *Noise `json:"noise"`
|
||||
Noises []*Noise `json:"noises"`
|
||||
ProxyProtocol uint32 `json:"proxyProtocol"`
|
||||
IPsBlocked *StringList `json:"ipsBlocked"`
|
||||
FinalRules []*FreedomFinalRuleConfig `json:"finalRules"`
|
||||
TargetStrategy string `json:"targetStrategy"`
|
||||
DomainStrategy string `json:"domainStrategy"`
|
||||
Redirect string `json:"redirect"`
|
||||
UserLevel uint32 `json:"userLevel"`
|
||||
Fragment *Fragment `json:"fragment"`
|
||||
Noise *Noise `json:"noise"`
|
||||
Noises []*Noise `json:"noises"`
|
||||
ProxyProtocol uint32 `json:"proxyProtocol"`
|
||||
IPsBlocked *StringList `json:"ipsBlocked"`
|
||||
Firewall []*FreedomFirewallConfig `json:"firewall"`
|
||||
FinalRules []*FreedomFirewallConfig `json:"finalRules"`
|
||||
}
|
||||
|
||||
type Fragment struct {
|
||||
@@ -44,21 +45,45 @@ type Noise struct {
|
||||
ApplyTo string `json:"applyTo"`
|
||||
}
|
||||
|
||||
type FreedomFinalRuleConfig struct {
|
||||
Action string `json:"action"`
|
||||
Network *NetworkList `json:"network"`
|
||||
Port *PortList `json:"port"`
|
||||
IP *StringList `json:"ip"`
|
||||
Delay *Int32Range `json:"delay"`
|
||||
LogLevel string `json:"logLevel"`
|
||||
BlockDelay *Int32Range `json:"blockDelay"`
|
||||
type FreedomFirewallConfig struct {
|
||||
Action string `json:"action"`
|
||||
Network *NetworkList `json:"network"`
|
||||
Port *PortList `json:"port"`
|
||||
IP *StringList `json:"ip"`
|
||||
Delay *Int32Range `json:"delay"`
|
||||
LogLevel string `json:"logLevel"`
|
||||
Reply *FreedomReplyConfig `json:"reply"`
|
||||
BlockDelay *Int32Range `json:"blockDelay"`
|
||||
}
|
||||
|
||||
type FreedomReplyConfig struct {
|
||||
Type string `json:"type"`
|
||||
CustomResponseData string `json:"customResponseData"`
|
||||
}
|
||||
|
||||
func (c *FreedomReplyConfig) Build() (*freedom.Reply, error) {
|
||||
replyType := strings.ToLower(c.Type)
|
||||
switch replyType {
|
||||
case "none", "":
|
||||
return &freedom.Reply{Type: "none"}, nil
|
||||
case "http":
|
||||
return &freedom.Reply{Type: "http"}, nil
|
||||
case "custom":
|
||||
data, err := base64.StdEncoding.DecodeString(c.CustomResponseData)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode custom reply data: " + err.Error())
|
||||
}
|
||||
return &freedom.Reply{Type: "custom", CustomResponseData: data}, nil
|
||||
default:
|
||||
return nil, errors.New("unknown firewall reply: " + replyType)
|
||||
}
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *FreedomConfig) Build() (proto.Message, error) {
|
||||
if c.IPsBlocked != nil {
|
||||
// todo: remove legacy
|
||||
errors.LogWarning(context.Background(), `The feature "ipsBlocked" has been removed and migrated to "finalRules". Please update your config(s) according to release note and documentation.`)
|
||||
errors.LogWarning(context.Background(), `The feature "ipsBlocked" has been removed and migrated to "firewall". Please update your config(s) according to release note and documentation.`)
|
||||
}
|
||||
|
||||
config := new(freedom.Config)
|
||||
@@ -184,15 +209,22 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
|
||||
}
|
||||
|
||||
if c.ProxyProtocol > 0 && c.ProxyProtocol <= 2 {
|
||||
config.ProxyProtocol = c.ProxyProtocol
|
||||
errors.PrintDeprecatedFeatureWarning(`"proxyProtocol" in Freedom`, `"proxy-protocol" in "streamSettings.finalmask.tcp"`)
|
||||
}
|
||||
|
||||
for _, r := range c.FinalRules {
|
||||
firewall := c.Firewall
|
||||
if c.FinalRules != nil {
|
||||
errors.PrintDeprecatedFeatureWarning("finalRules", "firewall")
|
||||
if firewall == nil {
|
||||
firewall = c.FinalRules
|
||||
}
|
||||
}
|
||||
for _, r := range firewall {
|
||||
rule, err := r.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.FinalRules = append(config.FinalRules, rule)
|
||||
config.Firewall = append(config.Firewall, rule)
|
||||
}
|
||||
|
||||
return config, nil
|
||||
@@ -254,8 +286,8 @@ func ParseNoise(noise *Noise) (*freedom.Noise, error) {
|
||||
return NConfig, nil
|
||||
}
|
||||
|
||||
func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
|
||||
rule := &freedom.FinalRuleConfig{}
|
||||
func (c *FreedomFirewallConfig) Build() (*freedom.FirewallConfig, error) {
|
||||
rule := &freedom.FirewallConfig{}
|
||||
|
||||
switch strings.ToLower(c.Action) {
|
||||
case "allow":
|
||||
@@ -283,13 +315,13 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
|
||||
}
|
||||
|
||||
if c.BlockDelay != nil {
|
||||
errors.PrintDeprecatedFeatureWarning("finalRules.blockDelay", "finalRules.delay")
|
||||
errors.PrintDeprecatedFeatureWarning("firewall.blockDelay", "firewall.delay")
|
||||
c.Delay = c.BlockDelay
|
||||
}
|
||||
|
||||
if rule.Action != freedom.RuleAction_Block {
|
||||
if c.Delay != nil || c.LogLevel != "" {
|
||||
return nil, errors.New("delay and logLevel are only supported for block finalRules")
|
||||
if c.Delay != nil || c.LogLevel != "" || c.Reply != nil {
|
||||
return nil, errors.New("delay, logLevel and reply are only supported for firewall action block")
|
||||
}
|
||||
return rule, nil
|
||||
}
|
||||
@@ -301,6 +333,14 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if c.Reply != nil {
|
||||
reply, err := c.Reply.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rule.Reply = reply
|
||||
}
|
||||
|
||||
switch strings.ToLower(c.LogLevel) {
|
||||
case "", "info":
|
||||
rule.LogLevel = log.Severity_Info.Enum()
|
||||
@@ -313,7 +353,7 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
|
||||
case "error":
|
||||
rule.LogLevel = log.Severity_Error.Enum()
|
||||
default:
|
||||
return nil, errors.New("unknown finalRules.logLevel: ", c.LogLevel)
|
||||
return nil, errors.New("unknown firewall.logLevel: ", c.LogLevel)
|
||||
}
|
||||
|
||||
return rule, nil
|
||||
|
||||
@@ -42,13 +42,17 @@ func TestFreedomConfig(t *testing.T) {
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
"finalRules": [{
|
||||
"firewall": [{
|
||||
"action": "block",
|
||||
"network": "tcp,udp",
|
||||
"port": "53,443",
|
||||
"ip": ["10.0.0.0/8", "2001:db8::/32"],
|
||||
"delay": "30-60",
|
||||
"logLevel": "debug"
|
||||
"logLevel": "debug",
|
||||
"reply": {
|
||||
"type": "custom",
|
||||
"customResponseData": "Y3VzdG9tIHJlc3BvbnNl"
|
||||
}
|
||||
}, {
|
||||
"action": "allow",
|
||||
"network": ["udp"]
|
||||
@@ -56,7 +60,7 @@ func TestFreedomConfig(t *testing.T) {
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &freedom.Config{
|
||||
FinalRules: []*freedom.FinalRuleConfig{
|
||||
Firewall: []*freedom.FirewallConfig{
|
||||
{
|
||||
Action: freedom.RuleAction_Block,
|
||||
Networks: []net.Network{net.Network_TCP, net.Network_UDP},
|
||||
@@ -90,6 +94,10 @@ func TestFreedomConfig(t *testing.T) {
|
||||
},
|
||||
Delay: &freedom.Range{Min: 30, Max: 60},
|
||||
LogLevel: log.Severity_Debug.Enum(),
|
||||
Reply: &freedom.Reply{
|
||||
Type: "custom",
|
||||
CustomResponseData: []byte("custom response"),
|
||||
},
|
||||
},
|
||||
{
|
||||
Action: freedom.RuleAction_Allow,
|
||||
|
||||
+11
-1
@@ -2,6 +2,7 @@ package conf
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/xtls/xray-core/app/geodata"
|
||||
@@ -19,11 +20,20 @@ func (c *GeodataAssetConfig) Build() (*geodata.Asset, error) {
|
||||
return nil, errors.New("invalid geodata asset url: ", c.URL).Base(err)
|
||||
}
|
||||
return &geodata.Asset{
|
||||
Url: c.URL,
|
||||
Url: migrateGeodataURL(c.URL),
|
||||
File: c.File,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func migrateGeodataURL(assetURL string) string {
|
||||
if strings.HasSuffix(strings.ToLower(assetURL), ".dat") && (strings.HasPrefix(strings.ToLower(assetURL), "https://github.com/xtls/xray-rules-dat/") ||
|
||||
strings.HasPrefix(strings.ToLower(assetURL), "https://raw.githubusercontent.com/xtls/xray-rules-dat/")) {
|
||||
errors.PrintDeprecatedFeatureWarning(assetURL, assetURL+".gz")
|
||||
return assetURL + ".gz"
|
||||
}
|
||||
return assetURL
|
||||
}
|
||||
|
||||
func validateHTTPS(s string) error {
|
||||
u, err := url.ParseRequestURI(s)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type BridgeConfig struct {
|
||||
Tag string `json:"tag"`
|
||||
Domain string `json:"domain"`
|
||||
}
|
||||
|
||||
func (c *BridgeConfig) Build() (*reverse.BridgeConfig, error) {
|
||||
return &reverse.BridgeConfig{
|
||||
Tag: c.Tag,
|
||||
Domain: c.Domain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type PortalConfig struct {
|
||||
Tag string `json:"tag"`
|
||||
Domain string `json:"domain"`
|
||||
}
|
||||
|
||||
func (c *PortalConfig) Build() (*reverse.PortalConfig, error) {
|
||||
return &reverse.PortalConfig{
|
||||
Tag: c.Tag,
|
||||
Domain: c.Domain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type ReverseConfig struct {
|
||||
Bridges []BridgeConfig `json:"bridges"`
|
||||
Portals []PortalConfig `json:"portals"`
|
||||
}
|
||||
|
||||
func (c *ReverseConfig) Build() (proto.Message, error) {
|
||||
config := &reverse.Config{}
|
||||
for _, bconfig := range c.Bridges {
|
||||
b, err := bconfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.BridgeConfig = append(config.BridgeConfig, b)
|
||||
}
|
||||
|
||||
for _, pconfig := range c.Portals {
|
||||
p, err := pconfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.PortalConfig = append(config.PortalConfig, p)
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/reverse"
|
||||
"github.com/xtls/xray-core/infra/conf"
|
||||
)
|
||||
|
||||
func TestReverseConfig(t *testing.T) {
|
||||
creator := func() conf.Buildable {
|
||||
return new(conf.ReverseConfig)
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{
|
||||
"bridges": [{
|
||||
"tag": "test",
|
||||
"domain": "test.example.com"
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &reverse.Config{
|
||||
BridgeConfig: []*reverse.BridgeConfig{
|
||||
{Tag: "test", Domain: "test.example.com"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
"portals": [{
|
||||
"tag": "test",
|
||||
"domain": "test.example.com"
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &reverse.Config{
|
||||
PortalConfig: []*reverse.PortalConfig{
|
||||
{Tag: "test", Domain: "test.example.com"},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package conf
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
@@ -18,6 +20,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
xlua "github.com/xtls/xray-core/common/lua"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/filter"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/fragment"
|
||||
@@ -26,6 +29,7 @@ import (
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/mkcp/header"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/mkcp/original"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/noise"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/proxyprotocol"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/realm"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/salamander"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask/sudoku"
|
||||
@@ -76,11 +80,12 @@ var (
|
||||
customVarNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
|
||||
|
||||
tcpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{
|
||||
"filter": func() interface{} { return new(Filter) },
|
||||
"header-custom": func() interface{} { return new(HeaderCustomTCP) },
|
||||
"fragment": func() interface{} { return new(FragmentMask) },
|
||||
"sudoku": func() interface{} { return new(Sudoku) },
|
||||
"xmc": func() interface{} { return new(XMC) },
|
||||
"filter": func() interface{} { return new(Filter) },
|
||||
"header-custom": func() interface{} { return new(HeaderCustomTCP) },
|
||||
"proxy-protocol": func() interface{} { return new(ProxyProtocol) },
|
||||
"fragment": func() interface{} { return new(FragmentMask) },
|
||||
"sudoku": func() interface{} { return new(Sudoku) },
|
||||
"xmc": func() interface{} { return new(XMC) },
|
||||
}, "type", "settings")
|
||||
|
||||
udpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{
|
||||
@@ -97,6 +102,32 @@ var (
|
||||
}, "type", "settings")
|
||||
)
|
||||
|
||||
type ProxyProtocol struct {
|
||||
Version uint32 `json:"version"`
|
||||
}
|
||||
|
||||
func (c *ProxyProtocol) Build() (proto.Message, error) {
|
||||
version := c.Version
|
||||
if version == 0 {
|
||||
version = 2
|
||||
}
|
||||
if version != 1 && version != 2 {
|
||||
return nil, errors.New("PROXY protocol version must be 1 or 2")
|
||||
}
|
||||
return &proxyprotocol.Config{Version: version}, nil
|
||||
}
|
||||
|
||||
func addProxyProtocolMask(config *internet.StreamConfig, version uint32) {
|
||||
mask := serial.ToTypedMessage(&proxyprotocol.Config{Version: version})
|
||||
for _, existing := range config.Tcpmasks {
|
||||
if existing.Type == mask.Type {
|
||||
return
|
||||
}
|
||||
}
|
||||
// Put the header directly on the socket, before the other masks.
|
||||
config.Tcpmasks = append(config.Tcpmasks, mask)
|
||||
}
|
||||
|
||||
type Filter struct {
|
||||
BlockedSourceIPs []string `json:"blockedSourceIPs"`
|
||||
AllowedSourceIPs []string `json:"allowedSourceIPs"`
|
||||
@@ -836,6 +867,7 @@ type XDNSDomain struct {
|
||||
LabelLimit int32 `json:"labelLimit"`
|
||||
Types []int32 `json:"types"`
|
||||
Edns0 int32 `json:"edns0"`
|
||||
Alphabet string `json:"alphabet"`
|
||||
}
|
||||
|
||||
type XDNSResolver struct {
|
||||
@@ -862,7 +894,7 @@ func (c *XDNS) Build() (proto.Message, error) {
|
||||
c.Domains[i].LabelLimit = 63
|
||||
}
|
||||
for j := range c.Domains[i].Names {
|
||||
domain, err := xdns.NewDomain(c.Domains[i].Names[j], int(c.Domains[i].LenLimit), int(c.Domains[i].LabelLimit), []uint16{1, 5, 16, 28}, uint16(c.Domains[i].Edns0))
|
||||
domain, err := xdns.NewDomain(c.Domains[i].Names[j], int(c.Domains[i].LenLimit), int(c.Domains[i].LabelLimit), []uint16{1, 5, 16, 28}, uint16(c.Domains[i].Edns0), c.Domains[i].Alphabet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -873,6 +905,7 @@ func (c *XDNS) Build() (proto.Message, error) {
|
||||
LabelLimit: c.Domains[i].LabelLimit,
|
||||
Types: c.Domains[i].Types,
|
||||
Edns0: c.Domains[i].Edns0,
|
||||
Alphabet: c.Domains[i].Alphabet,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -932,9 +965,39 @@ func (c *XDNS) Build() (proto.Message, error) {
|
||||
}
|
||||
|
||||
type XMC struct {
|
||||
Hostname string `json:"hostname"`
|
||||
Profiles []XMCProfile `json:"profiles"`
|
||||
Password string `json:"password"`
|
||||
Hostname string `json:"hostname"`
|
||||
Profiles []XMCProfile `json:"profiles"`
|
||||
Password string `json:"password"`
|
||||
Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
|
||||
Yggdrasil *XMCYggdrasil `json:"yggdrasil,omitempty"`
|
||||
// A configured list is the complete padding schedule and replaces the
|
||||
// built-in preset entirely, including the preset's Play-state join tail.
|
||||
// NoPadding disables padding. An explicit empty "paddings" array means the
|
||||
// same; an absent one keeps the built-in preset.
|
||||
NoPadding bool `json:"noPadding,omitempty"`
|
||||
}
|
||||
|
||||
type XMCPaddingTurn struct {
|
||||
Length string `json:"length"`
|
||||
Direction string `json:"direction"`
|
||||
// Delay is an optional millisecond value or inclusive min-max range: the
|
||||
// pause that leads into this turn, written on the turn that follows the gap
|
||||
// it reproduces. The sending side samples the range, the peer spends its
|
||||
// minimum, and nothing pauses after the last turn.
|
||||
Delay string `json:"delay,omitempty"`
|
||||
}
|
||||
|
||||
// XMCYggdrasil enables third-party login through a Yggdrasil API server such
|
||||
// as Blessing Skin. The client authenticates with the API and the server
|
||||
// verifies players through its hasJoined endpoint.
|
||||
type XMCYggdrasil struct {
|
||||
// API root of the Yggdrasil API, for example
|
||||
// https://skin.example.com/api/yggdrasil
|
||||
API string `json:"api"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
// Optional player name, required when the account owns several players.
|
||||
Player string `json:"player"`
|
||||
}
|
||||
|
||||
type XMCProfile struct {
|
||||
@@ -970,17 +1033,115 @@ func (c *XMCProfile) Build() (*xmc.Profile, error) {
|
||||
}
|
||||
|
||||
func (c *XMC) Build() (proto.Message, error) {
|
||||
if len(c.Profiles) == 0 {
|
||||
// An explicit empty array is different from an absent field: json leaves
|
||||
// Paddings nil when it is absent, so the user can turn padding off without
|
||||
// a second switch.
|
||||
noPadding := c.NoPadding || (c.Paddings != nil && len(c.Paddings) == 0)
|
||||
if noPadding && len(c.Paddings) > 0 {
|
||||
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
|
||||
}
|
||||
config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding}
|
||||
for i, turn := range c.Paddings {
|
||||
minimum, maximum, err := ParseRangeString(turn.Length)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft padding turn %d length: %w", i, err)
|
||||
}
|
||||
delayMinimum, delayMaximum, err := ParseRangeString(turn.Delay)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft padding turn %d delay: %w", i, err)
|
||||
}
|
||||
|
||||
var direction int32
|
||||
switch turn.Direction {
|
||||
case "c2s", "client-to-server":
|
||||
direction = 1
|
||||
case "s2c", "server-to-client":
|
||||
direction = 2
|
||||
default:
|
||||
return nil, fmt.Errorf("minecraft padding turn %d: invalid direction %q (must be \"c2s\" or \"s2c\")", i, turn.Direction)
|
||||
}
|
||||
|
||||
config.Paddings = append(config.Paddings, &xmc.Padding{
|
||||
LengthMin: int64(minimum),
|
||||
LengthMax: int64(maximum),
|
||||
Direction: direction,
|
||||
DelayMin: int64(delayMinimum),
|
||||
DelayMax: int64(delayMaximum),
|
||||
})
|
||||
}
|
||||
if err := config.ValidatePadding(); err != nil {
|
||||
return nil, fmt.Errorf("minecraft padding: %w", err)
|
||||
}
|
||||
|
||||
var yggdrasil *xmc.Yggdrasil
|
||||
if c.Yggdrasil != nil {
|
||||
if c.Yggdrasil.API == "" {
|
||||
return nil, fmt.Errorf("empty minecraft yggdrasil api")
|
||||
}
|
||||
|
||||
apiURL, err := url.Parse(c.Yggdrasil.API)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid minecraft yggdrasil api: %w", err)
|
||||
}
|
||||
if apiURL.Scheme != "http" && apiURL.Scheme != "https" {
|
||||
return nil, fmt.Errorf("invalid minecraft yggdrasil api scheme: %q", apiURL.Scheme)
|
||||
}
|
||||
if apiURL.Host == "" {
|
||||
return nil, fmt.Errorf("invalid minecraft yggdrasil api: missing host")
|
||||
}
|
||||
if apiURL.RawQuery != "" || apiURL.Fragment != "" {
|
||||
return nil, fmt.Errorf("invalid minecraft yggdrasil api: query and fragment are not allowed")
|
||||
}
|
||||
if (c.Yggdrasil.Username == "") != (c.Yggdrasil.Password == "") {
|
||||
return nil, fmt.Errorf("minecraft yggdrasil username and password must be set together")
|
||||
}
|
||||
if c.Yggdrasil.Player != "" && !xmcUsernamePattern.MatchString(c.Yggdrasil.Player) {
|
||||
return nil, fmt.Errorf("invalid minecraft yggdrasil player: %q", c.Yggdrasil.Player)
|
||||
}
|
||||
|
||||
yggdrasil = &xmc.Yggdrasil{
|
||||
Api: strings.TrimSuffix(c.Yggdrasil.API, "/"),
|
||||
Username: c.Yggdrasil.Username,
|
||||
Password: c.Yggdrasil.Password,
|
||||
Player: c.Yggdrasil.Player,
|
||||
}
|
||||
} else if len(c.Profiles) == 0 {
|
||||
return nil, fmt.Errorf("minecraft profiles are required")
|
||||
}
|
||||
|
||||
if c.Password == "" {
|
||||
return nil, fmt.Errorf("empty password")
|
||||
}
|
||||
var (
|
||||
rsaPrivateKey *rsa.PrivateKey
|
||||
password string
|
||||
)
|
||||
if yggdrasil != nil {
|
||||
// Yggdrasil mode binds the transport through the session hash: the
|
||||
// client joins with the server's actual public key and the server
|
||||
// checks hasJoined. The key pair is therefore generated per process
|
||||
// instead of being derived from the password.
|
||||
generated, err := rsa.GenerateKey(rand.Reader, 1024)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate minecraft rsa key: %w", err)
|
||||
}
|
||||
rsaPrivateKey = generated
|
||||
|
||||
rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive minecraft rsa key: %w", err)
|
||||
warning := `XMC: Yggdrasil mode is enabled. The RSA key pair is generated randomly and "password" is no longer used to derive it or to authenticate the transport; players are verified through ` + yggdrasil.Api + ` (client /join, server /hasJoined). Both ends must be able to reach the Yggdrasil API.`
|
||||
if c.Password != "" {
|
||||
warning += ` The configured "password" is ignored.`
|
||||
}
|
||||
errors.LogWarning(context.Background(), warning)
|
||||
} else {
|
||||
if c.Password == "" {
|
||||
return nil, fmt.Errorf("empty password")
|
||||
}
|
||||
if len(c.Password) > xmc.MaxLegacyPasswordLength {
|
||||
return nil, fmt.Errorf("minecraft password is longer than %d bytes", xmc.MaxLegacyPasswordLength)
|
||||
}
|
||||
derived, err := xmc.DeriveRSAKey(c.Password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive minecraft rsa key: %w", err)
|
||||
}
|
||||
rsaPrivateKey = derived
|
||||
password = c.Password
|
||||
}
|
||||
|
||||
rsaPublicKey, err := x509.MarshalPKIXPublicKey(&rsaPrivateKey.PublicKey)
|
||||
@@ -997,13 +1158,12 @@ func (c *XMC) Build() (proto.Message, error) {
|
||||
profiles = append(profiles, profile)
|
||||
}
|
||||
|
||||
return &xmc.Config{
|
||||
Password: c.Password,
|
||||
Hostname: c.Hostname,
|
||||
RsaPrivateKey: x509.MarshalPKCS1PrivateKey(rsaPrivateKey),
|
||||
RsaPublicKey: rsaPublicKey,
|
||||
Profiles: profiles,
|
||||
}, nil
|
||||
config.Password = password
|
||||
config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey)
|
||||
config.RsaPublicKey = rsaPublicKey
|
||||
config.Profiles = profiles
|
||||
config.Yggdrasil = yggdrasil
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type Xicmp struct {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -10,6 +12,11 @@ import (
|
||||
func TestXMCBuildProfile(t *testing.T) {
|
||||
built, err := (&XMC{
|
||||
Password: "test-password",
|
||||
Paddings: []XMCPaddingTurn{
|
||||
{Length: "3", Direction: "c2s"},
|
||||
{Length: "127-129", Direction: "s2c", Delay: "100"},
|
||||
{Length: "8388608", Direction: "c2s", Delay: "50-150"},
|
||||
},
|
||||
Profiles: []XMCProfile{
|
||||
{
|
||||
Username: "TestUser",
|
||||
@@ -26,6 +33,19 @@ func TestXMCBuildProfile(t *testing.T) {
|
||||
if len(config.Profiles) != 1 || len(config.Profiles[0].Uuid) != 16 {
|
||||
t.Fatalf("unexpected profiles: %+v", config.Profiles)
|
||||
}
|
||||
if len(config.Paddings) != 3 || config.Paddings[0].LengthMin != 3 || config.Paddings[0].LengthMax != 3 ||
|
||||
config.Paddings[1].LengthMin != 127 || config.Paddings[1].LengthMax != 129 ||
|
||||
config.Paddings[2].LengthMin != 8388608 || config.Paddings[2].LengthMax != 8388608 {
|
||||
t.Fatalf("unexpected padding: %v", config.Paddings)
|
||||
}
|
||||
if config.Paddings[0].Direction != 1 || config.Paddings[1].Direction != 2 || config.Paddings[2].Direction != 1 {
|
||||
t.Fatalf("unexpected padding directions: %v, %v, %v", config.Paddings[0].Direction, config.Paddings[1].Direction, config.Paddings[2].Direction)
|
||||
}
|
||||
if config.Paddings[0].DelayMin != 0 || config.Paddings[0].DelayMax != 0 ||
|
||||
config.Paddings[1].DelayMin != 100 || config.Paddings[1].DelayMax != 100 ||
|
||||
config.Paddings[2].DelayMin != 50 || config.Paddings[2].DelayMax != 150 {
|
||||
t.Fatalf("unexpected padding delays: %v, %v, %v", config.Paddings[0].DelayMin, config.Paddings[1].DelayMin, config.Paddings[2].DelayMin)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildRequiresProfile(t *testing.T) {
|
||||
@@ -34,3 +54,191 @@ func TestXMCBuildRequiresProfile(t *testing.T) {
|
||||
t.Fatalf("expected required profiles error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildRejectsPadding(t *testing.T) {
|
||||
for name, padding := range map[string]string{
|
||||
"empty_length": `[{"length": "", "direction": "c2s"}]`,
|
||||
"zero_length": `[{"length": "0", "direction": "c2s"}]`,
|
||||
"one_length": `[{"length": "1", "direction": "c2s"}]`,
|
||||
"two_length": `[{"length": "2", "direction": "c2s"}]`,
|
||||
"negative_length": `[{"length": "-1", "direction": "c2s"}]`,
|
||||
"reversed_range": `[{"length": "64-32", "direction": "c2s"}]`,
|
||||
"oversized_length": `[{"length": "8388609", "direction": "c2s"}]`,
|
||||
"huge_length": `[{"length": "4294967299", "direction": "c2s"}]`,
|
||||
"overflow_length": `[{"length": "9223372036854775808", "direction": "c2s"}]`,
|
||||
"invalid_range_format": `[{"length": "1-2-3", "direction": "c2s"}]`,
|
||||
"invalid_direction": `[{"length": "3", "direction": "invalid"}]`,
|
||||
"missing_direction": `[{"length": "3"}]`,
|
||||
"numeric_direction": `[{"length": "3", "direction": "1"}]`,
|
||||
"negative_delay": `[{"length": "3", "direction": "c2s", "delay": "-1"}]`,
|
||||
"reversed_delay": `[{"length": "3", "direction": "c2s", "delay": "10-5"}]`,
|
||||
"invalid_delay_format": `[{"length": "3", "direction": "c2s", "delay": "abc"}]`,
|
||||
"huge_delay": `[{"length": "3", "direction": "c2s", "delay": "9223372036854775807"}]`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
var config XMC
|
||||
if err := json.Unmarshal([]byte(`{"paddings":`+padding+`}`), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.Password = "test-password"
|
||||
config.Profiles = []XMCProfile{{
|
||||
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
|
||||
}}
|
||||
if _, err := config.Build(); err == nil {
|
||||
t.Fatalf("expected error for padding %s, got success", padding)
|
||||
} else {
|
||||
t.Logf("correctly rejected: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildRejectsLongPassword(t *testing.T) {
|
||||
profile := XMCProfile{
|
||||
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
|
||||
}
|
||||
|
||||
// The verify token and the password share one RSA-1024 PKCS#1 v1.5 block,
|
||||
// so the password cannot exceed xmc.MaxLegacyPasswordLength bytes.
|
||||
valid := strings.Repeat("p", xmc.MaxLegacyPasswordLength)
|
||||
if _, err := (&XMC{Password: valid, Profiles: []XMCProfile{profile}}).Build(); err != nil {
|
||||
t.Fatalf("password of %d bytes was rejected: %v", len(valid), err)
|
||||
}
|
||||
|
||||
tooLong := valid + "p"
|
||||
_, err := (&XMC{Password: tooLong, Profiles: []XMCProfile{profile}}).Build()
|
||||
if err == nil || !strings.Contains(err.Error(), "longer than") {
|
||||
t.Fatalf("expected a password length error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildYggdrasil(t *testing.T) {
|
||||
built, err := (&XMC{
|
||||
Password: "test-password",
|
||||
Yggdrasil: &XMCYggdrasil{
|
||||
API: "https://skin.example.com/api/yggdrasil/",
|
||||
Username: "user@example.com",
|
||||
Password: "login-password",
|
||||
Player: "TestUser",
|
||||
},
|
||||
}).Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build XMC config: %v", err)
|
||||
}
|
||||
|
||||
config := built.(*xmc.Config)
|
||||
if config.Yggdrasil == nil {
|
||||
t.Fatal("yggdrasil config is missing")
|
||||
}
|
||||
if config.Yggdrasil.Api != "https://skin.example.com/api/yggdrasil" {
|
||||
t.Fatalf("yggdrasil api = %q", config.Yggdrasil.Api)
|
||||
}
|
||||
if config.Yggdrasil.Username != "user@example.com" || config.Yggdrasil.Password != "login-password" || config.Yggdrasil.Player != "TestUser" {
|
||||
t.Fatalf("unexpected yggdrasil config: %+v", config.Yggdrasil)
|
||||
}
|
||||
if config.Password != "" {
|
||||
t.Fatalf("password must not be used in yggdrasil mode: %q", config.Password)
|
||||
}
|
||||
if len(config.RsaPrivateKey) == 0 || len(config.RsaPublicKey) == 0 {
|
||||
t.Fatal("yggdrasil mode must build a random rsa key pair")
|
||||
}
|
||||
privateKey, err := x509.ParsePKCS1PrivateKey(config.RsaPrivateKey)
|
||||
if err != nil {
|
||||
t.Fatalf("parse generated rsa private key: %v", err)
|
||||
}
|
||||
publicKey, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal generated rsa public key: %v", err)
|
||||
}
|
||||
if string(publicKey) != string(config.RsaPublicKey) {
|
||||
t.Fatal("generated rsa key pair does not match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildYggdrasilServerWithoutCredentials(t *testing.T) {
|
||||
built, err := (&XMC{
|
||||
Yggdrasil: &XMCYggdrasil{
|
||||
API: "https://skin.example.com/api/yggdrasil",
|
||||
},
|
||||
}).Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build server-side XMC config: %v", err)
|
||||
}
|
||||
if built.(*xmc.Config).Yggdrasil == nil {
|
||||
t.Fatal("yggdrasil config is missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildRejectsInvalidYggdrasil(t *testing.T) {
|
||||
cases := []*XMCYggdrasil{
|
||||
{API: ""},
|
||||
{API: "ftp://skin.example.com/api/yggdrasil"},
|
||||
{API: "https://skin.example.com/api/yggdrasil?foo=bar"},
|
||||
{API: "https://skin.example.com/api/yggdrasil", Username: "user@example.com"},
|
||||
{API: "https://skin.example.com/api/yggdrasil", Password: "login-password"},
|
||||
{API: "https://skin.example.com/api/yggdrasil", Player: "bad name"},
|
||||
}
|
||||
for i, yggdrasil := range cases {
|
||||
_, err := (&XMC{Yggdrasil: yggdrasil}).Build()
|
||||
if err == nil {
|
||||
t.Fatalf("case %d was accepted: %+v", i, yggdrasil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildRequiresPasswordInLegacyMode(t *testing.T) {
|
||||
_, err := (&XMC{
|
||||
Profiles: []XMCProfile{
|
||||
{
|
||||
Username: "TestUser",
|
||||
UUID: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
TexturesValue: "textures-value",
|
||||
TexturesSignature: "textures-signature",
|
||||
},
|
||||
},
|
||||
}).Build()
|
||||
if err == nil || !strings.Contains(err.Error(), "empty password") {
|
||||
t.Fatalf("expected empty password error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildDisablesPadding(t *testing.T) {
|
||||
profile := XMCProfile{
|
||||
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
|
||||
}
|
||||
|
||||
for name, settings := range map[string]string{
|
||||
"explicit_empty_array": `{"paddings": []}`,
|
||||
"no_padding_switch": `{"noPadding": true}`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
var config XMC
|
||||
if err := json.Unmarshal([]byte(settings), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.Password = "test-password"
|
||||
config.Profiles = []XMCProfile{profile}
|
||||
built, err := config.Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build XMC config: %v", err)
|
||||
}
|
||||
builtConfig := built.(*xmc.Config)
|
||||
if !builtConfig.NoPadding || len(builtConfig.Paddings) != 0 {
|
||||
t.Fatalf("padding was not disabled: %+v", builtConfig)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
var config XMC
|
||||
if err := json.Unmarshal([]byte(`{"noPadding": true, "paddings": [{"length": "3", "direction": "c2s"}]}`), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.Password = "test-password"
|
||||
config.Profiles = []XMCProfile{profile}
|
||||
if _, err := config.Build(); err == nil || !strings.Contains(err.Error(), "exclusive") {
|
||||
t.Fatalf("expected an exclusive padding error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -697,10 +697,10 @@ func (c *HttpUpgradeConfig) Build() (proto.Message, error) {
|
||||
|
||||
const (
|
||||
Byte = 1
|
||||
Kilobyte = 1024 * Byte
|
||||
Megabyte = 1024 * Kilobyte
|
||||
Gigabyte = 1024 * Megabyte
|
||||
Terabyte = 1024 * Gigabyte
|
||||
Kilobyte = 1000 * Byte
|
||||
Megabyte = 1000 * Kilobyte
|
||||
Gigabyte = 1000 * Megabyte
|
||||
Terabyte = 1000 * Gigabyte
|
||||
)
|
||||
|
||||
type Bandwidth string
|
||||
|
||||
@@ -529,26 +529,25 @@ func TestXDriveOutboundConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, input := range []string{
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": 0, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}]}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct{ input, err string }{
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": false}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpConcurrency": -1}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpProxyUDP443": "skip"}}`, `"mux"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}]}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"testpre"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"xudpConcurrency": 8}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
|
||||
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||
{`{"protocol": "freedom", ` + xdriveStream + `}`, "VLESS"},
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/proxy/tun"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
type TunConfig struct {
|
||||
Name string `json:"name"`
|
||||
Desc string `json:"desc"`
|
||||
GUID string `json:"guid"`
|
||||
MTU uint32 `json:"mtu"`
|
||||
Gateway []string `json:"gateway"`
|
||||
DNS []string `json:"dns"`
|
||||
@@ -37,6 +39,13 @@ func (v *TunConfig) Build() (proto.Message, error) {
|
||||
AutoSystemRoutingTable: v.AutoSystemRoutingTable,
|
||||
AutoSystemDnsToGateway: v.AutoSystemDnsToGateway,
|
||||
}
|
||||
if v.GUID != "" {
|
||||
// only Windows gives the TUN a GUID, but a config is checked wherever it is loaded
|
||||
if _, err := tun.ParseGUID(v.GUID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.GUID = strings.ToLower(v.GUID)
|
||||
}
|
||||
leaks, err := tun.ExpandWfpBlockLeak(v.AutoSystemWfpBlockLeak)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -124,3 +124,48 @@ func TestTunConfigAutoSystemWfpBlockLeakUnknown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTunConfigGUID checks that a guid is read, written back in the canonical
|
||||
// form, and rejected unless it is one, on every system, even though only
|
||||
// Windows gives the TUN a GUID.
|
||||
func TestTunConfigGUID(t *testing.T) {
|
||||
build := func(guid string) (*tun.Config, error) {
|
||||
config := new(TunConfig)
|
||||
if err := json.Unmarshal([]byte(`{"name": "xray0", "guid": "`+guid+`"}`), config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message, err := config.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return message.(*tun.Config), nil
|
||||
}
|
||||
|
||||
if config, err := build("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if config.GUID != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {
|
||||
t.Errorf("guid = %q, want it kept", config.GUID)
|
||||
}
|
||||
if config, err := build("6BA7B810-9DAD-11D1-80B4-00C04FD430C8"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if config.GUID != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {
|
||||
t.Errorf("guid = %q, want it lowercased", config.GUID)
|
||||
}
|
||||
if config, err := build(""); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if config.GUID != "" {
|
||||
t.Errorf("guid = %q, want it empty, as the adapter GUID is derived from the name then", config.GUID)
|
||||
}
|
||||
for _, guid := range []string{
|
||||
"xray0",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
||||
"6ba7b8109dad11d180b400c04fd430c8",
|
||||
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
||||
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430cg",
|
||||
} {
|
||||
if _, err := build(guid); err == nil {
|
||||
t.Errorf("guid %q was accepted", guid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+27
-1
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/uuid"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vless/inbound"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/proxy/vless/outbound"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
@@ -236,6 +237,25 @@ func (c *VLessReverseConfig) Build() (*vless.Reverse, error) {
|
||||
return r, nil
|
||||
}
|
||||
|
||||
type MultiplexConfig struct {
|
||||
Concurrency int16 `json:"concurrency"`
|
||||
XudpConcurrency int16 `json:"xudpConcurrency"`
|
||||
XudpProxyUDP443 string `json:"xudpProxyUDP443"`
|
||||
}
|
||||
|
||||
func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
udp443 := c.XudpProxyUDP443
|
||||
if udp443 == "" {
|
||||
udp443 = "reject"
|
||||
}
|
||||
return multiplex.NormalizeConfig(&vless.Multiplex{
|
||||
Concurrency: int32(c.Concurrency), XudpConcurrency: int32(c.XudpConcurrency), XudpProxyUDP443: udp443,
|
||||
})
|
||||
}
|
||||
|
||||
type VLessOutboundVnext struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
@@ -251,6 +271,7 @@ type VLessOutboundConfig struct {
|
||||
Flow string `json:"flow"`
|
||||
Seed string `json:"seed"`
|
||||
Encryption string `json:"encryption"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
Reverse *VLessReverseConfig `json:"reverse"`
|
||||
Testpre uint32 `json:"testpre"`
|
||||
Testseed []uint32 `json:"testseed"`
|
||||
@@ -259,7 +280,12 @@ type VLessOutboundConfig struct {
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *VLessOutboundConfig) Build() (proto.Message, error) {
|
||||
config := new(outbound.Config)
|
||||
multiplex, err := c.Multiplex.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
|
||||
if c.Address != nil {
|
||||
c.Vnext = []*VLessOutboundVnext{
|
||||
{
|
||||
|
||||
+6
-1
@@ -117,13 +117,18 @@ type VMessOutboundConfig struct {
|
||||
Security string `json:"security"`
|
||||
Experiments string `json:"experiments"`
|
||||
Receivers []*VMessOutboundTarget `json:"vnext"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *VMessOutboundConfig) Build() (proto.Message, error) {
|
||||
errors.PrintNonRemovalDeprecatedFeatureWarning("VMess (with no Forward Secrecy, etc.)", "VLESS Encryption")
|
||||
|
||||
config := new(outbound.Config)
|
||||
multiplex, err := c.Multiplex.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
if c.Address != nil {
|
||||
c.Receivers = []*VMessOutboundTarget{
|
||||
{
|
||||
|
||||
+23
-47
@@ -107,30 +107,6 @@ func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
type MuxConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Concurrency int16 `json:"concurrency"`
|
||||
XudpConcurrency int16 `json:"xudpConcurrency"`
|
||||
XudpProxyUDP443 string `json:"xudpProxyUDP443"`
|
||||
}
|
||||
|
||||
// Build creates MultiplexingConfig, Concurrency < 0 completely disables mux.
|
||||
func (m *MuxConfig) Build() (*proxyman.MultiplexingConfig, error) {
|
||||
switch m.XudpProxyUDP443 {
|
||||
case "":
|
||||
m.XudpProxyUDP443 = "reject"
|
||||
case "reject", "allow", "skip":
|
||||
default:
|
||||
return nil, errors.New(`unknown "xudpProxyUDP443": `, m.XudpProxyUDP443)
|
||||
}
|
||||
return &proxyman.MultiplexingConfig{
|
||||
Enabled: m.Enabled,
|
||||
Concurrency: int32(m.Concurrency),
|
||||
XudpConcurrency: int32(m.XudpConcurrency),
|
||||
XudpProxyUDP443: m.XudpProxyUDP443,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type InboundDetourConfig struct {
|
||||
Protocol string `json:"protocol"`
|
||||
PortList *PortList `json:"port"`
|
||||
@@ -213,7 +189,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
|
||||
if _, ok := ts.(*masque.ServerConfig); !ok && receiverSettings.StreamSettings != nil && receiverSettings.StreamSettings.ProtocolName == "masque" {
|
||||
return nil, errors.New("the masque transport can only be used by the masque inbound")
|
||||
}
|
||||
if err := validateXDrive(ts, receiverSettings.StreamSettings, nil, receiverSettings.PortList); err != nil {
|
||||
if err := validateXDrive(ts, receiverSettings.StreamSettings, receiverSettings.PortList); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -231,7 +207,7 @@ type OutboundDetourConfig struct {
|
||||
Settings *json.RawMessage `json:"settings"`
|
||||
StreamSetting *StreamConfig `json:"streamSettings"`
|
||||
ProxySettings *json.RawMessage `json:"proxySettings"`
|
||||
MuxSettings *MuxConfig `json:"mux"`
|
||||
LegacyMux json.RawMessage `json:"mux,omitempty"`
|
||||
TargetStrategy string `json:"targetStrategy"`
|
||||
}
|
||||
|
||||
@@ -270,8 +246,8 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateXDrive allows only VLESS with encryption on xdrive, and on the client Mux.Cool for every connection
|
||||
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.MultiplexingConfig, pl *net.PortList) error {
|
||||
// validateXDrive allows only encrypted VLESS on xdrive, with native multiplex on every client connection.
|
||||
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortList) error {
|
||||
if ss == nil || ss.ProtocolName != "xdrive" {
|
||||
return nil
|
||||
}
|
||||
@@ -288,9 +264,9 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.Mu
|
||||
if account.Encryption == "none" {
|
||||
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
|
||||
}
|
||||
// reverse opens its own mux
|
||||
if account.Reverse == nil && (ms == nil || !ms.Enabled || ms.Concurrency < 0 || ms.XudpConcurrency < 0 || ms.XudpProxyUDP443 == "skip") {
|
||||
return errors.New(`the xdrive transport needs "mux" enabled, with no negative "concurrency" or "xudpConcurrency" and no "xudpProxyUDP443":"skip"`)
|
||||
// Reverse opens its own multiplexed connection.
|
||||
if account.Reverse == nil && (c.Multiplex.GetConcurrency() == 0 || c.Multiplex.GetXudpProxyUDP443() == "skip") {
|
||||
return errors.New(`the xdrive transport needs positive "settings.multiplex.concurrency" and does not support "xudpProxyUDP443":"skip"`)
|
||||
}
|
||||
if account.Testpre != 0 {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
||||
@@ -376,14 +352,6 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
senderSettings.StreamSettings = ss
|
||||
}
|
||||
|
||||
if c.MuxSettings != nil {
|
||||
ms, err := c.MuxSettings.Build()
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build Mux config").Base(err)
|
||||
}
|
||||
senderSettings.MultiplexSettings = ms
|
||||
}
|
||||
|
||||
settings := []byte("{}")
|
||||
if c.Settings != nil {
|
||||
settings = ([]byte)(*c.Settings)
|
||||
@@ -392,13 +360,17 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to load outbound detour config for protocol ", c.Protocol).Base(err)
|
||||
}
|
||||
if c.LegacyMux != nil {
|
||||
errors.LogWarning(context.Background(), `The legacy "mux" setting is ignored. To enable Multiplex for VLESS or VMess outbounds, use "settings.multiplex". If Multiplex is disabled, Xray will use ordinary outbound connections.`)
|
||||
}
|
||||
ts, err := rawConfig.(Buildable).Build()
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
|
||||
}
|
||||
if err := validateXDrive(ts, senderSettings.StreamSettings, senderSettings.MultiplexSettings, nil); err != nil {
|
||||
if err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -407,7 +379,16 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
return nil, errors.New("the masque transport can only be used by the masque outbound")
|
||||
}
|
||||
|
||||
if fc, ok := ts.(*freedom.Config); ok {
|
||||
if _, ok := rawConfig.(*BlackholeConfig); ok {
|
||||
// The legacy blackhole outbound never used its transport settings.
|
||||
senderSettings.StreamSettings = nil
|
||||
} else if fc, ok := ts.(*freedom.Config); ok {
|
||||
if legacy := rawConfig.(*FreedomConfig); legacy.ProxyProtocol > 0 && legacy.ProxyProtocol <= 2 {
|
||||
if senderSettings.StreamSettings == nil {
|
||||
senderSettings.StreamSettings = &internet.StreamConfig{}
|
||||
}
|
||||
addProxyProtocolMask(senderSettings.StreamSettings, legacy.ProxyProtocol)
|
||||
}
|
||||
if senderSettings.StreamSettings != nil &&
|
||||
senderSettings.StreamSettings.SocketSettings != nil &&
|
||||
senderSettings.StreamSettings.SocketSettings.AddressPortStrategy != internet.AddressPortStrategy_None {
|
||||
@@ -469,7 +450,7 @@ type Config struct {
|
||||
API *APIConfig `json:"api"`
|
||||
Metrics *MetricsConfig `json:"metrics"`
|
||||
Stats *StatsConfig `json:"stats"`
|
||||
Reverse *ReverseConfig `json:"reverse"`
|
||||
Reverse *json.RawMessage `json:"reverse"`
|
||||
FakeDNS *FakeDNSConfig `json:"fakeDns"`
|
||||
Observatory *ObservatoryConfig `json:"observatory"`
|
||||
BurstObservatory *BurstObservatoryConfig `json:"burstObservatory"`
|
||||
@@ -671,11 +652,6 @@ func (c *Config) Build() (*core.Config, error) {
|
||||
|
||||
if c.Reverse != nil {
|
||||
return nil, errors.PrintRemovedFeatureError(`"legacy reverse"`, `"VLESS Reverse Proxy"`)
|
||||
r, err := c.Reverse.Build()
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build reverse configuration").Base(err)
|
||||
}
|
||||
config.App = append(config.App, serial.ToTypedMessage(r))
|
||||
}
|
||||
|
||||
if c.FakeDNS != nil {
|
||||
|
||||
+101
-37
@@ -1,6 +1,7 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -10,7 +11,6 @@ import (
|
||||
"github.com/xtls/xray-core/app/log"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
clog "github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
core "github.com/xtls/xray-core/core"
|
||||
. "github.com/xtls/xray-core/infra/conf"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/proxy/vmess"
|
||||
"github.com/xtls/xray-core/proxy/vmess/inbound"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
@@ -225,49 +226,112 @@ func TestSniffingConfig_Build(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxConfig_Build(t *testing.T) {
|
||||
tests := []struct {
|
||||
func TestMultiplexConfig_Build(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
fields string
|
||||
want *proxyman.MultiplexingConfig
|
||||
want *vless.Multiplex
|
||||
bad bool
|
||||
}{
|
||||
{"default", `{"enabled": true, "concurrency": 16}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: true,
|
||||
Concurrency: 16,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"empty def", `{}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: 0,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"not enable", `{"enabled": false, "concurrency": 4}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: 4,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
{"forbidden", `{"enabled": false, "concurrency": -1}`, &proxyman.MultiplexingConfig{
|
||||
Enabled: false,
|
||||
Concurrency: -1,
|
||||
XudpConcurrency: 0,
|
||||
XudpProxyUDP443: "reject",
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
m := &MuxConfig{}
|
||||
common.Must(json.Unmarshal([]byte(tt.fields), m))
|
||||
if got, _ := m.Build(); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("MuxConfig.Build() = %v, want %v", got, tt.want)
|
||||
{name: "empty", fields: `{}`},
|
||||
{name: "both zero", fields: `{"concurrency":0,"xudpConcurrency":0}`},
|
||||
{name: "regular pool", fields: `{"concurrency":4}`, want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"}},
|
||||
{name: "XUDP only", fields: `{"xudpConcurrency":8}`, want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"}},
|
||||
{name: "negative concurrency", fields: `{"concurrency":-1,"xudpConcurrency":8}`, bad: true},
|
||||
{name: "negative XUDP concurrency", fields: `{"concurrency":4,"xudpConcurrency":-1}`, bad: true},
|
||||
{name: "invalid UDP policy", fields: `{"concurrency":4,"xudpProxyUDP443":"invalid"}`, bad: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var config MultiplexConfig
|
||||
if err := json.Unmarshal([]byte(tc.fields), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := config.Build()
|
||||
if (err != nil) != tc.bad || !proto.Equal(got, tc.want) {
|
||||
t.Fatalf("Build() = %v, %v, want config %v, error %t", got, err, tc.want, tc.bad)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutboundMultiplexConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
legacy string
|
||||
native string
|
||||
want *vless.Multiplex
|
||||
}{
|
||||
{name: "absent"},
|
||||
{name: "legacy enabled", legacy: `{"enabled":true,"concurrency":16}`},
|
||||
{name: "legacy disabled", legacy: `{"enabled":false}`},
|
||||
{name: "legacy null", legacy: `null`},
|
||||
{name: "legacy empty", legacy: `{}`},
|
||||
{name: "legacy values are not decoded", legacy: `{"enabled":"ignored","concurrency":"ignored"}`},
|
||||
{name: "empty native object", native: `{}`},
|
||||
{name: "enabled flag alone does not create a pool", native: `{"enabled":true}`},
|
||||
{
|
||||
name: "positive concurrency with old enabled flag", native: `{"concurrency":4,"enabled":false}`,
|
||||
want: &vless.Multiplex{Concurrency: 4, XudpProxyUDP443: "reject"},
|
||||
},
|
||||
{
|
||||
name: "native XUDP only", native: `{"xudpConcurrency":8}`,
|
||||
want: &vless.Multiplex{XudpConcurrency: 8, XudpProxyUDP443: "reject"},
|
||||
},
|
||||
{
|
||||
name: "native options override legacy", legacy: `{"enabled":true,"concurrency":16}`,
|
||||
native: `{"concurrency":4,"xudpConcurrency":8,"xudpProxyUDP443":"allow"}`,
|
||||
want: &vless.Multiplex{Concurrency: 4, XudpConcurrency: 8, XudpProxyUDP443: "allow"},
|
||||
},
|
||||
{name: "empty native with legacy enabled", legacy: `{"enabled":true}`, native: `{}`},
|
||||
}
|
||||
for _, protoName := range []string{"vless", "vmess"} {
|
||||
for _, tc := range tests {
|
||||
t.Run(protoName+"/"+tc.name, func(t *testing.T) {
|
||||
settings := `"address":"127.0.0.1","port":443,"id":"d19768cb-2891-4c3c-b45d-863f8fd64b6d"`
|
||||
if protoName == "vless" {
|
||||
settings += `,"encryption":"none"`
|
||||
}
|
||||
if tc.native != "" {
|
||||
settings += `,"multiplex":` + tc.native
|
||||
}
|
||||
input := `{"protocol":"` + protoName + `","settings":{` + settings + `}`
|
||||
if tc.legacy != "" {
|
||||
input += `,"mux":` + tc.legacy
|
||||
}
|
||||
|
||||
var config OutboundDetourConfig
|
||||
if err := json.Unmarshal([]byte(input+"}"), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := string(config.LegacyMux); got != tc.legacy {
|
||||
t.Errorf("legacy mux marker = %q, want %q", got, tc.legacy)
|
||||
}
|
||||
serialized, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hasMux := bytes.Contains(serialized, []byte(`"mux":`)); hasMux != (tc.legacy != "") {
|
||||
t.Errorf("serialized config changed legacy mux presence: %s", serialized)
|
||||
}
|
||||
built, err := config.Build()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxyConfig, err := built.ProxySettings.GetInstance()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := proxyConfig.(interface{ GetMultiplex() *vless.Multiplex }).GetMultiplex()
|
||||
if !proto.Equal(got, tc.want) {
|
||||
t.Errorf("multiplex = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_Override(t *testing.T) {
|
||||
legacyReverse := json.RawMessage(`{}`)
|
||||
tests := []struct {
|
||||
name string
|
||||
orig *Config
|
||||
@@ -285,7 +349,7 @@ func TestConfig_Override(t *testing.T) {
|
||||
Policy: &PolicyConfig{},
|
||||
API: &APIConfig{},
|
||||
Stats: &StatsConfig{},
|
||||
Reverse: &ReverseConfig{},
|
||||
Reverse: &legacyReverse,
|
||||
},
|
||||
"",
|
||||
&Config{
|
||||
@@ -295,7 +359,7 @@ func TestConfig_Override(t *testing.T) {
|
||||
Policy: &PolicyConfig{},
|
||||
API: &APIConfig{},
|
||||
Stats: &StatsConfig{},
|
||||
Reverse: &ReverseConfig{},
|
||||
Reverse: &legacyReverse,
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
_ "github.com/xtls/xray-core/app/log"
|
||||
_ "github.com/xtls/xray-core/app/metrics"
|
||||
_ "github.com/xtls/xray-core/app/policy"
|
||||
_ "github.com/xtls/xray-core/app/reverse"
|
||||
_ "github.com/xtls/xray-core/app/router"
|
||||
_ "github.com/xtls/xray-core/app/stats"
|
||||
|
||||
@@ -35,7 +34,6 @@ import (
|
||||
_ "github.com/xtls/xray-core/app/observatory"
|
||||
|
||||
// Inbound and outbound proxies.
|
||||
_ "github.com/xtls/xray-core/proxy/blackhole"
|
||||
_ "github.com/xtls/xray-core/proxy/dns"
|
||||
_ "github.com/xtls/xray-core/proxy/dokodemo"
|
||||
_ "github.com/xtls/xray-core/proxy/freedom"
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build coveragemain
|
||||
// +build coveragemain
|
||||
|
||||
package main
|
||||
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
// Package blackhole is an outbound handler that blocks all connections.
|
||||
package blackhole
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/dice"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
// Handler is an outbound connection that silently swallow the entire payload.
|
||||
type Handler struct {
|
||||
response []byte
|
||||
}
|
||||
|
||||
var http403response = http.Response{
|
||||
StatusCode: 403,
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{
|
||||
"Connection": {"close"},
|
||||
"Cache-Control": {"max-age=3600, public"},
|
||||
},
|
||||
}
|
||||
|
||||
// New creates a new blackhole handler.
|
||||
func New(ctx context.Context, config *Config) (*Handler, error) {
|
||||
response := []byte{}
|
||||
if config.Response != nil {
|
||||
switch config.Response.Type {
|
||||
case "", "none":
|
||||
case "http":
|
||||
var data bytes.Buffer
|
||||
common.Must(http403response.Write(&data))
|
||||
response = data.Bytes()
|
||||
case "custom":
|
||||
response = config.Response.CustomResponseData
|
||||
default:
|
||||
return nil, errors.New("unknown blackhole response: " + config.Response.Type)
|
||||
}
|
||||
}
|
||||
return &Handler{
|
||||
response: response,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Process implements OutboundHandler.Dispatch().
|
||||
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
ob := outbounds[len(outbounds)-1]
|
||||
ob.Name = "blackhole"
|
||||
|
||||
if len(h.response) > 0 {
|
||||
mbc := buf.MultiBufferContainer{}
|
||||
common.Must2(mbc.Write(h.response))
|
||||
link.Writer.WriteMultiBuffer(mbc.MultiBuffer)
|
||||
// Sleep a little here to make sure the response is sent to client.
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
defer common.Interrupt(link.Writer)
|
||||
defer common.Interrupt(link.Reader)
|
||||
// wait to drain all the possible incoming UDP data
|
||||
if ob.Target.Network == net.Network_UDP {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
}, time.Duration(30+dice.Roll(61))*time.Second)
|
||||
go buf.Copy(link.Reader, buf.Discard, buf.UpdateActivity(timer))
|
||||
<-ctx.Done()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
||||
return New(ctx, config.(*Config))
|
||||
}))
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package blackhole_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestBlackholeHTTPResponse(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{}})
|
||||
handler, err := blackhole.New(ctx, &blackhole.Config{
|
||||
Response: &blackhole.Response{Type: "http"},
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
|
||||
dataCh := make(chan buf.MultiBuffer, 1)
|
||||
go func() {
|
||||
mb := common.Must2(reader.ReadMultiBuffer())
|
||||
dataCh <- mb
|
||||
}()
|
||||
link := transport.Link{
|
||||
Reader: reader,
|
||||
Writer: writer,
|
||||
}
|
||||
common.Must(handler.Process(ctx, &link, nil))
|
||||
mb := <-dataCh
|
||||
data := make([]byte, mb.Len())
|
||||
mb.Copy(data)
|
||||
resp := common.Must2(http.ReadResponse(bufio.NewReader(bytes.NewBuffer(data)), nil))
|
||||
if resp.StatusCode != 403 {
|
||||
t.Errorf("expected 403 response, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlackholeCustomResponse(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{}})
|
||||
// slightly bigger than a buffer
|
||||
expected := make([]byte, buf.Size+1000)
|
||||
if _, err := rand.Read(expected); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler, err := blackhole.New(ctx, &blackhole.Config{
|
||||
Response: &blackhole.Response{
|
||||
Type: "custom",
|
||||
CustomResponseData: expected,
|
||||
},
|
||||
})
|
||||
common.Must(err)
|
||||
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
var actual buf.MultiBuffer
|
||||
var rerr error
|
||||
go func() {
|
||||
actual, rerr = reader.ReadMultiBuffer()
|
||||
}()
|
||||
|
||||
link := transport.Link{Reader: reader, Writer: writer}
|
||||
common.Must(handler.Process(ctx, &link, nil))
|
||||
common.Must(rerr)
|
||||
|
||||
if actual.String() != string(expected) {
|
||||
t.Errorf("custom response mismatch")
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.12
|
||||
// protoc (unknown)
|
||||
// source: proxy/blackhole/config.proto
|
||||
|
||||
package blackhole
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
|
||||
CustomResponseData []byte `protobuf:"bytes,2,opt,name=custom_response_data,json=customResponseData,proto3" json:"custom_response_data,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Response) Reset() {
|
||||
*x = Response{}
|
||||
mi := &file_proxy_blackhole_config_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Response) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Response) ProtoMessage() {}
|
||||
|
||||
func (x *Response) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_blackhole_config_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Response.ProtoReflect.Descriptor instead.
|
||||
func (*Response) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Response) GetType() string {
|
||||
if x != nil {
|
||||
return x.Type
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Response) GetCustomResponseData() []byte {
|
||||
if x != nil {
|
||||
return x.CustomResponseData
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Response *Response `protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
*x = Config{}
|
||||
mi := &file_proxy_blackhole_config_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Config) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Config) ProtoMessage() {}
|
||||
|
||||
func (x *Config) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_blackhole_config_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
|
||||
func (*Config) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *Config) GetResponse() *Response {
|
||||
if x != nil {
|
||||
return x.Response
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_proxy_blackhole_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_blackhole_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x1cproxy/blackhole/config.proto\x12\x14xray.proxy.blackhole\"P\n" +
|
||||
"\bResponse\x12\x12\n" +
|
||||
"\x04type\x18\x01 \x01(\tR\x04type\x120\n" +
|
||||
"\x14custom_response_data\x18\x02 \x01(\fR\x12customResponseData\"D\n" +
|
||||
"\x06Config\x12:\n" +
|
||||
"\bresponse\x18\x01 \x01(\v2\x1e.xray.proxy.blackhole.ResponseR\bresponseB^\n" +
|
||||
"\x18com.xray.proxy.blackholeP\x01Z)github.com/xtls/xray-core/proxy/blackhole\xaa\x02\x14Xray.Proxy.Blackholeb\x06proto3"
|
||||
|
||||
var (
|
||||
file_proxy_blackhole_config_proto_rawDescOnce sync.Once
|
||||
file_proxy_blackhole_config_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_proxy_blackhole_config_proto_rawDescGZIP() []byte {
|
||||
file_proxy_blackhole_config_proto_rawDescOnce.Do(func() {
|
||||
file_proxy_blackhole_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)))
|
||||
})
|
||||
return file_proxy_blackhole_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_proxy_blackhole_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_proxy_blackhole_config_proto_goTypes = []any{
|
||||
(*Response)(nil), // 0: xray.proxy.blackhole.Response
|
||||
(*Config)(nil), // 1: xray.proxy.blackhole.Config
|
||||
}
|
||||
var file_proxy_blackhole_config_proto_depIdxs = []int32{
|
||||
0, // 0: xray.proxy.blackhole.Config.response:type_name -> xray.proxy.blackhole.Response
|
||||
1, // [1:1] is the sub-list for method output_type
|
||||
1, // [1:1] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_blackhole_config_proto_init() }
|
||||
func file_proxy_blackhole_config_proto_init() {
|
||||
if File_proxy_blackhole_config_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_proxy_blackhole_config_proto_goTypes,
|
||||
DependencyIndexes: file_proxy_blackhole_config_proto_depIdxs,
|
||||
MessageInfos: file_proxy_blackhole_config_proto_msgTypes,
|
||||
}.Build()
|
||||
File_proxy_blackhole_config_proto = out.File
|
||||
file_proxy_blackhole_config_proto_goTypes = nil
|
||||
file_proxy_blackhole_config_proto_depIdxs = nil
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package xray.proxy.blackhole;
|
||||
option csharp_namespace = "Xray.Proxy.Blackhole";
|
||||
option go_package = "github.com/xtls/xray-core/proxy/blackhole";
|
||||
option java_package = "com.xray.proxy.blackhole";
|
||||
option java_multiple_files = true;
|
||||
|
||||
message Response {
|
||||
string type = 1;
|
||||
bytes custom_response_data = 2;
|
||||
}
|
||||
|
||||
message Config {
|
||||
Response response = 1;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package blackhole_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/proxy/blackhole"
|
||||
)
|
||||
|
||||
func TestHTTPResponse(t *testing.T) {
|
||||
handler, err := blackhole.New(context.Background(), &blackhole.Config{
|
||||
Response: &blackhole.Response{Type: "http"},
|
||||
})
|
||||
common.Must(err)
|
||||
if handler == nil {
|
||||
t.Error("expected HTTP response handler")
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package dokodemo
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build openbsd
|
||||
// +build openbsd
|
||||
|
||||
package dokodemo
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !linux && !openbsd
|
||||
// +build !linux,!openbsd
|
||||
|
||||
package dokodemo
|
||||
|
||||
|
||||
+130
-74
@@ -352,32 +352,28 @@ func (x *Range) GetMax() uint64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
type FinalRuleConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Action RuleAction `protobuf:"varint,1,opt,name=action,proto3,enum=xray.proxy.freedom.RuleAction" json:"action,omitempty"`
|
||||
Networks []net.Network `protobuf:"varint,2,rep,packed,name=networks,proto3,enum=xray.common.net.Network" json:"networks,omitempty"`
|
||||
PortList *net.PortList `protobuf:"bytes,3,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"`
|
||||
Ip []*geodata.IPRule `protobuf:"bytes,4,rep,name=ip,proto3" json:"ip,omitempty"`
|
||||
Delay *Range `protobuf:"bytes,5,opt,name=delay,proto3" json:"delay,omitempty"`
|
||||
LogLevel *log.Severity `protobuf:"varint,6,opt,name=log_level,json=logLevel,proto3,enum=xray.common.log.Severity,oneof" json:"log_level,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
type Reply struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
|
||||
CustomResponseData []byte `protobuf:"bytes,2,opt,name=custom_response_data,json=customResponseData,proto3" json:"custom_response_data,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *FinalRuleConfig) Reset() {
|
||||
*x = FinalRuleConfig{}
|
||||
func (x *Reply) Reset() {
|
||||
*x = Reply{}
|
||||
mi := &file_proxy_freedom_config_proto_msgTypes[4]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *FinalRuleConfig) String() string {
|
||||
func (x *Reply) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*FinalRuleConfig) ProtoMessage() {}
|
||||
func (*Reply) ProtoMessage() {}
|
||||
|
||||
func (x *FinalRuleConfig) ProtoReflect() protoreflect.Message {
|
||||
func (x *Reply) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_freedom_config_proto_msgTypes[4]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
@@ -389,69 +385,132 @@ func (x *FinalRuleConfig) ProtoReflect() protoreflect.Message {
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use FinalRuleConfig.ProtoReflect.Descriptor instead.
|
||||
func (*FinalRuleConfig) Descriptor() ([]byte, []int) {
|
||||
// Deprecated: Use Reply.ProtoReflect.Descriptor instead.
|
||||
func (*Reply) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{4}
|
||||
}
|
||||
|
||||
func (x *FinalRuleConfig) GetAction() RuleAction {
|
||||
func (x *Reply) GetType() string {
|
||||
if x != nil {
|
||||
return x.Type
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Reply) GetCustomResponseData() []byte {
|
||||
if x != nil {
|
||||
return x.CustomResponseData
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type FirewallConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Action RuleAction `protobuf:"varint,1,opt,name=action,proto3,enum=xray.proxy.freedom.RuleAction" json:"action,omitempty"`
|
||||
Networks []net.Network `protobuf:"varint,2,rep,packed,name=networks,proto3,enum=xray.common.net.Network" json:"networks,omitempty"`
|
||||
PortList *net.PortList `protobuf:"bytes,3,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"`
|
||||
Ip []*geodata.IPRule `protobuf:"bytes,4,rep,name=ip,proto3" json:"ip,omitempty"`
|
||||
Delay *Range `protobuf:"bytes,5,opt,name=delay,proto3" json:"delay,omitempty"`
|
||||
LogLevel *log.Severity `protobuf:"varint,6,opt,name=log_level,json=logLevel,proto3,enum=xray.common.log.Severity,oneof" json:"log_level,omitempty"`
|
||||
Reply *Reply `protobuf:"bytes,7,opt,name=reply,proto3" json:"reply,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *FirewallConfig) Reset() {
|
||||
*x = FirewallConfig{}
|
||||
mi := &file_proxy_freedom_config_proto_msgTypes[5]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *FirewallConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*FirewallConfig) ProtoMessage() {}
|
||||
|
||||
func (x *FirewallConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_freedom_config_proto_msgTypes[5]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use FirewallConfig.ProtoReflect.Descriptor instead.
|
||||
func (*FirewallConfig) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{5}
|
||||
}
|
||||
|
||||
func (x *FirewallConfig) GetAction() RuleAction {
|
||||
if x != nil {
|
||||
return x.Action
|
||||
}
|
||||
return RuleAction_Allow
|
||||
}
|
||||
|
||||
func (x *FinalRuleConfig) GetNetworks() []net.Network {
|
||||
func (x *FirewallConfig) GetNetworks() []net.Network {
|
||||
if x != nil {
|
||||
return x.Networks
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *FinalRuleConfig) GetPortList() *net.PortList {
|
||||
func (x *FirewallConfig) GetPortList() *net.PortList {
|
||||
if x != nil {
|
||||
return x.PortList
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *FinalRuleConfig) GetIp() []*geodata.IPRule {
|
||||
func (x *FirewallConfig) GetIp() []*geodata.IPRule {
|
||||
if x != nil {
|
||||
return x.Ip
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *FinalRuleConfig) GetDelay() *Range {
|
||||
func (x *FirewallConfig) GetDelay() *Range {
|
||||
if x != nil {
|
||||
return x.Delay
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *FinalRuleConfig) GetLogLevel() log.Severity {
|
||||
func (x *FirewallConfig) GetLogLevel() log.Severity {
|
||||
if x != nil && x.LogLevel != nil {
|
||||
return *x.LogLevel
|
||||
}
|
||||
return log.Severity(0)
|
||||
}
|
||||
|
||||
func (x *FirewallConfig) GetReply() *Reply {
|
||||
if x != nil {
|
||||
return x.Reply
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
DomainStrategy internet.DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"domain_strategy,omitempty"`
|
||||
DestinationOverride *DestinationOverride `protobuf:"bytes,3,opt,name=destination_override,json=destinationOverride,proto3" json:"destination_override,omitempty"`
|
||||
UserLevel uint32 `protobuf:"varint,4,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
|
||||
Fragment *Fragment `protobuf:"bytes,5,opt,name=fragment,proto3" json:"fragment,omitempty"`
|
||||
ProxyProtocol uint32 `protobuf:"varint,6,opt,name=proxy_protocol,json=proxyProtocol,proto3" json:"proxy_protocol,omitempty"`
|
||||
Noises []*Noise `protobuf:"bytes,7,rep,name=noises,proto3" json:"noises,omitempty"`
|
||||
FinalRules []*FinalRuleConfig `protobuf:"bytes,8,rep,name=final_rules,json=finalRules,proto3" json:"final_rules,omitempty"`
|
||||
Firewall []*FirewallConfig `protobuf:"bytes,8,rep,name=firewall,proto3" json:"firewall,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
*x = Config{}
|
||||
mi := &file_proxy_freedom_config_proto_msgTypes[5]
|
||||
mi := &file_proxy_freedom_config_proto_msgTypes[6]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -463,7 +522,7 @@ func (x *Config) String() string {
|
||||
func (*Config) ProtoMessage() {}
|
||||
|
||||
func (x *Config) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_proxy_freedom_config_proto_msgTypes[5]
|
||||
mi := &file_proxy_freedom_config_proto_msgTypes[6]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -476,7 +535,7 @@ func (x *Config) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
|
||||
func (*Config) Descriptor() ([]byte, []int) {
|
||||
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{5}
|
||||
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{6}
|
||||
}
|
||||
|
||||
func (x *Config) GetDomainStrategy() internet.DomainStrategy {
|
||||
@@ -507,13 +566,6 @@ func (x *Config) GetFragment() *Fragment {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetProxyProtocol() uint32 {
|
||||
if x != nil {
|
||||
return x.ProxyProtocol
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Config) GetNoises() []*Noise {
|
||||
if x != nil {
|
||||
return x.Noises
|
||||
@@ -521,9 +573,9 @@ func (x *Config) GetNoises() []*Noise {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetFinalRules() []*FinalRuleConfig {
|
||||
func (x *Config) GetFirewall() []*FirewallConfig {
|
||||
if x != nil {
|
||||
return x.FinalRules
|
||||
return x.Firewall
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -558,26 +610,28 @@ const file_proxy_freedom_config_proto_rawDesc = "" +
|
||||
"\bapply_to\x18\x06 \x01(\tR\aapplyTo\"+\n" +
|
||||
"\x05Range\x12\x10\n" +
|
||||
"\x03min\x18\x01 \x01(\x04R\x03min\x12\x10\n" +
|
||||
"\x03max\x18\x02 \x01(\x04R\x03max\"\xe0\x02\n" +
|
||||
"\x0fFinalRuleConfig\x126\n" +
|
||||
"\x03max\x18\x02 \x01(\x04R\x03max\"M\n" +
|
||||
"\x05Reply\x12\x12\n" +
|
||||
"\x04type\x18\x01 \x01(\tR\x04type\x120\n" +
|
||||
"\x14custom_response_data\x18\x02 \x01(\fR\x12customResponseData\"\x90\x03\n" +
|
||||
"\x0eFirewallConfig\x126\n" +
|
||||
"\x06action\x18\x01 \x01(\x0e2\x1e.xray.proxy.freedom.RuleActionR\x06action\x124\n" +
|
||||
"\bnetworks\x18\x02 \x03(\x0e2\x18.xray.common.net.NetworkR\bnetworks\x126\n" +
|
||||
"\tport_list\x18\x03 \x01(\v2\x19.xray.common.net.PortListR\bportList\x12+\n" +
|
||||
"\x02ip\x18\x04 \x03(\v2\x1b.xray.common.geodata.IPRuleR\x02ip\x12/\n" +
|
||||
"\x05delay\x18\x05 \x01(\v2\x19.xray.proxy.freedom.RangeR\x05delay\x12;\n" +
|
||||
"\tlog_level\x18\x06 \x01(\x0e2\x19.xray.common.log.SeverityH\x00R\blogLevel\x88\x01\x01B\f\n" +
|
||||
"\tlog_level\x18\x06 \x01(\x0e2\x19.xray.common.log.SeverityH\x00R\blogLevel\x88\x01\x01\x12/\n" +
|
||||
"\x05reply\x18\a \x01(\v2\x19.xray.proxy.freedom.ReplyR\x05replyB\f\n" +
|
||||
"\n" +
|
||||
"_log_level\"\xaf\x03\n" +
|
||||
"_log_level\"\x88\x03\n" +
|
||||
"\x06Config\x12P\n" +
|
||||
"\x0fdomain_strategy\x18\x01 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0edomainStrategy\x12Z\n" +
|
||||
"\x14destination_override\x18\x03 \x01(\v2'.xray.proxy.freedom.DestinationOverrideR\x13destinationOverride\x12\x1d\n" +
|
||||
"\n" +
|
||||
"user_level\x18\x04 \x01(\rR\tuserLevel\x128\n" +
|
||||
"\bfragment\x18\x05 \x01(\v2\x1c.xray.proxy.freedom.FragmentR\bfragment\x12%\n" +
|
||||
"\x0eproxy_protocol\x18\x06 \x01(\rR\rproxyProtocol\x121\n" +
|
||||
"\x06noises\x18\a \x03(\v2\x19.xray.proxy.freedom.NoiseR\x06noises\x12D\n" +
|
||||
"\vfinal_rules\x18\b \x03(\v2#.xray.proxy.freedom.FinalRuleConfigR\n" +
|
||||
"finalRules*\"\n" +
|
||||
"\bfragment\x18\x05 \x01(\v2\x1c.xray.proxy.freedom.FragmentR\bfragment\x121\n" +
|
||||
"\x06noises\x18\a \x03(\v2\x19.xray.proxy.freedom.NoiseR\x06noises\x12>\n" +
|
||||
"\bfirewall\x18\b \x03(\v2\".xray.proxy.freedom.FirewallConfigR\bfirewallJ\x04\b\x06\x10\a*\"\n" +
|
||||
"\n" +
|
||||
"RuleAction\x12\t\n" +
|
||||
"\x05Allow\x10\x00\x12\t\n" +
|
||||
@@ -597,40 +651,42 @@ func file_proxy_freedom_config_proto_rawDescGZIP() []byte {
|
||||
}
|
||||
|
||||
var file_proxy_freedom_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||
var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
|
||||
var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
|
||||
var file_proxy_freedom_config_proto_goTypes = []any{
|
||||
(RuleAction)(0), // 0: xray.proxy.freedom.RuleAction
|
||||
(*DestinationOverride)(nil), // 1: xray.proxy.freedom.DestinationOverride
|
||||
(*Fragment)(nil), // 2: xray.proxy.freedom.Fragment
|
||||
(*Noise)(nil), // 3: xray.proxy.freedom.Noise
|
||||
(*Range)(nil), // 4: xray.proxy.freedom.Range
|
||||
(*FinalRuleConfig)(nil), // 5: xray.proxy.freedom.FinalRuleConfig
|
||||
(*Config)(nil), // 6: xray.proxy.freedom.Config
|
||||
(*protocol.ServerEndpoint)(nil), // 7: xray.common.protocol.ServerEndpoint
|
||||
(net.Network)(0), // 8: xray.common.net.Network
|
||||
(*net.PortList)(nil), // 9: xray.common.net.PortList
|
||||
(*geodata.IPRule)(nil), // 10: xray.common.geodata.IPRule
|
||||
(log.Severity)(0), // 11: xray.common.log.Severity
|
||||
(internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy
|
||||
(*Reply)(nil), // 5: xray.proxy.freedom.Reply
|
||||
(*FirewallConfig)(nil), // 6: xray.proxy.freedom.FirewallConfig
|
||||
(*Config)(nil), // 7: xray.proxy.freedom.Config
|
||||
(*protocol.ServerEndpoint)(nil), // 8: xray.common.protocol.ServerEndpoint
|
||||
(net.Network)(0), // 9: xray.common.net.Network
|
||||
(*net.PortList)(nil), // 10: xray.common.net.PortList
|
||||
(*geodata.IPRule)(nil), // 11: xray.common.geodata.IPRule
|
||||
(log.Severity)(0), // 12: xray.common.log.Severity
|
||||
(internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy
|
||||
}
|
||||
var file_proxy_freedom_config_proto_depIdxs = []int32{
|
||||
7, // 0: xray.proxy.freedom.DestinationOverride.server:type_name -> xray.common.protocol.ServerEndpoint
|
||||
0, // 1: xray.proxy.freedom.FinalRuleConfig.action:type_name -> xray.proxy.freedom.RuleAction
|
||||
8, // 2: xray.proxy.freedom.FinalRuleConfig.networks:type_name -> xray.common.net.Network
|
||||
9, // 3: xray.proxy.freedom.FinalRuleConfig.port_list:type_name -> xray.common.net.PortList
|
||||
10, // 4: xray.proxy.freedom.FinalRuleConfig.ip:type_name -> xray.common.geodata.IPRule
|
||||
4, // 5: xray.proxy.freedom.FinalRuleConfig.delay:type_name -> xray.proxy.freedom.Range
|
||||
11, // 6: xray.proxy.freedom.FinalRuleConfig.log_level:type_name -> xray.common.log.Severity
|
||||
12, // 7: xray.proxy.freedom.Config.domain_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||
1, // 8: xray.proxy.freedom.Config.destination_override:type_name -> xray.proxy.freedom.DestinationOverride
|
||||
2, // 9: xray.proxy.freedom.Config.fragment:type_name -> xray.proxy.freedom.Fragment
|
||||
3, // 10: xray.proxy.freedom.Config.noises:type_name -> xray.proxy.freedom.Noise
|
||||
5, // 11: xray.proxy.freedom.Config.final_rules:type_name -> xray.proxy.freedom.FinalRuleConfig
|
||||
12, // [12:12] is the sub-list for method output_type
|
||||
12, // [12:12] is the sub-list for method input_type
|
||||
12, // [12:12] is the sub-list for extension type_name
|
||||
12, // [12:12] is the sub-list for extension extendee
|
||||
0, // [0:12] is the sub-list for field type_name
|
||||
8, // 0: xray.proxy.freedom.DestinationOverride.server:type_name -> xray.common.protocol.ServerEndpoint
|
||||
0, // 1: xray.proxy.freedom.FirewallConfig.action:type_name -> xray.proxy.freedom.RuleAction
|
||||
9, // 2: xray.proxy.freedom.FirewallConfig.networks:type_name -> xray.common.net.Network
|
||||
10, // 3: xray.proxy.freedom.FirewallConfig.port_list:type_name -> xray.common.net.PortList
|
||||
11, // 4: xray.proxy.freedom.FirewallConfig.ip:type_name -> xray.common.geodata.IPRule
|
||||
4, // 5: xray.proxy.freedom.FirewallConfig.delay:type_name -> xray.proxy.freedom.Range
|
||||
12, // 6: xray.proxy.freedom.FirewallConfig.log_level:type_name -> xray.common.log.Severity
|
||||
5, // 7: xray.proxy.freedom.FirewallConfig.reply:type_name -> xray.proxy.freedom.Reply
|
||||
13, // 8: xray.proxy.freedom.Config.domain_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||
1, // 9: xray.proxy.freedom.Config.destination_override:type_name -> xray.proxy.freedom.DestinationOverride
|
||||
2, // 10: xray.proxy.freedom.Config.fragment:type_name -> xray.proxy.freedom.Fragment
|
||||
3, // 11: xray.proxy.freedom.Config.noises:type_name -> xray.proxy.freedom.Noise
|
||||
6, // 12: xray.proxy.freedom.Config.firewall:type_name -> xray.proxy.freedom.FirewallConfig
|
||||
13, // [13:13] is the sub-list for method output_type
|
||||
13, // [13:13] is the sub-list for method input_type
|
||||
13, // [13:13] is the sub-list for extension type_name
|
||||
13, // [13:13] is the sub-list for extension extendee
|
||||
0, // [0:13] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_proxy_freedom_config_proto_init() }
|
||||
@@ -638,14 +694,14 @@ func file_proxy_freedom_config_proto_init() {
|
||||
if File_proxy_freedom_config_proto != nil {
|
||||
return
|
||||
}
|
||||
file_proxy_freedom_config_proto_msgTypes[4].OneofWrappers = []any{}
|
||||
file_proxy_freedom_config_proto_msgTypes[5].OneofWrappers = []any{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_freedom_config_proto_rawDesc), len(file_proxy_freedom_config_proto_rawDesc)),
|
||||
NumEnums: 1,
|
||||
NumMessages: 6,
|
||||
NumMessages: 7,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
|
||||
@@ -47,21 +47,27 @@ enum RuleAction {
|
||||
Block = 1;
|
||||
}
|
||||
|
||||
message FinalRuleConfig {
|
||||
message Reply {
|
||||
string type = 1;
|
||||
bytes custom_response_data = 2;
|
||||
}
|
||||
|
||||
message FirewallConfig {
|
||||
RuleAction action = 1;
|
||||
repeated xray.common.net.Network networks = 2;
|
||||
xray.common.net.PortList port_list = 3;
|
||||
repeated xray.common.geodata.IPRule ip = 4;
|
||||
Range delay = 5;
|
||||
optional xray.common.log.Severity log_level = 6;
|
||||
Reply reply = 7;
|
||||
}
|
||||
|
||||
message Config {
|
||||
reserved 6;
|
||||
xray.transport.internet.DomainStrategy domain_strategy = 1;
|
||||
DestinationOverride destination_override = 3;
|
||||
uint32 user_level = 4;
|
||||
Fragment fragment = 5;
|
||||
uint32 proxy_protocol = 6;
|
||||
repeated Noise noises = 7;
|
||||
repeated FinalRuleConfig final_rules = 8;
|
||||
repeated FirewallConfig firewall = 8;
|
||||
}
|
||||
|
||||
+88
-54
@@ -1,14 +1,15 @@
|
||||
package freedom
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/pires/go-proxyproto"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/crypto"
|
||||
@@ -35,10 +36,20 @@ import (
|
||||
var (
|
||||
useSplice atomic.Bool
|
||||
allNetworks [8]bool
|
||||
defaultBlockPrivateRule *FinalRule
|
||||
defaultBlockAllRule *FinalRule
|
||||
defaultBlockPrivateRule *Firewall
|
||||
defaultBlockAllRule *Firewall
|
||||
)
|
||||
|
||||
var http403response = http.Response{
|
||||
StatusCode: 403,
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{
|
||||
"Connection": {"close"},
|
||||
"Cache-Control": {"max-age=3600, public"},
|
||||
},
|
||||
}
|
||||
|
||||
func reloadEnvSettings() error {
|
||||
const defaultFlagValue = "NOT_DEFINED_AT_ALL"
|
||||
value := platform.NewEnvFlag(platform.UseFreedomSplice).GetValue(func() string { return defaultFlagValue })
|
||||
@@ -72,45 +83,60 @@ func init() {
|
||||
allNetworks[i] = true
|
||||
}
|
||||
|
||||
defaultBlockPrivateRule = &FinalRule{
|
||||
defaultBlockPrivateRule = &Firewall{
|
||||
action: RuleAction_Block,
|
||||
network: allNetworks,
|
||||
ip: geodata.GetPrivateIPMatcher(),
|
||||
logLevel: log.Severity_Warning.Enum(),
|
||||
}
|
||||
|
||||
defaultBlockAllRule = &FinalRule{
|
||||
defaultBlockAllRule = &Firewall{
|
||||
action: RuleAction_Block,
|
||||
network: allNetworks,
|
||||
logLevel: log.Severity_Warning.Enum(),
|
||||
}
|
||||
}
|
||||
|
||||
type FinalRule struct {
|
||||
type Firewall struct {
|
||||
action RuleAction
|
||||
network [8]bool
|
||||
port net.MemoryPortList
|
||||
ip geodata.IPMatcher
|
||||
delay *Range
|
||||
logLevel *log.Severity
|
||||
reply []byte
|
||||
}
|
||||
|
||||
// Handler handles Freedom connections.
|
||||
type Handler struct {
|
||||
policyManager policy.Manager
|
||||
config *Config
|
||||
finalRules []*FinalRule
|
||||
firewall []*Firewall
|
||||
resolveStrategy internet.DomainStrategy
|
||||
usesDialerProxy bool
|
||||
}
|
||||
|
||||
func buildFinalRule(config *FinalRuleConfig) (*FinalRule, error) {
|
||||
rule := &FinalRule{
|
||||
func buildRule(config *FirewallConfig) (*Firewall, error) {
|
||||
rule := &Firewall{
|
||||
action: config.GetAction(),
|
||||
delay: config.GetDelay(),
|
||||
logLevel: config.LogLevel,
|
||||
}
|
||||
|
||||
if config.Reply != nil {
|
||||
switch config.Reply.Type {
|
||||
case "", "none":
|
||||
case "http":
|
||||
var data bytes.Buffer
|
||||
common.Must(http403response.Write(&data))
|
||||
rule.reply = data.Bytes()
|
||||
case "custom":
|
||||
rule.reply = config.Reply.CustomResponseData
|
||||
default:
|
||||
return nil, errors.New("unknown firewall reply: " + config.Reply.Type)
|
||||
}
|
||||
}
|
||||
|
||||
if len(config.Networks) == 0 {
|
||||
rule.network = allNetworks
|
||||
} else {
|
||||
@@ -134,25 +160,25 @@ func buildFinalRule(config *FinalRuleConfig) (*FinalRule, error) {
|
||||
return rule, nil
|
||||
}
|
||||
|
||||
func (r *FinalRule) matchNetwork(network net.Network) bool {
|
||||
func (r *Firewall) matchNetwork(network net.Network) bool {
|
||||
return r.network[int(network)]
|
||||
}
|
||||
|
||||
func (r *FinalRule) matchPort(port net.Port) bool {
|
||||
func (r *Firewall) matchPort(port net.Port) bool {
|
||||
if len(r.port) == 0 {
|
||||
return true
|
||||
}
|
||||
return r.port.Contains(port)
|
||||
}
|
||||
|
||||
func (r *FinalRule) matchIP(addr net.Address) bool {
|
||||
func (r *Firewall) matchIP(addr net.Address) bool {
|
||||
if r.ip == nil {
|
||||
return true
|
||||
}
|
||||
return addr != nil && addr.Family().IsIP() && r.ip.Match(addr.IP())
|
||||
}
|
||||
|
||||
func (r *FinalRule) Apply(network net.Network, address net.Address, port net.Port) bool {
|
||||
func (r *Firewall) Apply(network net.Network, address net.Address, port net.Port) bool {
|
||||
if !r.matchNetwork(network) {
|
||||
return false
|
||||
}
|
||||
@@ -162,7 +188,7 @@ func (r *FinalRule) Apply(network net.Network, address net.Address, port net.Por
|
||||
return r.matchIP(address)
|
||||
}
|
||||
|
||||
func getDefaultFinalRule(inbound *session.Inbound) *FinalRule {
|
||||
func getDefaultRule(inbound *session.Inbound) *Firewall {
|
||||
if inbound == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -179,8 +205,8 @@ func getDefaultFinalRule(inbound *session.Inbound) *FinalRule {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) matchFinalRule(network net.Network, address net.Address, port net.Port, defaultRule *FinalRule) *FinalRule {
|
||||
for _, rule := range h.finalRules {
|
||||
func (h *Handler) matchRule(network net.Network, address net.Address, port net.Port, defaultRule *Firewall) *Firewall {
|
||||
for _, rule := range h.firewall {
|
||||
if rule.Apply(network, address, port) {
|
||||
return rule
|
||||
}
|
||||
@@ -195,19 +221,19 @@ func (h *Handler) matchFinalRule(network net.Network, address net.Address, port
|
||||
func (h *Handler) Init(config *Config, pm policy.Manager) error {
|
||||
h.config = config
|
||||
h.policyManager = pm
|
||||
if h.usesDialerProxy { // freedom is not the final outbound, final rules do not apply
|
||||
if len(config.FinalRules) > 0 {
|
||||
errors.LogWarning(context.Background(), `The "finalRules" setting is ignored when "sockopt.dialerProxy" is set, since freedom is not the final outbound.`)
|
||||
if h.usesDialerProxy { // freedom is not the final outbound, firewall does not apply
|
||||
if len(config.Firewall) > 0 {
|
||||
errors.LogWarning(context.Background(), `The "firewall" setting is ignored when "sockopt.dialerProxy" is set, since freedom is not the final outbound.`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
h.finalRules = make([]*FinalRule, 0, len(config.FinalRules))
|
||||
for _, rc := range config.FinalRules {
|
||||
rule, err := buildFinalRule(rc)
|
||||
h.firewall = make([]*Firewall, 0, len(config.Firewall))
|
||||
for _, rc := range config.Firewall {
|
||||
rule, err := buildRule(rc)
|
||||
if err != nil {
|
||||
return errors.New("failed to build final rule").Base(err)
|
||||
return errors.New("failed to build firewall rule").Base(err)
|
||||
}
|
||||
h.finalRules = append(h.finalRules, rule)
|
||||
h.firewall = append(h.firewall, rule)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -217,7 +243,7 @@ func (h *Handler) policy() policy.Session {
|
||||
return p
|
||||
}
|
||||
|
||||
func (r *FinalRule) blockDuration() time.Duration {
|
||||
func (r *Firewall) blockDuration() time.Duration {
|
||||
min := uint64(30)
|
||||
max := uint64(90)
|
||||
if r.delay != nil {
|
||||
@@ -231,7 +257,7 @@ func (r *FinalRule) blockDuration() time.Duration {
|
||||
return time.Duration(min+uint64(dice.Roll(int(span+1)))) * time.Second
|
||||
}
|
||||
|
||||
func (r *FinalRule) log(ctx context.Context, msg ...interface{}) {
|
||||
func (r *Firewall) log(ctx context.Context, msg ...interface{}) {
|
||||
level := log.Severity_Info
|
||||
if r.logLevel != nil {
|
||||
level = *r.logLevel
|
||||
@@ -248,10 +274,17 @@ func (r *FinalRule) log(ctx context.Context, msg ...interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *FinalRule, dest *net.Destination) error {
|
||||
func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *Firewall, dest *net.Destination) error {
|
||||
delay := rule.blockDuration()
|
||||
rule.log(ctx, "target blocked by a finalrule: ", *dest, ", blackholing connection for ", delay)
|
||||
rule.log(ctx, "target blocked by a firewall rule: ", *dest, ", blackholing connection for ", delay)
|
||||
defer common.Close(output)
|
||||
if len(rule.reply) > 0 {
|
||||
mbc := buf.MultiBufferContainer{}
|
||||
common.Must2(mbc.Write(rule.reply))
|
||||
output.WriteMultiBuffer(mbc.MultiBuffer)
|
||||
// Sleep a little here to make sure the reply is sent to client.
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { // a DispatchLink inbound's reader ignores Interrupt, so don't wait for this copy
|
||||
_ = buf.Copy(input, buf.Discard)
|
||||
@@ -285,10 +318,17 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
ob.Name = "freedom"
|
||||
ob.CanSpliceCopy = 1
|
||||
|
||||
if !h.usesDialerProxy && len(h.firewall) > 0 {
|
||||
rule := h.firewall[0]
|
||||
if rule.action == RuleAction_Block && rule.network == allNetworks && len(rule.port) == 0 && rule.ip == nil {
|
||||
return h.blackhole(ctx, link.Reader, link.Writer, rule, &ob.Target)
|
||||
}
|
||||
}
|
||||
inbound := session.InboundFromContext(ctx)
|
||||
var defaultRule *FinalRule
|
||||
if !h.usesDialerProxy { // freedom is not the final outbound, final rules do not apply (and the domain is not resolved)
|
||||
defaultRule = getDefaultFinalRule(inbound)
|
||||
var defaultRule *Firewall
|
||||
if !h.usesDialerProxy { // freedom is not the final outbound, firewall does not apply (and the domain is not resolved)
|
||||
defaultRule = getDefaultRule(inbound)
|
||||
}
|
||||
|
||||
destination := ob.Target
|
||||
@@ -311,15 +351,19 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
}
|
||||
|
||||
if h.resolveStrategy.HasStrategy() && session.SkipDNSResolveFromContext(ctx) {
|
||||
errors.LogInfo(ctx, "DNS-origin connection to ", destination, " may recursively resolve with sockopt.domainStrategy ", h.resolveStrategy)
|
||||
}
|
||||
|
||||
input := link.Reader
|
||||
output := link.Writer
|
||||
|
||||
var conn stat.Connection
|
||||
var blockedDest *net.Destination
|
||||
var blockedRule *FinalRule
|
||||
var blockedRule *Firewall
|
||||
err := retry.ExponentialBackoff(5, 100).On(func() error {
|
||||
if destination.Address.Family().IsDomain() {
|
||||
if defaultRule != nil || len(h.finalRules) > 0 {
|
||||
if defaultRule != nil || len(h.firewall) > 0 {
|
||||
if strategy := h.resolveStrategy; strategy.HasStrategy() {
|
||||
ips, err := internet.LookupForIP(destination.Address.Domain(), strategy, outGateway)
|
||||
if err != nil { // non-force may still dial with system DNS
|
||||
@@ -330,7 +374,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if addr := net.IPAddress(ip); addr != nil {
|
||||
if rule := h.matchFinalRule(destination.Network, addr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
if rule := h.matchRule(destination.Network, addr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
blockedDest = &destination
|
||||
blockedDest.Address = addr
|
||||
blockedRule = rule
|
||||
@@ -345,7 +389,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
for _, addr := range addrs {
|
||||
if ipAddr := net.IPAddress(addr.IP); ipAddr != nil {
|
||||
if rule := h.matchFinalRule(destination.Network, ipAddr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
if rule := h.matchRule(destination.Network, ipAddr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
blockedDest = &destination
|
||||
blockedDest.Address = ipAddr
|
||||
blockedRule = rule
|
||||
@@ -356,7 +400,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if rule := h.matchFinalRule(destination.Network, destination.Address, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
if rule := h.matchRule(destination.Network, destination.Address, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
blockedDest = &destination
|
||||
blockedRule = rule
|
||||
return nil
|
||||
@@ -377,25 +421,15 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
if blockedDest != nil {
|
||||
return h.blackhole(ctx, input, output, blockedRule, blockedDest)
|
||||
}
|
||||
if destination.Address.Family().IsDomain() && (defaultRule != nil || len(h.finalRules) > 0) {
|
||||
if destination.Address.Family().IsDomain() && (defaultRule != nil || len(h.firewall) > 0) {
|
||||
// pre-check may fail or dialer may select another IP
|
||||
remoteDest := net.DestinationFromAddr(conn.RemoteAddr())
|
||||
if rule := h.matchFinalRule(remoteDest.Network, remoteDest.Address, remoteDest.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
if rule := h.matchRule(remoteDest.Network, remoteDest.Address, remoteDest.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
conn.Close()
|
||||
return h.blackhole(ctx, input, output, rule, &remoteDest)
|
||||
}
|
||||
}
|
||||
|
||||
if h.config.ProxyProtocol > 0 && h.config.ProxyProtocol <= 2 {
|
||||
version := byte(h.config.ProxyProtocol)
|
||||
srcAddr := inbound.Source.RawNetAddr()
|
||||
dstAddr := conn.RemoteAddr()
|
||||
header := proxyproto.HeaderProxyFromAddrs(version, srcAddr, dstAddr)
|
||||
if _, err = header.WriteTo(conn); err != nil {
|
||||
conn.Close()
|
||||
return errors.New("failed to set PROXY protocol v", version).Base(err)
|
||||
}
|
||||
}
|
||||
defer conn.Close()
|
||||
errors.LogInfo(ctx, "connection opened to ", destination, ", local endpoint ", conn.LocalAddr(), ", remote endpoint ", conn.RemoteAddr())
|
||||
|
||||
@@ -484,7 +518,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewPacketReader(conn net.Conn, h *Handler, defaultRule *FinalRule, UDPOverride net.Destination, DialDest net.Destination) buf.Reader {
|
||||
func NewPacketReader(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverride net.Destination, DialDest net.Destination) buf.Reader {
|
||||
iConn := conn
|
||||
statConn, ok := iConn.(*stat.CounterConnection)
|
||||
if ok {
|
||||
@@ -517,7 +551,7 @@ type PacketReader struct {
|
||||
*net.PacketConnWrapper
|
||||
stats.Counter
|
||||
Handler *Handler
|
||||
DefaultRule *FinalRule
|
||||
DefaultRule *Firewall
|
||||
IsOverridden bool
|
||||
InitUnchangedAddr net.Address
|
||||
InitChangedAddr net.Address
|
||||
@@ -534,7 +568,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
}
|
||||
udpAddr := d.(*net.UDPAddr)
|
||||
sourceAddr := net.IPAddress(udpAddr.IP)
|
||||
if rule := r.Handler.matchFinalRule(net.Network_UDP, sourceAddr, net.Port(udpAddr.Port), r.DefaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
if rule := r.Handler.matchRule(net.Network_UDP, sourceAddr, net.Port(udpAddr.Port), r.DefaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
continue
|
||||
}
|
||||
b.Resize(0, int32(n))
|
||||
@@ -559,7 +593,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
}
|
||||
|
||||
// DialDest means the dial target used in the dialer when creating conn
|
||||
func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *FinalRule, UDPOverride net.Destination, DialDest net.Destination, outGateway net.Address) buf.Writer {
|
||||
func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverride net.Destination, DialDest net.Destination, outGateway net.Address) buf.Writer {
|
||||
iConn := conn
|
||||
statConn, ok := iConn.(*stat.CounterConnection)
|
||||
if ok {
|
||||
@@ -593,7 +627,7 @@ type PacketWriter struct {
|
||||
*net.PacketConnWrapper
|
||||
stats.Counter
|
||||
*Handler
|
||||
DefaultRule *FinalRule
|
||||
DefaultRule *Firewall
|
||||
UDPOverride net.Destination
|
||||
|
||||
// Dest of udp packets might be a domain, we will resolve them to IP
|
||||
@@ -652,7 +686,7 @@ func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
if rule := w.matchFinalRule(net.Network_UDP, b.UDP.Address, b.UDP.Port, w.DefaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
if rule := w.matchRule(net.Network_UDP, b.UDP.Address, b.UDP.Port, w.DefaultRule); rule != nil && rule.action == RuleAction_Block {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package freedom
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
func TestUnconditionalBlockFastPath(t *testing.T) {
|
||||
for _, network := range []net.Network{net.Network_TCP, net.Network_UDP} {
|
||||
t.Run(network.String(), func(t *testing.T) {
|
||||
const reply = "blocked"
|
||||
h := new(Handler)
|
||||
if err := h.Init(&Config{Firewall: []*FirewallConfig{{
|
||||
Action: RuleAction_Block,
|
||||
Delay: &Range{},
|
||||
Reply: &Reply{Type: "custom", CustomResponseData: []byte(reply)},
|
||||
}}}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.Destination{Network: network, Address: net.DomainAddress("blocked.invalid"), Port: 443},
|
||||
}})
|
||||
var output bytes.Buffer
|
||||
link := &transport.Link{
|
||||
Reader: buf.NewReader(bytes.NewReader(nil)),
|
||||
Writer: &buf.BufferToBytesWriter{Writer: &output},
|
||||
}
|
||||
// An unconditional block must finish without touching the dialer or resolving the domain.
|
||||
if err := h.Process(ctx, link, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if output.String() != reply {
|
||||
t.Fatalf("reply = %q, want %q", output.String(), reply)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFirewallReply(t *testing.T) {
|
||||
custom := bytes.Repeat([]byte("custom response"), buf.Size)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
reply *Reply
|
||||
want []byte
|
||||
}{
|
||||
{name: "default"},
|
||||
{name: "none", reply: &Reply{Type: "none"}},
|
||||
{name: "http", reply: &Reply{Type: "http"}},
|
||||
{name: "custom", reply: &Reply{Type: "custom", CustomResponseData: custom}, want: custom},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
rule, err := buildRule(&FirewallConfig{
|
||||
Action: RuleAction_Block,
|
||||
Delay: &Range{},
|
||||
Reply: test.reply,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output bytes.Buffer
|
||||
dest := net.TCPDestination(net.LocalHostIP, 80)
|
||||
if err := new(Handler).blackhole(context.Background(), buf.NewReader(bytes.NewReader(nil)), &buf.BufferToBytesWriter{Writer: &output}, rule, &dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if test.name == "http" {
|
||||
response, err := http.ReadResponse(bufio.NewReader(&output), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("HTTP status = %d, want 403", response.StatusCode)
|
||||
}
|
||||
} else if !bytes.Equal(output.Bytes(), test.want) {
|
||||
t.Fatalf("reply has %d bytes, want %d", output.Len(), len(test.want))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -150,6 +150,7 @@ Start:
|
||||
To: request.URL,
|
||||
Status: log.AccessAccepted,
|
||||
Reason: "",
|
||||
Email: inbound.User.Email,
|
||||
})
|
||||
|
||||
if strings.EqualFold(request.Method, "CONNECT") {
|
||||
|
||||
@@ -30,7 +30,7 @@ func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet
|
||||
|
||||
errors.LogInfo(ctx, "opening connection to ", destination)
|
||||
content := new(session.Content)
|
||||
content.SkipDNSResolve = true
|
||||
content.SkipDNSResolve = session.SkipDNSResolveFromContext(ctx)
|
||||
content.SniffingRequest = l.sniffingRequest
|
||||
|
||||
ctx = session.ContextWithContent(ctx, content)
|
||||
|
||||
@@ -25,7 +25,6 @@ type Server struct {
|
||||
config *ServerConfig
|
||||
validator *Validator
|
||||
policyManager policy.Manager
|
||||
cone bool
|
||||
}
|
||||
|
||||
// NewServer create a new Shadowsocks server.
|
||||
@@ -47,7 +46,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
|
||||
config: config,
|
||||
validator: validator,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
cone: ctx.Value("cone").(bool),
|
||||
}
|
||||
|
||||
return s, nil
|
||||
@@ -185,7 +183,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
|
||||
|
||||
data.UDP = &destination
|
||||
|
||||
if !s.cone || dest == nil {
|
||||
if dest == nil {
|
||||
dest = &destination
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ import (
|
||||
type Server struct {
|
||||
config *ServerConfig
|
||||
policyManager policy.Manager
|
||||
cone bool
|
||||
httpServer *http.Server
|
||||
}
|
||||
|
||||
@@ -39,7 +38,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
|
||||
s := &Server{
|
||||
config: config,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
cone: ctx.Value("cone").(bool),
|
||||
}
|
||||
httpConfig := &http.ServerConfig{
|
||||
UserLevel: config.UserLevel,
|
||||
@@ -149,6 +147,7 @@ func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatche
|
||||
To: dest,
|
||||
Status: log.AccessAccepted,
|
||||
Reason: "",
|
||||
Email: inbound.User.Email,
|
||||
})
|
||||
}
|
||||
if inbound.CanSpliceCopy == 2 {
|
||||
@@ -270,12 +269,13 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
|
||||
To: destination,
|
||||
Status: log.AccessAccepted,
|
||||
Reason: "",
|
||||
Email: inbound.User.Email,
|
||||
})
|
||||
}
|
||||
|
||||
payload.UDP = &destination
|
||||
|
||||
if !s.cone || dest == nil {
|
||||
if dest == nil {
|
||||
dest = &destination
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,6 @@ type Server struct {
|
||||
policyManager policy.Manager
|
||||
validator *Validator
|
||||
fallbacks map[string]map[string]map[string]*Fallback // or nil
|
||||
cone bool
|
||||
}
|
||||
|
||||
// NewServer creates a new trojan inbound handler.
|
||||
@@ -59,7 +58,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
|
||||
server := &Server{
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
validator: validator,
|
||||
cone: ctx.Value("cone").(bool),
|
||||
}
|
||||
|
||||
if config.Fallbacks != nil {
|
||||
@@ -302,7 +300,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, sessionPolicy policy.Sess
|
||||
}
|
||||
errors.LogInfo(ctx, "tunnelling request to ", destination)
|
||||
|
||||
if !s.cone || dest == nil {
|
||||
if dest == nil {
|
||||
dest = &destination
|
||||
}
|
||||
|
||||
|
||||
+5
-3
@@ -223,16 +223,18 @@ To make it start, wintun.dll specific for your Windows/arch must be present next
|
||||
|
||||
After the start network adapter with the name you chose in the config will be created in the system, and exist while Xray is running. A Wintun adapter that already has that name is reused.
|
||||
|
||||
With IPv6 disabled system-wide (the `DisabledComponents` registry value), the adapter has no IPv6, and the TUN starts with IPv4 only, unless `gateway` or `autoSystemRoutingTable` has IPv6 entries, which then keep it from starting.
|
||||
`guid` sets the GUID of the adapter Xray creates, as in `"guid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8"`, for applications that identify the adapter by something other than its name, e.g. to keep the same identity across renames. It is used only when Xray creates the adapter: a Wintun adapter that already has the name is opened as it is and keeps its own GUID, so this setting cannot change it. Without it the GUID is derived from the name with MD5, which keeps it the same for as long as the name does. The GUID must not be one that another adapter uses, and Wintun holds one session per adapter, so an adapter is in use by one engine at a time. The config is rejected, on Windows and elsewhere, if the value is not a canonical GUID; other systems ignore it.
|
||||
|
||||
With IPv6 turned off by the `DisabledComponents` registry value (0x10 set, as in 0xFF), errors setting up IPv6 for `gateway`, `dns` and `autoSystemRoutingTable`, clearing the IPv6 DNS servers when `dns` has none included, are only logged. Otherwise, they keep the TUN from starting.
|
||||
|
||||
When `dns` is set, those servers are applied to the adapter. Windows is kept from registering the TUN's addresses in DNS, and its DNS cache is flushed when the TUN starts and stops. Xray's own lookups through the system's DNS servers, like those of the `localhost` DNS server with `autoOutboundsInterface`, skip them, unless another interface uses them as well, as they would lead back into the TUN.
|
||||
|
||||
Setting `autoSystemWfpBlockLeak` to at least `["dns"]` is recommended, to block DNS leaks. It needs `autoSystemRoutingTable` (the config is rejected otherwise), and adds Windows Filtering Platform filters that let traffic of every program but Xray itself leave only through the TUN, each kind chosen by a value:
|
||||
Setting `autoSystemWfpBlockLeak` to at least `["dns", "misconfigtun"]` is recommended, to block DNS leaks and the traffic of an IP version without routes. It needs `autoSystemRoutingTable` (the config is rejected otherwise), and adds Windows Filtering Platform filters that let traffic of every program but Xray itself leave only through the TUN, each kind chosen by a value:
|
||||
- `"dns"`: stands for `"53"`, `"853"` (DNS over TLS and QUIC) and `"windnsclient"`. Windows also queries the DNS servers of the other interfaces, through those interfaces whatever the routes say, and other programs reach a resolver on the local network (e.g. `192.168.1.1` from DHCP) through its more specific route.
|
||||
- `"windnsclient"`: Windows' DNS Client service, except for name resolution on the local network (LLMNR, mDNS). Since Windows 11 and Server 2022, it may query over HTTPS or TLS, to any port; earlier versions only query port 53, so there it does nothing.
|
||||
- `"tcp"`, `"udp"`: that protocol, to all ports, or with `/<port>` or `/<low>-<high>` (1 to 65535) to some, e.g. `"tcp/853"` or `"udp/10-20"`. The ports alone stand for both, e.g. `"53"` or `"10-20"`.
|
||||
- `"icmp"`: ICMP and ICMPv6, e.g. `ping`.
|
||||
- `"misconfigtun"`: an IP version without routes in `autoSystemRoutingTable`, which would bypass the TUN.
|
||||
- `"misconfigtun"`: an IP version without routes in `autoSystemRoutingTable`, which would bypass the TUN. With IPv6 turned off by `DisabledComponents`, it covers IPv6 whatever the routes, as IPv6 setup errors are then only logged, and IPv6 still works until the reboot that applies the value.
|
||||
- `"all"`: everything, in both directions. Access to the local network then breaks unless it is routed into the TUN as well, and so do incoming connections to other programs, other VPNs, and virtual machines whose NAT runs on the host.
|
||||
- `"allexceptlan"`: like `"all"`, but traffic to and from the local network stays allowed, e.g. for printers or casting to a TV: private, link-local, multicast and broadcast addresses (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`, `224.0.0.0/4`, `255.255.255.255`, `fc00::/7`, `fe80::/10`, `ff00::/8`), not global IPv6 ones. It includes `"dns"`, and the other values apply there as well. `"all"` overrides it.
|
||||
|
||||
|
||||
+11
-2
@@ -33,6 +33,7 @@ type Config struct {
|
||||
Desc string `protobuf:"bytes,8,opt,name=desc,proto3" json:"desc,omitempty"`
|
||||
AutoSystemDnsToGateway bool `protobuf:"varint,9,opt,name=auto_system_dns_to_gateway,json=autoSystemDnsToGateway,proto3" json:"auto_system_dns_to_gateway,omitempty"`
|
||||
AutoSystemWfpBlockLeak []string `protobuf:"bytes,10,rep,name=auto_system_wfp_block_leak,json=autoSystemWfpBlockLeak,proto3" json:"auto_system_wfp_block_leak,omitempty"`
|
||||
GUID string `protobuf:"bytes,11,opt,name=GUID,proto3" json:"GUID,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -137,11 +138,18 @@ func (x *Config) GetAutoSystemWfpBlockLeak() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetGUID() string {
|
||||
if x != nil {
|
||||
return x.GUID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_proxy_tun_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_proxy_tun_config_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x16proxy/tun/config.proto\x12\x0exray.proxy.tun\"\xfa\x02\n" +
|
||||
"\x16proxy/tun/config.proto\x12\x0exray.proxy.tun\"\x8e\x03\n" +
|
||||
"\x06Config\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n" +
|
||||
"\x03MTU\x18\x02 \x01(\rR\x03MTU\x12\x18\n" +
|
||||
@@ -154,7 +162,8 @@ const file_proxy_tun_config_proto_rawDesc = "" +
|
||||
"\x04desc\x18\b \x01(\tR\x04desc\x12:\n" +
|
||||
"\x1aauto_system_dns_to_gateway\x18\t \x01(\bR\x16autoSystemDnsToGateway\x12:\n" +
|
||||
"\x1aauto_system_wfp_block_leak\x18\n" +
|
||||
" \x03(\tR\x16autoSystemWfpBlockLeakBL\n" +
|
||||
" \x03(\tR\x16autoSystemWfpBlockLeak\x12\x12\n" +
|
||||
"\x04GUID\x18\v \x01(\tR\x04GUIDBL\n" +
|
||||
"\x12com.xray.proxy.tunP\x01Z#github.com/xtls/xray-core/proxy/tun\xaa\x02\x0eXray.Proxy.Tunb\x06proto3"
|
||||
|
||||
var (
|
||||
|
||||
@@ -17,4 +17,5 @@ message Config {
|
||||
string desc = 8;
|
||||
bool auto_system_dns_to_gateway = 9;
|
||||
repeated string auto_system_wfp_block_leak = 10;
|
||||
string GUID = 11;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user