Compare commits

..
23 Commits
Author SHA1 Message Date
f73471e6b4 gRPC transport: Pass standard size buffer (#7449)
https://github.com/XTLS/Xray-core/pull/7438#issuecomment-7008713358

Fixes https://github.com/XTLS/Xray-core/issues/7369 and https://github.com/XTLS/Xray-core/pull/7424

---------

Co-authored-by: b84330808 <b84330808@gmail.com>
Co-authored-by: anonymousmeower <arasouli@duck.com>
2026-11-19 13:48:04 +00:00
8e07407486 XHTTP/3 client: Close the UDP socket when the QUIC dial fails (#7413)
https://github.com/XTLS/Xray-core/pull/7413#pullrequestreview-5975182281

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: 风扇滑翔翼 <Fangliding.fshxy@outlook.com>
2026-11-19 12:54:02 +00:00
febc082f03 DNS: Avoid mutating cache records during cleanup (#7442)
https://github.com/XTLS/Xray-core/pull/7442#pullrequestreview-5958707394

---------

Co-authored-by: Meow <197331664+Meo597@users.noreply.github.com>
2026-11-19 12:36:34 +00:00
anonymousmeowerandGitHub 09b1b0701f Sockopt: Report the real ioctl error from OriginalDst on Darwin (#7367)
https://github.com/XTLS/Xray-core/pull/7367#issuecomment-7008748396
2026-11-19 12:14:35 +00:00
MeowandGitHub ce074ce572 Env: Remove XRAY_CONE_DISABLED (#6110)
https://github.com/XTLS/Xray-core/pull/6057#issuecomment-4364744151
https://github.com/XTLS/Xray-core/pull/6075#issuecomment-4395258425
https://github.com/XTLS/Xray-core/pull/6110#issuecomment-7003152469
2026-11-19 11:25:41 +00:00
b1dfdf25e7 uTLS: Pick "random" only from fingerprints that have X25519MLKEM768 (#7432)
https://github.com/XTLS/Xray-core/issues/7259#issuecomment-6718349626

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:07:29 +00:00
Roy Hill-PercivalandGitHub 1c5a1fbf70 TUN inbound: End UDP flows and cancel dispatches when the inbound closes (#7350)
https://github.com/XTLS/Xray-core/pull/7350#pullrequestreview-5901009138
2026-11-19 07:57:32 +00:00
deadnewsandGitHub b983473390 Socks & HTTP inbounds: Add email to access log (#7437)
Fixes https://github.com/XTLS/Xray-core/issues/7436
2026-11-19 07:11:16 +00:00
5e861653c2 VMess inbound: Refactor code to use DispatchLink() (#5143)
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-3403697498
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-6743282472
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-7000643202

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-19 06:38:22 +00:00
36112cd886 Routing: Fix process for Linux IPv4-mapped sockets (#7414)
https://github.com/XTLS/Xray-core/pull/7414#issuecomment-6987317102

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 18:13:31 +00:00
b1905088c3 transport/internet/udp/dispatcher.go: Avoid info-level read failure after local session termination; Fix race (#7411)
https://github.com/XTLS/Xray-core/issues/4621#issuecomment-2803983542
https://github.com/XTLS/Xray-core/pull/7411#issuecomment-6893907446
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6915895563

---------

Co-authored-by: Meow <197331664+Meo597@users.noreply.github.com>
2026-11-18 12:14:26 +00:00
381e450943 DNS: Add udp+local:// support and udp:// (remote) as well (#7420)
https://github.com/XTLS/Xray-core/pull/7380#issuecomment-6977561366

Closes https://github.com/XTLS/Xray-core/issues/7321#issuecomment-6674139825

---------

Co-authored-by: Ivan Zorin <creator@localzet.com>
2026-11-18 11:50:30 +00:00
7daa8e4b6a Direct/Freedom outbound: Rename finalRules to firewall; Add reply to firewall; Merge Block/Blackhole outbound; Move proxyProtocol to "proxy-protocol" TCP finalmask (#7281)
https://github.com/XTLS/Xray-core/pull/7238#issuecomment-6467092152
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6484050347
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6484439860
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6621021705
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6623818990
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6624149740
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6625219097
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6627156942
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6850640864
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6973501579

---------

Co-authored-by: Codex <codex@openai.com>
2026-11-18 10:39:20 +00:00
yangdujunandGitHub a32023be5f XMC finalmask: Bound padding schedules; Fix delay placement; Stop compressing frames (#7423)
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6912788851
https://github.com/XTLS/Xray-core/pull/7430#issuecomment-6917170115
https://github.com/XTLS/Xray-core/pull/7423#issuecomment-6973045579
2026-11-18 08:27:34 +00:00
TurboRigbyandGitHub 82b5b76bc5 XMC finalmask: Prevent deadlock during bidirectional startup padding (#7430)
https://github.com/XTLS/Xray-core/pull/7430#issuecomment-6954499005
2026-11-17 16:43:50 +00:00
yangdujunandRPRXX f781c68715 XMC finalmask: Switch to native frame padding (breaking); delay supports range (receiver waits at least minimal ms) (#7402)
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6117945421
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6855385193
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6880324101
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6887468010
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6890345279
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6896090317
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6897315492
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6912788851
2026-11-16 09:49:32 +00:00
5d17b872ed XMC finalmask: Make startup paddings configurable (direction, length and delay) (#6769)
https://github.com/XTLS/Xray-core/pull/6487#issuecomment-5008140264
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-5861391675
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6056420905
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6876480694
https://github.com/XTLS/Xray-core/pull/7401#issuecomment-6876702404
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6876963752

Closes https://github.com/XTLS/Xray-core/issues/6732#issuecomment-5575293343

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-14 15:58:21 +00:00
𐲓𐳛𐳪𐳂𐳐 𐲀𐳢𐳦𐳫𐳢 𐲥𐳔𐳛𐳪𐳌𐳑𐳖𐳇andGitHub c456141815 Build: Build list optimization; build tags clean-up (#5824)
https://github.com/XTLS/Xray-core/pull/5824#issuecomment-6796919801
2026-11-11 13:42:32 +00:00
LjhAUMEMandGitHub f082058590 Hysteria transport: Proper Brutal behavior; Bump quic-go (#7356)
Fixes https://github.com/XTLS/Xray-core/issues/7353
2026-11-11 08:45:54 +00:00
e184d774a2 Metrics: Close HTTP connections when stopping Xray Instance (#7361)
https://github.com/XTLS/Xray-core/pull/7361#pullrequestreview-5840920982

---------

Co-authored-by: 风扇滑翔翼 <Fangliding.fshxy@outlook.com>
2026-11-11 08:23:01 +00:00
LjhAUMEMandGitHub 14df0738f3 XDNS finalmask: Implement worker for TCP resolver (#7354)
Fixes https://github.com/XTLS/Xray-core/issues/7349
2026-11-11 08:12:22 +00:00
36cc9ff510 VLESS Multiplex (mux.cool): Raise maxConcurrency to 128 only for XDRIVE (#7375)
Closes https://github.com/XTLS/Xray-core/issues/7358#issuecomment-6785007489 and https://github.com/XTLS/Xray-core/pull/7365#issuecomment-6785026850

---------

Co-authored-by: Ivan Zorin <creator@localzet.com>
2026-11-11 07:37:36 +00:00
c43ee98ec7 VLESS Multiplex (mux.cool): Replace MutexWriter with buf.BufferedWriter (#7359)
Fixes https://github.com/XTLS/Xray-core/pull/7355#issuecomment-6738888441

---------

Co-authored-by: Medium1992 <Medium1992@users.noreply.github.com>
2026-11-10 22:13:21 +00:00
139 changed files with 3234 additions and 2582 deletions
+1 -2
View File
@@ -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" },
+8 -13
View File
@@ -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/*
+178 -85
View File
@@ -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
@@ -215,13 +163,7 @@ jobs:
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
+19 -2
View File
@@ -231,6 +231,20 @@ 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
@@ -238,10 +252,13 @@ GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=/path/to/aarch64-linux-android24-clan
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
+8 -5
View File
@@ -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
View File
@@ -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}},
}),
},
},
+4
View File
@@ -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) {
+45
View File
@@ -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
View File
@@ -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")
}
}
+1 -7
View File
@@ -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,
+4 -1
View File
@@ -122,7 +122,10 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
if config.Concurrency < 0 {
h.mux = &mux.ClientManager{Enabled: false}
}
if config.Concurrency >= 0 && config.Concurrency <= 128 {
if config.Concurrency == 0 {
config.Concurrency = 8 // same as before
}
if config.Concurrency > 0 && config.Concurrency < 128 && h.streamSettings != nil && h.streamSettings.ProtocolName == "xdrive" {
config.Concurrency = 128
}
if config.Concurrency > 0 {
+3 -3
View File
@@ -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 {
+2 -3
View File
@@ -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 -2
View File
@@ -1,5 +1,4 @@
//go:build !windows && !wasm && !illumos && !openbsd
// +build !windows,!wasm,!illumos,!openbsd
//go:build !windows && !openbsd
package buf
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build !wasm && !openbsd
// +build !wasm,!openbsd
//go:build !openbsd
package buf
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build wasm || openbsd
// +build wasm openbsd
//go:build openbsd
package buf
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build !wasm && !openbsd
// +build !wasm,!openbsd
//go:build !openbsd
package buf_test
-37
View File
@@ -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{}
}
+4
View File
@@ -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
+3 -1
View File
@@ -188,7 +188,9 @@ var (
// NewClientWorker creates a new mux.Client.
func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) {
stream.Writer = &MutexWriter{Writer: stream.Writer}
writer := buf.NewBufferedWriter(stream.Writer)
writer.SetBuffered(false)
stream.Writer = writer
c := &ClientWorker{
sessionManager: NewSessionManager(),
link: stream,
+3 -1
View File
@@ -93,9 +93,11 @@ type ServerWorker struct {
}
func NewServerWorker(ctx context.Context, d routing.Dispatcher, link *transport.Link) (*ServerWorker, error) {
writer := buf.NewBufferedWriter(link.Writer)
writer.SetBuffered(false)
worker := &ServerWorker{
dispatcher: d,
link: &transport.Link{Reader: link.Reader, Writer: &MutexWriter{Writer: link.Writer}},
link: &transport.Link{Reader: link.Reader, Writer: writer},
sessionManager: NewSessionManager(),
done: done.New(),
timer: time.NewTicker(60 * time.Second),
-13
View File
@@ -1,8 +1,6 @@
package mux
import (
"sync"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/net"
@@ -11,17 +9,6 @@ import (
"github.com/xtls/xray-core/common/session"
)
type MutexWriter struct {
sync.Mutex
buf.Writer
}
func (w *MutexWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
w.Lock()
defer w.Unlock()
return w.Writer.WriteMultiBuffer(mb)
}
type Writer struct {
dest net.Destination
writer buf.Writer
+12 -11
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"net"
"os"
"slices"
"strconv"
"strings"
@@ -31,7 +32,7 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
switch network {
case "tcp":
if net.ParseIP(srcIP).To4() != nil {
procFiles = []string{"/proc/net/tcp"}
procFiles = []string{"/proc/net/tcp", "/proc/net/tcp6"}
} else {
procFiles = []string{"/proc/net/tcp6"}
}
@@ -45,14 +46,18 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
panic("Unsupported network type for process lookup.")
}
targetHexAddr := formatProcNetAddress(net.ParseIP(srcIP), Port(srcPort))
targetHexAddrs := []string{formatProcNetAddress(net.ParseIP(srcIP).To16(), Port(srcPort))}
if ipv4 := net.ParseIP(srcIP).To4(); ipv4 != nil {
// the one above is then the IPv4-mapped IPv6 address that an IPv6 socket has it as, in the IPv6 file
targetHexAddrs = append(targetHexAddrs, formatProcNetAddress(ipv4, Port(srcPort)))
}
portFallback := ""
if network == "udp" {
portFallback = fmt.Sprintf(":%04X", srcPort)
}
inode, err := findInodeInFiles(procFiles, targetHexAddr, portFallback)
inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
if err != nil {
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
}
@@ -84,13 +89,9 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
return pid, procName, absPath, nil
}
// formatProcNetAddress formats the 4 or 16 bytes of addr as they are: an IPv4-mapped IPv6 address stays one
func formatProcNetAddress(addr net.IP, port Port) string {
var ipBytes []byte
if ipv4 := addr.To4(); ipv4 != nil {
ipBytes = ipv4
} else {
ipBytes = addr.To16()
}
ipBytes := []byte(addr)
var formatted strings.Builder
formatted.Grow(len(ipBytes)*2 + 5)
@@ -101,7 +102,7 @@ func formatProcNetAddress(addr net.IP, port Port) string {
return formatted.String()
}
func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (string, error) {
func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
onlyMatchedPort := ""
for i, filePath := range filePaths {
@@ -122,7 +123,7 @@ func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (s
}
localAddress := fields[1]
if localAddress == targetHexAddr {
if slices.Contains(targetHexAddrs, localAddress) {
return fields[9], nil
}
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
+50
View File
@@ -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
View File
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package platform
-1
View File
@@ -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
View File
@@ -1,5 +1,4 @@
//go:build windows
// +build windows
package platform
-3
View File
@@ -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())
+3 -3
View File
@@ -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
View File
@@ -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()
+1 -1
View File
@@ -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
+2 -2
View File
@@ -1,5 +1,5 @@
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=
+12 -6
View File
@@ -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
}
+26 -9
View File
@@ -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
View File
@@ -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
+11 -3
View File
@@ -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,
+99 -15
View File
@@ -18,6 +18,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 +27,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 +78,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 +100,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"`
@@ -932,9 +961,25 @@ 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"`
// 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"`
}
type XMCProfile struct {
@@ -977,6 +1022,48 @@ func (c *XMC) Build() (proto.Message, error) {
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)
}
// 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{Password: c.Password, 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)
}
rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password)
if err != nil {
@@ -997,13 +1084,10 @@ 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.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey)
config.RsaPublicKey = rsaPublicKey
config.Profiles = profiles
return config, nil
}
type Xicmp struct {
+117
View File
@@ -1,6 +1,7 @@
package conf
import (
"encoding/json"
"strings"
"testing"
@@ -10,6 +11,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 +32,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 +53,101 @@ 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 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)
}
}
+4 -4
View File
@@ -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
+10 -1
View File
@@ -407,7 +407,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 {
-1
View File
@@ -35,7 +35,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
View File
@@ -1,5 +1,4 @@
//go:build coveragemain
// +build coveragemain
package main
-88
View File
@@ -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))
}))
}
-76
View File
@@ -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")
}
}
-180
View File
@@ -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
}
-16
View File
@@ -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;
}
-19
View File
@@ -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
View File
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package dokodemo
-1
View File
@@ -1,5 +1,4 @@
//go:build openbsd
// +build openbsd
package dokodemo
-1
View File
@@ -1,5 +1,4 @@
//go:build !linux && !openbsd
// +build !linux,!openbsd
package dokodemo
+130 -74
View File
@@ -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,
},
+9 -3
View File
@@ -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;
}
+83 -54
View File
@@ -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,16 @@ 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
@@ -316,10 +355,10 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
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 +369,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 +384,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 +395,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 +416,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 +513,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 +546,7 @@ type PacketReader struct {
*net.PacketConnWrapper
stats.Counter
Handler *Handler
DefaultRule *FinalRule
DefaultRule *Firewall
IsOverridden bool
InitUnchangedAddr net.Address
InitChangedAddr net.Address
@@ -534,7 +563,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 +588,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 +622,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 +681,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
}
+87
View File
@@ -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))
}
})
}
}
+1
View File
@@ -150,6 +150,7 @@ Start:
To: request.URL,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
if strings.EqualFold(request.Method, "CONNECT") {
+1 -3
View File
@@ -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
}
+3 -3
View File
@@ -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
}
+1 -3
View File
@@ -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
}
+9 -1
View File
@@ -25,7 +25,10 @@ import (
// Handler is managing object that tie together tun interface, ip stack and dispatch connections to the routing
type Handler struct {
// ctx is detached from the instance's; cancel ends it, and with it every dispatch started from it,
// when the handler closes, since nothing else would
ctx context.Context
cancel context.CancelFunc
config *Config
stack Stack
tun Tun
@@ -96,7 +99,7 @@ func (t *Handler) Init(ctx context.Context, pm policy.Manager, dispatcher routin
t.sniffingRequest = content.SniffingRequest
}
t.ctx = core.ToBackgroundDetachedContext(ctx)
t.ctx, t.cancel = context.WithCancel(core.ToBackgroundDetachedContext(ctx))
t.policyManager = pm
t.dispatcher = dispatcher
@@ -265,6 +268,11 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
// Close implements common.Closable.
func (t *Handler) Close() error {
// cancel first so every dispatch in flight unwinds, then close the stack (resets TCP, ends UDP flows)
// and the tun
if t.cancel != nil {
t.cancel()
}
return errors.Combine(common.CloseIfExists(t.stack), common.CloseIfExists(t.tun))
}
+34
View File
@@ -179,3 +179,37 @@ func TestHandlerCountsTunConnectionTraffic(t *testing.T) {
t.Fatalf("connection write mismatch: got %q, want %q", got, "downlink")
}
}
// a dispatcher that only returns when its context ends
type blockingDispatcher struct {
testDispatcher
entered chan struct{}
}
func (d *blockingDispatcher) DispatchLink(ctx context.Context, dest xnet.Destination, link *transport.Link) error {
close(d.entered)
<-ctx.Done()
return ctx.Err()
}
// Closing the handler must end a dispatch that is not reading its connection: the handler's context
// is detached from the instance's, so Close is what cancels it
func TestHandlerCloseCancelsDispatches(t *testing.T) {
dispatcher := &blockingDispatcher{entered: make(chan struct{})}
handler := &Handler{config: &Config{}, dispatcher: dispatcher}
handler.ctx, handler.cancel = context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
handler.HandleConnection(newTestConn(nil), xnet.TCPDestination(xnet.LocalHostIP, 443))
close(done)
}()
<-dispatcher.entered
if err := handler.Close(); err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("dispatch still running after Close")
}
}
+5
View File
@@ -148,6 +148,11 @@ func (s *stack) Close() error {
for _, u := range sockets {
u.queue.close()
}
// the UDP flows the other side opened are in neither conns nor sockets; end them too, or their
// dispatches and what they hold survive the instance
if s.udp != nil {
s.udp.closeAll()
}
return nil
}
+1 -2
View File
@@ -17,7 +17,6 @@ import (
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/proxy/blackhole"
proxydns "github.com/xtls/xray-core/proxy/dns"
"github.com/xtls/xray-core/proxy/freedom"
)
@@ -73,7 +72,7 @@ func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.Na
Outbound: []*core.OutboundHandlerConfig{
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
},
})
if err != nil {
+23
View File
@@ -16,6 +16,8 @@ type udpConnectionHandler struct {
sync.RWMutex
udpConns map[net.Destination]*udpConn
// closed is set by closeAll; a packet that arrives after it opens no flow
closed bool
handleConnection func(conn net.Conn, dest net.Destination)
writePacket func(data []byte, src net.Destination, dst net.Destination) error
@@ -51,6 +53,10 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
u.Lock()
defer u.Unlock()
if u.closed {
data.Release()
return
}
conn, found = u.udpConns[src]
if !found {
conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst}
@@ -66,6 +72,23 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
}
}
// closeAll ends every UDP flow and takes no new ones: the readers get EOF, so the dispatch of each flow
// returns and lets go of its outbound. Called when the stack closes; without it an inbound's UDP flows,
// and whatever carries them, outlive the instance.
func (u *udpConnectionHandler) closeAll() {
u.Lock()
u.closed = true
conns := make([]*udpConn, 0, len(u.udpConns))
for _, c := range u.udpConns {
conns = append(conns, c)
}
u.udpConns = make(map[net.Destination]*udpConn)
u.Unlock()
for _, c := range conns {
c.queue.close()
}
}
func (u *udpConnectionHandler) connectionFinished(conn *udpConn) {
u.Lock()
// Close runs twice per flow; a newer conn may already own this src.
+36
View File
@@ -89,3 +89,39 @@ func TestPacketQueueDropsDrainedStorage(t *testing.T) {
t.Fatalf("drained queue still holds %d slots", cap(q.items))
}
}
// A closing stack must end its UDP flows: the dispatch reading a flow gets EOF and returns, instead of
// waiting on the queue forever and keeping its outbound alive past the instance; a packet that arrives
// afterwards opens no flow.
func TestUDPHandlerCloseAllEndsFlows(t *testing.T) {
done := make(chan struct{}, 2)
handler := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {
b := make([]byte, 2048)
for {
if _, err := conn.Read(b); err != nil {
done <- struct{}{}
return
}
}
}, func(data []byte, src net.Destination, dst net.Destination) error { return nil })
dst := net.UDPDestination(net.IPAddress([]byte{10, 6, 0, 2}), 53)
for _, port := range []net.Port{40000, 40001} {
src := net.UDPDestination(net.IPAddress([]byte{10, 255, 0, 2}), port)
handler.HandlePacket(src, dst, buf.FromBytes([]byte("query")))
}
handler.closeAll()
for i := 0; i < 2; i++ {
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatalf("flow %d still running after closeAll", i)
}
}
handler.HandlePacket(net.UDPDestination(net.IPAddress([]byte{10, 255, 0, 2}), 40002), dst, buf.FromBytes([]byte("late")))
handler.RLock()
n := len(handler.udpConns)
handler.RUnlock()
if n != 0 {
t.Fatalf("%d flows in the table after closeAll", n)
}
}
+1 -3
View File
@@ -50,7 +50,6 @@ func init() {
type Handler struct {
server *protocol.ServerSpec
policyManager policy.Manager
cone bool
encryption *encryption.ClientInstance
reverse *Reverse
@@ -78,7 +77,6 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{
server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
a := handler.server.User.Account.(*vless.MemoryAccount)
@@ -300,7 +298,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
clientReader := link.Reader // .(*pipe.Reader)
clientWriter := link.Writer // .(*pipe.Writer)
trafficState := proxy.NewTrafficState(account.ID.Bytes())
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (h.cone && request.Port != 53 && request.Port != 443)) {
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (request.Port != 53 && request.Port != 443)) {
request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666)
+17 -76
View File
@@ -14,8 +14,6 @@ import (
"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"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/common/uuid"
"github.com/xtls/xray-core/core"
feature_inbound "github.com/xtls/xray-core/features/inbound"
@@ -23,6 +21,7 @@ import (
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/proxy/vmess"
"github.com/xtls/xray-core/proxy/vmess/encoding"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet/stat"
)
@@ -185,44 +184,6 @@ func (h *Handler) RemoveUser(ctx context.Context, email string) error {
return nil
}
func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input buf.Reader, output *buf.BufferedWriter) error {
session.EncodeResponseHeader(response, output)
bodyWriter, err := session.EncodeResponseBody(request, output)
if err != nil {
return errors.New("failed to start decoding response").Base(err)
}
{
// Optimize for small response packet
data, err := input.ReadMultiBuffer()
if err != nil {
return err
}
if err := bodyWriter.WriteMultiBuffer(data); err != nil {
return err
}
}
if err := output.SetBuffered(false); err != nil {
return err
}
if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
return err
}
account := request.User.Account.(*vmess.MemoryAccount)
if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
return err
}
}
return nil
}
// Process implements proxy.Inbound.Process().
func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
sessionPolicy := h.policyManager.ForLevel(0)
@@ -273,49 +234,29 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
inbound.CanSpliceCopy = 3
inbound.User = request.User
sessionPolicy = h.policyManager.ForLevel(request.User.Level)
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
link, err := dispatcher.Dispatch(ctx, request.Destination())
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
if err != nil {
return errors.New("failed to dispatch request to ", request.Destination()).Base(err)
return errors.New("failed to start decoding").Base(err)
}
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
if err != nil {
return errors.New("failed to start decoding").Base(err)
}
if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
return errors.New("failed to transfer request").Base(err)
}
return nil
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
}
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
defer writer.Flush()
response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
}
return transferResponse(timer, svrSession, request, response, link.Reader, writer)
svrSession.EncodeResponseHeader(response, writer)
bodyWriter, err := svrSession.EncodeResponseBody(request, writer)
if err != nil {
return errors.New("failed to start decoding response").Base(err)
}
writer.SetFlushNext()
requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
return errors.New("connection ends").Base(err)
if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
Reader: bodyReader,
Writer: bodyWriter,
},
); err != nil {
return errors.New("failed to dispatch request").Base(err)
}
return nil
}
+1 -3
View File
@@ -32,7 +32,6 @@ import (
type Handler struct {
server *protocol.ServerSpec
policyManager policy.Manager
cone bool
}
// New creates a new VMess outbound handler.
@@ -49,7 +48,6 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{
server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
return handler, nil
@@ -143,7 +141,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
}
}, sessionPolicy.Timeouts.ConnectionIdle)
if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 {
if request.Command == protocol.RequestCommandUDP && request.Port != 53 && request.Port != 443 {
request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666)
+5 -5
View File
@@ -71,7 +71,7 @@ func TestCommanderListenConfigurationItem(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -166,7 +166,7 @@ func TestCommanderRemoveHandler(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -262,7 +262,7 @@ func TestCommanderListHandlers(t *testing.T) {
{
Tag: "default-outbound",
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -390,7 +390,7 @@ func TestCommanderAddRemoveUser(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}},
}),
},
},
@@ -579,7 +579,7 @@ func TestCommanderStats(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}},
}),
},
},
-1
View File
@@ -1,5 +1,4 @@
//go:build coverage
// +build coverage
package scenarios
-1
View File
@@ -1,5 +1,4 @@
//go:build !coverage
// +build !coverage
package scenarios
+1 -2
View File
@@ -13,7 +13,6 @@ import (
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/proxy/blackhole"
"github.com/xtls/xray-core/proxy/freedom"
"github.com/xtls/xray-core/proxy/socks"
"github.com/xtls/xray-core/testing/servers/tcp"
@@ -78,7 +77,7 @@ func TestResolveIP(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
},
{
Tag: "direct",
+2 -2
View File
@@ -60,7 +60,7 @@ func TestDokodemoTCP(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}},
}),
},
},
@@ -163,7 +163,7 @@ func TestDokodemoUDP(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}},
}),
},
},
+10 -11
View File
@@ -21,7 +21,6 @@ import (
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/uuid"
core "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/proxy/blackhole"
"github.com/xtls/xray-core/proxy/dokodemo"
"github.com/xtls/xray-core/proxy/freedom"
v2http "github.com/xtls/xray-core/proxy/http"
@@ -62,7 +61,7 @@ func TestPassiveConnection(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}},
}),
},
},
@@ -123,7 +122,7 @@ func TestDialerProxy(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}},
}),
},
},
@@ -152,7 +151,7 @@ func TestDialerProxy(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}},
}),
},
},
@@ -254,7 +253,7 @@ func TestDialerProxyOverKCP(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}},
}),
},
},
@@ -283,7 +282,7 @@ func TestDialerProxyOverKCP(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}},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
@@ -402,11 +401,11 @@ func TestBlackhole(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
{
Tag: "blocked",
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
},
},
App: []*serial.TypedMessage{
@@ -517,7 +516,7 @@ func TestUDPConnection(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}},
}),
},
},
@@ -582,7 +581,7 @@ func TestDomainSniffing(t *testing.T) {
},
{
Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
App: []*serial.TypedMessage{
@@ -669,7 +668,7 @@ func TestDialXray(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}},
}),
},
},
+6 -6
View File
@@ -50,7 +50,7 @@ func TestHttpConformance(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}},
}),
},
},
@@ -113,7 +113,7 @@ func TestHttpError(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}},
}),
},
},
@@ -163,7 +163,7 @@ func TestHTTPConnectMethod(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}},
}),
},
},
@@ -245,7 +245,7 @@ func TestHttpPost(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}},
}),
},
},
@@ -317,7 +317,7 @@ func TestHttpBasicAuth(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}},
}),
},
},
@@ -405,7 +405,7 @@ func TestHTTPOutboundServerFirst(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}},
}),
},
},
+1 -1
View File
@@ -499,7 +499,7 @@ func masqueServerConfig(serverPort net.Port, certificate *tls.Certificate, h2 bo
Port: uint32(dest.Port),
},
},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}),
}
}
+1 -1
View File
@@ -63,7 +63,7 @@ func TestMetrics(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
+2 -2
View File
@@ -85,7 +85,7 @@ func TestVMessClosing(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}},
}),
},
},
@@ -193,7 +193,7 @@ func TestZeroBuffer(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}},
}),
},
},
+4 -5
View File
@@ -17,7 +17,6 @@ import (
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/uuid"
core "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/proxy/blackhole"
"github.com/xtls/xray-core/proxy/dokodemo"
"github.com/xtls/xray-core/proxy/freedom"
"github.com/xtls/xray-core/proxy/vmess"
@@ -100,7 +99,7 @@ func TestReverseProxy(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
},
},
}
@@ -151,7 +150,7 @@ func TestReverseProxy(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "freedom",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
{
Tag: "reverse",
@@ -275,7 +274,7 @@ func TestReverseProxyLongRunning(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
},
},
}
@@ -340,7 +339,7 @@ func TestReverseProxyLongRunning(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "freedom",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
{
Tag: "reverse",
+2 -2
View File
@@ -91,7 +91,7 @@ func testShadowsocks2022Tcp(t *testing.T, method string, password string) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -176,7 +176,7 @@ func testShadowsocks2022Udp(t *testing.T, method string, password string) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+4 -4
View File
@@ -53,7 +53,7 @@ func TestShadowsocksChaCha20Poly1305TCP(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}},
}),
},
},
@@ -141,7 +141,7 @@ func TestShadowsocksAES256GCMTCP(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}},
}),
},
},
@@ -236,7 +236,7 @@ func TestShadowsocksAES128GCMUDP(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}},
}),
},
},
@@ -330,7 +330,7 @@ func TestShadowsocksAES128GCMUDPMux(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}},
}),
},
},
+6 -7
View File
@@ -11,7 +11,6 @@ import (
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/proxy/blackhole"
"github.com/xtls/xray-core/proxy/dokodemo"
"github.com/xtls/xray-core/proxy/freedom"
"github.com/xtls/xray-core/proxy/http"
@@ -51,7 +50,7 @@ func TestSocksBridgeTCP(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}},
}),
},
},
@@ -128,7 +127,7 @@ func TestSocksWithHttpRequest(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}},
}),
},
},
@@ -217,7 +216,7 @@ func TestSocksBridageUDP(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -331,11 +330,11 @@ func TestSocksBridageUDPWithRouting(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
},
{
Tag: "out",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -435,7 +434,7 @@ func TestSocksConformanceMod(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}},
}),
},
},
+10 -10
View File
@@ -69,7 +69,7 @@ func TestSimpleTLSConnection(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}},
}),
},
},
@@ -182,7 +182,7 @@ func TestAutoIssuingCertificate(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}},
}),
},
},
@@ -287,7 +287,7 @@ func TestTLSOverKCP(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}},
}),
},
},
@@ -387,7 +387,7 @@ func TestTLSOverWebSocket(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}},
}),
},
},
@@ -503,7 +503,7 @@ func TestGRPC(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}},
}),
},
},
@@ -619,7 +619,7 @@ func TestGRPCMultiMode(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}},
}),
},
},
@@ -728,7 +728,7 @@ func TestSimpleTLSConnectionPinned(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}},
}),
},
},
@@ -827,7 +827,7 @@ func TestSimpleTLSConnectionPinnedWrongCert(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}},
}),
},
},
@@ -925,7 +925,7 @@ func TestUTLSConnectionPinned(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}},
}),
},
},
@@ -1025,7 +1025,7 @@ func TestUTLSConnectionPinnedWrongCert(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}},
}),
},
},
+1 -1
View File
@@ -63,7 +63,7 @@ func TestHTTPConnectionHeader(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}},
}),
},
},
+8 -8
View File
@@ -70,7 +70,7 @@ func TestVless(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}},
}),
},
},
@@ -175,7 +175,7 @@ func TestVlessTls(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}},
}),
},
},
@@ -298,7 +298,7 @@ func TestVlessXtlsVision(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}},
}),
},
},
@@ -430,7 +430,7 @@ func TestVlessXtlsVisionReality(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}},
}),
},
},
@@ -569,7 +569,7 @@ func TestVlessRealityFingerprints(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}},
}),
},
},
@@ -661,7 +661,7 @@ func TestVlessRealityFingerprints(t *testing.T) {
wg.Wait()
}
// A blocked connection must close after finalRules.delay even while the client keeps it open and sends nothing.
// A blocked connection must close after firewall.delay even while the client keeps it open and sends nothing.
func TestVlessBlockDelay(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
@@ -695,7 +695,7 @@ func TestVlessBlockDelay(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{
Firewall: []*freedom.FirewallConfig{
{
Action: freedom.RuleAction_Block,
Delay: &freedom.Range{Min: delay, Max: delay},
@@ -734,7 +734,7 @@ func TestVlessBlockDelay(t *testing.T) {
t.Fatalf("connection is still open after %v", elapsed)
}
if elapsed < blockDuration {
t.Fatalf("connection is closed after %v, before finalRules.delay", elapsed)
t.Fatalf("connection is closed after %v, before firewall.delay", elapsed)
}
})
}
+10 -10
View File
@@ -62,7 +62,7 @@ func TestVMessGCM(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}},
}),
},
},
@@ -162,7 +162,7 @@ func TestVMessGCMReadv(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}},
}),
},
},
@@ -265,7 +265,7 @@ func TestVMessGCMUDP(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}},
}),
},
},
@@ -362,7 +362,7 @@ func TestVMessChacha20(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}},
}),
},
},
@@ -463,7 +463,7 @@ func TestVMessKCP(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}},
}),
},
},
@@ -568,7 +568,7 @@ func TestVMessKCPLarge(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}},
}),
},
},
@@ -674,7 +674,7 @@ func TestVMessGCMMux(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}},
}),
},
},
@@ -787,7 +787,7 @@ func TestVMessGCMMuxUDP(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}},
}),
},
},
@@ -910,7 +910,7 @@ func TestVMessGCMLengthAuth(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}},
}),
},
},
@@ -1012,7 +1012,7 @@ func TestVMessGCMLengthAuthPlusNoTerminationSignal(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}},
}),
},
},
+1 -1
View File
@@ -61,7 +61,7 @@ func TestWireguard(t *testing.T) {
Port: uint32(dest.Port),
},
},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}),
}
}
-1
View File
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package internet
@@ -9,9 +9,11 @@ import (
"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/session"
)
type Dialer struct {
Source net.Addr
DialTCP func(net.Destination) (net.Conn, error)
DialUDP func(net.Destination) (net.Conn, error)
}
@@ -85,6 +87,9 @@ func (fm *FinalMask) DialTCP(ctx context.Context, dest net.Destination) (net.Con
return &net.PacketConnWrapper{PacketConn: conn, Dest: addr}, err
},
}
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
dialer.Source = inbound.Source.RawNetAddr()
}
for i := range fm.tcpMasks {
var newConn net.Conn
newConn, err = fm.tcpMasks[i].WrapConnClient(conn, &dest, dialer)
@@ -1,5 +1,4 @@
//go:build !amd64
// +build !amd64
package original
@@ -0,0 +1,31 @@
package proxyprotocol
import (
"github.com/pires/go-proxyproto"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, 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")
}
source := conn.LocalAddr()
if dialer != nil && dialer.Source != nil {
source = dialer.Source
}
header := proxyproto.HeaderProxyFromAddrs(byte(version), source, conn.RemoteAddr())
if _, err := header.WriteTo(conn); err != nil {
return nil, errors.New("failed to write PROXY protocol header").Base(err)
}
return conn, nil
}
func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
return proxyproto.NewConn(conn, proxyproto.WithPolicy(proxyproto.REQUIRE)), nil
}
@@ -0,0 +1,123 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.12
// protoc (unknown)
// source: transport/internet/finalmask/proxyprotocol/config.proto
package proxyprotocol
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 Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Version uint32 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes[0]
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_transport_internet_finalmask_proxyprotocol_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 Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetVersion() uint32 {
if x != nil {
return x.Version
}
return 0
}
var File_transport_internet_finalmask_proxyprotocol_config_proto protoreflect.FileDescriptor
const file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc = "" +
"\n" +
"7transport/internet/finalmask/proxyprotocol/config.proto\x12/xray.transport.internet.finalmask.proxyprotocol\"\"\n" +
"\x06Config\x12\x18\n" +
"\aversion\x18\x01 \x01(\rR\aversionB\xaf\x01\n" +
"3com.xray.transport.internet.finalmask.proxyprotocolP\x01ZDgithub.com/xtls/xray-core/transport/internet/finalmask/proxyprotocol\xaa\x02/Xray.Transport.Internet.Finalmask.ProxyProtocolb\x06proto3"
var (
file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescOnce sync.Once
file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData []byte
)
func file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescGZIP() []byte {
file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescOnce.Do(func() {
file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc), len(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc)))
})
return file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData
}
var file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes = []any{
(*Config)(nil), // 0: xray.transport.internet.finalmask.proxyprotocol.Config
}
var file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_transport_internet_finalmask_proxyprotocol_config_proto_init() }
func file_transport_internet_finalmask_proxyprotocol_config_proto_init() {
if File_transport_internet_finalmask_proxyprotocol_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc), len(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes,
DependencyIndexes: file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs,
MessageInfos: file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes,
}.Build()
File_transport_internet_finalmask_proxyprotocol_config_proto = out.File
file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes = nil
file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs = nil
}
@@ -0,0 +1,11 @@
syntax = "proto3";
package xray.transport.internet.finalmask.proxyprotocol;
option csharp_namespace = "Xray.Transport.Internet.Finalmask.ProxyProtocol";
option go_package = "github.com/xtls/xray-core/transport/internet/finalmask/proxyprotocol";
option java_package = "com.xray.transport.internet.finalmask.proxyprotocol";
option java_multiple_files = true;
message Config {
uint32 version = 1;
}
@@ -0,0 +1,93 @@
package proxyprotocol
import (
"context"
"fmt"
"io"
"testing"
"time"
"github.com/pires/go-proxyproto"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
func TestClientHeader(t *testing.T) {
for _, version := range []uint32{0, 1, 2} {
for _, sourceIP := range []string{"", "198.51.100.7", "2001:db8::7"} {
t.Run(fmt.Sprintf("version=%d/source=%s", version, sourceIP), func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
ctx := context.Background()
if sourceIP != "" {
ctx = session.ContextWithInbound(ctx, &session.Inbound{
Source: net.TCPDestination(net.ParseAddress(sourceIP), 12345),
})
}
fm := finalmask.NewFinalMask([]finalmask.TCPMask{&Config{Version: version}}, nil,
func(ctx context.Context, dest net.Destination) (net.Conn, error) {
return net.Dial("tcp", dest.NetAddr())
}, func(ctx context.Context, addr net.Addr) (net.Listener, error) {
return listener, nil
}, nil, nil)
maskedListener, err := fm.Listen(context.Background(), listener.Addr())
if err != nil {
t.Fatal(err)
}
client, err := fm.DialTCP(ctx, net.DestinationFromAddr(listener.Addr()))
if err != nil {
t.Fatal(err)
}
defer client.Close()
server, err := maskedListener.Accept()
if err != nil {
t.Fatal(err)
}
defer server.Close()
deadline := time.Now().Add(5 * time.Second)
if err := client.SetDeadline(deadline); err != nil {
t.Fatal(err)
}
if err := server.SetDeadline(deadline); err != nil {
t.Fatal(err)
}
proxyConn, ok := server.(*proxyproto.Conn)
if !ok {
t.Fatalf("server connection type = %T, want *proxyproto.Conn", server)
}
header := proxyConn.ProxyHeader()
wantVersion := byte(version)
if wantVersion == 0 {
wantVersion = 2
}
if header == nil || header.Version != wantVersion || header.Command != proxyproto.PROXY {
t.Fatalf("unexpected PROXY header: %v", header)
}
wantSource := client.LocalAddr()
if sourceIP != "" {
wantSource = &net.TCPAddr{IP: net.ParseIP(sourceIP), Port: 12345}
}
if server.RemoteAddr().String() != wantSource.String() || server.LocalAddr().String() != listener.Addr().String() {
t.Fatalf("addresses = %v -> %v, want %v -> %v", server.RemoteAddr(), server.LocalAddr(), wantSource, listener.Addr())
}
for _, pair := range [][2]net.Conn{{client, server}, {client, server}, {server, client}} {
const payload = "application payload"
if _, err := io.WriteString(pair[0], payload); err != nil {
t.Fatal(err)
}
data := make([]byte, len(payload))
if _, err := io.ReadFull(pair[1], data); err != nil {
t.Fatal(err)
}
if string(data) != payload {
t.Fatalf("payload = %q", data)
}
}
})
}
}
}
@@ -279,7 +279,7 @@ func runVLESSRealityCase(t *testing.T, bin string, mode trafficMode, payloadSize
},
Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})},
},
})
@@ -398,7 +398,7 @@ func runHysteria2Case(t *testing.T, bin string, mode trafficMode, payloadSize in
},
Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})},
},
})
@@ -514,7 +514,7 @@ func runVLesseEncCase(t *testing.T, bin string, mode trafficMode, payloadSize in
},
Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})},
},
})
@@ -614,7 +614,7 @@ func runVLESSXHTTPCase(t *testing.T, bin string, mode trafficMode, payloadSize i
},
Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})},
},
})
+9 -2
View File
@@ -108,8 +108,15 @@ func NewDomain(domain string, lenLimit int, labelLimit int, types []uint16, edns
return nil, err
}
ascii = strings.Trim(ascii, ".")
name, err := dnsmessage.NewName(domain + ".")
if ascii == "" {
return nil, errors.New("empty domain")
}
for _, label := range strings.Split(ascii, ".") {
if len(label) == 0 || len(label) > 63 {
return nil, errors.New("invalid domain")
}
}
name, err := dnsmessage.NewName(ascii + ".")
if err != nil {
return nil, err
}
+104 -57
View File
@@ -1,11 +1,11 @@
package xdns
import (
"encoding/binary"
"errors"
"context"
"io"
"sync"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
@@ -14,11 +14,9 @@ type TCPResolver struct {
dest net.Destination
dialer *finalmask.Dialer
conn net.Conn
tcpAddr *net.TCPAddr
udpAddr *net.UDPAddr
readCh chan []byte
sendCh chan []byte
closeCh chan struct{}
wg sync.WaitGroup
mu sync.Mutex
@@ -33,12 +31,10 @@ func NewTCPResolver(config *ResolverProto, dialer *finalmask.Dialer) (Resolver,
dest: dest,
dialer: dialer,
readCh: make(chan []byte),
sendCh: make(chan []byte),
closeCh: make(chan struct{}),
}
if err := r.dial(); err != nil {
r.Close()
return nil, err
}
go r.run(config.Worker)
return r, nil
}
@@ -51,60 +47,113 @@ func (r *TCPResolver) closed() bool {
}
}
func (r *TCPResolver) dial() error {
if r.closed() {
return errors.New("closed")
func (r *TCPResolver) setaddr(addr net.Addr) {
r.mu.Lock()
defer r.mu.Unlock()
switch v := addr.(type) {
case *net.TCPAddr:
r.udpAddr = &net.UDPAddr{IP: v.IP, Port: v.Port}
case *net.UDPAddr:
r.udpAddr = v
default:
panic(v)
}
if r.conn != nil {
return nil
}
func (r *TCPResolver) read(reader io.Reader, p []byte) (l int, err error) {
if _, err := io.ReadFull(reader, p[:2]); err != nil {
return 0, err
}
conn, err := r.dialer.DialTCP(r.dest)
l = int(p[0])<<8 | int(p[1])
if l == 0 || l > 4096 {
return 0, errors.New("err resp len ", l)
}
if _, err = io.ReadFull(reader, p[:l]); err != nil {
return 0, err
}
return l, nil
}
func (r *TCPResolver) do(conn *net.Conn, buf *[4096 + 2]byte, p []byte) error {
var err error
if *conn == nil {
*conn, err = r.dialer.DialTCP(r.dest)
if err != nil {
*conn = nil
return err
}
r.setaddr((*conn).RemoteAddr())
}
c := *conn
l := len(p)
buf[0] = byte(l >> 8)
buf[1] = byte(l)
copy(buf[2:], p)
_, err = c.Write(buf[:2+len(p)])
if err != nil {
c.Close()
*conn = nil
return err
}
r.conn = conn
r.tcpAddr = conn.RemoteAddr().(*net.TCPAddr)
r.udpAddr = &net.UDPAddr{IP: r.tcpAddr.IP, Port: r.tcpAddr.Port}
r.wg.Add(1)
go r.recv(conn)
b := pool4K.Get().([]byte)
l, err = r.read(c, b)
if err != nil {
c.Close()
*conn = nil
pool4K.Put(b[:cap(b)])
return err
}
select {
case <-r.closeCh:
pool4K.Put(b[:cap(b)])
case r.readCh <- b[:l]:
}
return nil
}
func (r *TCPResolver) recv(conn net.Conn) {
func (r *TCPResolver) worker() {
defer r.wg.Done()
var buf [4096]byte
var conn net.Conn
defer func() {
if conn != nil {
_ = conn.Close()
}
}()
var buf [4096 + 2]byte
var p []byte
for {
_, err := io.ReadFull(conn, buf[:2])
if err != nil {
break
}
n := binary.BigEndian.Uint16(buf[:2])
if n == 0 || n > 4096 {
io.CopyN(io.Discard, conn, int64(n))
continue
}
_, err = io.ReadFull(conn, buf[:n])
if err != nil {
break
}
p := pool4K.Get().([]byte)
copy(p, buf[:n])
select {
case <-r.closeCh:
pool4K.Put(p[:cap(p)])
case r.readCh <- p[:n]:
return
default:
select {
case <-r.closeCh:
return
case p = <-r.sendCh:
}
}
if err := r.do(&conn, &buf, p); err != nil {
errors.LogErrorInner(context.Background(), err, "do err")
}
}
}
r.mu.Lock()
defer r.mu.Unlock()
_ = conn.Close()
r.conn = nil
func (r *TCPResolver) run(worker int32) {
for range worker {
r.wg.Add(1)
go r.worker()
}
r.wg.Wait()
close(r.readCh)
// close(r.sendCh)
}
func (r *TCPResolver) Addr() *net.UDPAddr {
r.mu.Lock()
defer r.mu.Unlock()
return r.udpAddr
}
@@ -119,27 +168,25 @@ func (r *TCPResolver) Read(p []byte) (n int, err error) {
}
func (r *TCPResolver) Send(p []byte) {
r.mu.Lock()
defer r.mu.Unlock()
if r.dial() != nil {
select {
case <-r.closeCh:
return
default:
b := make([]byte, len(p))
copy(b, p)
select {
case <-r.closeCh:
return
case r.sendCh <- b:
}
}
_ = binary.Write(r.conn, binary.BigEndian, len(p))
_, _ = r.conn.Write(p)
}
func (r *TCPResolver) Close() {
r.mu.Lock()
defer r.mu.Unlock()
if r.closed() {
r.mu.Unlock()
return
}
close(r.closeCh)
conn := r.conn
r.mu.Unlock()
if conn != nil {
_ = conn.Close()
}
r.wg.Wait()
close(r.readCh)
}
+34 -5
View File
@@ -32,6 +32,9 @@ type clientConn struct {
paddingSchedule []paddingTurn
packet *packetStream
deadlines *connectionDeadlines
done chan struct{}
closeOnce sync.Once
}
type clientState int
@@ -41,16 +44,15 @@ var (
clientStateProxy clientState = 2
)
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string) (*clientConn, error) {
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn) (*clientConn, error) {
if len(rsaPublicKey) == 0 {
return nil, fmt.Errorf("empty rsa public key")
}
if len(profiles) == 0 {
return nil, fmt.Errorf("empty profiles")
}
paddingSchedule, err := newClientPaddingSchedule2612()
if err != nil {
return nil, fmt.Errorf("select padding profile: %w", err)
if len(password) > MaxLegacyPasswordLength {
return nil, fmt.Errorf("password is longer than %d bytes", MaxLegacyPasswordLength)
}
return &clientConn{
reader: bufio.NewReader(c),
@@ -64,9 +66,15 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
hostname: hostname,
paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c),
done: make(chan struct{}),
}, nil
}
// paddingPause applies one padding pause, stopping early on Close.
func (c *clientConn) paddingPause(d time.Duration) error {
return pausePadding(c.done, d)
}
func (c *clientConn) handshake() error {
c.handshakeLock.Lock()
defer c.handshakeLock.Unlock()
@@ -195,6 +203,24 @@ func (c *clientConn) handshake() error {
if err != nil {
return fmt.Errorf("read login finished: %w", err)
}
// Set Compression is not compressed itself and must be handled before the
// packet that follows it, which already uses the compressed framing. The
// threshold only decides whether the framing applies: this writer never
// compresses, so a server-side threshold does not shrink padding turns.
if pkt.packetID == 0x03 {
var threshold Varint
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
}
if threshold >= 0 {
c.reader = newCompressionReader(c.reader)
c.writer = newCompressionWriter(c.writer)
}
pkt, err = readPacket(c.reader)
if err != nil {
return fmt.Errorf("read login finished: %w", err)
}
}
if pkt.packetID == 0x00 {
var reason String
if readErr := pkt.readFields(&reason); readErr != nil {
@@ -217,7 +243,9 @@ func (c *clientConn) handshake() error {
if err != nil {
return fmt.Errorf("write login acknowledged: %w", err)
}
if err = runPaddingSchedule(c.reader, c.writer, true, loginAcknowledgedLength, c.paddingSchedule); err != nil {
c.reader = newPaddingReader(c.reader, true)
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil {
_ = c.Close() // Unblock the startup reader if writing failed.
return fmt.Errorf("run startup padding: %w", err)
}
@@ -260,6 +288,7 @@ func (c *clientConn) Close() error {
c.closed = true
packet := c.packet
c.lifecycleMu.Unlock()
c.closeOnce.Do(func() { close(c.done) })
if packet != nil {
packet.Stop()
}
@@ -0,0 +1,180 @@
// Minecraft compression framing, negotiated by the login Set Compression packet.
// The reader decodes whatever the peer sends, including deflated bodies; the
// writer always sends the uncompressed variant.
package xmc
import (
"bytes"
"compress/zlib"
"fmt"
"io"
)
const (
// Packet Length is a VarInt, so one frame cannot exceed 2^21-1 bytes.
maxCompressedFrameLength = (1 << 21) - 1
// Vanilla caps serverbound uncompressed packet bodies at 2^23 bytes.
maxUncompressedFrameBody = 1 << 23
)
// compressionReader converts the post-Set Compression framing
// (Packet Length, Data Length, optional zlib body) back into the plain
// (VarInt body length, body) frame that readPacket expects.
//
// A zero Data Length means the body was sent uncompressed, which vanilla
// servers accept even when the body exceeds the negotiated threshold.
type compressionReader struct {
r io.Reader
frame bytes.Buffer
}
func newCompressionReader(r io.Reader) io.Reader {
return &compressionReader{r: r}
}
func (c *compressionReader) Read(p []byte) (int, error) {
if c.frame.Len() == 0 {
if err := c.readFrame(); err != nil {
return 0, err
}
}
return c.frame.Read(p)
}
func (c *compressionReader) readFrame() error {
packetLength, _, err := readVarintWithLength(c.r)
if err != nil {
return fmt.Errorf("read compressed packet length: %w", err)
}
if packetLength < 1 || int(packetLength) > maxCompressedFrameLength {
return fmt.Errorf("read compressed packet: bad length: %d", packetLength)
}
dataLength, dataLengthSize, err := readVarintWithLength(c.r)
if err != nil {
return fmt.Errorf("read compressed data length: %w", err)
}
if dataLength < 0 || int(dataLength) > maxUncompressedFrameBody {
return fmt.Errorf("read compressed packet: bad uncompressed length: %d", dataLength)
}
payloadLength := int(packetLength) - dataLengthSize
if payloadLength < 0 {
return fmt.Errorf("read compressed packet: bad length: %d", packetLength)
}
payload := make([]byte, payloadLength)
if _, err := io.ReadFull(c.r, payload); err != nil {
return fmt.Errorf("read compressed packet data: %w", err)
}
body := payload
if dataLength > 0 {
zr, err := zlib.NewReader(bytes.NewReader(payload))
if err != nil {
return fmt.Errorf("open compressed packet: %w", err)
}
body = make([]byte, int(dataLength))
_, readErr := io.ReadFull(zr, body)
closeErr := zr.Close()
if readErr != nil {
return fmt.Errorf("decompress packet: %w", readErr)
}
if closeErr != nil {
return fmt.Errorf("close decompressor: %w", closeErr)
}
}
if len(body) < 1 {
return fmt.Errorf("read compressed packet: empty body")
}
var frame bytes.Buffer
frame.Grow(varintSize(Varint(len(body))) + len(body))
bodyLength := Varint(len(body))
if err := bodyLength.writeTo(&frame); err != nil {
return err
}
frame.Write(body)
c.frame = frame
return nil
}
// compressionWriter converts a plain frame (VarInt body length, body) into the
// post-Set Compression framing. Frames are buffered until complete, because a
// caller may split one frame across several Write calls.
//
// It never compresses, whatever the negotiated threshold is. What XMC writes is
// padding and proxied bytes: the padding exists for its size on the wire, so
// deflating it would shrink a padded turn from tens of kilobytes to a hundred
// bytes and erase the shape it is there for, and proxied bytes are already
// encrypted or compressed by whoever produced them. Vanilla accepts an
// uncompressed body of any size when Data Length is zero, so the framing alone
// is enough to stay inside the protocol.
type compressionWriter struct {
w io.Writer
pending []byte
}
func newCompressionWriter(w io.Writer) io.Writer {
return &compressionWriter{w: w}
}
func (c *compressionWriter) Write(p []byte) (int, error) {
c.pending = append(c.pending, p...)
for {
body, ok, err := c.nextFrame()
if err != nil {
return 0, err
}
if !ok {
return len(p), nil
}
if err := c.writeFrame(body); err != nil {
return 0, err
}
}
}
// nextFrame returns one complete frame body from the pending bytes. It only
// waits for more bytes while the length prefix or the body is still
// incomplete; a complete but invalid prefix is an error.
func (c *compressionWriter) nextFrame() ([]byte, bool, error) {
limit := len(c.pending)
if limit > 5 {
limit = 5
}
bodyLength, prefixLength, err := readVarintWithLength(bytes.NewReader(c.pending[:limit]))
if err != nil {
if len(c.pending) < 5 {
return nil, false, nil
}
return nil, false, fmt.Errorf("read frame length: %w", err)
}
if bodyLength < 1 {
return nil, false, fmt.Errorf("read frame: bad length: %d", bodyLength)
}
end := prefixLength + int(bodyLength)
if end > len(c.pending) {
return nil, false, nil
}
// The body stays valid after the reslice: appends only write past the
// remaining pending length and writeFrame consumes it immediately.
body := c.pending[prefixLength:end]
c.pending = c.pending[end:]
return body, true, nil
}
func (c *compressionWriter) writeFrame(body []byte) error {
// Packet Length covers the Data Length varint and the body; a zero Data
// Length is the uncompressed variant.
packetLength := 1 + len(body)
var frame bytes.Buffer
frame.Grow(varintSize(Varint(packetLength)) + packetLength)
packetLengthVarint := Varint(packetLength)
if err := packetLengthVarint.writeTo(&frame); err != nil {
return err
}
frame.WriteByte(0)
frame.Write(body)
return writeFull(c.w, frame.Bytes())
}
@@ -0,0 +1,253 @@
package xmc
import (
"bytes"
"compress/zlib"
"crypto/rand"
"errors"
"io"
"testing"
)
func plainFrame(body []byte) []byte {
frame := make([]byte, 0, 5+len(body))
length := Varint(len(body))
var buf bytes.Buffer
_ = length.writeTo(&buf)
frame = append(frame, buf.Bytes()...)
return append(frame, body...)
}
type wireFrame struct {
packetLength int
dataLength int
payload []byte
}
func readWireFrame(t *testing.T, r *bytes.Reader) wireFrame {
t.Helper()
packetLength, _, err := readVarintWithLength(r)
if err != nil {
t.Fatalf("read packet length: %v", err)
}
dataLength, dataLengthSize, err := readVarintWithLength(r)
if err != nil {
t.Fatalf("read data length: %v", err)
}
payload := make([]byte, int(packetLength)-dataLengthSize)
if _, err := io.ReadFull(r, payload); err != nil {
t.Fatalf("read payload: %v", err)
}
return wireFrame{packetLength: int(packetLength), dataLength: int(dataLength), payload: payload}
}
func randomBody(t *testing.T, size int) []byte {
t.Helper()
body := make([]byte, size)
if _, err := rand.Read(body); err != nil {
t.Fatalf("random body: %v", err)
}
return body
}
// TestCompressionWriterNeverCompresses pins the write policy: whatever the
// negotiated threshold is, XMC sends the uncompressed framing so that a padding
// turn keeps its wire size. A padded turn of zeros would otherwise deflate from
// tens of kilobytes to a hundred bytes and the shape would be gone.
func TestCompressionWriterNeverCompresses(t *testing.T) {
for _, size := range []int{1, 10, 255, 256, 257, 32768, 65535, 65536} {
for _, body := range [][]byte{bytes.Repeat([]byte{0}, size), randomBody(t, size)} {
var wire bytes.Buffer
w := newCompressionWriter(&wire)
if _, err := w.Write(plainFrame(body)); err != nil {
t.Fatalf("size %d: write: %v", size, err)
}
frame := readWireFrame(t, bytes.NewReader(wire.Bytes()))
if frame.dataLength != 0 {
t.Fatalf("size %d: writer compressed the body (data length %d)", size, frame.dataLength)
}
if !bytes.Equal(frame.payload, body) {
t.Fatalf("size %d: payload mismatch", size)
}
if frame.packetLength != 1+size {
t.Fatalf("size %d: packet length %d, want %d", size, frame.packetLength, 1+size)
}
if wire.Len() != varintSize(Varint(1+size))+1+size {
t.Fatalf("size %d: frame is %d bytes on the wire, want %d", size, wire.Len(), varintSize(Varint(1+size))+1+size)
}
decoded, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("size %d: decode: %v", size, err)
}
if !bytes.Equal(decoded, body) {
t.Fatalf("size %d: round trip mismatch", size)
}
}
}
}
func TestCompressionRoundTripChunked(t *testing.T) {
cases := [][]byte{
[]byte("hello"),
randomBody(t, 255),
randomBody(t, 24*1024),
randomBody(t, 64*1024),
bytes.Repeat([]byte("xmc"), 8*1024),
}
var wire bytes.Buffer
w := newCompressionWriter(&wire)
// One Write per frame, split into awkward chunk sizes.
for _, body := range cases {
frame := plainFrame(body)
for len(frame) > 0 {
n := 7
if n > len(frame) {
n = len(frame)
}
if _, err := w.Write(frame[:n]); err != nil {
t.Fatalf("chunked write: %v", err)
}
frame = frame[n:]
}
}
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range cases {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("frame %d: decode: %v", i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("frame %d: mismatch (%d vs %d bytes)", i, len(got), len(want))
}
}
if _, _, err := readFrame(r, maxUncompressedFrameBody); !errors.Is(err, io.EOF) {
t.Fatalf("expected EOF after the last frame, got %v", err)
}
}
func TestCompressionMultipleFramesOneWrite(t *testing.T) {
var plain []byte
bodies := [][]byte{[]byte("a"), randomBody(t, 1024), randomBody(t, 300)}
for _, body := range bodies {
plain = append(plain, plainFrame(body)...)
}
var wire bytes.Buffer
w := newCompressionWriter(&wire)
if _, err := w.Write(plain); err != nil {
t.Fatalf("write: %v", err)
}
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range bodies {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("frame %d: decode: %v", i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("frame %d: mismatch", i)
}
}
}
// Vanilla servers accept uncompressed packets even when the body exceeds the
// negotiated threshold, which is what lets padding frames keep their wire size.
func TestCompressionReaderUncompressedOverThreshold(t *testing.T) {
body := randomBody(t, 64*1024)
var wire bytes.Buffer
length := Varint(1 + len(body))
if err := length.writeTo(&wire); err != nil {
t.Fatal(err)
}
wire.WriteByte(0)
wire.Write(body)
got, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("decode: %v", err)
}
if !bytes.Equal(got, body) {
t.Fatal("payload mismatch")
}
}
// The writer stopped compressing, but a real server still does, so the reader
// must keep decoding deflated bodies.
func TestCompressionReaderDecodesCompressedBody(t *testing.T) {
body := append(bytes.Repeat([]byte("xmc"), 4096), 0, 1, 2, 3)
var compressed bytes.Buffer
zw := zlib.NewWriter(&compressed)
if _, err := zw.Write(body); err != nil {
t.Fatal(err)
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
var wire bytes.Buffer
packetLength := Varint(varintSize(Varint(len(body))) + compressed.Len())
if err := packetLength.writeTo(&wire); err != nil {
t.Fatal(err)
}
dataLength := Varint(len(body))
if err := dataLength.writeTo(&wire); err != nil {
t.Fatal(err)
}
wire.Write(compressed.Bytes())
got, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("decode: %v", err)
}
if !bytes.Equal(got, body) {
t.Fatal("payload mismatch")
}
}
func TestCompressionReaderErrors(t *testing.T) {
// Compressed packet with a bogus body.
var badZlib bytes.Buffer
length := Varint(1 + 10)
_ = length.writeTo(&badZlib)
dataLength := Varint(64)
_ = dataLength.writeTo(&badZlib)
badZlib.Write(bytes.Repeat([]byte{0xff}, 10))
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(badZlib.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for an invalid zlib body")
}
// Uncompressed length beyond the vanilla limit.
var tooLong bytes.Buffer
length = Varint(1 + 4)
_ = length.writeTo(&tooLong)
dataLength = Varint(maxUncompressedFrameBody + 1)
_ = dataLength.writeTo(&tooLong)
tooLong.Write([]byte{1, 2, 3, 4})
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(tooLong.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for an oversized uncompressed length")
}
// Truncated payload.
var truncated bytes.Buffer
length = Varint(1 + 100)
_ = length.writeTo(&truncated)
var zero Varint
_ = zero.writeTo(&truncated)
truncated.Write([]byte{1, 2, 3})
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(truncated.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for a truncated payload")
}
}
func TestCompressionWriterInvalidFrameLength(t *testing.T) {
var wire bytes.Buffer
w := newCompressionWriter(&wire)
if _, err := w.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff}); err == nil {
t.Fatal("expected an error for an invalid frame length prefix")
}
}

Some files were not shown because too many files have changed in this diff Show More