mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-21 09:01:39 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e2b8ef1ad | ||
|
|
153eb771ac | ||
|
|
2a351fe2aa | ||
|
|
b1ef448a88 | ||
|
|
02decee3d2 | ||
|
|
9af8bb7f05 | ||
|
|
939ca80bed | ||
|
|
f781c68715 | ||
|
|
5d17b872ed | ||
|
|
c456141815 | ||
|
|
f082058590 | ||
|
|
e184d774a2 | ||
|
|
14df0738f3 | ||
|
|
36cc9ff510 | ||
|
|
c43ee98ec7 |
@@ -0,0 +1,5 @@
|
||||
<!--
|
||||
Read CONTRIBUTING.md before opening a pull request.
|
||||
Human-led pull requests can use a normal description.
|
||||
For agent-led pull requests, disclose each AI tool and model, then paste the complete conversation directly in a collapsed <details> block in this PR body. External transcript links are not accepted.
|
||||
-->
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"android-arm64": { "friendlyName": "android-arm64-v8a" },
|
||||
"android-amd64": { "friendlyName": "android-amd64" },
|
||||
"darwin-amd64": { "friendlyName": "macos-64" },
|
||||
"darwin-arm64": { "friendlyName": "macos-arm64-v8a" },
|
||||
"freebsd-386": { "friendlyName": "freebsd-32" },
|
||||
@@ -14,9 +15,7 @@
|
||||
"linux-arm7": { "friendlyName": "linux-arm32-v7a" },
|
||||
"linux-mips64le": { "friendlyName": "linux-mips64le" },
|
||||
"linux-mips64": { "friendlyName": "linux-mips64" },
|
||||
"linux-mipslesoftfloat": { "friendlyName": "linux-mips32le-softfloat" },
|
||||
"linux-mipsle": { "friendlyName": "linux-mips32le" },
|
||||
"linux-mipssoftfloat": { "friendlyName": "linux-mips32-softfloat" },
|
||||
"linux-mips": { "friendlyName": "linux-mips32" },
|
||||
"linux-ppc64le": { "friendlyName": "linux-ppc64le" },
|
||||
"linux-ppc64": { "friendlyName": "linux-ppc64" },
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Contributing to Xray-core
|
||||
|
||||
We review pull requests that address a concrete problem or an agreed proposal. Please keep each change focused and provide evidence that maintainers can check.
|
||||
|
||||
## Bug fixes
|
||||
|
||||
A bug-fix pull request must link an existing issue filed using the issue template. Summarize the code change and verification in the pull request, and add a regression test when practical. A speculative fix without a demonstrated problem is not ready for a pull request. Report security vulnerabilities through [the security policy](SECURITY.md) rather than a public issue.
|
||||
|
||||
## Features
|
||||
|
||||
Propose the use case and intended design in an issue before implementing it. Wait for a maintainer to accept the proposal. Explain how the change fits the existing architecture and any compatibility impact.
|
||||
|
||||
## Refactors
|
||||
|
||||
Propose the scope in an issue and wait for maintainer acceptance before implementing it. Show which complexity the change removes and why the resulting design is easier to understand. Prefer a reduction in code and moving parts, but line count alone is not the review criterion. Preserve observable behavior and test both old-to-new and new-to-old client/server connections when protocol or network behavior is affected.
|
||||
|
||||
## AI involvement and author responsibility
|
||||
|
||||
AI assistance does not require a conversation record when the author selects or verifies the problem, directs the approach, reviews every changed line, verifies the result, and personally responds to review feedback. The author must be able to explain every changed line and maintain the change. A pull request meeting these conditions is considered human-led, regardless of whether AI wrote the code or who pushed the commits. Such pull requests may ignore the agent-led requirements below.
|
||||
|
||||
If an AI agent independently selected the task or made key implementation decisions without ongoing human direction, the pull request is agent-led even if a person submits it manually. Disclose each tool and model and paste the complete prompt-and-response record for every session used for the pull request, including retries and changes after review feedback, inside a collapsed `<details>` block in the pull request description. External links, summaries, and selected excerpts are insufficient. A transcript does not replace the author's review, verification, or responsibility for responding to maintainers.
|
||||
|
||||
In agent-led pull requests, commits containing AI-generated changes must credit the specific LLM as their author or co-author.
|
||||
|
||||
We do not oppose the use of AI, but agent-led pull requests must have a human author who responds to maintainer feedback for several weeks after submission. Dishonest declarations, fabricated verification, intentionally incomplete records, or abandoning an agent-led pull request are prohibited and may result in being blocked from contributing to Xray-core.
|
||||
|
||||
## Review
|
||||
|
||||
Maintainers may ask for missing evidence before reviewing code or close a pull request that is outside the agreed scope. The contributor is responsible for understanding, testing, and explaining the change, regardless of the tools used to produce it.
|
||||
@@ -41,10 +41,10 @@
|
||||
|
||||
## Telegram
|
||||
|
||||
[Project X](https://t.me/projectXray)
|
||||
|
||||
[Project X Channel](https://t.me/projectXtls)
|
||||
|
||||
[Project X](https://t.me/projectXray) (中文 / English)
|
||||
|
||||
[Project VLESS](https://t.me/projectVless) (Русский)
|
||||
|
||||
[Project XHTTP](https://t.me/projectXhttp) (Persian)
|
||||
@@ -53,7 +53,6 @@
|
||||
|
||||
- Linux Script
|
||||
- [XTLS/Xray-install](https://github.com/XTLS/Xray-install) (**Official**)
|
||||
- [tempest](https://github.com/team-cloudchaser/tempest) (supports [`systemd`](https://systemd.io) and [OpenRC](https://github.com/OpenRC/openrc); Linux-only)
|
||||
- Docker
|
||||
- [ghcr.io/xtls/xray-core](https://ghcr.io/xtls/xray-core) (**Official**)
|
||||
- [teddysun/xray](https://hub.docker.com/r/teddysun/xray)
|
||||
@@ -69,12 +68,10 @@
|
||||
- [TX-UI](https://github.com/AghayeCoder/tx-ui)
|
||||
- [CELERITY](https://github.com/ClickDevTech/CELERITY-panel)
|
||||
- One Click
|
||||
- [Xray-REALITY](https://github.com/zxcvos/Xray-script), [xray-reality](https://github.com/sajjaddg/xray-reality), [reality-ezpz](https://github.com/aleskxyz/reality-ezpz)
|
||||
- [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey), [XTool](https://github.com/LordPenguin666/XTool), [VPainLess](https://github.com/vpainless/vpainless)
|
||||
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey), [ProxySU](https://github.com/proxysu/ProxySU)
|
||||
- [xray-reality](https://github.com/sajjaddg/xray-reality), [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey)
|
||||
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey)
|
||||
- Magisk
|
||||
- [Magic_V2Ray](https://github.com/vincentng295/Magic_V2Ray)
|
||||
- [Xray_For_Magisk](https://github.com/E7KMbb/Xray_For_Magisk)
|
||||
- Homebrew
|
||||
- `brew install xray`
|
||||
|
||||
@@ -86,14 +83,7 @@
|
||||
- [All-in-One-fallbacks-Nginx](https://github.com/XTLS/Xray-examples/tree/main/All-in-One-fallbacks-Nginx)
|
||||
- Xray-examples
|
||||
- [XTLS/Xray-examples](https://github.com/XTLS/Xray-examples)
|
||||
- [chika0801/Xray-examples](https://github.com/chika0801/Xray-examples)
|
||||
- [lxhao61/integrated-examples](https://github.com/lxhao61/integrated-examples)
|
||||
- Tutorial
|
||||
- [XTLS Vision](https://github.com/chika0801/Xray-install)
|
||||
- [REALITY (English)](https://cscot.pages.dev/2023/03/02/Xray-REALITY-tutorial/)
|
||||
- [XTLS-Iran-Reality (English)](https://github.com/SasukeFreestyle/XTLS-Iran-Reality)
|
||||
- [Xray REALITY with 'steal oneself' (English)](https://computerscot.github.io/vless-xtls-utls-reality-steal-oneself.html)
|
||||
- [Xray with WireGuard inbound (English)](https://g800.pages.dev/wireguard)
|
||||
|
||||
## GUI Clients
|
||||
|
||||
@@ -106,43 +96,31 @@
|
||||
- [fancyss](https://github.com/hq450/fancyss)
|
||||
- Windows
|
||||
- [v2rayN](https://github.com/2dust/v2rayN)
|
||||
- [Furious](https://github.com/LorenEteval/Furious)
|
||||
- [Invisible Man - Xray](https://github.com/InvisibleManVPN/InvisibleMan-XRayClient)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev)
|
||||
- Android
|
||||
- [v2rayNG](https://github.com/2dust/v2rayNG)
|
||||
- [X-flutter](https://github.com/XTLS/X-flutter)
|
||||
- [SaeedDev94/Xray](https://github.com/SaeedDev94/Xray)
|
||||
- [SimpleXray](https://github.com/lhear/SimpleXray)
|
||||
- [XrayFA](https://github.com/Q7DF1/XrayFA)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG)
|
||||
- iOS & macOS arm64 & tvOS
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
|
||||
- [Streisand](https://apps.apple.com/app/streisand/id6450534064)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [INCY](https://apps.apple.com/en/app/incy/id6756943388)
|
||||
- macOS arm64 & x64
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973)
|
||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215)
|
||||
- [V2rayU](https://github.com/yanue/V2rayU)
|
||||
- [V2RayXS](https://github.com/tzmax/V2RayXS)
|
||||
- [Furious](https://github.com/LorenEteval/Furious)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
- [GoXRay](https://github.com/goxray/desktop)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [v2rayN](https://github.com/2dust/v2rayN)
|
||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||
- [INCY](https://apps.apple.com/en/app/incy/id6756943388)
|
||||
- Linux
|
||||
- [v2rayA](https://github.com/v2rayA/v2rayA)
|
||||
- [Furious](https://github.com/LorenEteval/Furious)
|
||||
- [GorzRay](https://github.com/ketetefid/GorzRay)
|
||||
- [GoXRay](https://github.com/goxray/desktop)
|
||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||
- [v2rayN](https://github.com/2dust/v2rayN)
|
||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||
- [OneXray](https://github.com/OneXray/OneXray)
|
||||
@@ -163,24 +141,29 @@
|
||||
- Xray Wrapper
|
||||
- [XTLS/libXray](https://github.com/XTLS/libXray)
|
||||
- [xtls-sdk](https://github.com/remnawave/xtls-sdk)
|
||||
- [xtlsapi](https://github.com/hiddify/xtlsapi)
|
||||
- [AndroidLibXrayLite](https://github.com/2dust/AndroidLibXrayLite)
|
||||
- [flutter_vless](https://github.com/XIIIFOX/flutter_vless)
|
||||
- [Xray-core-python](https://github.com/LorenEteval/Xray-core-python)
|
||||
- [xray-api](https://github.com/XVGuardian/xray-api)
|
||||
- [XrayR](https://github.com/XrayR-project/XrayR)
|
||||
- [XrayR-release](https://github.com/XrayR-project/XrayR-release)
|
||||
- [XrayR-V2Board](https://github.com/missuo/XrayR-V2Board)
|
||||
- Cores
|
||||
- [Amnezia VPN](https://github.com/amnezia-vpn)
|
||||
- [mihomo](https://github.com/MetaCubeX/mihomo)
|
||||
- [sing-box](https://github.com/SagerNet/sing-box)
|
||||
|
||||
<details>
|
||||
<summary>Project listing criteria</summary>
|
||||
|
||||
To submit a project to the [README](https://github.com/XTLS/Xray-core#readme), open a [pull request](https://github.com/XTLS/Xray-core/pulls). Projects are listed under these rules:
|
||||
|
||||
- Projects must be based on Xray-core, have been maintained for at least one month, and have at least 30 stars.
|
||||
- Projects with no activity for three months will be removed.
|
||||
- **Closed-source iOS clients must be submitted by their developers.**
|
||||
|
||||
</details>
|
||||
|
||||
## Contributing
|
||||
|
||||
[Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md)
|
||||
For code contributions, please read [CONTRIBUTING.md](CONTRIBUTING.md) and [Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md) before opening a pull request.
|
||||
|
||||
[](https://deepwiki.com/XTLS/Xray-core)
|
||||
[Ask DeepWiki](https://deepwiki.com/XTLS/Xray-core) might be helpful.
|
||||
|
||||
## Credits
|
||||
|
||||
@@ -231,6 +214,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,12 +235,19 @@ 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
|
||||
|
||||
[](https://starchart.cc/XTLS/Xray-core)
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&theme=dark&legend=top-left" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
|
||||
</picture>
|
||||
|
||||
+13
-5
@@ -29,6 +29,7 @@ type MetricsHandler struct {
|
||||
listen string
|
||||
tcpListener xnet.Listener
|
||||
listener *OutboundListener
|
||||
server *http.Server
|
||||
}
|
||||
|
||||
// NewMetricsHandler creates a new MetricsHandler based on the given config.
|
||||
@@ -50,7 +51,8 @@ func (p *MetricsHandler) Type() interface{} {
|
||||
}
|
||||
|
||||
func (p *MetricsHandler) Start() error {
|
||||
handler := p.httpHandler()
|
||||
server := &http.Server{Handler: p.httpHandler()}
|
||||
p.server = server
|
||||
|
||||
// direct listen a port if listen is set
|
||||
if p.listen != "" {
|
||||
@@ -61,7 +63,7 @@ func (p *MetricsHandler) Start() error {
|
||||
p.tcpListener = TCPlistener
|
||||
errors.LogInfo(context.Background(), "Metrics server listening on ", p.listen)
|
||||
|
||||
go p.serve(TCPlistener, handler)
|
||||
go p.serve(TCPlistener, server)
|
||||
}
|
||||
|
||||
if p.tag == "" {
|
||||
@@ -77,7 +79,7 @@ func (p *MetricsHandler) Start() error {
|
||||
}
|
||||
p.listener = listener
|
||||
|
||||
go p.serve(listener, handler)
|
||||
go p.serve(listener, server)
|
||||
|
||||
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
|
||||
errors.LogInfo(context.Background(), "failed to remove existing handler")
|
||||
@@ -106,6 +108,12 @@ func (p *MetricsHandler) Close() error {
|
||||
errs = append(errs, p.listener.Close())
|
||||
p.listener = nil
|
||||
}
|
||||
if p.server != nil {
|
||||
if err := p.server.Close(); !isClosedListenerError(err) {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
p.server = nil
|
||||
}
|
||||
if p.ohm != nil && p.tag != "" {
|
||||
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
|
||||
errors.LogInfo(context.Background(), "failed to remove metrics handler")
|
||||
@@ -114,8 +122,8 @@ func (p *MetricsHandler) Close() error {
|
||||
return errors.Combine(errs...)
|
||||
}
|
||||
|
||||
func (p *MetricsHandler) serve(listener xnet.Listener, handler http.Handler) {
|
||||
if err := http.Serve(listener, handler); err != nil && !isClosedListenerError(err) {
|
||||
func (p *MetricsHandler) serve(listener xnet.Listener, server *http.Server) {
|
||||
if err := server.Serve(listener); err != nil && !isClosedListenerError(err) {
|
||||
errors.LogErrorInner(context.Background(), err, "failed to start metrics server")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !windows && !wasm && !illumos && !openbsd
|
||||
// +build !windows,!wasm,!illumos,!openbsd
|
||||
//go:build !windows && !openbsd
|
||||
|
||||
package buf
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !wasm && !openbsd
|
||||
// +build !wasm,!openbsd
|
||||
//go:build !openbsd
|
||||
|
||||
package buf
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build wasm || openbsd
|
||||
// +build wasm openbsd
|
||||
//go:build openbsd
|
||||
|
||||
package buf
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !wasm && !openbsd
|
||||
// +build !wasm,!openbsd
|
||||
//go:build !openbsd
|
||||
|
||||
package buf_test
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
//go:build illumos
|
||||
// +build illumos
|
||||
|
||||
package buf
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
type unixReader struct {
|
||||
iovs [][]byte
|
||||
}
|
||||
|
||||
func (r *unixReader) Init(bs []*Buffer) {
|
||||
iovs := r.iovs
|
||||
if iovs == nil {
|
||||
iovs = make([][]byte, 0, len(bs))
|
||||
}
|
||||
for _, b := range bs {
|
||||
iovs = append(iovs, b.v)
|
||||
}
|
||||
r.iovs = iovs
|
||||
}
|
||||
|
||||
func (r *unixReader) Read(fd uintptr) int32 {
|
||||
n, e := unix.Readv(int(fd), r.iovs)
|
||||
if e != nil {
|
||||
return -1
|
||||
}
|
||||
return int32(n)
|
||||
}
|
||||
|
||||
func (r *unixReader) Clear() {
|
||||
r.iovs = r.iovs[:0]
|
||||
}
|
||||
|
||||
func newMultiReader() multiReader {
|
||||
return &unixReader{}
|
||||
}
|
||||
@@ -236,6 +236,10 @@ func (w *BufferedWriter) Close() error {
|
||||
return common.Close(w.writer)
|
||||
}
|
||||
|
||||
func (w *BufferedWriter) Interrupt() {
|
||||
common.Interrupt(w.writer)
|
||||
}
|
||||
|
||||
// SequentialWriter is a Writer that writes MultiBuffer sequentially into the underlying io.Writer.
|
||||
type SequentialWriter struct {
|
||||
io.Writer
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build generate
|
||||
// +build generate
|
||||
|
||||
package main
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package platform
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package platform
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -932,9 +932,17 @@ 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"`
|
||||
}
|
||||
|
||||
type XMCPaddingTurn struct {
|
||||
Length string `json:"length"`
|
||||
Direction string `json:"direction"`
|
||||
// Delay is an optional millisecond value or inclusive min-max range.
|
||||
Delay string `json:"delay,omitempty"`
|
||||
}
|
||||
|
||||
type XMCProfile struct {
|
||||
@@ -977,6 +985,41 @@ 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)
|
||||
}
|
||||
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname}
|
||||
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 +1040,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 {
|
||||
|
||||
@@ -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,62 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build coveragemain
|
||||
// +build coveragemain
|
||||
|
||||
package main
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package dokodemo
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build openbsd
|
||||
// +build openbsd
|
||||
|
||||
package dokodemo
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !linux && !openbsd
|
||||
// +build !linux,!openbsd
|
||||
|
||||
package dokodemo
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build coverage
|
||||
// +build coverage
|
||||
|
||||
package scenarios
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !coverage
|
||||
// +build !coverage
|
||||
|
||||
package scenarios
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package internet
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !amd64
|
||||
// +build !amd64
|
||||
|
||||
package original
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -41,14 +41,17 @@ 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, padding []*Padding) (*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 len(password) > MaxLegacyPasswordLength {
|
||||
return nil, fmt.Errorf("password is longer than %d bytes", MaxLegacyPasswordLength)
|
||||
}
|
||||
paddingSchedule, err := newPaddingSchedule(padding, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select padding profile: %w", err)
|
||||
}
|
||||
@@ -195,6 +198,22 @@ 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.
|
||||
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, int32(threshold))
|
||||
}
|
||||
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 +236,7 @@ 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 {
|
||||
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule); err != nil {
|
||||
return fmt.Errorf("run startup padding: %w", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
// Minecraft compression framing, negotiated by the login Set Compression packet.
|
||||
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.
|
||||
type compressionWriter struct {
|
||||
w io.Writer
|
||||
threshold int32
|
||||
pending []byte
|
||||
}
|
||||
|
||||
func newCompressionWriter(w io.Writer, threshold int32) io.Writer {
|
||||
return &compressionWriter{w: w, threshold: threshold}
|
||||
}
|
||||
|
||||
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 {
|
||||
if len(body) >= int(c.threshold) {
|
||||
var compressed bytes.Buffer
|
||||
zw := zlib.NewWriter(&compressed)
|
||||
if _, err := zw.Write(body); err != nil {
|
||||
_ = zw.Close()
|
||||
return fmt.Errorf("compress packet: %w", err)
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
return fmt.Errorf("close compressor: %w", err)
|
||||
}
|
||||
|
||||
var frame bytes.Buffer
|
||||
packetLength := varintSize(Varint(len(body))) + compressed.Len()
|
||||
frame.Grow(varintSize(Varint(packetLength)) + packetLength)
|
||||
packetLengthVarint := Varint(packetLength)
|
||||
if err := packetLengthVarint.writeTo(&frame); err != nil {
|
||||
return err
|
||||
}
|
||||
bodyLength := Varint(len(body))
|
||||
if err := bodyLength.writeTo(&frame); err != nil {
|
||||
return err
|
||||
}
|
||||
frame.Write(compressed.Bytes())
|
||||
return writeFull(c.w, frame.Bytes())
|
||||
}
|
||||
|
||||
var frame bytes.Buffer
|
||||
frame.Grow(varintSize(Varint(1+len(body))) + 1 + len(body))
|
||||
frameLength := Varint(1 + len(body))
|
||||
if err := frameLength.writeTo(&frame); err != nil {
|
||||
return err
|
||||
}
|
||||
frame.WriteByte(0)
|
||||
frame.Write(body)
|
||||
return writeFull(c.w, frame.Bytes())
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"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
|
||||
}
|
||||
|
||||
func TestCompressionWriterThreshold(t *testing.T) {
|
||||
for _, threshold := range []int32{0, 1, 256, 65536} {
|
||||
for _, size := range []int{1, 10, 255, 256, 257, 65535, 65536} {
|
||||
body := bytes.Repeat([]byte{0}, size)
|
||||
var wire bytes.Buffer
|
||||
w := newCompressionWriter(&wire, threshold)
|
||||
if _, err := w.Write(plainFrame(body)); err != nil {
|
||||
t.Fatalf("threshold %d size %d: write: %v", threshold, size, err)
|
||||
}
|
||||
|
||||
frame := readWireFrame(t, bytes.NewReader(wire.Bytes()))
|
||||
wantCompressed := int32(size) >= threshold
|
||||
if wantCompressed && frame.dataLength != size {
|
||||
t.Fatalf("threshold %d size %d: want compressed data length %d, got %d", threshold, size, size, frame.dataLength)
|
||||
}
|
||||
if !wantCompressed {
|
||||
if frame.dataLength != 0 {
|
||||
t.Fatalf("threshold %d size %d: want uncompressed frame, got data length %d", threshold, size, frame.dataLength)
|
||||
}
|
||||
if !bytes.Equal(frame.payload, body) {
|
||||
t.Fatalf("threshold %d size %d: uncompressed payload mismatch", threshold, size)
|
||||
}
|
||||
if frame.packetLength != 1+size {
|
||||
t.Fatalf("threshold %d size %d: packet length %d", threshold, size, frame.packetLength)
|
||||
}
|
||||
}
|
||||
|
||||
decoded, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
|
||||
if err != nil {
|
||||
t.Fatalf("threshold %d size %d: decode: %v", threshold, size, err)
|
||||
}
|
||||
if !bytes.Equal(decoded, body) {
|
||||
t.Fatalf("threshold %d size %d: round trip mismatch", threshold, 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),
|
||||
}
|
||||
|
||||
for _, threshold := range []int32{0, 256, 65536} {
|
||||
var wire bytes.Buffer
|
||||
w := newCompressionWriter(&wire, threshold)
|
||||
// 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("threshold %d: chunked write: %v", threshold, 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("threshold %d frame %d: decode: %v", threshold, i, err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("threshold %d frame %d: mismatch (%d vs %d bytes)", threshold, i, len(got), len(want))
|
||||
}
|
||||
}
|
||||
if _, _, err := readFrame(r, maxUncompressedFrameBody); !errors.Is(err, io.EOF) {
|
||||
t.Fatalf("threshold %d: expected EOF after the last frame, got %v", threshold, 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, 256)
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
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, 256)
|
||||
if _, err := w.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff}); err == nil {
|
||||
t.Fatal("expected an error for an invalid frame length prefix")
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,28 @@ package xmc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask"
|
||||
)
|
||||
|
||||
// maxPaddingDelayMilliseconds keeps the millisecond value convertible to a
|
||||
// time.Duration on every platform.
|
||||
const maxPaddingDelayMilliseconds = int64(math.MaxInt64 / int64(time.Millisecond))
|
||||
|
||||
// MaxLegacyPasswordLength is the longest pre-shared password the login can
|
||||
// carry. The verify token (4 random bytes) and the password travel together in
|
||||
// one RSA-1024 PKCS#1 v1.5 block, which holds at most 128-11 bytes.
|
||||
const MaxLegacyPasswordLength = 128 - 11 - 4
|
||||
|
||||
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
|
||||
profiles, err := profilesFromConfig(c.Profiles)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname)
|
||||
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname, c.Paddings)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
@@ -25,10 +36,68 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey)
|
||||
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, c.Paddings)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
|
||||
return cc, nil
|
||||
}
|
||||
|
||||
// ValidatePadding checks custom startup turns without selecting a built-in preset.
|
||||
func (c *Config) ValidatePadding() error {
|
||||
_, err := paddingScheduleFromConfig(c.Paddings)
|
||||
return err
|
||||
}
|
||||
|
||||
func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) {
|
||||
if len(paddings) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
schedule := make([]paddingTurn, len(paddings))
|
||||
for i, turn := range paddings {
|
||||
if turn == nil || turn.LengthMin < 1 || turn.LengthMax < turn.LengthMin || turn.LengthMax > maxPaddingTurnLength {
|
||||
return nil, fmt.Errorf("invalid padding length range at turn %d", i)
|
||||
}
|
||||
if turn.DelayMin < 0 || turn.DelayMax < turn.DelayMin {
|
||||
return nil, fmt.Errorf("invalid padding delay range %d-%d at turn %d (must be non-negative and ordered)", turn.DelayMin, turn.DelayMax, i)
|
||||
}
|
||||
if turn.DelayMax > maxPaddingDelayMilliseconds {
|
||||
return nil, fmt.Errorf("padding delay range %d-%d at turn %d is too large", turn.DelayMin, turn.DelayMax, i)
|
||||
}
|
||||
var direction paddingDirection
|
||||
switch turn.Direction {
|
||||
case 1:
|
||||
direction = paddingClientToServer
|
||||
case 2:
|
||||
direction = paddingServerToClient
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid padding direction %d at turn %d (1=client-to-server, 2=server-to-client)", turn.Direction, i)
|
||||
}
|
||||
schedule[i] = paddingTurn{
|
||||
direction: direction,
|
||||
minLength: int(turn.LengthMin),
|
||||
maxLength: int(turn.LengthMax),
|
||||
delay: paddingDelayRange{
|
||||
min: time.Duration(turn.DelayMin) * time.Millisecond,
|
||||
max: time.Duration(turn.DelayMax) * time.Millisecond,
|
||||
},
|
||||
}
|
||||
}
|
||||
// The first turn includes the two-byte Login Acknowledged packet.
|
||||
if err := validatePaddingSchedule(schedule, 2); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return schedule, nil
|
||||
}
|
||||
|
||||
func newPaddingSchedule(paddings []*Padding, isClient bool) ([]paddingTurn, error) {
|
||||
schedule, err := paddingScheduleFromConfig(paddings)
|
||||
if err != nil || schedule != nil {
|
||||
return schedule, err
|
||||
}
|
||||
if isClient {
|
||||
return newClientPaddingSchedule2612()
|
||||
}
|
||||
return newServerPaddingSchedule2612()
|
||||
}
|
||||
|
||||
@@ -99,6 +99,8 @@ type Config struct {
|
||||
RsaPublicKey []byte `protobuf:"bytes,9,opt,name=rsa_public_key,json=rsaPublicKey,proto3" json:"rsa_public_key,omitempty"`
|
||||
Hostname string `protobuf:"bytes,10,opt,name=hostname,proto3" json:"hostname,omitempty"`
|
||||
Profiles []*Profile `protobuf:"bytes,11,rep,name=profiles,proto3" json:"profiles,omitempty"`
|
||||
// Startup padding turns. Empty uses the built-in preset.
|
||||
Paddings []*Padding `protobuf:"bytes,12,rep,name=paddings,proto3" json:"paddings,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -168,6 +170,93 @@ func (x *Config) GetProfiles() []*Profile {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Config) GetPaddings() []*Padding {
|
||||
if x != nil {
|
||||
return x.Paddings
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Padding struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"`
|
||||
LengthMax int64 `protobuf:"varint,2,opt,name=length_max,json=lengthMax,proto3" json:"length_max,omitempty"`
|
||||
// 1 = client to server, 2 = server to client
|
||||
Direction int32 `protobuf:"varint,3,opt,name=direction,proto3" json:"direction,omitempty"`
|
||||
// Millisecond pause after this turn, including the last one. The sender
|
||||
// waits for a uniformly selected value in [delay_min, delay_max]; the
|
||||
// receiver waits at least delay_min. Zero means no delay.
|
||||
DelayMin int64 `protobuf:"varint,4,opt,name=delay_min,json=delayMin,proto3" json:"delay_min,omitempty"`
|
||||
DelayMax int64 `protobuf:"varint,5,opt,name=delay_max,json=delayMax,proto3" json:"delay_max,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Padding) Reset() {
|
||||
*x = Padding{}
|
||||
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Padding) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Padding) ProtoMessage() {}
|
||||
|
||||
func (x *Padding) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Padding.ProtoReflect.Descriptor instead.
|
||||
func (*Padding) Descriptor() ([]byte, []int) {
|
||||
return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *Padding) GetLengthMin() int64 {
|
||||
if x != nil {
|
||||
return x.LengthMin
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Padding) GetLengthMax() int64 {
|
||||
if x != nil {
|
||||
return x.LengthMax
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Padding) GetDirection() int32 {
|
||||
if x != nil {
|
||||
return x.Direction
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Padding) GetDelayMin() int64 {
|
||||
if x != nil {
|
||||
return x.DelayMin
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Padding) GetDelayMax() int64 {
|
||||
if x != nil {
|
||||
return x.DelayMax
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var File_transport_internet_finalmask_xmc_config_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
|
||||
@@ -177,14 +266,23 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
|
||||
"\busername\x18\x01 \x01(\tR\busername\x12\x12\n" +
|
||||
"\x04uuid\x18\x02 \x01(\fR\x04uuid\x12%\n" +
|
||||
"\x0etextures_value\x18\x03 \x01(\tR\rtexturesValue\x12-\n" +
|
||||
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xe0\x01\n" +
|
||||
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xac\x02\n" +
|
||||
"\x06Config\x12\x1a\n" +
|
||||
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
|
||||
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
|
||||
"\x0ersa_public_key\x18\t \x01(\fR\frsaPublicKey\x12\x1a\n" +
|
||||
"\bhostname\x18\n" +
|
||||
" \x01(\tR\bhostname\x12J\n" +
|
||||
"\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofilesJ\x04\b\x02\x10\x03B\x91\x01\n" +
|
||||
"\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofiles\x12J\n" +
|
||||
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddingsJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
|
||||
"\aPadding\x12\x1d\n" +
|
||||
"\n" +
|
||||
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
|
||||
"\n" +
|
||||
"length_max\x18\x02 \x01(\x03R\tlengthMax\x12\x1c\n" +
|
||||
"\tdirection\x18\x03 \x01(\x05R\tdirection\x12\x1b\n" +
|
||||
"\tdelay_min\x18\x04 \x01(\x03R\bdelayMin\x12\x1b\n" +
|
||||
"\tdelay_max\x18\x05 \x01(\x03R\bdelayMaxB\x91\x01\n" +
|
||||
")com.xray.transport.internet.finalmask.xmcP\x01Z:github.com/xtls/xray-core/transport/internet/finalmask/xmc\xaa\x02%Xray.Transport.Internet.Finalmask.XMCb\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -199,18 +297,20 @@ func file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP() []byte {
|
||||
return file_transport_internet_finalmask_xmc_config_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
|
||||
var file_transport_internet_finalmask_xmc_config_proto_goTypes = []any{
|
||||
(*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile
|
||||
(*Config)(nil), // 1: xray.transport.internet.finalmask.xmc.Config
|
||||
(*Padding)(nil), // 2: xray.transport.internet.finalmask.xmc.Padding
|
||||
}
|
||||
var file_transport_internet_finalmask_xmc_config_proto_depIdxs = []int32{
|
||||
0, // 0: xray.transport.internet.finalmask.xmc.Config.profiles:type_name -> xray.transport.internet.finalmask.xmc.Profile
|
||||
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
|
||||
2, // 1: xray.transport.internet.finalmask.xmc.Config.paddings:type_name -> xray.transport.internet.finalmask.xmc.Padding
|
||||
2, // [2:2] is the sub-list for method output_type
|
||||
2, // [2:2] is the sub-list for method input_type
|
||||
2, // [2:2] is the sub-list for extension type_name
|
||||
2, // [2:2] is the sub-list for extension extendee
|
||||
0, // [0:2] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_transport_internet_finalmask_xmc_config_proto_init() }
|
||||
@@ -224,7 +324,7 @@ func file_transport_internet_finalmask_xmc_config_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_xmc_config_proto_rawDesc), len(file_transport_internet_finalmask_xmc_config_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumMessages: 3,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
|
||||
@@ -23,4 +23,18 @@ message Config {
|
||||
bytes rsa_public_key = 9;
|
||||
string hostname = 10;
|
||||
repeated Profile profiles = 11;
|
||||
// Startup padding turns. Empty uses the built-in preset.
|
||||
repeated Padding paddings = 12;
|
||||
}
|
||||
|
||||
message Padding {
|
||||
int64 length_min = 1;
|
||||
int64 length_max = 2;
|
||||
// 1 = client to server, 2 = server to client
|
||||
int32 direction = 3;
|
||||
// Millisecond pause after this turn, including the last one. The sender
|
||||
// waits for a uniformly selected value in [delay_min, delay_max]; the
|
||||
// receiver waits at least delay_min. Zero means no delay.
|
||||
int64 delay_min = 4;
|
||||
int64 delay_max = 5;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClientRejectsLongLegacyPassword(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer client.Close()
|
||||
defer server.Close()
|
||||
|
||||
profiles := []loginProfile{{Username: "TestUser"}}
|
||||
publicKey := []byte{0x01}
|
||||
|
||||
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil); err != nil {
|
||||
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
|
||||
}
|
||||
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil); err == nil {
|
||||
t.Fatal("expected the long password to be rejected")
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestConnectionDeadlinesRestoreCallerValues(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer client.Close()
|
||||
defer server.Close()
|
||||
|
||||
recording := &deadlineRecordingConn{Conn: client}
|
||||
deadlines := newConnectionDeadlines(recording)
|
||||
callerDeadline := time.Now().Add(10 * time.Minute)
|
||||
if err := deadlines.setDeadline(callerDeadline); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := deadlines.beginHandshake(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
read, write := recording.currentDeadlines()
|
||||
if !read.Before(callerDeadline) || !write.Before(callerDeadline) {
|
||||
t.Fatalf("handshake deadlines = %s/%s, caller = %s", read, write, callerDeadline)
|
||||
}
|
||||
|
||||
shortReadDeadline := time.Now().Add(time.Second)
|
||||
if err := deadlines.setReadDeadline(shortReadDeadline); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read, _ = recording.currentDeadlines()
|
||||
if !read.Equal(shortReadDeadline) {
|
||||
t.Fatalf("read deadline = %s, want %s", read, shortReadDeadline)
|
||||
}
|
||||
|
||||
if err := deadlines.endHandshake(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read, write = recording.currentDeadlines()
|
||||
if !read.Equal(shortReadDeadline) || !write.Equal(callerDeadline) {
|
||||
t.Fatalf("restored deadlines = %s/%s, want %s/%s", read, write, shortReadDeadline, callerDeadline)
|
||||
}
|
||||
}
|
||||
|
||||
type deadlineRecordingConn struct {
|
||||
net.Conn
|
||||
mu sync.Mutex
|
||||
read time.Time
|
||||
write time.Time
|
||||
}
|
||||
|
||||
func (c *deadlineRecordingConn) SetDeadline(t time.Time) error {
|
||||
c.mu.Lock()
|
||||
c.read = t
|
||||
c.write = t
|
||||
c.mu.Unlock()
|
||||
return c.Conn.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (c *deadlineRecordingConn) SetReadDeadline(t time.Time) error {
|
||||
c.mu.Lock()
|
||||
c.read = t
|
||||
c.mu.Unlock()
|
||||
return c.Conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (c *deadlineRecordingConn) SetWriteDeadline(t time.Time) error {
|
||||
c.mu.Lock()
|
||||
c.write = t
|
||||
c.mu.Unlock()
|
||||
return c.Conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (c *deadlineRecordingConn) currentDeadlines() (time.Time, time.Time) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.read, c.write
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDeriveRSAKey(t *testing.T) {
|
||||
password := "my-very-secret-password-12345"
|
||||
|
||||
key1, err := DeriveRSAKey(password)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to derive key: %v", err)
|
||||
}
|
||||
|
||||
err = key1.Validate()
|
||||
if err != nil {
|
||||
t.Fatalf("key is not valid RSA key: %v", err)
|
||||
}
|
||||
|
||||
key2, err := DeriveRSAKey(password)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to derive key second time: %v", err)
|
||||
}
|
||||
|
||||
// Verify determinism
|
||||
if key1.D.Cmp(key2.D) != 0 || key1.N.Cmp(key2.N) != 0 {
|
||||
t.Errorf("derived keys are not identical for the same password")
|
||||
}
|
||||
|
||||
// Verify different passwords yield different keys
|
||||
keyDifferent, err := DeriveRSAKey(password + "-different")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to derive different key: %v", err)
|
||||
}
|
||||
|
||||
if key1.D.Cmp(keyDifferent.D) == 0 || key1.N.Cmp(keyDifferent.N) == 0 {
|
||||
t.Errorf("derived keys are identical for different passwords")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveRSAKeyGoldenPrivateKey(t *testing.T) {
|
||||
const password = "deterministic-rsa-key-golden"
|
||||
const wantPKCS1DERHash = "3a8c4ad56a6fb42dab73c4d5fc3af754460a2db1441edc0970cbc7f4e0798d2f"
|
||||
|
||||
key, err := DeriveRSAKey(password)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to derive key: %v", err)
|
||||
}
|
||||
|
||||
gotHash := sha256.Sum256(x509.MarshalPKCS1PrivateKey(key))
|
||||
got := hex.EncodeToString(gotHash[:])
|
||||
if got != wantPKCS1DERHash {
|
||||
t.Fatalf("derived private key changed\nwant sha256: %s\n got sha256: %s", wantPKCS1DERHash, got)
|
||||
}
|
||||
}
|
||||
@@ -1,390 +0,0 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func deriveTestRSAKey(t *testing.T, password string) ([]byte, []byte) {
|
||||
t.Helper()
|
||||
|
||||
key, err := DeriveRSAKey(password)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to derive rsa key: %v", err)
|
||||
}
|
||||
|
||||
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to marshal public key: %v", err)
|
||||
}
|
||||
|
||||
return x509.MarshalPKCS1PrivateKey(key), publicKey
|
||||
}
|
||||
|
||||
func testLoginProfile(username string) loginProfile {
|
||||
profile := loginProfile{
|
||||
Username: username,
|
||||
TexturesValue: strings.Repeat("texture-value-", 40),
|
||||
TexturesSignature: strings.Repeat("texture-signature-", 24),
|
||||
}
|
||||
digest := sha256.Sum256([]byte(username))
|
||||
copy(profile.UUID[:], digest[:16])
|
||||
profile.UUID[6] = (profile.UUID[6] & 0x0f) | 0x40
|
||||
profile.UUID[8] = (profile.UUID[8] & 0x3f) | 0x80
|
||||
return profile
|
||||
}
|
||||
|
||||
func TestHandshakeSuccess(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to listen: %v", err)
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
password := "super-secure-shared-key-12345"
|
||||
profiles := []loginProfile{testLoginProfile("test_user")}
|
||||
privateKey, publicKey := deriveTestRSAKey(t, password)
|
||||
|
||||
go func() {
|
||||
rawConn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer rawConn.Close()
|
||||
|
||||
server, err := wrapConnServer(rawConn, profiles, password, privateKey, publicKey)
|
||||
if err != nil {
|
||||
t.Errorf("failed to wrap server: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
buf := make([]byte, 1024)
|
||||
n, err := server.Read(buf)
|
||||
if err != nil {
|
||||
t.Errorf("server read error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !bytes.Equal(buf[:n], []byte("hello server")) {
|
||||
t.Errorf("unexpected payload from client: %s", string(buf[:n]))
|
||||
return
|
||||
}
|
||||
|
||||
_, err = server.Write([]byte("hello client"))
|
||||
if err != nil {
|
||||
t.Errorf("server write error: %v", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
clientRaw, err := net.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to dial: %v", err)
|
||||
}
|
||||
defer clientRaw.Close()
|
||||
|
||||
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create client: %v", err)
|
||||
}
|
||||
|
||||
_, err = client.Write([]byte("hello server"))
|
||||
if err != nil {
|
||||
t.Fatalf("client write error: %v", err)
|
||||
}
|
||||
|
||||
buf := make([]byte, 1024)
|
||||
n, err := client.Read(buf)
|
||||
if err != nil {
|
||||
t.Fatalf("client read error: %v", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(buf[:n], []byte("hello client")) {
|
||||
t.Errorf("unexpected payload from server: %s", string(buf[:n]))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandshakePasswordMismatch(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to listen: %v", err)
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
clientPassword := "client-secret-123"
|
||||
serverPassword := "server-secret-456"
|
||||
profiles := []loginProfile{testLoginProfile("test_user")}
|
||||
serverPrivateKey, serverPublicKey := deriveTestRSAKey(t, serverPassword)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
rawConn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer rawConn.Close()
|
||||
|
||||
server, err := wrapConnServer(rawConn, profiles, serverPassword, serverPrivateKey, serverPublicKey)
|
||||
if err != nil {
|
||||
// Wrapping is synchronous and shouldn't fail initially simply because key derivation works with any string
|
||||
t.Logf("wrapped server: %v", err)
|
||||
}
|
||||
|
||||
// When client sends data, handshake happens and should fail
|
||||
buf := make([]byte, 1024)
|
||||
_, err = server.Read(buf)
|
||||
if err == nil {
|
||||
t.Errorf("expected handshake to fail due to password mismatch, but it succeeded")
|
||||
} else {
|
||||
t.Logf("server read failed as expected: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
clientRaw, err := net.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to dial: %v", err)
|
||||
}
|
||||
defer clientRaw.Close()
|
||||
|
||||
client, err := newClientConn(clientRaw, profiles, clientPassword, serverPublicKey, "localhost")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create client: %v", err)
|
||||
}
|
||||
|
||||
err = client.handshake()
|
||||
if err == nil {
|
||||
t.Fatal("expected client handshake to fail due to password mismatch")
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Check if we lost connection or received error
|
||||
t.Log("Handshake mismatch tested")
|
||||
}
|
||||
|
||||
func TestHandshakeNetPipeWithKeepAlive(t *testing.T) {
|
||||
clientRaw, serverRaw := net.Pipe()
|
||||
defer clientRaw.Close()
|
||||
defer serverRaw.Close()
|
||||
|
||||
const password = "net-pipe-shared-key"
|
||||
profiles := []loginProfile{testLoginProfile("pipe_user")}
|
||||
privateKey, publicKey := deriveTestRSAKey(t, password)
|
||||
serverDone := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
server, err := wrapConnServer(serverRaw, profiles, password, privateKey, publicKey)
|
||||
if err != nil {
|
||||
serverDone <- err
|
||||
return
|
||||
}
|
||||
|
||||
request := make([]byte, len("hello server"))
|
||||
if _, err = io.ReadFull(server, request); err != nil {
|
||||
serverDone <- fmt.Errorf("read request: %w", err)
|
||||
return
|
||||
}
|
||||
if string(request) != "hello server" {
|
||||
serverDone <- fmt.Errorf("unexpected request: %q", request)
|
||||
return
|
||||
}
|
||||
|
||||
followupDone := make(chan error, 1)
|
||||
go func() {
|
||||
followup := make([]byte, len("after keepalive"))
|
||||
_, readErr := io.ReadFull(server, followup)
|
||||
if readErr == nil && string(followup) != "after keepalive" {
|
||||
readErr = fmt.Errorf("unexpected followup: %q", followup)
|
||||
}
|
||||
followupDone <- readErr
|
||||
}()
|
||||
|
||||
if err = server.packet.writeKeepAlive(Long(42)); err != nil {
|
||||
serverDone <- fmt.Errorf("write keep-alive: %w", err)
|
||||
return
|
||||
}
|
||||
if _, err = server.Write([]byte("hello client")); err != nil {
|
||||
serverDone <- fmt.Errorf("write response: %w", err)
|
||||
return
|
||||
}
|
||||
serverDone <- <-followupDone
|
||||
}()
|
||||
|
||||
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = client.Write([]byte("hello server")); err != nil {
|
||||
t.Fatalf("write request: %v", err)
|
||||
}
|
||||
response := make([]byte, len("hello client"))
|
||||
if _, err = io.ReadFull(client, response); err != nil {
|
||||
t.Fatalf("read response: %v", err)
|
||||
}
|
||||
if string(response) != "hello client" {
|
||||
t.Fatalf("unexpected response: %q", response)
|
||||
}
|
||||
if _, err = client.Write([]byte("after keepalive")); err != nil {
|
||||
t.Fatalf("write followup: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err = <-serverDone:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("net.Pipe handshake timed out")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusQueryUnaffected(t *testing.T) {
|
||||
clientRaw, serverRaw := net.Pipe()
|
||||
defer clientRaw.Close()
|
||||
defer serverRaw.Close()
|
||||
|
||||
const password = "status-shared-key"
|
||||
profiles := []loginProfile{testLoginProfile("status_user")}
|
||||
privateKey, publicKey := deriveTestRSAKey(t, password)
|
||||
serverDone := make(chan error, 1)
|
||||
go func() {
|
||||
server, err := wrapConnServer(serverRaw, profiles, password, privateKey, publicKey)
|
||||
if err == nil {
|
||||
err = server.handshake()
|
||||
}
|
||||
serverDone <- err
|
||||
}()
|
||||
|
||||
protocolVersion := Varint(775)
|
||||
serverAddress := String("localhost")
|
||||
serverPort := UnsignedShort(25565)
|
||||
nextState := Varint(1)
|
||||
if err := writePacket(clientRaw, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writePacket(clientRaw, 0x00); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response, err := readPacket(clientRaw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.packetID != 0x00 {
|
||||
t.Fatalf("status packet id = %d", response.packetID)
|
||||
}
|
||||
var responseJSON String
|
||||
if err = response.readFields(&responseJSON); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(responseJSON) != statusResponse {
|
||||
t.Fatalf("status response = %q", responseJSON)
|
||||
}
|
||||
|
||||
payload := Long(0x0102030405060708)
|
||||
if err = writePacket(clientRaw, 0x01, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pong, err := readPacket(clientRaw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var receivedPayload Long
|
||||
if pong.packetID != 0x01 {
|
||||
t.Fatalf("pong packet id = %d", pong.packetID)
|
||||
}
|
||||
if err = pong.readFields(&receivedPayload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if receivedPayload != payload {
|
||||
t.Fatalf("pong payload = %x", receivedPayload)
|
||||
}
|
||||
|
||||
select {
|
||||
case err = <-serverDone:
|
||||
if err == nil || !strings.Contains(err.Error(), "ping") {
|
||||
t.Fatalf("server error = %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("status handshake timed out")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientHandshakeHonorsCallerDeadline(t *testing.T) {
|
||||
clientRaw, serverRaw := net.Pipe()
|
||||
defer clientRaw.Close()
|
||||
defer serverRaw.Close()
|
||||
|
||||
const password = "deadline-shared-key"
|
||||
profiles := []loginProfile{testLoginProfile("deadline_user")}
|
||||
_, publicKey := deriveTestRSAKey(t, password)
|
||||
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = client.SetDeadline(time.Now().Add(30 * time.Millisecond)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
_, err = client.Write([]byte("blocked"))
|
||||
var netErr net.Error
|
||||
if !errors.As(err, &netErr) || !netErr.Timeout() {
|
||||
t.Fatalf("error = %v, want network timeout", err)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed > 500*time.Millisecond {
|
||||
t.Fatalf("caller deadline took %s", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCloseInterruptsHandshake(t *testing.T) {
|
||||
clientRaw, serverRaw := net.Pipe()
|
||||
defer serverRaw.Close()
|
||||
|
||||
const password = "close-shared-key"
|
||||
profiles := []loginProfile{testLoginProfile("close_user")}
|
||||
_, publicKey := deriveTestRSAKey(t, password)
|
||||
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, writeErr := client.Write([]byte("blocked"))
|
||||
done <- writeErr
|
||||
}()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if err = client.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err = <-done:
|
||||
if err == nil {
|
||||
t.Fatal("handshake unexpectedly succeeded after close")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("close did not interrupt handshake")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateLoginAcknowledgedPacketRejectsData(t *testing.T) {
|
||||
if err := validateLoginAcknowledgedPacket(&mcPacket{packetID: 0x03}); err != nil {
|
||||
t.Fatalf("valid login acknowledged packet: %v", err)
|
||||
}
|
||||
if err := validateLoginAcknowledgedPacket(&mcPacket{packetID: 0x03, data: []byte{0x00}}); err == nil {
|
||||
t.Fatal("login acknowledged packet with trailing data was accepted")
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPacketStreamUsesPlainFraming(t *testing.T) {
|
||||
payload := []byte("hello")
|
||||
var wire bytes.Buffer
|
||||
stream := newPacketStream(bytes.NewReader(nil), &wire, true)
|
||||
|
||||
written, err := stream.Write(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("write payload: %v", err)
|
||||
}
|
||||
if written != len(payload) {
|
||||
t.Fatalf("written = %d, want %d", written, len(payload))
|
||||
}
|
||||
wantOutbound := []byte{0x0f, 0x02, 0x08, 'x', 'm', 'c', ':', 'd', 'a', 't', 'a', 'h', 'e', 'l', 'l', 'o'}
|
||||
if !bytes.Equal(wire.Bytes(), wantOutbound) {
|
||||
t.Fatalf("wire frame = %x, want %x", wire.Bytes(), wantOutbound)
|
||||
}
|
||||
|
||||
wantInbound := append([]byte(nil), wantOutbound...)
|
||||
wantInbound[1] = configurationClientboundCustomPayload
|
||||
reader := newPacketStream(bytes.NewReader(wantInbound), io.Discard, true)
|
||||
got := make([]byte, len(payload))
|
||||
if _, err = io.ReadFull(reader, got); err != nil {
|
||||
t.Fatalf("read payload: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("payload = %q, want %q", got, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketStreamRoundTrip(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
const password = "packet-stream-shared-key"
|
||||
privateKey, publicKey := deriveTestRSAKey(t, password)
|
||||
profiles := []loginProfile{testLoginProfile("packet_user")}
|
||||
clientPayload := bytes.Repeat([]byte("client-payload-"), 5000)
|
||||
serverPayload := bytes.Repeat([]byte("server-payload-"), 5000)
|
||||
serverDone := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
rawConn, acceptErr := ln.Accept()
|
||||
if acceptErr != nil {
|
||||
serverDone <- acceptErr
|
||||
return
|
||||
}
|
||||
defer rawConn.Close()
|
||||
|
||||
server, wrapErr := wrapConnServer(rawConn, profiles, password, privateKey, publicKey)
|
||||
if wrapErr != nil {
|
||||
serverDone <- wrapErr
|
||||
return
|
||||
}
|
||||
got := make([]byte, len(clientPayload))
|
||||
if _, readErr := io.ReadFull(server, got); readErr != nil {
|
||||
serverDone <- readErr
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(got, clientPayload) {
|
||||
serverDone <- io.ErrUnexpectedEOF
|
||||
return
|
||||
}
|
||||
_, writeErr := server.Write(serverPayload)
|
||||
serverDone <- writeErr
|
||||
}()
|
||||
|
||||
rawClient, err := net.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rawClient.Close()
|
||||
|
||||
client, err := newClientConn(rawClient, profiles, password, publicKey, "localhost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = client.Write(clientPayload); err != nil {
|
||||
t.Fatalf("write payload: %v", err)
|
||||
}
|
||||
got := make([]byte, len(serverPayload))
|
||||
if _, err = io.ReadFull(client, got); err != nil {
|
||||
t.Fatalf("read payload: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, serverPayload) {
|
||||
t.Fatal("server payload mismatch")
|
||||
}
|
||||
if err = <-serverDone; err != nil {
|
||||
t.Fatalf("server: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -18,8 +17,21 @@ const (
|
||||
paddingBufferLength = 16 * 1024
|
||||
maxPaddingChunkLength = 48 * 1024
|
||||
maxPaddingTurnLength = 8 * 1024 * 1024
|
||||
|
||||
// Frame padding carries the startup padding in ordinary Minecraft custom
|
||||
// payload packets so that a vanilla server can parse the whole connection
|
||||
// without taking the pipeline over. The channel is deliberately different
|
||||
// from the packet stream channel: both ends drop unknown payloads.
|
||||
paddingFrameChannel = "xmc:pad"
|
||||
// Serverbound custom payload data is capped at 32767 bytes by
|
||||
// ServerboundCustomPayloadPacket; keep the same budget in both directions.
|
||||
maxPaddingFrameDataLength = 32767
|
||||
// Length varint, packet id, channel length varint and the channel itself.
|
||||
paddingFrameOverhead = 1 + 1 + 1 + len(paddingFrameChannel)
|
||||
)
|
||||
|
||||
var maxPaddingFrameLength = paddingFrameLength(maxPaddingFrameDataLength)
|
||||
|
||||
type paddingVariant struct {
|
||||
chunks []int
|
||||
delays []paddingDelayRange
|
||||
@@ -34,6 +46,7 @@ type paddingTurn struct {
|
||||
direction paddingDirection
|
||||
minLength int
|
||||
maxLength int
|
||||
delay paddingDelayRange // pause after this turn, including the last one
|
||||
variants []paddingVariant
|
||||
startDelay paddingDelayRange
|
||||
chunkDelay paddingDelayRange
|
||||
@@ -44,27 +57,40 @@ type paddingTurn struct {
|
||||
sendVariants []int
|
||||
}
|
||||
|
||||
func runPaddingSchedule(reader io.Reader, writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn) error {
|
||||
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn) error {
|
||||
return runPaddingScheduleWithSleep(writer, isClient, firstTurnPrefixLength, schedule, time.Sleep)
|
||||
}
|
||||
|
||||
func runPaddingScheduleWithSleep(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration)) error {
|
||||
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var writeBuffer []byte
|
||||
for i, turn := range schedule {
|
||||
prefixLength := 0
|
||||
if i == 0 {
|
||||
prefixLength = firstTurnPrefixLength
|
||||
}
|
||||
|
||||
localSends := isClient == (turn.direction == paddingClientToServer)
|
||||
if localSends {
|
||||
if err := writePaddingTurnWithBuffer(writer, turn, prefixLength, time.Sleep, &writeBuffer); err != nil {
|
||||
return fmt.Errorf("write padding turn %d: %w", i, err)
|
||||
if isClient != (turn.direction == paddingClientToServer) {
|
||||
// Padding is ordinary Minecraft traffic, so the peer's turns are
|
||||
// never consumed here: they stay in the stream and are dropped as
|
||||
// unknown packets by whoever reads it next. Both endpoints still
|
||||
// apply the same minimum pause, including after the last turn.
|
||||
if turn.delay.min > 0 {
|
||||
sleep(turn.delay.min)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := readPaddingTurn(reader, turn, prefixLength); err != nil {
|
||||
return fmt.Errorf("read padding turn %d: %w", i, err)
|
||||
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
|
||||
return fmt.Errorf("write padding turn %d: %w", i, err)
|
||||
}
|
||||
delay, err := randomPaddingDelay(turn.delay)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select padding turn %d delay: %w", i, err)
|
||||
}
|
||||
if delay > 0 {
|
||||
sleep(delay)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -91,6 +117,9 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
|
||||
if err := validatePaddingDelayRange(turn.chunkDelay); err != nil {
|
||||
return fmt.Errorf("padding turn %d has an invalid chunk delay: %w", i, err)
|
||||
}
|
||||
if err := validatePaddingDelayRange(turn.delay); err != nil {
|
||||
return fmt.Errorf("padding turn %d has an invalid inter-turn delay: %w", i, err)
|
||||
}
|
||||
if turn.writeChunkMinLength < 0 || turn.writeChunkLength < turn.writeChunkMinLength || turn.writeChunkLength > maxPaddingChunkLength {
|
||||
return fmt.Errorf("padding turn %d has an invalid write chunk range: %d-%d", i, turn.writeChunkMinLength, turn.writeChunkLength)
|
||||
}
|
||||
@@ -121,25 +150,27 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
|
||||
}
|
||||
}
|
||||
}
|
||||
if i > 0 && turn.direction == schedule[i-1].direction {
|
||||
return fmt.Errorf("padding turns %d and %d have the same direction", i-1, i)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writePaddingTurn(w io.Writer, turn paddingTurn, prefixLength int) error {
|
||||
return writePaddingTurnWithSleep(w, turn, prefixLength, time.Sleep)
|
||||
// paddingFramePacketID returns the configuration-state custom payload packet id
|
||||
// used by the side that sends the padding bytes; both values come from the
|
||||
// vanilla configuration protocol, so no proxy-specific id ever reaches the wire.
|
||||
func paddingFramePacketID(isClient bool) int {
|
||||
if isClient {
|
||||
return configurationServerboundCustomPayload
|
||||
}
|
||||
return configurationClientboundCustomPayload
|
||||
}
|
||||
|
||||
func writePaddingTurnWithSleep(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration)) error {
|
||||
return writePaddingTurnWithBuffer(w, turn, prefixLength, sleep, nil)
|
||||
}
|
||||
|
||||
func writePaddingTurnWithBuffer(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration), reusableBuffer *[]byte) error {
|
||||
// writePaddingTurnFrames writes one padding turn as a sequence of valid
|
||||
// Minecraft custom payload frames. Only the framing is native: payload bodies
|
||||
// stay zero-filled, so the captured traffic shape is kept.
|
||||
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration), packetID int) (int, error) {
|
||||
startDelay, err := randomPaddingDelay(turn.startDelay)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select padding start delay: %w", err)
|
||||
return 0, fmt.Errorf("select padding start delay: %w", err)
|
||||
}
|
||||
if startDelay > 0 {
|
||||
sleep(startDelay)
|
||||
@@ -147,17 +178,11 @@ func writePaddingTurnWithBuffer(w io.Writer, turn paddingTurn, prefixLength int,
|
||||
|
||||
targetLength, chunks, delays, err := selectPaddingVariant(turn, prefixLength)
|
||||
if err != nil {
|
||||
return err
|
||||
return 0, err
|
||||
}
|
||||
recordLength := targetLength - prefixLength
|
||||
if recordLength < 1 {
|
||||
return fmt.Errorf("target length %d leaves an invalid record length %d", targetLength, recordLength)
|
||||
}
|
||||
|
||||
encodedLength := Varint(recordLength)
|
||||
var header bytes.Buffer
|
||||
if err = encodedLength.writeTo(&header); err != nil {
|
||||
return fmt.Errorf("write padding header: %w", err)
|
||||
payloadLength := targetLength - prefixLength
|
||||
if payloadLength < 1 {
|
||||
return 0, fmt.Errorf("target length %d leaves an invalid padding payload of %d bytes", targetLength, payloadLength)
|
||||
}
|
||||
if len(chunks) == 0 {
|
||||
writeChunkLength := turn.writeChunkLength
|
||||
@@ -166,89 +191,103 @@ func writePaddingTurnWithBuffer(w io.Writer, turn paddingTurn, prefixLength int,
|
||||
} else if turn.writeChunkMinLength > 0 {
|
||||
writeChunkLength, err = randomPaddingTarget(turn.writeChunkMinLength, writeChunkLength)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select padding write chunk length: %w", err)
|
||||
return 0, fmt.Errorf("select padding write chunk length: %w", err)
|
||||
}
|
||||
}
|
||||
chunks = defaultPaddingChunks(recordLength, writeChunkLength)
|
||||
chunks = defaultPaddingChunks(payloadLength, writeChunkLength)
|
||||
delays = make([]paddingDelayRange, len(chunks))
|
||||
for i := 1; i < len(delays); i++ {
|
||||
delays[i] = turn.chunkDelay
|
||||
}
|
||||
}
|
||||
if chunks[0] < header.Len() {
|
||||
return fmt.Errorf("first padding chunk %d is shorter than header %d", chunks[0], header.Len())
|
||||
}
|
||||
|
||||
maxChunkLength := 0
|
||||
for _, chunkLength := range chunks {
|
||||
if chunkLength < 1 || chunkLength > maxPaddingChunkLength {
|
||||
return fmt.Errorf("invalid padding chunk length: %d", chunkLength)
|
||||
}
|
||||
maxChunkLength = max(maxChunkLength, chunkLength)
|
||||
}
|
||||
var buffer []byte
|
||||
if reusableBuffer == nil {
|
||||
buffer = make([]byte, maxChunkLength)
|
||||
} else {
|
||||
if cap(*reusableBuffer) < maxChunkLength {
|
||||
*reusableBuffer = make([]byte, maxChunkLength)
|
||||
}
|
||||
buffer = (*reusableBuffer)[:maxChunkLength]
|
||||
clear(buffer)
|
||||
}
|
||||
copy(buffer, header.Bytes())
|
||||
zeros := make([]byte, maxPaddingFrameDataLength)
|
||||
channel := String(paddingFrameChannel)
|
||||
written := 0
|
||||
for i, chunkLength := range chunks {
|
||||
if i < len(delays) {
|
||||
delay, delayErr := randomPaddingDelay(delays[i])
|
||||
if delayErr != nil {
|
||||
return fmt.Errorf("select padding chunk %d delay: %w", i, delayErr)
|
||||
return written, fmt.Errorf("select padding chunk %d delay: %w", i, delayErr)
|
||||
}
|
||||
if delay > 0 {
|
||||
sleep(delay)
|
||||
}
|
||||
}
|
||||
if err = writeFull(w, buffer[:chunkLength]); err != nil {
|
||||
return fmt.Errorf("write padding chunk %d: %w", i, err)
|
||||
frameLengths, planErr := paddingFramePlan(chunkLength)
|
||||
if planErr != nil {
|
||||
return written, planErr
|
||||
}
|
||||
written += chunkLength
|
||||
if i == 0 {
|
||||
clear(buffer[:header.Len()])
|
||||
for _, frameLength := range frameLengths {
|
||||
dataLength, ok := paddingFrameDataLength(frameLength)
|
||||
if !ok {
|
||||
return written, fmt.Errorf("unframed padding length %d", frameLength)
|
||||
}
|
||||
payload := RestBytes(zeros[:dataLength])
|
||||
if err = writePacket(w, packetID, &channel, &payload); err != nil {
|
||||
return written, fmt.Errorf("write padding frame: %w", err)
|
||||
}
|
||||
written += frameLength
|
||||
}
|
||||
}
|
||||
if written != recordLength {
|
||||
return fmt.Errorf("padding chunks total %d, want %d", written, recordLength)
|
||||
}
|
||||
return nil
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func readPaddingTurn(r io.Reader, turn paddingTurn, prefixLength int) error {
|
||||
encodedLength, headerLength, err := readVarintWithLength(r)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read padding header: %w", err)
|
||||
}
|
||||
recordLength := int(encodedLength)
|
||||
if recordLength < headerLength || recordLength > maxPaddingTurnLength {
|
||||
return fmt.Errorf("invalid padding record length: %d", recordLength)
|
||||
}
|
||||
totalLength := prefixLength + recordLength
|
||||
if !paddingTurnAcceptsLength(turn, totalLength) {
|
||||
if len(turn.variants) > 0 {
|
||||
return fmt.Errorf("padding turn length %d is not an allowed variant", totalLength)
|
||||
}
|
||||
return fmt.Errorf("padding turn length %d is outside %d-%d", totalLength, turn.minLength, turn.maxLength)
|
||||
}
|
||||
// paddingFrameLength is the wire size of a custom payload frame whose payload
|
||||
// body is dataLength bytes long.
|
||||
func paddingFrameLength(dataLength int) int {
|
||||
bodyLength := 1 + 1 + len(paddingFrameChannel) + dataLength
|
||||
return varintSize(Varint(bodyLength)) + bodyLength
|
||||
}
|
||||
|
||||
var buffer [paddingBufferLength]byte
|
||||
remaining := recordLength - headerLength
|
||||
for remaining > 0 {
|
||||
chunkLength := min(remaining, len(buffer))
|
||||
if _, err := io.ReadFull(r, buffer[:chunkLength]); err != nil {
|
||||
return fmt.Errorf("read padding body: %w", err)
|
||||
// paddingFrameDataLength is the payload body that makes a frame exactly
|
||||
// frameLength bytes long. Some lengths are unreachable because the length
|
||||
// varint grows in steps.
|
||||
func paddingFrameDataLength(frameLength int) (int, bool) {
|
||||
for overhead := paddingFrameOverhead; overhead <= paddingFrameOverhead+2; overhead++ {
|
||||
dataLength := frameLength - overhead
|
||||
if dataLength < 0 || dataLength > maxPaddingFrameDataLength {
|
||||
continue
|
||||
}
|
||||
if paddingFrameLength(dataLength) == frameLength {
|
||||
return dataLength, true
|
||||
}
|
||||
remaining -= chunkLength
|
||||
}
|
||||
return nil
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// paddingFramePlan splits length bytes into reachable frame sizes. The result is
|
||||
// exact whenever a partition exists; a length below the smallest frame (the
|
||||
// captured 2-byte turns) is rounded up to that frame.
|
||||
func paddingFramePlan(length int) ([]int, error) {
|
||||
if length <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if length < paddingFrameOverhead {
|
||||
return []int{paddingFrameOverhead}, nil
|
||||
}
|
||||
frameLengths := make([]int, 0, length/paddingBufferLength+1)
|
||||
for remaining := length; remaining > 0; {
|
||||
candidate := min(remaining, maxPaddingFrameLength)
|
||||
picked := 0
|
||||
for ; candidate >= paddingFrameOverhead; candidate-- {
|
||||
if _, ok := paddingFrameDataLength(candidate); !ok {
|
||||
continue
|
||||
}
|
||||
rest := remaining - candidate
|
||||
if rest > 0 && rest < paddingFrameOverhead {
|
||||
continue
|
||||
}
|
||||
picked = candidate
|
||||
break
|
||||
}
|
||||
if picked == 0 {
|
||||
return nil, fmt.Errorf("cannot frame %d padding bytes", length)
|
||||
}
|
||||
frameLengths = append(frameLengths, picked)
|
||||
remaining -= picked
|
||||
}
|
||||
return frameLengths, nil
|
||||
}
|
||||
|
||||
func selectPaddingVariant(turn paddingTurn, prefixLength int) (int, []int, []paddingDelayRange, error) {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
|
||||
for dataLength := 0; dataLength <= maxPaddingFrameDataLength; dataLength++ {
|
||||
frameLength := paddingFrameLength(dataLength)
|
||||
got, ok := paddingFrameDataLength(frameLength)
|
||||
if !ok || got != dataLength {
|
||||
t.Fatalf("data length %d -> frame %d -> data %d (ok=%v)", dataLength, frameLength, got, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingFramePlanTotals(t *testing.T) {
|
||||
lengths := []int{paddingFrameOverhead, paddingFrameOverhead + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, maxPaddingFrameLength - 1, maxPaddingFrameLength, maxPaddingFrameLength + 1, 3 * maxPaddingFrameLength, 1024 * 1024}
|
||||
for _, length := range lengths {
|
||||
plan, err := paddingFramePlan(length)
|
||||
if err != nil {
|
||||
t.Fatalf("plan %d: %v", length, err)
|
||||
}
|
||||
total := 0
|
||||
for _, frameLength := range plan {
|
||||
if _, ok := paddingFrameDataLength(frameLength); !ok {
|
||||
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
|
||||
}
|
||||
if frameLength > maxPaddingFrameLength {
|
||||
t.Fatalf("plan %d contains oversized frame %d", length, frameLength)
|
||||
}
|
||||
total += frameLength
|
||||
}
|
||||
if total != length {
|
||||
t.Fatalf("plan %d totals %d", length, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingFramePlanRoundsUpShortTurn(t *testing.T) {
|
||||
plan, err := paddingFramePlan(2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(plan) != 1 || plan[0] != paddingFrameOverhead {
|
||||
t.Fatalf("short turn plan = %v", plan)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
|
||||
turns := []paddingTurn{
|
||||
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
|
||||
{direction: paddingClientToServer, minLength: 2, maxLength: 2},
|
||||
{direction: paddingClientToServer, minLength: maxPaddingFrameLength, maxLength: maxPaddingFrameLength},
|
||||
{direction: paddingClientToServer, minLength: 3*maxPaddingFrameLength + 7, maxLength: 3*maxPaddingFrameLength + 7},
|
||||
}
|
||||
for i, turn := range turns {
|
||||
var buffer bytes.Buffer
|
||||
written, err := writePaddingTurnFrames(&buffer, turn, 0, func(time.Duration) {}, configurationServerboundCustomPayload)
|
||||
if err != nil {
|
||||
t.Fatalf("turn %d: %v", i, err)
|
||||
}
|
||||
if written != buffer.Len() {
|
||||
t.Fatalf("turn %d wrote %d bytes, buffer has %d", i, written, buffer.Len())
|
||||
}
|
||||
target := turn.minLength
|
||||
if written < target {
|
||||
t.Fatalf("turn %d wrote %d bytes, want at least %d", i, written, target)
|
||||
}
|
||||
|
||||
reader := bytes.NewReader(buffer.Bytes())
|
||||
frames := 0
|
||||
for reader.Len() > 0 {
|
||||
packet, err := readPacket(reader)
|
||||
if err != nil {
|
||||
t.Fatalf("turn %d frame %d is not a valid packet: %v", i, frames, err)
|
||||
}
|
||||
if packet.packetID != configurationServerboundCustomPayload {
|
||||
t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID)
|
||||
}
|
||||
_, ok, err := parseCustomPayload(packet)
|
||||
if err != nil {
|
||||
t.Fatalf("turn %d frame %d: %v", i, frames, err)
|
||||
}
|
||||
if ok {
|
||||
t.Fatalf("turn %d frame %d uses the packet stream channel", i, frames)
|
||||
}
|
||||
if len(packet.data) == 0 {
|
||||
t.Fatalf("turn %d frame %d has no channel", i, frames)
|
||||
}
|
||||
frames++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
|
||||
schedule := []paddingTurn{
|
||||
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
|
||||
{direction: paddingServerToClient, minLength: 64, maxLength: 64},
|
||||
{direction: paddingClientToServer, minLength: 25, maxLength: 25},
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := runPaddingSchedule(&out, true, 2, schedule); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reader := bytes.NewReader(out.Bytes())
|
||||
total := 0
|
||||
for reader.Len() > 0 {
|
||||
before := reader.Len()
|
||||
packet, err := readPacket(reader)
|
||||
if err != nil {
|
||||
t.Fatalf("padding stream is not a valid packet stream: %v", err)
|
||||
}
|
||||
if packet.packetID != configurationServerboundCustomPayload {
|
||||
t.Fatalf("unexpected packet id %d in padding stream", packet.packetID)
|
||||
}
|
||||
total += before - reader.Len()
|
||||
}
|
||||
// Turn 0 carries the 2 byte Login Acknowledged prefix, turn 1 is the peer's.
|
||||
want := 44 - 2 + 25
|
||||
if total != want {
|
||||
t.Fatalf("padding stream carries %d payload bytes, want %d", total, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) {
|
||||
schedule := []paddingTurn{
|
||||
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
|
||||
}
|
||||
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule); err == nil {
|
||||
t.Fatal("expected an error for a prefixed server-to-client first turn")
|
||||
}
|
||||
}
|
||||
@@ -1,618 +0,0 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPaddingTurnReachesFinalTargetLength(t *testing.T) {
|
||||
turn := paddingTurn{direction: paddingClientToServer, minLength: 128, maxLength: 128}
|
||||
const prefixLength = 3
|
||||
var encoded bytes.Buffer
|
||||
if err := writePaddingTurn(&encoded, turn, prefixLength); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := prefixLength + encoded.Len(); got != turn.minLength {
|
||||
t.Fatalf("total turn length = %d, want %d", got, turn.minLength)
|
||||
}
|
||||
encodedReader := bytes.NewReader(encoded.Bytes())
|
||||
var recordLength Varint
|
||||
if err := recordLength.readFrom(encodedReader); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := int(recordLength); got != encoded.Len() {
|
||||
t.Fatalf("record length = %d, encoded = %d", got, encoded.Len())
|
||||
}
|
||||
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, prefixLength); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingTurnSupportsThreeByteTarget(t *testing.T) {
|
||||
turn := paddingTurn{direction: paddingClientToServer, minLength: 3, maxLength: 3}
|
||||
var encoded bytes.Buffer
|
||||
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := encoded.Len(); got != 3 {
|
||||
t.Fatalf("padding length = %d, want 3", got)
|
||||
}
|
||||
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingTurnVarintBoundaries(t *testing.T) {
|
||||
for _, targetLength := range []int{127, 128, 16383, 16384} {
|
||||
t.Run(strconv.Itoa(targetLength), func(t *testing.T) {
|
||||
turn := paddingTurn{direction: paddingClientToServer, minLength: targetLength, maxLength: targetLength}
|
||||
var encoded bytes.Buffer
|
||||
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if encoded.Len() != targetLength {
|
||||
t.Fatalf("padding length = %d, want %d", encoded.Len(), targetLength)
|
||||
}
|
||||
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingTurnRandomRange(t *testing.T) {
|
||||
turn := paddingTurn{direction: paddingServerToClient, minLength: 127, maxLength: 129}
|
||||
seen := make(map[int]bool)
|
||||
for range 100 {
|
||||
var encoded bytes.Buffer
|
||||
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if encoded.Len() < turn.minLength || encoded.Len() > turn.maxLength {
|
||||
t.Fatalf("padding length = %d", encoded.Len())
|
||||
}
|
||||
seen[encoded.Len()] = true
|
||||
}
|
||||
if len(seen) < 2 {
|
||||
t.Fatalf("padding range did not vary: %v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingTurnUsesRestrictedSendRange(t *testing.T) {
|
||||
turn := paddingTurn{
|
||||
direction: paddingServerToClient,
|
||||
minLength: 3,
|
||||
maxLength: 100,
|
||||
sendMinLength: 90,
|
||||
sendMaxLength: 100,
|
||||
}
|
||||
seen := make(map[int]bool)
|
||||
for range 100 {
|
||||
var encoded bytes.Buffer
|
||||
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if encoded.Len() < turn.sendMinLength || encoded.Len() > turn.sendMaxLength {
|
||||
t.Fatalf("padding length = %d", encoded.Len())
|
||||
}
|
||||
seen[encoded.Len()] = true
|
||||
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if len(seen) < 2 {
|
||||
t.Fatalf("restricted send range did not vary: %v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingScheduleSynchronizesDirections(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer client.Close()
|
||||
defer server.Close()
|
||||
|
||||
schedule := []paddingTurn{
|
||||
{direction: paddingClientToServer, minLength: 33, maxLength: 33},
|
||||
{direction: paddingServerToClient, minLength: 4097, maxLength: 4097},
|
||||
{direction: paddingClientToServer, minLength: 16385, maxLength: 16385},
|
||||
}
|
||||
serverDone := make(chan error, 1)
|
||||
go func() {
|
||||
serverDone <- runPaddingSchedule(server, server, false, 3, schedule)
|
||||
}()
|
||||
if err := runPaddingSchedule(client, client, true, 3, schedule); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case err := <-serverDone:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("server padding schedule did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadPaddingTurnHandlesFragmentedInput(t *testing.T) {
|
||||
turn := paddingTurn{direction: paddingClientToServer, minLength: 1024, maxLength: 1024}
|
||||
var encoded bytes.Buffer
|
||||
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := readPaddingTurn(&oneByteReader{reader: bytes.NewReader(encoded.Bytes())}, turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadPaddingTurnRejectsInvalidLength(t *testing.T) {
|
||||
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 96}
|
||||
data := encodePaddingLength(t, 63)
|
||||
if err := readPaddingTurn(bytes.NewReader(data), turn, 0); err == nil || !strings.Contains(err.Error(), "outside") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadPaddingTurnRejectsNonCanonicalHeader(t *testing.T) {
|
||||
turn := paddingTurn{direction: paddingClientToServer, minLength: 3, maxLength: 3}
|
||||
err := readPaddingTurn(bytes.NewReader([]byte{0x83, 0x00, 0x00}), turn, 0)
|
||||
if err == nil || !strings.Contains(err.Error(), "non-canonical") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadPaddingTurnRejectsTruncatedBody(t *testing.T) {
|
||||
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 64}
|
||||
data := encodePaddingLength(t, 64)
|
||||
if err := readPaddingTurn(bytes.NewReader(data), turn, 0); err == nil || !strings.Contains(err.Error(), "body") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadPaddingTurnHonorsConnectionTimeout(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer client.Close()
|
||||
defer server.Close()
|
||||
|
||||
if err := server.SetReadDeadline(time.Now().Add(20 * time.Millisecond)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 64}
|
||||
err := readPaddingTurn(server, turn, 0)
|
||||
var netErr net.Error
|
||||
if !errors.As(err, &netErr) || !netErr.Timeout() {
|
||||
t.Fatalf("error = %v, want network timeout", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePaddingSchedule(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
schedule []paddingTurn
|
||||
prefix int
|
||||
}{
|
||||
{name: "empty"},
|
||||
{name: "bad direction", schedule: []paddingTurn{{direction: 99, minLength: 4, maxLength: 4}}},
|
||||
{name: "too small", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 0, maxLength: 4}}},
|
||||
{name: "reversed range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 7}}},
|
||||
{name: "wrong first direction", prefix: 3, schedule: []paddingTurn{{direction: paddingServerToClient, minLength: 8, maxLength: 8}}},
|
||||
{name: "prefix leaves no header", prefix: 8, schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8}}},
|
||||
{name: "same direction", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8}, {direction: paddingClientToServer, minLength: 8, maxLength: 8}}},
|
||||
{name: "range with variants", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, variants: []paddingVariant{paddingVariantFromChunks(8)}}}},
|
||||
{name: "empty variant", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{{}}}}},
|
||||
{name: "bad chunk", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(maxPaddingChunkLength + 1)}}}},
|
||||
{
|
||||
name: "delay mismatch",
|
||||
schedule: []paddingTurn{{
|
||||
direction: paddingClientToServer,
|
||||
variants: []paddingVariant{{
|
||||
chunks: []int{4, 4},
|
||||
delays: []paddingDelayRange{{min: time.Millisecond, max: time.Millisecond}},
|
||||
}},
|
||||
}},
|
||||
},
|
||||
{name: "reversed start delay", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, startDelay: paddingDelayRange{min: 2 * time.Millisecond, max: time.Millisecond}}}},
|
||||
{name: "reversed generated chunk delay", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, chunkDelay: paddingDelayRange{min: 2 * time.Millisecond, max: time.Millisecond}}}},
|
||||
{name: "oversized generated chunk", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, writeChunkLength: maxPaddingChunkLength + 1}}},
|
||||
{name: "reversed generated chunk range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, writeChunkMinLength: 9, writeChunkLength: 8}}},
|
||||
{name: "variant with generated chunks", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, writeChunkLength: 8}}},
|
||||
{name: "send range outside accepted range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 16, sendMinLength: 7, sendMaxLength: 12}}},
|
||||
{name: "variant with send range", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, sendMinLength: 8, sendMaxLength: 8}}},
|
||||
{name: "negative chunk delay", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{{chunks: []int{8}, delays: []paddingDelayRange{{min: -time.Millisecond}}}}}}},
|
||||
{name: "bad send variant", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, sendVariants: []int{1}}}},
|
||||
{name: "prefix splits chunk", prefix: 3, schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8, 4)}}}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if err := validatePaddingSchedule(test.schedule, test.prefix); err == nil {
|
||||
t.Fatal("expected invalid padding schedule")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingSchedule2612MatchesCapturedTemplates(t *testing.T) {
|
||||
wantDirections := []paddingDirection{
|
||||
paddingClientToServer,
|
||||
paddingServerToClient,
|
||||
paddingClientToServer,
|
||||
paddingServerToClient,
|
||||
paddingClientToServer,
|
||||
paddingServerToClient,
|
||||
}
|
||||
wantLengths := [][]int{
|
||||
{44},
|
||||
{72},
|
||||
{25},
|
||||
{41172},
|
||||
{2},
|
||||
{7464, 8267, 8790, 8153, 7375, 7347, 8184, 6633, 7670, 8241, 7857, 7254, 8407, 8283, 6804, 8177, 8177, 7929, 8296, 8177},
|
||||
}
|
||||
if len(paddingSchedule2612) != len(wantDirections)+33 {
|
||||
t.Fatalf("padding schedule has %d turns, want %d", len(paddingSchedule2612), len(wantDirections)+33)
|
||||
}
|
||||
for i, turn := range paddingSchedule2612[:len(wantDirections)] {
|
||||
if turn.direction != wantDirections[i] {
|
||||
t.Fatalf("padding turn %d direction = %d, want %d", i, turn.direction, wantDirections[i])
|
||||
}
|
||||
if len(turn.variants) != len(wantLengths[i]) {
|
||||
t.Fatalf("padding turn %d has %d variants, want %d", i, len(turn.variants), len(wantLengths[i]))
|
||||
}
|
||||
for j, variant := range turn.variants {
|
||||
if got := paddingVariantLength(variant); got != wantLengths[i][j] {
|
||||
t.Fatalf("padding turn %d variant %d length = %d, want %d", i, j, got, wantLengths[i][j])
|
||||
}
|
||||
}
|
||||
}
|
||||
wantPlayBounds := [][2]int{
|
||||
{6, 883},
|
||||
{346, 58638},
|
||||
{6, 887},
|
||||
{388, 61077},
|
||||
{2, 50},
|
||||
{575, 65584},
|
||||
{6, 45},
|
||||
{86, 63563},
|
||||
{2, 44},
|
||||
{42, 51983},
|
||||
{2, 851},
|
||||
{309, 25083},
|
||||
{2, 19},
|
||||
{74, 63885},
|
||||
{8, 24},
|
||||
{30, 66128},
|
||||
{2, 19},
|
||||
{26, 35818},
|
||||
{6, 19},
|
||||
{35, 59407},
|
||||
{6, 19},
|
||||
{37, 65328},
|
||||
{2, 19},
|
||||
{26, 60622},
|
||||
{6, 19},
|
||||
{11, 60808},
|
||||
{8, 43},
|
||||
{55, 62027},
|
||||
{2, 19},
|
||||
{427, 65622},
|
||||
{5, 19},
|
||||
{35, 59401},
|
||||
{6, 19},
|
||||
}
|
||||
for i, want := range wantPlayBounds {
|
||||
turn := paddingSchedule2612[len(wantDirections)+i]
|
||||
wantDirection := paddingClientToServer
|
||||
if i%2 == 1 {
|
||||
wantDirection = paddingServerToClient
|
||||
}
|
||||
if turn.direction != wantDirection {
|
||||
t.Fatalf("play turn %d direction = %d, want %d", i, turn.direction, wantDirection)
|
||||
}
|
||||
if turn.minLength != want[0] || turn.maxLength != want[1] {
|
||||
t.Fatalf("play turn %d bounds = %d-%d, want %d-%d", i, turn.minLength, turn.maxLength, want[0], want[1])
|
||||
}
|
||||
if len(turn.variants) != 0 {
|
||||
t.Fatalf("play turn %d unexpectedly has captured variants", i)
|
||||
}
|
||||
}
|
||||
if got := len(paddingSchedule2612[3].variants[0].chunks); got != 30 {
|
||||
t.Fatalf("registry turn chunks = %d, want 30", got)
|
||||
}
|
||||
minimumPlayStart := maxPaddingTurnLength
|
||||
maximumPlayStart := 0
|
||||
for _, variant := range paddingSchedule2612[5].variants {
|
||||
length := paddingVariantLength(variant)
|
||||
minimumPlayStart = min(minimumPlayStart, length)
|
||||
maximumPlayStart = max(maximumPlayStart, length)
|
||||
if variant.chunks[0] != 4941 {
|
||||
t.Fatalf("play start first chunk = %d, want 4941", variant.chunks[0])
|
||||
}
|
||||
}
|
||||
if minimumPlayStart != 6633 || maximumPlayStart != 8790 {
|
||||
t.Fatalf("play start bounds = %d-%d, want 6633-8790", minimumPlayStart, maximumPlayStart)
|
||||
}
|
||||
if err := validatePaddingSchedule(paddingSchedule2612, 2); err != nil {
|
||||
t.Fatalf("captured schedule is invalid: %v", err)
|
||||
}
|
||||
|
||||
serverSchedule, err := newServerPaddingSchedule2612()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = validatePaddingSchedule(serverSchedule, 2); err != nil {
|
||||
t.Fatalf("server schedule is invalid: %v", err)
|
||||
}
|
||||
for i, branches := range serverPlayBranches2612 {
|
||||
turn := serverSchedule[len(startupPaddingSchedule2612)+1+i*2]
|
||||
got := paddingLengthRange2612{turn.sendMinLength, turn.sendMaxLength}
|
||||
if got != branches.small && got != branches.large {
|
||||
t.Fatalf("server play turn %d send range = %v, want %v or %v", i, got, branches.small, branches.large)
|
||||
}
|
||||
}
|
||||
|
||||
for range 20 {
|
||||
clientSchedule, clientErr := newClientPaddingSchedule2612()
|
||||
if clientErr != nil {
|
||||
t.Fatal(clientErr)
|
||||
}
|
||||
if clientErr = validatePaddingSchedule(clientSchedule, 2); clientErr != nil {
|
||||
t.Fatalf("client schedule is invalid: %v", clientErr)
|
||||
}
|
||||
burstCount := 0
|
||||
for _, burst := range clientPlayBursts2612 {
|
||||
turn := clientSchedule[len(startupPaddingSchedule2612)+burst.playIndex]
|
||||
got := paddingLengthRange2612{turn.sendMinLength, turn.sendMaxLength}
|
||||
switch got {
|
||||
case burst.regular:
|
||||
case burst.burst:
|
||||
burstCount++
|
||||
default:
|
||||
t.Fatalf("client play turn %d send range = %v", burst.playIndex, got)
|
||||
}
|
||||
}
|
||||
if burstCount != 1 {
|
||||
t.Fatalf("client schedule has %d initialization bursts, want 1", burstCount)
|
||||
}
|
||||
}
|
||||
|
||||
for variantIndex := range paddingSchedule2612[3].variants {
|
||||
turn := paddingSchedule2612[3]
|
||||
turn.sendVariants = []int{variantIndex}
|
||||
var encoded bytes.Buffer
|
||||
if err = writePaddingTurnWithSleep(&encoded, turn, 0, func(time.Duration) {}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = readPaddingTurn(bytes.NewReader(encoded.Bytes()), paddingSchedule2612[3], 0); err != nil {
|
||||
t.Fatalf("registry variant %d was rejected: %v", variantIndex, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingVariantPreservesWriteBoundaries(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
turn paddingTurn
|
||||
prefix int
|
||||
want []int
|
||||
}{
|
||||
{name: "login acknowledged turn", turn: paddingSchedule2612[0], prefix: 2, want: []int{26, 16}},
|
||||
{name: "server response turn", turn: paddingSchedule2612[1], want: []int{26, 21, 25}},
|
||||
{name: "single packet turn", turn: paddingSchedule2612[2], want: []int{25}},
|
||||
{name: "fixed registry profile", turn: paddingSchedule2612[3], want: paddingSchedule2612[3].variants[0].chunks},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var writer recordingWriter
|
||||
if err := writePaddingTurnWithSleep(&writer, test.turn, test.prefix, func(time.Duration) {}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(writer.writes) != len(test.want) {
|
||||
t.Fatalf("writes = %v, want %v", writer.writes, test.want)
|
||||
}
|
||||
for i := range test.want {
|
||||
if writer.writes[i] != test.want[i] {
|
||||
t.Fatalf("writes = %v, want %v", writer.writes, test.want)
|
||||
}
|
||||
}
|
||||
if err := readPaddingTurn(bytes.NewReader(writer.Bytes()), test.turn, test.prefix); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingVariantAppliesPacing(t *testing.T) {
|
||||
turn := paddingTurn{
|
||||
direction: paddingClientToServer,
|
||||
startDelay: paddingDelayRange{min: 3 * time.Millisecond, max: 3 * time.Millisecond},
|
||||
variants: []paddingVariant{{
|
||||
chunks: []int{3, 5, 7},
|
||||
delays: []paddingDelayRange{
|
||||
{},
|
||||
{min: 2 * time.Millisecond, max: 2 * time.Millisecond},
|
||||
{min: 4 * time.Millisecond, max: 4 * time.Millisecond},
|
||||
},
|
||||
}},
|
||||
}
|
||||
var slept []time.Duration
|
||||
var writer recordingWriter
|
||||
if err := writePaddingTurnWithSleep(&writer, turn, 3, func(delay time.Duration) {
|
||||
slept = append(slept, delay)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []time.Duration{3 * time.Millisecond, 2 * time.Millisecond, 4 * time.Millisecond}
|
||||
if len(slept) != len(want) {
|
||||
t.Fatalf("delays = %v, want %v", slept, want)
|
||||
}
|
||||
for i := range want {
|
||||
if slept[i] != want[i] {
|
||||
t.Fatalf("delays = %v, want %v", slept, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneratedPaddingChunksApplyPacing(t *testing.T) {
|
||||
turn := paddingTurn{
|
||||
direction: paddingServerToClient,
|
||||
minLength: 100,
|
||||
maxLength: 100,
|
||||
writeChunkLength: 32,
|
||||
chunkDelay: paddingDelayRange{min: 2 * time.Millisecond, max: 2 * time.Millisecond},
|
||||
}
|
||||
var slept []time.Duration
|
||||
var writer recordingWriter
|
||||
if err := writePaddingTurnWithSleep(&writer, turn, 0, func(delay time.Duration) {
|
||||
slept = append(slept, delay)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantWrites := []int{32, 32, 32, 4}
|
||||
if !slicesEqual(writer.writes, wantWrites) {
|
||||
t.Fatalf("writes = %v, want %v", writer.writes, wantWrites)
|
||||
}
|
||||
wantSleeps := []time.Duration{2 * time.Millisecond, 2 * time.Millisecond, 2 * time.Millisecond}
|
||||
if !slicesEqual(slept, wantSleeps) {
|
||||
t.Fatalf("delays = %v, want %v", slept, wantSleeps)
|
||||
}
|
||||
if err := readPaddingTurn(bytes.NewReader(writer.Bytes()), turn, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneratedPaddingChunkLengthIsRandomized(t *testing.T) {
|
||||
turn := paddingTurn{
|
||||
direction: paddingServerToClient,
|
||||
minLength: 100,
|
||||
maxLength: 100,
|
||||
writeChunkMinLength: 16,
|
||||
writeChunkLength: 32,
|
||||
}
|
||||
seen := make(map[int]bool)
|
||||
for range 100 {
|
||||
var writer recordingWriter
|
||||
if err := writePaddingTurnWithSleep(&writer, turn, 0, func(time.Duration) {}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstWrite := writer.writes[0]
|
||||
if firstWrite < turn.writeChunkMinLength || firstWrite > turn.writeChunkLength {
|
||||
t.Fatalf("first write = %d", firstWrite)
|
||||
}
|
||||
seen[firstWrite] = true
|
||||
}
|
||||
if len(seen) < 2 {
|
||||
t.Fatalf("generated write chunk length did not vary: %v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingDelayRangeIsRandomized(t *testing.T) {
|
||||
delayRange := millisecondRange(25, 40)
|
||||
seen := make(map[time.Duration]bool)
|
||||
for range 100 {
|
||||
delay, err := randomPaddingDelay(delayRange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if delay < delayRange.min || delay > delayRange.max {
|
||||
t.Fatalf("delay = %s, want %s-%s", delay, delayRange.min, delayRange.max)
|
||||
}
|
||||
seen[delay] = true
|
||||
}
|
||||
if len(seen) < 2 {
|
||||
t.Fatalf("padding delay did not vary: %v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingSchedule2612UsesCoarseTimingBands(t *testing.T) {
|
||||
assertDelayRange(t, "turn 3 to 4", paddingSchedule2612[3].startDelay, 20*time.Millisecond, 50*time.Millisecond)
|
||||
assertDelayRange(t, "turn 5 to 6", paddingSchedule2612[5].startDelay, 35*time.Millisecond, 50*time.Millisecond)
|
||||
assertDelayRange(t, "first play client turn", paddingSchedule2612[6].startDelay, time.Millisecond, 30*time.Millisecond)
|
||||
assertDelayRange(t, "first play server turn", paddingSchedule2612[7].startDelay, time.Millisecond, 45*time.Millisecond)
|
||||
assertDelayRange(t, "play server chunk pacing", paddingSchedule2612[7].chunkDelay, time.Millisecond, 4*time.Millisecond)
|
||||
if paddingSchedule2612[6].writeChunkLength != 1024 {
|
||||
t.Fatalf("play client write chunk = %d, want 1024", paddingSchedule2612[6].writeChunkLength)
|
||||
}
|
||||
if paddingSchedule2612[7].writeChunkLength != maxPaddingChunkLength {
|
||||
t.Fatalf("play server write chunk = %d, want %d", paddingSchedule2612[7].writeChunkLength, maxPaddingChunkLength)
|
||||
}
|
||||
if paddingSchedule2612[7].writeChunkMinLength != 32*1024 {
|
||||
t.Fatalf("play server minimum write chunk = %d, want %d", paddingSchedule2612[7].writeChunkMinLength, 32*1024)
|
||||
}
|
||||
|
||||
for i, variant := range paddingSchedule2612[3].variants {
|
||||
minimum, maximum := paddingVariantDelayBounds(variant)
|
||||
if minimum != 45*time.Millisecond || maximum != 65*time.Millisecond {
|
||||
t.Fatalf("turn 4 variant %d duration = %s-%s, want 45ms-65ms", i, minimum, maximum)
|
||||
}
|
||||
}
|
||||
for i, variant := range paddingSchedule2612[5].variants {
|
||||
minimum, maximum := paddingVariantDelayBounds(variant)
|
||||
if minimum != 10*time.Millisecond || maximum != 25*time.Millisecond {
|
||||
t.Fatalf("turn 6 variant %d duration = %s-%s, want 10ms-25ms", i, minimum, maximum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertDelayRange(t *testing.T, name string, got paddingDelayRange, minimum, maximum time.Duration) {
|
||||
t.Helper()
|
||||
if got.min != minimum || got.max != maximum {
|
||||
t.Fatalf("%s delay = %s-%s, want %s-%s", name, got.min, got.max, minimum, maximum)
|
||||
}
|
||||
}
|
||||
|
||||
func paddingVariantDelayBounds(variant paddingVariant) (time.Duration, time.Duration) {
|
||||
var minimum time.Duration
|
||||
var maximum time.Duration
|
||||
for _, delay := range variant.delays {
|
||||
minimum += delay.min
|
||||
maximum += delay.max
|
||||
}
|
||||
return minimum, maximum
|
||||
}
|
||||
|
||||
func slicesEqual[T comparable](left, right []T) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
for i := range left {
|
||||
if left[i] != right[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func encodePaddingLength(t *testing.T, length int) []byte {
|
||||
t.Helper()
|
||||
var encoded bytes.Buffer
|
||||
value := Varint(length)
|
||||
if err := value.writeTo(&encoded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return encoded.Bytes()
|
||||
}
|
||||
|
||||
type oneByteReader struct {
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r *oneByteReader) Read(p []byte) (int, error) {
|
||||
if len(p) > 1 {
|
||||
p = p[:1]
|
||||
}
|
||||
return r.reader.Read(p)
|
||||
}
|
||||
|
||||
type recordingWriter struct {
|
||||
bytes.Buffer
|
||||
writes []int
|
||||
}
|
||||
|
||||
func (w *recordingWriter) Write(p []byte) (int, error) {
|
||||
w.writes = append(w.writes, len(p))
|
||||
return w.Buffer.Write(p)
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestProfilesFromConfigRejectsEmpty(t *testing.T) {
|
||||
if _, err := profilesFromConfig(nil); err == nil {
|
||||
t.Fatal("expected empty profiles error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfilesFromConfig(t *testing.T) {
|
||||
uuid := bytes.Repeat([]byte{0x2a}, 16)
|
||||
profiles, err := profilesFromConfig([]*Profile{
|
||||
{
|
||||
Username: "SignedUser",
|
||||
Uuid: uuid,
|
||||
TexturesValue: "textures-value",
|
||||
TexturesSignature: "textures-signature",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build explicit profile: %v", err)
|
||||
}
|
||||
if len(profiles) != 1 || profiles[0].Username != "SignedUser" {
|
||||
t.Fatalf("unexpected profile: %+v", profiles)
|
||||
}
|
||||
if profiles[0].TexturesValue != "textures-value" || profiles[0].TexturesSignature != "textures-signature" {
|
||||
t.Fatalf("textures were not preserved: %+v", profiles[0])
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,11 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
maxPacketDataLength = 32 * 1024
|
||||
// Clientbound custom payloads are allowed up to 1 MiB by vanilla, and a
|
||||
// vanilla configuration state can send large registry data packets. This is
|
||||
// only an upper bound for decoding; the XMC payload stream keeps its own,
|
||||
// much smaller, chunk size.
|
||||
maxPacketDataLength = 1024 * 1024
|
||||
maxPacketBodyLength = maxPacketDataLength + 5
|
||||
)
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadPacketDoesNotConsumeFollowingPacket(t *testing.T) {
|
||||
data := []byte{0x01, 0x80, 0x01, 0x00}
|
||||
r := bytes.NewReader(data)
|
||||
if _, err := readPacket(r); err == nil {
|
||||
t.Fatal("expected truncated packet ID to fail")
|
||||
}
|
||||
pkt, err := readPacket(r)
|
||||
if err != nil {
|
||||
t.Fatalf("read following packet: %v", err)
|
||||
}
|
||||
if pkt.packetID != 0 {
|
||||
t.Fatalf("packet ID = %d", pkt.packetID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketWithLengthReportsWireBytes(t *testing.T) {
|
||||
var wire bytes.Buffer
|
||||
written, err := writePacketWithLength(&wire, 0x03)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if written != 2 || !bytes.Equal(wire.Bytes(), []byte{0x01, 0x03}) {
|
||||
t.Fatalf("wire = %x, length = %d", wire.Bytes(), written)
|
||||
}
|
||||
|
||||
packet, read, err := readPacketWithLength(bytes.NewReader(wire.Bytes()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if packet.packetID != 0x03 || read != written {
|
||||
t.Fatalf("packet ID = %d, read = %d, written = %d", packet.packetID, read, written)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadPacketRejectsNonCanonicalLengthVarint(t *testing.T) {
|
||||
_, _, err := readPacketWithLength(bytes.NewReader([]byte{0x81, 0x00, 0x03}))
|
||||
if err == nil || !strings.Contains(err.Error(), "non-canonical") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVarintRejectsOversizedFifthByte(t *testing.T) {
|
||||
var value Varint
|
||||
err := value.readFrom(bytes.NewReader([]byte{0xff, 0xff, 0xff, 0xff, 0x1f}))
|
||||
if err == nil || !strings.Contains(err.Error(), "too large") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -245,7 +245,7 @@ func (c *serverConn) handshake() error {
|
||||
if err = validateLoginAcknowledgedPacket(pkt); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = runPaddingSchedule(c.reader, c.writer, false, loginAcknowledgedLength, c.paddingSchedule); err != nil {
|
||||
if err = runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule); err != nil {
|
||||
return fmt.Errorf("run startup padding: %w", err)
|
||||
}
|
||||
|
||||
@@ -328,7 +328,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
|
||||
return c.deadlines.setWriteDeadline(t)
|
||||
}
|
||||
|
||||
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte) (*serverConn, error) {
|
||||
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, padding []*Padding) (*serverConn, error) {
|
||||
if len(profiles) == 0 {
|
||||
return nil, fmt.Errorf("empty profiles")
|
||||
}
|
||||
@@ -342,7 +342,7 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse rsa private key: %w", err)
|
||||
}
|
||||
paddingSchedule, err := newServerPaddingSchedule2612()
|
||||
paddingSchedule, err := newPaddingSchedule(padding, false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select padding profile: %w", err)
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type dataAndEOFReader struct {
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (r *dataAndEOFReader) Read(p []byte) (int, error) {
|
||||
if len(r.data) == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, r.data)
|
||||
r.data = r.data[n:]
|
||||
return n, io.EOF
|
||||
}
|
||||
|
||||
type shortWriter struct {
|
||||
bytes.Buffer
|
||||
}
|
||||
|
||||
func (w *shortWriter) Write(p []byte) (int, error) {
|
||||
if len(p) > 1 {
|
||||
p = p[:len(p)/2]
|
||||
}
|
||||
return w.Buffer.Write(p)
|
||||
}
|
||||
|
||||
func TestCryptoReaderPreservesDataReturnedWithEOF(t *testing.T) {
|
||||
secret := []byte("0123456789abcdef")
|
||||
plaintext := []byte("payload returned with EOF")
|
||||
var encrypted bytes.Buffer
|
||||
writer, err := newCryptoWriter(&encrypted, secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = writer.Write(plaintext); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reader, err := newCryptoReader(&dataAndEOFReader{data: encrypted.Bytes()}, secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make([]byte, len(plaintext))
|
||||
n, err := reader.Read(got)
|
||||
if err == nil || n != len(plaintext) {
|
||||
t.Fatalf("Read = %d, %v", n, err)
|
||||
}
|
||||
if !bytes.Equal(got[:n], plaintext) {
|
||||
t.Fatalf("plaintext = %q", got[:n])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCryptoWriterHandlesShortWrites(t *testing.T) {
|
||||
secret := []byte("0123456789abcdef")
|
||||
plaintext := bytes.Repeat([]byte("short-write"), 100)
|
||||
var dst shortWriter
|
||||
writer, err := newCryptoWriter(&dst, secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := writer.Write(plaintext); err != nil || n != len(plaintext) {
|
||||
t.Fatalf("Write = %d, %v", n, err)
|
||||
}
|
||||
reader, err := newCryptoReader(bytes.NewReader(dst.Bytes()), secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, plaintext) {
|
||||
t.Fatal("decrypted payload mismatch")
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ func (h *HunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if len(h.buf) == buf.Size {
|
||||
if cap(h.buf) >= buf.Size {
|
||||
b := h.buf
|
||||
h.index = len(h.buf)
|
||||
return buf.MultiBuffer{buf.NewExisted(b)}, nil
|
||||
|
||||
@@ -74,10 +74,14 @@ func (h *MultiHunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(b) == buf.Size {
|
||||
if cap(b) >= buf.Size {
|
||||
mb = append(mb, buf.NewExisted(b))
|
||||
} else {
|
||||
mb = buf.MergeBytes(mb, b)
|
||||
nb := buf.New()
|
||||
nb.Extend(int32(len(b)))
|
||||
copy(nb.Bytes(), b)
|
||||
|
||||
mb = append(mb, nb)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -197,7 +197,8 @@ func (c *client) dial(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// udp, _ := strconv.ParseBool(resp.Header.Get(ResponseHeaderUDPEnabled))
|
||||
down, _ := strconv.ParseUint(resp.Header.Get(CommonHeaderCCRX), 10, 64)
|
||||
remote_rx, _ := strconv.ParseUint(resp.Header.Get(CommonHeaderCCRX), 10, 64)
|
||||
tx := quicParams.BrutalUp
|
||||
errors.LogDebug(context.Background(), "ECHAccepted ", conn.ConnectionState().TLS.ECHAccepted)
|
||||
|
||||
switch quicParams.Congestion {
|
||||
@@ -205,10 +206,13 @@ func (c *client) dial(ctx context.Context) error {
|
||||
case "bbr":
|
||||
congestion.UseBBR(conn, bbr.Profile(quicParams.BbrProfile))
|
||||
case "", "brutal":
|
||||
if quicParams.BrutalUp == 0 || down == 0 {
|
||||
if tx == 0 {
|
||||
congestion.UseBBR(conn, bbr.Profile(quicParams.BbrProfile))
|
||||
} else {
|
||||
congestion.UseBrutal(conn, min(quicParams.BrutalUp, down), quicParams.BrutalDisableLossCompensation)
|
||||
if remote_rx > 0 {
|
||||
tx = min(tx, remote_rx)
|
||||
}
|
||||
congestion.UseBrutal(conn, tx, quicParams.BrutalDisableLossCompensation)
|
||||
}
|
||||
case "force-brutal":
|
||||
congestion.UseBrutal(conn, quicParams.BrutalUp, quicParams.BrutalDisableLossCompensation)
|
||||
|
||||
@@ -55,7 +55,8 @@ func (h *httpHandler) AuthHTTP(w http.ResponseWriter, r *http.Request) bool {
|
||||
}
|
||||
|
||||
auth := r.Header.Get(RequestHeaderAuth)
|
||||
down, _ := strconv.ParseUint(r.Header.Get(CommonHeaderCCRX), 10, 64)
|
||||
remote_rx, _ := strconv.ParseUint(r.Header.Get(CommonHeaderCCRX), 10, 64)
|
||||
tx := h.quicParams.BrutalUp
|
||||
|
||||
var user *protocol.MemoryUser
|
||||
var ok bool
|
||||
@@ -76,10 +77,13 @@ func (h *httpHandler) AuthHTTP(w http.ResponseWriter, r *http.Request) bool {
|
||||
case "bbr":
|
||||
congestion.UseBBR(conn, bbr.Profile(quicParams.BbrProfile))
|
||||
case "", "brutal":
|
||||
if quicParams.BrutalUp == 0 || down == 0 {
|
||||
if remote_rx == 0 {
|
||||
congestion.UseBBR(conn, bbr.Profile(quicParams.BbrProfile))
|
||||
} else {
|
||||
congestion.UseBrutal(conn, min(quicParams.BrutalUp, down), quicParams.BrutalDisableLossCompensation)
|
||||
if tx > 0 {
|
||||
remote_rx = min(remote_rx, tx)
|
||||
}
|
||||
congestion.UseBrutal(conn, remote_rx, quicParams.BrutalDisableLossCompensation)
|
||||
}
|
||||
case "force-brutal":
|
||||
congestion.UseBrutal(conn, quicParams.BrutalUp, quicParams.BrutalDisableLossCompensation)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build openbsd
|
||||
// +build openbsd
|
||||
|
||||
package internet
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build js || netbsd || solaris
|
||||
// +build js netbsd solaris
|
||||
//go:build !windows && !darwin && !linux && !freebsd && !openbsd
|
||||
|
||||
package internet
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
package tcp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build freebsd
|
||||
// +build freebsd
|
||||
|
||||
package tcp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package tcp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package tcp_test
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !linux && !freebsd && !darwin
|
||||
// +build !linux,!freebsd,!darwin
|
||||
|
||||
package tcp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package tls
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package tls
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
package udp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build freebsd
|
||||
// +build freebsd
|
||||
|
||||
package udp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package udp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build openbsd
|
||||
// +build openbsd
|
||||
|
||||
package udp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build openbsd
|
||||
// +build openbsd
|
||||
|
||||
package udp
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !linux && !freebsd && !darwin && !openbsd
|
||||
// +build !linux,!freebsd,!darwin,!openbsd
|
||||
|
||||
package udp
|
||||
|
||||
|
||||
Reference in New Issue
Block a user