Compare commits
221 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
6987ac5344 | |
|
|
d65af355f1 | |
|
|
23c4d38ee4 | |
|
|
b7a31af911 | |
|
|
76bf1c9a98 | |
|
|
fc339b3643 | |
|
|
6eb7b369a0 | |
|
|
01d7d19b11 | |
|
|
0953b83e3c | |
|
|
8a0b633bb1 | |
|
|
72077bbd0c | |
|
|
0cd189fb84 | |
|
|
87694c6218 | |
|
|
916a21eeec | |
|
|
f8f27d366d | |
|
|
ce9f11a35e | |
|
|
7fadc8d28d | |
|
|
3efbfd75cc | |
|
|
8820a42359 | |
|
|
0394971791 | |
|
|
430e304936 | |
|
|
765981f03d | |
|
|
c0b10e9467 | |
|
|
8c8a6edd25 | |
|
|
3f1adbc58f | |
|
|
a955946fdb | |
|
|
5782107c84 | |
|
|
9e2ab59121 | |
|
|
9fb2042cad | |
|
|
7a9cf371fb | |
|
|
1385cb9423 | |
|
|
e4c6a6138a | |
|
|
ae121a5eb9 | |
|
|
56ee600350 | |
|
|
7351d9c5a6 | |
|
|
2c6b5a7ce2 | |
|
|
9ce9e6d69a | |
|
|
b85ddbff4e | |
|
|
774d926bf9 | |
|
|
f9c048f4f1 | |
|
|
d91d5de440 | |
|
|
b5e830a5eb | |
|
|
115a265676 | |
|
|
e4e054e75a | |
|
|
99ff76d595 | |
|
|
303515cfba | |
|
|
7ceabebf02 | |
|
|
ed532421f5 | |
|
|
0231ef8a6e | |
|
|
f08240cf58 | |
|
|
630c3fde73 | |
|
|
67f9c06935 | |
|
|
8ed66f9553 | |
|
|
580faf659a | |
|
|
31d0020483 | |
|
|
04761fb6a3 | |
|
|
feaac0c713 | |
|
|
b841053628 | |
|
|
cf92089005 | |
|
|
e0a13702ea | |
|
|
c36e7373e8 | |
|
|
3671a83971 | |
|
|
c7bca41616 | |
|
|
486d745d47 | |
|
|
74b6648db1 | |
|
|
4543fa82f8 | |
|
|
83ba39e59a | |
|
|
533466b63a | |
|
|
6dee7613a5 | |
|
|
4c0263f7f7 | |
|
|
4d228cf1e1 | |
|
|
55215567dd | |
|
|
ab8d2c2185 | |
|
|
875177f779 | |
|
|
2a24ac34d0 | |
|
|
8fc61f986f | |
|
|
ee6768dee1 | |
|
|
091bb2c707 | |
|
|
2d05fb282d | |
|
|
3c54aba63f | |
|
|
a9e4511190 | |
|
|
fbf13b86f3 | |
|
|
9f35caf4ca | |
|
|
7bb7d211fa | |
|
|
430ab8a743 | |
|
|
04c31c7f53 | |
|
|
60282d730f | |
|
|
da238fad5c | |
|
|
85f0cb19cf | |
|
|
c95720f3da | |
|
|
730eab8553 | |
|
|
4d0249e8ef | |
|
|
4cd7321cc2 | |
|
|
fe1333621b | |
|
|
8dbf52cba3 | |
|
|
29e9ef739c | |
|
|
84797f55ab | |
|
|
53ce4f21a0 | |
|
|
ca9dd9ec06 | |
|
|
f9e272d6bf | |
|
|
ee539ea4a6 | |
|
|
5952fbe3cc | |
|
|
dfbaff2c21 | |
|
|
c2bc764613 | |
|
|
0951afa499 | |
|
|
ba5fe72873 | |
|
|
eb0a193fee | |
|
|
95e72f6136 | |
|
|
472fb8dc11 | |
|
|
8825cf0838 | |
|
|
0fdea7ee21 | |
|
|
9f143f730a | |
|
|
355a9f789a | |
|
|
53132036c5 | |
|
|
95a36e2bdf | |
|
|
9095f0dacd | |
|
|
a82c664e5b | |
|
|
4f34f7f19c | |
|
|
f20618400e | |
|
|
38f1752fda | |
|
|
6b58e0e8f3 | |
|
|
6fa6170c75 | |
|
|
02de5456aa | |
|
|
b67bd18eee | |
|
|
5ce4ed559a | |
|
|
f7cc555567 | |
|
|
e27378574c | |
|
|
902e762c91 | |
|
|
7257da174a | |
|
|
585c74556e | |
|
|
0a022a4763 | |
|
|
f88de11d98 | |
|
|
907d03ca38 | |
|
|
6d8e5dd68d | |
|
|
af7e148874 | |
|
|
2f15a90f15 | |
|
|
7986b1ca5b | |
|
|
cd218c9cf8 | |
|
|
8577824a3f | |
|
|
7656f3a3ce | |
|
|
f4830f043f | |
|
|
2870569c55 | |
|
|
8cfb7e9c17 | |
|
|
0ef43bb823 | |
|
|
ba71af2abb | |
|
|
6a685f8226 | |
|
|
da06cbc8f3 | |
|
|
4650947b00 | |
|
|
4ee2007754 | |
|
|
cb797c42d0 | |
|
|
0334322aae | |
|
|
2ba9a3694d | |
|
|
fe5db7cb10 | |
|
|
ebbe96e4e1 | |
|
|
57a5464103 | |
|
|
1b836b26ab | |
|
|
a0292b6087 | |
|
|
36ef6f2d04 | |
|
|
5fa957830c | |
|
|
c13642fa3b | |
|
|
3c687aad46 | |
|
|
f90607e471 | |
|
|
aeba340405 | |
|
|
ddb9ac2123 | |
|
|
360f84e5bd | |
|
|
c7a614958e | |
|
|
33145febbb | |
|
|
6d9b7d8a26 | |
|
|
532bdc7e76 | |
|
|
7bc31d2bac | |
|
|
25fa74eab6 | |
|
|
d8d3e858e9 | |
|
|
19f2c36400 | |
|
|
543e36e60e | |
|
|
54fdd444c9 | |
|
|
cbdb20402d | |
|
|
18899db1b2 | |
|
|
db1f8a5b89 | |
|
|
d63c039181 | |
|
|
05d4fe166c | |
|
|
5c39f24bee | |
|
|
3b88359746 | |
|
|
4155e48224 | |
|
|
6d57b3ef00 | |
|
|
38c4f242e4 | |
|
|
13128c510a | |
|
|
d018d68b79 | |
|
|
3920665d89 | |
|
|
d8930fd96a | |
|
|
43d28b2c81 | |
|
|
cea8ebaa5c | |
|
|
ba1a5cd16c | |
|
|
9ac0908c1e | |
|
|
ac91665263 | |
|
|
2bff6623d9 | |
|
|
85bac8f70a | |
|
|
800c07de5d | |
|
|
8e7c1e58e6 | |
|
|
55912832bf | |
|
|
b46be0d4be | |
|
|
24aa6dc0b2 | |
|
|
44bc2339d0 | |
|
|
def11a631c | |
|
|
49c3bce029 | |
|
|
04dc133453 | |
|
|
352253b95f | |
|
|
07ee8e85fe | |
|
|
d738caaaa1 | |
|
|
d3a07f3d32 | |
|
|
7f499d6263 | |
|
|
8c03903524 | |
|
|
abcb8999ce | |
|
|
9c59cabfc7 | |
|
|
89380ef70b | |
|
|
3564747c1b | |
|
|
46c1ac4519 | |
|
|
4ab0f04a1b | |
|
|
097a67e214 | |
|
|
f65fce3144 | |
|
|
65baa4ed7e | |
|
|
cba7be4b75 |
|
|
@ -1,4 +1,6 @@
|
||||||
name: Universal CI/CD Release Matrix
|
name: CI/CD
|
||||||
|
|
||||||
|
run-name: "CI/CD: release version ${{ github.ref_name }}"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
|
|
@ -16,8 +18,45 @@ env:
|
||||||
RUST_BACKTRACE: short
|
RUST_BACKTRACE: short
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
check-and-test:
|
||||||
|
name: Check & Test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Bump version based on tag
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
run: python scripts/bump_version.py ${{ github.ref_name }}
|
||||||
|
|
||||||
|
- name: Setup Rust toolchain
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Restore Cargo cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
target/
|
||||||
|
key: cargo-check-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
restore-keys: cargo-check-
|
||||||
|
|
||||||
|
- name: Install musl-tools
|
||||||
|
run: sudo apt-get update && sudo apt-get install -y musl-tools
|
||||||
|
|
||||||
|
- name: cargo check
|
||||||
|
run: cargo check --workspace
|
||||||
|
|
||||||
|
- name: cargo test
|
||||||
|
run: cargo test --workspace --lib
|
||||||
|
|
||||||
publish-release-matrix:
|
publish-release-matrix:
|
||||||
name: Release for ${{ matrix.target }}
|
name: Release for ${{ matrix.target }}
|
||||||
|
needs: check-and-test
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
|
|
@ -28,21 +67,18 @@ jobs:
|
||||||
target: x86_64-pc-windows-msvc
|
target: x86_64-pc-windows-msvc
|
||||||
artifact_name: ostp.exe
|
artifact_name: ostp.exe
|
||||||
release_name: ostp-windows-amd64.zip
|
release_name: ostp-windows-amd64.zip
|
||||||
tun2socks_arch: windows-amd64
|
|
||||||
wintun_arch: amd64
|
wintun_arch: amd64
|
||||||
|
|
||||||
- os: windows-latest
|
- os: windows-latest
|
||||||
target: i686-pc-windows-msvc
|
target: i686-pc-windows-msvc
|
||||||
artifact_name: ostp.exe
|
artifact_name: ostp.exe
|
||||||
release_name: ostp-windows-386.zip
|
release_name: ostp-windows-386.zip
|
||||||
tun2socks_arch: windows-386
|
|
||||||
wintun_arch: x86
|
wintun_arch: x86
|
||||||
|
|
||||||
- os: windows-latest
|
- os: windows-latest
|
||||||
target: aarch64-pc-windows-msvc
|
target: aarch64-pc-windows-msvc
|
||||||
artifact_name: ostp.exe
|
artifact_name: ostp.exe
|
||||||
release_name: ostp-windows-arm64.zip
|
release_name: ostp-windows-arm64.zip
|
||||||
tun2socks_arch: windows-arm64
|
|
||||||
wintun_arch: arm64
|
wintun_arch: arm64
|
||||||
|
|
||||||
# ── macOS ─────────────────────────────────────────────────────────
|
# ── macOS ─────────────────────────────────────────────────────────
|
||||||
|
|
@ -50,26 +86,22 @@ jobs:
|
||||||
target: x86_64-apple-darwin
|
target: x86_64-apple-darwin
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-darwin-amd64.tar.gz
|
release_name: ostp-darwin-amd64.tar.gz
|
||||||
tun2socks_arch: darwin-amd64
|
|
||||||
|
|
||||||
- os: macos-latest
|
- os: macos-latest
|
||||||
target: aarch64-apple-darwin
|
target: aarch64-apple-darwin
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-darwin-arm64.tar.gz
|
release_name: ostp-darwin-arm64.tar.gz
|
||||||
tun2socks_arch: darwin-arm64
|
|
||||||
|
|
||||||
# ── Linux native ──────────────────────────────────────────────────
|
# ── Linux native ──────────────────────────────────────────────────
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-latest
|
||||||
target: x86_64-unknown-linux-musl
|
target: x86_64-unknown-linux-musl
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-linux-amd64.tar.gz
|
release_name: ostp-linux-amd64.tar.gz
|
||||||
tun2socks_arch: linux-amd64
|
|
||||||
|
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-latest
|
||||||
target: i686-unknown-linux-musl
|
target: i686-unknown-linux-musl
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-linux-386.tar.gz
|
release_name: ostp-linux-386.tar.gz
|
||||||
tun2socks_arch: linux-386
|
|
||||||
use_cross: true
|
use_cross: true
|
||||||
|
|
||||||
# ── Linux cross ───────────────────────────────────────────────────
|
# ── Linux cross ───────────────────────────────────────────────────
|
||||||
|
|
@ -77,28 +109,24 @@ jobs:
|
||||||
target: aarch64-unknown-linux-musl
|
target: aarch64-unknown-linux-musl
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-linux-arm64.tar.gz
|
release_name: ostp-linux-arm64.tar.gz
|
||||||
tun2socks_arch: linux-arm64
|
|
||||||
use_cross: true
|
use_cross: true
|
||||||
|
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-latest
|
||||||
target: armv7-unknown-linux-musleabihf
|
target: armv7-unknown-linux-musleabihf
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-linux-armv7.tar.gz
|
release_name: ostp-linux-armv7.tar.gz
|
||||||
tun2socks_arch: linux-armv7
|
|
||||||
use_cross: true
|
use_cross: true
|
||||||
|
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-latest
|
||||||
target: x86_64-unknown-freebsd
|
target: x86_64-unknown-freebsd
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-freebsd-amd64.tar.gz
|
release_name: ostp-freebsd-amd64.tar.gz
|
||||||
tun2socks_arch: freebsd-amd64
|
|
||||||
use_cross: true
|
use_cross: true
|
||||||
|
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-latest
|
||||||
target: mipsel-unknown-linux-musl
|
target: mipsel-unknown-linux-musl
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-linux-mipsle.tar.gz
|
release_name: ostp-linux-mipsle.tar.gz
|
||||||
tun2socks_arch: linux-mipsle-softfloat
|
|
||||||
use_cross: true
|
use_cross: true
|
||||||
toolchain: nightly
|
toolchain: nightly
|
||||||
|
|
||||||
|
|
@ -106,20 +134,18 @@ jobs:
|
||||||
target: riscv64gc-unknown-linux-gnu
|
target: riscv64gc-unknown-linux-gnu
|
||||||
artifact_name: ostp
|
artifact_name: ostp
|
||||||
release_name: ostp-linux-riscv64.tar.gz
|
release_name: ostp-linux-riscv64.tar.gz
|
||||||
tun2socks_arch: linux-riscv64
|
|
||||||
use_cross: true
|
use_cross: true
|
||||||
|
|
||||||
- os: ubuntu-latest
|
|
||||||
target: aarch64-linux-android
|
|
||||||
artifact_name: ostp
|
|
||||||
release_name: ostp-android-arm64.tar.gz
|
|
||||||
tun2socks_arch: linux-arm64
|
|
||||||
use_cross: true
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Bump version based on tag
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
run: python scripts/bump_version.py ${{ github.ref_name }}
|
||||||
|
|
||||||
# ── Rust toolchain ─────────────────────────────────────────────────────
|
# ── Rust toolchain ─────────────────────────────────────────────────────
|
||||||
- name: Setup Rust toolchain
|
- name: Setup Rust toolchain
|
||||||
uses: dtolnay/rust-toolchain@stable
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
|
@ -169,31 +195,16 @@ jobs:
|
||||||
run: cross build --release --target ${{ matrix.target }} --bin ostp
|
run: cross build --release --target ${{ matrix.target }} --bin ostp
|
||||||
|
|
||||||
# ── Driver dependencies ────────────────────────────────────────────────
|
# ── Driver dependencies ────────────────────────────────────────────────
|
||||||
- name: Download tun2socks + wintun (Windows)
|
- name: Download wintun (Windows)
|
||||||
if: ${{ matrix.os == 'windows-latest' && matrix.tun2socks_arch }}
|
if: ${{ matrix.os == 'windows-latest' }}
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: |
|
run: |
|
||||||
$ProgressPreference = 'SilentlyContinue'
|
$ProgressPreference = 'SilentlyContinue'
|
||||||
$dir = "target/${{ matrix.target }}/release"
|
$dir = "target/${{ matrix.target }}/release"
|
||||||
Invoke-WebRequest -Uri "https://github.com/xjasonlyu/tun2socks/releases/download/v2.6.0/tun2socks-${{ matrix.tun2socks_arch }}.zip" -OutFile "$dir/t2s.zip"
|
|
||||||
Expand-Archive "$dir/t2s.zip" -DestinationPath "$dir/t2s_tmp" -Force
|
|
||||||
Get-ChildItem "$dir/t2s_tmp" -Filter "*.exe" -Recurse | Select-Object -First 1 | Copy-Item -Destination "$dir/tun2socks.exe"
|
|
||||||
Invoke-WebRequest -Uri "https://www.wintun.net/builds/wintun-0.14.1.zip" -OutFile "$dir/wt.zip"
|
Invoke-WebRequest -Uri "https://www.wintun.net/builds/wintun-0.14.1.zip" -OutFile "$dir/wt.zip"
|
||||||
Expand-Archive "$dir/wt.zip" -DestinationPath "$dir/wt_tmp" -Force
|
Expand-Archive "$dir/wt.zip" -DestinationPath "$dir/wt_tmp" -Force
|
||||||
Get-ChildItem "$dir/wt_tmp" -Filter "wintun.dll" -Recurse | Where-Object { $_.FullName -match 'bin[\\/]${{ matrix.wintun_arch }}[\\/]' } | Copy-Item -Destination "$dir/"
|
Get-ChildItem "$dir/wt_tmp" -Filter "wintun.dll" -Recurse | Where-Object { $_.FullName -match 'bin[\\/]${{ matrix.wintun_arch }}[\\/]' } | Copy-Item -Destination "$dir/"
|
||||||
Remove-Item "$dir/t2s.zip","$dir/t2s_tmp","$dir/wt.zip","$dir/wt_tmp" -Recurse -Force
|
Remove-Item "$dir/wt.zip","$dir/wt_tmp" -Recurse -Force
|
||||||
|
|
||||||
- name: Download tun2socks (Unix)
|
|
||||||
if: ${{ matrix.os != 'windows-latest' && matrix.tun2socks_arch }}
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
dir="target/${{ matrix.target }}/release"
|
|
||||||
URL="https://github.com/xjasonlyu/tun2socks/releases/download/v2.6.0/tun2socks-${{ matrix.tun2socks_arch }}.zip"
|
|
||||||
curl -fsSL "$URL" -o "$dir/t2s.zip" || exit 0
|
|
||||||
unzip -o "$dir/t2s.zip" -d "$dir/t2s_tmp"
|
|
||||||
find "$dir/t2s_tmp" -type f -name "tun2socks*" ! -name "*.zip" | head -1 | xargs -I{} cp {} "$dir/tun2socks"
|
|
||||||
chmod +x "$dir/tun2socks" 2>/dev/null || true
|
|
||||||
rm -rf "$dir/t2s.zip" "$dir/t2s_tmp"
|
|
||||||
|
|
||||||
# ── Package ────────────────────────────────────────────────────────────
|
# ── Package ────────────────────────────────────────────────────────────
|
||||||
- name: Package (Windows)
|
- name: Package (Windows)
|
||||||
|
|
@ -202,7 +213,6 @@ jobs:
|
||||||
run: |
|
run: |
|
||||||
$dir = "target/${{ matrix.target }}/release"
|
$dir = "target/${{ matrix.target }}/release"
|
||||||
$files = @("ostp.exe")
|
$files = @("ostp.exe")
|
||||||
if (Test-Path "$dir/tun2socks.exe") { $files += "tun2socks.exe" }
|
|
||||||
if (Test-Path "$dir/wintun.dll") { $files += "wintun.dll" }
|
if (Test-Path "$dir/wintun.dll") { $files += "wintun.dll" }
|
||||||
Push-Location $dir
|
Push-Location $dir
|
||||||
Compress-Archive -Path $files -DestinationPath "../../../${{ matrix.release_name }}" -Force
|
Compress-Archive -Path $files -DestinationPath "../../../${{ matrix.release_name }}" -Force
|
||||||
|
|
@ -213,7 +223,6 @@ jobs:
|
||||||
run: |
|
run: |
|
||||||
dir="target/${{ matrix.target }}/release"
|
dir="target/${{ matrix.target }}/release"
|
||||||
FILES="${{ matrix.artifact_name }}"
|
FILES="${{ matrix.artifact_name }}"
|
||||||
[ -f "$dir/tun2socks" ] && FILES="$FILES tun2socks"
|
|
||||||
tar -czf "${{ matrix.release_name }}" -C "$dir" $FILES
|
tar -czf "${{ matrix.release_name }}" -C "$dir" $FILES
|
||||||
|
|
||||||
# ── Upload ─────────────────────────────────────────────────────────────
|
# ── Upload ─────────────────────────────────────────────────────────────
|
||||||
|
|
@ -225,4 +234,280 @@ jobs:
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
build-windows-gui:
|
||||||
|
name: Build Windows GUI (Tauri) - ${{ matrix.arch }}
|
||||||
|
needs: check-and-test
|
||||||
|
runs-on: windows-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- arch: amd64
|
||||||
|
target: x86_64-pc-windows-msvc
|
||||||
|
- arch: arm64
|
||||||
|
target: aarch64-pc-windows-msvc
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Bump version based on tag
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
run: python scripts/bump_version.py ${{ github.ref_name }}
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
|
||||||
|
- name: Setup Rust toolchain
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
|
- name: Install Tauri CLI
|
||||||
|
run: npm install -g @tauri-apps/cli
|
||||||
|
|
||||||
|
- name: Cache cargo
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
target/
|
||||||
|
key: cargo-windows-gui-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|
||||||
|
- name: Download wintun
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ProgressPreference = 'SilentlyContinue'
|
||||||
|
|
||||||
|
# Download wintun
|
||||||
|
New-Item -ItemType Directory -Force -Path "target/${{ matrix.target }}/release"
|
||||||
|
Invoke-WebRequest -Uri "https://www.wintun.net/builds/wintun-0.14.1.zip" -OutFile "target/wt.zip"
|
||||||
|
Expand-Archive "target/wt.zip" -DestinationPath "target/wt_tmp" -Force
|
||||||
|
Get-ChildItem "target/wt_tmp" -Filter "wintun.dll" -Recurse | Where-Object { $_.FullName -match 'bin[\\/]${{ matrix.arch }}[\\/]' } | Copy-Item -Destination "target/${{ matrix.target }}/release/wintun.dll" -Force
|
||||||
|
|
||||||
|
- name: Build Tauri App
|
||||||
|
working-directory: ostp-gui
|
||||||
|
run: |
|
||||||
|
npm install
|
||||||
|
cargo build -p ostp-tun-helper --release --target ${{ matrix.target }}
|
||||||
|
npx tauri build --no-bundle --target ${{ matrix.target }}
|
||||||
|
|
||||||
|
- name: Package Portable ZIP
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$dir = "ostp-gui-dist"
|
||||||
|
New-Item -ItemType Directory -Force -Path $dir
|
||||||
|
Copy-Item "ostp-gui/src-tauri/target/${{ matrix.target }}/release/ostp-gui.exe" $dir
|
||||||
|
Copy-Item "target/${{ matrix.target }}/release/ostp-tun-helper.exe" $dir
|
||||||
|
Copy-Item "target/${{ matrix.target }}/release/wintun.dll" $dir
|
||||||
|
|
||||||
|
Compress-Archive -Path "$dir/*" -DestinationPath "ostp-windows-gui-${{ matrix.arch }}.zip" -Force
|
||||||
|
|
||||||
|
- name: Upload to GitHub Release
|
||||||
|
if: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: ostp-windows-gui-${{ matrix.arch }}.zip
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
build-linux-gui:
|
||||||
|
name: Build Linux GUI (Tauri) - ${{ matrix.arch }}
|
||||||
|
needs: check-and-test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- arch: amd64
|
||||||
|
target: x86_64-unknown-linux-gnu
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Bump version based on tag
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
run: python scripts/bump_version.py ${{ github.ref_name }}
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
|
||||||
|
- name: Setup Rust toolchain
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
|
- name: Install Linux Dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
|
||||||
|
|
||||||
|
- name: Install Tauri CLI
|
||||||
|
run: npm install -g @tauri-apps/cli
|
||||||
|
|
||||||
|
- name: Cache cargo
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
target/
|
||||||
|
key: cargo-linux-gui-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|
||||||
|
- name: Build Tauri App
|
||||||
|
working-directory: ostp-gui
|
||||||
|
run: |
|
||||||
|
npm install
|
||||||
|
npx tauri build --no-bundle --target ${{ matrix.target }}
|
||||||
|
|
||||||
|
- name: Package Portable Tarball
|
||||||
|
run: |
|
||||||
|
mkdir ostp-linux-gui-${{ matrix.arch }}
|
||||||
|
cp ostp-gui/src-tauri/target/${{ matrix.target }}/release/ostp-gui ostp-linux-gui-${{ matrix.arch }}/
|
||||||
|
tar -czf ostp-linux-gui-${{ matrix.arch }}.tar.gz ostp-linux-gui-${{ matrix.arch }}
|
||||||
|
|
||||||
|
- name: Upload to GitHub Release
|
||||||
|
if: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: ostp-linux-gui-${{ matrix.arch }}.tar.gz
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
build-macos-gui:
|
||||||
|
name: Build macOS GUI (Tauri) - ${{ matrix.arch }}
|
||||||
|
needs: check-and-test
|
||||||
|
runs-on: macos-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- arch: amd64
|
||||||
|
target: x86_64-apple-darwin
|
||||||
|
- arch: arm64
|
||||||
|
target: aarch64-apple-darwin
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Bump version based on tag
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
run: python scripts/bump_version.py ${{ github.ref_name }}
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
|
||||||
|
- name: Setup Rust toolchain
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
|
- name: Install Tauri CLI
|
||||||
|
run: npm install -g @tauri-apps/cli
|
||||||
|
|
||||||
|
- name: Cache cargo
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
target/
|
||||||
|
key: cargo-macos-gui-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|
||||||
|
- name: Build Tauri App
|
||||||
|
working-directory: ostp-gui
|
||||||
|
run: |
|
||||||
|
npm install
|
||||||
|
npx tauri build --no-bundle --target ${{ matrix.target }}
|
||||||
|
|
||||||
|
- name: Package Portable Tarball
|
||||||
|
run: |
|
||||||
|
mkdir ostp-macos-gui-${{ matrix.arch }}
|
||||||
|
cp ostp-gui/src-tauri/target/${{ matrix.target }}/release/ostp-gui ostp-macos-gui-${{ matrix.arch }}/
|
||||||
|
tar -czf ostp-macos-gui-${{ matrix.arch }}.tar.gz ostp-macos-gui-${{ matrix.arch }}
|
||||||
|
|
||||||
|
- name: Upload to GitHub Release
|
||||||
|
if: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: ostp-macos-gui-${{ matrix.arch }}.tar.gz
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
build-android:
|
||||||
|
name: Build Android Client (Flutter) - ${{ matrix.arch }}
|
||||||
|
needs: check-and-test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- arch: arm64-v8a
|
||||||
|
rust_target: aarch64-linux-android
|
||||||
|
flutter_target: android-arm64
|
||||||
|
- arch: armeabi-v7a
|
||||||
|
rust_target: armv7-linux-androideabi
|
||||||
|
flutter_target: android-arm
|
||||||
|
tun2socks_arch: linux-armv7
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Bump version based on tag
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
run: python scripts/bump_version.py ${{ github.ref_name }}
|
||||||
|
|
||||||
|
- name: Setup Java
|
||||||
|
uses: actions/setup-java@v3
|
||||||
|
with:
|
||||||
|
distribution: 'zulu'
|
||||||
|
java-version: '17'
|
||||||
|
|
||||||
|
- name: Setup Flutter
|
||||||
|
uses: subosito/flutter-action@v2
|
||||||
|
with:
|
||||||
|
flutter-version: '3.41.6'
|
||||||
|
channel: 'stable'
|
||||||
|
|
||||||
|
- name: Setup Rust toolchain
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
targets: ${{ matrix.rust_target }}
|
||||||
|
|
||||||
|
- name: Setup Android NDK
|
||||||
|
uses: nttld/setup-ndk@v1
|
||||||
|
with:
|
||||||
|
ndk-version: r26b
|
||||||
|
|
||||||
|
- name: Install cargo-ndk
|
||||||
|
run: cargo install cargo-ndk
|
||||||
|
|
||||||
|
- name: Build Android APK
|
||||||
|
shell: bash
|
||||||
|
working-directory: ostp-flutter
|
||||||
|
run: |
|
||||||
|
# 1. Compile JNI
|
||||||
|
mkdir -p android/app/src/main/jniLibs/${{ matrix.arch }}
|
||||||
|
|
||||||
|
cd ../ostp-jni
|
||||||
|
cargo ndk -t ${{ matrix.arch }} -o "../ostp-flutter/android/app/src/main/jniLibs" build --release
|
||||||
|
cd ../ostp-flutter
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# 3. Build Flutter APK
|
||||||
|
flutter build apk --release --target-platform ${{ matrix.flutter_target }}
|
||||||
|
|
||||||
|
# 4. Copy to output
|
||||||
|
cp build/app/outputs/flutter-apk/app-release.apk ostp-android-${{ matrix.arch }}.apk
|
||||||
|
|
||||||
|
- name: Upload to GitHub Release
|
||||||
|
if: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: ostp-flutter/ostp-android-${{ matrix.arch }}.apk
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
127.0.0.1
|
|
||||||
|
|
@ -0,0 +1,106 @@
|
||||||
|
# Contributing to OSTP
|
||||||
|
|
||||||
|
Thank you for your interest in contributing to **OSTP (Ospab Stealth Transport Protocol)**! We welcome contributions from developers, security researchers, testers, and documentation writers of all skill levels.
|
||||||
|
|
||||||
|
By contributing to this project, you agree to abide by our code of conduct and license terms.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Development Setup](#development-setup)
|
||||||
|
2. [Project Structure](#project-structure)
|
||||||
|
3. [Development Workflow](#development-workflow)
|
||||||
|
4. [Coding Guidelines](#coding-guidelines)
|
||||||
|
5. [Submitting Pull Requests](#submitting-pull-requests)
|
||||||
|
6. [Security Vulnerabilities](#security-vulnerabilities)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Development Setup
|
||||||
|
|
||||||
|
To build and test OSTP locally, you will need:
|
||||||
|
|
||||||
|
* **Rust Toolchain**: Install via [rustup](https://rustup.rs/) (stable channel).
|
||||||
|
* **Node.js (18+) & npm**: Required to compile Tauri GUI resources.
|
||||||
|
* **Git**: For version control.
|
||||||
|
|
||||||
|
### Building the Project
|
||||||
|
|
||||||
|
1. **Clone the repository**:
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/ospab/ostp.git
|
||||||
|
cd ostp
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Build the entire Cargo workspace**:
|
||||||
|
```bash
|
||||||
|
cargo build
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Run tests**:
|
||||||
|
```bash
|
||||||
|
cargo test --workspace
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
The repository is organized as a Cargo workspace containing the following crates:
|
||||||
|
|
||||||
|
* [`ostp-core/`](file:///d:/ospab-projects/ostp/ostp-core): Core protocol logic, including packet formatting, serialization, selective ACK/NACK (ARQ) state machine, and the Noise protocol (`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`) handshake.
|
||||||
|
* [`ostp-client/`](file:///d:/ospab-projects/ostp/ostp-client): Client implementations, including SOCKS5/HTTP local proxies, `tun2socks` integration, native TUN interface routing, and split-tunneling bypass mechanisms.
|
||||||
|
* [`ostp-server/`](file:///d:/ospab-projects/ostp/ostp-server): Server logic, session dispatcher, anti-probing fallback server proxying, access key database, and the REST API.
|
||||||
|
* [`ostp-gui/`](file:///d:/ospab-projects/ostp/ostp-gui): Tauri-based desktop GUI application for Windows and Linux.
|
||||||
|
* [`ostp-flutter/`](file:///d:/ospab-projects/ostp/ostp-flutter): Mobile client code for Android platforms.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Development Workflow
|
||||||
|
|
||||||
|
1. **Check for existing issues** or open a new one to discuss proposed changes before starting work.
|
||||||
|
2. **Fork the repository** and create a new branch from `master`:
|
||||||
|
```bash
|
||||||
|
git checkout -b feat/your-feature-name
|
||||||
|
```
|
||||||
|
3. **Implement your changes**, ensuring you write appropriate unit or integration tests.
|
||||||
|
4. **Format your code**:
|
||||||
|
```bash
|
||||||
|
cargo fmt --all
|
||||||
|
```
|
||||||
|
5. **Run linter checks**:
|
||||||
|
```bash
|
||||||
|
cargo clippy --workspace --all-targets -- -D warnings
|
||||||
|
```
|
||||||
|
6. **Ensure all tests pass**:
|
||||||
|
```bash
|
||||||
|
cargo test --workspace
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Coding Guidelines
|
||||||
|
|
||||||
|
* **Safety**: Avoid using `unsafe` blocks unless absolutely necessary for low-level system bindings (e.g., FFI configurations like `setsockopt`). When using `unsafe`, add safety doc comments explaining why it is safe.
|
||||||
|
* **Documentation**: Document public modules, structs, and functions. Maintain comment integrity across codebase changes.
|
||||||
|
* **Logging**: Use the `tracing` framework for structured logging. Avoid `println!` for production logs.
|
||||||
|
* **Aesthetics**: When editing GUI or Web components, adhere to premium, modern web design aesthetics (vibrant color palettes, glassmorphism, responsive grids).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Submitting Pull Requests
|
||||||
|
|
||||||
|
1. Push your branch to your GitHub fork:
|
||||||
|
```bash
|
||||||
|
git push origin feat/your-feature-name
|
||||||
|
```
|
||||||
|
2. Open a Pull Request (PR) targeting the `master` branch.
|
||||||
|
3. In your PR description, explain the rationale behind your changes, what was fixed/added, and how it was tested.
|
||||||
|
4. Verify that GitHub Actions CI runs successfully on your PR.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security Vulnerabilities
|
||||||
|
|
||||||
|
If you discover a security-related vulnerability, please do **not** open a public issue. Instead, report it privately by emailing the core maintainers at [gvoprgrg@gmail.com](mailto:gvoprgrg@gmail.com). We will coordinate a swift disclosure and fix.
|
||||||
|
|
@ -0,0 +1,106 @@
|
||||||
|
# Участие в разработке OSTP
|
||||||
|
|
||||||
|
Спасибо за интерес к участию в разработке **OSTP (Ospab Stealth Transport Protocol)**! Мы рады любой помощи: от написания кода и тестирования до работы над документацией и проведения аудита безопасности.
|
||||||
|
|
||||||
|
Присылая изменения в проект, вы соглашаетесь соблюдать правила нашего сообщества и условия лицензии.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Содержание
|
||||||
|
|
||||||
|
1. [Подготовка окружения](#подготовка-окружения)
|
||||||
|
2. [Структура проекта](#структура-проекта)
|
||||||
|
3. [Процесс разработки](#процесс-разработки)
|
||||||
|
4. [Правила оформления кода](#правила-оформления-кода)
|
||||||
|
5. [Создание Pull Request](#создание-pull-request)
|
||||||
|
6. [Уязвимости безопасности](#уязвимости-безопасности)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Подготовка окружения
|
||||||
|
|
||||||
|
Для локальной сборки и тестирования OSTP вам понадобятся:
|
||||||
|
|
||||||
|
* **Rust Toolchain**: Установите через [rustup](https://rustup.rs/) (stable канал).
|
||||||
|
* **Node.js (18+) и npm**: Необходимы для сборки интерфейса Tauri.
|
||||||
|
* **Git**: Для контроля версий.
|
||||||
|
|
||||||
|
### Сборка проекта
|
||||||
|
|
||||||
|
1. **Клонируйте репозиторий**:
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/ospab/ostp.git
|
||||||
|
cd ostp
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Соберите весь Cargo-workspace**:
|
||||||
|
```bash
|
||||||
|
cargo build
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Запустите тесты**:
|
||||||
|
```bash
|
||||||
|
cargo test --workspace
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Структура проекта
|
||||||
|
|
||||||
|
Репозиторий представляет собой единый Cargo-workspace со следующими компонентами:
|
||||||
|
|
||||||
|
* [`ostp-core/`](file:///d:/ospab-projects/ostp/ostp-core): Базовая логика протокола: форматирование пакетов, сериализация, конечный автомат выборочного подтверждения (ARQ/ACK/NACK) и рукопожатие Noise (`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`).
|
||||||
|
* [`ostp-client/`](file:///d:/ospab-projects/ostp/ostp-client): Клиентская часть: локальные SOCKS5/HTTP прокси-серверы, интеграция с драйвером `wintun` / `tun2socks` и реализация раздельного туннелирования для прямого обхода трафика.
|
||||||
|
* [`ostp-server/`](file:///d:/ospab-projects/ostp/ostp-server): Логика сервера, диспетчер сессий, защита от пробинга, база данных ключей и REST API.
|
||||||
|
* [`ostp-gui/`](file:///d:/ospab-projects/ostp/ostp-gui): Настольное приложение-клиент для Windows и Linux на платформе Tauri.
|
||||||
|
* [`ostp-flutter/`](file:///d:/ospab-projects/ostp/ostp-flutter): Мобильный клиент для платформы Android.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Процесс разработки
|
||||||
|
|
||||||
|
1. **Проверьте существующие задачи** или откройте новую тему (Issue) для обсуждения предлагаемых изменений.
|
||||||
|
2. **Сделайте fork репозитория** и создайте новую ветку от `master`:
|
||||||
|
```bash
|
||||||
|
git checkout -b feat/имя-вашей-фичи
|
||||||
|
```
|
||||||
|
3. **Внесите необходимые изменения** и добавьте соответствующие модульные или интеграционные тесты.
|
||||||
|
4. **Выровняйте форматирование кода**:
|
||||||
|
```bash
|
||||||
|
cargo fmt --all
|
||||||
|
```
|
||||||
|
5. **Запустите статический анализатор**:
|
||||||
|
```bash
|
||||||
|
cargo clippy --workspace --all-targets -- -D warnings
|
||||||
|
```
|
||||||
|
6. **Убедитесь, что все тесты проходят**:
|
||||||
|
```bash
|
||||||
|
cargo test --workspace
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Правила оформления кода
|
||||||
|
|
||||||
|
* **Безопасность (Safety)**: Избегайте использования блоков `unsafe` везде, где это возможно. Допускается их использование только для низкоуровневых системных вызовов (например, FFI-настройки сокетов `setsockopt`). Любой блок `unsafe` должен сопровождаться комментарием `// SAFETY: ...`.
|
||||||
|
* **Документация**: Пишите документацию для публичных модулей, структур и методов. Сохраняйте целостность комментариев при рефакторинге.
|
||||||
|
* **Логирование**: Используйте фреймворк `tracing` для структурированного логирования. Не используйте `println!` в рабочем коде.
|
||||||
|
* **Дизайн**: При изменении веб-интерфейсов или GUI следуйте современным визуальным трендам (плавные анимации, сбалансированная цветовая гамма, адаптивная верстка).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Создание Pull Request
|
||||||
|
|
||||||
|
1. Отправьте ветку в ваш fork-репозиторий:
|
||||||
|
```bash
|
||||||
|
git push origin feat/имя-вашей-фичи
|
||||||
|
```
|
||||||
|
2. Создайте Pull Request (PR) в ветку `master` основного репозитория.
|
||||||
|
3. Подробно опишите внесенные изменения: какая проблема решается, как проводилось тестирование и на каких платформах проверялась сборка.
|
||||||
|
4. Убедитесь, что автоматическое тестирование (GitHub Actions CI) завершилось успешно.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Уязвимости безопасности
|
||||||
|
|
||||||
|
Если вы обнаружили уязвимость, пожалуйста, **не** публикуйте её в открытых Issue. Вместо этого отправьте отчёт разработчикам на почту [gvoprgrg@gmail.com](mailto:gvoprgrg@gmail.com) для координации закрытого исправления.
|
||||||
|
|
@ -6,13 +6,13 @@ members = [
|
||||||
"ostp-jni", "ostp",
|
"ostp-jni", "ostp",
|
||||||
"ostp-tun-helper"
|
"ostp-tun-helper"
|
||||||
]
|
]
|
||||||
exclude = ["ostp-gui/src-tauri"]
|
exclude = ["ostp-gui/src-tauri", "ostp-brain", "ostp-prober", "ostp-sandbox", "ostp-control", "ostp-license"]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "BSL 1.1"
|
license = "BSL 1.1"
|
||||||
version = "0.2.30"
|
version = "0.3.12"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
|
|
@ -26,3 +26,8 @@ tracing = "0.1"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
hmac = "0.12"
|
hmac = "0.12"
|
||||||
portable-atomic = "1.10"
|
portable-atomic = "1.10"
|
||||||
|
ed25519-dalek = "2.1"
|
||||||
|
base64 = "0.22"
|
||||||
|
|
||||||
|
[patch.crates-io]
|
||||||
|
netstack-smoltcp = { path = "netstack-smoltcp" }
|
||||||
|
|
|
||||||
701
LICENSE
|
|
@ -1,74 +1,661 @@
|
||||||
Business Source License 1.1
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
Parameters
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Licensor: Ospab Foundation (represented by Syralev Georgiy)
|
Preamble
|
||||||
Licensed Work: The Ospab Stealth Transport Protocol (OSTP) and all
|
|
||||||
associated workspace crates, utilities, and documents.
|
|
||||||
Additional Use Grant: The Licensor hereby grants you the right to copy,
|
|
||||||
modify, create derivative works, redistribute, and
|
|
||||||
make non-production and non-commercial use of the
|
|
||||||
Licensed Work. You are also permitted to use the
|
|
||||||
Licensed Work in production for personal, private
|
|
||||||
utility and non-profit organizations.
|
|
||||||
Change Date: May 14, 2030
|
|
||||||
Change License: MIT License (as defined below)
|
|
||||||
|
|
||||||
-----------------------------------------------------------------------------------
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
Terms
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
1. The Licensor hereby grants you the right to copy, modify, create derivative works,
|
When we speak of free software, we are referring to freedom, not
|
||||||
redistribute, and make use of the Licensed Work only as permitted by the
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
Additional Use Grant.
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
2. The Licensor hereby grants you the right to copy, modify, create derivative works,
|
Developers that use our General Public Licenses protect your rights
|
||||||
redistribute, and make use of the Licensed Work under the terms of the Change
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
License on and after the Change Date.
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
3. To the extent that any term of this License (including the Additional Use Grant
|
A secondary benefit of defending all users' freedom is that
|
||||||
and the Change License) is in conflict with the Terms of this License, these
|
improvements made in alternate versions of the program, if they
|
||||||
Terms shall take precedence.
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
4. Every copy of the Licensed Work and any derivative work must include this
|
The GNU Affero General Public License is designed specifically to
|
||||||
License and all other copyright, trademark, and proprietary notices included
|
ensure that, in such cases, the modified source code becomes available
|
||||||
with the Licensed Work.
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
5. Any use of the Licensed Work that is not permitted by this License is a breach
|
An older license, called the Affero General Public License and
|
||||||
of this License and may terminate your rights under this License.
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
6. DISCLAIMER OF WARRANTY. TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED
|
The precise terms and conditions for copying, distribution and
|
||||||
WORK IS PROVIDED ON AN "AS IS" BASIS. THE LICENSOR MAKES NO REPRESENTATIONS OR
|
modification follow.
|
||||||
WARRANTIES OF ANY KIND CONCERNING THE LICENSED WORK, EXPRESS OR IMPLIED, STATUTORY
|
|
||||||
OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE,
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NONINFRINGEMENT.
|
|
||||||
|
|
||||||
7. LIMITATION OF LIABILITY. TO THE EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT
|
TERMS AND CONDITIONS
|
||||||
WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL,
|
|
||||||
CONSEQUENTIAL, PUNITIVE, OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE
|
|
||||||
USE OF THE LICENSED WORK, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE
|
|
||||||
POSSIBILITY OF SUCH DAMAGES.
|
|
||||||
|
|
||||||
-----------------------------------------------------------------------------------
|
0. Definitions.
|
||||||
|
|
||||||
Change License Text (MIT License)
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
Copyright (c) 2026 Syralev Georgiy (Ospab Foundation)
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
in the Software without restriction, including without limitation the rights
|
"recipients" may be individuals or organizations.
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
copies or substantial portions of the Software.
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
A "covered work" means either the unmodified Program or a work based
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
on the Program.
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
To "propagate" a work means to do anything with it that, without
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
permission, would make you directly or secondarily liable for
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
infringement under applicable copyright law, except executing it on a
|
||||||
SOFTWARE.
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
|
||||||
245
README.md
|
|
@ -1,198 +1,139 @@
|
||||||
# OSTP — Ospab Stealth Transport Protocol
|
# OSTP — Ospab Stealth Transport Protocol
|
||||||
|
|
||||||
[Русский язык](README.ru.md) · [Wiki](https://github.com/ospab/ostp/wiki) · [Releases](https://github.com/ospab/ostp/releases)
|
[Русский язык](README.ru.md) · [Wiki](https://github.com/ospab/ostp/wiki) · [Contributing](CONTRIBUTING.md) · [Releases](https://github.com/ospab/ostp/releases) · [Migration Guide](docs/migration_v0_3_1.md)
|
||||||
|
|
||||||

|

|
||||||

|

|
||||||

|

|
||||||

|

|
||||||

|

|
||||||
|
|
||||||
**OSTP** is a high-performance, censorship-resistant transport protocol designed to tunnel TCP traffic over UDP with full traffic obfuscation. Every byte on the wire — including packet headers — is cryptographically indistinguishable from random noise. Resistant to Deep Packet Inspection (DPI), active probing, and statistical traffic analysis.
|
OSTP (Ospab Stealth Transport Protocol) is an encrypted transport protocol written in Rust. It implements a custom ARQ transport over UDP and a UDP-over-TCP (UoT) mode. The protocol uses cryptographic masking for all packet headers and payloads to resist traffic classification by Deep Packet Inspection (DPI) systems.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **Upgrading from v0.2.x?** Please read the [v0.3.1 Configuration Migration Guide](docs/migration_v0_3_1.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Install
|
## Technical Capabilities
|
||||||
|
|
||||||
### Linux
|
| Capability | Description |
|
||||||
```bash
|
|------------|-------------|
|
||||||
bash <(curl -Ls https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.sh)
|
| **Traffic Masking** | Header and payload encryption using per-packet HMAC-derived keys. Indistinguishable from random noise. |
|
||||||
```
|
| **Noise Protocol** | `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` — PSK-authenticated, forward-secret key exchange. |
|
||||||
|
|
||||||
### Windows (PowerShell, run as Administrator)
|
|
||||||
```powershell
|
|
||||||
irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | iex
|
|
||||||
```
|
|
||||||
|
|
||||||
### Manual Download
|
|
||||||
Download pre-built binaries for your platform from [GitHub Releases](https://github.com/ospab/ostp/releases).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Key Features
|
|
||||||
|
|
||||||
| Feature | Description |
|
|
||||||
|---------|-------------|
|
|
||||||
| **Full Traffic Obfuscation** | Every packet — including headers — is indistinguishable from random noise. Session IDs and nonces are masked with per-packet HMAC-derived keys. |
|
|
||||||
| **Noise Protocol Handshake** | `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` — PSK-authenticated, forward-secret key exchange with no static identity exposure. |
|
|
||||||
| **Reliable UDP (ARQ)** | Selective ACK/NACK with rate-limited retransmission, configurable reorder buffer, and exponential backoff. |
|
| **Reliable UDP (ARQ)** | Selective ACK/NACK with rate-limited retransmission, configurable reorder buffer, and exponential backoff. |
|
||||||
| **Multiplexed Streams** | Multiple logical TCP streams over a single encrypted UDP session with per-stream flow control. |
|
| **Multiplexed Streams**| Multiple logical TCP streams over a single encrypted UDP session with per-stream flow control. |
|
||||||
| **Seamless Roaming** | Clients can switch networks (WiFi ↔ LTE) without session interruption — tracked by session-ID, not IP. |
|
| **Session Roaming** | Connection persistence across IP changes via session ID tracking. |
|
||||||
| **Management API** | Built-in REST API for third-party panels (3x-ui, custom dashboards). Per-user stats, traffic limits, key CRUD. |
|
| **UoT Mode** | UDP-over-TCP encapsulation with length-prefixing to bypass UDP blocking. |
|
||||||
| **Fallback Server** | TCP fallback proxy to a web server — makes OSTP indistinguishable from nginx during active probing. |
|
| **Fallback Server** | TCP proxying to a legitimate web server to resist active probing. |
|
||||||
| **Multi-Listener** | Bind to multiple addresses simultaneously (dual-stack IPv4/IPv6, multi-port). |
|
| **TUN Mode** | Native network stack integration (`smoltcp`) for full-system routing without external dependencies. |
|
||||||
| **TUN Mode** | Full-system VPN via `tun2socks` integration. All traffic transparently routed through the tunnel. |
|
| **Management API** | Built-in REST API for server administration, metrics, and key generation. |
|
||||||
| **xHTTP Stealth (UoT)** | UDP-over-TCP tunnel disguised as standard HTTP/1.1 or TLS traffic to bypass Level 1 Deep Packet Inspection (DPI) whitelists. |
|
| **TURN Relay** | RFC 5766 TURN support for NAT traversal. |
|
||||||
| **TURN Relay** | RFC 5766 TURN support for environments where direct UDP is blocked. |
|
|
||||||
| **Hot-Reload** | Runtime config reload without restart (access keys, exclusions, mux settings). |
|
|
||||||
| **Structured Logging** | `tracing`-based logging with `RUST_LOG` filtering. JSON/file/syslog output support. |
|
|
||||||
| **Cross-Platform** | Windows, Linux, macOS, Android, FreeBSD, MIPS, RISC-V. Single binary, no runtime dependencies. |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
```
|
```mermaid
|
||||||
┌─────────────────────────────────────────────────────────────┐
|
flowchart LR
|
||||||
│ Client │
|
Apps[Local Apps] -->|SOCKS5 / TUN| CoreC
|
||||||
│ ┌──────────┐ ┌──────────┐ ┌────────────────────────┐ │
|
|
||||||
│ │ Browser │──▸│ SOCKS5/ │──▸│ Bridge (Mux) │ │
|
subgraph Client [Client Node]
|
||||||
│ │ / Apps │ │ HTTP │ │ ┌─────────────────┐ │ │
|
CoreC[OSTP Client] -.->|Encrypt & Mask| NetC[Transport Layer]
|
||||||
│ │ │ │ Proxy │ │ │ ProtocolMachine │ │ │
|
end
|
||||||
│ └──────────┘ └──────────┘ │ │ (Noise + AEAD) │ │ │
|
|
||||||
│ │ └────────┬────────┘ │ │
|
NetC <==>|Encrypted UDP / UoT| NetS
|
||||||
│ ┌──────────┐ │ │ │ │
|
|
||||||
│ │ TUN Mode │──────────────────┤ UDP Socket │ │
|
subgraph Server [Server Node]
|
||||||
│ │tun2socks │ │ (32MB buffers, │ │
|
NetS[Transport Layer] -.->|Decrypt & Auth| CoreS[OSTP Server]
|
||||||
│ └──────────┘ │ obfuscated wire) │ │
|
NetS -->|Unauthenticated| Fallback[Fallback Server]
|
||||||
│ └───────────┬────────────┘ │
|
end
|
||||||
└────────────────────────────────────────────┼────────────────┘
|
|
||||||
│ UDP
|
CoreS -->|Relay| WWW((Internet))
|
||||||
┌────────────────────────────────────────────┼────────────────┐
|
Fallback -->|Forward| Web((Web / NGINX))
|
||||||
│ Server │ │
|
|
||||||
│ ┌─────────────────────────────────────────┴───────────┐ │
|
|
||||||
│ │ Dispatcher │ │
|
|
||||||
│ │ (Session lookup, roaming, replay guard, per-user │ │
|
|
||||||
│ │ traffic accounting, limit enforcement) │ │
|
|
||||||
│ └──┬──────────────────────┬───────────────────────────┘ │
|
|
||||||
│ │ │ │
|
|
||||||
│ ┌──▾──────────────────┐ ┌─▾──────────────────────────┐ │
|
|
||||||
│ │ Relay Loop │ │ Management API (REST) │ │
|
|
||||||
│ │ (per-stream TCP) │ │ /api/users, /api/stats │ │
|
|
||||||
│ │ ──▸ Internet │ │ Bearer token auth │ │
|
|
||||||
│ └─────────────────────┘ └────────────────────────────┘ │
|
|
||||||
│ │
|
|
||||||
│ ┌──────────────────────────────────────────────────────┐ │
|
|
||||||
│ │ Fallback TCP Proxy ──▸ nginx/caddy (anti-DPI) │ │
|
|
||||||
│ └──────────────────────────────────────────────────────┘ │
|
|
||||||
└─────────────────────────────────────────────────────────────┘
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
### 1. Generate config
|
### 1. Installation
|
||||||
|
|
||||||
|
**Linux:**
|
||||||
```bash
|
```bash
|
||||||
# On your VPS (server):
|
bash <(curl -Ls https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.sh)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Windows (PowerShell as Administrator):**
|
||||||
|
```powershell
|
||||||
|
irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | iex
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Configuration
|
||||||
|
|
||||||
|
Initialize the configuration files for the server and client:
|
||||||
|
```bash
|
||||||
|
# On the server:
|
||||||
./ostp --init server
|
./ostp --init server
|
||||||
|
|
||||||
# On your machine (client):
|
# On the client:
|
||||||
./ostp --init client
|
./ostp --init client
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Edit config
|
**Server Example** (`config.json`):
|
||||||
|
|
||||||
**Server** — set your access keys:
|
|
||||||
```jsonc
|
```jsonc
|
||||||
{
|
{
|
||||||
"mode": "server",
|
"mode": "server",
|
||||||
"listen": "0.0.0.0:50000",
|
"listen": "0.0.0.0:50000",
|
||||||
"access_keys": ["YOUR_SECRET_KEY"],
|
"access_keys": ["YOUR_SECRET_KEY"]
|
||||||
"api": { "enabled": true, "bind": "127.0.0.1:9090", "token": "admin-token" },
|
|
||||||
"fallback": { "enabled": false, "listen": "0.0.0.0:443", "target": "127.0.0.1:8080" }
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Client** — point to your server:
|
**Client Example** (`config.json`):
|
||||||
```jsonc
|
```jsonc
|
||||||
{
|
{
|
||||||
"mode": "client",
|
"mode": "client",
|
||||||
"server": "YOUR_SERVER_IP:50000",
|
"version": "0.3.1",
|
||||||
"access_key": "YOUR_SECRET_KEY",
|
"inbounds": [
|
||||||
"socks5_bind": "127.0.0.1:1088",
|
{ "type": "local_proxy", "tag": "socks-in", "protocol": "socks", "listen": "127.0.0.1", "port": 1088 }
|
||||||
"transport": { "mode": "udp", "stealth_sni": "vk.com", "stealth_port": 443 },
|
],
|
||||||
"tun": { "enable": false, "dns": "1.1.1.1" }
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"type": "ostp",
|
||||||
|
"tag": "proxy",
|
||||||
|
"server": "YOUR_SERVER_IP",
|
||||||
|
"port": 50000,
|
||||||
|
"access_key": "YOUR_SECRET_KEY",
|
||||||
|
"transport": { "type": "udp" }
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. Run
|
### 3. Execution
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./ostp # Uses config.json in current directory
|
# Run with default config.json
|
||||||
./ostp --config /path/to.json # Custom config path
|
./ostp
|
||||||
./ostp --check # Validate config without running
|
|
||||||
./ostp --generate-key # Generate a new access key
|
# Run with a specific config path
|
||||||
./ostp --links # Print client share links
|
./ostp --config /path/to/config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4. Connect via share link (one-liner)
|
Or connect via a one-line share link on the client:
|
||||||
```bash
|
```bash
|
||||||
./ostp ostp://ACCESS_KEY@server.com:50000
|
./ostp "ostp://YOUR_SECRET_KEY@YOUR_SERVER_IP:50000?transport=udp"
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Management API
|
## Protocol Specification
|
||||||
|
|
||||||
Built-in REST API for building panels and dashboards.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Server status
|
|
||||||
curl -H "Authorization: Bearer mytoken" http://127.0.0.1:9090/api/server/status
|
|
||||||
|
|
||||||
# List all users with traffic stats
|
|
||||||
curl -H "Authorization: Bearer mytoken" http://127.0.0.1:9090/api/users
|
|
||||||
|
|
||||||
# Create a user with 10GB traffic limit
|
|
||||||
curl -X POST -H "Authorization: Bearer mytoken" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d '{"limit_bytes": 10737418240}' \
|
|
||||||
http://127.0.0.1:9090/api/users
|
|
||||||
```
|
|
||||||
|
|
||||||
Full API reference: [Management API](https://github.com/ospab/ostp/wiki/Management-API)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## CLI Reference
|
|
||||||
|
|
||||||
```
|
|
||||||
ostp [OPTIONS] [URL]
|
|
||||||
|
|
||||||
Options:
|
|
||||||
--config <PATH> Config file path (default: config.json)
|
|
||||||
--init <MODE> Generate template config (server/client)
|
|
||||||
--check Validate configuration and exit
|
|
||||||
-g, --generate-key Generate a secure access key
|
|
||||||
-c, --count <N> Number of keys to generate (default: 1)
|
|
||||||
--format <FMT> Key format: hex, base64 (default: hex)
|
|
||||||
--links Print client share links from server config
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
[URL] Connect via share link: ostp://KEY@HOST:PORT
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Protocol Summary
|
|
||||||
|
|
||||||
| Layer | Mechanism |
|
| Layer | Mechanism |
|
||||||
|-------|-----------|
|
|-------|-----------|
|
||||||
| Key Exchange | Noise NNpsk0 (X25519 + ChaChaPoly + BLAKE2s) |
|
| Key Exchange | Noise NNpsk0 (X25519 + ChaChaPoly + BLAKE2s) zero-RTT |
|
||||||
| Encryption | ChaCha20-Poly1305 AEAD per-packet |
|
| Encryption | ChaCha20-Poly1305 AEAD per-packet |
|
||||||
| Header Obfuscation | HMAC-SHA256 derived per-packet mask |
|
| Header Masking | HMAC-SHA256 derived per-packet mask |
|
||||||
| Reliability | Selective ACK with cumulative + SACK ranges |
|
| Reliability | Selective ACK with cumulative + SACK ranges |
|
||||||
| Retransmission | Rate-limited NACK + exponential backoff RTO |
|
| Retransmission | Rate-limited NACK + exponential backoff RTO |
|
||||||
| Keepalive | Ping/Pong with RTT measurement every 5s |
|
| Keepalive | Ping/Pong with RTT measurement every 5s |
|
||||||
|
|
@ -202,31 +143,31 @@ Arguments:
|
||||||
## Building from Source
|
## Building from Source
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Prerequisites: Rust 1.75+
|
# Requires Rust 1.75+
|
||||||
cargo build --release
|
cargo build --release
|
||||||
|
|
||||||
# Cross-compile for Linux
|
# Cross-compile for Linux
|
||||||
cross build --release --target x86_64-unknown-linux-gnu
|
cross build --release --target x86_64-unknown-linux-gnu
|
||||||
|
|
||||||
# Run tests
|
|
||||||
cargo test -p ostp-core -p ostp-server
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
- **[Wiki](https://github.com/ospab/ostp/wiki)** — Full documentation
|
- **[Wiki](https://github.com/ospab/ostp/wiki)**
|
||||||
- [Installation](https://github.com/ospab/ostp/wiki/Installation)
|
|
||||||
- [Configuration Reference](https://github.com/ospab/ostp/wiki/Configuration)
|
- [Configuration Reference](https://github.com/ospab/ostp/wiki/Configuration)
|
||||||
- [Management API](https://github.com/ospab/ostp/wiki/Management-API)
|
- [Management API](https://github.com/ospab/ostp/wiki/Management-API)
|
||||||
- [Protocol Design](https://github.com/ospab/ostp/wiki/Protocol-Design)
|
- [Protocol Design](https://github.com/ospab/ostp/wiki/Protocol-Design)
|
||||||
- [Building from Source](https://github.com/ospab/ostp/wiki/Building-from-Source)
|
|
||||||
- [FAQ](https://github.com/ospab/ostp/wiki/FAQ)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Business Source License 1.1. Free for personal and non-commercial use.
|
GNU Affero General Public License v3.0 (AGPL-3.0). See [LICENSE](LICENSE) for more details.
|
||||||
Converts to MIT License on May 14, 2030.
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contacts
|
||||||
|
|
||||||
|
- **Telegram**: [@ospab0](https://t.me/ospab0)
|
||||||
|
- **Email**: gvoprgrg@gmail.com
|
||||||
|
|
|
||||||
207
README.ru.md
|
|
@ -1,161 +1,129 @@
|
||||||
# OSTP — Ospab Stealth Transport Protocol
|
# OSTP — Ospab Stealth Transport Protocol
|
||||||
|
|
||||||
[English](README.md)
|
[English](README.md) · [Wiki](https://github.com/ospab/ostp/wiki) · [Contributing](CONTRIBUTING.ru.md) · [Миграция v0.3.1](docs/migration_v0_3_1_ru.md)
|
||||||
|
|
||||||

|

|
||||||

|

|
||||||

|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
OSTP — высокопроизводительный транспортный протокол, устойчивый к цензуре. Туннелирует TCP-трафик поверх UDP с полной обфускацией. Устойчив к Deep Packet Inspection (DPI), активному зондированию и статистическому анализу трафика.
|
OSTP (Ospab Stealth Transport Protocol) — зашифрованный транспортный протокол, написанный на Rust. Реализует механизм ARQ поверх UDP, а также режим UoT (UDP-over-TCP). Протокол использует криптографическое маскирование заголовков и полезной нагрузки для защиты от систем глубокого анализа трафика (DPI).
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **Обновляетесь с версии v0.2.x?** Пожалуйста, ознакомьтесь с [Руководством по миграции конфигурации v0.3.1](docs/migration_v0_3_1_ru.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Возможности
|
## Технические характеристики
|
||||||
|
|
||||||
| Возможность | Описание |
|
| Возможность | Описание |
|
||||||
|-------------|----------|
|
|-------------|----------|
|
||||||
| **Обфускация трафика** | Каждый пакет, включая заголовки, неотличим от случайного шума. Session ID и nonce маскируются HMAC-ключами, уникальными для каждого пакета. |
|
| **Маскирование трафика** | Шифрование заголовков и полезной нагрузки с помощью HMAC ключей на каждый пакет. Трафик неотличим от шума. |
|
||||||
| **Noise Protocol** | `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` — аутентификация через PSK, forward secrecy, без раскрытия идентичности. |
|
| **Noise Protocol** | `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` — аутентификация через PSK, forward secrecy. |
|
||||||
| **Reliable UDP (ARQ)** | Selective ACK/NACK с rate-limited ретрансмиссией, настраиваемым reorder-буфером и exponential backoff. Разработан для 10 Гбит/с. |
|
| **Reliable UDP (ARQ)** | Selective ACK/NACK с rate-limited ретрансмиссией, настраиваемым reorder-буфером и exponential backoff. |
|
||||||
| **Мультиплексирование** | Несколько логических TCP-потоков поверх одной зашифрованной UDP-сессии с per-stream flow control. |
|
| **Мультиплексирование** | Несколько логических TCP-потоков поверх одной зашифрованной UDP-сессии с per-stream flow control. |
|
||||||
| **Бесшовный роуминг** | Клиент может менять сети (WiFi ↔ 4G) без разрыва сессии — сервер отслеживает session-ID, а не IP-адрес. |
|
| **Session Roaming** | Сохранение соединения при смене IP-адреса благодаря отслеживанию по идентификатору сессии (session ID). |
|
||||||
| **TUN-режим** | Полносистемный VPN через интеграцию с `tun2socks` на Windows и Linux. |
|
| **Режим UoT** | Инкапсуляция UDP внутри TCP с указанием длины пакетов для обхода блокировок неизвестного UDP-трафика. |
|
||||||
| **xHTTP Стелс (UoT)** | Туннель UDP-over-TCP, замаскированный под обычный HTTP/1.1 или TLS трафик для обхода белых списков ТСПУ (DPI). |
|
| **Fallback Server** | Проксирование неаутентифицированных TCP подключений на веб-сервер для защиты от активного пробинга. |
|
||||||
| **TURN Relay** | RFC 5766 TURN для окружений, где прямой UDP заблокирован. |
|
| **TUN-режим** | Полносистемная маршрутизация через встроенный сетевой стек `smoltcp` без внешних зависимостей. |
|
||||||
| **Hot-Reload** | Перезагрузка конфига в рантайме без перезапуска (ключи, исключения, mux, TURN). |
|
| **Management API** | Встроенный REST API для администрирования сервера, сбора метрик и генерации ключей. |
|
||||||
| **Кросс-платформа** | Windows, Linux, macOS, Android. Один бинарник, без зависимостей. |
|
| **TURN Relay** | Поддержка RFC 5766 TURN для обхода NAT. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Архитектура
|
## Архитектура
|
||||||
|
|
||||||
```
|
```mermaid
|
||||||
┌────────────────────────────────────────────────────────────┐
|
flowchart LR
|
||||||
│ Клиент │
|
Apps[Приложения] -->|SOCKS5 / TUN| CoreC
|
||||||
│ ┌──────────┐ ┌──────────┐ ┌───────────────────────┐ │
|
|
||||||
│ │ Браузер │──▸│ SOCKS5/ │──▸│ Bridge (Mux) │ │
|
subgraph Client [Клиент]
|
||||||
│ │ / Прил. │ │ HTTP │ │ ┌─────────────────┐ │ │
|
CoreC[OSTP Клиент] -.->|Шифрование| NetC[Транспортный уровень]
|
||||||
│ │ │ │ Прокси │ │ │ ProtocolMachine │ │ │
|
end
|
||||||
│ └──────────┘ └──────────┘ │ │ (Noise + AEAD) │ │ │
|
|
||||||
│ │ └────────┬────────┘ │ │
|
NetC <==>|Зашифрованный UDP / UoT| NetS
|
||||||
│ ┌──────────┐ │ │ │ │
|
|
||||||
│ │ TUN Mode │──────────────────┤ UDP-сокет │ │
|
subgraph Server [Сервер]
|
||||||
│ │tun2socks │ │ (32МБ буферы, │ │
|
NetS[Транспортный уровень] -.->|Дешифрование| CoreS[OSTP Сервер]
|
||||||
│ └──────────┘ │ обфускация) │ │
|
NetS -->|Неавторизованные| Fallback[Fallback Сервер]
|
||||||
│ └───────────┬────────────┘ │
|
end
|
||||||
└────────────────────────────────────────────┼────────────────┘
|
|
||||||
│ UDP
|
CoreS -->|Проксирование| WWW((Интернет))
|
||||||
┌────────────────────────────────────────────┼────────────────┐
|
Fallback -->|Перенаправление| Web((Веб-сервер / NGINX))
|
||||||
│ Сервер │ │
|
|
||||||
│ ┌─────────────────────────────────────────┴──────────┐ │
|
|
||||||
│ │ Dispatcher │ │
|
|
||||||
│ │ (Поиск сессий, роуминг, защита от replay) │ │
|
|
||||||
│ └──────────────┬──────────────────────────────────────┘ │
|
|
||||||
│ │ │
|
|
||||||
│ ┌──────────────▾──────────────────┐ │
|
|
||||||
│ │ Relay Loop (TCP per-stream) │──▸ Интернет / Backend │
|
|
||||||
│ └─────────────────────────────────┘ │
|
|
||||||
└──────────────────────────────────────────────────────────────┘
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Установка
|
## Быстрый старт
|
||||||
|
|
||||||
### Linux
|
### 1. Установка
|
||||||
|
|
||||||
|
**Linux:**
|
||||||
```bash
|
```bash
|
||||||
bash <(curl -Ls https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.sh)
|
bash <(curl -Ls https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.sh)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Windows (PowerShell от Администратора)
|
**Windows (PowerShell от Администратора):**
|
||||||
```powershell
|
```powershell
|
||||||
irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | iex
|
irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | iex
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
### 2. Конфигурация
|
||||||
|
|
||||||
## Конфигурация
|
Сгенерируйте базовые файлы конфигурации:
|
||||||
|
|
||||||
Создать конфиг по умолчанию:
|
|
||||||
```bash
|
```bash
|
||||||
./ostp --init server # VPS
|
# На сервере:
|
||||||
./ostp --init client # Локальная машина
|
./ostp --init server
|
||||||
|
|
||||||
|
# На клиенте:
|
||||||
|
./ostp --init client
|
||||||
```
|
```
|
||||||
|
|
||||||
### Сервер (`config.json`)
|
**Пример конфигурации сервера** (`config.json`):
|
||||||
```jsonc
|
```jsonc
|
||||||
{
|
{
|
||||||
"mode": "server",
|
"mode": "server",
|
||||||
"listen": "0.0.0.0:50000",
|
"listen": "0.0.0.0:50000",
|
||||||
"access_keys": ["ВАШ_КЛЮЧ"],
|
"access_keys": ["ВАШ_КЛЮЧ"]
|
||||||
"debug": false,
|
|
||||||
// Опционально: проксировать трафик через upstream
|
|
||||||
"outbound": {
|
|
||||||
"enabled": false,
|
|
||||||
"protocol": "socks5",
|
|
||||||
"address": "127.0.0.1",
|
|
||||||
"port": 9050,
|
|
||||||
"default_action": "proxy"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Клиент (`config.json`)
|
**Пример конфигурации клиента** (`config.json`):
|
||||||
```jsonc
|
```jsonc
|
||||||
{
|
{
|
||||||
"mode": "client",
|
"mode": "client",
|
||||||
"server": "IP_СЕРВЕРА:50000",
|
"version": "0.3.1",
|
||||||
"access_key": "ВАШ_КЛЮЧ",
|
"inbounds": [
|
||||||
"socks5_bind": "127.0.0.1:1088",
|
{ "type": "local_proxy", "tag": "socks-in", "protocol": "socks", "listen": "127.0.0.1", "port": 1088 }
|
||||||
"debug": false,
|
],
|
||||||
// Настройки транспорта (udp или uot)
|
"outbounds": [
|
||||||
"transport": {
|
{
|
||||||
"mode": "udp",
|
"type": "ostp",
|
||||||
"stealth_sni": "vk.com",
|
"tag": "proxy",
|
||||||
"stealth_port": 443
|
"server": "IP_СЕРВЕРА",
|
||||||
},
|
"port": 50000,
|
||||||
// TUN-режим (полносистемный VPN)
|
"access_key": "ВАШ_КЛЮЧ",
|
||||||
"tun": {
|
"transport": { "type": "udp" }
|
||||||
"enable": false,
|
}
|
||||||
"dns": "1.1.1.1"
|
]
|
||||||
},
|
|
||||||
// Мультиплексирование: несколько UDP-сессий
|
|
||||||
"mux": {
|
|
||||||
"enabled": false,
|
|
||||||
"sessions": 2
|
|
||||||
},
|
|
||||||
// TURN-реле для заблокированных сетей
|
|
||||||
"turn": {
|
|
||||||
"enabled": false,
|
|
||||||
"server_addr": "turn.example.com:3478",
|
|
||||||
"username": "user",
|
|
||||||
"access_key": "pass"
|
|
||||||
},
|
|
||||||
// Исключения (идут напрямую, минуя туннель)
|
|
||||||
"exclude": {
|
|
||||||
"domains": ["example.local"],
|
|
||||||
"ips": ["192.168.0.0/16"]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
### 3. Запуск
|
||||||
|
|
||||||
## Использование
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Запуск с конфигом
|
# Запуск с конфигурацией по умолчанию (config.json)
|
||||||
./ostp --config config.json
|
|
||||||
|
|
||||||
# Или просто (ищет config.json рядом с бинарником)
|
|
||||||
./ostp
|
./ostp
|
||||||
|
|
||||||
|
# Запуск с указанием пути к конфигурации
|
||||||
|
./ostp --config /path/to/config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
### TUN-режим (Windows)
|
Либо подключение через однострочную ссылку на стороне клиента:
|
||||||
Требуется `tun2socks.exe` в той же директории. Автоматически запрашивает права Администратора.
|
```bash
|
||||||
|
./ostp "ostp://ВАШ_КЛЮЧ@IP_СЕРВЕРА:50000?transport=udp"
|
||||||
### TUN-режим (Linux)
|
```
|
||||||
Требуется root. Нужен бинарник `tun2socks` (рядом или в `$PATH`).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -163,21 +131,19 @@ irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | ie
|
||||||
|
|
||||||
| Уровень | Механизм |
|
| Уровень | Механизм |
|
||||||
|---------|----------|
|
|---------|----------|
|
||||||
| Обмен ключами | Noise NNpsk0 (X25519 + ChaChaPoly + BLAKE2s) |
|
| Обмен ключами | Noise NNpsk0 (X25519 + ChaChaPoly + BLAKE2s) zero-RTT |
|
||||||
| Шифрование | ChaCha20-Poly1305 AEAD на каждый пакет |
|
| Шифрование | ChaCha20-Poly1305 AEAD на каждый пакет |
|
||||||
| Обфускация заголовков | HMAC-SHA256 маска session_id + nonce, уникальная для каждого пакета |
|
| Обфускация заголовков | HMAC-SHA256 маска на основе session_id и nonce |
|
||||||
| Надёжность | Selective ACK с cumulative + SACK диапазонами |
|
| Надёжность | Selective ACK с cumulative + SACK диапазонами |
|
||||||
| Ретрансмиссия | Rate-limited NACK (30мс cooldown) + exponential backoff RTO |
|
| Ретрансмиссия | Rate-limited NACK + exponential backoff RTO |
|
||||||
| Flow Control | Окно in-flight (только retransmittable фреймы) |
|
|
||||||
| Keepalive | Ping/Pong с измерением RTT каждые 5с |
|
| Keepalive | Ping/Pong с измерением RTT каждые 5с |
|
||||||
| Таймаут сессии | 60с на клиенте, 300с на сервере |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Сборка из исходников
|
## Сборка из исходников
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Требования: Rust toolchain (1.75+)
|
# Требования: Rust 1.75+
|
||||||
cargo build --release
|
cargo build --release
|
||||||
|
|
||||||
# Кросс-компиляция для Linux
|
# Кросс-компиляция для Linux
|
||||||
|
|
@ -188,16 +154,21 @@ cross build --release --target x86_64-unknown-linux-gnu
|
||||||
|
|
||||||
## Документация
|
## Документация
|
||||||
|
|
||||||
- [Архитектура](docs/ru/architecture.md)
|
- **[Wiki](https://github.com/ospab/ostp/wiki)**
|
||||||
- [Спецификация протокола](docs/ru/specification.md)
|
- [Спецификация протокола](docs/ru/specification.md)
|
||||||
- [Дизайн обфускации](docs/ru/obfuscation.md)
|
- [Дизайн обфускации](docs/ru/obfuscation.md)
|
||||||
- [Администрирование сервера](docs/ru/server.md)
|
- [Архитектура](docs/ru/architecture.md)
|
||||||
- [Настройка клиента](docs/ru/client.md)
|
- [Настройка клиента](docs/ru/client.md)
|
||||||
- [Интеграции](docs/ru/integrations.md)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Лицензия
|
## Лицензия
|
||||||
|
|
||||||
Business Source License 1.1. Бесплатно для личного и некоммерческого использования.
|
GNU Affero General Public License v3.0 (AGPL-3.0). Подробнее см. в файле [LICENSE](LICENSE).
|
||||||
Переходит в MIT License 14 мая 2030 года.
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Контакты
|
||||||
|
|
||||||
|
- **Telegram**: [@ospab0](https://t.me/ospab0)
|
||||||
|
- **Email**: gvoprgrg@gmail.com
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="g2" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#111827" />
|
||||||
|
<stop offset="100%" stop-color="#374151" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="g2_path" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#3B82F6" />
|
||||||
|
<stop offset="100%" stop-color="#14B8A6" />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<rect width="512" height="512" rx="120" fill="url(#g2)" />
|
||||||
|
<path d="M144 256c0-61.9 50.1-112 112-112s112 50.1 112 112-50.1 112-112 112S144 317.9 144 256zm-48 0c0 88.4 71.6 160 160 160s160-71.6 160-160S344.4 96 256 96 96 167.6 96 256z" fill="url(#g2_path)"/>
|
||||||
|
<circle cx="256" cy="256" r="40" fill="#F59E0B" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 779 B |
|
|
@ -0,0 +1 @@
|
||||||
|
Subproject commit 0c5c52a57d899c05428c116898941761a2ed83c2
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
|
||||||
|
____ _____ _______ _____
|
||||||
|
/ __ \ / ____|__ __| __ \
|
||||||
|
| | | | (___ | | | |__) |
|
||||||
|
| | | |\___ \ | | | ___/
|
||||||
|
| |__| |____) | | | | |
|
||||||
|
\____/|_____/ |_| |_|
|
||||||
|
|
@ -5,10 +5,20 @@ The Obfuscated Secure Transport Protocol (OSTP) is a high-performance, asynchron
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Kerckhoffs's Principle and DPI Resilience
|
||||||
|
|
||||||
|
The OSTP architecture strictly adheres to **Kerckhoffs's Principle**: a cryptosystem should be secure even if everything about the system, except the key, is public knowledge.
|
||||||
|
All encryption and obfuscation algorithms are fully open source. The security and indistinguishability of the traffic rely entirely on the secrecy of the pre-shared key (`access_key` / PSK).
|
||||||
|
|
||||||
|
Through cryptographic transformations using this key (Noise Protocol + ChaCha20Poly1305 + Blake2s) and adaptive padding, every transmitted packet is visually indistinguishable from completely random white noise.
|
||||||
|
The protocol lacks any static headers or plaintext handshakes. This makes it impossible for Deep Packet Inspection (DPI) systems, such as state censors, to create a static filter or signature to block OSTP within minutes. Blocking the protocol would require either blocking all unknown UDP traffic globally (which breaks many legitimate services) or possessing the secret key.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Workspace Structure
|
## Workspace Structure
|
||||||
The project is modularized into the following crates:
|
The project is modularized into the following crates:
|
||||||
1. **ostp-core**: The core engine. Contains protocol state machines, Noise Protocol Framework handshakes, data framing serialization, dynamic obfuscation algorithms, and reliable packet delivery (ARQ).
|
1. **ostp-core**: The core engine. Contains protocol state machines, Noise Protocol Framework handshakes, data framing serialization, dynamic obfuscation algorithms, and reliable packet delivery (ARQ).
|
||||||
2. **ostp-client**: The client daemon. Manages local traffic interception via dual-mode SOCKS5/HTTP proxies or virtualized network adapters (TUN/Wintun), multiplexing active host streams into a single UDP tunnel, and interfacing with TURN servers.
|
2. **ostp-client**: The client daemon. Manages routing configuration via arrays of `inbounds` (e.g., SOCKS5, TUN) and `outbounds` (e.g., OSTP, direct, block), handling multiplexing of streams and interacting with TURN servers.
|
||||||
3. **ostp-server**: The high-concurrency connection dispatcher, responsible for demultiplexing data from multiple sessions, handling seamless IP roaming, and forwarding traffic to the broader internet.
|
3. **ostp-server**: The high-concurrency connection dispatcher, responsible for demultiplexing data from multiple sessions, handling seamless IP roaming, and forwarding traffic to the broader internet.
|
||||||
4. **ostp-obfuscator**: Utility crate for static traffic shaping and dynamic obfuscation key derivation tools.
|
4. **ostp-obfuscator**: Utility crate for static traffic shaping and dynamic obfuscation key derivation tools.
|
||||||
5. **ostp-jni**: Android JNI bindings that allow embedding OSTP inside mobile applications via an isolated runtime.
|
5. **ostp-jni**: Android JNI bindings that allow embedding OSTP inside mobile applications via an isolated runtime.
|
||||||
|
|
|
||||||
|
|
@ -46,16 +46,29 @@ The client is engineered to maintain persistence without requiring user interven
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Routing Exclusions (Bypass Mode)
|
## Modular Routing Architecture (Inbounds / Outbounds)
|
||||||
|
|
||||||
To minimize latency and overhead for trusted resources, the OSTP client incorporates an integrated direct-routing bypass engine. This is configured inside the `"exclude"` block of the `config.json` file:
|
Starting from version `0.3.1`, the OSTP client utilizes a modular configuration architecture based on inbound and outbound arrays, similar to Xray or Sing-box.
|
||||||
|
|
||||||
- **`domains`**: A list of domain suffixes (e.g., `["trusted-site.com", "local.lan"]`). Traffic bound for these domains is instantly channeled via the default local gateway, bypassing encryption entirely.
|
- **`inbounds`**: Defines how local traffic enters the client. Supported types include `tun` (virtual network interface) and `local_proxy` (SOCKS5/HTTP proxy).
|
||||||
- **`ips`**: A list of target subnet destinations in CIDR format (e.g., `["192.168.1.0/24", "10.0.0.0/8"]`), ensuring local area networks maintain full wire-speed throughput.
|
- **`outbounds`**: Defines where the client sends the traffic. The main type is `ostp` (encapsulation and transmission to the server), but it also supports `direct` (bypassing the VPN to connect directly to the internet) and `block` (dropping traffic).
|
||||||
- **`processes`**: A list of OS executable filenames (e.g., `["discord.exe", "steam.exe"]`). Applications specified here will automatically evade the VPN's virtual network driver.
|
- **`routing`**: The mechanism replacing the legacy `exclude` block. It allows for flexible traffic routing based on advanced rules.
|
||||||
|
|
||||||
|
Routing rule example in `config.json`:
|
||||||
|
```json
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": ["trusted-site.com", "local.lan"],
|
||||||
|
"outbound": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default_outbound": "proxy"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> The exclusion/bypass logic is fully operational, rigorously optimized, and ready for immediate production deployment.
|
> This architecture enables the client to connect to multiple OSTP servers simultaneously, split traffic by domain, or block telemetry directly at the VPN routing level.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
# Frequently Asked Questions (FAQ)
|
||||||
|
|
||||||
|
## What is OSTP and how does it differ from other VPNs (WireGuard, OpenVPN)?
|
||||||
|
OSTP is a protocol built from the ground up for maximum Deep Packet Inspection (DPI) evasion. Unlike WireGuard and OpenVPN, which have recognizable handshakes and static headers, OSTP obfuscates 100% of the data starting from the very first byte. Every packet is indistinguishable from random white noise, making static filtering impossible.
|
||||||
|
|
||||||
|
## How does DPI evasion work? Is it secure?
|
||||||
|
OSTP architecture strictly adheres to **Kerckhoffs's Principle**. The code is fully open source and does not rely on security by obscurity. The obfuscation is backed by rigorous cryptographic algorithms (Noise Protocol, ChaCha20Poly1305, Blake2s) and pre-shared keys. Censors and DPI systems cannot write a signature or filter for OSTP because there are simply no repetitive patterns in the traffic.
|
||||||
|
|
||||||
|
## How do I upgrade to version 0.3.1 and what happens to `config.json`?
|
||||||
|
Version 0.3.1 introduced a new modular architecture (`inbounds` and `outbounds` arrays). When you run OSTP v0.3.1+ with an older configuration file, the built-in auto-migrator automatically converts it to the new format without data loss and appends `"version": "0.3.1"`.
|
||||||
|
|
||||||
|
## Why is multiplexing not working for me (sessions > 1)?
|
||||||
|
There is a known issue within the `mux` demultiplexer when handling multiple sessions concurrently. The handshake succeeds, but application data fails to stream. Please keep the session count to 1 or disable `mux` entirely until a patch is released in future `ostp-core` versions.
|
||||||
|
|
||||||
|
## Is there proprietary or closed-source code in OSTP?
|
||||||
|
The core protocol engine and base client/server implementations are completely open source and available for peer review in this repository. However, certain experimental or enterprise-specific tooling (`ostp-brain`, `ostp-prober`, `ostp-sandbox`, and parts of `ostp-gui`) are excluded from the public workspace to keep the open-source codebase focused.
|
||||||
|
|
@ -0,0 +1,108 @@
|
||||||
|
# OSTP Configuration Migration to v0.3.1
|
||||||
|
|
||||||
|
The OSTP `config.json` schema has been significantly redesigned in version `v0.3.1` to support a modern multi-server architecture. The new schema provides greater flexibility by splitting configuration into `inbounds`, `outbounds`, and flexible `routing` rules, replacing the monolithic architecture of previous versions.
|
||||||
|
|
||||||
|
## Automatic Migration
|
||||||
|
|
||||||
|
The OSTP core and GUI clients are equipped with an automatic migrator. When launching OSTP `v0.3.1` with a `config.json` from a previous version, the migrator will automatically transform the legacy schema into the new `v0.3.1` schema.
|
||||||
|
|
||||||
|
The migrated file will be overwritten with the new format and will begin with:
|
||||||
|
```json
|
||||||
|
// OSTP Configuration v0.3.1
|
||||||
|
// DO NOT EDIT THIS COMMENT - Migrator relies on it
|
||||||
|
{
|
||||||
|
"version": "0.3.1",
|
||||||
|
"mode": "client",
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Manual Schema Reference
|
||||||
|
|
||||||
|
If you prefer to configure manually, the following is a reference of the new modular configuration format:
|
||||||
|
|
||||||
|
### Legacy Configuration (v0.2.x)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "client",
|
||||||
|
"server": "192.168.1.100:50000",
|
||||||
|
"access_key": "mysecretkey",
|
||||||
|
"socks5_bind": "127.0.0.1:1088",
|
||||||
|
"tun": {
|
||||||
|
"enable": true,
|
||||||
|
"kill_switch": true
|
||||||
|
},
|
||||||
|
"exclude": {
|
||||||
|
"domains": ["localhost"],
|
||||||
|
"ips": ["192.168.1.0/24"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### New Configuration (v0.3.1)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": "0.3.1",
|
||||||
|
"mode": "client",
|
||||||
|
"api": {
|
||||||
|
"enabled": true,
|
||||||
|
"bind": "127.0.0.1:50001",
|
||||||
|
"token": "admin-secret-token"
|
||||||
|
},
|
||||||
|
"log": {
|
||||||
|
"level": "info"
|
||||||
|
},
|
||||||
|
"inbounds": [
|
||||||
|
{
|
||||||
|
"type": "tun",
|
||||||
|
"tag": "tun-in",
|
||||||
|
"auto_route": true,
|
||||||
|
"mtu": 1140
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "socks",
|
||||||
|
"tag": "socks-in",
|
||||||
|
"bind_addr": "127.0.0.1:1088"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"type": "ostp",
|
||||||
|
"tag": "proxy",
|
||||||
|
"server": "192.168.1.100",
|
||||||
|
"port": 50000,
|
||||||
|
"access_key": "mysecretkey",
|
||||||
|
"transport": {
|
||||||
|
"type": "udp"
|
||||||
|
},
|
||||||
|
"multiplex": {
|
||||||
|
"enabled": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "direct",
|
||||||
|
"tag": "direct"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "block",
|
||||||
|
"tag": "block"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": ["localhost"],
|
||||||
|
"ip_cidr": ["192.168.1.0/24"],
|
||||||
|
"outbound": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default_outbound": "proxy"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key Changes
|
||||||
|
- **Outbounds List**: Multiple proxy servers can now be defined.
|
||||||
|
- **Inbounds List**: TUN and SOCKS5 are now independent listeners.
|
||||||
|
- **Routing**: Fine-grained traffic routing between inbounds and outbounds based on domains, IPs, and processes.
|
||||||
|
- **Comments**: The GUI and migrator now use JS-style `//` comments in `config.json` instead of the legacy `"_comment"` JSON keys.
|
||||||
|
|
@ -49,3 +49,13 @@ The `AdaptivePadder` calculates dynamic dummy byte quantities to append to the p
|
||||||
|
|
||||||
- **Dynamic Distributions**: The padding algorithms emulate length profiles commonly seen in whitelisted HTTPS or real-time video streams.
|
- **Dynamic Distributions**: The padding algorithms emulate length profiles commonly seen in whitelisted HTTPS or real-time video streams.
|
||||||
- **Encrypted Overheads**: The appended padding resides within the AEAD cipher scope. Consequently, passive observers cannot distinguish padding bytes from useful application payload, hiding the true message boundary lengths.
|
- **Encrypted Overheads**: The appended padding resides within the AEAD cipher scope. Consequently, passive observers cannot distinguish padding bytes from useful application payload, hiding the true message boundary lengths.
|
||||||
|
|
||||||
|
## XTLS-Reality Impersonation
|
||||||
|
|
||||||
|
OSTP provides a custom, dependency-free implementation of the XTLS-Reality protocol. It fully simulates a TLS 1.3 handshake (with realistic ClientHello profiles) to bypass advanced DPI filters. Post-handshake, it utilizes ChaCha20Poly1305 to seamlessly encrypt and tunnel the inner HTTP/WSS connections.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Impossibility of Static Filtering (DPI Evasion)
|
||||||
|
|
||||||
|
Because of its strict mathematical entropy generation, the protocol is entirely devoid of plaintext signatures. This ensures that filtering systems (such as state censors like RKN or the Great Firewall) **physically cannot** write an effective blocking rule by analyzing packet contents. Any attempt to write a filter would inevitably result in blocking legitimate, randomized UDP traffic (like WebRTC or gaming traffic). Security is backed by Kerckhoffs's Principle — knowing the algorithms is useless for classifying traffic without possessing the `access_key`.
|
||||||
|
|
@ -0,0 +1,102 @@
|
||||||
|
# OSTP v0.3.1 Configuration Migration
|
||||||
|
|
||||||
|
In OSTP version 0.3.1, we have completely overhauled the `config.json` architecture for the client. The old monolithic structure (where all settings were in the root object) has been replaced by a modular system based on arrays of `inbounds` (incoming connections) and `outbounds` (outgoing connections), similar to Xray/V2Ray/Sing-box.
|
||||||
|
|
||||||
|
This allows OSTP to scale, support multiple proxy servers, multiple entry points (SOCKS5, TUN), and complex routing (`routing`).
|
||||||
|
|
||||||
|
## Automatic Migration
|
||||||
|
|
||||||
|
The `ostp` core includes a built-in automatic migrator. Upon starting any program (cli, gui, flutter), the core will check your `config.json`.
|
||||||
|
|
||||||
|
If the configuration lacks the `"version": "0.3.1"` field, OSTP will **automatically** convert your old config into the new modular format and save it to disk without data loss.
|
||||||
|
|
||||||
|
### What happens during migration:
|
||||||
|
|
||||||
|
1. **TUN and SOCKS5** -> converted into the `inbounds` array.
|
||||||
|
- The `socks5_bind` setting becomes an inbound `local_proxy` (SOCKS).
|
||||||
|
- The `tun` setting becomes an inbound `tun`.
|
||||||
|
2. **OSTP Server** -> moved into the `outbounds` array.
|
||||||
|
- Parameters `server`, `access_key`, `transport`, `mux` are combined into an outbound of type `"ostp"`.
|
||||||
|
3. **Split Tunneling (Exclude)** -> converted into `routing` rules.
|
||||||
|
- Old `domains` and `ips` are converted into rules routing traffic to the `"direct"` outbound.
|
||||||
|
- All other requests are routed by default to the `"proxy"` outbound.
|
||||||
|
4. **`version` fields**
|
||||||
|
- The field `"version": "0.3.1"` is added to prevent re-migration in the future. The `_comment` field has been removed.
|
||||||
|
|
||||||
|
## Change Example
|
||||||
|
|
||||||
|
### Before 0.3.1 (Old format)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "client",
|
||||||
|
"log_level": "info",
|
||||||
|
"server": "1.2.3.4:50000",
|
||||||
|
"access_key": "secret",
|
||||||
|
"socks5_bind": "127.0.0.1:1088",
|
||||||
|
"tun": {
|
||||||
|
"enable": true
|
||||||
|
},
|
||||||
|
"exclude": {
|
||||||
|
"domains": ["localhost"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### After 0.3.1 (New format)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "client",
|
||||||
|
"version": "0.3.1",
|
||||||
|
"log": {
|
||||||
|
"level": "info"
|
||||||
|
},
|
||||||
|
"inbounds": [
|
||||||
|
{
|
||||||
|
"type": "tun",
|
||||||
|
"tag": "tun-in",
|
||||||
|
"auto_route": true,
|
||||||
|
"mtu": 1140
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "local_proxy",
|
||||||
|
"tag": "socks-in",
|
||||||
|
"protocol": "socks",
|
||||||
|
"listen": "127.0.0.1",
|
||||||
|
"port": 1088
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"type": "ostp",
|
||||||
|
"tag": "proxy",
|
||||||
|
"server": "1.2.3.4",
|
||||||
|
"port": 50000,
|
||||||
|
"access_key": "secret",
|
||||||
|
"transport": {
|
||||||
|
"type": "udp"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "direct",
|
||||||
|
"tag": "direct"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "block",
|
||||||
|
"tag": "block"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": ["localhost"],
|
||||||
|
"outbound": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default_outbound": "proxy"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Information for GUI Developers (ostp-gui, ostp-flutter)
|
||||||
|
|
||||||
|
If you are developing integrations or third-party clients, **you no longer need to parse the old fields**. You should use the `inbounds` and `outbounds` arrays. If the GUI passes a `serde_json::Value` to the core, the core will migrate it itself before starting. However, to save changes from the UI, you must modify the new array structure explicitly.
|
||||||
|
|
@ -0,0 +1,102 @@
|
||||||
|
# Миграция конфигурации OSTP v0.3.1
|
||||||
|
|
||||||
|
В версии OSTP 0.3.1 мы полностью переработали архитектуру конфигурации `config.json` для клиента. Старая монолитная структура (где все настройки были в корневом объекте) заменена на модульную систему на базе массивов `inbounds` (входящие соединения) и `outbounds` (исходящие соединения), аналогично Xray/V2Ray/Sing-box.
|
||||||
|
|
||||||
|
Это позволяет OSTP масштабироваться, поддерживать несколько прокси-серверов, несколько точек входа (SOCKS5, TUN) и сложную маршрутизацию (`routing`).
|
||||||
|
|
||||||
|
## Автоматическая миграция
|
||||||
|
|
||||||
|
В ядро `ostp` встроен автоматический мигратор. При запуске любой программы (cli, gui, flutter) ядро проверит ваш `config.json`.
|
||||||
|
|
||||||
|
Если в конфигурации отсутствует поле `"version": "0.3.1"`, OSTP **автоматически** конвертирует ваш старый конфиг в новый модульный формат и сохранит его на диск без потери данных.
|
||||||
|
|
||||||
|
### Что происходит при миграции:
|
||||||
|
|
||||||
|
1. **TUN и SOCKS5** -> преобразуются в массив `inbounds`.
|
||||||
|
- Настройка `socks5_bind` становится входящим `local_proxy` (SOCKS).
|
||||||
|
- Настройка `tun` становится входящим `tun`.
|
||||||
|
2. **Сервер OSTP** -> переносится в массив `outbounds`.
|
||||||
|
- Параметры `server`, `access_key`, `transport`, `mux` объединяются в `outbound` с типом `"ostp"`.
|
||||||
|
3. **Split Tunneling (Exclude)** -> преобразуется в `routing` правила.
|
||||||
|
- Старые `domains` и `ips` конвертируются в правила, направляющие трафик в `"direct"` outbound.
|
||||||
|
- Все остальные запросы по умолчанию направляются в `"proxy"` outbound.
|
||||||
|
4. **Поля `version`**
|
||||||
|
- Добавляется поле `"version": "0.3.1"`, чтобы предотвратить повторную миграцию в будущем. Поле `_comment` было удалено.
|
||||||
|
|
||||||
|
## Пример изменения
|
||||||
|
|
||||||
|
### До 0.3.1 (Старый формат)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "client",
|
||||||
|
"log_level": "info",
|
||||||
|
"server": "1.2.3.4:50000",
|
||||||
|
"access_key": "secret",
|
||||||
|
"socks5_bind": "127.0.0.1:1088",
|
||||||
|
"tun": {
|
||||||
|
"enable": true
|
||||||
|
},
|
||||||
|
"exclude": {
|
||||||
|
"domains": ["localhost"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### После 0.3.1 (Новый формат)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "client",
|
||||||
|
"version": "0.3.1",
|
||||||
|
"log": {
|
||||||
|
"level": "info"
|
||||||
|
},
|
||||||
|
"inbounds": [
|
||||||
|
{
|
||||||
|
"type": "tun",
|
||||||
|
"tag": "tun-in",
|
||||||
|
"auto_route": true,
|
||||||
|
"mtu": 1140
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "local_proxy",
|
||||||
|
"tag": "socks-in",
|
||||||
|
"protocol": "socks",
|
||||||
|
"listen": "127.0.0.1",
|
||||||
|
"port": 1088
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"type": "ostp",
|
||||||
|
"tag": "proxy",
|
||||||
|
"server": "1.2.3.4",
|
||||||
|
"port": 50000,
|
||||||
|
"access_key": "secret",
|
||||||
|
"transport": {
|
||||||
|
"type": "udp"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "direct",
|
||||||
|
"tag": "direct"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "block",
|
||||||
|
"tag": "block"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": ["localhost"],
|
||||||
|
"outbound": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default_outbound": "proxy"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Информация для разработчиков GUI (ostp-gui, ostp-flutter)
|
||||||
|
|
||||||
|
Если вы разрабатываете интеграции или сторонние клиенты, **вам больше не нужно парсить старые поля**. Вы должны использовать массивы `inbounds` и `outbounds`. Если GUI передает `serde_json::Value` в ядро, ядро само проведет миграцию перед запуском. Однако для сохранения изменений из UI вы должны изменять именно новую структуру массивов.
|
||||||
|
|
@ -5,10 +5,20 @@ Obfuscated Secure Transport Protocol (OSTP) — это высокопроизв
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Принцип Керкгоффса и устойчивость к DPI (Kerckhoffs's Principle)
|
||||||
|
|
||||||
|
Архитектура OSTP строго следует **Принципу Керкгоффса**: система должна оставаться безопасной, даже если все о ней, кроме ключа, является общедоступным знанием.
|
||||||
|
Весь исходный код алгоритмов шифрования и обфускации полностью открыт. Безопасность и нераспознаваемость трафика базируются исключительно на секретности предварительно согласованного ключа (`access_key` / PSK).
|
||||||
|
|
||||||
|
Благодаря криптографическим преобразованиям с использованием этого ключа (Noise Protocol + ChaCha20Poly1305 + Blake2s) и адаптивному паддингу, каждый пакет передаваемых данных визуально неотличим от абсолютно случайного белого шума.
|
||||||
|
Протокол не имеет статических заголовков или "рукопожатий" в открытом виде. Это делает невозможным для систем глубокого анализа трафика (DPI), таких как ТСПУ Роскомнадзора, создать статический фильтр или сигнатуру для блокировки OSTP за считанные минуты. Блокировка протокола потребовала бы либо полной блокировки всего неизвестного UDP-трафика (что нарушает работу многих легитимных сервисов), либо знания секретного ключа.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Структура проекта
|
## Структура проекта
|
||||||
Проект состоит из следующих специализированных модулей (crates):
|
Проект состоит из следующих специализированных модулей (crates):
|
||||||
1. **ostp-core**: Основа протокола. Содержит конечные автоматы состояний, реализацию рукопожатия (Noise Protocol Framework), механизмы сериализации кадров (framing), алгоритмы обфускации и логику надежной доставки пакетов (ARQ).
|
1. **ostp-core**: Основа протокола. Содержит конечные автоматы состояний, реализацию рукопожатия (Noise Protocol Framework), механизмы сериализации кадров (framing), алгоритмы обфускации и логику надежной доставки пакетов (ARQ).
|
||||||
2. **ostp-client**: Клиентский демон, управляющий перехватом трафика хоста через двухрежимный SOCKS5/HTTP-прокси или виртуальные адаптеры (TUN/Wintun), мультиплексированием потоков в единый UDP-туннель и взаимодействием с TURN для обхода NAT.
|
2. **ostp-client**: Клиентский демон. Управляет конфигурацией маршрутизации через массивы входящих (`inbounds`, например, SOCKS5, TUN) и исходящих (`outbounds`, например, OSTP, direct) соединений. Выполняет мультиплексирование потоков и взаимодействие с TURN для обхода NAT.
|
||||||
3. **ostp-server**: Высоконагруженный диспетчер соединений, отвечающий за демультиплексирование данных от множества сессий, прозрачный роуминг адресов и проксирование трафика в интернет.
|
3. **ostp-server**: Высоконагруженный диспетчер соединений, отвечающий за демультиплексирование данных от множества сессий, прозрачный роуминг адресов и проксирование трафика в интернет.
|
||||||
4. **ostp-obfuscator**: Утилиты для статического шейпинга трафика и генерации динамических ключей маскировки.
|
4. **ostp-obfuscator**: Утилиты для статического шейпинга трафика и генерации динамических ключей маскировки.
|
||||||
5. **ostp-jni**: Нативный SDK для интеграции в мобильные платформы Android.
|
5. **ostp-jni**: Нативный SDK для интеграции в мобильные платформы Android.
|
||||||
|
|
|
||||||
|
|
@ -46,16 +46,29 @@
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Маршрутизация исключений (Bypass / Exclusions)
|
## Модульная архитектура маршрутизации (Inbounds / Outbounds)
|
||||||
|
|
||||||
Для снижения задержек и оптимизации трафика клиент OSTP поддерживает механизм прямых подключений в обход туннеля. Настройка производится в блоке `"exclude"` конфигурационного файла `config.json`:
|
Начиная с версии `0.3.1`, клиент OSTP использует модульную архитектуру конфигурации на базе массивов точек входа и выхода, аналогичную Xray или Sing-box.
|
||||||
|
|
||||||
- **`domains`**: Список доменных имен (например, `["trusted-site.com", "yandex.ru"]`). Любой запрос к этим доменам или их поддоменам направляется напрямую через системный шлюз провайдера.
|
- **`inbounds` (Входящие точки)**: Определяет, как локальный трафик попадает в клиент. Поддерживаются типы `tun` (создание виртуального интерфейса) и `local_proxy` (SOCKS5/HTTP прокси).
|
||||||
- **`ips`**: Список диапазонов IP-адресов в формате CIDR (например, `["192.168.1.0/24", "10.0.0.0/8"]`). Полезно для доступа к ресурсам локальной сети.
|
- **`outbounds` (Исходящие точки)**: Определяет, куда клиент отправляет трафик. Основной тип — `ostp` (инкапсуляция и отправка на сервер), но также поддерживаются `direct` (прямое подключение к интернету в обход VPN) и `block` (блокировка трафика).
|
||||||
- **`processes`**: Список имен исполняемых файлов процессов ОС (например, `["discord.exe", "steam.exe"]`), чьи сетевые запросы должны игнорировать VPN.
|
- **`routing` (Правила маршрутизации)**: Механизм, заменяющий старый блок `exclude`. Позволяет гибко перенаправлять трафик.
|
||||||
|
|
||||||
|
Пример правила маршрутизации в `config.json`:
|
||||||
|
```json
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": ["trusted-site.com", "local.lan"],
|
||||||
|
"outbound": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default_outbound": "proxy"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> Механизм исключений полностью отлажен и готов к промышленной эксплуатации, обеспечивая нулевые задержки для доверенных ресурсов.
|
> Такая архитектура позволяет подключать клиента сразу к нескольким серверам OSTP, разделять трафик по доменам или блокировать телеметрию на уровне роутера VPN.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
# Часто задаваемые вопросы (FAQ)
|
||||||
|
|
||||||
|
## Что такое OSTP и чем он отличается от других VPN (WireGuard, OpenVPN)?
|
||||||
|
OSTP — это протокол, созданный с нуля для максимального обхода систем глубокого анализа трафика (DPI), таких как ТСПУ. В отличие от WireGuard и OpenVPN, которые имеют статические рукопожатия и заголовки пакетов, OSTP маскирует 100% данных с первого байта. Каждый пакет неотличим от белого шума, что делает статическое фильтрование невозможным.
|
||||||
|
|
||||||
|
## Как работает защита от DPI? Безопасно ли это?
|
||||||
|
Архитектура OSTP строго следует **Принципу Керкгоффса**. Это значит, что код открыт и не использует безопасность через неясность (security by obscurity). Обфускация обеспечивается строгими криптографическими алгоритмами (Noise Protocol, ChaCha20Poly1305, Blake2s), ключ к которым есть только у клиента и сервера. ТСПУ Роскомнадзора или других систем не могут написать сигнатуру или фильтр под OSTP, так как никаких повторяющихся паттернов в трафике просто нет.
|
||||||
|
|
||||||
|
## Как обновиться до версии 0.3.1 и что делать с `config.json`?
|
||||||
|
Версия 0.3.1 перешла на новую модульную систему (массивы `inbounds` и `outbounds`). При первом запуске OSTP v0.3.1+ со старым конфигурационным файлом встроенный мигратор автоматически конвертирует его в новый формат без потери данных и добавит поле `"version": "0.3.1"`.
|
||||||
|
|
||||||
|
## Почему у меня не работает мультиплексирование (sessions > 1)?
|
||||||
|
Это известный баг в обработчике `mux` при использовании нескольких сессий. Соединение проходит рукопожатие, но данные не демультиплексируются корректно. Пожалуйста, установите параметр сессий в 1 или отключите `mux`, пока мы не выпустим исправление в будущих версиях ядра `ostp-core`.
|
||||||
|
|
||||||
|
## Есть ли в OSTP проприетарный или скрытый код?
|
||||||
|
Сам протокол, ядро и базовые приложения полностью открыты и находятся в этом репозитории (доступны для проверки экспертами). Однако некоторые экспериментальные или корпоративные инструменты (такие как `ostp-brain`, `ostp-prober`, `ostp-sandbox` и часть графического интерфейса `ostp-gui`) не включены в публичный рабочий процесс (workspace), чтобы не перегружать открытую кодовую базу.
|
||||||
|
|
@ -0,0 +1,108 @@
|
||||||
|
# Миграция конфигурации OSTP на версию 0.3.1
|
||||||
|
|
||||||
|
В версии `v0.3.1` формат `config.json` проекта OSTP был значительно переработан для поддержки современной архитектуры мульти-серверных подключений. Новый формат конфигурации обеспечивает большую гибкость: теперь он разделен на входящие подключения (`inbounds`), исходящие подключения (`outbounds`) и гибкие правила маршрутизации (`routing`), заменяя устаревшую монолитную структуру прошлых версий.
|
||||||
|
|
||||||
|
## Автоматическая миграция
|
||||||
|
|
||||||
|
Ядро OSTP и GUI клиенты оснащены автоматическим мигратором. При запуске OSTP `v0.3.1` с файлом `config.json` от предыдущей версии, мигратор автоматически преобразует старый формат в новый.
|
||||||
|
|
||||||
|
После успешной миграции файл будет перезаписан в новом формате, и его заголовок будет содержать комментарий:
|
||||||
|
```json
|
||||||
|
// OSTP Configuration v0.3.1
|
||||||
|
// DO NOT EDIT THIS COMMENT - Migrator relies on it
|
||||||
|
{
|
||||||
|
"version": "0.3.1",
|
||||||
|
"mode": "client",
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Справочник по новому формату
|
||||||
|
|
||||||
|
Если вы предпочитаете настраивать OSTP вручную, ниже приведено сравнение и примеры нового формата.
|
||||||
|
|
||||||
|
### Устаревшая конфигурация (v0.2.x)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "client",
|
||||||
|
"server": "192.168.1.100:50000",
|
||||||
|
"access_key": "mysecretkey",
|
||||||
|
"socks5_bind": "127.0.0.1:1088",
|
||||||
|
"tun": {
|
||||||
|
"enable": true,
|
||||||
|
"kill_switch": true
|
||||||
|
},
|
||||||
|
"exclude": {
|
||||||
|
"domains": ["localhost"],
|
||||||
|
"ips": ["192.168.1.0/24"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Новая конфигурация (v0.3.1)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": "0.3.1",
|
||||||
|
"mode": "client",
|
||||||
|
"api": {
|
||||||
|
"enabled": true,
|
||||||
|
"bind": "127.0.0.1:50001",
|
||||||
|
"token": "admin-secret-token"
|
||||||
|
},
|
||||||
|
"log": {
|
||||||
|
"level": "info"
|
||||||
|
},
|
||||||
|
"inbounds": [
|
||||||
|
{
|
||||||
|
"type": "tun",
|
||||||
|
"tag": "tun-in",
|
||||||
|
"auto_route": true,
|
||||||
|
"mtu": 1140
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "socks",
|
||||||
|
"tag": "socks-in",
|
||||||
|
"bind_addr": "127.0.0.1:1088"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"type": "ostp",
|
||||||
|
"tag": "proxy",
|
||||||
|
"server": "192.168.1.100",
|
||||||
|
"port": 50000,
|
||||||
|
"access_key": "mysecretkey",
|
||||||
|
"transport": {
|
||||||
|
"type": "udp"
|
||||||
|
},
|
||||||
|
"multiplex": {
|
||||||
|
"enabled": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "direct",
|
||||||
|
"tag": "direct"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "block",
|
||||||
|
"tag": "block"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": ["localhost"],
|
||||||
|
"ip_cidr": ["192.168.1.0/24"],
|
||||||
|
"outbound": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default_outbound": "proxy"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Основные изменения
|
||||||
|
- **Outbounds (Исходящие)**: Теперь можно задать сразу несколько прокси-серверов.
|
||||||
|
- **Inbounds (Входящие)**: TUN и SOCKS5 выделены в отдельные независимые модули.
|
||||||
|
- **Routing (Маршрутизация)**: Точная маршрутизация трафика между входящими и исходящими узлами на основе доменов, IP-адресов и имен процессов.
|
||||||
|
- **Комментарии**: GUI и ядро теперь поддерживают JS-комментарии (с помощью `//`) в `config.json` вместо устаревших полей вида `"_comment"`.
|
||||||
|
|
@ -49,3 +49,13 @@ $$\text{Key} = \text{SHA-256}(\text{access\_key})[0..8]$$
|
||||||
|
|
||||||
- **Стратегия заполнения буферов**: Механизм анализирует текущую длину выборки телеметрии и производит масштабирование до типичных кратных длин промышленных сетей передачи данных и буферов потоковых агрегаторов.
|
- **Стратегия заполнения буферов**: Механизм анализирует текущую длину выборки телеметрии и производит масштабирование до типичных кратных длин промышленных сетей передачи данных и буферов потоковых агрегаторов.
|
||||||
- **Изоляция выравнивания**: Данные заполнения помещаются внутрь защищенной области кадра. Внешние анализаторы топологии сети не способны определить внутренние границы между телеметрической нагрузкой и служебными полями выравнивания, видя только монолитный блок данных.
|
- **Изоляция выравнивания**: Данные заполнения помещаются внутрь защищенной области кадра. Внешние анализаторы топологии сети не способны определить внутренние границы между телеметрической нагрузкой и служебными полями выравнивания, видя только монолитный блок данных.
|
||||||
|
|
||||||
|
## XTLS-Reality (Имитация TLS 1.3)
|
||||||
|
|
||||||
|
OSTP предоставляет собственную реализацию протокола XTLS-Reality без сторонних зависимостей. Протокол полностью имитирует рукопожатие TLS 1.3 (с реалистичным профилем ClientHello) для обхода продвинутых DPI фильтров. После успешного рукопожатия применяется ChaCha20Poly1305 для бесшовного шифрования и туннелирования внутренних HTTP/WSS соединений.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Невозможность создания статических фильтров (Защита от DPI)
|
||||||
|
|
||||||
|
Благодаря строгой математической базе генерации энтропии, протокол полностью лишен открытых сигнатур. Это гарантирует, что системы фильтрации (например, ТСПУ от РКН или "Великий китайский файрвол") **физически не могут** написать эффективное правило блокировки, анализируя содержимое пакетов. Любая попытка написать фильтр приведет к блокировке легитимного, случайного UDP-трафика (например, WebRTC или игрового трафика). Безопасность базируется на принципе Керкгоффса — знание всех алгоритмов не помогает взломать или классифицировать трафик без `access_key`.
|
||||||
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 183 KiB |
|
|
@ -0,0 +1,15 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="g2" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#111827" />
|
||||||
|
<stop offset="100%" stop-color="#374151" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="g2_path" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#3B82F6" />
|
||||||
|
<stop offset="100%" stop-color="#14B8A6" />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<rect width="512" height="512" rx="120" fill="url(#g2)" />
|
||||||
|
<path d="M144 256c0-61.9 50.1-112 112-112s112 50.1 112 112-50.1 112-112 112S144 317.9 144 256zm-48 0c0 88.4 71.6 160 160 160s160-71.6 160-160S344.4 96 256 96 96 167.6 96 256z" fill="url(#g2_path)"/>
|
||||||
|
<circle cx="256" cy="256" r="40" fill="#F59E0B" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 779 B |
|
|
@ -0,0 +1 @@
|
||||||
|
{"v":1}
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"git": {
|
||||||
|
"sha1": "702f6dfe124c5e4d343cfd3ca5a3efe0446cf6f0"
|
||||||
|
},
|
||||||
|
"path_in_vcs": ""
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
name: Setup Android NDK and Rust compiler ENV
|
||||||
|
description: Setup an Android_NDK_HOME environment by downloading and Rust compiler environment.
|
||||||
|
inputs:
|
||||||
|
rust-target:
|
||||||
|
description: Rust target to build
|
||||||
|
required: true
|
||||||
|
sdk-version:
|
||||||
|
description: Exact SDK version to use
|
||||||
|
default: "33"
|
||||||
|
ndk-version:
|
||||||
|
description: Exact NDK version to use
|
||||||
|
default: "25"
|
||||||
|
ndk-platform:
|
||||||
|
description: Which host platform to use
|
||||||
|
default: "linux"
|
||||||
|
runs:
|
||||||
|
using: "composite"
|
||||||
|
steps:
|
||||||
|
- name: Download Android NDK
|
||||||
|
run: curl --http1.1 -O https://dl.google.com/android/repository/android-ndk-r${{ inputs.ndk-version }}-${{ inputs.ndk-platform }}.zip
|
||||||
|
shell: bash
|
||||||
|
- name: Extract Android NDK
|
||||||
|
run: unzip -q android-ndk-r${{ inputs.ndk-version }}-${{ inputs.ndk-platform }}.zip
|
||||||
|
shell: bash
|
||||||
|
- name: Set Rust compiler ENV
|
||||||
|
run: |
|
||||||
|
ndk_home=${{ github.workspace }}/android-ndk-r${{ inputs.ndk-version }}
|
||||||
|
platform=$(ls ${ndk_home}/toolchains/llvm/prebuilt/ | head -1)
|
||||||
|
ndk_tool=${ndk_home}/toolchains/llvm/prebuilt/${platform}/bin
|
||||||
|
envvar_suffix=$(echo ${{ inputs.rust-target }} | sed "s/-/_/g")
|
||||||
|
upper_suffix=$(echo ${envvar_suffix} | tr '[:lower:]' '[:upper:]')
|
||||||
|
tool_prefix=${{ inputs.rust-target }}${{ inputs.sdk-version }}
|
||||||
|
echo "ANDROID_NDK_HOME=${ndk_home}" >> $GITHUB_ENV
|
||||||
|
echo "CC_${envvar_suffix}=${ndk_tool}/${tool_prefix}-clang" >> $GITHUB_ENV
|
||||||
|
echo "AR_${envvar_suffix}=${ndk_tool}/llvm-ar" >> $GITHUB_ENV
|
||||||
|
echo "CARGO_TARGET_${upper_suffix}_LINKER=${ndk_tool}/${tool_prefix}-clang" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
@ -0,0 +1,80 @@
|
||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '**'
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- '**'
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_INCREMENTAL: 0
|
||||||
|
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: Test
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- build: linux-amd64
|
||||||
|
os: ubuntu-latest
|
||||||
|
target: x86_64-unknown-linux-gnu
|
||||||
|
- build: android-arm64
|
||||||
|
os: ubuntu-latest
|
||||||
|
target: aarch64-linux-android
|
||||||
|
no_run: --no-run
|
||||||
|
- build: android-amd64
|
||||||
|
os: ubuntu-latest
|
||||||
|
target: x86_64-linux-android
|
||||||
|
no_run: --no-run
|
||||||
|
- build: macos-amd64
|
||||||
|
os: macos-latest
|
||||||
|
target: x86_64-apple-darwin
|
||||||
|
- build: macos-arm64
|
||||||
|
os: macos-14
|
||||||
|
target: aarch64-apple-darwin
|
||||||
|
- build: ios-arm64
|
||||||
|
os: macos-latest
|
||||||
|
target: aarch64-apple-ios
|
||||||
|
no_run: --no-run
|
||||||
|
- build: windows-amd64
|
||||||
|
os: windows-latest
|
||||||
|
target: x86_64-pc-windows-msvc
|
||||||
|
- build: windows-arm64
|
||||||
|
os: windows-latest
|
||||||
|
target: aarch64-pc-windows-msvc
|
||||||
|
no_run: --no-run
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Install Rust (rustup)
|
||||||
|
run: |
|
||||||
|
set -euxo pipefail
|
||||||
|
rustup toolchain install stable --no-self-update --profile minimal --target ${{ matrix.target }}
|
||||||
|
rustup default stable
|
||||||
|
shell: bash
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
- name: Setup android environment
|
||||||
|
if: contains(matrix.build, 'android')
|
||||||
|
uses: ./.github/actions/ndk-dev-rs
|
||||||
|
with:
|
||||||
|
rust-target: ${{ matrix.target }}
|
||||||
|
- run: cargo test ${{ matrix.no_run }} --workspace --target ${{ matrix.target }}
|
||||||
|
- run: cargo test ${{ matrix.no_run }} --workspace --target ${{ matrix.target }} --release
|
||||||
|
|
||||||
|
msrv_n_clippy:
|
||||||
|
name: MSRV & Clippy & Rustfmt
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
- run: cargo fmt -- --check
|
||||||
|
- run: cargo clippy --all-features -- -D warnings
|
||||||
|
- run: cargo check --lib -p netstack-smoltcp
|
||||||
|
- run: cargo check --lib -p netstack-smoltcp --all-features
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Publish to crates.io
|
||||||
|
run: |
|
||||||
|
cargo publish
|
||||||
|
env:
|
||||||
|
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
/target
|
||||||
|
/Cargo.lock
|
||||||
|
|
||||||
|
.idea
|
||||||
|
.VSCodeCounter/
|
||||||
|
.vscode
|
||||||
|
.DS_Store
|
||||||
|
*.iml
|
||||||
|
**/*.log
|
||||||
|
|
@ -0,0 +1,136 @@
|
||||||
|
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||||
|
#
|
||||||
|
# When uploading crates to the registry Cargo will automatically
|
||||||
|
# "normalize" Cargo.toml files for maximal compatibility
|
||||||
|
# with all versions of Cargo and also rewrite `path` dependencies
|
||||||
|
# to registry (e.g., crates.io) dependencies.
|
||||||
|
#
|
||||||
|
# If you are reading this file be aware that the original Cargo.toml
|
||||||
|
# will likely look very different (and much more reasonable).
|
||||||
|
# See Cargo.toml.orig for the original contents.
|
||||||
|
|
||||||
|
[package]
|
||||||
|
edition = "2021"
|
||||||
|
rust-version = "1.75.0"
|
||||||
|
name = "netstack-smoltcp"
|
||||||
|
version = "0.2.2"
|
||||||
|
authors = ["cavivie <cavivie@gmail.com>"]
|
||||||
|
build = false
|
||||||
|
autolib = false
|
||||||
|
autobins = false
|
||||||
|
autoexamples = false
|
||||||
|
autotests = false
|
||||||
|
autobenches = false
|
||||||
|
description = """
|
||||||
|
A netstack for the special purpose of turning packets from/to a TUN interface
|
||||||
|
into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
|
||||||
|
"""
|
||||||
|
homepage = "https://github.com/cavivie/netstack-smoltcp"
|
||||||
|
documentation = "https://docs.rs/netstack-smoltcp"
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = [
|
||||||
|
"netstack",
|
||||||
|
"smoltcp",
|
||||||
|
"network",
|
||||||
|
"ip",
|
||||||
|
"tun",
|
||||||
|
]
|
||||||
|
categories = ["network-programming"]
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
repository = "https://github.com/cavivie/netstack-smoltcp"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "netstack_smoltcp"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "forward"
|
||||||
|
path = "examples/forward.rs"
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "forward-offload-linux"
|
||||||
|
path = "examples/forward-offload-linux.rs"
|
||||||
|
|
||||||
|
[[test]]
|
||||||
|
name = "regression"
|
||||||
|
path = "tests/regression.rs"
|
||||||
|
|
||||||
|
[dependencies.etherparse]
|
||||||
|
version = "0.16"
|
||||||
|
|
||||||
|
[dependencies.futures]
|
||||||
|
version = "0.3"
|
||||||
|
|
||||||
|
[dependencies.rand]
|
||||||
|
version = "0.8"
|
||||||
|
|
||||||
|
[dependencies.smoltcp]
|
||||||
|
version = "0.12"
|
||||||
|
features = [
|
||||||
|
"std",
|
||||||
|
"log",
|
||||||
|
"medium-ip",
|
||||||
|
"proto-ipv4",
|
||||||
|
"proto-ipv6",
|
||||||
|
"socket-icmp",
|
||||||
|
"socket-udp",
|
||||||
|
"socket-tcp",
|
||||||
|
]
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[dependencies.spin]
|
||||||
|
version = "0.9"
|
||||||
|
|
||||||
|
[dependencies.tokio]
|
||||||
|
version = "1"
|
||||||
|
features = [
|
||||||
|
"sync",
|
||||||
|
"time",
|
||||||
|
"rt",
|
||||||
|
"macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependencies.tokio-util]
|
||||||
|
version = "0.7.10"
|
||||||
|
|
||||||
|
[dependencies.tracing]
|
||||||
|
version = "0.1"
|
||||||
|
features = ["std"]
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[dev-dependencies.socket2]
|
||||||
|
version = "0.5.6"
|
||||||
|
|
||||||
|
[dev-dependencies.socket2-ext]
|
||||||
|
version = "0.1"
|
||||||
|
|
||||||
|
[dev-dependencies.structopt]
|
||||||
|
version = "0.3"
|
||||||
|
|
||||||
|
[dev-dependencies.tokio]
|
||||||
|
version = "1"
|
||||||
|
features = [
|
||||||
|
"rt",
|
||||||
|
"macros",
|
||||||
|
"rt-multi-thread",
|
||||||
|
"io-util",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dev-dependencies.tracing]
|
||||||
|
version = "0.1"
|
||||||
|
features = ["std"]
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[dev-dependencies.tracing-subscriber]
|
||||||
|
version = "0.3.18"
|
||||||
|
|
||||||
|
[dev-dependencies.tun-rs]
|
||||||
|
version = "2"
|
||||||
|
features = [
|
||||||
|
"async",
|
||||||
|
"async_framed",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dev-dependencies.tun2]
|
||||||
|
version = "3"
|
||||||
|
features = ["async"]
|
||||||
|
|
@ -0,0 +1,51 @@
|
||||||
|
[package]
|
||||||
|
name = "netstack-smoltcp"
|
||||||
|
version = "0.2.2"
|
||||||
|
edition = "2021"
|
||||||
|
authors = ["cavivie <cavivie@gmail.com>"]
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
repository = "https://github.com/cavivie/netstack-smoltcp"
|
||||||
|
homepage = "https://github.com/cavivie/netstack-smoltcp"
|
||||||
|
documentation = "https://docs.rs/netstack-smoltcp"
|
||||||
|
keywords = ["netstack", "smoltcp", "network", "ip", "tun"]
|
||||||
|
categories = ["network-programming"]
|
||||||
|
description = """
|
||||||
|
A netstack for the special purpose of turning packets from/to a TUN interface
|
||||||
|
into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
|
||||||
|
"""
|
||||||
|
rust-version = "1.75.0"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tracing = { version = "0.1", default-features = false, features = ["std"] }
|
||||||
|
tokio = { version = "1", features = ["sync", "time", "rt", "macros"] }
|
||||||
|
tokio-util = "0.7.10"
|
||||||
|
etherparse = "0.16"
|
||||||
|
futures = "0.3"
|
||||||
|
rand = "0.8"
|
||||||
|
spin = "0.9"
|
||||||
|
smoltcp = { version = "0.12", default-features = false, features = [
|
||||||
|
"std",
|
||||||
|
"log",
|
||||||
|
"medium-ip",
|
||||||
|
"proto-ipv4",
|
||||||
|
"proto-ipv6",
|
||||||
|
"socket-icmp",
|
||||||
|
"socket-udp",
|
||||||
|
"socket-tcp",
|
||||||
|
] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tun2 = { version = "3", features = ["async"] }
|
||||||
|
# has better performance on linux than tun2
|
||||||
|
tun-rs = { version = "2", features = ["async", "async_framed"] }
|
||||||
|
tokio = { version = "1", features = [
|
||||||
|
"rt",
|
||||||
|
"macros",
|
||||||
|
"rt-multi-thread",
|
||||||
|
"io-util",
|
||||||
|
] }
|
||||||
|
tracing = { version = "0.1", default-features = false, features = ["std"] }
|
||||||
|
tracing-subscriber = "0.3.18"
|
||||||
|
structopt = "0.3"
|
||||||
|
socket2 = "0.5.6"
|
||||||
|
socket2-ext = { version = "0.1" }
|
||||||
|
|
@ -0,0 +1,201 @@
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
Copyright (c) 2024 cavivie and netstack-smoltcp Contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any
|
||||||
|
person obtaining a copy of this software and associated
|
||||||
|
documentation files (the "Software"), to deal in the
|
||||||
|
Software without restriction, including without
|
||||||
|
limitation the rights to use, copy, modify, merge,
|
||||||
|
publish, distribute, sublicense, and/or sell copies of
|
||||||
|
the Software, and to permit persons to whom the Software
|
||||||
|
is furnished to do so, subject to the following
|
||||||
|
conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice
|
||||||
|
shall be included in all copies or substantial portions
|
||||||
|
of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||||
|
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||||
|
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||||
|
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||||
|
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||||
|
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
|
|
@ -0,0 +1,136 @@
|
||||||
|
# Netstack Smoltcp
|
||||||
|
|
||||||
|
A netstack for the special purpose of turning packets from/to a TUN interface into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
|
||||||
|
|
||||||
|
[![Crates.io][crates-badge]][crates-url]
|
||||||
|
[![MIT licensed][mit-badge]][mit-url]
|
||||||
|
[![Apache licensed, Version 2.0][apache-badge]][apache-url]
|
||||||
|
[![Build Status][actions-badge]][actions-url]
|
||||||
|
|
||||||
|
[crates-badge]: https://img.shields.io/crates/v/netstack-smoltcp.svg
|
||||||
|
[crates-url]: https://crates.io/crates/netstack-smoltcp
|
||||||
|
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
|
||||||
|
[mit-url]: https://github.com/automesh-network/netstack-smoltcp/blob/master/LICENSE-MIT
|
||||||
|
[apache-badge]: https://img.shields.io/badge/license-APACHE2.0-blue.svg
|
||||||
|
[apache-url]: https://github.com/automesh-network/netstack-smoltcp/blob/master/LICENSE-APACHE
|
||||||
|
[actions-badge]: https://github.com/automesh-network/netstack-smoltcp/workflows/CI/badge.svg
|
||||||
|
[actions-url]: https://github.com/automesh-network/netstack-smoltcp/actions?query=workflow%3ACI+branch%3Amain
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Supports Future Send and non-Send, mostly pepole use Send.
|
||||||
|
- Supports ICMP protocol drive by TCP runner to use ICMP ping.
|
||||||
|
- Supports filtering packets by source and destination IP addresses.
|
||||||
|
- Can read IP packets from netstack, write IP packets to netstack.
|
||||||
|
- Can receive TcpStream from TcpListener exposed from netstack.
|
||||||
|
- Can receive UDP datagram from UdpSocket exposed from netstack.
|
||||||
|
- Implements popular future streaming traits and asynchronous IO traits:
|
||||||
|
* TcpListener implements futures Stream/Sink trait
|
||||||
|
* TcpStream implements tokio AsyncRead/AsyncWrite trait
|
||||||
|
* UdpSocket(ReadHalf/WriteHalf) implements futures Stream/Sink trait.
|
||||||
|
|
||||||
|
## Platforms
|
||||||
|
|
||||||
|
This crate provides lightweight netstack support for Linux, iOS, macOS, Android and Windows.
|
||||||
|
Currently, it works on most targets, but mainly tested the popular platforms which includes:
|
||||||
|
- linux-amd64: x86_64-unknown-linux-gnu
|
||||||
|
- android-arm64: aarch64-linux-android
|
||||||
|
- android-amd64: x86_64-linux-android
|
||||||
|
- macos-amd64: x86_64-apple-darwin
|
||||||
|
- macos-arm64: aarch64-apple-darwin
|
||||||
|
- ios-arm64: aarch64-apple-ios
|
||||||
|
- windows-amd64: x86_64-pc-windows-msvc
|
||||||
|
- windows-arm64: aarch64-pc-windows-msvc
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// let device = tun2::create_as_async(&cfg)?;
|
||||||
|
// let framed = device.into_framed();
|
||||||
|
|
||||||
|
let (stack, runner, udp_socket, tcp_listener) = netstack_smoltcp::StackBuilder::default()
|
||||||
|
.stack_buffer_size(512)
|
||||||
|
.tcp_buffer_size(4096)
|
||||||
|
.enable_udp(true)
|
||||||
|
.enable_tcp(true)
|
||||||
|
.enable_icmp(true)
|
||||||
|
.mtu(9000) // virtual device usually benefits from larger MTU
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
let mut udp_socket = udp_socket.unwrap(); // udp enabled
|
||||||
|
let mut tcp_listener = tcp_listener.unwrap(); // tcp/icmp enabled
|
||||||
|
if let Some(runner) = runner {
|
||||||
|
tokio::spawn(runner);
|
||||||
|
}
|
||||||
|
|
||||||
|
let (mut stack_sink, mut stack_stream) = stack.split();
|
||||||
|
let (mut tun_sink, mut tun_stream) = framed.split();
|
||||||
|
|
||||||
|
// Reads packet from stack and sends to TUN.
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some(pkt) = stack_stream.next().await {
|
||||||
|
if let Ok(pkt) = pkt {
|
||||||
|
tun_sink.send(pkt).await.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reads packet from TUN and sends to stack.
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some(pkt) = tun_stream.next().await {
|
||||||
|
if let Ok(pkt) = pkt {
|
||||||
|
stack_sink.send(pkt).await.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Extracts TCP connections from stack and sends them to the dispatcher.
|
||||||
|
tokio::spawn(async move {
|
||||||
|
handle_inbound_stream(tcp_listener).await;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Receive and send UDP packets between netstack and NAT manager. The NAT
|
||||||
|
// manager would maintain UDP sessions and send them to the dispatcher.
|
||||||
|
tokio::spawn(async move {
|
||||||
|
handle_inbound_datagram(udp_socket).await;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
Typically, `netstack-smoltcp` will be used with an tun device, so a careful choice of TUN crate matters.
|
||||||
|
|
||||||
|
[tun-rs](https://github.com/tun-rs/tun-rs) have better performance on **Linux** than [rust-tun](https://github.com/meh/rust-tun/) due to GSO/GRO which allow you to process the packets in batches.
|
||||||
|
|
||||||
|
`bash scripts/bench-offload.sh` could tell that `tun-rs` boosts the performance by 4x. Try it out on your Linux machine!
|
||||||
|
|
||||||
|
The example for using `tun-rs` with `netstack-smoltcp` could be found at [forward-offload-linux.rs](examples/forward-offload-linux.rs)
|
||||||
|
|
||||||
|
For further tuning, refer to `tun-rs`'s detailed [README](https://github.com/tun-rs/tun-rs/blob/main/README.md)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under either of
|
||||||
|
|
||||||
|
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
|
||||||
|
https://www.apache.org/licenses/LICENSE-2.0)
|
||||||
|
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
|
||||||
|
https://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
at your option.
|
||||||
|
|
||||||
|
### Contribution
|
||||||
|
|
||||||
|
Unless you explicitly state otherwise, any contribution intentionally submitted
|
||||||
|
for inclusion in netstack-smoltcp by you, as defined in the Apache-2.0 license,
|
||||||
|
shall be dual licensed as above, without any additional terms or conditions.
|
||||||
|
|
||||||
|
## Inspired By
|
||||||
|
|
||||||
|
Special thanks to these amazing projects that inspired netstack-smoltcp (in no particular order):
|
||||||
|
- [shadowsocks-rust](https://github.com/shadowsocks/shadowsocks-rust/)
|
||||||
|
- [netstack-lwip](https://github.com/eycorsican/netstack-lwip/)
|
||||||
|
- [rust-tun-active](https://github.com/tun2proxy/rust-tun)
|
||||||
|
- [rust-tun](https://github.com/meh/rust-tun/)
|
||||||
|
- [tun-rs](https://github.com/tun-rs/tun-rs)
|
||||||
|
- [smoltcp](https://github.com/smoltcp-rs/smoltcp)
|
||||||
|
|
@ -0,0 +1,239 @@
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
mod inner {
|
||||||
|
use futures::{SinkExt, StreamExt};
|
||||||
|
use netstack_smoltcp::{StackBuilder, TcpListener, UdpSocket};
|
||||||
|
use std::{net::SocketAddr, sync::Arc};
|
||||||
|
use structopt::StructOpt;
|
||||||
|
use tokio::net::{TcpSocket, TcpStream};
|
||||||
|
use tracing::{error, info, warn};
|
||||||
|
use tun_rs::{DeviceBuilder, IDEAL_BATCH_SIZE, VIRTIO_NET_HDR_LEN};
|
||||||
|
|
||||||
|
// Patched forward example: tun2 → tun-rs with Linux GRO/GSO offload.
|
||||||
|
// For further reading, check out https://blog.cloudflare.com/virtual-networking-101-understanding-tap
|
||||||
|
//
|
||||||
|
// Key changes vs forward.rs:
|
||||||
|
// 1. Use tun-rs DeviceBuilder with .offload(true) on Linux (enables
|
||||||
|
// IFF_VNET_HDR + TUN_F_CSUM/TSO4/TSO6/USO4/USO6).
|
||||||
|
// 2. TX (stack → TUN): prepend 10-byte zero virtio_net_hdr (GSO_NONE)
|
||||||
|
// so the kernel accepts the write when IFF_VNET_HDR is set.
|
||||||
|
// 3. RX (TUN → stack): use recv_multiple() for batch GSO splitting;
|
||||||
|
// buffers sized to 1600 to fit smoltcp's 1504-byte MTU segments.
|
||||||
|
#[derive(Debug, StructOpt)]
|
||||||
|
#[structopt(name = "forward", about = "Simply forward tun tcp/udp traffic.")]
|
||||||
|
struct Opt {
|
||||||
|
/// Outbound interface to bind forwarded connections to.
|
||||||
|
#[structopt(short = "i", long = "interface")]
|
||||||
|
interface: String,
|
||||||
|
/// Name of the TUN device.
|
||||||
|
#[structopt(short = "n", long = "name", default_value = "utun8")]
|
||||||
|
name: String,
|
||||||
|
/// Tracing log level.
|
||||||
|
#[structopt(long = "log-level", default_value = "debug")]
|
||||||
|
log_level: tracing::Level,
|
||||||
|
/// Use current-thread Tokio runtime (default: multi-thread).
|
||||||
|
#[structopt(long = "current-thread")]
|
||||||
|
current_thread: bool,
|
||||||
|
/// Use spawn_local instead of spawn.
|
||||||
|
#[structopt(long = "local-task")]
|
||||||
|
local_task: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn main() {
|
||||||
|
let opt = Opt::from_args();
|
||||||
|
let rt = if opt.current_thread {
|
||||||
|
tokio::runtime::Builder::new_current_thread()
|
||||||
|
} else {
|
||||||
|
tokio::runtime::Builder::new_multi_thread()
|
||||||
|
}
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
rt.block_on(main_exec(opt));
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn main_exec(opt: Opt) {
|
||||||
|
macro_rules! tokio_spawn {
|
||||||
|
($fut:expr) => {
|
||||||
|
if opt.local_task {
|
||||||
|
tokio::task::spawn_local($fut)
|
||||||
|
} else {
|
||||||
|
tokio::task::spawn($fut)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
tracing::subscriber::set_global_default(
|
||||||
|
tracing_subscriber::FmtSubscriber::builder()
|
||||||
|
.with_max_level(opt.log_level)
|
||||||
|
.finish(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Build TUN device with GRO/GSO offload on Linux.
|
||||||
|
let builder = DeviceBuilder::new()
|
||||||
|
.name(opt.name)
|
||||||
|
.ipv4("10.10.10.2", 24, Some("10.10.10.1"))
|
||||||
|
.mtu(9000);
|
||||||
|
let builder = builder.offload(true);
|
||||||
|
let dev = Arc::new(builder.build_async().unwrap());
|
||||||
|
|
||||||
|
let (stack, runner, udp_socket, tcp_listener) = StackBuilder::default()
|
||||||
|
.enable_tcp(true)
|
||||||
|
.enable_udp(true)
|
||||||
|
.enable_icmp(true)
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
let udp_socket = udp_socket.unwrap();
|
||||||
|
let tcp_listener = tcp_listener.unwrap();
|
||||||
|
if let Some(runner) = runner {
|
||||||
|
tokio_spawn!(runner);
|
||||||
|
}
|
||||||
|
let (mut stack_sink, mut stack_stream) = stack.split();
|
||||||
|
|
||||||
|
let mut futs = vec![];
|
||||||
|
|
||||||
|
// stack → TUN
|
||||||
|
// With IFF_VNET_HDR every write must start with a virtio_net_hdr.
|
||||||
|
// We use all-zero (gso_type = GSO_NONE, flags = 0): plain packet,
|
||||||
|
// checksum already valid (smoltcp always computes checksums itself).
|
||||||
|
let dev1 = dev.clone();
|
||||||
|
futs.push(tokio_spawn!(async move {
|
||||||
|
while let Some(pkt) = stack_stream.next().await {
|
||||||
|
if let Ok(pkt) = pkt {
|
||||||
|
let result = {
|
||||||
|
let mut buf = vec![0u8; VIRTIO_NET_HDR_LEN + pkt.len()];
|
||||||
|
buf[VIRTIO_NET_HDR_LEN..].copy_from_slice(&pkt);
|
||||||
|
dev1.send(&buf).await
|
||||||
|
};
|
||||||
|
if let Err(e) = result {
|
||||||
|
warn!("failed to send packet to TUN: {:?}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// TUN → stack
|
||||||
|
// recv_multiple() does one read() syscall and returns N individual IP
|
||||||
|
// packets after splitting any incoming GRO super-packet.
|
||||||
|
// Buffer size 1600 > smoltcp MTU (1504) to avoid an out-of-bounds panic
|
||||||
|
// when the kernel segments at MSS=1464 with 40-byte IP+TCP headers.
|
||||||
|
futs.push(tokio_spawn!(async move {
|
||||||
|
let mut orig = vec![0u8; VIRTIO_NET_HDR_LEN + 65535];
|
||||||
|
let mut bufs = vec![vec![0u8; 1600]; IDEAL_BATCH_SIZE];
|
||||||
|
let mut sizes = vec![0usize; IDEAL_BATCH_SIZE];
|
||||||
|
while let Ok(n) = dev.recv_multiple(&mut orig, &mut bufs, &mut sizes, 0).await {
|
||||||
|
for i in 0..n {
|
||||||
|
let pkt = &bufs[i][..sizes[i]];
|
||||||
|
if let Err(e) = stack_sink.send(pkt.to_vec()).await {
|
||||||
|
warn!("failed to send packet to stack: {:?}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
futs.push(tokio_spawn!({
|
||||||
|
let iface = opt.interface.clone();
|
||||||
|
async move {
|
||||||
|
handle_inbound_stream(tcp_listener, iface).await;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
futs.push(tokio_spawn!(async move {
|
||||||
|
handle_inbound_datagram(udp_socket, opt.interface).await;
|
||||||
|
}));
|
||||||
|
|
||||||
|
futures::future::join_all(futs).await.iter().for_each(|r| {
|
||||||
|
if let Err(e) = r {
|
||||||
|
error!("{:?}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_inbound_stream(mut tcp_listener: TcpListener, interface: String) {
|
||||||
|
while let Some((mut stream, local, remote)) = tcp_listener.next().await {
|
||||||
|
let interface = interface.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
info!("tcp: {:?} => {:?}", local, remote);
|
||||||
|
match new_tcp_stream(remote, &interface).await {
|
||||||
|
Ok(mut r) => {
|
||||||
|
if let Err(e) = tokio::io::copy_bidirectional(&mut stream, &mut r).await {
|
||||||
|
warn!(
|
||||||
|
"failed to copy tcp stream {:?}=>{:?}: {:?}",
|
||||||
|
local, remote, e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => warn!(
|
||||||
|
"failed to open tcp stream {:?}=>{:?}: {:?}",
|
||||||
|
local, remote, e
|
||||||
|
),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_inbound_datagram(udp_socket: UdpSocket, interface: String) {
|
||||||
|
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||||
|
let (mut read_half, mut write_half) = udp_socket.split();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some((data, local, remote)) = rx.recv().await {
|
||||||
|
let _ = write_half.send((data, remote, local)).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
while let Some((data, local, remote)) = read_half.next().await {
|
||||||
|
let tx = tx.clone();
|
||||||
|
let interface = interface.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
match new_udp_packet(remote, &interface).await {
|
||||||
|
Ok(sock) => {
|
||||||
|
let _ = sock.send(&data).await;
|
||||||
|
loop {
|
||||||
|
let mut buf = vec![0; 1024];
|
||||||
|
match sock.recv_from(&mut buf).await {
|
||||||
|
Ok((n, _)) => {
|
||||||
|
let _ = tx.send((buf[..n].to_vec(), local, remote));
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!("udp recv {:?}: {:?}", remote, e);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => warn!("failed to open udp socket {:?}: {:?}", remote, e),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn new_tcp_stream(addr: SocketAddr, iface: &str) -> std::io::Result<TcpStream> {
|
||||||
|
use socket2_ext::{AddressBinding, BindDeviceOption};
|
||||||
|
let s = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None)?;
|
||||||
|
s.bind_to_device(BindDeviceOption::v4(iface))?;
|
||||||
|
s.set_keepalive(true)?;
|
||||||
|
s.set_nodelay(true)?;
|
||||||
|
s.set_nonblocking(true)?;
|
||||||
|
Ok(TcpSocket::from_std_stream(s.into()).connect(addr).await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn new_udp_packet(
|
||||||
|
addr: SocketAddr,
|
||||||
|
iface: &str,
|
||||||
|
) -> std::io::Result<tokio::net::UdpSocket> {
|
||||||
|
use socket2_ext::{AddressBinding, BindDeviceOption};
|
||||||
|
let s = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::DGRAM, None)?;
|
||||||
|
s.bind_to_device(BindDeviceOption::v4(iface))?;
|
||||||
|
s.set_nonblocking(true)?;
|
||||||
|
let sock = tokio::net::UdpSocket::from_std(s.into())?;
|
||||||
|
sock.connect(addr).await?;
|
||||||
|
Ok(sock)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
mod inner {
|
||||||
|
pub(super) fn main() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
inner::main();
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,326 @@
|
||||||
|
use std::net::{IpAddr, SocketAddr};
|
||||||
|
|
||||||
|
use futures::{SinkExt, StreamExt};
|
||||||
|
use netstack_smoltcp::{StackBuilder, TcpListener, UdpSocket};
|
||||||
|
use structopt::StructOpt;
|
||||||
|
use tokio::net::{TcpSocket, TcpStream};
|
||||||
|
use tracing::{error, info, warn};
|
||||||
|
|
||||||
|
// to run this example, you should set the policy routing **after the start of the main program**
|
||||||
|
//
|
||||||
|
// linux:
|
||||||
|
// with bind device:
|
||||||
|
// `curl 1.1.1.1 --interface utun8`
|
||||||
|
// with default route:
|
||||||
|
// `bash scripts/route-linux.sh add`
|
||||||
|
// `curl 1.1.1.1`
|
||||||
|
// with single route:
|
||||||
|
// `ip rule add to 1.1.1.1 table 200`
|
||||||
|
// `ip route add default dev utun8 table 200`
|
||||||
|
// `curl 1.1.1.1`
|
||||||
|
//
|
||||||
|
// macos:
|
||||||
|
// with default route:
|
||||||
|
// `bash scripts/route-macos.sh add`
|
||||||
|
// `curl 1.1.1.1`
|
||||||
|
//
|
||||||
|
// windows:
|
||||||
|
// with default route:
|
||||||
|
// tun2 set default route automatically, won't set agian
|
||||||
|
// # `powershell.exe scripts/route-windows.ps1 add`
|
||||||
|
// `curl 1.1.1.1`
|
||||||
|
//
|
||||||
|
// currently, the example only supports the TCP stream, and the UDP packet will be dropped.
|
||||||
|
|
||||||
|
#[derive(Debug, StructOpt)]
|
||||||
|
#[structopt(name = "forward", about = "Simply forward tun tcp/udp traffic.")]
|
||||||
|
struct Opt {
|
||||||
|
/// Default binding interface, default by guessed.
|
||||||
|
/// Specify but doesn't exist, no device is bound.
|
||||||
|
#[structopt(short = "i", long = "interface")]
|
||||||
|
interface: String,
|
||||||
|
|
||||||
|
/// name of the tun device, default to rtun8.
|
||||||
|
#[structopt(short = "n", long = "name", default_value = "utun8")]
|
||||||
|
name: String,
|
||||||
|
|
||||||
|
/// Tracing subscriber log level.
|
||||||
|
#[structopt(long = "log-level", default_value = "debug")]
|
||||||
|
log_level: tracing::Level,
|
||||||
|
|
||||||
|
/// Tokio current-thread runtime, default to multi-thread.
|
||||||
|
#[structopt(long = "current-thread")]
|
||||||
|
current_thread: bool,
|
||||||
|
|
||||||
|
/// Tokio task spawn_local, default to spwan.
|
||||||
|
#[structopt(long = "local-task")]
|
||||||
|
local_task: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let opt = Opt::from_args();
|
||||||
|
|
||||||
|
let rt = if opt.current_thread {
|
||||||
|
tokio::runtime::Builder::new_current_thread()
|
||||||
|
} else {
|
||||||
|
tokio::runtime::Builder::new_multi_thread()
|
||||||
|
}
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
rt.block_on(main_exec(opt));
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn main_exec(opt: Opt) {
|
||||||
|
macro_rules! tokio_spawn {
|
||||||
|
($fut: expr) => {
|
||||||
|
if opt.local_task {
|
||||||
|
tokio::task::spawn_local($fut)
|
||||||
|
} else {
|
||||||
|
tokio::task::spawn($fut)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::subscriber::set_global_default(
|
||||||
|
tracing_subscriber::FmtSubscriber::builder()
|
||||||
|
.with_max_level(opt.log_level)
|
||||||
|
.finish(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut cfg = tun2::Configuration::default();
|
||||||
|
cfg.layer(tun2::Layer::L3);
|
||||||
|
let fd = -1;
|
||||||
|
if fd >= 0 {
|
||||||
|
cfg.raw_fd(fd);
|
||||||
|
} else {
|
||||||
|
cfg.tun_name(&opt.name)
|
||||||
|
.address("10.10.10.2")
|
||||||
|
.destination("10.10.10.1")
|
||||||
|
.mtu(tun2::DEFAULT_MTU);
|
||||||
|
#[cfg(not(any(target_arch = "mips", target_arch = "mips64",)))]
|
||||||
|
{
|
||||||
|
cfg.netmask("255.255.255.0");
|
||||||
|
}
|
||||||
|
cfg.up();
|
||||||
|
}
|
||||||
|
|
||||||
|
let device = tun2::create_as_async(&cfg).unwrap();
|
||||||
|
let mut builder = StackBuilder::default()
|
||||||
|
.enable_tcp(true)
|
||||||
|
.enable_udp(true)
|
||||||
|
.enable_icmp(true)
|
||||||
|
.mtu(9000);
|
||||||
|
if let Some(device_broadcast) = get_device_broadcast(&device) {
|
||||||
|
builder = builder
|
||||||
|
// .add_ip_filter(Box::new(move |src, dst| *src != device_broadcast && *dst != device_broadcast));
|
||||||
|
.add_ip_filter_fn(move |src, dst| *src != device_broadcast && *dst != device_broadcast);
|
||||||
|
}
|
||||||
|
|
||||||
|
let (stack, runner, udp_socket, tcp_listener) = builder.build().unwrap();
|
||||||
|
let udp_socket = udp_socket.unwrap(); // udp enabled
|
||||||
|
let tcp_listener = tcp_listener.unwrap(); // tcp enabled or icmp enabled
|
||||||
|
|
||||||
|
if let Some(runner) = runner {
|
||||||
|
tokio_spawn!(runner);
|
||||||
|
}
|
||||||
|
|
||||||
|
let framed = device.into_framed();
|
||||||
|
let (mut tun_sink, mut tun_stream) = framed.split();
|
||||||
|
let (mut stack_sink, mut stack_stream) = stack.split();
|
||||||
|
|
||||||
|
let mut futs = vec![];
|
||||||
|
|
||||||
|
// Reads packet from stack and sends to TUN.
|
||||||
|
futs.push(tokio_spawn!(async move {
|
||||||
|
while let Some(pkt) = stack_stream.next().await {
|
||||||
|
if let Ok(pkt) = pkt {
|
||||||
|
match tun_sink.send(pkt).await {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) => warn!("failed to send packet to TUN, err: {:?}", e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Reads packet from TUN and sends to stack.
|
||||||
|
futs.push(tokio_spawn!(async move {
|
||||||
|
while let Some(pkt) = tun_stream.next().await {
|
||||||
|
if let Ok(pkt) = pkt {
|
||||||
|
match stack_sink.send(pkt).await {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) => warn!("failed to send packet to stack, err: {:?}", e),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Extracts TCP connections from stack and sends them to the dispatcher.
|
||||||
|
futs.push(tokio_spawn!({
|
||||||
|
let interface = opt.interface.clone();
|
||||||
|
async move {
|
||||||
|
handle_inbound_stream(tcp_listener, interface).await;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Receive and send UDP packets between netstack and NAT manager. The NAT
|
||||||
|
// manager would maintain UDP sessions and send them to the dispatcher.
|
||||||
|
futs.push(tokio_spawn!(async move {
|
||||||
|
handle_inbound_datagram(udp_socket, opt.interface).await;
|
||||||
|
}));
|
||||||
|
|
||||||
|
futures::future::join_all(futs)
|
||||||
|
.await
|
||||||
|
.iter()
|
||||||
|
.for_each(|res| {
|
||||||
|
if let Err(e) = res {
|
||||||
|
error!("error: {:?}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// simply forward tcp stream
|
||||||
|
async fn handle_inbound_stream(mut tcp_listener: TcpListener, interface: String) {
|
||||||
|
while let Some((mut stream, local, remote)) = tcp_listener.next().await {
|
||||||
|
let interface = interface.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
info!("new tcp connection: {:?} => {:?}", local, remote);
|
||||||
|
match new_tcp_stream(remote, &interface).await {
|
||||||
|
Ok(mut remote_stream) => {
|
||||||
|
// pipe between two tcp stream
|
||||||
|
match tokio::io::copy_bidirectional(&mut stream, &mut remote_stream).await {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) => warn!(
|
||||||
|
"failed to copy tcp stream {:?}=>{:?}, err: {:?}",
|
||||||
|
local, remote, e
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => warn!(
|
||||||
|
"failed to new tcp stream {:?}=>{:?}, err: {:?}",
|
||||||
|
local, remote, e
|
||||||
|
),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// simply forward udp datagram
|
||||||
|
async fn handle_inbound_datagram(udp_socket: UdpSocket, interface: String) {
|
||||||
|
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||||
|
let (mut read_half, mut write_half) = udp_socket.split();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some((data, local, remote)) = rx.recv().await {
|
||||||
|
let _ = write_half.send((data, remote, local)).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
while let Some((data, local, remote)) = read_half.next().await {
|
||||||
|
let tx = tx.clone();
|
||||||
|
let interface = interface.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
info!("new udp datagram: {:?} => {:?}", local, remote);
|
||||||
|
match new_udp_packet(remote, &interface).await {
|
||||||
|
Ok(remote_socket) => {
|
||||||
|
// pipe between two udp sockets
|
||||||
|
let _ = remote_socket.send(&data).await;
|
||||||
|
loop {
|
||||||
|
let mut buf = vec![0; 1024];
|
||||||
|
match remote_socket.recv_from(&mut buf).await {
|
||||||
|
Ok((len, _)) => {
|
||||||
|
let _ = tx.send((buf[..len].to_vec(), local, remote));
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!(
|
||||||
|
"failed to recv udp datagram {:?}<->{:?}: {:?}",
|
||||||
|
local, remote, e
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => warn!(
|
||||||
|
"failed to new udp socket {:?}=>{:?}, err: {:?}",
|
||||||
|
local, remote, e
|
||||||
|
),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn new_tcp_stream<'a>(addr: SocketAddr, iface: &str) -> std::io::Result<TcpStream> {
|
||||||
|
use socket2_ext::{AddressBinding, BindDeviceOption};
|
||||||
|
let socket = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None)?;
|
||||||
|
socket.bind_to_device(BindDeviceOption::v4(iface))?;
|
||||||
|
socket.set_keepalive(true)?;
|
||||||
|
socket.set_nodelay(true)?;
|
||||||
|
socket.set_nonblocking(true)?;
|
||||||
|
|
||||||
|
let stream = TcpSocket::from_std_stream(socket.into())
|
||||||
|
.connect(addr)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn new_udp_packet(addr: SocketAddr, iface: &str) -> std::io::Result<tokio::net::UdpSocket> {
|
||||||
|
use socket2_ext::{AddressBinding, BindDeviceOption};
|
||||||
|
let socket = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::DGRAM, None)?;
|
||||||
|
socket.bind_to_device(BindDeviceOption::v4(iface))?;
|
||||||
|
socket.set_nonblocking(true)?;
|
||||||
|
|
||||||
|
let socket = tokio::net::UdpSocket::from_std(socket.into());
|
||||||
|
if let Ok(ref socket) = socket {
|
||||||
|
socket.connect(addr).await?;
|
||||||
|
}
|
||||||
|
socket
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_device_broadcast(device: &tun2::AsyncDevice) -> Option<std::net::Ipv4Addr> {
|
||||||
|
use tun2::AbstractDevice;
|
||||||
|
|
||||||
|
let mtu = device.mtu().unwrap_or(tun2::DEFAULT_MTU);
|
||||||
|
|
||||||
|
let address = match device.address() {
|
||||||
|
Ok(a) => match a {
|
||||||
|
IpAddr::V4(v4) => v4,
|
||||||
|
IpAddr::V6(_) => return None,
|
||||||
|
},
|
||||||
|
Err(_) => return None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let netmask = match device.netmask() {
|
||||||
|
Ok(n) => match n {
|
||||||
|
IpAddr::V4(v4) => v4,
|
||||||
|
IpAddr::V6(_) => return None,
|
||||||
|
},
|
||||||
|
Err(_) => return None,
|
||||||
|
};
|
||||||
|
|
||||||
|
match smoltcp::wire::Ipv4Cidr::from_netmask(address, netmask) {
|
||||||
|
Ok(address_net) => match address_net.broadcast() {
|
||||||
|
Some(broadcast) => {
|
||||||
|
info!(
|
||||||
|
"tun device network: {} (address: {}, netmask: {}, broadcast: {}, mtu: {})",
|
||||||
|
address_net, address, netmask, broadcast, mtu,
|
||||||
|
);
|
||||||
|
|
||||||
|
Some(broadcast)
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
error!("invalid tun address {}, netmask {}", address, netmask);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(err) => {
|
||||||
|
error!(
|
||||||
|
"invalid tun address {}, netmask {}, error: {}",
|
||||||
|
address, netmask, err
|
||||||
|
);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,174 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# bench-offload.sh
|
||||||
|
#
|
||||||
|
# Benchmarks netstack-smoltcp's forward examples with 2-stream iperf3.
|
||||||
|
# Compares:
|
||||||
|
# - examples/forward (tun2, no GRO/GSO offload)
|
||||||
|
# - examples/forward-offload-linux (tun-rs, Linux GRO/GSO offload via IFF_VNET_HDR)
|
||||||
|
#
|
||||||
|
# Setup: creates a veth pair + network namespace; iperf3 server runs inside
|
||||||
|
# the namespace, the forward proxy bridges traffic through a TUN device.
|
||||||
|
#
|
||||||
|
# Requirements: cargo, iperf3, ip (iproute2), root/CAP_NET_ADMIN
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# sudo bash scripts/bench-offload.sh
|
||||||
|
#
|
||||||
|
# Run from the root of the netstack-smoltcp repository.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# ── config ────────────────────────────────────────────────────────────────────
|
||||||
|
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
NS=bench
|
||||||
|
VETH_HOST=veth-host
|
||||||
|
VETH_NS=veth-bench
|
||||||
|
HOST_IP=172.19.0.1
|
||||||
|
NS_IP=172.19.0.2
|
||||||
|
PREFIX=24
|
||||||
|
TUN_NAME=utun8
|
||||||
|
TUN_IP=10.10.10.2
|
||||||
|
IPERF_PORT=5201
|
||||||
|
DURATION=15
|
||||||
|
STREAMS=2
|
||||||
|
|
||||||
|
# ── helpers ───────────────────────────────────────────────────────────────────
|
||||||
|
die() { echo "ERROR: $*" >&2; exit 1; }
|
||||||
|
require() { command -v "$1" &>/dev/null || die "'$1' not found"; }
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
pkill -f "forward-" 2>/dev/null || true
|
||||||
|
ip netns exec "$NS" pkill iperf3 2>/dev/null || true
|
||||||
|
ip route del "${NS_IP}/32" dev "$TUN_NAME" 2>/dev/null || true
|
||||||
|
ip tuntap del dev "$TUN_NAME" mode tun 2>/dev/null || true
|
||||||
|
ip link del "$VETH_HOST" 2>/dev/null || true
|
||||||
|
ip netns del "$NS" 2>/dev/null || true
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
|
# ── preflight ─────────────────────────────────────────────────────────────────
|
||||||
|
require cargo
|
||||||
|
require iperf3
|
||||||
|
require ip
|
||||||
|
[[ $EUID -eq 0 ]] || die "run as root (needs CAP_NET_ADMIN for TUN + netns)"
|
||||||
|
[[ -f "$REPO_DIR/Cargo.toml" ]] || die "run from the netstack-smoltcp repo root"
|
||||||
|
grep -q 'name = "netstack-smoltcp"' "$REPO_DIR/Cargo.toml" \
|
||||||
|
|| die "Cargo.toml does not look like netstack-smoltcp"
|
||||||
|
|
||||||
|
# ── network setup ─────────────────────────────────────────────────────────────
|
||||||
|
echo "[net] setting up namespace '$NS' and veth pair..."
|
||||||
|
cleanup 2>/dev/null || true
|
||||||
|
sleep 0.5
|
||||||
|
|
||||||
|
ip netns add "$NS"
|
||||||
|
ip link add "$VETH_HOST" type veth peer name "$VETH_NS"
|
||||||
|
ip link set "$VETH_NS" netns "$NS"
|
||||||
|
ip addr add "${HOST_IP}/${PREFIX}" dev "$VETH_HOST"
|
||||||
|
ip link set "$VETH_HOST" up
|
||||||
|
ip netns exec "$NS" ip addr add "${NS_IP}/${PREFIX}" dev "$VETH_NS"
|
||||||
|
ip netns exec "$NS" ip link set "$VETH_NS" up
|
||||||
|
ip netns exec "$NS" ip link set lo up
|
||||||
|
echo "[net] ${HOST_IP} <──veth──> ${NS_IP} (ns:${NS})"
|
||||||
|
|
||||||
|
# ── build: forward (tun2, no offload) ────────────────────────────────────────
|
||||||
|
echo ""
|
||||||
|
echo "[build] examples/forward (tun2, no GRO/GSO offload)..."
|
||||||
|
(
|
||||||
|
cd "$REPO_DIR"
|
||||||
|
cargo build --example forward --release --quiet
|
||||||
|
cp target/release/examples/forward /tmp/forward-tun2
|
||||||
|
)
|
||||||
|
echo "[build] done → /tmp/forward-tun2"
|
||||||
|
|
||||||
|
# ── build: forward-offload-linux (tun-rs, GRO/GSO offload) ───────────────────
|
||||||
|
echo ""
|
||||||
|
echo "[build] examples/forward-offload-linux (tun-rs, GRO/GSO offload)..."
|
||||||
|
(
|
||||||
|
cd "$REPO_DIR"
|
||||||
|
cargo build --example forward-offload-linux --release --quiet
|
||||||
|
cp target/release/examples/forward-offload-linux /tmp/forward-tun-rs
|
||||||
|
)
|
||||||
|
echo "[build] done → /tmp/forward-tun-rs"
|
||||||
|
|
||||||
|
# ── benchmark runner ──────────────────────────────────────────────────────────
|
||||||
|
run_bench() {
|
||||||
|
local label="$1" binary="$2"
|
||||||
|
|
||||||
|
# clean any leftover state
|
||||||
|
pkill -f "forward-" 2>/dev/null || true
|
||||||
|
ip netns exec "$NS" pkill iperf3 2>/dev/null || true
|
||||||
|
ip route del "${NS_IP}/32" dev "$TUN_NAME" 2>/dev/null || true
|
||||||
|
ip tuntap del dev "$TUN_NAME" mode tun 2>/dev/null || true
|
||||||
|
sleep 0.8
|
||||||
|
|
||||||
|
# start iperf3 server inside namespace
|
||||||
|
ip netns exec "$NS" iperf3 -s -p "$IPERF_PORT" -D \
|
||||||
|
--logfile /tmp/iperf3-bench-server.log
|
||||||
|
|
||||||
|
# start proxy
|
||||||
|
"$binary" -i "$VETH_HOST" -n "$TUN_NAME" --log-level warn &
|
||||||
|
sleep 2
|
||||||
|
|
||||||
|
ip link show "$TUN_NAME" &>/dev/null \
|
||||||
|
|| { echo " [!] TUN not up, skipping"; return 1; }
|
||||||
|
|
||||||
|
# route iperf3 traffic through TUN (more-specific /32 overrides /24 via veth)
|
||||||
|
ip route add "${NS_IP}/32" dev "$TUN_NAME"
|
||||||
|
|
||||||
|
echo " running iperf3: ${STREAMS} streams × ${DURATION}s …"
|
||||||
|
local out
|
||||||
|
out=$(iperf3 -c "$NS_IP" -p "$IPERF_PORT" \
|
||||||
|
-t "$DURATION" -P "$STREAMS" 2>&1)
|
||||||
|
|
||||||
|
local sender receiver
|
||||||
|
sender=$(echo "$out" | grep "SUM.*sender" | awk '{print $6, $7}')
|
||||||
|
receiver=$(echo "$out" | grep "SUM.*receiver" | awk '{print $6, $7}')
|
||||||
|
|
||||||
|
if [[ -z "$sender" ]]; then
|
||||||
|
echo " result: FAILED"
|
||||||
|
echo "$out" | tail -5 | sed 's/^/ /'
|
||||||
|
else
|
||||||
|
printf " sender: %s\n" "$sender"
|
||||||
|
printf " receiver: %s\n" "$receiver"
|
||||||
|
fi
|
||||||
|
|
||||||
|
pkill -f "forward-" 2>/dev/null || true
|
||||||
|
ip netns exec "$NS" pkill iperf3 2>/dev/null || true
|
||||||
|
ip route del "${NS_IP}/32" dev "$TUN_NAME" 2>/dev/null || true
|
||||||
|
ip tuntap del dev "$TUN_NAME" mode tun 2>/dev/null || true
|
||||||
|
sleep 0.8
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── direct baseline ───────────────────────────────────────────────────────────
|
||||||
|
echo ""
|
||||||
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
echo " BASELINE: direct veth (no TUN, no proxy)"
|
||||||
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
ip netns exec "$NS" pkill iperf3 2>/dev/null || true; sleep 0.3
|
||||||
|
ip netns exec "$NS" iperf3 -s -p "$IPERF_PORT" -D \
|
||||||
|
--logfile /tmp/iperf3-bench-server.log; sleep 0.3
|
||||||
|
echo " running iperf3: ${STREAMS} streams × ${DURATION}s …"
|
||||||
|
baseline_out=$(iperf3 -c "$NS_IP" -p "$IPERF_PORT" \
|
||||||
|
-t "$DURATION" -P "$STREAMS" 2>&1)
|
||||||
|
echo "$baseline_out" | grep "SUM.*sender" | awk '{printf " sender: %s %s\n", $6, $7}'
|
||||||
|
echo "$baseline_out" | grep "SUM.*receiver" | awk '{printf " receiver: %s %s\n", $6, $7}'
|
||||||
|
ip netns exec "$NS" pkill iperf3 2>/dev/null || true; sleep 0.5
|
||||||
|
|
||||||
|
# ── tun2 ─────────────────────────────────────────────────────────────────────
|
||||||
|
echo ""
|
||||||
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
echo " tun2 (main branch — no GRO/GSO offload)"
|
||||||
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
run_bench "tun2" /tmp/forward-tun2
|
||||||
|
|
||||||
|
# ── tun-rs + offload ──────────────────────────────────────────────────────────
|
||||||
|
echo ""
|
||||||
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
echo " tun-rs (patched — GRO/GSO offload via IFF_VNET_HDR)"
|
||||||
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
run_bench "tun-rs+offload" /tmp/forward-tun-rs
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
echo " done."
|
||||||
|
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
#!/bin/bash
|
||||||
|
#__author__: cavivie
|
||||||
|
|
||||||
|
DEFAULT_TUN_NAME="utun8"
|
||||||
|
|
||||||
|
function do_route() {
|
||||||
|
local route_op="${1}"
|
||||||
|
local tun_name="${2:-$DEFAULT_TUN_NAME}"
|
||||||
|
ip route ${route_op} 0.0.0.0/1 dev ${tun_name}
|
||||||
|
ip route ${route_op} 128.0.0.0/1 dev ${tun_name}
|
||||||
|
}
|
||||||
|
|
||||||
|
function usage(){
|
||||||
|
echo "Usage:
|
||||||
|
route add add tun routes to system route table
|
||||||
|
route del delete routes from system route table
|
||||||
|
route help display all usages of the shell script"
|
||||||
|
}
|
||||||
|
|
||||||
|
# START MAIN-OPTIONS
|
||||||
|
case $1 in
|
||||||
|
add) do_route add $2;;
|
||||||
|
del) do_route delete $2;;
|
||||||
|
*) usage ;;
|
||||||
|
esac
|
||||||
|
# END MAIN-OPTIONS
|
||||||
|
|
@ -0,0 +1,36 @@
|
||||||
|
#!/bin/bash
|
||||||
|
#__author__: cavivie
|
||||||
|
|
||||||
|
DEFAULT_TUN_ADDR="10.10.10.2/24"
|
||||||
|
DEFAULT_TUN_DEST="10.10.10.1"
|
||||||
|
|
||||||
|
function do_route() {
|
||||||
|
local route_op="${1}"
|
||||||
|
local tun_addr="${2:-$DEFAULT_TUN_ADDR}"
|
||||||
|
local tun_dest="${3:-$DEFAULT_TUN_DEST}"
|
||||||
|
sudo route ${route_op} -net 1.0.0.0/8 ${tun_dest}
|
||||||
|
sudo route ${route_op} -net 2.0.0.0/7 ${tun_dest}
|
||||||
|
sudo route ${route_op} -net 4.0.0.0/6 ${tun_dest}
|
||||||
|
sudo route ${route_op} -net 8.0.0.0/5 ${tun_dest}
|
||||||
|
sudo route ${route_op} -net 16.0.0.0/4 ${tun_dest}
|
||||||
|
sudo route ${route_op} -net 32.0.0.0/3 ${tun_dest}
|
||||||
|
sudo route ${route_op} -net 64.0.0.0/2 ${tun_dest}
|
||||||
|
sudo route ${route_op} -net 128.0.0.0/1 ${tun_dest}
|
||||||
|
# tun2 do like this automatically
|
||||||
|
sudo route ${route_op} -net ${tun_addr} ${tun_dest}
|
||||||
|
}
|
||||||
|
|
||||||
|
function usage(){
|
||||||
|
echo "Usage:
|
||||||
|
route add add tun routes to system route table
|
||||||
|
route del delete routes from system route table
|
||||||
|
route help display all usages of the shell script"
|
||||||
|
}
|
||||||
|
|
||||||
|
# START MAIN-OPTIONS
|
||||||
|
case $1 in
|
||||||
|
add) do_route add $2 $3;;
|
||||||
|
del) do_route delete $2 $3;;
|
||||||
|
*) usage ;;
|
||||||
|
esac
|
||||||
|
# END MAIN-OPTIONS
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
#__author__: cavivie
|
||||||
|
|
||||||
|
param(
|
||||||
|
[string]$Cmd = "help",
|
||||||
|
[string]$TunName = "utun8",
|
||||||
|
[string]$TunGateway = "10.10.10.1"
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
# START MAIN-OPTIONS
|
||||||
|
switch ($Cmd) {
|
||||||
|
"add" {
|
||||||
|
# tun2 do like this automatically
|
||||||
|
New-NetRoute -DestinationPrefix "0.0.0.0/1" -InterfaceAlias $TunName -NextHop "$TunGateway"
|
||||||
|
New-NetRoute -DestinationPrefix "128.0.0.0/1" -InterfaceAlias $TunName -NextHop "$TunGateway"
|
||||||
|
}
|
||||||
|
"del" {
|
||||||
|
# tun2 do like this automatically
|
||||||
|
Get-NetRoute -DestinationPrefix "0.0.0.0/1" -InterfaceAlias $TunName | Remove-NetRoute
|
||||||
|
Get-NetRoute -DestinationPrefix "128.0.0.0/1" -InterfaceAlias $TunName | Remove-NetRoute
|
||||||
|
}
|
||||||
|
default {
|
||||||
|
Write-Host "Usage:
|
||||||
|
route add add tun routes to system route table
|
||||||
|
route del delete routes from system route table
|
||||||
|
route help display all usages of the shell script"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# END MAIN-OPTIONS
|
||||||
|
|
@ -0,0 +1,109 @@
|
||||||
|
use std::sync::{
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
Arc,
|
||||||
|
};
|
||||||
|
|
||||||
|
use smoltcp::{
|
||||||
|
phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken},
|
||||||
|
time::Instant,
|
||||||
|
};
|
||||||
|
use tokio::sync::mpsc::{unbounded_channel, Permit, Sender, UnboundedReceiver, UnboundedSender};
|
||||||
|
|
||||||
|
use crate::packet::AnyIpPktFrame;
|
||||||
|
|
||||||
|
pub(super) struct VirtualDevice {
|
||||||
|
in_buf_avail: Arc<AtomicBool>,
|
||||||
|
in_buf: UnboundedReceiver<Vec<u8>>,
|
||||||
|
out_buf: Sender<AnyIpPktFrame>,
|
||||||
|
mtu: usize,
|
||||||
|
cached_packet: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VirtualDevice {
|
||||||
|
pub(super) fn new(
|
||||||
|
iface_egress_tx: Sender<AnyIpPktFrame>,
|
||||||
|
mtu: usize,
|
||||||
|
) -> (Self, UnboundedSender<Vec<u8>>, Arc<AtomicBool>) {
|
||||||
|
let iface_ingress_tx_avail = Arc::new(AtomicBool::new(false));
|
||||||
|
let (iface_ingress_tx, iface_ingress_rx) = unbounded_channel();
|
||||||
|
(
|
||||||
|
Self {
|
||||||
|
in_buf_avail: iface_ingress_tx_avail.clone(),
|
||||||
|
in_buf: iface_ingress_rx,
|
||||||
|
out_buf: iface_egress_tx,
|
||||||
|
mtu,
|
||||||
|
cached_packet: None,
|
||||||
|
},
|
||||||
|
iface_ingress_tx,
|
||||||
|
iface_ingress_tx_avail,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Device for VirtualDevice {
|
||||||
|
type RxToken<'a> = VirtualRxToken;
|
||||||
|
type TxToken<'a> = VirtualTxToken<'a>;
|
||||||
|
|
||||||
|
fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
|
||||||
|
let buffer = if let Some(buf) = self.cached_packet.take() {
|
||||||
|
buf
|
||||||
|
} else {
|
||||||
|
let Ok(buf) = self.in_buf.try_recv() else {
|
||||||
|
self.in_buf_avail.store(false, Ordering::Release);
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
buf
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(permit) = self.out_buf.try_reserve() else {
|
||||||
|
self.cached_packet = Some(buffer);
|
||||||
|
self.in_buf_avail.store(false, Ordering::Release);
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
|
||||||
|
Some((Self::RxToken { buffer }, Self::TxToken { permit }))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transmit(&mut self, _timestamp: Instant) -> Option<Self::TxToken<'_>> {
|
||||||
|
match self.out_buf.try_reserve() {
|
||||||
|
Ok(permit) => Some(Self::TxToken { permit }),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capabilities(&self) -> DeviceCapabilities {
|
||||||
|
let mut capabilities = DeviceCapabilities::default();
|
||||||
|
capabilities.medium = Medium::Ip;
|
||||||
|
capabilities.max_transmission_unit = self.mtu;
|
||||||
|
capabilities
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct VirtualRxToken {
|
||||||
|
buffer: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RxToken for VirtualRxToken {
|
||||||
|
fn consume<R, F>(self, f: F) -> R
|
||||||
|
where
|
||||||
|
F: FnOnce(&[u8]) -> R,
|
||||||
|
{
|
||||||
|
f(&self.buffer[..])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct VirtualTxToken<'a> {
|
||||||
|
permit: Permit<'a, Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> TxToken for VirtualTxToken<'a> {
|
||||||
|
fn consume<R, F>(self, len: usize, f: F) -> R
|
||||||
|
where
|
||||||
|
F: FnOnce(&mut [u8]) -> R,
|
||||||
|
{
|
||||||
|
let mut buffer = vec![0u8; len];
|
||||||
|
let result = f(&mut buffer);
|
||||||
|
self.permit.send(buffer);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
use std::net::IpAddr;
|
||||||
|
|
||||||
|
pub type IpFilter<'a> = Box<dyn Fn(&IpAddr, &IpAddr) -> bool + Send + Sync + 'a>;
|
||||||
|
|
||||||
|
pub struct IpFilters<'a> {
|
||||||
|
filters: Vec<IpFilter<'a>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Default for IpFilters<'a> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> IpFilters<'a> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
filters: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_non_broadcast() -> Self {
|
||||||
|
macro_rules! non_broadcast {
|
||||||
|
($addr:ident) => {
|
||||||
|
match $addr {
|
||||||
|
IpAddr::V4(a) => !(a.is_broadcast() || a.is_multicast() || a.is_unspecified()),
|
||||||
|
IpAddr::V6(a) => !(a.is_multicast() || a.is_unspecified()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
filters: vec![Box::new(|src, dst| {
|
||||||
|
non_broadcast!(src) && non_broadcast!(dst)
|
||||||
|
})],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add(&mut self, filter: IpFilter<'a>) {
|
||||||
|
self.filters.push(filter);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_fn<F>(&mut self, filter: F)
|
||||||
|
where
|
||||||
|
F: Fn(&IpAddr, &IpAddr) -> bool + Send + Sync + 'a,
|
||||||
|
{
|
||||||
|
self.filters.push(Box::new(filter));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_all<I: IntoIterator<Item = IpFilter<'a>>>(&mut self, filters: I) {
|
||||||
|
self.filters.extend(filters);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_allowed(&self, src: &IpAddr, dst: &IpAddr) -> bool {
|
||||||
|
self.filters.iter().all(|filter| filter(src, dst))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
mod device;
|
||||||
|
|
||||||
|
mod runner;
|
||||||
|
pub use runner::Runner;
|
||||||
|
|
||||||
|
mod packet;
|
||||||
|
pub use packet::AnyIpPktFrame;
|
||||||
|
|
||||||
|
mod filter;
|
||||||
|
pub use filter::{IpFilter, IpFilters};
|
||||||
|
|
||||||
|
pub mod udp;
|
||||||
|
pub use udp::UdpSocket;
|
||||||
|
|
||||||
|
pub mod tcp;
|
||||||
|
pub use tcp::{TcpListener, TcpStream};
|
||||||
|
|
||||||
|
pub mod stack;
|
||||||
|
pub use stack::{Stack, StackBuilder};
|
||||||
|
|
||||||
|
/// Re-export
|
||||||
|
pub use smoltcp;
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
use std::net::IpAddr;
|
||||||
|
|
||||||
|
use smoltcp::wire::{IpProtocol, IpVersion, Ipv4Packet, Ipv6Packet};
|
||||||
|
|
||||||
|
pub type AnyIpPktFrame = Vec<u8>;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(super) enum IpPacket<T: AsRef<[u8]>> {
|
||||||
|
Ipv4(Ipv4Packet<T>),
|
||||||
|
Ipv6(Ipv6Packet<T>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: AsRef<[u8]> + Copy> IpPacket<T> {
|
||||||
|
pub fn new_checked(packet: T) -> smoltcp::wire::Result<IpPacket<T>> {
|
||||||
|
let buffer = packet.as_ref();
|
||||||
|
match IpVersion::of_packet(buffer)? {
|
||||||
|
IpVersion::Ipv4 => Ok(IpPacket::Ipv4(Ipv4Packet::new_checked(packet)?)),
|
||||||
|
IpVersion::Ipv6 => Ok(IpPacket::Ipv6(Ipv6Packet::new_checked(packet)?)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn src_addr(&self) -> IpAddr {
|
||||||
|
match *self {
|
||||||
|
IpPacket::Ipv4(ref packet) => IpAddr::from(packet.src_addr()),
|
||||||
|
IpPacket::Ipv6(ref packet) => IpAddr::from(packet.src_addr()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dst_addr(&self) -> IpAddr {
|
||||||
|
match *self {
|
||||||
|
IpPacket::Ipv4(ref packet) => IpAddr::from(packet.dst_addr()),
|
||||||
|
IpPacket::Ipv6(ref packet) => IpAddr::from(packet.dst_addr()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn protocol(&self) -> IpProtocol {
|
||||||
|
match *self {
|
||||||
|
IpPacket::Ipv4(ref packet) => packet.next_header(),
|
||||||
|
IpPacket::Ipv6(ref packet) => packet.next_header(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: AsRef<[u8]> + ?Sized> IpPacket<&'a T> {
|
||||||
|
/// Return a pointer to the payload.
|
||||||
|
#[inline]
|
||||||
|
pub fn payload(&self) -> &'a [u8] {
|
||||||
|
match *self {
|
||||||
|
IpPacket::Ipv4(ref packet) => packet.payload(),
|
||||||
|
IpPacket::Ipv6(ref packet) => packet.payload(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
use std::{
|
||||||
|
future::{Future, IntoFuture},
|
||||||
|
pin::Pin,
|
||||||
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// BoxFuture acts the same as the [BoxFuture in crate futures utils],
|
||||||
|
/// which is an owned dynamically typed Future for use in cases where you
|
||||||
|
/// can’t statically type your result or need to add some indirection.
|
||||||
|
/// But the difference of this structure is that it will conditionally
|
||||||
|
/// implement Send according to the properties of type T, which does not
|
||||||
|
/// require two sets of API interfaces in single-threaded and multi-threaded.
|
||||||
|
///
|
||||||
|
/// [BoxFuture in crate futures utils]: https://docs.rs/futures-util/latest/futures_util/future/type.BoxFuture.html
|
||||||
|
pub struct BoxFuture<'a, T>(Pin<Box<dyn Future<Output = T> + Send + 'a>>);
|
||||||
|
|
||||||
|
impl<'a, T> BoxFuture<'a, T> {
|
||||||
|
pub fn new<F>(f: F) -> BoxFuture<'a, T>
|
||||||
|
where
|
||||||
|
F: IntoFuture<Output = T> + Send + 'a,
|
||||||
|
F::IntoFuture: Send + 'a,
|
||||||
|
{
|
||||||
|
BoxFuture(Box::pin(f.into_future()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
|
pub fn wrap(f: Pin<Box<dyn Future<Output = T> + Send + 'a>>) -> BoxFuture<'a, T> {
|
||||||
|
BoxFuture(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
impl<T> Future for BoxFuture<'_, T> {
|
||||||
|
type Output = T;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
self.0.as_mut().poll(context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Runner = BoxFuture<'static, std::io::Result<()>>;
|
||||||
|
|
@ -0,0 +1,279 @@
|
||||||
|
use std::{
|
||||||
|
net::IpAddr,
|
||||||
|
pin::Pin,
|
||||||
|
task::{ready, Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
|
use futures::{Sink, Stream};
|
||||||
|
use smoltcp::wire::IpProtocol;
|
||||||
|
use tokio::sync::mpsc::{channel, Receiver};
|
||||||
|
use tokio_util::sync::PollSender;
|
||||||
|
use tracing::{debug, trace};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
filter::{IpFilter, IpFilters},
|
||||||
|
packet::{AnyIpPktFrame, IpPacket},
|
||||||
|
runner::Runner,
|
||||||
|
tcp::TcpListener,
|
||||||
|
udp::UdpSocket,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct StackBuilder {
|
||||||
|
enable_udp: bool,
|
||||||
|
enable_tcp: bool,
|
||||||
|
enable_icmp: bool,
|
||||||
|
stack_buffer_size: usize,
|
||||||
|
udp_buffer_size: usize,
|
||||||
|
tcp_buffer_size: usize,
|
||||||
|
mtu: usize,
|
||||||
|
ip_filters: IpFilters<'static>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for StackBuilder {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
enable_udp: false,
|
||||||
|
enable_tcp: false,
|
||||||
|
enable_icmp: false,
|
||||||
|
stack_buffer_size: 1024,
|
||||||
|
udp_buffer_size: 512,
|
||||||
|
tcp_buffer_size: 512,
|
||||||
|
mtu: 1504, // 1500 for Ethernet + 4 for VLAN
|
||||||
|
ip_filters: IpFilters::with_non_broadcast(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
|
impl StackBuilder {
|
||||||
|
pub fn enable_udp(mut self, enable: bool) -> Self {
|
||||||
|
self.enable_udp = enable;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn enable_tcp(mut self, enable: bool) -> Self {
|
||||||
|
self.enable_tcp = enable;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn enable_icmp(mut self, enable: bool) -> Self {
|
||||||
|
self.enable_icmp = enable;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stack_buffer_size(mut self, size: usize) -> Self {
|
||||||
|
self.stack_buffer_size = size;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn udp_buffer_size(mut self, size: usize) -> Self {
|
||||||
|
self.udp_buffer_size = size;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tcp_buffer_size(mut self, size: usize) -> Self {
|
||||||
|
self.tcp_buffer_size = size;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_ip_filters(mut self, filters: IpFilters<'static>) -> Self {
|
||||||
|
self.ip_filters = filters;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_ip_filter(mut self, filter: IpFilter<'static>) -> Self {
|
||||||
|
self.ip_filters.add(filter);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_ip_filter_fn<F>(mut self, filter: F) -> Self
|
||||||
|
where
|
||||||
|
F: Fn(&IpAddr, &IpAddr) -> bool + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
self.ip_filters.add_fn(filter);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mtu(mut self, mtu: usize) -> Self {
|
||||||
|
self.mtu = mtu;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
pub fn build(
|
||||||
|
self,
|
||||||
|
) -> std::io::Result<(
|
||||||
|
Stack,
|
||||||
|
Option<Runner>,
|
||||||
|
Option<UdpSocket>,
|
||||||
|
Option<TcpListener>,
|
||||||
|
)> {
|
||||||
|
let (stack_tx, stack_rx) = channel(self.stack_buffer_size);
|
||||||
|
|
||||||
|
let (udp_tx, udp_rx) = if self.enable_udp {
|
||||||
|
let (udp_tx, udp_rx) = channel(self.udp_buffer_size);
|
||||||
|
(Some(PollSender::new(udp_tx)), Some(udp_rx))
|
||||||
|
} else {
|
||||||
|
(None, None)
|
||||||
|
};
|
||||||
|
|
||||||
|
let (tcp_tx, tcp_rx) = if self.enable_tcp {
|
||||||
|
let (tcp_tx, tcp_rx) = channel(self.tcp_buffer_size);
|
||||||
|
(Some(PollSender::new(tcp_tx)), Some(tcp_rx))
|
||||||
|
} else {
|
||||||
|
(None, None)
|
||||||
|
};
|
||||||
|
|
||||||
|
// ICMP is handled by TCP's Interface.
|
||||||
|
// smoltcp's interface will always send replies to EchoRequest
|
||||||
|
if self.enable_icmp && !self.enable_tcp {
|
||||||
|
use std::io::{Error, ErrorKind::InvalidInput};
|
||||||
|
return Err(Error::new(InvalidInput, "ICMP requires TCP"));
|
||||||
|
}
|
||||||
|
let icmp_tx = if self.enable_icmp {
|
||||||
|
tcp_tx.clone()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let udp_socket = udp_rx.map(|udp_rx| UdpSocket::new(udp_rx, stack_tx.clone()));
|
||||||
|
|
||||||
|
let (tcp_runner, tcp_listener) = if let Some(tcp_rx) = tcp_rx {
|
||||||
|
let (tcp_runner, tcp_listener) = TcpListener::new(tcp_rx, stack_tx, self.mtu)?;
|
||||||
|
(Some(tcp_runner), Some(tcp_listener))
|
||||||
|
} else {
|
||||||
|
(None, None)
|
||||||
|
};
|
||||||
|
|
||||||
|
let stack = Stack {
|
||||||
|
ip_filters: self.ip_filters,
|
||||||
|
stack_rx,
|
||||||
|
sink_buf: None,
|
||||||
|
udp_tx,
|
||||||
|
tcp_tx,
|
||||||
|
icmp_tx,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok((stack, tcp_runner, udp_socket, tcp_listener))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Stack {
|
||||||
|
ip_filters: IpFilters<'static>,
|
||||||
|
sink_buf: Option<(AnyIpPktFrame, IpProtocol)>,
|
||||||
|
udp_tx: Option<PollSender<AnyIpPktFrame>>,
|
||||||
|
tcp_tx: Option<PollSender<AnyIpPktFrame>>,
|
||||||
|
icmp_tx: Option<PollSender<AnyIpPktFrame>>,
|
||||||
|
stack_rx: Receiver<AnyIpPktFrame>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stack {
|
||||||
|
fn poll_send(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
|
||||||
|
let (item, proto) = match self.sink_buf.take() {
|
||||||
|
Some(val) => val,
|
||||||
|
None => return Poll::Ready(Ok(())),
|
||||||
|
};
|
||||||
|
|
||||||
|
let tx = match proto {
|
||||||
|
IpProtocol::Tcp => self.tcp_tx.as_mut(),
|
||||||
|
IpProtocol::Udp => self.udp_tx.as_mut(),
|
||||||
|
IpProtocol::Icmp | IpProtocol::Icmpv6 => self.icmp_tx.as_mut(),
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(tx) = tx else {
|
||||||
|
return Poll::Ready(Ok(()));
|
||||||
|
};
|
||||||
|
|
||||||
|
match tx.poll_reserve(cx) {
|
||||||
|
Poll::Pending => {
|
||||||
|
self.sink_buf = Some((item, proto));
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
Poll::Ready(Err(_)) => Poll::Ready(Err(channel_closed_err("channel is closed"))),
|
||||||
|
Poll::Ready(Ok(_)) => match tx.send_item(item) {
|
||||||
|
Ok(()) => Poll::Ready(Ok(())),
|
||||||
|
Err(_) => Poll::Ready(Err(channel_closed_err("channel is closed"))),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recv from stack.
|
||||||
|
impl Stream for Stack {
|
||||||
|
type Item = std::io::Result<AnyIpPktFrame>;
|
||||||
|
|
||||||
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||||
|
match self.stack_rx.poll_recv(cx) {
|
||||||
|
Poll::Ready(Some(pkt)) => Poll::Ready(Some(Ok(pkt))),
|
||||||
|
Poll::Ready(None) => Poll::Ready(None),
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send to stack.
|
||||||
|
impl Sink<AnyIpPktFrame> for Stack {
|
||||||
|
type Error = std::io::Error;
|
||||||
|
|
||||||
|
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
// If a buffered item exists, try to flush it first. This also properly
|
||||||
|
// registers the waker via poll_reserve so we get woken when the channel
|
||||||
|
// has capacity. Without this, returning Pending here with _cx unused
|
||||||
|
// means the task never gets rescheduled.
|
||||||
|
if self.sink_buf.is_some() {
|
||||||
|
ready!(self.poll_send(cx))?;
|
||||||
|
}
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_send(mut self: Pin<&mut Self>, item: AnyIpPktFrame) -> Result<(), Self::Error> {
|
||||||
|
if item.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
use std::io::{Error, ErrorKind::InvalidInput};
|
||||||
|
let packet = IpPacket::new_checked(item.as_slice())
|
||||||
|
.map_err(|err| Error::new(InvalidInput, format!("invalid IP packet: {err}")))?;
|
||||||
|
|
||||||
|
let src_ip = packet.src_addr();
|
||||||
|
let dst_ip = packet.dst_addr();
|
||||||
|
|
||||||
|
let addr_allowed = self.ip_filters.is_allowed(&src_ip, &dst_ip);
|
||||||
|
if !addr_allowed {
|
||||||
|
trace!("IP packet {src_ip} -> {dst_ip} (allowed? {addr_allowed}) throwing away",);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let protocol = packet.protocol();
|
||||||
|
if matches!(
|
||||||
|
protocol,
|
||||||
|
IpProtocol::Tcp | IpProtocol::Udp | IpProtocol::Icmp | IpProtocol::Icmpv6
|
||||||
|
) {
|
||||||
|
self.sink_buf.replace((item, protocol));
|
||||||
|
} else {
|
||||||
|
debug!("tun IP packet ignored (protocol: {:?})", protocol);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
self.poll_send(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_close(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
_cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Result<(), Self::Error>> {
|
||||||
|
self.stack_rx.close();
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn channel_closed_err<E>(err: E) -> std::io::Error
|
||||||
|
where
|
||||||
|
E: Into<Box<dyn std::error::Error + Send + Sync>>,
|
||||||
|
{
|
||||||
|
std::io::Error::new(std::io::ErrorKind::BrokenPipe, err)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,564 @@
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
net::SocketAddr,
|
||||||
|
pin::Pin,
|
||||||
|
sync::{
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
Arc,
|
||||||
|
},
|
||||||
|
task::{Context, Poll, Waker},
|
||||||
|
};
|
||||||
|
|
||||||
|
use futures::Stream;
|
||||||
|
use smoltcp::{
|
||||||
|
iface::{Config as InterfaceConfig, Interface, SocketHandle, SocketSet},
|
||||||
|
phy::Device,
|
||||||
|
socket::tcp::{Socket as TcpSocket, SocketBuffer as TcpSocketBuffer, State as TcpState},
|
||||||
|
storage::RingBuffer,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
wire::{HardwareAddress, IpAddress, IpCidr, IpProtocol, Ipv4Address, Ipv6Address, TcpPacket},
|
||||||
|
};
|
||||||
|
use spin::Mutex as SpinMutex;
|
||||||
|
use tokio::{
|
||||||
|
io::{AsyncRead, AsyncWrite, ReadBuf},
|
||||||
|
sync::{
|
||||||
|
mpsc::{channel, Receiver, Sender, UnboundedSender},
|
||||||
|
Notify,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use tracing::{error, trace};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
device::VirtualDevice,
|
||||||
|
packet::{AnyIpPktFrame, IpPacket},
|
||||||
|
Runner,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Reduced buffer sizes to 16KB to prevent excessive memory overhead (was 0x3FFF * 20 = 327KB per buffer)
|
||||||
|
const DEFAULT_TCP_SEND_BUFFER_SIZE: u32 = 16384;
|
||||||
|
const DEFAULT_TCP_RECV_BUFFER_SIZE: u32 = 16384;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||||
|
enum TcpSocketState {
|
||||||
|
Normal,
|
||||||
|
Close,
|
||||||
|
Closing,
|
||||||
|
Closed,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TcpSocketControl {
|
||||||
|
send_buffer: RingBuffer<'static, u8>,
|
||||||
|
send_waker: Option<Waker>,
|
||||||
|
recv_buffer: RingBuffer<'static, u8>,
|
||||||
|
recv_waker: Option<Waker>,
|
||||||
|
recv_state: TcpSocketState,
|
||||||
|
send_state: TcpSocketState,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TcpSocketCreation {
|
||||||
|
control: SharedControl,
|
||||||
|
socket: TcpSocket<'static>,
|
||||||
|
}
|
||||||
|
|
||||||
|
type SharedNotify = Arc<Notify>;
|
||||||
|
type SharedControl = Arc<SpinMutex<TcpSocketControl>>;
|
||||||
|
|
||||||
|
struct TcpListenerRunner;
|
||||||
|
|
||||||
|
impl TcpListenerRunner {
|
||||||
|
fn create(
|
||||||
|
device: VirtualDevice,
|
||||||
|
iface: Interface,
|
||||||
|
iface_ingress_tx: UnboundedSender<Vec<u8>>,
|
||||||
|
iface_ingress_tx_avail: Arc<AtomicBool>,
|
||||||
|
tcp_rx: Receiver<AnyIpPktFrame>,
|
||||||
|
stream_tx: Sender<TcpStream>,
|
||||||
|
sockets: HashMap<SocketHandle, SharedControl>,
|
||||||
|
) -> Runner {
|
||||||
|
Runner::new(async move {
|
||||||
|
let notify = Arc::new(Notify::new());
|
||||||
|
let (socket_tx, socket_rx) = channel::<TcpSocketCreation>(1024);
|
||||||
|
let res = tokio::select! {
|
||||||
|
v = Self::handle_packet(notify.clone(), iface_ingress_tx, iface_ingress_tx_avail.clone(), tcp_rx, stream_tx, socket_tx) => v,
|
||||||
|
v = Self::handle_socket(notify, device, iface, iface_ingress_tx_avail, sockets, socket_rx) => v,
|
||||||
|
};
|
||||||
|
res?;
|
||||||
|
trace!("VirtDevice::poll thread exited");
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_packet(
|
||||||
|
notify: SharedNotify,
|
||||||
|
iface_ingress_tx: UnboundedSender<Vec<u8>>,
|
||||||
|
iface_ingress_tx_avail: Arc<AtomicBool>,
|
||||||
|
mut tcp_rx: Receiver<AnyIpPktFrame>,
|
||||||
|
stream_tx: Sender<TcpStream>,
|
||||||
|
socket_tx: Sender<TcpSocketCreation>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
while let Some(frame) = tcp_rx.recv().await {
|
||||||
|
let packet = match IpPacket::new_checked(frame.as_slice()) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(err) => {
|
||||||
|
error!("invalid TCP IP packet: {:?}", err,);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Specially handle icmp packet by TCP interface.
|
||||||
|
if matches!(packet.protocol(), IpProtocol::Icmp | IpProtocol::Icmpv6) {
|
||||||
|
iface_ingress_tx
|
||||||
|
.send(frame)
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e))?;
|
||||||
|
iface_ingress_tx_avail.store(true, Ordering::Release);
|
||||||
|
notify.notify_one();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let src_ip = packet.src_addr();
|
||||||
|
let dst_ip = packet.dst_addr();
|
||||||
|
let payload = packet.payload();
|
||||||
|
|
||||||
|
let packet = match TcpPacket::new_checked(payload) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(err) => {
|
||||||
|
error!("invalid TCP err: {err}, src_ip: {src_ip}, dst_ip: {dst_ip}, payload: {payload:?}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let src_port = packet.src_port();
|
||||||
|
let dst_port = packet.dst_port();
|
||||||
|
|
||||||
|
let src_addr = SocketAddr::new(src_ip, src_port);
|
||||||
|
let dst_addr = SocketAddr::new(dst_ip, dst_port);
|
||||||
|
|
||||||
|
// TCP first handshake packet, create a new Connection
|
||||||
|
if packet.syn() && !packet.ack() {
|
||||||
|
let mut socket = TcpSocket::new(
|
||||||
|
TcpSocketBuffer::new(vec![0u8; DEFAULT_TCP_RECV_BUFFER_SIZE as usize]),
|
||||||
|
TcpSocketBuffer::new(vec![0u8; DEFAULT_TCP_SEND_BUFFER_SIZE as usize]),
|
||||||
|
);
|
||||||
|
socket.set_keep_alive(Some(Duration::from_secs(28)));
|
||||||
|
// FIXME: It should follow system's setting. 7200 is Linux's default.
|
||||||
|
socket.set_timeout(Some(Duration::from_secs(7200)));
|
||||||
|
// NO ACK delay
|
||||||
|
// socket.set_ack_delay(None);
|
||||||
|
|
||||||
|
if let Err(err) = socket.listen(dst_addr) {
|
||||||
|
error!("listen error: {:?}", err);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
trace!("created TCP connection for {} <-> {}", src_addr, dst_addr);
|
||||||
|
|
||||||
|
let control = Arc::new(SpinMutex::new(TcpSocketControl {
|
||||||
|
send_buffer: RingBuffer::new(vec![0u8; DEFAULT_TCP_SEND_BUFFER_SIZE as usize]),
|
||||||
|
send_waker: None,
|
||||||
|
recv_buffer: RingBuffer::new(vec![0u8; DEFAULT_TCP_RECV_BUFFER_SIZE as usize]),
|
||||||
|
recv_waker: None,
|
||||||
|
recv_state: TcpSocketState::Normal,
|
||||||
|
send_state: TcpSocketState::Normal,
|
||||||
|
}));
|
||||||
|
|
||||||
|
if let Err(_) = stream_tx.try_send(TcpStream {
|
||||||
|
src_addr,
|
||||||
|
dst_addr,
|
||||||
|
notify: notify.clone(),
|
||||||
|
control: control.clone(),
|
||||||
|
}) {
|
||||||
|
error!("stream_tx full or dropped, dropping SYN from {}", src_addr);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(_) = socket_tx.try_send(TcpSocketCreation { control, socket }) {
|
||||||
|
error!("socket_tx full or dropped, dropping SYN from {}", src_addr);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pipeline tcp stream packet
|
||||||
|
iface_ingress_tx
|
||||||
|
.send(frame)
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e))?;
|
||||||
|
iface_ingress_tx_avail.store(true, Ordering::Release);
|
||||||
|
notify.notify_one();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_socket(
|
||||||
|
notify: SharedNotify,
|
||||||
|
mut device: VirtualDevice,
|
||||||
|
mut iface: Interface,
|
||||||
|
iface_ingress_tx_avail: Arc<AtomicBool>,
|
||||||
|
mut sockets: HashMap<SocketHandle, SharedControl>,
|
||||||
|
mut socket_rx: Receiver<TcpSocketCreation>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let mut socket_set = SocketSet::new(vec![]);
|
||||||
|
loop {
|
||||||
|
while let Ok(TcpSocketCreation { control, socket }) = socket_rx.try_recv() {
|
||||||
|
let handle = socket_set.add(socket);
|
||||||
|
sockets.insert(handle, control);
|
||||||
|
}
|
||||||
|
|
||||||
|
let before_poll = Instant::now();
|
||||||
|
let updated_sockets = iface.poll(before_poll, &mut device, &mut socket_set);
|
||||||
|
if matches!(
|
||||||
|
updated_sockets,
|
||||||
|
smoltcp::iface::PollResult::SocketStateChanged
|
||||||
|
) {
|
||||||
|
trace!("VirtDevice::poll costed {}", Instant::now() - before_poll);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check all the sockets' status
|
||||||
|
let mut sockets_to_remove = Vec::new();
|
||||||
|
|
||||||
|
for (socket_handle, control) in sockets.iter() {
|
||||||
|
let socket_handle = *socket_handle;
|
||||||
|
let socket = socket_set.get_mut::<TcpSocket>(socket_handle);
|
||||||
|
let mut control = control.lock();
|
||||||
|
|
||||||
|
// Remove the socket only when it is in the closed state.
|
||||||
|
if socket.state() == TcpState::Closed {
|
||||||
|
sockets_to_remove.push(socket_handle);
|
||||||
|
|
||||||
|
control.send_state = TcpSocketState::Closed;
|
||||||
|
control.recv_state = TcpSocketState::Closed;
|
||||||
|
|
||||||
|
if let Some(waker) = control.send_waker.take() {
|
||||||
|
waker.wake();
|
||||||
|
}
|
||||||
|
if let Some(waker) = control.recv_waker.take() {
|
||||||
|
waker.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
trace!("closed TCP connection");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SHUT_WR — only close once the send_buffer has been fully
|
||||||
|
// drained into the smoltcp socket. Closing earlier transitions
|
||||||
|
// the socket to FIN_WAIT_1, making can_send() return false, so
|
||||||
|
// the send loop below never runs and the remaining data is lost.
|
||||||
|
if matches!(control.send_state, TcpSocketState::Close)
|
||||||
|
&& control.send_buffer.is_empty()
|
||||||
|
{
|
||||||
|
trace!("closing TCP Write Half, {:?}", socket.state());
|
||||||
|
|
||||||
|
socket.close();
|
||||||
|
control.send_state = TcpSocketState::Closing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if readable
|
||||||
|
let mut wake_receiver = false;
|
||||||
|
while socket.can_recv() && !control.recv_buffer.is_full() {
|
||||||
|
let result = socket.recv(|buffer| {
|
||||||
|
let n = control.recv_buffer.enqueue_slice(buffer);
|
||||||
|
(n, ())
|
||||||
|
});
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(..) => wake_receiver = true,
|
||||||
|
Err(err) => {
|
||||||
|
error!("socket recv error: {:?}, {:?}", err, socket.state());
|
||||||
|
|
||||||
|
// Don't know why. Abort the connection.
|
||||||
|
socket.abort();
|
||||||
|
|
||||||
|
if matches!(control.recv_state, TcpSocketState::Normal) {
|
||||||
|
control.recv_state = TcpSocketState::Closed;
|
||||||
|
}
|
||||||
|
wake_receiver = true;
|
||||||
|
|
||||||
|
// The socket will be recycled in the next poll.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If socket is not in ESTABLISH, FIN-WAIT-1, FIN-WAIT-2,
|
||||||
|
// the local client have closed our receiver.
|
||||||
|
let states = [
|
||||||
|
TcpState::Listen,
|
||||||
|
TcpState::SynReceived,
|
||||||
|
TcpState::Established,
|
||||||
|
TcpState::FinWait1,
|
||||||
|
TcpState::FinWait2,
|
||||||
|
];
|
||||||
|
if matches!(control.recv_state, TcpSocketState::Normal)
|
||||||
|
&& !socket.may_recv()
|
||||||
|
&& !states.contains(&socket.state())
|
||||||
|
{
|
||||||
|
trace!("closed TCP Read Half, {:?}", socket.state());
|
||||||
|
|
||||||
|
// Let TcpStream::poll_read returns EOF.
|
||||||
|
control.recv_state = TcpSocketState::Closed;
|
||||||
|
wake_receiver = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if wake_receiver && control.recv_waker.is_some() {
|
||||||
|
if let Some(waker) = control.recv_waker.take() {
|
||||||
|
waker.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if writable
|
||||||
|
let mut wake_sender = false;
|
||||||
|
while socket.can_send() && !control.send_buffer.is_empty() {
|
||||||
|
let result = socket.send(|buffer| {
|
||||||
|
let n = control.send_buffer.dequeue_slice(buffer);
|
||||||
|
(n, ())
|
||||||
|
});
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(..) => wake_sender = true,
|
||||||
|
Err(err) => {
|
||||||
|
error!("socket send error: {:?}, {:?}", err, socket.state());
|
||||||
|
|
||||||
|
// Don't know why. Abort the connection.
|
||||||
|
socket.abort();
|
||||||
|
|
||||||
|
if matches!(control.send_state, TcpSocketState::Normal) {
|
||||||
|
control.send_state = TcpSocketState::Closed;
|
||||||
|
}
|
||||||
|
wake_sender = true;
|
||||||
|
|
||||||
|
// The socket will be recycled in the next poll.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if wake_sender && control.send_waker.is_some() {
|
||||||
|
if let Some(waker) = control.send_waker.take() {
|
||||||
|
waker.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for socket_handle in sockets_to_remove {
|
||||||
|
sockets.remove(&socket_handle);
|
||||||
|
socket_set.remove(socket_handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !iface_ingress_tx_avail.load(Ordering::Acquire) {
|
||||||
|
let next_duration = iface
|
||||||
|
.poll_delay(before_poll, &socket_set)
|
||||||
|
.unwrap_or(Duration::from_millis(5));
|
||||||
|
if next_duration != Duration::ZERO {
|
||||||
|
let _ = tokio::time::timeout(
|
||||||
|
tokio::time::Duration::from(next_duration),
|
||||||
|
notify.notified(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TcpListener {
|
||||||
|
stream_rx: Receiver<TcpStream>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TcpListener {
|
||||||
|
pub(super) fn new(
|
||||||
|
tcp_rx: Receiver<AnyIpPktFrame>,
|
||||||
|
stack_tx: Sender<AnyIpPktFrame>,
|
||||||
|
mtu: usize,
|
||||||
|
) -> std::io::Result<(Runner, Self)> {
|
||||||
|
let (mut device, iface_ingress_tx, iface_ingress_tx_avail) =
|
||||||
|
VirtualDevice::new(stack_tx, mtu);
|
||||||
|
let iface = Self::create_interface(&mut device)?;
|
||||||
|
|
||||||
|
let (stream_tx, stream_rx) = channel(1024);
|
||||||
|
|
||||||
|
let runner = TcpListenerRunner::create(
|
||||||
|
device,
|
||||||
|
iface,
|
||||||
|
iface_ingress_tx,
|
||||||
|
iface_ingress_tx_avail,
|
||||||
|
tcp_rx,
|
||||||
|
stream_tx,
|
||||||
|
HashMap::new(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok((runner, Self { stream_rx }))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_interface<D>(device: &mut D) -> std::io::Result<Interface>
|
||||||
|
where
|
||||||
|
D: Device + ?Sized,
|
||||||
|
{
|
||||||
|
let mut iface_config = InterfaceConfig::new(HardwareAddress::Ip);
|
||||||
|
iface_config.random_seed = rand::random();
|
||||||
|
let mut iface = Interface::new(iface_config, device, Instant::now());
|
||||||
|
iface.update_ip_addrs(|ip_addrs| {
|
||||||
|
ip_addrs
|
||||||
|
.push(IpCidr::new(IpAddress::v4(0, 0, 0, 1), 0))
|
||||||
|
.expect("iface IPv4");
|
||||||
|
ip_addrs
|
||||||
|
.push(IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 0))
|
||||||
|
.expect("iface IPv6");
|
||||||
|
});
|
||||||
|
iface
|
||||||
|
.routes_mut()
|
||||||
|
.add_default_ipv4_route(Ipv4Address::new(0, 0, 0, 1))
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::AddrNotAvailable, e))?;
|
||||||
|
iface
|
||||||
|
.routes_mut()
|
||||||
|
.add_default_ipv6_route(Ipv6Address::new(0, 0, 0, 0, 0, 0, 0, 1))
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::AddrNotAvailable, e))?;
|
||||||
|
iface.set_any_ip(true);
|
||||||
|
Ok(iface)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream for TcpListener {
|
||||||
|
type Item = (TcpStream, SocketAddr, SocketAddr);
|
||||||
|
|
||||||
|
fn poll_next(
|
||||||
|
mut self: std::pin::Pin<&mut Self>,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Option<Self::Item>> {
|
||||||
|
self.stream_rx.poll_recv(cx).map(|stream| {
|
||||||
|
stream.map(|stream| {
|
||||||
|
let local_addr = *stream.local_addr();
|
||||||
|
let remote_addr: SocketAddr = *stream.remote_addr();
|
||||||
|
(stream, local_addr, remote_addr)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TcpStream {
|
||||||
|
src_addr: SocketAddr,
|
||||||
|
dst_addr: SocketAddr,
|
||||||
|
notify: SharedNotify,
|
||||||
|
control: SharedControl,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TcpStream {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let mut control = self.control.lock();
|
||||||
|
|
||||||
|
if matches!(control.recv_state, TcpSocketState::Normal) {
|
||||||
|
control.recv_state = TcpSocketState::Close;
|
||||||
|
}
|
||||||
|
|
||||||
|
if matches!(control.send_state, TcpSocketState::Normal) {
|
||||||
|
control.send_state = TcpSocketState::Close;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.notify.notify_one();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TcpStream {
|
||||||
|
pub fn local_addr(&self) -> &SocketAddr {
|
||||||
|
&self.src_addr
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remote_addr(&self) -> &SocketAddr {
|
||||||
|
&self.dst_addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncRead for TcpStream {
|
||||||
|
fn poll_read(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &mut ReadBuf<'_>,
|
||||||
|
) -> Poll<std::io::Result<()>> {
|
||||||
|
let mut control = self.control.lock();
|
||||||
|
|
||||||
|
// Read from buffer
|
||||||
|
if control.recv_buffer.is_empty() {
|
||||||
|
// If socket is already closed / half closed, just return EOF directly.
|
||||||
|
if matches!(control.recv_state, TcpSocketState::Closed) {
|
||||||
|
return Ok(()).into();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nothing could be read. Wait for notify.
|
||||||
|
if let Some(old_waker) = control.recv_waker.replace(cx.waker().clone()) {
|
||||||
|
if !old_waker.will_wake(cx.waker()) {
|
||||||
|
old_waker.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Poll::Pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
let recv_buf = buf.initialize_unfilled();
|
||||||
|
let n = control.recv_buffer.dequeue_slice(recv_buf);
|
||||||
|
buf.advance(n);
|
||||||
|
|
||||||
|
if n > 0 {
|
||||||
|
self.notify.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(()).into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWrite for TcpStream {
|
||||||
|
fn poll_write(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &[u8],
|
||||||
|
) -> Poll<std::io::Result<usize>> {
|
||||||
|
let mut control = self.control.lock();
|
||||||
|
|
||||||
|
// If state == Close | Closing | Closed, the TCP stream WR half is closed.
|
||||||
|
if !matches!(control.send_state, TcpSocketState::Normal) {
|
||||||
|
return Err(std::io::ErrorKind::BrokenPipe.into()).into();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write to buffer
|
||||||
|
|
||||||
|
if control.send_buffer.is_full() {
|
||||||
|
if let Some(old_waker) = control.send_waker.replace(cx.waker().clone()) {
|
||||||
|
if !old_waker.will_wake(cx.waker()) {
|
||||||
|
old_waker.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Poll::Pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
let n = control.send_buffer.enqueue_slice(buf);
|
||||||
|
|
||||||
|
if n > 0 {
|
||||||
|
self.notify.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(n).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
Ok(()).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
let mut control = self.control.lock();
|
||||||
|
|
||||||
|
if matches!(control.send_state, TcpSocketState::Closed | TcpSocketState::Closing) {
|
||||||
|
return Ok(()).into();
|
||||||
|
}
|
||||||
|
|
||||||
|
// SHUT_WR
|
||||||
|
if matches!(control.send_state, TcpSocketState::Normal) {
|
||||||
|
control.send_state = TcpSocketState::Close;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(old_waker) = control.send_waker.replace(cx.waker().clone()) {
|
||||||
|
if !old_waker.will_wake(cx.waker()) {
|
||||||
|
old_waker.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.notify.notify_one();
|
||||||
|
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,155 @@
|
||||||
|
use std::{
|
||||||
|
net::SocketAddr,
|
||||||
|
pin::Pin,
|
||||||
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
|
use etherparse::PacketBuilder;
|
||||||
|
use futures::{ready, Sink, SinkExt, Stream};
|
||||||
|
use smoltcp::wire::UdpPacket;
|
||||||
|
use tokio::sync::mpsc::{Receiver, Sender};
|
||||||
|
use tokio_util::sync::PollSender;
|
||||||
|
use tracing::{error, trace};
|
||||||
|
|
||||||
|
use crate::packet::{AnyIpPktFrame, IpPacket};
|
||||||
|
|
||||||
|
pub type UdpMsg = (
|
||||||
|
Vec<u8>, /* payload */
|
||||||
|
SocketAddr, /* local */
|
||||||
|
SocketAddr, /* remote */
|
||||||
|
);
|
||||||
|
|
||||||
|
pub struct UdpSocket {
|
||||||
|
udp_rx: Receiver<AnyIpPktFrame>,
|
||||||
|
stack_tx: PollSender<AnyIpPktFrame>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UdpSocket {
|
||||||
|
pub(super) fn new(udp_rx: Receiver<AnyIpPktFrame>, stack_tx: Sender<AnyIpPktFrame>) -> Self {
|
||||||
|
Self {
|
||||||
|
udp_rx,
|
||||||
|
stack_tx: PollSender::new(stack_tx),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn split(self) -> (ReadHalf, WriteHalf) {
|
||||||
|
(
|
||||||
|
ReadHalf {
|
||||||
|
udp_rx: self.udp_rx,
|
||||||
|
},
|
||||||
|
WriteHalf {
|
||||||
|
stack_tx: self.stack_tx,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ReadHalf {
|
||||||
|
udp_rx: Receiver<AnyIpPktFrame>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WriteHalf {
|
||||||
|
stack_tx: PollSender<AnyIpPktFrame>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream for ReadHalf {
|
||||||
|
type Item = UdpMsg;
|
||||||
|
|
||||||
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
|
||||||
|
loop {
|
||||||
|
match ready!(self.udp_rx.poll_recv(cx)) {
|
||||||
|
Some(frame) => {
|
||||||
|
let packet = match IpPacket::new_checked(frame.as_slice()) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(err) => {
|
||||||
|
error!("invalid IP packet: {}", err);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let src_ip = packet.src_addr();
|
||||||
|
let dst_ip = packet.dst_addr();
|
||||||
|
let payload = packet.payload();
|
||||||
|
|
||||||
|
let packet = match UdpPacket::new_checked(payload) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(err) => {
|
||||||
|
error!("invalid err: {err}, src_ip: {src_ip}, dst_ip: {dst_ip}, payload: {payload:?}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let src_port = packet.src_port();
|
||||||
|
let dst_port = packet.dst_port();
|
||||||
|
|
||||||
|
let src_addr = SocketAddr::new(src_ip, src_port);
|
||||||
|
let dst_addr = SocketAddr::new(dst_ip, dst_port);
|
||||||
|
|
||||||
|
trace!("created UDP socket for {} <-> {}", src_addr, dst_addr);
|
||||||
|
|
||||||
|
return Poll::Ready(Some((packet.payload().to_vec(), src_addr, dst_addr)));
|
||||||
|
}
|
||||||
|
None => return Poll::Ready(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sink<UdpMsg> for WriteHalf {
|
||||||
|
type Error = std::io::Error;
|
||||||
|
|
||||||
|
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
match ready!(self.stack_tx.poll_ready_unpin(cx)) {
|
||||||
|
Ok(()) => Poll::Ready(Ok(())),
|
||||||
|
Err(err) => Poll::Ready(Err(std::io::Error::other(err))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_send(mut self: Pin<&mut Self>, item: UdpMsg) -> Result<(), Self::Error> {
|
||||||
|
use std::io::{Error, ErrorKind::InvalidData};
|
||||||
|
let (data, src_addr, dst_addr) = item;
|
||||||
|
|
||||||
|
if data.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let builder = match (src_addr, dst_addr) {
|
||||||
|
(SocketAddr::V4(src), SocketAddr::V4(dst)) => {
|
||||||
|
PacketBuilder::ipv4(src.ip().octets(), dst.ip().octets(), 20)
|
||||||
|
.udp(src_addr.port(), dst_addr.port())
|
||||||
|
}
|
||||||
|
(SocketAddr::V6(src), SocketAddr::V6(dst)) => {
|
||||||
|
PacketBuilder::ipv6(src.ip().octets(), dst.ip().octets(), 20)
|
||||||
|
.udp(src_addr.port(), dst_addr.port())
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
return Err(Error::new(InvalidData, "src or destination type unmatch"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut ip_packet_writer = Vec::with_capacity(builder.size(data.len()));
|
||||||
|
builder
|
||||||
|
.write(&mut ip_packet_writer, &data)
|
||||||
|
.map_err(|err| Error::other(format!("PacketBuilder::write: {err}")))?;
|
||||||
|
|
||||||
|
match self.stack_tx.start_send_unpin(ip_packet_writer) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(err) => Err(Error::other(format!("send error: {err}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
use std::io::Error;
|
||||||
|
match ready!(self.stack_tx.poll_flush_unpin(cx)) {
|
||||||
|
Ok(()) => Poll::Ready(Ok(())),
|
||||||
|
Err(err) => Poll::Ready(Err(Error::other(format!("flush error: {err}")))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
use std::io::Error;
|
||||||
|
match ready!(self.stack_tx.poll_close_unpin(cx)) {
|
||||||
|
Ok(()) => Poll::Ready(Ok(())),
|
||||||
|
Err(err) => Poll::Ready(Err(Error::other(format!("close error: {err}")))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,75 @@
|
||||||
|
//! Regression tests that reproduce the bugs found in the static analysis.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use etherparse::{IpNumber, Ipv4Header, UdpHeader};
|
||||||
|
use futures::SinkExt;
|
||||||
|
use tokio::time::timeout;
|
||||||
|
|
||||||
|
use netstack_smoltcp::StackBuilder;
|
||||||
|
|
||||||
|
fn make_udp_ipv4(
|
||||||
|
src_ip: [u8; 4],
|
||||||
|
src_port: u16,
|
||||||
|
dst_ip: [u8; 4],
|
||||||
|
dst_port: u16,
|
||||||
|
payload: &[u8],
|
||||||
|
) -> Vec<u8> {
|
||||||
|
let udp_hdr = UdpHeader::with_ipv4_checksum(
|
||||||
|
src_port,
|
||||||
|
dst_port,
|
||||||
|
&Ipv4Header::new(
|
||||||
|
(UdpHeader::LEN + payload.len()) as u16,
|
||||||
|
64,
|
||||||
|
IpNumber::UDP,
|
||||||
|
src_ip,
|
||||||
|
dst_ip,
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let ip_hdr = Ipv4Header::new(
|
||||||
|
(UdpHeader::LEN + payload.len()) as u16,
|
||||||
|
64,
|
||||||
|
IpNumber::UDP,
|
||||||
|
src_ip,
|
||||||
|
dst_ip,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut buf = Vec::with_capacity(Ipv4Header::MIN_LEN + UdpHeader::LEN + payload.len());
|
||||||
|
ip_hdr.write(&mut buf).unwrap();
|
||||||
|
udp_hdr.write(&mut buf).unwrap();
|
||||||
|
buf.extend_from_slice(payload);
|
||||||
|
buf
|
||||||
|
}
|
||||||
|
|
||||||
|
/// before(include) a15e0b72bfc72cb032e67138070da01e325d66f8
|
||||||
|
/// sink_buf is used in `Stack` to hold a slot for sending any pkt
|
||||||
|
///
|
||||||
|
/// the original assumption is that the `poll_ready` -> `start_send` -> `poll_flush`
|
||||||
|
/// are called sequentially so the slot could be reused and will never get blocked.
|
||||||
|
///
|
||||||
|
/// but once the user calls `send_all` on `Stack`, which will not immediate flush the pkt(call `poll_flush`),
|
||||||
|
/// then `sink_buf` is could be Some(pkt), then it will trigger `Poll::Pending` branch in `Stack::poll_ready`,
|
||||||
|
/// who did not register the waker correctly, so it will got hanged forever.
|
||||||
|
#[tokio::test(flavor = "current_thread")]
|
||||||
|
async fn bug1_poll_ready_waker_registered_via_send_all() {
|
||||||
|
let (mut stack, _runner, _udp_socket, _tcp) = StackBuilder::default()
|
||||||
|
.enable_udp(true)
|
||||||
|
.udp_buffer_size(64)
|
||||||
|
.stack_buffer_size(64)
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let pkt1 = make_udp_ipv4([1, 2, 3, 4], 1111, [5, 6, 7, 8], 9999, b"first");
|
||||||
|
let pkt2 = make_udp_ipv4([1, 2, 3, 4], 1111, [5, 6, 7, 8], 9999, b"second");
|
||||||
|
|
||||||
|
let mut stream = futures::stream::iter([Ok(pkt1), Ok(pkt2)]);
|
||||||
|
|
||||||
|
let result = timeout(Duration::from_secs(1), stack.send_all(&mut stream)).await;
|
||||||
|
// should be ok after the fix
|
||||||
|
assert!(result.is_ok());
|
||||||
|
}
|
||||||
|
|
@ -9,7 +9,10 @@ anyhow.workspace = true
|
||||||
bytes.workspace = true
|
bytes.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
tracing-appender = "0.2"
|
||||||
ostp-core = { path = "../ostp-core" }
|
ostp-core = { path = "../ostp-core" }
|
||||||
|
ostp-tun = { path = "../ostp-tun" }
|
||||||
rand.workspace = true
|
rand.workspace = true
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
|
@ -17,11 +20,20 @@ json_comments = "0.2"
|
||||||
portable-atomic.workspace = true
|
portable-atomic.workspace = true
|
||||||
chrono = "0.4"
|
chrono = "0.4"
|
||||||
socket2 = "0.6.3"
|
socket2 = "0.6.3"
|
||||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
|
|
||||||
tokio-rustls = { version = "0.26", default-features = false, features = ["ring"] }
|
|
||||||
futures-util = "0.3.32"
|
futures-util = "0.3.32"
|
||||||
hmac = "0.12.1"
|
hmac = "0.12.1"
|
||||||
sha2 = "0.10.8"
|
sha2 = "0.10.8"
|
||||||
base64 = "0.22.1"
|
base64 = "0.22.1"
|
||||||
webpki-roots = "0.26"
|
webpki-roots = "0.26"
|
||||||
rustls-pki-types = "1.7"
|
tun = { version = "0.8.9", features = ["async"] }
|
||||||
|
netstack-smoltcp = "0.2.2"
|
||||||
|
futures = "0.3.32"
|
||||||
|
libc = "0.2.186"
|
||||||
|
x25519-dalek = "2.0.1"
|
||||||
|
chacha20poly1305.workspace = true
|
||||||
|
hex = "0.4.3"
|
||||||
|
winapi = { version = "0.3.9", features = ["iphlpapi", "tcpmib", "processthreadsapi", "psapi", "handleapi", "winerror", "minwindef", "winnt", "iptypes", "ws2def", "ws2tcpip", "winsock2"] }
|
||||||
|
ipnet = "2.12.0"
|
||||||
|
|
||||||
|
[target."cfg(unix)".dependencies]
|
||||||
|
libc = "0.2.186"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
fn main() {
|
||||||
|
let socket = std::net::UdpSocket::bind("0.0.0.0:0").unwrap();
|
||||||
|
let port = socket.local_addr().unwrap().port();
|
||||||
|
println!("Bound UDP to port {}", port);
|
||||||
|
|
||||||
|
if let Some(name) = ostp_client::tunnel::process_lookup::get_process_name_from_port_udp(port) {
|
||||||
|
println!("Found process for UDP port {}: {}", port, name);
|
||||||
|
} else {
|
||||||
|
println!("Process not found for UDP port {}", port);
|
||||||
|
}
|
||||||
|
|
||||||
|
let tcp_socket = std::net::TcpListener::bind("0.0.0.0:0").unwrap();
|
||||||
|
let tcp_port = tcp_socket.local_addr().unwrap().port();
|
||||||
|
println!("Bound TCP to port {}", tcp_port);
|
||||||
|
|
||||||
|
if let Some(name) = ostp_client::tunnel::process_lookup::get_process_name_from_port(tcp_port) {
|
||||||
|
println!("Found process for TCP port {}: {}", tcp_port, name);
|
||||||
|
} else {
|
||||||
|
println!("Process not found for TCP port {}", tcp_port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,983 +1,26 @@
|
||||||
use std::time::{Duration, SystemTime};
|
use portable_atomic::{AtomicU64, AtomicU32, AtomicU8};
|
||||||
use std::sync::atomic::Ordering;
|
|
||||||
use portable_atomic::{AtomicU64, AtomicU8};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use anyhow::{Context, Result};
|
|
||||||
use bytes::Bytes;
|
|
||||||
use ostp_core::relay::RelayMessage;
|
|
||||||
use ostp_core::{NoiseRole, OstpEvent, PaddingStrategy, ProtocolAction, ProtocolConfig, ProtocolMachine, TrafficProfile};
|
|
||||||
use rand::Rng;
|
|
||||||
use tokio::net::UdpSocket;
|
|
||||||
use tokio::sync::{mpsc, watch};
|
|
||||||
use tokio::time::{interval, timeout, Instant};
|
|
||||||
|
|
||||||
use crate::app::{BridgeCommand, ConnectionStatus, UiEvent};
|
|
||||||
use crate::config::ClientConfig;
|
|
||||||
use crate::tunnel::{ProxyEvent, ProxyToClientMsg};
|
|
||||||
|
|
||||||
static SOCKET_PROTECTOR: std::sync::OnceLock<Box<dyn Fn(i32) -> bool + Send + Sync>> = std::sync::OnceLock::new();
|
|
||||||
|
|
||||||
pub fn set_socket_protector<F>(f: F)
|
|
||||||
where
|
|
||||||
F: Fn(i32) -> bool + Send + Sync + 'static,
|
|
||||||
{
|
|
||||||
let _ = SOCKET_PROTECTOR.set(Box::new(f));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn protect_socket(fd: i32) -> bool {
|
|
||||||
if let Some(f) = SOCKET_PROTECTOR.get() {
|
|
||||||
return f(fd);
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct BridgeMetrics {
|
pub struct BridgeMetrics {
|
||||||
pub bytes_sent: AtomicU64,
|
pub bytes_sent: AtomicU64,
|
||||||
pub bytes_recv: AtomicU64,
|
pub bytes_recv: AtomicU64,
|
||||||
pub connection_state: AtomicU8,
|
pub connection_state: AtomicU8,
|
||||||
pub rtt_ms: portable_atomic::AtomicU32,
|
pub rtt_ms: AtomicU32,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_datagram(socket: &crate::transport::Transport, frame: &Bytes, webrtc_masquerade: bool) -> std::io::Result<usize> {
|
impl Default for BridgeMetrics {
|
||||||
if webrtc_masquerade {
|
fn default() -> Self {
|
||||||
let mut out = bytes::BytesMut::with_capacity(12 + frame.len());
|
Self {
|
||||||
// Fake SRTP Header:
|
bytes_sent: portable_atomic::AtomicU64::new(0),
|
||||||
// [0] 0x80 (Version 2)
|
bytes_recv: portable_atomic::AtomicU64::new(0),
|
||||||
// [1] 0x60 (Payload Type 96 - dynamic video)
|
connection_state: portable_atomic::AtomicU8::new(0),
|
||||||
// [2..3] Sequence number (dummy 0x1234)
|
rtt_ms: portable_atomic::AtomicU32::new(0),
|
||||||
// [4..7] Timestamp (dummy)
|
|
||||||
// [8..11] SSRC (dummy)
|
|
||||||
out.extend_from_slice(&[0x80, 0x60, 0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44]);
|
|
||||||
out.extend_from_slice(frame);
|
|
||||||
socket.send(&out.freeze()).await
|
|
||||||
} else {
|
|
||||||
socket.send(frame).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct SessionState {
|
|
||||||
socket: crate::transport::Transport,
|
|
||||||
machine: ProtocolMachine,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Bridge {
|
|
||||||
running: bool,
|
|
||||||
pub debug: bool,
|
|
||||||
profile: TrafficProfile,
|
|
||||||
server_addr: String,
|
|
||||||
local_bind_addr: String,
|
|
||||||
proxy_addr: String,
|
|
||||||
access_key: Bytes,
|
|
||||||
handshake_timeout_ms: u64,
|
|
||||||
io_timeout_ms: u64,
|
|
||||||
|
|
||||||
pub keepalive_interval_sec: u64,
|
|
||||||
pub mode: String,
|
|
||||||
pub mux_enabled: bool,
|
|
||||||
pub mux_sessions: usize,
|
|
||||||
|
|
||||||
pub transport_mode: String,
|
|
||||||
pub stealth_sni: String,
|
|
||||||
pub stealth_port: u16,
|
|
||||||
pub mtu: usize,
|
|
||||||
pub reality_enabled: bool,
|
|
||||||
|
|
||||||
metrics: Arc<BridgeMetrics>,
|
|
||||||
sample_sent: u64,
|
|
||||||
sample_recv: u64,
|
|
||||||
last_rtt_ms: f64,
|
|
||||||
last_sample_at: Instant,
|
|
||||||
last_valid_recv: Instant,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Bridge {
|
|
||||||
pub fn new(config: &ClientConfig, metrics: Arc<BridgeMetrics>) -> Result<Self> {
|
|
||||||
Ok(Self {
|
|
||||||
running: false,
|
|
||||||
debug: config.debug,
|
|
||||||
profile: TrafficProfile::JsonRpc,
|
|
||||||
server_addr: config.ostp.server_addr.clone(),
|
|
||||||
local_bind_addr: config.ostp.local_bind_addr.clone(),
|
|
||||||
proxy_addr: config.local_proxy.bind_addr.clone(),
|
|
||||||
access_key: Bytes::from(config.ostp.access_key.clone()),
|
|
||||||
handshake_timeout_ms: config.ostp.handshake_timeout_ms,
|
|
||||||
io_timeout_ms: config.ostp.io_timeout_ms,
|
|
||||||
|
|
||||||
keepalive_interval_sec: config.ostp.keepalive_interval_sec,
|
|
||||||
mode: config.mode.clone(),
|
|
||||||
mux_enabled: config.multiplex.enabled,
|
|
||||||
mux_sessions: config.multiplex.sessions.max(1),
|
|
||||||
|
|
||||||
transport_mode: config.transport.mode.clone(),
|
|
||||||
stealth_sni: config.transport.stealth_sni.clone(),
|
|
||||||
stealth_port: config.transport.stealth_port,
|
|
||||||
mtu: config.ostp.mtu,
|
|
||||||
reality_enabled: !config.reality.pbk.is_empty(),
|
|
||||||
|
|
||||||
metrics,
|
|
||||||
sample_sent: 0,
|
|
||||||
sample_recv: 0,
|
|
||||||
last_rtt_ms: 0.0,
|
|
||||||
last_sample_at: Instant::now(),
|
|
||||||
last_valid_recv: Instant::now(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn run(
|
|
||||||
mut self,
|
|
||||||
tx: mpsc::Sender<UiEvent>,
|
|
||||||
mut bridge_rx: mpsc::Receiver<BridgeCommand>,
|
|
||||||
mut shutdown: watch::Receiver<bool>,
|
|
||||||
mut proxy_rx: mpsc::Receiver<ProxyEvent>,
|
|
||||||
proxy_tx: mpsc::UnboundedSender<(u16, ProxyToClientMsg)>,
|
|
||||||
) -> Result<()> {
|
|
||||||
let mut metrics_tick = interval(Duration::from_millis(500));
|
|
||||||
let mut keepalive_tick = tokio::time::interval(Duration::from_secs(self.keepalive_interval_sec.max(1)));
|
|
||||||
let mut retransmit_tick = tokio::time::interval(Duration::from_millis(50));
|
|
||||||
let init_msg = if self.mode == "tun" {
|
|
||||||
"Bridge initialized (TUN mode)".to_string()
|
|
||||||
} else {
|
|
||||||
"Bridge initialized (proxy mode)".to_string()
|
|
||||||
};
|
|
||||||
tx.send(UiEvent::Log(init_msg)).await.ok();
|
|
||||||
|
|
||||||
let mut sessions_opt: Option<Vec<SessionState>> = None;
|
|
||||||
let mut udp_rx_opt: Option<mpsc::Receiver<(usize, Bytes)>> = None;
|
|
||||||
let mut _proxy_guard: Option<crate::sysproxy::WindowsProxyGuard> = None;
|
|
||||||
let mut stream_map: std::collections::HashMap<u16, usize> = std::collections::HashMap::new();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
biased;
|
|
||||||
_ = shutdown.changed() => {
|
|
||||||
if *shutdown.borrow() {
|
|
||||||
self.running = false;
|
|
||||||
self.metrics.connection_state.store(0, Ordering::Relaxed);
|
|
||||||
_proxy_guard = None;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
udp_msg = async {
|
|
||||||
match udp_rx_opt.as_mut() {
|
|
||||||
Some(rx) => rx.recv().await,
|
|
||||||
None => std::future::pending().await,
|
|
||||||
}
|
|
||||||
}, if self.running => {
|
|
||||||
match udp_msg {
|
|
||||||
Some((session_index, inbound)) => {
|
|
||||||
self.metrics.bytes_recv.fetch_add(inbound.len() as u64, Ordering::Relaxed);
|
|
||||||
self.last_valid_recv = Instant::now();
|
|
||||||
if let Some(sessions) = sessions_opt.as_mut() {
|
|
||||||
if session_index < sessions.len() {
|
|
||||||
let session = &mut sessions[session_index];
|
|
||||||
let initial_action = match session.machine.on_event(OstpEvent::Inbound(inbound)) {
|
|
||||||
Ok(a) => a,
|
|
||||||
Err(e) => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Protocol decrypt error: {e}"))).await;
|
|
||||||
tracing::warn!("Inbound protocol error (session {}): {}", session_index, e);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut actions_queue = std::collections::VecDeque::new();
|
|
||||||
actions_queue.push_back(initial_action);
|
|
||||||
|
|
||||||
while let Some(current_action) = actions_queue.pop_front() {
|
|
||||||
match current_action {
|
|
||||||
ProtocolAction::Multiple(nested) => {
|
|
||||||
for a in nested {
|
|
||||||
actions_queue.push_back(a);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ProtocolAction::DeliverApp(stream_id, dec_payload) => {
|
|
||||||
match RelayMessage::decode(&dec_payload) {
|
|
||||||
Ok(relay_msg) => {
|
|
||||||
match relay_msg {
|
|
||||||
RelayMessage::ConnectOk => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Relay CONNECT OK stream_id={stream_id}"))).await;
|
|
||||||
let _ = proxy_tx.send((stream_id, ProxyToClientMsg::ConnectOk));
|
|
||||||
}
|
|
||||||
RelayMessage::Data(data) => {
|
|
||||||
let _ = proxy_tx.send((stream_id, ProxyToClientMsg::Data(Bytes::from(data))));
|
|
||||||
}
|
|
||||||
RelayMessage::Close => {
|
|
||||||
let _ = proxy_tx.send((stream_id, ProxyToClientMsg::Close));
|
|
||||||
}
|
|
||||||
RelayMessage::Error(msg) => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Relay error for stream {stream_id}: {msg}"))).await;
|
|
||||||
let _ = proxy_tx.send((stream_id, ProxyToClientMsg::Error(msg)));
|
|
||||||
}
|
|
||||||
RelayMessage::Pong(ts) => {
|
|
||||||
let now = SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64;
|
|
||||||
self.last_rtt_ms = now.saturating_sub(ts) as f64;
|
|
||||||
self.metrics.rtt_ms.store(self.last_rtt_ms as u32, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
RelayMessage::KeepAlive | RelayMessage::Ping(_) | RelayMessage::Connect(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Relay decode error for stream {stream_id}: {err}"))).await;
|
|
||||||
let _ = proxy_tx.send((stream_id, ProxyToClientMsg::Error("relay decode failed".to_string())));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ProtocolAction::SendDatagram(frame) => {
|
|
||||||
let _ = send_datagram(&session.socket, &frame, self.transport_mode == "udp" ).await;
|
|
||||||
self.metrics.bytes_sent.fetch_add(frame.len() as u64, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
let _ = tx.send(UiEvent::Log("UDP channel closed, resetting connection".to_string())).await;
|
|
||||||
self.running = false;
|
|
||||||
crate::sysproxy::disable_windows_proxy();
|
|
||||||
sessions_opt = None;
|
|
||||||
udp_rx_opt = None;
|
|
||||||
stream_map.clear();
|
|
||||||
self.reset_proxy_streams(&tx, &proxy_tx, "udp reader closed");
|
|
||||||
let _ = tx.send(UiEvent::TunnelStopped).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cmd = bridge_rx.recv() => {
|
|
||||||
match cmd {
|
|
||||||
Some(BridgeCommand::ToggleTunnel) => {
|
|
||||||
if self.running {
|
|
||||||
self.running = false;
|
|
||||||
self.metrics.connection_state.store(0, Ordering::Relaxed);
|
|
||||||
_proxy_guard = None;
|
|
||||||
sessions_opt = None;
|
|
||||||
udp_rx_opt = None;
|
|
||||||
stream_map.clear();
|
|
||||||
self.reset_proxy_streams(&tx, &proxy_tx, "manual stop");
|
|
||||||
tx.send(UiEvent::TunnelStopped).await.ok();
|
|
||||||
let stop_msg = if self.mode == "tun" { "TUN tunnel stopped" } else { "Bridge stopped" };
|
|
||||||
tx.send(UiEvent::Log(stop_msg.to_string())).await.ok();
|
|
||||||
} else {
|
|
||||||
tx.send(UiEvent::Log("Connecting to remote server...".to_string())).await.ok();
|
|
||||||
tx.send(UiEvent::Metrics { status: ConnectionStatus::Handshaking, rtt_ms: 0.0, throughput_bps: 0 }).await.ok();
|
|
||||||
self.metrics.connection_state.store(1, Ordering::Relaxed);
|
|
||||||
|
|
||||||
let session_count = if self.mux_enabled { self.mux_sessions.max(1) } else { 1 };
|
|
||||||
let (udp_tx, udp_rx) = mpsc::channel(100000); // Increased for high-speed traffic stability
|
|
||||||
let mut sessions = Vec::with_capacity(session_count);
|
|
||||||
let mut rtt_sum = 0.0;
|
|
||||||
let mut successful_sessions = 0;
|
|
||||||
|
|
||||||
for idx in 0..session_count {
|
|
||||||
let session_id: u32 = rand::thread_rng().gen();
|
|
||||||
match self.perform_handshake_with_id(&tx, session_id).await {
|
|
||||||
Ok((sock, mach, rtt)) => {
|
|
||||||
let session_index = sessions.len();
|
|
||||||
let socket_clone = sock.clone();
|
|
||||||
let udp_tx_clone = udp_tx.clone();
|
|
||||||
let is_webrtc = self.transport_mode == "udp" ;
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut buf = vec![0_u8; 65535];
|
|
||||||
loop {
|
|
||||||
match socket_clone.recv(&mut buf).await {
|
|
||||||
Ok(n) => {
|
|
||||||
let inbound = if is_webrtc && n >= 12 && buf[0] == 0x80 {
|
|
||||||
Bytes::copy_from_slice(&buf[12..n])
|
|
||||||
} else {
|
|
||||||
Bytes::copy_from_slice(&buf[..n])
|
|
||||||
};
|
|
||||||
if udp_tx_clone.send((session_index, inbound)).await.is_err() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
// Under Windows/Winsock, transient UDP socket errors (like WSAECONNRESET) are returned
|
|
||||||
// as Err(ConnectionReset). We MUST NOT break the loop on transient errors, otherwise the
|
|
||||||
// download path will be permanently killed while the upload path keeps running.
|
|
||||||
tracing::warn!("UDP socket recv error (session {}): {}", session_index, e);
|
|
||||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
sessions.push(SessionState { socket: sock, machine: mach });
|
|
||||||
rtt_sum += rtt;
|
|
||||||
successful_sessions += 1;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
tx.send(UiEvent::Log(format!("Multiplex session {}/{} handshake failed: {}. Continuing with remaining sessions...", idx + 1, session_count, err))).await.ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if sessions.is_empty() {
|
|
||||||
_proxy_guard = None;
|
|
||||||
tx.send(UiEvent::Log("All multiplexed handshake attempts failed. Connection aborted.".to_string())).await.ok();
|
|
||||||
tx.send(UiEvent::TunnelStopped).await.ok();
|
|
||||||
self.metrics.connection_state.store(0, Ordering::Relaxed);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
udp_rx_opt = Some(udp_rx);
|
|
||||||
sessions_opt = Some(sessions);
|
|
||||||
self.last_rtt_ms = rtt_sum / successful_sessions as f64;
|
|
||||||
self.running = true;
|
|
||||||
self.last_sample_at = Instant::now();
|
|
||||||
self.last_valid_recv = Instant::now();
|
|
||||||
|
|
||||||
let sys_proxy_addr = self.proxy_addr.replace("0.0.0.0:", "127.0.0.1:");
|
|
||||||
_proxy_guard = Some(crate::sysproxy::WindowsProxyGuard::enable(&sys_proxy_addr));
|
|
||||||
|
|
||||||
tx.send(UiEvent::Metrics {
|
|
||||||
status: ConnectionStatus::Established,
|
|
||||||
rtt_ms: self.last_rtt_ms,
|
|
||||||
throughput_bps: 0,
|
|
||||||
}).await.ok();
|
|
||||||
self.metrics.connection_state.store(2, Ordering::Relaxed);
|
|
||||||
let start_msg = if self.mode == "tun" { "TUN tunnel established" } else { "Connection established" };
|
|
||||||
tx.send(UiEvent::Log(start_msg.to_string())).await.ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(BridgeCommand::NextProfile) => {
|
|
||||||
self.profile = next_profile(self.profile);
|
|
||||||
tx.send(UiEvent::ProfileChanged(self.profile)).await.ok();
|
|
||||||
tx.send(UiEvent::Log(format!("Obfuscation profile switched to {:?}", self.profile))).await.ok();
|
|
||||||
}
|
|
||||||
Some(BridgeCommand::NetworkChanged) => {
|
|
||||||
if self.running {
|
|
||||||
// Network changed (e.g. WiFi→LTE): IP address changed, existing UDP
|
|
||||||
// socket is dead. Trigger immediate reconnect without waiting for stall.
|
|
||||||
let _ = tx.send(UiEvent::Log("Network changed — starting immediate reconnect".to_string())).await;
|
|
||||||
self.metrics.connection_state.store(1, Ordering::Relaxed);
|
|
||||||
self.last_valid_recv = Instant::now() - Duration::from_secs(100); // force stall path
|
|
||||||
|
|
||||||
let session_count = if self.mux_enabled { self.mux_sessions.max(1) } else { 1 };
|
|
||||||
let (udp_tx, udp_rx) = mpsc::channel(100000);
|
|
||||||
let mut new_sessions = Vec::with_capacity(session_count);
|
|
||||||
let mut successful_sessions = 0;
|
|
||||||
let mut rtt_sum = 0.0;
|
|
||||||
|
|
||||||
for idx in 0..session_count {
|
|
||||||
let session_id: u32 = rand::thread_rng().gen();
|
|
||||||
match self.perform_handshake_with_id(&tx, session_id).await {
|
|
||||||
Ok((sock, mach, rtt)) => {
|
|
||||||
let session_index = new_sessions.len();
|
|
||||||
let socket_clone = sock.clone();
|
|
||||||
let udp_tx_clone = udp_tx.clone();
|
|
||||||
let is_webrtc = self.transport_mode == "udp" ;
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut buf = vec![0_u8; 65535];
|
|
||||||
loop {
|
|
||||||
match socket_clone.recv(&mut buf).await {
|
|
||||||
Ok(n) => {
|
|
||||||
let inbound = if is_webrtc && n >= 12 && buf[0] == 0x80 {
|
|
||||||
Bytes::copy_from_slice(&buf[12..n])
|
|
||||||
} else {
|
|
||||||
Bytes::copy_from_slice(&buf[..n])
|
|
||||||
};
|
|
||||||
if udp_tx_clone.send((session_index, inbound)).await.is_err() { break; }
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!("UDP recv error (network-change session {}): {}", session_index, e);
|
|
||||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
new_sessions.push(SessionState { socket: sock, machine: mach });
|
|
||||||
rtt_sum += rtt;
|
|
||||||
successful_sessions += 1;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("NetworkChanged reconnect session {}/{} failed: {}", idx + 1, session_count, err))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !new_sessions.is_empty() {
|
|
||||||
sessions_opt = Some(new_sessions);
|
|
||||||
udp_rx_opt = Some(udp_rx);
|
|
||||||
self.last_rtt_ms = rtt_sum / successful_sessions as f64;
|
|
||||||
self.last_valid_recv = Instant::now();
|
|
||||||
stream_map.clear();
|
|
||||||
self.reset_proxy_streams(&tx, &proxy_tx, "network changed");
|
|
||||||
self.metrics.connection_state.store(2, Ordering::Relaxed);
|
|
||||||
let _ = tx.send(UiEvent::Log("NetworkChanged reconnect successful!".to_string())).await;
|
|
||||||
} else {
|
|
||||||
let _ = tx.send(UiEvent::Log("NetworkChanged reconnect failed — will retry on keepalive tick".to_string())).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(BridgeCommand::ReloadConfig) => {
|
|
||||||
match ClientConfig::reload_from_json_near_binary() {
|
|
||||||
Ok(cfg) => {
|
|
||||||
self.apply_runtime_config(&cfg);
|
|
||||||
tx.send(UiEvent::Log("Runtime config reloaded".to_string())).await.ok();
|
|
||||||
if self.running {
|
|
||||||
self.running = false;
|
|
||||||
self.metrics.connection_state.store(0, Ordering::Relaxed);
|
|
||||||
_proxy_guard = None;
|
|
||||||
sessions_opt = None;
|
|
||||||
stream_map.clear();
|
|
||||||
self.reset_proxy_streams(&tx, &proxy_tx, "config reload");
|
|
||||||
// User logic handles UI restart
|
|
||||||
let _ = tx.send(UiEvent::TunnelStopped).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Config reload failed: {err}"))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(BridgeCommand::Shutdown) | None => {
|
|
||||||
self.running = false;
|
|
||||||
_proxy_guard = None;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = metrics_tick.tick() => {
|
|
||||||
if self.running {
|
|
||||||
self.emit_metrics(&tx).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = keepalive_tick.tick() => {
|
|
||||||
if self.running {
|
|
||||||
// 1. Connection Liveness Check & Silent Background Reconnect
|
|
||||||
if self.last_valid_recv.elapsed().as_secs() > 8 {
|
|
||||||
let elapsed = self.last_valid_recv.elapsed().as_secs();
|
|
||||||
if elapsed > 180 {
|
|
||||||
// Hard timeout after 3 minutes of total silence
|
|
||||||
let _ = tx.send(UiEvent::Log("Connection permanently lost (3-minute hard timeout). Stopping tunnel.".into())).await;
|
|
||||||
self.running = false;
|
|
||||||
_proxy_guard = None;
|
|
||||||
sessions_opt = None;
|
|
||||||
stream_map.clear();
|
|
||||||
self.reset_proxy_streams(&tx, &proxy_tx, "keepalive hard timeout");
|
|
||||||
let _ = tx.send(UiEvent::TunnelStopped).await;
|
|
||||||
self.metrics.connection_state.store(0, Ordering::Relaxed);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Connection stall detected ({}s silence). Attempting background reconnect...", elapsed))).await;
|
|
||||||
self.metrics.connection_state.store(1, Ordering::Relaxed); // State: Connecting (Handshake)
|
|
||||||
|
|
||||||
let session_count = if self.mux_enabled { self.mux_sessions.max(1) } else { 1 };
|
|
||||||
let (udp_tx, udp_rx) = mpsc::channel(100000);
|
|
||||||
let mut new_sessions = Vec::with_capacity(session_count);
|
|
||||||
let mut successful_sessions = 0;
|
|
||||||
let mut rtt_sum = 0.0;
|
|
||||||
|
|
||||||
for idx in 0..session_count {
|
|
||||||
let session_id: u32 = rand::thread_rng().gen();
|
|
||||||
match self.perform_handshake_with_id(&tx, session_id).await {
|
|
||||||
Ok((sock, mach, rtt)) => {
|
|
||||||
let session_index = new_sessions.len();
|
|
||||||
let socket_clone = sock.clone();
|
|
||||||
let udp_tx_clone = udp_tx.clone();
|
|
||||||
let is_webrtc = self.transport_mode == "udp" ;
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut buf = vec![0_u8; 65535];
|
|
||||||
loop {
|
|
||||||
match socket_clone.recv(&mut buf).await {
|
|
||||||
Ok(n) => {
|
|
||||||
let inbound = if is_webrtc && n >= 12 && buf[0] == 0x80 {
|
|
||||||
Bytes::copy_from_slice(&buf[12..n])
|
|
||||||
} else {
|
|
||||||
Bytes::copy_from_slice(&buf[..n])
|
|
||||||
};
|
|
||||||
if udp_tx_clone.send((session_index, inbound)).await.is_err() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!("UDP socket recv error (reconnect session {}): {}", session_index, e);
|
|
||||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
new_sessions.push(SessionState { socket: sock, machine: mach });
|
|
||||||
rtt_sum += rtt;
|
|
||||||
successful_sessions += 1;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Background reconnect session {}/{} failed: {}", idx + 1, session_count, err))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !new_sessions.is_empty() {
|
|
||||||
sessions_opt = Some(new_sessions);
|
|
||||||
udp_rx_opt = Some(udp_rx);
|
|
||||||
self.last_rtt_ms = rtt_sum / successful_sessions as f64;
|
|
||||||
self.last_valid_recv = Instant::now();
|
|
||||||
self.metrics.connection_state.store(2, Ordering::Relaxed); // State: Connected
|
|
||||||
let _ = tx.send(UiEvent::Log("Background reconnect successful! Connection restored.".into())).await;
|
|
||||||
} else {
|
|
||||||
let _ = tx.send(UiEvent::Log("Background reconnect failed. Will retry on next tick...".into())).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Active Keep-Alive / Heartbeat
|
|
||||||
if let Some(sessions) = sessions_opt.as_mut() {
|
|
||||||
for session in sessions.iter_mut() {
|
|
||||||
// Send Ping (Internal RTT Metric)
|
|
||||||
let ts = SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64;
|
|
||||||
let ping_payload = Bytes::from(RelayMessage::Ping(ts).encode());
|
|
||||||
if let Ok(ProtocolAction::SendDatagram(frame)) = session.machine.on_event(OstpEvent::Outbound(0, ping_payload)) {
|
|
||||||
// Must go through send_datagram() for TURN-mode wrapping;
|
|
||||||
// raw socket.send() bypasses the ChannelData header and breaks RTT in TURN.
|
|
||||||
let _ = send_datagram(&session.socket, &frame, self.transport_mode == "udp" ).await;
|
|
||||||
self.metrics.bytes_sent.fetch_add(frame.len() as u64, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send Relay KeepAlive (Force NAT/Server Persistence)
|
|
||||||
let ka_payload = Bytes::from(RelayMessage::KeepAlive.encode());
|
|
||||||
if let Ok(ProtocolAction::SendDatagram(frame)) = session.machine.on_event(OstpEvent::Outbound(0, ka_payload)) {
|
|
||||||
let _ = send_datagram(&session.socket, &frame, self.transport_mode == "udp" ).await;
|
|
||||||
self.metrics.bytes_sent.fetch_add(frame.len() as u64, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = retransmit_tick.tick() => {
|
|
||||||
if self.running {
|
|
||||||
let mut fatal_err = None;
|
|
||||||
if let Some(sessions) = sessions_opt.as_mut() {
|
|
||||||
for session in sessions.iter_mut() {
|
|
||||||
match session.machine.on_event(OstpEvent::Tick) {
|
|
||||||
Ok(action) => {
|
|
||||||
let mut queue = vec![action];
|
|
||||||
while let Some(current_action) = queue.pop() {
|
|
||||||
match current_action {
|
|
||||||
ProtocolAction::Multiple(nested) => {
|
|
||||||
for a in nested {
|
|
||||||
queue.push(a);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ProtocolAction::SendDatagram(frame) => {
|
|
||||||
let _ = send_datagram(&session.socket, &frame, self.transport_mode == "udp" ).await;
|
|
||||||
self.metrics.bytes_sent.fetch_add(frame.len() as u64, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
fatal_err = Some(e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(e) = fatal_err {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Protocol tick fatal error: {e}"))).await;
|
|
||||||
self.running = false;
|
|
||||||
_proxy_guard = None;
|
|
||||||
sessions_opt = None;
|
|
||||||
udp_rx_opt = None;
|
|
||||||
stream_map.clear();
|
|
||||||
self.reset_proxy_streams(&tx, &proxy_tx, "protocol fatal error");
|
|
||||||
let _ = tx.send(UiEvent::TunnelStopped).await;
|
|
||||||
self.metrics.connection_state.store(0, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
proxy_ev = proxy_rx.recv(), if self.running && sessions_opt.as_ref().map(|s| {
|
|
||||||
// Backpressure: suspend proxy reads when ARQ window is saturated
|
|
||||||
s.iter().all(|ses| ses.machine.in_flight_count() < 256)
|
|
||||||
}).unwrap_or(true) => {
|
|
||||||
if let Some(ev) = proxy_ev {
|
|
||||||
if let Some(sessions) = sessions_opt.as_mut() {
|
|
||||||
if sessions.is_empty() {
|
|
||||||
if let ProxyEvent::NewStream { stream_id, .. } = ev {
|
|
||||||
let _ = proxy_tx.send((stream_id, ProxyToClientMsg::Error("tunnel stopped".into())));
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let (stream_id, relay_msg, is_close) = match ev {
|
|
||||||
ProxyEvent::NewStream { stream_id, target } => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Proxy CONNECT stream_id={stream_id} target={target}"))).await;
|
|
||||||
(stream_id, RelayMessage::Connect(target), false)
|
|
||||||
}
|
|
||||||
ProxyEvent::Data { stream_id, payload } => (stream_id, RelayMessage::Data(payload.to_vec()), false),
|
|
||||||
ProxyEvent::Close { stream_id } => {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Proxy CLOSE stream_id={stream_id}"))).await;
|
|
||||||
(stream_id, RelayMessage::Close, true)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let len = sessions.len();
|
|
||||||
let session_index = *stream_map.entry(stream_id).or_insert_with(|| {
|
|
||||||
// §8 FIX: Load balance multiplexed streams randomly across available connection sockets
|
|
||||||
rand::thread_rng().gen_range(0..len)
|
|
||||||
});
|
|
||||||
if is_close {
|
|
||||||
stream_map.remove(&stream_id);
|
|
||||||
}
|
|
||||||
let session = &mut sessions[session_index];
|
|
||||||
let out_payload = Bytes::from(relay_msg.encode());
|
|
||||||
match session.machine.on_event(OstpEvent::Outbound(stream_id, out_payload)) {
|
|
||||||
Ok(ProtocolAction::SendDatagram(frame)) => {
|
|
||||||
if send_datagram(&session.socket, &frame, self.transport_mode == "udp" ).await.is_ok() {
|
|
||||||
self.metrics.bytes_sent.fetch_add(frame.len() as u64, Ordering::Relaxed);
|
|
||||||
if self.debug {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!(
|
|
||||||
"Outbound datagram sent stream_id={stream_id} bytes={}",
|
|
||||||
frame.len()
|
|
||||||
))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(ProtocolAction::Multiple(list)) => {
|
|
||||||
let mut sent = 0usize;
|
|
||||||
for item in list {
|
|
||||||
if let ProtocolAction::SendDatagram(frame) = item {
|
|
||||||
if send_datagram(&session.socket, &frame, self.transport_mode == "udp" ).await.is_ok() {
|
|
||||||
self.metrics.bytes_sent.fetch_add(frame.len() as u64, Ordering::Relaxed);
|
|
||||||
sent += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if self.debug {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!(
|
|
||||||
"Outbound datagram batch stream_id={stream_id} sent={sent}"
|
|
||||||
))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(ProtocolAction::Noop) => {
|
|
||||||
if self.debug {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!(
|
|
||||||
"Outbound datagram noop stream_id={stream_id}"
|
|
||||||
))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(_) => {
|
|
||||||
if self.debug {
|
|
||||||
let _ = tx.send(UiEvent::Log(format!(
|
|
||||||
"Outbound datagram unexpected action stream_id={stream_id}"
|
|
||||||
))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!("Protocol error packing outbound stream_id={}: {}", stream_id, e);
|
|
||||||
let _ = tx.send(UiEvent::Log(format!("Protocol error packing TCP: {e}"))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Drop it, not connected
|
|
||||||
if let ProxyEvent::NewStream { stream_id, .. } = ev {
|
|
||||||
let _ = proxy_tx.send((stream_id, ProxyToClientMsg::Error("tunnel stopped".into())));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tx.send(UiEvent::Log("Bridge stopped".to_string())).await.ok();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reset_proxy_streams(
|
|
||||||
&self,
|
|
||||||
tx: &mpsc::Sender<UiEvent>,
|
|
||||||
proxy_tx: &mpsc::UnboundedSender<(u16, ProxyToClientMsg)>,
|
|
||||||
reason: &str,
|
|
||||||
) {
|
|
||||||
if proxy_tx
|
|
||||||
.send((0, ProxyToClientMsg::Close))
|
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
let tx_clone = tx.clone();
|
|
||||||
let reason_str = reason.to_string();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let _ = tx_clone
|
|
||||||
.send(UiEvent::Log(format!(
|
|
||||||
"Failed to reset local proxy streams ({reason_str})"
|
|
||||||
)))
|
|
||||||
.await;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn emit_metrics(&mut self, tx: &mpsc::Sender<UiEvent>) {
|
|
||||||
let now = Instant::now();
|
|
||||||
let elapsed = now.duration_since(self.last_sample_at).as_secs_f64().max(0.001);
|
|
||||||
self.last_sample_at = now;
|
|
||||||
|
|
||||||
let cur_sent = self.metrics.bytes_sent.load(Ordering::Relaxed);
|
|
||||||
let cur_recv = self.metrics.bytes_recv.load(Ordering::Relaxed);
|
|
||||||
|
|
||||||
let sent_delta = cur_sent.saturating_sub(self.sample_sent);
|
|
||||||
let recv_delta = cur_recv.saturating_sub(self.sample_recv);
|
|
||||||
|
|
||||||
self.sample_sent = cur_sent;
|
|
||||||
self.sample_recv = cur_recv;
|
|
||||||
|
|
||||||
let outgoing = (sent_delta as f64 / elapsed) as u64;
|
|
||||||
let incoming = (recv_delta as f64 / elapsed) as u64;
|
|
||||||
let throughput = incoming.saturating_add(outgoing);
|
|
||||||
|
|
||||||
tx.send(UiEvent::Traffic { incoming_bps: incoming, outgoing_bps: outgoing }).await.ok();
|
|
||||||
|
|
||||||
// Dynamically report connection status based on whether we have received server packets recently (last 10 seconds)
|
|
||||||
let is_healthy = self.last_valid_recv.elapsed() < Duration::from_secs(10);
|
|
||||||
let status = if is_healthy {
|
|
||||||
self.metrics.connection_state.store(2, Ordering::Relaxed);
|
|
||||||
ConnectionStatus::Established
|
|
||||||
} else {
|
|
||||||
self.metrics.connection_state.store(1, Ordering::Relaxed);
|
|
||||||
ConnectionStatus::Handshaking
|
|
||||||
};
|
|
||||||
|
|
||||||
tx.send(UiEvent::Metrics {
|
|
||||||
status,
|
|
||||||
rtt_ms: self.last_rtt_ms,
|
|
||||||
throughput_bps: throughput,
|
|
||||||
}).await.ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn perform_handshake_with_id(
|
|
||||||
&mut self,
|
|
||||||
tx: &mpsc::Sender<UiEvent>,
|
|
||||||
session_id: u32,
|
|
||||||
) -> Result<(crate::transport::Transport, ProtocolMachine, f64)> {
|
|
||||||
let timestamp = std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_secs();
|
|
||||||
|
|
||||||
let mut handshake_payload = Vec::with_capacity(8 + 4 + self.access_key.len());
|
|
||||||
handshake_payload.extend_from_slice(×tamp.to_be_bytes());
|
|
||||||
handshake_payload.extend_from_slice(&session_id.to_be_bytes());
|
|
||||||
handshake_payload.extend_from_slice(&self.access_key);
|
|
||||||
|
|
||||||
let secrets = ostp_core::crypto::derive_all_secrets(&self.access_key);
|
|
||||||
|
|
||||||
let mut machine = ProtocolMachine::new(ProtocolConfig {
|
|
||||||
role: NoiseRole::Initiator,
|
|
||||||
psk: secrets.psk,
|
|
||||||
session_id,
|
|
||||||
handshake_payload,
|
|
||||||
max_padding: 1280, // Safe MTU size to avoid UDP fragmentation on Windows/PPPoE
|
|
||||||
padding_strategy: PaddingStrategy::Profile(self.profile),
|
|
||||||
obfuscation_key: secrets.obfuscation_key,
|
|
||||||
max_reorder: 16384, // Max gap between expected and received nonce
|
|
||||||
max_reorder_buffer: 8192, // Max buffered out-of-order frames
|
|
||||||
ack_delay_ms: 5,
|
|
||||||
rto_ms: 100,
|
|
||||||
max_retries: 8,
|
|
||||||
max_sent_history: 32768, // Reduced: gap recovery handles unrecoverable frames
|
|
||||||
handshake_pad_min: secrets.handshake_pad_min,
|
|
||||||
handshake_pad_max: secrets.handshake_pad_max,
|
|
||||||
mtu: self.mtu,
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let resolved_addrs: Vec<std::net::SocketAddr> = match tokio::net::lookup_host(&self.server_addr).await {
|
|
||||||
Ok(addrs) => addrs.collect(),
|
|
||||||
Err(e) => return Err(anyhow::anyhow!("failed to resolve server address {}: {}", self.server_addr, e)),
|
|
||||||
};
|
|
||||||
let target_addr = resolved_addrs.first().ok_or_else(|| anyhow::anyhow!("no IP addresses resolved for {}", self.server_addr))?;
|
|
||||||
let target_ip = target_addr.ip();
|
|
||||||
let port = target_addr.port();
|
|
||||||
|
|
||||||
tx.send(UiEvent::Log(format!("Connecting to remote server: {}...", target_addr))).await.ok();
|
|
||||||
|
|
||||||
let socket = match self.try_connect_transport(target_ip, port).await {
|
|
||||||
Ok(sock) => sock,
|
|
||||||
Err(e) => {
|
|
||||||
if let std::net::IpAddr::V4(ipv4) = target_ip {
|
|
||||||
tx.send(UiEvent::Log(format!("Direct IPv4 connection failed: {}. Trying NAT64 fallback...", e))).await.ok();
|
|
||||||
let nat64_ipv6 = synthesize_nat64(ipv4);
|
|
||||||
match self.try_connect_transport(std::net::IpAddr::V6(nat64_ipv6), port).await {
|
|
||||||
Ok(sock) => sock,
|
|
||||||
Err(fallback_err) => {
|
|
||||||
return Err(anyhow::anyhow!("Direct IPv4 failed: {}. NAT64 fallback failed: {}", e, fallback_err));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Connection to remote is handled inside try_connect_transport
|
|
||||||
|
|
||||||
let start = Instant::now();
|
|
||||||
let action = machine.on_event(OstpEvent::Start)?;
|
|
||||||
let handshake_frame = match action {
|
|
||||||
ProtocolAction::SendDatagram(frame) => frame,
|
|
||||||
_ => anyhow::bail!("protocol did not emit handshake datagram"),
|
|
||||||
};
|
|
||||||
let mut buf = vec![0_u8; 4096];
|
|
||||||
let mut size = 0;
|
|
||||||
let mut success = false;
|
|
||||||
|
|
||||||
// For UoT: TCP is reliable so we don't retry on the same connection.
|
|
||||||
// Multiple retries would cause stale Noise responses to queue in the mpsc channel
|
|
||||||
// and break the Noise state machine (noise-read error).
|
|
||||||
// For UDP: retry up to 4x with 1200ms timeout to survive packet loss.
|
|
||||||
let is_uot = matches!(socket, crate::transport::Transport::Uot { .. });
|
|
||||||
let (attempt_limit, attempt_timeout_ms) = if is_uot { (1, 4000) } else { (4, 1200) };
|
|
||||||
|
|
||||||
for attempt in 0..attempt_limit {
|
|
||||||
if attempt > 0 {
|
|
||||||
tx.send(UiEvent::Log(format!("Handshake attempt {} lost. Retransmitting...", attempt))).await.ok();
|
|
||||||
}
|
|
||||||
send_datagram(&socket, &handshake_frame, self.transport_mode == "udp" ).await?;
|
|
||||||
self.metrics.bytes_sent.fetch_add(handshake_frame.len() as u64, Ordering::Relaxed);
|
|
||||||
|
|
||||||
match timeout(Duration::from_millis(attempt_timeout_ms), socket.recv(&mut buf)).await {
|
|
||||||
Ok(Ok(n)) => {
|
|
||||||
size = n;
|
|
||||||
success = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
_ => {} // retry on timeout or error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let (final_socket, size) = if success {
|
|
||||||
(socket, size)
|
|
||||||
} else {
|
|
||||||
if let std::net::IpAddr::V4(ipv4) = target_ip {
|
|
||||||
tx.send(UiEvent::Log("Direct IPv4 handshake timed out. Trying NAT64 fallback...".to_string())).await.ok();
|
|
||||||
let nat64_ipv6 = synthesize_nat64(ipv4);
|
|
||||||
match self.try_connect_transport(std::net::IpAddr::V6(nat64_ipv6), port).await {
|
|
||||||
Ok(fallback_socket) => {
|
|
||||||
let mut fallback_success = false;
|
|
||||||
for attempt in 0..4 {
|
|
||||||
if attempt > 0 {
|
|
||||||
tx.send(UiEvent::Log(format!("NAT64 handshake attempt {} lost. Retransmitting...", attempt))).await.ok();
|
|
||||||
}
|
|
||||||
send_datagram(&fallback_socket, &handshake_frame, self.transport_mode == "udp" ).await?;
|
|
||||||
match timeout(Duration::from_millis(1200), fallback_socket.recv(&mut buf)).await {
|
|
||||||
Ok(Ok(n)) => {
|
|
||||||
size = n;
|
|
||||||
fallback_success = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if fallback_success {
|
|
||||||
tx.send(UiEvent::Log("NAT64 fallback handshake successful!".to_string())).await.ok();
|
|
||||||
(fallback_socket, size)
|
|
||||||
} else {
|
|
||||||
return Err(anyhow::anyhow!("NAT64 handshake failed after 3 attempts"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => return Err(anyhow::anyhow!("NAT64 fallback socket creation failed: {}", e)),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err(anyhow::anyhow!("Direct handshake failed after 3 attempts"));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let socket = final_socket;
|
|
||||||
self.metrics.bytes_recv.fetch_add(size as u64, Ordering::Relaxed);
|
|
||||||
tracing::info!("Handshake response received: {} bytes", size);
|
|
||||||
|
|
||||||
let inbound = if (self.transport_mode == "udp") && size >= 12 && buf[0] == 0x80 {
|
|
||||||
Bytes::copy_from_slice(&buf[12..size])
|
|
||||||
} else {
|
|
||||||
Bytes::copy_from_slice(&buf[..size])
|
|
||||||
};
|
|
||||||
machine.on_event(OstpEvent::Inbound(inbound))?;
|
|
||||||
let rtt_ms = start.elapsed().as_secs_f64() * 1000.0;
|
|
||||||
tracing::info!("Handshake complete: session={:#010x} rtt={:.1}ms", session_id, rtt_ms);
|
|
||||||
|
|
||||||
Ok((socket, machine, rtt_ms))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_runtime_config(&mut self, cfg: &ClientConfig) {
|
|
||||||
self.server_addr = cfg.ostp.server_addr.clone();
|
|
||||||
self.local_bind_addr = cfg.ostp.local_bind_addr.clone();
|
|
||||||
self.proxy_addr = cfg.local_proxy.bind_addr.clone();
|
|
||||||
self.access_key = Bytes::from(cfg.ostp.access_key.clone());
|
|
||||||
self.handshake_timeout_ms = cfg.ostp.handshake_timeout_ms;
|
|
||||||
self.io_timeout_ms = cfg.ostp.io_timeout_ms;
|
|
||||||
self.mode = cfg.mode.clone(); // Bug fix: mode was never updated on hot-reload
|
|
||||||
self.mux_enabled = cfg.multiplex.enabled;
|
|
||||||
self.mux_sessions = cfg.multiplex.sessions.max(1);
|
|
||||||
self.transport_mode = cfg.transport.mode.clone();
|
|
||||||
self.stealth_sni = cfg.transport.stealth_sni.clone();
|
|
||||||
self.stealth_port = cfg.transport.stealth_port;
|
|
||||||
self.reality_enabled = !cfg.reality.pbk.is_empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn try_connect_transport(
|
|
||||||
&self,
|
|
||||||
target_ip: std::net::IpAddr,
|
|
||||||
port: u16,
|
|
||||||
) -> Result<crate::transport::Transport> {
|
|
||||||
let mode = self.transport_mode.to_lowercase();
|
|
||||||
if mode == "uot" || mode == "tcp" {
|
|
||||||
// For UoT, use the stealth_port if it's configured and differs from default 443;
|
|
||||||
// otherwise fall back to the actual server port so the user doesn't need two separate
|
|
||||||
// port fields for the same destination.
|
|
||||||
let uot_port = if self.stealth_port != 443 {
|
|
||||||
self.stealth_port
|
|
||||||
} else {
|
|
||||||
port
|
|
||||||
};
|
|
||||||
let (tx, rx) = crate::transport::xhttp::connect_xhttp(
|
|
||||||
target_ip, uot_port, &self.stealth_sni, &self.access_key, self.reality_enabled
|
|
||||||
).await?;
|
|
||||||
Ok(crate::transport::Transport::Uot { tx, rx })
|
|
||||||
} else {
|
|
||||||
let is_ipv6 = target_ip.is_ipv6();
|
|
||||||
let domain = if is_ipv6 { socket2::Domain::IPV6 } else { socket2::Domain::IPV4 };
|
|
||||||
let bind_addr = if is_ipv6 {
|
|
||||||
std::net::SocketAddr::new(std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED), 0)
|
|
||||||
} else {
|
|
||||||
std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
|
|
||||||
};
|
|
||||||
|
|
||||||
let sock = socket2::Socket::new(domain, socket2::Type::DGRAM, Some(socket2::Protocol::UDP))?;
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
use std::os::unix::io::AsRawFd;
|
|
||||||
protect_socket(sock.as_raw_fd());
|
|
||||||
}
|
|
||||||
let _ = sock.set_recv_buffer_size(33554432); // 32MB
|
|
||||||
let _ = sock.set_send_buffer_size(33554432); // 32MB
|
|
||||||
let actual_recv = sock.recv_buffer_size().unwrap_or(0);
|
|
||||||
let actual_send = sock.send_buffer_size().unwrap_or(0);
|
|
||||||
tracing::info!("UDP socket buffers: recv={}KB send={}KB", actual_recv / 1024, actual_send / 1024);
|
|
||||||
sock.bind(&bind_addr.into())?;
|
|
||||||
sock.set_nonblocking(true)?;
|
|
||||||
let socket = UdpSocket::from_std(sock.into())?;
|
|
||||||
|
|
||||||
let connect_addr = std::net::SocketAddr::new(target_ip, port);
|
|
||||||
socket.connect(connect_addr).await.with_context(|| format!("failed to connect udp to {}", connect_addr))?;
|
|
||||||
Ok(crate::transport::Transport::Udp(Arc::new(socket)))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn next_profile(current: TrafficProfile) -> TrafficProfile {
|
pub fn set_socket_protector<F>(_f: F)
|
||||||
match current {
|
where
|
||||||
TrafficProfile::JsonRpc => TrafficProfile::HttpsBurst,
|
F: Fn(i32) -> bool + Send + Sync + 'static,
|
||||||
TrafficProfile::HttpsBurst => TrafficProfile::VideoStream,
|
{
|
||||||
TrafficProfile::VideoStream => TrafficProfile::JsonRpc,
|
// stub
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn synthesize_nat64(ip: std::net::Ipv4Addr) -> std::net::Ipv6Addr {
|
|
||||||
let octets = ip.octets();
|
|
||||||
std::net::Ipv6Addr::new(
|
|
||||||
0x0064, 0xff9b, 0, 0, 0, 0,
|
|
||||||
((octets[0] as u16) << 8) | octets[1] as u16,
|
|
||||||
((octets[2] as u16) << 8) | octets[3] as u16,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,150 +1,133 @@
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// Client runtime configuration.
|
|
||||||
/// Constructed by the main binary from the unified `config.json`,
|
|
||||||
/// then passed into `runner::run_client`. All I/O happens in the
|
|
||||||
/// binary layer — this crate only owns the plain data structures.
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ClientConfig {
|
pub struct ClientConfig {
|
||||||
pub mode: String,
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub version: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub debug: bool,
|
pub log: LogConfig,
|
||||||
pub ostp: OstpConfig,
|
|
||||||
pub local_proxy: LocalProxyConfig,
|
|
||||||
pub reality: RealityConfig,
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub transport: TransportConfig,
|
pub inbounds: Vec<InboundConfig>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub exclusions: ExclusionConfig,
|
pub outbounds: Vec<OutboundConfig>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub multiplex: MultiplexConfig,
|
pub routing: RoutingConfig,
|
||||||
pub dns_server: Option<String>,
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
}
|
pub gui: Option<serde_json::Value>,
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
|
||||||
pub struct ExclusionConfig {
|
|
||||||
#[serde(default)]
|
|
||||||
pub domains: Vec<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub ips: Vec<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub processes: Vec<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct MultiplexConfig {
|
pub struct LogConfig {
|
||||||
pub enabled: bool,
|
#[serde(default = "default_log_level")]
|
||||||
pub sessions: usize,
|
pub level: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for LogConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { level: default_log_level() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_log_level() -> String { "info".to_string() }
|
||||||
|
fn default_true() -> bool { true }
|
||||||
|
pub fn default_mtu() -> usize { 1140 }
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
|
pub enum InboundConfig {
|
||||||
|
Tun {
|
||||||
|
tag: String,
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
auto_route: bool,
|
||||||
|
#[serde(default = "default_mtu")]
|
||||||
|
mtu: usize,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
fd: Option<i32>,
|
||||||
|
},
|
||||||
|
LocalProxy {
|
||||||
|
tag: String,
|
||||||
|
protocol: String, // "socks" or "http"
|
||||||
|
listen: String,
|
||||||
|
port: u16,
|
||||||
|
#[serde(default)]
|
||||||
|
set_system_proxy: bool,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct OstpConfig {
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
pub server_addr: String,
|
pub enum OutboundConfig {
|
||||||
pub local_bind_addr: String,
|
Selector {
|
||||||
#[serde(alias = "auth_token")]
|
tag: String,
|
||||||
pub access_key: String,
|
outbounds: Vec<String>,
|
||||||
pub handshake_timeout_ms: u64,
|
default: Option<String>,
|
||||||
pub io_timeout_ms: u64,
|
},
|
||||||
#[serde(default = "default_mtu")]
|
Urltest {
|
||||||
pub mtu: usize,
|
tag: String,
|
||||||
#[serde(default = "default_keepalive")]
|
outbounds: Vec<String>,
|
||||||
pub keepalive_interval_sec: u64,
|
url: Option<String>,
|
||||||
|
interval: Option<String>,
|
||||||
|
},
|
||||||
|
Ostp {
|
||||||
|
tag: String,
|
||||||
|
server: String,
|
||||||
|
port: u16,
|
||||||
|
access_key: String,
|
||||||
|
#[serde(default)]
|
||||||
|
transport: TransportConfig,
|
||||||
|
#[serde(default)]
|
||||||
|
multiplex: MultiplexConfig,
|
||||||
|
},
|
||||||
|
Direct {
|
||||||
|
tag: String,
|
||||||
|
},
|
||||||
|
Socks {
|
||||||
|
tag: String,
|
||||||
|
server: String,
|
||||||
|
port: u16,
|
||||||
|
},
|
||||||
|
Block {
|
||||||
|
tag: String,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_keepalive() -> u64 { 5 }
|
|
||||||
|
|
||||||
fn default_mtu() -> usize { 1350 }
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct LocalProxyConfig {
|
|
||||||
pub bind_addr: String,
|
|
||||||
pub connect_timeout_ms: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Transport layer configuration.
|
|
||||||
/// `mode` = "udp" (default) or "uot" (UDP over TCP with xHTTP stealth).
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct TransportConfig {
|
pub struct TransportConfig {
|
||||||
/// "udp" or "uot"
|
|
||||||
#[serde(default = "default_transport_mode")]
|
#[serde(default = "default_transport_mode")]
|
||||||
pub mode: String,
|
pub r#type: String, // "udp", "uot", or "dns"
|
||||||
/// TLS SNI and HTTP Host for stealth routing
|
|
||||||
#[serde(default)]
|
// Settings for DNS transport
|
||||||
pub stealth_sni: String,
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
/// TCP Port for the stealth connection
|
pub domain: Option<String>,
|
||||||
#[serde(default = "default_stealth_port")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub stealth_port: u16,
|
pub resolver: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub pubkey: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_transport_mode() -> String { "udp".to_string() }
|
fn default_transport_mode() -> String { "udp".to_string() }
|
||||||
fn default_stealth_port() -> u16 { 443 }
|
|
||||||
|
|
||||||
impl Default for TransportConfig {
|
impl Default for TransportConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
mode: default_transport_mode(),
|
r#type: default_transport_mode(),
|
||||||
stealth_sni: String::new(),
|
domain: None,
|
||||||
stealth_port: default_stealth_port(),
|
resolver: None,
|
||||||
|
pubkey: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
pub struct MultiplexConfig {
|
||||||
pub struct RealityConfig {
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub sni: String,
|
pub enabled: bool,
|
||||||
#[serde(default)]
|
#[serde(default = "default_mux_sessions")]
|
||||||
pub fp: String,
|
pub sessions: usize,
|
||||||
#[serde(default)]
|
|
||||||
pub pbk: String,
|
|
||||||
#[serde(default)]
|
|
||||||
pub sid: String,
|
|
||||||
#[serde(default)]
|
|
||||||
pub spx: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn default_mux_sessions() -> usize { 1 }
|
||||||
impl Default for OstpConfig {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
server_addr: "127.0.0.1:50000".to_string(),
|
|
||||||
local_bind_addr: "0.0.0.0:0".to_string(),
|
|
||||||
access_key: String::new(),
|
|
||||||
handshake_timeout_ms: 5000,
|
|
||||||
io_timeout_ms: 2500,
|
|
||||||
mtu: default_mtu(),
|
|
||||||
keepalive_interval_sec: default_keepalive(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for LocalProxyConfig {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
bind_addr: "127.0.0.1:1088".to_string(),
|
|
||||||
connect_timeout_ms: 15000,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
impl Default for ClientConfig {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
mode: "proxy".to_string(),
|
|
||||||
debug: false,
|
|
||||||
ostp: OstpConfig::default(),
|
|
||||||
local_proxy: LocalProxyConfig::default(),
|
|
||||||
reality: RealityConfig::default(),
|
|
||||||
transport: TransportConfig::default(),
|
|
||||||
exclusions: ExclusionConfig::default(),
|
|
||||||
multiplex: MultiplexConfig::default(),
|
|
||||||
dns_server: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for MultiplexConfig {
|
impl Default for MultiplexConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
|
|
@ -155,62 +138,30 @@ impl Default for MultiplexConfig {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unified shape of `config.json` as seen by the client.
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
/// Used only for hot-reloading (`BridgeCommand::ReloadConfig`).
|
pub struct RoutingConfig {
|
||||||
#[derive(Debug, Deserialize)]
|
#[serde(default)]
|
||||||
struct RawUnifiedConfig {
|
pub rules: Vec<RoutingRule>,
|
||||||
#[allow(dead_code)]
|
#[serde(default)]
|
||||||
mode: String,
|
pub default_outbound: String,
|
||||||
debug: Option<bool>,
|
|
||||||
server: Option<String>,
|
|
||||||
access_key: Option<String>,
|
|
||||||
mtu: Option<usize>,
|
|
||||||
socks5_bind: Option<String>,
|
|
||||||
tun: Option<RawTunSection>,
|
|
||||||
exclude: Option<RawExcludeSection>,
|
|
||||||
mux: Option<RawMuxSection>,
|
|
||||||
reality: Option<RawRealitySection>,
|
|
||||||
transport: Option<RawTransportSection>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
struct RawTransportSection {
|
pub struct RoutingRule {
|
||||||
mode: Option<String>,
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
stealth_sni: Option<String>,
|
pub domain_suffix: Option<Vec<String>>,
|
||||||
stealth_port: Option<u16>,
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
}
|
pub ip_cidr: Option<Vec<String>>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
#[derive(Debug, Deserialize)]
|
pub process_name: Option<Vec<String>>,
|
||||||
struct RawTunSection {
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
enable: Option<bool>,
|
pub inbound_tag: Option<Vec<String>>,
|
||||||
dns: Option<String>,
|
pub outbound: String,
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct RawExcludeSection {
|
|
||||||
domains: Option<Vec<String>>,
|
|
||||||
ips: Option<Vec<String>>,
|
|
||||||
processes: Option<Vec<String>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct RawMuxSection {
|
|
||||||
enabled: Option<bool>,
|
|
||||||
sessions: Option<usize>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct RawRealitySection {
|
|
||||||
sni: Option<String>,
|
|
||||||
fp: Option<String>,
|
|
||||||
pbk: Option<String>,
|
|
||||||
sid: Option<String>,
|
|
||||||
spx: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ClientConfig {
|
impl ClientConfig {
|
||||||
/// Hot-reload from `config.json` placed next to the running binary.
|
/// Hot-reload from `config.json` placed next to the running binary.
|
||||||
/// Returns a new `ClientConfig` built from the unified JSON format.
|
/// Returns a new `ClientConfig` built from the JSON format.
|
||||||
pub fn reload_from_json_near_binary() -> Result<Self> {
|
pub fn reload_from_json_near_binary() -> Result<Self> {
|
||||||
let exe = std::env::current_exe().context("cannot resolve binary path")?;
|
let exe = std::env::current_exe().context("cannot resolve binary path")?;
|
||||||
let dir = exe.parent().context("cannot resolve binary directory")?;
|
let dir = exe.parent().context("cannot resolve binary directory")?;
|
||||||
|
|
@ -219,63 +170,161 @@ impl ClientConfig {
|
||||||
let raw = std::fs::read_to_string(&path)
|
let raw = std::fs::read_to_string(&path)
|
||||||
.with_context(|| format!("failed to read {}", path.display()))?;
|
.with_context(|| format!("failed to read {}", path.display()))?;
|
||||||
let mut stripped = json_comments::StripComments::new(raw.as_bytes());
|
let mut stripped = json_comments::StripComments::new(raw.as_bytes());
|
||||||
let raw: RawUnifiedConfig = serde_json::from_reader(&mut stripped)
|
let raw_json: serde_json::Value = serde_json::from_reader(&mut stripped)
|
||||||
.with_context(|| format!("failed to parse {}", path.display()))?;
|
.with_context(|| format!("failed to parse JSON from {}", path.display()))?;
|
||||||
|
|
||||||
let is_tun = raw.tun.as_ref().and_then(|t| t.enable).unwrap_or(false);
|
let (migrated_json, was_migrated) = Self::migrate_json(raw_json);
|
||||||
let server = raw.server.unwrap_or_else(|| "127.0.0.1:50000".to_string());
|
if was_migrated {
|
||||||
let key = raw.access_key.unwrap_or_default();
|
tracing::warn!(
|
||||||
let mtu = raw.mtu.unwrap_or(default_mtu());
|
"Config at {} is in an outdated format. Run 'ostp --migrate' to upgrade it.",
|
||||||
let socks5 = raw.socks5_bind.unwrap_or_else(|| "127.0.0.1:1088".to_string());
|
path.display()
|
||||||
let exclusions = raw.exclude.unwrap_or(RawExcludeSection {
|
);
|
||||||
domains: None,
|
}
|
||||||
ips: None,
|
|
||||||
processes: None,
|
let config: ClientConfig = serde_json::from_value(migrated_json)
|
||||||
});
|
.with_context(|| format!("failed to deserialize config from {}", path.display()))?;
|
||||||
let mux = raw.mux.unwrap_or(RawMuxSection {
|
|
||||||
enabled: None,
|
Ok(config)
|
||||||
sessions: None,
|
}
|
||||||
|
|
||||||
|
/// Migrates old monolithic JSON to the new modular format.
|
||||||
|
/// Returns the migrated JSON value and a boolean indicating if a migration occurred.
|
||||||
|
pub fn migrate_json(json: serde_json::Value) -> (serde_json::Value, bool) {
|
||||||
|
// Consider the config already migrated if:
|
||||||
|
// 1. Version matches exactly, OR
|
||||||
|
// 2. The JSON already has the new modular format (inbounds + outbounds arrays)
|
||||||
|
let has_version = json.get("version").and_then(|v| v.as_str()) == Some(env!("CARGO_PKG_VERSION"));
|
||||||
|
let has_new_format = json.get("inbounds").and_then(|v| v.as_array()).is_some()
|
||||||
|
&& json.get("outbounds").and_then(|v| v.as_array()).is_some();
|
||||||
|
|
||||||
|
if has_version || has_new_format {
|
||||||
|
// If format is already new but version is old, just bump the version
|
||||||
|
if has_new_format && !has_version {
|
||||||
|
let mut updated = json.clone();
|
||||||
|
updated["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
|
||||||
|
return (updated, false);
|
||||||
|
}
|
||||||
|
return (json, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Needs migration
|
||||||
|
let mut new_json = serde_json::json!({
|
||||||
|
"version": env!("CARGO_PKG_VERSION"),
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(ClientConfig {
|
// 1. Log level
|
||||||
mode: if is_tun { "tun".to_string() } else { "proxy".to_string() },
|
let log_level = if let Some(ll) = json.get("log_level") {
|
||||||
debug: raw.debug.unwrap_or(false),
|
ll.clone()
|
||||||
ostp: OstpConfig {
|
} else if let Some(d) = json.get("debug") {
|
||||||
server_addr: server,
|
if d.as_bool().unwrap_or(false) { serde_json::json!("debug") } else { serde_json::json!("info") }
|
||||||
local_bind_addr: "0.0.0.0:0".to_string(),
|
} else {
|
||||||
access_key: key,
|
serde_json::json!("info")
|
||||||
handshake_timeout_ms: 5000,
|
};
|
||||||
io_timeout_ms: 2500,
|
new_json["log"] = serde_json::json!({ "level": log_level });
|
||||||
mtu,
|
|
||||||
keepalive_interval_sec: default_keepalive(),
|
|
||||||
},
|
|
||||||
local_proxy: LocalProxyConfig {
|
|
||||||
bind_addr: socks5,
|
|
||||||
connect_timeout_ms: 15000,
|
|
||||||
},
|
|
||||||
reality: RealityConfig {
|
|
||||||
sni: raw.reality.as_ref().and_then(|t| t.sni.clone()).unwrap_or_default(),
|
|
||||||
fp: raw.reality.as_ref().and_then(|t| t.fp.clone()).unwrap_or_default(),
|
|
||||||
pbk: raw.reality.as_ref().and_then(|t| t.pbk.clone()).unwrap_or_default(),
|
|
||||||
sid: raw.reality.as_ref().and_then(|t| t.sid.clone()).unwrap_or_default(),
|
|
||||||
spx: raw.reality.as_ref().and_then(|t| t.spx.clone()).unwrap_or_default(),
|
|
||||||
},
|
|
||||||
transport: TransportConfig {
|
|
||||||
mode: raw.transport.as_ref().and_then(|t| t.mode.clone()).unwrap_or_else(|| "udp".to_string()),
|
|
||||||
stealth_sni: raw.transport.as_ref().and_then(|t| t.stealth_sni.clone()).unwrap_or_else(|| "microsoft.com".to_string()),
|
|
||||||
stealth_port: raw.transport.as_ref().and_then(|t| t.stealth_port).unwrap_or(443),
|
|
||||||
},
|
|
||||||
exclusions: ExclusionConfig {
|
|
||||||
domains: exclusions.domains.unwrap_or_default(),
|
|
||||||
ips: exclusions.ips.unwrap_or_default(),
|
|
||||||
processes: exclusions.processes.unwrap_or_default(),
|
|
||||||
},
|
|
||||||
multiplex: MultiplexConfig {
|
|
||||||
enabled: mux.enabled.unwrap_or(false),
|
|
||||||
sessions: mux.sessions.unwrap_or(1),
|
|
||||||
},
|
|
||||||
dns_server: raw.tun.as_ref().and_then(|t| t.dns.clone()),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
// 2. Inbounds
|
||||||
|
let mut inbounds = Vec::new();
|
||||||
|
|
||||||
|
if let Some(tun) = json.get("tun") {
|
||||||
|
if tun.get("enable").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||||
|
inbounds.push(serde_json::json!({
|
||||||
|
"type": "tun",
|
||||||
|
"tag": "tun-in",
|
||||||
|
"auto_route": true,
|
||||||
|
"mtu": 1140
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let socks_bind = json.get("socks5_bind").and_then(|v| v.as_str()).unwrap_or("127.0.0.1:1088");
|
||||||
|
let parts: Vec<&str> = socks_bind.split(':').collect();
|
||||||
|
let listen = parts.get(0).unwrap_or(&"127.0.0.1");
|
||||||
|
let port = parts.get(1).unwrap_or(&"1088").parse::<u16>().unwrap_or(1088);
|
||||||
|
|
||||||
|
inbounds.push(serde_json::json!({
|
||||||
|
"type": "local_proxy",
|
||||||
|
"tag": "socks-in",
|
||||||
|
"protocol": "socks",
|
||||||
|
"listen": listen,
|
||||||
|
"port": port
|
||||||
|
}));
|
||||||
|
|
||||||
|
new_json["inbounds"] = serde_json::Value::Array(inbounds);
|
||||||
|
|
||||||
|
// 3. Outbounds
|
||||||
|
let mut outbounds = Vec::new();
|
||||||
|
let server_full = json.get("server").and_then(|v| v.as_str()).unwrap_or("127.0.0.1:50000");
|
||||||
|
let server_parts: Vec<&str> = server_full.split(':').collect();
|
||||||
|
let server_host = server_parts.get(0).unwrap_or(&"127.0.0.1");
|
||||||
|
let server_port = server_parts.get(1).unwrap_or(&"50000").parse::<u16>().unwrap_or(50000);
|
||||||
|
let access_key = json.get("access_key").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
|
||||||
|
let transport_type = json.get("transport").and_then(|t| t.get("mode").or(t.get("type"))).and_then(|v| v.as_str()).unwrap_or("udp");
|
||||||
|
let mux_enabled = json.get("mux").and_then(|m| m.get("enabled")).and_then(|v| v.as_bool()).unwrap_or(false);
|
||||||
|
let mux_sessions = json.get("mux").and_then(|m| m.get("sessions")).and_then(|v| v.as_u64()).unwrap_or(1);
|
||||||
|
|
||||||
|
outbounds.push(serde_json::json!({
|
||||||
|
"type": "ostp",
|
||||||
|
"tag": "proxy",
|
||||||
|
"server": server_host,
|
||||||
|
"port": server_port,
|
||||||
|
"access_key": access_key,
|
||||||
|
"transport": {
|
||||||
|
"type": transport_type
|
||||||
|
},
|
||||||
|
"multiplex": {
|
||||||
|
"enabled": mux_enabled,
|
||||||
|
"sessions": mux_sessions
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
outbounds.push(serde_json::json!({
|
||||||
|
"type": "direct",
|
||||||
|
"tag": "direct"
|
||||||
|
}));
|
||||||
|
|
||||||
|
outbounds.push(serde_json::json!({
|
||||||
|
"type": "block",
|
||||||
|
"tag": "block"
|
||||||
|
}));
|
||||||
|
|
||||||
|
new_json["outbounds"] = serde_json::Value::Array(outbounds);
|
||||||
|
|
||||||
|
// 4. Routing
|
||||||
|
let mut rules = Vec::new();
|
||||||
|
|
||||||
|
// Migrate exclusions to route to direct
|
||||||
|
if let Some(exclude) = json.get("exclude") {
|
||||||
|
if let Some(domains) = exclude.get("domains") {
|
||||||
|
rules.push(serde_json::json!({
|
||||||
|
"domain_suffix": domains,
|
||||||
|
"outbound": "direct"
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if let Some(ips) = exclude.get("ips") {
|
||||||
|
rules.push(serde_json::json!({
|
||||||
|
"ip_cidr": ips,
|
||||||
|
"outbound": "direct"
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if let Some(processes) = exclude.get("processes") {
|
||||||
|
rules.push(serde_json::json!({
|
||||||
|
"process_name": processes,
|
||||||
|
"outbound": "direct"
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new_json["routing"] = serde_json::json!({
|
||||||
|
"rules": rules,
|
||||||
|
"default_outbound": "proxy"
|
||||||
|
});
|
||||||
|
|
||||||
|
// 5. Preserve GUI state
|
||||||
|
if let Some(gui) = json.get("gui") {
|
||||||
|
new_json["gui"] = gui.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
(new_json, true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,3 +8,4 @@ pub mod tunnel;
|
||||||
|
|
||||||
|
|
||||||
pub mod runner;
|
pub mod runner;
|
||||||
|
pub mod logging;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,118 @@
|
||||||
|
use std::fs::OpenOptions;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
|
||||||
|
|
||||||
|
pub fn setup_panic_hook() {
|
||||||
|
std::panic::set_hook(Box::new(|info| {
|
||||||
|
let payload = info.payload();
|
||||||
|
let msg = if let Some(s) = payload.downcast_ref::<&str>() {
|
||||||
|
*s
|
||||||
|
} else if let Some(s) = payload.downcast_ref::<String>() {
|
||||||
|
s.as_str()
|
||||||
|
} else {
|
||||||
|
"Box<dyn Any>"
|
||||||
|
};
|
||||||
|
|
||||||
|
let location = info.location().unwrap_or_else(|| std::panic::Location::caller());
|
||||||
|
let backtrace = std::backtrace::Backtrace::force_capture();
|
||||||
|
|
||||||
|
let crash_msg = format!(
|
||||||
|
"[{}] PANIC at {}:{}\nMessage: {}\nBacktrace:\n{:?}",
|
||||||
|
chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
|
||||||
|
location.file(),
|
||||||
|
location.line(),
|
||||||
|
msg,
|
||||||
|
backtrace
|
||||||
|
);
|
||||||
|
|
||||||
|
eprintln!("{}", crash_msg);
|
||||||
|
tracing::error!("{}", crash_msg);
|
||||||
|
|
||||||
|
let path = std::env::current_exe()
|
||||||
|
.ok()
|
||||||
|
.and_then(|p| p.parent().map(|d| d.join("ostp-crash.log")))
|
||||||
|
.unwrap_or_else(|| PathBuf::from("ostp-crash.log"));
|
||||||
|
|
||||||
|
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
|
||||||
|
let _ = file.write_all(crash_msg.as_bytes());
|
||||||
|
let _ = file.write_all(b"\n===================================================\n");
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialises tracing and writes to `<app_name>.log` next to the executable.
|
||||||
|
///
|
||||||
|
/// The `level` parameter controls the minimum log level:
|
||||||
|
/// - `"error"` — only errors
|
||||||
|
/// - `"warn"` — warnings and errors
|
||||||
|
/// - `"info"` — informational messages (default)
|
||||||
|
/// - `"debug"` — detailed debug messages (use when `debug: true` in config)
|
||||||
|
/// - `"trace"` — all messages including very verbose internal state
|
||||||
|
///
|
||||||
|
/// The environment variable `RUST_LOG` overrides this value if set.
|
||||||
|
pub fn init_tracing(level: &str, app_name: &str, version: &str) -> Option<tracing_appender::non_blocking::WorkerGuard> {
|
||||||
|
// RUST_LOG overrides the config-derived level
|
||||||
|
let env_filter = EnvFilter::try_from_default_env()
|
||||||
|
.unwrap_or_else(|_| {
|
||||||
|
// When debug or trace is requested, enable for all ostp crates
|
||||||
|
if level == "debug" || level == "trace" {
|
||||||
|
// Enable the requested level for ostp crates, but keep noisy deps at warn
|
||||||
|
EnvFilter::new(format!(
|
||||||
|
"warn,ostp_client={level},ostp_core={level},ostp_jni={level},ostp_gui_lib={level}"
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
EnvFilter::new(level)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let path = std::env::current_exe()
|
||||||
|
.ok()
|
||||||
|
.and_then(|p| p.parent().map(|d| d.join(format!("{}.log", app_name))))
|
||||||
|
.unwrap_or_else(|| PathBuf::from(format!("{}.log", app_name)));
|
||||||
|
|
||||||
|
if let Ok(file) = OpenOptions::new().create(true).append(true).open(&path) {
|
||||||
|
let (file_writer, guard) = tracing_appender::non_blocking(file);
|
||||||
|
|
||||||
|
let fmt_layer = tracing_subscriber::fmt::layer()
|
||||||
|
.with_target(true)
|
||||||
|
.with_line_number(true)
|
||||||
|
.with_thread_ids(false)
|
||||||
|
.with_thread_names(false)
|
||||||
|
.with_ansi(false)
|
||||||
|
.with_writer(file_writer);
|
||||||
|
|
||||||
|
let stderr_layer = tracing_subscriber::fmt::layer()
|
||||||
|
.with_target(true)
|
||||||
|
.with_writer(std::io::stderr);
|
||||||
|
|
||||||
|
let _ = tracing_subscriber::registry()
|
||||||
|
.with(env_filter)
|
||||||
|
.with(fmt_layer)
|
||||||
|
.with(stderr_layer)
|
||||||
|
.try_init();
|
||||||
|
|
||||||
|
tracing::debug!(
|
||||||
|
"{} v{} | OS: {} | Arch: {} | log_level: {} | log_file: {}",
|
||||||
|
app_name,
|
||||||
|
version,
|
||||||
|
std::env::consts::OS,
|
||||||
|
std::env::consts::ARCH,
|
||||||
|
level,
|
||||||
|
path.display(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Some(guard)
|
||||||
|
} else {
|
||||||
|
// Fallback: stderr only
|
||||||
|
let stderr_layer = tracing_subscriber::fmt::layer()
|
||||||
|
.with_target(true)
|
||||||
|
.with_writer(std::io::stderr);
|
||||||
|
let _ = tracing_subscriber::registry()
|
||||||
|
.with(EnvFilter::new(level))
|
||||||
|
.with(stderr_layer)
|
||||||
|
.try_init();
|
||||||
|
eprintln!("[WARN] Could not open log file at {}. Logging to stderr only.", path.display());
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,332 +1,73 @@
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use tokio::sync::{mpsc, watch};
|
|
||||||
|
|
||||||
use crate::app::BridgeCommand;
|
|
||||||
use crate::bridge::{Bridge, BridgeMetrics};
|
|
||||||
use crate::signal::wait_for_shutdown_signal;
|
|
||||||
use crate::tunnel;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::fs::OpenOptions;
|
use tokio::sync::watch;
|
||||||
use std::io::Write as _;
|
|
||||||
|
|
||||||
fn log_to_core_file(msg: &str) {
|
use crate::config::{ClientConfig, InboundConfig};
|
||||||
let path = std::env::current_exe()
|
use crate::tunnel::balancer::Balancer;
|
||||||
.ok()
|
use crate::tunnel::outbounds::OutboundManager;
|
||||||
.and_then(|p| p.parent().map(|d| d.join("ostp-core.log")))
|
use crate::tunnel::router::Router;
|
||||||
.unwrap_or_else(|| std::path::PathBuf::from("ostp-core.log"));
|
|
||||||
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
|
|
||||||
let _ = writeln!(file, "[{}] {}", chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
#[link(name = "kernel32")]
|
|
||||||
extern "system" {
|
|
||||||
fn FreeConsole() -> i32;
|
|
||||||
fn GetConsoleWindow() -> *mut std::ffi::c_void;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
#[link(name = "user32")]
|
|
||||||
extern "system" {
|
|
||||||
fn ShowWindow(hwnd: *mut std::ffi::c_void, cmd_show: i32) -> i32;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hide_console() {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
unsafe {
|
|
||||||
let hwnd = GetConsoleWindow();
|
|
||||||
if !hwnd.is_null() {
|
|
||||||
ShowWindow(hwnd, 0); // SW_HIDE = 0
|
|
||||||
}
|
|
||||||
FreeConsole();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
pub fn is_admin() -> bool {
|
|
||||||
std::process::Command::new("net")
|
|
||||||
.arg("session")
|
|
||||||
.stdout(std::process::Stdio::null())
|
|
||||||
.stderr(std::process::Stdio::null())
|
|
||||||
.status()
|
|
||||||
.map(|s| s.success())
|
|
||||||
.unwrap_or(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
fn relaunch_as_admin() -> Result<()> {
|
|
||||||
use std::ffi::OsStr;
|
|
||||||
use std::os::windows::ffi::OsStrExt;
|
|
||||||
use std::ptr::null_mut;
|
|
||||||
|
|
||||||
let exe = std::env::current_exe()?;
|
|
||||||
let exe_wstr: Vec<u16> = exe.as_os_str().encode_wide().chain(Some(0)).collect();
|
|
||||||
|
|
||||||
let mut args_joined = String::new();
|
|
||||||
for arg in std::env::args().skip(1) {
|
|
||||||
if !args_joined.is_empty() {
|
|
||||||
args_joined.push(' ');
|
|
||||||
}
|
|
||||||
args_joined.push('"');
|
|
||||||
args_joined.push_str(&arg.replace('"', "\\\""));
|
|
||||||
args_joined.push('"');
|
|
||||||
}
|
|
||||||
let args_wstr: Vec<u16> = OsStr::new(&args_joined).encode_wide().chain(Some(0)).collect();
|
|
||||||
|
|
||||||
let dir = std::env::current_dir()?;
|
|
||||||
let dir_wstr: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
|
|
||||||
|
|
||||||
let verb_wstr: Vec<u16> = OsStr::new("runas").encode_wide().chain(Some(0)).collect();
|
|
||||||
|
|
||||||
#[link(name = "shell32")]
|
|
||||||
extern "system" {
|
|
||||||
fn ShellExecuteW(
|
|
||||||
hwnd: *mut std::ffi::c_void,
|
|
||||||
lpOperation: *const u16,
|
|
||||||
lpFile: *const u16,
|
|
||||||
lpParameters: *const u16,
|
|
||||||
lpDirectory: *const u16,
|
|
||||||
nShowCmd: i32,
|
|
||||||
) -> isize;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
let ret = ShellExecuteW(
|
|
||||||
null_mut(),
|
|
||||||
verb_wstr.as_ptr(),
|
|
||||||
exe_wstr.as_ptr(),
|
|
||||||
args_wstr.as_ptr(),
|
|
||||||
dir_wstr.as_ptr(),
|
|
||||||
1, // SW_SHOWNORMAL = 1
|
|
||||||
);
|
|
||||||
if ret <= 32 {
|
|
||||||
return Err(anyhow::anyhow!(
|
|
||||||
"Windows UAC Elevation failed or was denied by policy (ShellExecuteW code: {})",
|
|
||||||
ret
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::process::exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn run_client(config: crate::config::ClientConfig) -> Result<()> {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
if config.mode == "tun" && !is_admin() {
|
|
||||||
println!("[ostp] TUN mode requires administrator privileges. Relaunching...");
|
|
||||||
relaunch_as_admin()?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let bg = std::env::args().any(|a| a == "--bg");
|
|
||||||
|
|
||||||
if bg {
|
|
||||||
hide_console();
|
|
||||||
}
|
|
||||||
|
|
||||||
let metrics = Arc::new(BridgeMetrics {
|
|
||||||
bytes_sent: portable_atomic::AtomicU64::new(0),
|
|
||||||
bytes_recv: portable_atomic::AtomicU64::new(0),
|
|
||||||
connection_state: portable_atomic::AtomicU8::new(0),
|
|
||||||
rtt_ms: portable_atomic::AtomicU32::new(0),
|
|
||||||
});
|
|
||||||
|
|
||||||
let (shutdown_tx, shutdown_rx) = watch::channel(false);
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if wait_for_shutdown_signal().await.is_ok() {
|
|
||||||
let _ = shutdown_tx.send(true);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
run_client_core(config, metrics, shutdown_rx).await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn run_client_core(
|
pub async fn run_client_core(
|
||||||
config: crate::config::ClientConfig,
|
config: ClientConfig,
|
||||||
metrics: Arc<BridgeMetrics>,
|
_metrics: Arc<crate::bridge::BridgeMetrics>,
|
||||||
mut shutdown_rx_ext: watch::Receiver<bool>,
|
mut shutdown_rx_ext: watch::Receiver<bool>,
|
||||||
|
_config_rx: Option<watch::Receiver<ClientConfig>>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
#[cfg(target_os = "windows")]
|
println!("[ostp] Starting run_client_core with multi-server architecture");
|
||||||
if config.mode == "tun" && !is_admin() {
|
|
||||||
return Err(anyhow::anyhow!("Administrator privileges are required to initialize TUN mode. Please run the application as Administrator."));
|
|
||||||
}
|
|
||||||
|
|
||||||
log_to_core_file(&format!("[core] Starting run_client_core in mode: {}", config.mode));
|
let router = Arc::new(Router::new(config.routing.clone()));
|
||||||
|
let balancer = Arc::new(Balancer::new(&config));
|
||||||
|
|
||||||
|
// TODO: Detect physical interface index for bypassing
|
||||||
|
let phys_if_for_bypass = None;
|
||||||
|
let outbound_manager = Arc::new(OutboundManager::new(balancer.clone(), phys_if_for_bypass, None));
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
let mut handles = Vec::new();
|
||||||
if config.mode == "tun" {
|
|
||||||
println!("\n[ostp] ===========================================================================");
|
|
||||||
println!("[ostp] WARNING: You are starting TUN mode on a Linux system.");
|
|
||||||
println!("[ostp] If this is a remote headless server, routing all traffic through the TUN");
|
|
||||||
println!("[ostp] interface WILL DROP your SSH connection and lock you out!");
|
|
||||||
println!("[ostp] ");
|
|
||||||
println!("[ostp] SOLUTION: Add a static route for your client IP to bypass the TUN.");
|
|
||||||
println!("[ostp] Find your default gateway (ip route | grep default) and run:");
|
|
||||||
println!("[ostp] sudo ip route add <your-client-ip> via <default-gateway-ip>");
|
|
||||||
println!("[ostp] ===========================================================================\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
for inbound in config.inbounds.clone() {
|
||||||
if config.mode == "proxy" {
|
let router_clone = router.clone();
|
||||||
println!("\n[ostp] ===========================================================================");
|
let outbound_manager_clone = outbound_manager.clone();
|
||||||
println!("[ostp] Proxy mode initialized on {}", config.local_proxy.bind_addr);
|
let shutdown_rx = shutdown_rx_ext.clone();
|
||||||
println!("[ostp] To use this proxy in your current terminal session, run:");
|
let config_clone = config.clone();
|
||||||
println!("[ostp] export http_proxy=\"http://{}\"", config.local_proxy.bind_addr);
|
|
||||||
println!("[ostp] export https_proxy=\"http://{}\"", config.local_proxy.bind_addr);
|
|
||||||
println!("[ostp] export all_proxy=\"socks5://{}\"", config.local_proxy.bind_addr);
|
|
||||||
println!("[ostp] ");
|
|
||||||
println!("[ostp] For GNOME desktop system-wide proxy, you can use:");
|
|
||||||
println!("[ostp] gsettings set org.gnome.system.proxy mode 'manual'");
|
|
||||||
let mut parts = config.local_proxy.bind_addr.split(':');
|
|
||||||
let host = parts.next().unwrap_or("127.0.0.1");
|
|
||||||
let port = parts.next().unwrap_or("1088");
|
|
||||||
println!("[ostp] gsettings set org.gnome.system.proxy.http host '{}'", host);
|
|
||||||
println!("[ostp] gsettings set org.gnome.system.proxy.http port {}", port);
|
|
||||||
println!("[ostp] ===========================================================================\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
if config.mode == "tun" && !config.exclusions.processes.is_empty() {
|
match inbound.clone() {
|
||||||
println!("[ostp] Process exclusions are not supported in TUN mode");
|
InboundConfig::Tun { .. } => {
|
||||||
}
|
handles.push(tokio::spawn(async move {
|
||||||
|
if let Err(e) = crate::tunnel::inbounds::tun::run_tun_inbound(
|
||||||
let (proxy_events_tx, proxy_events_rx) = mpsc::channel(256);
|
config_clone,
|
||||||
let (client_msgs_tx, client_msgs_rx) = mpsc::unbounded_channel();
|
inbound,
|
||||||
|
router_clone,
|
||||||
let bridge = Bridge::new(&config, metrics)?;
|
outbound_manager_clone,
|
||||||
|
shutdown_rx,
|
||||||
let (ui_tx, mut ui_rx) = mpsc::channel(512);
|
).await {
|
||||||
let (cmd_tx, cmd_rx) = mpsc::channel(128);
|
tracing::error!("TUN inbound failed: {}", e);
|
||||||
let (shutdown_tx, shutdown_rx) = watch::channel(false);
|
|
||||||
let proxy_shutdown_rx = shutdown_tx.subscribe();
|
|
||||||
|
|
||||||
|
|
||||||
// Auto-connect on startup
|
|
||||||
let _ = cmd_tx.send(BridgeCommand::ToggleTunnel).await;
|
|
||||||
|
|
||||||
let debug_enabled = config.debug;
|
|
||||||
|
|
||||||
// Headless event logger
|
|
||||||
let cmd_tx_clone = cmd_tx.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut last_status = None;
|
|
||||||
while let Some(msg) = ui_rx.recv().await {
|
|
||||||
match msg {
|
|
||||||
crate::app::UiEvent::Log(text) => {
|
|
||||||
if debug_enabled || is_essential_log(&text) {
|
|
||||||
log_to_core_file(&format!("[ostp] {text}"));
|
|
||||||
println!("[ostp] {text}");
|
|
||||||
}
|
}
|
||||||
}
|
}));
|
||||||
crate::app::UiEvent::Metrics { status, rtt_ms, .. } => {
|
}
|
||||||
let status_str = status.as_str().to_string();
|
InboundConfig::LocalProxy { .. } => {
|
||||||
if last_status != Some(status_str.clone()) {
|
handles.push(tokio::spawn(async move {
|
||||||
last_status = Some(status_str.clone());
|
if let Err(e) = crate::tunnel::inbounds::local_proxy::run_socks_inbound(
|
||||||
println!("[ostp] Status: {} (rtt={:.1}ms)", status_str, rtt_ms);
|
config_clone,
|
||||||
|
inbound,
|
||||||
|
router_clone,
|
||||||
|
outbound_manager_clone,
|
||||||
|
shutdown_rx,
|
||||||
|
).await {
|
||||||
|
tracing::error!("SOCKS inbound failed: {}", e);
|
||||||
}
|
}
|
||||||
}
|
}));
|
||||||
crate::app::UiEvent::Traffic { .. } => {}
|
|
||||||
crate::app::UiEvent::ProfileChanged(profile) => {
|
|
||||||
if debug_enabled {
|
|
||||||
println!("[ostp] Obfuscation profile: {profile:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
crate::app::UiEvent::TunnelStopped => {
|
|
||||||
println!("[ostp] Connection interrupted. Reconnecting in 5 seconds...");
|
|
||||||
let cmd_tx_inner = cmd_tx_clone.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
|
|
||||||
let _ = cmd_tx_inner.send(BridgeCommand::ToggleTunnel).await;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
let mut bridge_task = tokio::spawn(async move {
|
|
||||||
bridge.run(ui_tx, cmd_rx, shutdown_rx, proxy_events_rx, client_msgs_tx).await
|
|
||||||
});
|
|
||||||
|
|
||||||
let config_clone = config.clone();
|
|
||||||
let mut proxy_task = tokio::spawn(async move {
|
|
||||||
tunnel::run_local_proxy(
|
|
||||||
config.local_proxy,
|
|
||||||
config.ostp,
|
|
||||||
config.exclusions,
|
|
||||||
config.debug,
|
|
||||||
proxy_shutdown_rx,
|
|
||||||
proxy_events_tx,
|
|
||||||
client_msgs_rx,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
});
|
|
||||||
|
|
||||||
let wintun_shutdown_rx = shutdown_tx.subscribe();
|
|
||||||
let mut wintun_task = if config_clone.mode == "tun" {
|
|
||||||
Some(tokio::spawn(async move {
|
|
||||||
tunnel::run_tun_tunnel(config_clone, wintun_shutdown_rx).await
|
|
||||||
}))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
// Wait for either external shutdown OR any task to fail
|
|
||||||
tokio::select! {
|
|
||||||
_ = shutdown_rx_ext.changed() => {
|
|
||||||
let _ = cmd_tx.send(BridgeCommand::Shutdown).await;
|
|
||||||
let _ = shutdown_tx.send(true);
|
|
||||||
}
|
|
||||||
res = &mut bridge_task => {
|
|
||||||
let _ = shutdown_tx.send(true);
|
|
||||||
res.map_err(|e| anyhow::anyhow!("Bridge task panicked: {}", e))??;
|
|
||||||
}
|
|
||||||
res = &mut proxy_task => {
|
|
||||||
let _ = shutdown_tx.send(true);
|
|
||||||
res.map_err(|e| anyhow::anyhow!("Proxy task panicked: {}", e))??;
|
|
||||||
}
|
|
||||||
res = async {
|
|
||||||
if let Some(t) = wintun_task.as_mut() { t.await } else { std::future::pending().await }
|
|
||||||
} => {
|
|
||||||
let _ = shutdown_tx.send(true);
|
|
||||||
res.map_err(|e| anyhow::anyhow!("TUN task panicked: {}", e))??;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Final cleanup: wait for tasks to finish
|
// Wait for shutdown or for tasks to fail
|
||||||
let _ = bridge_task.await;
|
tokio::select! {
|
||||||
let _ = proxy_task.await;
|
_ = shutdown_rx_ext.changed() => {
|
||||||
if let Some(task) = wintun_task {
|
if *shutdown_rx_ext.borrow() {
|
||||||
let _ = task.await;
|
tracing::info!("Shutdown signal received in run_client_core");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
fn format_bytes(bps: u64) -> String {
|
|
||||||
if bps >= 1_000_000 {
|
|
||||||
format!("{:.1}MB", bps as f64 / 1_000_000.0)
|
|
||||||
} else if bps >= 1_000 {
|
|
||||||
format!("{:.1}KB", bps as f64 / 1_000.0)
|
|
||||||
} else {
|
|
||||||
format!("{bps}B")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_essential_log(text: &str) -> bool {
|
|
||||||
matches!(
|
|
||||||
text,
|
|
||||||
"Connection established"
|
|
||||||
| "TUN tunnel established"
|
|
||||||
| "TUN tunnel stopped"
|
|
||||||
| "Bridge stopped"
|
|
||||||
| "Runtime config reloaded"
|
|
||||||
| "Connecting to remote server..."
|
|
||||||
) || text.starts_with("Connected to ")
|
|
||||||
|| text.starts_with("TURN relay allocated")
|
|
||||||
|| text.starts_with("TURN allocation failed")
|
|
||||||
|| text.starts_with("Allocating TURN relay")
|
|
||||||
|| text.starts_with("Connection failed:")
|
|
||||||
|| text.starts_with("Connection lost")
|
|
||||||
|| text.starts_with("Protocol tick fatal error")
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -64,7 +64,79 @@ pub fn enable_windows_proxy(proxy_addr: &str) {
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set bypass list to prevent proxy loop for localhost traffic
|
// Set initial bypass list (will be expanded by update_proxy_bypass_list)
|
||||||
|
update_proxy_bypass_list_windows(&[], &[]);
|
||||||
|
|
||||||
|
refresh_wininet();
|
||||||
|
tracing::info!("System proxy enabled successfully");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the Windows ProxyOverride registry value to include user-configured
|
||||||
|
/// excluded domains and IPs. This makes excluded hosts bypass the OSTP proxy
|
||||||
|
/// entirely at the OS level — the most reliable split-tunneling mechanism.
|
||||||
|
///
|
||||||
|
/// For each domain `d`, adds both `d` and `*.d` so both the root and all
|
||||||
|
/// subdomains bypass the proxy.
|
||||||
|
/// For IPs, adds them verbatim (Windows supports exact IPs and wildcards like
|
||||||
|
/// `192.168.*`).
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn update_proxy_bypass_list(domains: &[String], ips: &[String]) {
|
||||||
|
update_proxy_bypass_list_windows(domains, ips);
|
||||||
|
refresh_wininet();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
pub fn update_proxy_bypass_list(_domains: &[String], _ips: &[String]) {
|
||||||
|
// Linux/macOS: no-op (gnome/kde proxy bypass list update not implemented)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
fn update_proxy_bypass_list_windows(domains: &[String], ips: &[String]) {
|
||||||
|
// Base list: always bypass local addresses
|
||||||
|
let mut parts: Vec<String> = vec![
|
||||||
|
"localhost".into(),
|
||||||
|
"127.*".into(),
|
||||||
|
"10.*".into(),
|
||||||
|
"172.16.*".into(),
|
||||||
|
"172.17.*".into(),
|
||||||
|
"172.18.*".into(),
|
||||||
|
"172.19.*".into(),
|
||||||
|
"172.20.*".into(),
|
||||||
|
"172.21.*".into(),
|
||||||
|
"172.22.*".into(),
|
||||||
|
"172.23.*".into(),
|
||||||
|
"172.24.*".into(),
|
||||||
|
"172.25.*".into(),
|
||||||
|
"172.26.*".into(),
|
||||||
|
"172.27.*".into(),
|
||||||
|
"172.28.*".into(),
|
||||||
|
"172.29.*".into(),
|
||||||
|
"172.30.*".into(),
|
||||||
|
"172.31.*".into(),
|
||||||
|
"192.168.*".into(),
|
||||||
|
"<local>".into(),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Add excluded domains: both exact and wildcard subdomain form
|
||||||
|
for d in domains {
|
||||||
|
let d = d.trim().trim_start_matches('.').to_lowercase();
|
||||||
|
if d.is_empty() { continue; }
|
||||||
|
parts.push(d.clone());
|
||||||
|
parts.push(format!("*.{}", d));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add excluded IPs verbatim
|
||||||
|
for ip in ips {
|
||||||
|
let ip = ip.trim();
|
||||||
|
if ip.is_empty() { continue; }
|
||||||
|
// Strip CIDR suffix if present — Windows ProxyOverride doesn't support CIDR
|
||||||
|
let host = ip.split('/').next().unwrap_or(ip);
|
||||||
|
parts.push(host.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let override_value = parts.join(";");
|
||||||
|
tracing::info!("Updating ProxyOverride: {}", override_value);
|
||||||
|
|
||||||
let _ = Command::new("reg")
|
let _ = Command::new("reg")
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
.creation_flags(CREATE_NO_WINDOW)
|
||||||
.args([
|
.args([
|
||||||
|
|
@ -72,17 +144,14 @@ pub fn enable_windows_proxy(proxy_addr: &str) {
|
||||||
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
||||||
"/v", "ProxyOverride",
|
"/v", "ProxyOverride",
|
||||||
"/t", "REG_SZ",
|
"/t", "REG_SZ",
|
||||||
"/d", "localhost;127.*;10.*;192.168.*;<local>",
|
"/d", &override_value,
|
||||||
"/f",
|
"/f",
|
||||||
])
|
])
|
||||||
.output();
|
.output();
|
||||||
|
|
||||||
refresh_wininet();
|
|
||||||
tracing::info!("System proxy enabled successfully");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
pub fn disable_windows_proxy() {
|
pub fn disable_system_proxy() {
|
||||||
tracing::info!("Disabling Windows system proxy");
|
tracing::info!("Disabling Windows system proxy");
|
||||||
let _ = Command::new("reg")
|
let _ = Command::new("reg")
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
.creation_flags(CREATE_NO_WINDOW)
|
||||||
|
|
@ -118,26 +187,92 @@ fn refresh_wininet() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
pub fn enable_windows_proxy(_proxy_addr: &str) {}
|
pub fn enable_system_proxy(proxy_addr: &str) {
|
||||||
|
let parts: Vec<&str> = proxy_addr.split(':').collect();
|
||||||
|
let host = parts.get(0).unwrap_or(&"127.0.0.1");
|
||||||
|
let port = parts.get(1).unwrap_or(&"1088");
|
||||||
|
|
||||||
|
let is_gui = std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok();
|
||||||
|
|
||||||
|
if is_gui {
|
||||||
|
tracing::info!("Enabling Linux system proxy (GNOME/KDE): {}", proxy_addr);
|
||||||
|
|
||||||
|
// Try GNOME gsettings
|
||||||
|
let gnome_res = std::process::Command::new("gsettings")
|
||||||
|
.args(["set", "org.gnome.system.proxy", "mode", "manual"])
|
||||||
|
.output();
|
||||||
|
|
||||||
|
if let Ok(out) = gnome_res {
|
||||||
|
if out.status.success() {
|
||||||
|
let _ = std::process::Command::new("gsettings").args(["set", "org.gnome.system.proxy.socks", "host", host]).output();
|
||||||
|
let _ = std::process::Command::new("gsettings").args(["set", "org.gnome.system.proxy.socks", "port", port]).output();
|
||||||
|
let _ = std::process::Command::new("gsettings").args(["set", "org.gnome.system.proxy", "ignore-hosts", "['localhost', '127.0.0.0/8', '10.0.0.0/8', '192.168.0.0/16']"]).output();
|
||||||
|
tracing::info!("GNOME system proxy enabled.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try KDE kwriteconfig5/6
|
||||||
|
for cmd in ["kwriteconfig5", "kwriteconfig6"] {
|
||||||
|
let kde_res = std::process::Command::new(cmd)
|
||||||
|
.args(["--file", "kioslaverc", "--group", "Proxy Settings", "--key", "ProxyType", "1"])
|
||||||
|
.output();
|
||||||
|
|
||||||
|
if let Ok(out) = kde_res {
|
||||||
|
if out.status.success() {
|
||||||
|
let socks_val = format!("socks://{}:{}", host, port);
|
||||||
|
let _ = std::process::Command::new(cmd).args(["--file", "kioslaverc", "--group", "Proxy Settings", "--key", "socksProxy", &socks_val]).output();
|
||||||
|
let _ = std::process::Command::new("dbus-send").args(["--type=signal", "/KIO/Scheduler", "org.kde.KIO.Scheduler.reparseSlaveConfiguration", "string:''"]).output();
|
||||||
|
tracing::info!("KDE system proxy enabled.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Headless fallback
|
||||||
|
println!("\n===================================================================");
|
||||||
|
println!("OSTP Local Proxy is running at socks5://{}", proxy_addr);
|
||||||
|
println!("Since you are in a headless/terminal environment, OSTP cannot automatically");
|
||||||
|
println!("configure your system proxy. To route traffic from this terminal, run:");
|
||||||
|
println!("\n eval $(ostp --proxy-env)\n");
|
||||||
|
println!("Or configure your application (e.g. curl -x socks5://{})", proxy_addr);
|
||||||
|
println!("===================================================================\n");
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
pub fn disable_windows_proxy() {}
|
pub fn disable_system_proxy() {
|
||||||
|
let is_gui = std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok();
|
||||||
|
if is_gui {
|
||||||
|
tracing::info!("Disabling Linux system proxy...");
|
||||||
|
let _ = std::process::Command::new("gsettings").args(["set", "org.gnome.system.proxy", "mode", "none"]).output();
|
||||||
|
let _ = std::process::Command::new("kwriteconfig5").args(["--file", "kioslaverc", "--group", "Proxy Settings", "--key", "ProxyType", "0"]).output();
|
||||||
|
let _ = std::process::Command::new("kwriteconfig6").args(["--file", "kioslaverc", "--group", "Proxy Settings", "--key", "ProxyType", "0"]).output();
|
||||||
|
let _ = std::process::Command::new("dbus-send").args(["--type=signal", "/KIO/Scheduler", "org.kde.KIO.Scheduler.reparseSlaveConfiguration", "string:''"]).output();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct WindowsProxyGuard {
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn enable_system_proxy(proxy_addr: &str) {
|
||||||
|
enable_windows_proxy(proxy_addr);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub struct SystemProxyGuard {
|
||||||
active: bool,
|
active: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowsProxyGuard {
|
impl SystemProxyGuard {
|
||||||
pub fn enable(proxy_addr: &str) -> Self {
|
pub fn enable(proxy_addr: &str) -> Self {
|
||||||
enable_windows_proxy(proxy_addr);
|
enable_system_proxy(proxy_addr);
|
||||||
Self { active: true }
|
Self { active: true }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for WindowsProxyGuard {
|
impl Drop for SystemProxyGuard {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if self.active {
|
if self.active {
|
||||||
disable_windows_proxy();
|
disable_system_proxy();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,104 @@
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use tokio::net::UdpSocket;
|
||||||
|
use tokio::sync::{mpsc, Mutex};
|
||||||
|
use rand::Rng;
|
||||||
|
|
||||||
|
pub use ostp_core::dns::{
|
||||||
|
DnsPacket, DnsRecordType, encode_payload_to_domain,
|
||||||
|
decode_domain_to_payload,
|
||||||
|
};
|
||||||
|
use crate::transport::Transport;
|
||||||
|
|
||||||
|
pub async fn start_dns_transport(domain: String, resolver: String, _pubkey: Option<String>) -> std::io::Result<Transport> {
|
||||||
|
let (app_tx, transport_rx) = mpsc::channel::<Bytes>(100);
|
||||||
|
let (transport_tx, app_rx) = mpsc::channel::<Bytes>(100);
|
||||||
|
|
||||||
|
let resolver_addr = if resolver.contains(':') {
|
||||||
|
resolver.clone()
|
||||||
|
} else {
|
||||||
|
format!("{}:53", resolver)
|
||||||
|
};
|
||||||
|
|
||||||
|
let socket = UdpSocket::bind("0.0.0.0:0").await?;
|
||||||
|
socket.connect(&resolver_addr).await?;
|
||||||
|
let socket = Arc::new(socket);
|
||||||
|
|
||||||
|
let sock_rx = socket.clone();
|
||||||
|
let sock_tx = socket;
|
||||||
|
let base_domain = domain.clone();
|
||||||
|
|
||||||
|
// Send task (reads from app, encodes into DNS TXT, sends to UDP socket)
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut rx = transport_rx;
|
||||||
|
loop {
|
||||||
|
let data_opt = tokio::select! {
|
||||||
|
res = rx.recv() => res,
|
||||||
|
_ = tokio::time::sleep(Duration::from_secs(2)) => Some(Bytes::new()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let data = match data_opt {
|
||||||
|
Some(d) => d,
|
||||||
|
None => break, // App closed
|
||||||
|
};
|
||||||
|
|
||||||
|
// Encode data to base32 domain
|
||||||
|
let fqdn = encode_payload_to_domain(&data, &base_domain);
|
||||||
|
let id: u16 = rand::thread_rng().gen();
|
||||||
|
|
||||||
|
// Randomly choose TXT or NULL for diversity (as requested)
|
||||||
|
let qtype = if rand::thread_rng().gen_bool(0.5) {
|
||||||
|
DnsRecordType::TXT
|
||||||
|
} else {
|
||||||
|
DnsRecordType::NULL
|
||||||
|
};
|
||||||
|
|
||||||
|
let packet = DnsPacket::new_query(id, &fqdn, qtype);
|
||||||
|
let encoded = packet.encode();
|
||||||
|
|
||||||
|
if let Err(e) = sock_tx.send(&encoded).await {
|
||||||
|
tracing::warn!("DNS transport send error: {}", e);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Receive task (reads from UDP socket, decodes DNS answer, sends to app)
|
||||||
|
let _base_domain_rx = domain.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut buf = vec![0u8; 65535];
|
||||||
|
loop {
|
||||||
|
match sock_rx.recv(&mut buf).await {
|
||||||
|
Ok(n) => {
|
||||||
|
if let Some(packet) = DnsPacket::decode(&buf[..n]) {
|
||||||
|
for answer in packet.answers {
|
||||||
|
if answer.rtype == DnsRecordType::TXT || answer.rtype == DnsRecordType::NULL {
|
||||||
|
// If it's a TXT record, the response might be base32 encoded payload?
|
||||||
|
// Actually, dnstt puts the payload in the TXT/NULL record data.
|
||||||
|
// We'll just assume the rdata is the raw payload, or base32 encoded if it was sent as such.
|
||||||
|
// Let's just pass the raw data (TXT strings are decoded in DnsPacket::decode)
|
||||||
|
|
||||||
|
// Wait, dnstt server responds with raw bytes in NULL, and base32/chunked strings in TXT.
|
||||||
|
// Our `DnsPacket::decode` already handles extracting TXT string bytes or NULL raw bytes into `rdata`.
|
||||||
|
// Let's just send `rdata` to the app.
|
||||||
|
if transport_tx.send(Bytes::from(answer.rdata)).await.is_err() {
|
||||||
|
return; // App closed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("DNS transport recv error: {}", e);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(Transport::Dns {
|
||||||
|
tx: app_tx,
|
||||||
|
rx: Arc::new(Mutex::new(app_rx)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
pub mod xhttp;
|
pub mod dns;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::net::UdpSocket;
|
use tokio::net::UdpSocket;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
|
@ -10,6 +9,10 @@ pub enum Transport {
|
||||||
Uot {
|
Uot {
|
||||||
tx: tokio::sync::mpsc::Sender<Bytes>,
|
tx: tokio::sync::mpsc::Sender<Bytes>,
|
||||||
rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Bytes>>>,
|
rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Bytes>>>,
|
||||||
|
},
|
||||||
|
Dns {
|
||||||
|
tx: tokio::sync::mpsc::Sender<Bytes>,
|
||||||
|
rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Bytes>>>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -17,8 +20,8 @@ impl Transport {
|
||||||
pub async fn send(&self, frame: &Bytes) -> std::io::Result<usize> {
|
pub async fn send(&self, frame: &Bytes) -> std::io::Result<usize> {
|
||||||
match self {
|
match self {
|
||||||
Self::Udp(sock) => sock.send(frame).await,
|
Self::Udp(sock) => sock.send(frame).await,
|
||||||
Self::Uot { tx, .. } => {
|
Self::Uot { tx, .. } | Self::Dns { tx, .. } => {
|
||||||
tx.send(frame.clone()).await.map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "uot closed"))?;
|
tx.send(frame.clone()).await.map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "channel closed"))?;
|
||||||
Ok(frame.len())
|
Ok(frame.len())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -27,14 +30,14 @@ impl Transport {
|
||||||
pub async fn send_to(&self, frame: &Bytes, target: std::net::SocketAddr) -> std::io::Result<usize> {
|
pub async fn send_to(&self, frame: &Bytes, target: std::net::SocketAddr) -> std::io::Result<usize> {
|
||||||
match self {
|
match self {
|
||||||
Self::Udp(sock) => sock.send_to(frame, target).await,
|
Self::Udp(sock) => sock.send_to(frame, target).await,
|
||||||
Self::Uot { .. } => self.send(frame).await,
|
Self::Uot { .. } | Self::Dns { .. } => self.send(frame).await,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result<usize> {
|
pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||||
match self {
|
match self {
|
||||||
Self::Udp(sock) => sock.recv(buf).await,
|
Self::Udp(sock) => sock.recv(buf).await,
|
||||||
Self::Uot { rx, .. } => {
|
Self::Uot { rx, .. } | Self::Dns { rx, .. } => {
|
||||||
let mut rx = rx.lock().await;
|
let mut rx = rx.lock().await;
|
||||||
match rx.recv().await {
|
match rx.recv().await {
|
||||||
Some(bytes) => {
|
Some(bytes) => {
|
||||||
|
|
@ -42,7 +45,7 @@ impl Transport {
|
||||||
buf[..len].copy_from_slice(&bytes[..len]);
|
buf[..len].copy_from_slice(&bytes[..len]);
|
||||||
Ok(len)
|
Ok(len)
|
||||||
}
|
}
|
||||||
None => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "uot closed")),
|
None => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "channel closed")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -51,7 +54,7 @@ impl Transport {
|
||||||
pub fn local_addr(&self) -> std::io::Result<std::net::SocketAddr> {
|
pub fn local_addr(&self) -> std::io::Result<std::net::SocketAddr> {
|
||||||
match self {
|
match self {
|
||||||
Self::Udp(sock) => sock.local_addr(),
|
Self::Udp(sock) => sock.local_addr(),
|
||||||
Self::Uot { .. } => Ok("0.0.0.0:0".parse().unwrap()),
|
Self::Uot { .. } | Self::Dns { .. } => Ok("0.0.0.0:0".parse().unwrap()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,68 +2,19 @@ use std::net::IpAddr;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||||
use anyhow::{Result, Context};
|
use anyhow::{Result, Context};
|
||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
use hmac::{Hmac, Mac};
|
use hmac::Hmac;
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
use rustls::ClientConfig;
|
use std::pin::Pin;
|
||||||
use rustls::pki_types::ServerName;
|
use std::task::{Context as TaskContext, Poll};
|
||||||
use std::sync::Arc as StdArc;
|
use x25519_dalek::PublicKey;
|
||||||
use tokio_rustls::TlsConnector;
|
use chacha20poly1305::{aead::Aead, ChaCha20Poly1305, Nonce};
|
||||||
|
|
||||||
mod danger {
|
use ostp_core::crypto::reality::{build_client_hello, derive_keys, generate_session_id, generate_x25519_keypair, REALITY_SERVER_HANDSHAKE_RECORDS};
|
||||||
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
|
use ostp_core::framing::wss::{encode_wss_frame, decode_wss_frame, WssFrameResult};
|
||||||
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
|
|
||||||
use rustls::DigitallySignedStruct;
|
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct NoCertificateVerification;
|
|
||||||
|
|
||||||
impl ServerCertVerifier for NoCertificateVerification {
|
|
||||||
fn verify_server_cert(
|
|
||||||
&self,
|
|
||||||
_end_entity: &CertificateDer<'_>,
|
|
||||||
_intermediates: &[CertificateDer<'_>],
|
|
||||||
_server_name: &ServerName<'_>,
|
|
||||||
_ocsp_response: &[u8],
|
|
||||||
_now: UnixTime,
|
|
||||||
) -> Result<ServerCertVerified, rustls::Error> {
|
|
||||||
Ok(ServerCertVerified::assertion())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn verify_tls12_signature(
|
|
||||||
&self,
|
|
||||||
_message: &[u8],
|
|
||||||
_cert: &CertificateDer<'_>,
|
|
||||||
_dss: &DigitallySignedStruct,
|
|
||||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
|
||||||
Ok(HandshakeSignatureValid::assertion())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn verify_tls13_signature(
|
|
||||||
&self,
|
|
||||||
_message: &[u8],
|
|
||||||
_cert: &CertificateDer<'_>,
|
|
||||||
_dss: &DigitallySignedStruct,
|
|
||||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
|
||||||
Ok(HandshakeSignatureValid::assertion())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
|
||||||
vec![
|
|
||||||
rustls::SignatureScheme::RSA_PKCS1_SHA256,
|
|
||||||
rustls::SignatureScheme::RSA_PKCS1_SHA384,
|
|
||||||
rustls::SignatureScheme::RSA_PKCS1_SHA512,
|
|
||||||
rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
|
|
||||||
rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
|
|
||||||
rustls::SignatureScheme::ED25519,
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type HmacSha256 = Hmac<Sha256>;
|
type HmacSha256 = Hmac<Sha256>;
|
||||||
|
|
||||||
|
|
@ -72,33 +23,232 @@ pub async fn connect_xhttp(
|
||||||
port: u16,
|
port: u16,
|
||||||
sni: &str,
|
sni: &str,
|
||||||
access_key: &[u8],
|
access_key: &[u8],
|
||||||
tls_enabled: bool,
|
reality_enabled: bool,
|
||||||
|
wss: bool,
|
||||||
|
reality_pbk: &str,
|
||||||
|
reality_sid: &str,
|
||||||
) -> Result<(mpsc::Sender<Bytes>, Arc<tokio::sync::Mutex<mpsc::Receiver<Bytes>>>)> {
|
) -> Result<(mpsc::Sender<Bytes>, Arc<tokio::sync::Mutex<mpsc::Receiver<Bytes>>>)> {
|
||||||
let addr = std::net::SocketAddr::new(target_ip, port);
|
let addr = std::net::SocketAddr::new(target_ip, port);
|
||||||
let tcp_stream = TcpStream::connect(addr).await
|
|
||||||
.with_context(|| format!("failed to connect to {}", addr))?;
|
#[cfg(not(target_os = "android"))]
|
||||||
|
let mut tcp_stream = tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(10),
|
||||||
|
tokio::net::TcpStream::connect(addr),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| anyhow::anyhow!("TCP connect timeout to {}", addr))?
|
||||||
|
.with_context(|| format!("failed to connect to {}", addr))?;
|
||||||
|
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
let mut tcp_stream = {
|
||||||
|
let domain = if target_ip.is_ipv6() { socket2::Domain::IPV6 } else { socket2::Domain::IPV4 };
|
||||||
|
let sock = socket2::Socket::new(domain, socket2::Type::STREAM, Some(socket2::Protocol::TCP))?;
|
||||||
|
|
||||||
|
use std::os::unix::io::AsRawFd;
|
||||||
|
crate::bridge::protect_socket(sock.as_raw_fd());
|
||||||
|
|
||||||
|
sock.set_nonblocking(true)?;
|
||||||
|
let tcp_socket = tokio::net::TcpSocket::from_std_stream(sock.into());
|
||||||
|
tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(10),
|
||||||
|
tcp_socket.connect(addr),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| anyhow::anyhow!("TCP connect timeout to {}", addr))?
|
||||||
|
.with_context(|| format!("failed to connect to {}", addr))?
|
||||||
|
};
|
||||||
|
|
||||||
tcp_stream.set_nodelay(true)?;
|
tcp_stream.set_nodelay(true)?;
|
||||||
|
|
||||||
if tls_enabled {
|
if reality_enabled {
|
||||||
// Setup rustls client skipping cert validation (Reality self-signed certs)
|
let pbk_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(reality_pbk)
|
||||||
let mut config = ClientConfig::builder_with_provider(rustls::crypto::ring::default_provider().into())
|
.context("invalid reality_pbk base64")?;
|
||||||
.with_safe_default_protocol_versions()
|
if pbk_bytes.len() != 32 {
|
||||||
.unwrap()
|
anyhow::bail!("reality_pbk must be 32 bytes");
|
||||||
.dangerous()
|
}
|
||||||
.with_custom_certificate_verifier(StdArc::new(danger::NoCertificateVerification))
|
let pbk = PublicKey::from(<[u8; 32]>::try_from(pbk_bytes.as_slice()).unwrap());
|
||||||
.with_no_client_auth();
|
|
||||||
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
let sid_bytes_vec = hex::decode(reality_sid).context("invalid reality_sid hex")?;
|
||||||
|
if sid_bytes_vec.len() != 8 {
|
||||||
|
anyhow::bail!("reality_sid must be 8 bytes");
|
||||||
|
}
|
||||||
|
let sid: [u8; 8] = sid_bytes_vec.try_into().unwrap();
|
||||||
|
|
||||||
let connector = TlsConnector::from(StdArc::new(config));
|
let (c_priv, c_pub) = generate_x25519_keypair();
|
||||||
let server_name = ServerName::try_from(sni.to_string())
|
let shared_secret = c_priv.diffie_hellman(&pbk);
|
||||||
.unwrap_or_else(|_| ServerName::try_from("www.microsoft.com").unwrap())
|
let (auth_key, data_key) = derive_keys(shared_secret.as_bytes());
|
||||||
.to_owned();
|
|
||||||
|
|
||||||
let tls_stream = connector.connect(server_name, tcp_stream).await
|
let session_id = generate_session_id(&auth_key, &sid);
|
||||||
.with_context(|| "TLS handshake failed")?;
|
let client_hello = build_client_hello(if sni.is_empty() { "www.microsoft.com" } else { sni }, &session_id, &c_pub);
|
||||||
xhttp_handshake_and_loop(tls_stream, target_ip, sni, access_key).await
|
|
||||||
|
tcp_stream.write_all(&client_hello).await?;
|
||||||
|
|
||||||
|
// Drain all server handshake records (ServerHello, CCS, fake encrypted records).
|
||||||
|
// The server sends exactly REALITY_SERVER_HANDSHAKE_RECORDS records before data starts.
|
||||||
|
// Reading them explicitly prevents RealityStream from seeing non-AppData bytes.
|
||||||
|
for i in 0..REALITY_SERVER_HANDSHAKE_RECORDS {
|
||||||
|
let mut head = [0u8; 5];
|
||||||
|
tcp_stream.read_exact(&mut head).await
|
||||||
|
.with_context(|| format!("reality handshake: failed reading record {} header", i))?;
|
||||||
|
if i == 0 && head[0] != 0x16 {
|
||||||
|
anyhow::bail!("expected ServerHello (0x16), got 0x{:02x}", head[0]);
|
||||||
|
}
|
||||||
|
let record_len = u16::from_be_bytes([head[3], head[4]]) as usize;
|
||||||
|
if record_len > 16384 {
|
||||||
|
anyhow::bail!("reality handshake: record {} too large: {} bytes", i, record_len);
|
||||||
|
}
|
||||||
|
let mut _payload = vec![0u8; record_len];
|
||||||
|
tcp_stream.read_exact(&mut _payload).await
|
||||||
|
.with_context(|| format!("reality handshake: failed reading record {} payload", i))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let reality_stream = RealityStream::new(tcp_stream, data_key);
|
||||||
|
xhttp_handshake_and_loop(reality_stream, target_ip, sni, access_key, wss).await
|
||||||
} else {
|
} else {
|
||||||
xhttp_handshake_and_loop(tcp_stream, target_ip, sni, access_key).await
|
xhttp_handshake_and_loop(tcp_stream, target_ip, sni, access_key, wss).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------
|
||||||
|
// RealityStream: Wraps a TCP stream in fake TLS Application Data Records
|
||||||
|
// -----------------------------------------------------------------------
|
||||||
|
struct RealityStream {
|
||||||
|
inner: TcpStream,
|
||||||
|
data_key: ChaCha20Poly1305,
|
||||||
|
rx_nonce: u64,
|
||||||
|
tx_nonce: u64,
|
||||||
|
rx_buf: BytesMut,
|
||||||
|
plaintext_buf: BytesMut,
|
||||||
|
tx_buf: BytesMut,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RealityStream {
|
||||||
|
fn new(inner: TcpStream, data_key: ChaCha20Poly1305) -> Self {
|
||||||
|
Self {
|
||||||
|
inner,
|
||||||
|
data_key,
|
||||||
|
rx_nonce: 0,
|
||||||
|
tx_nonce: 0,
|
||||||
|
rx_buf: BytesMut::with_capacity(16384),
|
||||||
|
plaintext_buf: BytesMut::new(),
|
||||||
|
tx_buf: BytesMut::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_nonce(seq: u64) -> [u8; 12] {
|
||||||
|
let mut nonce = [0u8; 12];
|
||||||
|
nonce[4..12].copy_from_slice(&seq.to_le_bytes());
|
||||||
|
nonce
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl tokio::io::AsyncRead for RealityStream {
|
||||||
|
fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut tokio::io::ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
loop {
|
||||||
|
if !self.plaintext_buf.is_empty() {
|
||||||
|
let out_len = std::cmp::min(buf.remaining(), self.plaintext_buf.len());
|
||||||
|
buf.put_slice(&self.plaintext_buf[..out_len]);
|
||||||
|
self.plaintext_buf.advance(out_len);
|
||||||
|
return Poll::Ready(Ok(()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.rx_buf.len() >= 5 {
|
||||||
|
let len = u16::from_be_bytes([self.rx_buf[3], self.rx_buf[4]]) as usize;
|
||||||
|
if self.rx_buf.len() >= 5 + len {
|
||||||
|
if self.rx_buf[0] != 0x17 {
|
||||||
|
return Poll::Ready(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected application data record")));
|
||||||
|
}
|
||||||
|
|
||||||
|
let ciphertext = &self.rx_buf[5..5+len];
|
||||||
|
let nonce_bytes = Self::make_nonce(self.rx_nonce);
|
||||||
|
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||||
|
|
||||||
|
match self.data_key.decrypt(nonce, ciphertext) {
|
||||||
|
Ok(plaintext) => {
|
||||||
|
self.rx_nonce += 1;
|
||||||
|
self.plaintext_buf.put_slice(&plaintext);
|
||||||
|
self.rx_buf.advance(5 + len);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
return Poll::Ready(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "reality decrypt failed")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut read_buf = [0u8; 8192];
|
||||||
|
let mut tokio_buf = tokio::io::ReadBuf::new(&mut read_buf);
|
||||||
|
match Pin::new(&mut self.inner).poll_read(cx, &mut tokio_buf) {
|
||||||
|
Poll::Ready(Ok(())) => {
|
||||||
|
if tokio_buf.filled().is_empty() {
|
||||||
|
return Poll::Ready(Ok(()));
|
||||||
|
}
|
||||||
|
self.rx_buf.put_slice(tokio_buf.filled());
|
||||||
|
}
|
||||||
|
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
|
||||||
|
Poll::Pending => return Poll::Pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl tokio::io::AsyncWrite for RealityStream {
|
||||||
|
fn poll_write(self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
|
||||||
|
let this = self.get_mut();
|
||||||
|
while !this.tx_buf.is_empty() {
|
||||||
|
match Pin::new(&mut this.inner).poll_write(cx, &this.tx_buf) {
|
||||||
|
Poll::Ready(Ok(n)) => this.tx_buf.advance(n),
|
||||||
|
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
|
||||||
|
Poll::Pending => return Poll::Pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let nonce_bytes = Self::make_nonce(this.tx_nonce);
|
||||||
|
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||||
|
|
||||||
|
match this.data_key.encrypt(nonce, buf) {
|
||||||
|
Ok(ciphertext) => {
|
||||||
|
this.tx_nonce += 1;
|
||||||
|
this.tx_buf.reserve(5 + ciphertext.len());
|
||||||
|
this.tx_buf.put_u8(0x17);
|
||||||
|
this.tx_buf.put_u16(0x0303);
|
||||||
|
this.tx_buf.put_u16(ciphertext.len() as u16);
|
||||||
|
this.tx_buf.put_slice(&ciphertext);
|
||||||
|
|
||||||
|
match Pin::new(&mut this.inner).poll_write(cx, &this.tx_buf) {
|
||||||
|
Poll::Ready(Ok(n)) => this.tx_buf.advance(n),
|
||||||
|
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
|
||||||
|
Poll::Pending => {}
|
||||||
|
}
|
||||||
|
Poll::Ready(Ok(buf.len()))
|
||||||
|
}
|
||||||
|
Err(_) => Poll::Ready(Err(std::io::Error::new(std::io::ErrorKind::Other, "reality encrypt failed"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
let this = self.get_mut();
|
||||||
|
while !this.tx_buf.is_empty() {
|
||||||
|
match Pin::new(&mut this.inner).poll_write(cx, &this.tx_buf) {
|
||||||
|
Poll::Ready(Ok(n)) => this.tx_buf.advance(n),
|
||||||
|
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
|
||||||
|
Poll::Pending => return Poll::Pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Pin::new(&mut this.inner).poll_flush(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
let this = self.get_mut();
|
||||||
|
while !this.tx_buf.is_empty() {
|
||||||
|
match Pin::new(&mut this.inner).poll_write(cx, &this.tx_buf) {
|
||||||
|
Poll::Ready(Ok(n)) => this.tx_buf.advance(n),
|
||||||
|
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
|
||||||
|
Poll::Pending => return Poll::Pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Pin::new(&mut this.inner).poll_shutdown(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -107,6 +257,7 @@ async fn xhttp_handshake_and_loop<S>(
|
||||||
target_ip: IpAddr,
|
target_ip: IpAddr,
|
||||||
sni: &str,
|
sni: &str,
|
||||||
access_key: &[u8],
|
access_key: &[u8],
|
||||||
|
wss: bool,
|
||||||
) -> Result<(mpsc::Sender<Bytes>, Arc<tokio::sync::Mutex<mpsc::Receiver<Bytes>>>)>
|
) -> Result<(mpsc::Sender<Bytes>, Arc<tokio::sync::Mutex<mpsc::Receiver<Bytes>>>)>
|
||||||
where
|
where
|
||||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
|
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
|
||||||
|
|
@ -114,7 +265,8 @@ where
|
||||||
// 1. Generate auth token: [8-byte timestamp BE] ++ [HMAC-SHA256]
|
// 1. Generate auth token: [8-byte timestamp BE] ++ [HMAC-SHA256]
|
||||||
let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
|
let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
|
||||||
let ts_bytes = timestamp.to_be_bytes();
|
let ts_bytes = timestamp.to_be_bytes();
|
||||||
let mut mac = HmacSha256::new_from_slice(access_key).unwrap_or_else(|_| HmacSha256::new_from_slice(b"").unwrap());
|
use hmac::Mac;
|
||||||
|
let mut mac = <HmacSha256 as Mac>::new_from_slice(access_key).unwrap_or_else(|_| <HmacSha256 as Mac>::new_from_slice(b"").unwrap());
|
||||||
mac.update(&ts_bytes);
|
mac.update(&ts_bytes);
|
||||||
let mac_bytes = mac.finalize().into_bytes();
|
let mac_bytes = mac.finalize().into_bytes();
|
||||||
|
|
||||||
|
|
@ -126,99 +278,117 @@ where
|
||||||
|
|
||||||
let http_host = if sni.is_empty() { target_ip.to_string() } else { sni.to_string() };
|
let http_host = if sni.is_empty() { target_ip.to_string() } else { sni.to_string() };
|
||||||
|
|
||||||
// 2. Send fake WebSocket upgrade — looks like a legit browser request to bypass DPI/proxies.
|
let req = if wss {
|
||||||
let req = format!(
|
format!(
|
||||||
"GET /stream HTTP/1.1\r\n\
|
"GET /wss HTTP/1.1\r\n\
|
||||||
Host: {}\r\n\
|
Host: {}\r\n\
|
||||||
Upgrade: websocket\r\n\
|
Upgrade: websocket\r\n\
|
||||||
Connection: upgrade\r\n\
|
Connection: upgrade\r\n\
|
||||||
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
|
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
|
||||||
Sec-WebSocket-Version: 13\r\n\
|
Sec-WebSocket-Version: 13\r\n\
|
||||||
Authorization: Bearer {}\r\n\
|
Authorization: Bearer {}\r\n\
|
||||||
\r\n",
|
\r\n",
|
||||||
http_host, auth_token
|
http_host, auth_token
|
||||||
);
|
)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"GET /stream HTTP/1.1\r\n\
|
||||||
|
Host: {}\r\n\
|
||||||
|
Authorization: Bearer {}\r\n\
|
||||||
|
\r\n",
|
||||||
|
http_host, auth_token
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
stream.write_all(req.as_bytes()).await?;
|
stream.write_all(req.as_bytes()).await?;
|
||||||
stream.flush().await?;
|
|
||||||
|
|
||||||
// 3. Read server response headers
|
// Wait for HTTP 200 OK or 101 Switching Protocols
|
||||||
let mut buf = vec![0u8; 4096];
|
let mut header_buf = Vec::new();
|
||||||
let mut header_len = 0;
|
let mut temp = [0u8; 1];
|
||||||
loop {
|
loop {
|
||||||
let n = stream.read(&mut buf[header_len..]).await?;
|
let n = stream.read(&mut temp).await?;
|
||||||
if n == 0 { anyhow::bail!("connection closed before handshake complete"); }
|
if n == 0 {
|
||||||
header_len += n;
|
anyhow::bail!("connection closed by server during handshake");
|
||||||
if buf[..header_len].windows(4).any(|w| w == b"\r\n\r\n") { break; }
|
|
||||||
if header_len >= buf.len() { anyhow::bail!("server response headers too large"); }
|
|
||||||
}
|
|
||||||
|
|
||||||
let resp = String::from_utf8_lossy(&buf[..header_len]);
|
|
||||||
if !resp.starts_with("HTTP/1.1 101 ") && !resp.starts_with("HTTP/1.1 200 ") {
|
|
||||||
anyhow::bail!("xHTTP handshake failed: expected 101 or 200, got: {}", resp.lines().next().unwrap_or(""));
|
|
||||||
}
|
|
||||||
if !resp.to_ascii_lowercase().contains("x-ostp-server:") {
|
|
||||||
let safe_resp = resp.chars().take(200).collect::<String>().replace("\r\n", " | ");
|
|
||||||
anyhow::bail!("xHTTP handshake failed: endpoint is not an OSTP server. Got: {}", safe_resp);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Extract leftover bytes after headers (data that arrived together with the response)
|
|
||||||
let headers_end = buf[..header_len].windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
|
|
||||||
let leftover = buf[headers_end..header_len].to_vec();
|
|
||||||
|
|
||||||
// 5. Split into read/write halves and start UoT loops
|
|
||||||
let (rx, tx) = tokio::io::split(stream);
|
|
||||||
start_uot_loops(rx, tx, leftover)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn start_uot_loops<R, W>(
|
|
||||||
mut net_rx: R,
|
|
||||||
mut net_tx: W,
|
|
||||||
leftover: Vec<u8>
|
|
||||||
) -> Result<(mpsc::Sender<Bytes>, Arc<tokio::sync::Mutex<mpsc::Receiver<Bytes>>>)>
|
|
||||||
where
|
|
||||||
R: tokio::io::AsyncRead + Unpin + Send + 'static,
|
|
||||||
W: tokio::io::AsyncWrite + Unpin + Send + 'static,
|
|
||||||
{
|
|
||||||
let (app_tx, mut tx_rx) = mpsc::channel::<Bytes>(1024);
|
|
||||||
let (rx_tx, app_rx) = mpsc::channel::<Bytes>(1024);
|
|
||||||
|
|
||||||
// TX Loop (App -> UoT -> Network): prefix each frame with u16 BE length
|
|
||||||
tokio::spawn(async move {
|
|
||||||
while let Some(frame) = tx_rx.recv().await {
|
|
||||||
let len = frame.len() as u16;
|
|
||||||
if net_tx.write_u16(len).await.is_err() { break; }
|
|
||||||
if net_tx.write_all(&frame).await.is_err() { break; }
|
|
||||||
}
|
}
|
||||||
});
|
header_buf.push(temp[0]);
|
||||||
|
if header_buf.ends_with(b"\r\n\r\n") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if header_buf.len() > 8192 {
|
||||||
|
anyhow::bail!("server response too long");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// RX Loop (Network -> UoT -> App): parse [u16 len][payload] frames
|
let resp_str = String::from_utf8_lossy(&header_buf);
|
||||||
tokio::spawn(async move {
|
if wss {
|
||||||
let mut buffer = BytesMut::from(&leftover[..]);
|
if !resp_str.starts_with("HTTP/1.1 101 ") {
|
||||||
loop {
|
anyhow::bail!("failed to switch protocols: {}", resp_str.lines().next().unwrap_or(""));
|
||||||
while buffer.len() < 2 {
|
}
|
||||||
let mut temp = [0u8; 4096];
|
} else {
|
||||||
match net_rx.read(&mut temp).await {
|
if !resp_str.starts_with("HTTP/1.1 200 OK") {
|
||||||
Ok(0) | Err(_) => return,
|
anyhow::bail!("server rejected stream: {}", resp_str.lines().next().unwrap_or(""));
|
||||||
Ok(n) => buffer.extend_from_slice(&temp[..n]),
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
let len = u16::from_be_bytes([buffer[0], buffer[1]]) as usize;
|
|
||||||
|
|
||||||
while buffer.len() < 2 + len {
|
let (tx, mut rx) = mpsc::channel::<Bytes>(16384);
|
||||||
let mut temp = [0u8; 4096];
|
let (mut read_half, mut write_half) = tokio::io::split(stream);
|
||||||
match net_rx.read(&mut temp).await {
|
|
||||||
Ok(0) | Err(_) => return,
|
|
||||||
Ok(n) => buffer.extend_from_slice(&temp[..n]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let packet = buffer.split_to(2 + len);
|
let writer_task = tokio::spawn(async move {
|
||||||
if rx_tx.send(Bytes::from(packet[2..].to_vec())).await.is_err() {
|
while let Some(packet) = rx.recv().await {
|
||||||
break;
|
if wss {
|
||||||
|
let header = encode_wss_frame(&packet, true);
|
||||||
|
if write_half.write_all(&header).await.is_err() { break; }
|
||||||
|
} else {
|
||||||
|
let mut out = BytesMut::with_capacity(2 + packet.len());
|
||||||
|
out.put_u16(packet.len() as u16);
|
||||||
|
out.put_slice(&packet);
|
||||||
|
if write_half.write_all(&out).await.is_err() { break; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok((app_tx, Arc::new(tokio::sync::Mutex::new(app_rx))))
|
let (in_tx, in_rx) = mpsc::channel::<Bytes>(16384);
|
||||||
|
let in_rx_arc = Arc::new(tokio::sync::Mutex::new(in_rx));
|
||||||
|
|
||||||
|
let in_tx_clone = in_tx.clone();
|
||||||
|
let reader_task = tokio::spawn(async move {
|
||||||
|
if wss {
|
||||||
|
let mut read_buf = BytesMut::with_capacity(65536);
|
||||||
|
let mut tmp = [0u8; 8192];
|
||||||
|
loop {
|
||||||
|
match read_half.read(&mut tmp).await {
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(n) => {
|
||||||
|
read_buf.put_slice(&tmp[..n]);
|
||||||
|
loop {
|
||||||
|
match decode_wss_frame(&mut read_buf) {
|
||||||
|
WssFrameResult::Frame { payload, total_len } => {
|
||||||
|
if in_tx_clone.send(Bytes::from(payload)).await.is_err() { return; }
|
||||||
|
read_buf.advance(total_len);
|
||||||
|
}
|
||||||
|
WssFrameResult::Incomplete => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let mut len_buf = [0u8; 2];
|
||||||
|
loop {
|
||||||
|
if read_half.read_exact(&mut len_buf).await.is_err() { break; }
|
||||||
|
let len = u16::from_be_bytes(len_buf) as usize;
|
||||||
|
if len > 65535 { break; }
|
||||||
|
let mut data = vec![0u8; len];
|
||||||
|
if read_half.read_exact(&mut data).await.is_err() { break; }
|
||||||
|
if in_tx_clone.send(Bytes::from(data)).await.is_err() { break; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = tokio::join!(writer_task, reader_task);
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok((tx, in_rx_arc))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,65 @@
|
||||||
|
use crate::config::{ClientConfig, OutboundConfig};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
pub struct Balancer {
|
||||||
|
outbounds: HashMap<String, OutboundConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Balancer {
|
||||||
|
pub fn new(config: &ClientConfig) -> Self {
|
||||||
|
let mut outbounds = HashMap::new();
|
||||||
|
for outbound in &config.outbounds {
|
||||||
|
let tag = match outbound {
|
||||||
|
OutboundConfig::Selector { tag, .. } => tag,
|
||||||
|
OutboundConfig::Urltest { tag, .. } => tag,
|
||||||
|
OutboundConfig::Ostp { tag, .. } => tag,
|
||||||
|
OutboundConfig::Direct { tag } => tag,
|
||||||
|
OutboundConfig::Socks { tag, .. } => tag,
|
||||||
|
OutboundConfig::Block { tag } => tag,
|
||||||
|
};
|
||||||
|
outbounds.insert(tag.clone(), outbound.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
Self { outbounds }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves an outbound tag into a concrete, non-group outbound tag.
|
||||||
|
/// E.g. "proxy-group" -> "server-helsinki"
|
||||||
|
pub fn resolve_outbound(&self, tag: &str) -> String {
|
||||||
|
// Prevent infinite loops if groups point to groups
|
||||||
|
let mut current_tag = tag.to_string();
|
||||||
|
for _ in 0..10 {
|
||||||
|
if let Some(outbound) = self.outbounds.get(¤t_tag) {
|
||||||
|
match outbound {
|
||||||
|
OutboundConfig::Selector { outbounds, default, .. } => {
|
||||||
|
current_tag = if let Some(def) = default {
|
||||||
|
def.clone()
|
||||||
|
} else {
|
||||||
|
outbounds.first().cloned().unwrap_or_else(|| "direct".to_string())
|
||||||
|
};
|
||||||
|
}
|
||||||
|
OutboundConfig::Urltest { outbounds, .. } => {
|
||||||
|
// TODO: Implement background ping worker to find the fastest node.
|
||||||
|
// For now, act as a fallback by taking the first available node.
|
||||||
|
current_tag = outbounds.first().cloned().unwrap_or_else(|| "direct".to_string());
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// It's a concrete physical outbound (ostp, direct, block)
|
||||||
|
return current_tag;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Outbound not found, fallback to direct
|
||||||
|
return "direct".to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"direct".to_string() // Max depth reached
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetches the config for a concrete outbound
|
||||||
|
pub fn get_concrete_outbound(&self, tag: &str) -> Option<&OutboundConfig> {
|
||||||
|
let resolved_tag = self.resolve_outbound(tag);
|
||||||
|
tracing::debug!("Balancer: tag '{}' resolved to '{}'", tag, resolved_tag);
|
||||||
|
self.outbounds.get(&resolved_tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,134 @@
|
||||||
|
use crate::config::ExclusionConfig;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::time::timeout;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ExclusionMatcher {
|
||||||
|
pub domain_suffix: Vec<String>,
|
||||||
|
pub cidrs: Vec<Cidr>,
|
||||||
|
pub processes: Vec<String>,
|
||||||
|
pub physical_if_index: Option<u32>,
|
||||||
|
pub physical_if_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExclusionMatcher {
|
||||||
|
pub fn new(
|
||||||
|
exclusions: &ExclusionConfig,
|
||||||
|
physical_if_index: Option<u32>,
|
||||||
|
physical_if_name: Option<String>,
|
||||||
|
) -> Self {
|
||||||
|
let mut cidrs = Vec::new();
|
||||||
|
for ip in &exclusions.ips {
|
||||||
|
if let Some(cidr) = parse_cidr(ip) {
|
||||||
|
cidrs.push(cidr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let processes = exclusions.processes.iter()
|
||||||
|
.map(|p| p.trim().to_lowercase())
|
||||||
|
.filter(|p| !p.is_empty())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
domain_suffix: exclusions
|
||||||
|
.domains
|
||||||
|
.iter()
|
||||||
|
.map(|d| d.trim().trim_start_matches('.').to_lowercase())
|
||||||
|
.filter(|d| !d.is_empty())
|
||||||
|
.collect(),
|
||||||
|
cidrs,
|
||||||
|
processes,
|
||||||
|
physical_if_index,
|
||||||
|
physical_if_name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn should_bypass_target(&self, host: &str, port: u16, timeout_value: Duration) -> bool {
|
||||||
|
if self.match_domain(host) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.cidrs.is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
|
||||||
|
return self.match_ip(&ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
let lookup_target = (host.to_string(), port);
|
||||||
|
match timeout(timeout_value, tokio::net::lookup_host(lookup_target)).await {
|
||||||
|
Ok(Ok(addrs)) => addrs.into_iter().any(|addr| self.match_ip(&addr.ip())),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn match_domain(&self, host: &str) -> bool {
|
||||||
|
if self.domain_suffix.is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let host = host.trim_end_matches('.').to_lowercase();
|
||||||
|
self.domain_suffix.iter().any(|suffix| {
|
||||||
|
host == *suffix || host.ends_with(&format!(".{suffix}"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn match_ip(&self, ip: &std::net::IpAddr) -> bool {
|
||||||
|
self.cidrs.iter().any(|cidr| cidr.contains(ip))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn match_process(&self, process_name: &str) -> bool {
|
||||||
|
if self.processes.is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let p = process_name.to_lowercase();
|
||||||
|
self.processes.iter().any(|ex| p.contains(ex))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum Cidr {
|
||||||
|
V4(u32, u8),
|
||||||
|
V6(u128, u8),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Cidr {
|
||||||
|
pub fn contains(&self, ip: &std::net::IpAddr) -> bool {
|
||||||
|
match (self, ip) {
|
||||||
|
(Cidr::V4(net, bits), std::net::IpAddr::V4(addr)) => {
|
||||||
|
let mask = if *bits == 0 { 0 } else { u32::MAX << (32 - bits) };
|
||||||
|
let ip = u32::from_be_bytes(addr.octets());
|
||||||
|
(ip & mask) == (*net & mask)
|
||||||
|
}
|
||||||
|
(Cidr::V6(net, bits), std::net::IpAddr::V6(addr)) => {
|
||||||
|
let mask = if *bits == 0 { 0 } else { u128::MAX << (128 - bits) };
|
||||||
|
let ip = u128::from_be_bytes(addr.octets());
|
||||||
|
(ip & mask) == (*net & mask)
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_cidr(s: &str) -> Option<Cidr> {
|
||||||
|
let parts: Vec<&str> = s.split('/').collect();
|
||||||
|
if parts.is_empty() || parts.len() > 2 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if let Ok(ip) = parts[0].parse::<std::net::IpAddr>() {
|
||||||
|
let bits = if parts.len() == 2 {
|
||||||
|
parts[1].parse::<u8>().ok()?
|
||||||
|
} else {
|
||||||
|
match ip {
|
||||||
|
std::net::IpAddr::V4(_) => 32,
|
||||||
|
std::net::IpAddr::V6(_) => 128,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match ip {
|
||||||
|
std::net::IpAddr::V4(v4) => Some(Cidr::V4(u32::from_be_bytes(v4.octets()), bits)),
|
||||||
|
std::net::IpAddr::V6(v6) => Some(Cidr::V6(u128::from_be_bytes(v6.octets()), bits)),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,231 @@
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use crate::config::{ClientConfig, InboundConfig};
|
||||||
|
use crate::tunnel::router::{Router, Session};
|
||||||
|
use crate::tunnel::outbounds::OutboundManager;
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::sync::watch;
|
||||||
|
|
||||||
|
pub async fn run_socks_inbound(
|
||||||
|
_config: ClientConfig,
|
||||||
|
inbound_config: InboundConfig,
|
||||||
|
router: Arc<Router>,
|
||||||
|
outbound_manager: Arc<OutboundManager>,
|
||||||
|
mut shutdown: watch::Receiver<bool>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let InboundConfig::LocalProxy { tag, protocol, listen, port, set_system_proxy } = inbound_config else {
|
||||||
|
return Err(anyhow!("Invalid config for LocalProxy inbound"));
|
||||||
|
};
|
||||||
|
|
||||||
|
let bind_addr = format!("{}:{}", listen, port);
|
||||||
|
tracing::info!("Starting {} proxy inbound on {} (tag: {})", protocol, bind_addr, tag);
|
||||||
|
|
||||||
|
let _proxy_guard = if set_system_proxy {
|
||||||
|
let proxy_host = if listen == "0.0.0.0" { "127.0.0.1" } else { &listen };
|
||||||
|
Some(crate::sysproxy::SystemProxyGuard::enable(&format!("{}:{}", proxy_host, port)))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let listener = TcpListener::bind(&bind_addr).await?;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = shutdown.changed() => {
|
||||||
|
tracing::info!("Local proxy inbound {} shutting down", tag);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
accept_res = listener.accept() => {
|
||||||
|
if let Ok((mut stream, client_addr)) = accept_res {
|
||||||
|
let rt = router.clone();
|
||||||
|
let om = outbound_manager.clone();
|
||||||
|
let proto = protocol.clone();
|
||||||
|
let inbound_tag = tag.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if proto == "socks" {
|
||||||
|
if let Err(e) = handle_socks5_connection(&mut stream, &rt, &om, &inbound_tag, client_addr).await {
|
||||||
|
tracing::debug!("SOCKS5 handling error: {}", e);
|
||||||
|
}
|
||||||
|
} else if proto == "http" {
|
||||||
|
if let Err(e) = handle_http_connection(&mut stream, &rt, &om, &inbound_tag, client_addr).await {
|
||||||
|
tracing::debug!("HTTP proxy handling error: {}", e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tracing::error!("Unknown local proxy protocol: {}", proto);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_socks5_connection(
|
||||||
|
stream: &mut tokio::net::TcpStream,
|
||||||
|
router: &Arc<Router>,
|
||||||
|
outbound_manager: &Arc<OutboundManager>,
|
||||||
|
inbound_tag: &str,
|
||||||
|
client_addr: std::net::SocketAddr,
|
||||||
|
) -> Result<()> {
|
||||||
|
let mut buf = [0u8; 256];
|
||||||
|
|
||||||
|
// Read version and method selection
|
||||||
|
stream.read_exact(&mut buf[0..2]).await?;
|
||||||
|
if buf[0] != 0x05 {
|
||||||
|
return Err(anyhow!("Unsupported SOCKS version: {}", buf[0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
let num_methods = buf[1] as usize;
|
||||||
|
stream.read_exact(&mut buf[0..num_methods]).await?;
|
||||||
|
|
||||||
|
// Reply with NO AUTHENTICATION REQUIRED (0x00)
|
||||||
|
stream.write_all(&[0x05, 0x00]).await?;
|
||||||
|
|
||||||
|
// Read the actual request
|
||||||
|
stream.read_exact(&mut buf[0..4]).await?;
|
||||||
|
if buf[0] != 0x05 || buf[1] != 0x01 { // Only CONNECT is supported
|
||||||
|
return Err(anyhow!("Unsupported SOCKS command"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let atyp = buf[3];
|
||||||
|
let (target_host, ip_addr) = match atyp {
|
||||||
|
0x01 => { // IPv4
|
||||||
|
stream.read_exact(&mut buf[0..4]).await?;
|
||||||
|
let ip = std::net::Ipv4Addr::new(buf[0], buf[1], buf[2], buf[3]);
|
||||||
|
(ip.to_string(), Some(std::net::IpAddr::V4(ip)))
|
||||||
|
}
|
||||||
|
0x03 => { // Domain
|
||||||
|
stream.read_exact(&mut buf[0..1]).await?;
|
||||||
|
let domain_len = buf[0] as usize;
|
||||||
|
stream.read_exact(&mut buf[0..domain_len]).await?;
|
||||||
|
let domain = String::from_utf8_lossy(&buf[0..domain_len]).to_string();
|
||||||
|
(domain, None)
|
||||||
|
}
|
||||||
|
0x04 => { // IPv6
|
||||||
|
stream.read_exact(&mut buf[0..16]).await?;
|
||||||
|
let mut ip_bytes = [0u8; 16];
|
||||||
|
ip_bytes.copy_from_slice(&buf[0..16]);
|
||||||
|
let ip = std::net::Ipv6Addr::from(ip_bytes);
|
||||||
|
(ip.to_string(), Some(std::net::IpAddr::V6(ip)))
|
||||||
|
}
|
||||||
|
_ => return Err(anyhow!("Unsupported SOCKS address type: {}", atyp)),
|
||||||
|
};
|
||||||
|
|
||||||
|
stream.read_exact(&mut buf[0..2]).await?;
|
||||||
|
let target_port = u16::from_be_bytes([buf[0], buf[1]]);
|
||||||
|
|
||||||
|
let process_name = crate::tunnel::process_lookup::get_process_name_from_port(client_addr.port());
|
||||||
|
|
||||||
|
let session = Session {
|
||||||
|
protocol: "tcp".to_string(),
|
||||||
|
inbound_tag: inbound_tag.to_string(),
|
||||||
|
source_ip: Some(client_addr.ip()),
|
||||||
|
destination_ip: ip_addr,
|
||||||
|
destination_port: target_port,
|
||||||
|
sni: if atyp == 0x03 { Some(target_host.clone()) } else { None },
|
||||||
|
process_name,
|
||||||
|
};
|
||||||
|
|
||||||
|
let outbound_tag = router.route(&session);
|
||||||
|
tracing::info!("SOCKS5 TCP {} -> {}:{} routed to {}", client_addr, target_host, target_port, outbound_tag);
|
||||||
|
|
||||||
|
match outbound_manager.dial_tcp(&outbound_tag, &target_host, target_port).await {
|
||||||
|
Ok(mut remote_stream) => {
|
||||||
|
// Reply success
|
||||||
|
stream.write_all(&[0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]).await?;
|
||||||
|
|
||||||
|
// Forward data
|
||||||
|
tokio::io::copy_bidirectional(stream, &mut remote_stream).await?;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("SOCKS5 TCP dial failed to {}: {}", outbound_tag, e);
|
||||||
|
// Reply host unreachable
|
||||||
|
let _ = stream.write_all(&[0x05, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_http_connection(
|
||||||
|
stream: &mut tokio::net::TcpStream,
|
||||||
|
router: &Arc<Router>,
|
||||||
|
outbound_manager: &Arc<OutboundManager>,
|
||||||
|
inbound_tag: &str,
|
||||||
|
client_addr: std::net::SocketAddr,
|
||||||
|
) -> Result<()> {
|
||||||
|
// Basic HTTP CONNECT implementation
|
||||||
|
let mut buf = [0u8; 4096];
|
||||||
|
let n = stream.read(&mut buf).await?;
|
||||||
|
if n == 0 { return Ok(()); }
|
||||||
|
|
||||||
|
let request = String::from_utf8_lossy(&buf[0..n]);
|
||||||
|
let mut lines = request.lines();
|
||||||
|
let first_line = lines.next().ok_or_else(|| anyhow!("Empty HTTP request"))?;
|
||||||
|
|
||||||
|
let parts: Vec<&str> = first_line.split_whitespace().collect();
|
||||||
|
if parts.len() < 3 {
|
||||||
|
return Err(anyhow!("Invalid HTTP request line"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let method = parts[0];
|
||||||
|
let target = parts[1]; // host:port for CONNECT, http://host:port/... for GET
|
||||||
|
|
||||||
|
let (target_host, target_port) = if method == "CONNECT" {
|
||||||
|
let parts: Vec<&str> = target.split(':').collect();
|
||||||
|
let host = parts[0].to_string();
|
||||||
|
let port = parts.get(1).unwrap_or(&"443").parse::<u16>().unwrap_or(443);
|
||||||
|
(host, port)
|
||||||
|
} else {
|
||||||
|
// Rudimentary GET parsing, ideally use httparse
|
||||||
|
if target.starts_with("http://") {
|
||||||
|
let without_scheme = &target[7..];
|
||||||
|
let host_part = without_scheme.split('/').next().unwrap_or(without_scheme);
|
||||||
|
let parts: Vec<&str> = host_part.split(':').collect();
|
||||||
|
let host = parts[0].to_string();
|
||||||
|
let port = parts.get(1).unwrap_or(&"80").parse::<u16>().unwrap_or(80);
|
||||||
|
(host, port)
|
||||||
|
} else {
|
||||||
|
return Err(anyhow!("Unsupported HTTP method/target: {} {}", method, target));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let process_name = crate::tunnel::process_lookup::get_process_name_from_port(client_addr.port());
|
||||||
|
|
||||||
|
let session = Session {
|
||||||
|
protocol: "tcp".to_string(),
|
||||||
|
inbound_tag: inbound_tag.to_string(),
|
||||||
|
source_ip: Some(client_addr.ip()),
|
||||||
|
destination_ip: None, // Could parse if IP
|
||||||
|
destination_port: target_port,
|
||||||
|
sni: Some(target_host.clone()),
|
||||||
|
process_name,
|
||||||
|
};
|
||||||
|
|
||||||
|
let outbound_tag = router.route(&session);
|
||||||
|
tracing::info!("HTTP TCP {} -> {}:{} routed to {}", client_addr, target_host, target_port, outbound_tag);
|
||||||
|
|
||||||
|
match outbound_manager.dial_tcp(&outbound_tag, &target_host, target_port).await {
|
||||||
|
Ok(mut remote_stream) => {
|
||||||
|
if method == "CONNECT" {
|
||||||
|
stream.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await?;
|
||||||
|
} else {
|
||||||
|
remote_stream.write_all(&buf[0..n]).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
tokio::io::copy_bidirectional(stream, &mut remote_stream).await?;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("HTTP TCP dial failed to {}: {}", outbound_tag, e);
|
||||||
|
if method == "CONNECT" {
|
||||||
|
let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
pub mod tun;
|
||||||
|
pub mod local_proxy;
|
||||||
|
|
@ -0,0 +1,301 @@
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use crate::config::{ClientConfig, InboundConfig};
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
use crate::tunnel::router::{Router, Session};
|
||||||
|
use crate::tunnel::outbounds::OutboundManager;
|
||||||
|
use tokio::sync::watch;
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||||
|
pub async fn run_tun_inbound(
|
||||||
|
config: ClientConfig,
|
||||||
|
inbound_config: InboundConfig,
|
||||||
|
router: Arc<Router>,
|
||||||
|
outbound_manager: Arc<OutboundManager>,
|
||||||
|
mut shutdown: watch::Receiver<bool>,
|
||||||
|
) -> Result<()> {
|
||||||
|
|
||||||
|
use netstack_smoltcp::StackBuilder;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use futures::{StreamExt, SinkExt};
|
||||||
|
|
||||||
|
let InboundConfig::Tun { tag, auto_route, mtu, .. } = inbound_config else {
|
||||||
|
return Err(anyhow!("Invalid config for TUN inbound"));
|
||||||
|
};
|
||||||
|
|
||||||
|
tracing::info!("Starting TUN inbound (tag: {}, auto_route: {}, mtu: {})", tag, auto_route, mtu);
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
let _phys_if_for_bypass: Option<u32> = ostp_tun::windows::windows_route::sys::get_default_ipv4_route().map(|(_, idx)| idx);
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
let _phys_if_for_bypass: Option<u32> = None;
|
||||||
|
|
||||||
|
let mut bypass_ips: Vec<std::net::IpAddr> = Vec::new();
|
||||||
|
|
||||||
|
// Bypass all outbound server IPs
|
||||||
|
for outbound in &config.outbounds {
|
||||||
|
let server = match outbound {
|
||||||
|
crate::config::OutboundConfig::Ostp { server, .. } => Some(server),
|
||||||
|
crate::config::OutboundConfig::Socks { server, .. } => Some(server),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
if let Some(host) = server {
|
||||||
|
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
|
||||||
|
bypass_ips.push(ip);
|
||||||
|
} else {
|
||||||
|
if let Ok(addrs) = tokio::net::lookup_host((host.as_str(), 443)).await {
|
||||||
|
for addr in addrs {
|
||||||
|
bypass_ips.push(addr.ip());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build smoltcp network stack with proper buffer sizes for throughput
|
||||||
|
let (stack, tcp_runner, udp_socket, tcp_listener) = StackBuilder::default()
|
||||||
|
.stack_buffer_size(65536) // 64KB for packet accumulation
|
||||||
|
.tcp_buffer_size(131072) // 128KB for TCP streams
|
||||||
|
.udp_buffer_size(65536) // 64KB for UDP datagrams
|
||||||
|
.enable_tcp(true)
|
||||||
|
.enable_udp(true)
|
||||||
|
.mtu(mtu)
|
||||||
|
.build()?;
|
||||||
|
|
||||||
|
let mut runner_task = tokio::spawn(async move {
|
||||||
|
if let Some(runner) = tcp_runner {
|
||||||
|
let _ = runner.await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let (mut stack_sink, mut stack_stream) = stack.split();
|
||||||
|
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
let mut _route_guard = None;
|
||||||
|
|
||||||
|
let (tun_to_stack, stack_to_tun) = {
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
{
|
||||||
|
if let Some(fd) = fd {
|
||||||
|
use std::os::fd::{FromRawFd, AsRawFd};
|
||||||
|
use tokio::io::unix::AsyncFd;
|
||||||
|
use std::os::unix::io::OwnedFd;
|
||||||
|
|
||||||
|
let async_fd = AsyncFd::new(unsafe { OwnedFd::from_raw_fd(fd) })?;
|
||||||
|
let async_fd_shared = std::sync::Arc::new(async_fd);
|
||||||
|
|
||||||
|
let afd1 = async_fd_shared.clone();
|
||||||
|
let tun_to_stack = tokio::spawn(async move {
|
||||||
|
let mut frame = vec![0u8; 65535];
|
||||||
|
loop {
|
||||||
|
let mut guard = match afd1.readable().await {
|
||||||
|
Ok(g) => g,
|
||||||
|
Err(_) => break,
|
||||||
|
};
|
||||||
|
match guard.try_io(|inner| {
|
||||||
|
let res = unsafe { libc::read(inner.as_raw_fd(), frame.as_mut_ptr() as *mut libc::c_void, frame.len()) };
|
||||||
|
if res < 0 {
|
||||||
|
let err = std::io::Error::last_os_error();
|
||||||
|
if err.kind() == std::io::ErrorKind::WouldBlock { Err(err) } else { Ok(res as isize) }
|
||||||
|
} else { Ok(res as isize) }
|
||||||
|
}) {
|
||||||
|
Ok(Ok(n)) if n > 0 => {
|
||||||
|
if let Err(_) = stack_sink.send(frame[..n as usize].to_vec()).await { break; }
|
||||||
|
}
|
||||||
|
Ok(Ok(_)) => break,
|
||||||
|
Ok(Err(_)) => break,
|
||||||
|
Err(_) => continue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let afd2 = async_fd_shared.clone();
|
||||||
|
let stack_to_tun = tokio::spawn(async move {
|
||||||
|
while let Some(Ok(frame)) = stack_stream.next().await {
|
||||||
|
let mut written = 0;
|
||||||
|
while written < frame.len() {
|
||||||
|
let mut guard = match afd2.writable().await {
|
||||||
|
Ok(g) => g,
|
||||||
|
Err(_) => break,
|
||||||
|
};
|
||||||
|
match guard.try_io(|inner| {
|
||||||
|
let res = unsafe { libc::write(inner.as_raw_fd(), frame[written..].as_ptr() as *const libc::c_void, frame.len() - written) };
|
||||||
|
if res < 0 {
|
||||||
|
let err = std::io::Error::last_os_error();
|
||||||
|
if err.kind() == std::io::ErrorKind::WouldBlock { Err(err) } else { Ok(res as isize) }
|
||||||
|
} else { Ok(res as isize) }
|
||||||
|
}) {
|
||||||
|
Ok(Ok(n)) if n > 0 => written += n as usize,
|
||||||
|
Ok(Ok(_)) => break,
|
||||||
|
Ok(Err(_)) => break,
|
||||||
|
Err(_) => continue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
(tun_to_stack, stack_to_tun)
|
||||||
|
} else {
|
||||||
|
return Err(anyhow!("FD is required on Android but not provided"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "android"))]
|
||||||
|
{
|
||||||
|
let opts = ostp_tun::OstpTunOptions {
|
||||||
|
server_ip: bypass_ips.first().copied().unwrap_or_else(|| "127.0.0.1".parse().unwrap()),
|
||||||
|
bypass_ips: bypass_ips,
|
||||||
|
dns_server: None,
|
||||||
|
kill_switch: false,
|
||||||
|
mtu: mtu as u16,
|
||||||
|
wintun_path: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let tun_interface = ostp_tun::OstpTunInterface::create(opts)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow!("Failed to create OstpTunInterface: {}", e))?;
|
||||||
|
|
||||||
|
let dev = tun_interface.device;
|
||||||
|
_route_guard = Some(tun_interface.guard);
|
||||||
|
|
||||||
|
let (mut tun_read, mut tun_write) = tokio::io::split(dev);
|
||||||
|
let tun_to_stack = tokio::spawn(async move {
|
||||||
|
let mut buf = vec![0u8; 65536];
|
||||||
|
loop {
|
||||||
|
match tun_read.read(&mut buf).await {
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(n) => {
|
||||||
|
if let Err(_) = stack_sink.send(buf[..n].to_vec()).await { break; }
|
||||||
|
}
|
||||||
|
Err(e) => tracing::debug!("tun_read error: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let stack_to_tun = tokio::spawn(async move {
|
||||||
|
while let Some(Ok(frame)) = stack_stream.next().await {
|
||||||
|
if let Err(e) = tun_write.write(&frame).await { tracing::debug!("tun_write error: {e}"); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
(tun_to_stack, stack_to_tun)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── TCP Handler ──
|
||||||
|
let outbound_manager_tcp = outbound_manager.clone();
|
||||||
|
let router_tcp = router.clone();
|
||||||
|
let tag_tcp = tag.clone();
|
||||||
|
|
||||||
|
let tcp_accept_task = tokio::spawn(async move {
|
||||||
|
let Some(mut listener) = tcp_listener else { return; };
|
||||||
|
while let Some((mut stream, local, remote)) = listener.next().await {
|
||||||
|
let om = outbound_manager_tcp.clone();
|
||||||
|
let rt = router_tcp.clone();
|
||||||
|
let ib_tag = tag_tcp.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let process_name = crate::tunnel::process_lookup::get_process_name_from_port(local.port());
|
||||||
|
|
||||||
|
let mut sniff_buf = [0u8; 2048];
|
||||||
|
let sniff_len = match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_millis(100),
|
||||||
|
stream.read(&mut sniff_buf)
|
||||||
|
).await {
|
||||||
|
Ok(Ok(n)) => n,
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut domain_suffix = None;
|
||||||
|
if sniff_len > 0 {
|
||||||
|
domain_suffix = crate::tunnel::sni_sniff::extract_sni(&sniff_buf[..sniff_len]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let session = Session {
|
||||||
|
protocol: "tcp".to_string(),
|
||||||
|
inbound_tag: ib_tag.clone(),
|
||||||
|
source_ip: Some(local.ip()),
|
||||||
|
destination_ip: Some(remote.ip()),
|
||||||
|
destination_port: remote.port(),
|
||||||
|
sni: domain_suffix.map(|s| s.to_string()),
|
||||||
|
process_name,
|
||||||
|
};
|
||||||
|
|
||||||
|
let outbound_tag = rt.route(&session);
|
||||||
|
tracing::info!("TUN TCP {} -> {} routed to {}", local, remote, outbound_tag);
|
||||||
|
|
||||||
|
let target_host = if let Some(domain) = session.sni {
|
||||||
|
domain
|
||||||
|
} else {
|
||||||
|
remote.ip().to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
match om.dial_tcp(&outbound_tag, &target_host, session.destination_port).await {
|
||||||
|
Ok(mut remote_stream) => {
|
||||||
|
if sniff_len > 0 {
|
||||||
|
if let Err(e) = remote_stream.write_all(&sniff_buf[..sniff_len]).await {
|
||||||
|
tracing::warn!("Failed to forward sniffed bytes to {}: {}", outbound_tag, e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = tokio::io::copy_bidirectional(&mut stream, &mut remote_stream).await;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("TUN TCP dial failed to {}: {}", outbound_tag, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── UDP Handler ──
|
||||||
|
let outbound_manager_udp = outbound_manager.clone();
|
||||||
|
let router_udp = router.clone();
|
||||||
|
let tag_udp = tag.clone();
|
||||||
|
|
||||||
|
let udp_proxy_task = tokio::spawn(async move {
|
||||||
|
if let Some(udp_sock) = udp_socket {
|
||||||
|
let (mut udp_rx, _udp_tx) = udp_sock.split();
|
||||||
|
while let Some((payload, local, remote)) = udp_rx.next().await {
|
||||||
|
let process_name = crate::tunnel::process_lookup::get_process_name_from_port_udp(local.port());
|
||||||
|
let session = Session {
|
||||||
|
protocol: "udp".to_string(),
|
||||||
|
inbound_tag: tag_udp.clone(),
|
||||||
|
source_ip: Some(local.ip()),
|
||||||
|
destination_ip: Some(remote.ip()),
|
||||||
|
destination_port: remote.port(),
|
||||||
|
sni: None,
|
||||||
|
process_name,
|
||||||
|
};
|
||||||
|
let outbound_tag = router_udp.route(&session);
|
||||||
|
|
||||||
|
let payload_bytes = bytes::Bytes::copy_from_slice(&payload);
|
||||||
|
if let Err(e) = outbound_manager_udp.handle_udp(&outbound_tag, local, remote, payload_bytes).await {
|
||||||
|
tracing::debug!("TUN UDP drop to {}: {}", outbound_tag, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
tokio::select! {
|
||||||
|
_ = shutdown.changed() => {
|
||||||
|
tracing::info!("TUN inbound {} shutting down", tag);
|
||||||
|
}
|
||||||
|
_ = &mut runner_task => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
tun_to_stack.abort();
|
||||||
|
stack_to_tun.abort();
|
||||||
|
tcp_accept_task.abort();
|
||||||
|
udp_proxy_task.abort();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
|
||||||
|
pub async fn run_tun_inbound(
|
||||||
|
_config: ClientConfig,
|
||||||
|
_inbound_config: InboundConfig,
|
||||||
|
_router: Arc<Router>,
|
||||||
|
_outbound_manager: Arc<OutboundManager>,
|
||||||
|
_shutdown: watch::Receiver<bool>,
|
||||||
|
) -> Result<()> {
|
||||||
|
Err(anyhow!("TUN is only supported on Windows and Linux"))
|
||||||
|
}
|
||||||
|
|
@ -1,233 +0,0 @@
|
||||||
use anyhow::{anyhow, Result};
|
|
||||||
use tokio::sync::watch;
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
use std::net::ToSocketAddrs;
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
use std::process::{Command, Stdio, Child};
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
use std::io::{BufRead, BufReader};
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
struct LinuxRouteGuard {
|
|
||||||
server_ip_str: String,
|
|
||||||
default_gw: String,
|
|
||||||
default_if: String,
|
|
||||||
child: Option<Child>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
impl Drop for LinuxRouteGuard {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Some(mut child) = self.child.take() {
|
|
||||||
let _ = child.kill();
|
|
||||||
}
|
|
||||||
let cleanup_script = format!(
|
|
||||||
"ip route del 0.0.0.0/1 dev ostp_tun || true; \
|
|
||||||
ip route del 128.0.0.0/1 dev ostp_tun || true; \
|
|
||||||
ip route del {} via {} dev {} || true; \
|
|
||||||
ip route del 1.1.1.1 via {} dev {} || true; \
|
|
||||||
ip link set dev ostp_tun down || true; \
|
|
||||||
ip tuntap del name ostp_tun mode tun || true",
|
|
||||||
self.server_ip_str, self.default_gw, self.default_if,
|
|
||||||
self.default_gw, self.default_if
|
|
||||||
);
|
|
||||||
let _ = Command::new("sh").args(["-c", &cleanup_script]).output();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
pub async fn run_linux_tunnel(
|
|
||||||
config: crate::config::ClientConfig,
|
|
||||||
mut shutdown: watch::Receiver<bool>,
|
|
||||||
) -> Result<()> {
|
|
||||||
let debug = config.debug;
|
|
||||||
if debug {
|
|
||||||
println!("[ostp] Initializing TUN tunnel...");
|
|
||||||
}
|
|
||||||
|
|
||||||
let exe = std::env::current_exe()?;
|
|
||||||
let dir = exe.parent().ok_or_else(|| anyhow!("failed to get binary directory"))?;
|
|
||||||
|
|
||||||
let mut tun2socks_exe = dir.join("tun2socks");
|
|
||||||
if !tun2socks_exe.exists() {
|
|
||||||
// Try system PATH via standard command check
|
|
||||||
let in_path = Command::new("which")
|
|
||||||
.arg("tun2socks")
|
|
||||||
.output()
|
|
||||||
.map(|o| o.status.success())
|
|
||||||
.unwrap_or(false);
|
|
||||||
|
|
||||||
if in_path {
|
|
||||||
tun2socks_exe = std::path::PathBuf::from("tun2socks");
|
|
||||||
} else {
|
|
||||||
return Err(anyhow!(
|
|
||||||
"CRITICAL: 'tun2socks' binary is missing!\n\
|
|
||||||
OSTP requires tun2socks for TUN mode on Linux. Please download the appropriate binary for your architecture from: \n\
|
|
||||||
https://github.com/xjasonlyu/tun2socks/releases \n\
|
|
||||||
and place it in the same directory as the ostp executable ({}), or install it globally in your PATH.",
|
|
||||||
dir.display()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1.5. Pre-flight system checks
|
|
||||||
let is_root = Command::new("id")
|
|
||||||
.arg("-u")
|
|
||||||
.output()
|
|
||||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim() == "0")
|
|
||||||
.unwrap_or(false);
|
|
||||||
|
|
||||||
if !is_root {
|
|
||||||
return Err(anyhow!("FATAL: OSTP TUN mode requires root privileges on Linux. Please run via sudo."));
|
|
||||||
}
|
|
||||||
|
|
||||||
let has_ip_cmd = Command::new("which")
|
|
||||||
.arg("ip")
|
|
||||||
.output()
|
|
||||||
.map(|o| o.status.success())
|
|
||||||
.unwrap_or(false);
|
|
||||||
|
|
||||||
if !has_ip_cmd {
|
|
||||||
return Err(anyhow!("FATAL: 'ip' command not found. OSTP TUN mode requires 'iproute2' package to be installed."));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Resolve Server IP for routing table exclusion
|
|
||||||
let server_ip = config.ostp.server_addr.to_socket_addrs()
|
|
||||||
.map_err(|e| anyhow!("Failed to resolve remote server IP: {}", e))?
|
|
||||||
.next()
|
|
||||||
.map(|addr| addr.ip())
|
|
||||||
.ok_or_else(|| anyhow!("Could not resolve host IP for routing exclusion"))?;
|
|
||||||
|
|
||||||
let server_ip_str = server_ip.to_string();
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
println!("[ostp] Resolved server IP: {}", server_ip_str);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Detect current default gateway and interface
|
|
||||||
let route_output = Command::new("sh")
|
|
||||||
.arg("-c")
|
|
||||||
.arg("ip route show default | head -n1")
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
let route_str = String::from_utf8_lossy(&route_output.stdout);
|
|
||||||
let parts: Vec<&str> = route_str.split_whitespace().collect();
|
|
||||||
|
|
||||||
// Expected: "default via 192.168.1.1 dev eth0 ..."
|
|
||||||
let mut default_gw = String::new();
|
|
||||||
let mut default_if = String::new();
|
|
||||||
|
|
||||||
for i in 0..parts.len() {
|
|
||||||
if parts[i] == "via" && i + 1 < parts.len() {
|
|
||||||
default_gw = parts[i+1].to_string();
|
|
||||||
}
|
|
||||||
if parts[i] == "dev" && i + 1 < parts.len() {
|
|
||||||
default_if = parts[i+1].to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if default_gw.is_empty() || default_if.is_empty() {
|
|
||||||
return Err(anyhow!("Failed to discover active default gateway or network interface on Linux system."));
|
|
||||||
}
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
println!("[ostp] Default route: gateway={} interface={}", default_gw, default_if);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Setup commands (Using standard /1 routing trick for fail-proof overriding)
|
|
||||||
let setup_script = format!(
|
|
||||||
"ip tuntap add name ostp_tun mode tun || true; \
|
|
||||||
ip link set dev ostp_tun mtu {}; \
|
|
||||||
ip addr add 10.1.0.2/24 dev ostp_tun || true; \
|
|
||||||
ip link set dev ostp_tun up; \
|
|
||||||
ip route add {} via {} dev {}; \
|
|
||||||
ip route add 1.1.1.1 via {} dev {}; \
|
|
||||||
ip route add 0.0.0.0/1 dev ostp_tun; \
|
|
||||||
ip route add 128.0.0.0/1 dev ostp_tun",
|
|
||||||
config.ostp.mtu, server_ip_str, default_gw, default_if,
|
|
||||||
default_gw, default_if
|
|
||||||
);
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
println!("[ostp] Executing Linux network config: {}", setup_script);
|
|
||||||
}
|
|
||||||
|
|
||||||
let out = Command::new("sh")
|
|
||||||
.args(["-c", &setup_script])
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
if !out.status.success() && debug {
|
|
||||||
println!("[ostp] Warning: Setup routing returned: {}", String::from_utf8_lossy(&out.stderr));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. Prepare and launch tun2socks
|
|
||||||
// Using HTTP Proxy natively avoids any UDP Associate requests,
|
|
||||||
// providing clean TCP proxying with maximum reliability.
|
|
||||||
let proxy_url = format!("http://{}", config.local_proxy.bind_addr);
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
println!("[ostp] Spawning {} -device ostp_tun -proxy {}", tun2socks_exe.display(), proxy_url);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut child = Command::new(&tun2socks_exe)
|
|
||||||
.args([
|
|
||||||
"-device", "ostp_tun",
|
|
||||||
"-proxy", &proxy_url,
|
|
||||||
])
|
|
||||||
.stdout(if debug { Stdio::piped() } else { Stdio::null() })
|
|
||||||
.stderr(if debug { Stdio::piped() } else { Stdio::null() })
|
|
||||||
.spawn()
|
|
||||||
.map_err(|e| anyhow!("Failed to spawn tun2socks process: {}", e))?;
|
|
||||||
|
|
||||||
let mut _guard = LinuxRouteGuard {
|
|
||||||
server_ip_str: server_ip_str.clone(),
|
|
||||||
default_gw: default_gw.clone(),
|
|
||||||
default_if: default_if.clone(),
|
|
||||||
child: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("[ostp] TUN tunnel active. All traffic is routed through OSTP.");
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
let stdout = child.stdout.take().unwrap();
|
|
||||||
let stderr = child.stderr.take().unwrap();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let reader = BufReader::new(stdout);
|
|
||||||
for line in reader.lines().map_while(Result::ok) {
|
|
||||||
println!("[tun2socks] {}", line);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let reader = BufReader::new(stderr);
|
|
||||||
for line in reader.lines().map_while(Result::ok) {
|
|
||||||
tracing::warn!("tun2socks: {}", line);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
_guard.child = Some(child);
|
|
||||||
|
|
||||||
// 6. Wait for shutdown signal
|
|
||||||
let _ = shutdown.changed().await;
|
|
||||||
|
|
||||||
println!("[ostp] Deactivating TUN tunnel...");
|
|
||||||
|
|
||||||
// Drop guard runs cleanup automatically
|
|
||||||
drop(_guard);
|
|
||||||
|
|
||||||
println!("[ostp] TUN tunnel stopped.");
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "linux"))]
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub async fn run_linux_tunnel(
|
|
||||||
_config: crate::config::ClientConfig,
|
|
||||||
_shutdown: watch::Receiver<bool>,
|
|
||||||
) -> Result<()> {
|
|
||||||
Err(anyhow!("Linux tunnel driver executed on a non-Linux host!"))
|
|
||||||
}
|
|
||||||
|
|
@ -1,69 +1,7 @@
|
||||||
mod proxy;
|
pub mod router;
|
||||||
mod wintun_handler;
|
pub mod balancer;
|
||||||
mod linux_handler;
|
pub mod outbounds;
|
||||||
|
pub mod inbounds;
|
||||||
pub async fn run_tun_tunnel(
|
|
||||||
config: crate::config::ClientConfig,
|
|
||||||
shutdown: watch::Receiver<bool>,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
{
|
|
||||||
wintun_handler::run_wintun_tunnel(config, shutdown).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
{
|
|
||||||
linux_handler::run_linux_tunnel(config, shutdown).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
|
|
||||||
{
|
|
||||||
let _ = shutdown;
|
|
||||||
let _ = config;
|
|
||||||
anyhow::bail!("Operating system unsupported, text an issue at github.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
use tokio::sync::{mpsc, watch};
|
|
||||||
|
|
||||||
use crate::config::{ExclusionConfig, LocalProxyConfig, OstpConfig};
|
|
||||||
|
|
||||||
pub use proxy::run_local_socks5_proxy;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum ProxyEvent {
|
|
||||||
NewStream {
|
|
||||||
stream_id: u16,
|
|
||||||
target: String,
|
|
||||||
},
|
|
||||||
Data {
|
|
||||||
stream_id: u16,
|
|
||||||
payload: bytes::Bytes,
|
|
||||||
},
|
|
||||||
Close {
|
|
||||||
stream_id: u16,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum ProxyToClientMsg {
|
|
||||||
ConnectOk,
|
|
||||||
Data(bytes::Bytes),
|
|
||||||
Close,
|
|
||||||
Error(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
pub async fn run_local_proxy(
|
|
||||||
cfg: LocalProxyConfig,
|
|
||||||
ostp: OstpConfig,
|
|
||||||
exclusions: ExclusionConfig,
|
|
||||||
debug: bool,
|
|
||||||
shutdown: watch::Receiver<bool>,
|
|
||||||
proxy_events_tx: mpsc::Sender<ProxyEvent>,
|
|
||||||
client_msgs_rx: mpsc::UnboundedReceiver<(u16, ProxyToClientMsg)>,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
run_local_socks5_proxy(cfg, ostp, exclusions, debug, shutdown, proxy_events_tx, client_msgs_rx).await
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
pub mod process_lookup;
|
||||||
|
pub mod sni_sniff;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
|
||||||
|
pub async fn dial_tcp(_target_host: &str, _target_port: u16) -> Result<TcpStream> {
|
||||||
|
Err(anyhow!("Connection blocked by routing rule"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_udp(
|
||||||
|
_client_src: std::net::SocketAddr,
|
||||||
|
_target_dst: std::net::SocketAddr,
|
||||||
|
_payload: bytes::Bytes,
|
||||||
|
) -> Result<()> {
|
||||||
|
Err(anyhow!("Connection blocked by routing rule"))
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,99 @@
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn bind_socket_to_interface(socket: &tokio::net::TcpSocket, is_ipv6: bool, if_index: u32) -> std::io::Result<()> {
|
||||||
|
use std::os::windows::io::AsRawSocket;
|
||||||
|
use winapi::shared::ws2def::{IPPROTO_IP, IPPROTO_IPV6};
|
||||||
|
|
||||||
|
// These constants are defined as 31 in the Windows SDK.
|
||||||
|
const IP_UNICAST_IF: i32 = 31;
|
||||||
|
const IPV6_UNICAST_IF: i32 = 31;
|
||||||
|
|
||||||
|
let fd = socket.as_raw_socket() as usize;
|
||||||
|
let idx_net = if_index.to_be();
|
||||||
|
|
||||||
|
let (level, optname) = if is_ipv6 {
|
||||||
|
(IPPROTO_IPV6 as i32, IPV6_UNICAST_IF)
|
||||||
|
} else {
|
||||||
|
(IPPROTO_IP as i32, IP_UNICAST_IF)
|
||||||
|
};
|
||||||
|
|
||||||
|
let ret = unsafe {
|
||||||
|
winapi::um::winsock2::setsockopt(
|
||||||
|
fd,
|
||||||
|
level as i32,
|
||||||
|
optname as i32,
|
||||||
|
&idx_net as *const _ as *const i8,
|
||||||
|
std::mem::size_of_val(&idx_net) as i32,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
if ret != 0 {
|
||||||
|
return Err(std::io::Error::last_os_error());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
pub fn bind_socket_to_interface(socket: &tokio::net::TcpSocket, _is_ipv6: bool, if_name: &str) -> std::io::Result<()> {
|
||||||
|
use std::os::unix::io::AsRawFd;
|
||||||
|
let fd = socket.as_raw_fd();
|
||||||
|
let name_bytes = if_name.as_bytes();
|
||||||
|
let ret = unsafe {
|
||||||
|
libc::setsockopt(
|
||||||
|
fd,
|
||||||
|
libc::SOL_SOCKET,
|
||||||
|
libc::SO_BINDTODEVICE,
|
||||||
|
name_bytes.as_ptr() as *const libc::c_void,
|
||||||
|
name_bytes.len() as libc::socklen_t,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if ret != 0 {
|
||||||
|
return Err(std::io::Error::last_os_error());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
pub fn bind_socket_to_interface(socket: &tokio::net::TcpSocket, _is_ipv6: bool, if_index: u32) -> std::io::Result<()> {
|
||||||
|
// macOS uses IP_BOUND_IF for IPv4 and IPV6_BOUND_IF for IPv6, similar to Windows
|
||||||
|
use std::os::unix::io::AsRawFd;
|
||||||
|
let fd = socket.as_raw_fd();
|
||||||
|
|
||||||
|
// We can implement this later, for now just a stub so compilation works
|
||||||
|
tracing::debug!("macOS socket binding not yet fully implemented for interface {}", if_index);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn dial_tcp(target_host: &str, target_port: u16, _phys_if_idx: Option<u32>) -> Result<TcpStream> {
|
||||||
|
let addrs = tokio::net::lookup_host((target_host, target_port)).await?.collect::<Vec<_>>();
|
||||||
|
if addrs.is_empty() {
|
||||||
|
return Err(anyhow!("Could not resolve target host: {}", target_host));
|
||||||
|
}
|
||||||
|
|
||||||
|
let target_addr = addrs[0];
|
||||||
|
let socket = match target_addr {
|
||||||
|
std::net::SocketAddr::V4(_) => tokio::net::TcpSocket::new_v4()?,
|
||||||
|
std::net::SocketAddr::V6(_) => tokio::net::TcpSocket::new_v6()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
if let Some(idx) = _phys_if_idx {
|
||||||
|
if let Err(e) = bind_socket_to_interface(&socket, target_addr.is_ipv6(), idx) {
|
||||||
|
tracing::warn!("DIRECT: Failed to bind to physical interface {}: {}", idx, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let stream = tokio::time::timeout(std::time::Duration::from_secs(10), socket.connect(target_addr)).await??;
|
||||||
|
Ok(stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_udp(
|
||||||
|
_client_src: std::net::SocketAddr,
|
||||||
|
_target_dst: std::net::SocketAddr,
|
||||||
|
_payload: bytes::Bytes,
|
||||||
|
_phys_if_idx: Option<u32>,
|
||||||
|
) -> Result<()> {
|
||||||
|
Err(anyhow!("Direct UDP is not yet fully implemented"))
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,77 @@
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use crate::tunnel::balancer::Balancer;
|
||||||
|
use crate::config::OutboundConfig;
|
||||||
|
|
||||||
|
pub mod direct;
|
||||||
|
pub mod block;
|
||||||
|
pub mod ostp;
|
||||||
|
pub mod socks;
|
||||||
|
|
||||||
|
pub struct OutboundManager {
|
||||||
|
balancer: Arc<Balancer>,
|
||||||
|
phys_if_index: Option<u32>,
|
||||||
|
_phys_if_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OutboundManager {
|
||||||
|
pub fn new(
|
||||||
|
balancer: Arc<Balancer>,
|
||||||
|
phys_if_index: Option<u32>,
|
||||||
|
phys_if_name: Option<String>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
balancer,
|
||||||
|
phys_if_index,
|
||||||
|
_phys_if_name: phys_if_name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn dial_tcp(&self, tag: &str, target_host: &str, target_port: u16) -> Result<tokio::net::TcpStream> {
|
||||||
|
let concrete_config = self.balancer.get_concrete_outbound(tag)
|
||||||
|
.ok_or_else(|| anyhow!("Outbound tag '{}' not found or resolved to invalid node", tag))?;
|
||||||
|
|
||||||
|
match concrete_config {
|
||||||
|
OutboundConfig::Direct { .. } => {
|
||||||
|
direct::dial_tcp(target_host, target_port, self.phys_if_index).await
|
||||||
|
}
|
||||||
|
OutboundConfig::Block { .. } => {
|
||||||
|
block::dial_tcp(target_host, target_port).await
|
||||||
|
}
|
||||||
|
OutboundConfig::Ostp { server, port, access_key, transport, multiplex, .. } => {
|
||||||
|
ostp::dial_tcp(target_host, target_port, server, *port, access_key, transport, multiplex).await
|
||||||
|
}
|
||||||
|
OutboundConfig::Socks { server, port, .. } => {
|
||||||
|
socks::dial_tcp(target_host, target_port, server, *port).await
|
||||||
|
}
|
||||||
|
_ => Err(anyhow!("Invalid concrete outbound type for {}", tag)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_udp(
|
||||||
|
&self,
|
||||||
|
tag: &str,
|
||||||
|
client_src: std::net::SocketAddr,
|
||||||
|
target_dst: std::net::SocketAddr,
|
||||||
|
payload: bytes::Bytes,
|
||||||
|
) -> Result<()> {
|
||||||
|
let concrete_config = self.balancer.get_concrete_outbound(tag)
|
||||||
|
.ok_or_else(|| anyhow!("Outbound tag '{}' not found or resolved to invalid node", tag))?;
|
||||||
|
|
||||||
|
match concrete_config {
|
||||||
|
OutboundConfig::Direct { .. } => {
|
||||||
|
direct::handle_udp(client_src, target_dst, payload, self.phys_if_index).await
|
||||||
|
}
|
||||||
|
OutboundConfig::Block { .. } => {
|
||||||
|
block::handle_udp(client_src, target_dst, payload).await
|
||||||
|
}
|
||||||
|
OutboundConfig::Ostp { server, port, access_key, transport, multiplex, .. } => {
|
||||||
|
ostp::handle_udp(client_src, target_dst, payload, server, *port, access_key, transport, multiplex).await
|
||||||
|
}
|
||||||
|
OutboundConfig::Socks { server, port, .. } => {
|
||||||
|
socks::handle_udp(client_src, target_dst, payload, server, *port).await
|
||||||
|
}
|
||||||
|
_ => Err(anyhow!("Invalid concrete outbound type for {}", tag)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,391 @@
|
||||||
|
use anyhow::Result;
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
use crate::config::{TransportConfig, MultiplexConfig};
|
||||||
|
|
||||||
|
use ostp_core::{OstpEvent, ProtocolAction, ProtocolConfig, ProtocolMachine};
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
|
/// Build the handshake payload the server expects:
|
||||||
|
/// [timestamp_u64_be (8 bytes)] [session_id_u32_be (4 bytes)] [access_key bytes]
|
||||||
|
fn build_handshake_payload(session_id: u32, access_key: &str) -> Vec<u8> {
|
||||||
|
let ts = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_secs();
|
||||||
|
let mut payload = Vec::with_capacity(12 + access_key.len());
|
||||||
|
payload.extend_from_slice(&ts.to_be_bytes());
|
||||||
|
payload.extend_from_slice(&session_id.to_be_bytes());
|
||||||
|
payload.extend_from_slice(access_key.as_bytes());
|
||||||
|
payload
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a correctly configured ProtocolConfig for an outgoing OSTP connection.
|
||||||
|
fn make_initiator_config(
|
||||||
|
session_id: u32,
|
||||||
|
access_key: &str,
|
||||||
|
transport_cfg: &TransportConfig,
|
||||||
|
) -> ProtocolConfig {
|
||||||
|
let secrets = ostp_core::crypto::derive_all_secrets(access_key.as_bytes());
|
||||||
|
let payload = build_handshake_payload(session_id, access_key);
|
||||||
|
|
||||||
|
let mtu = match transport_cfg.r#type.as_str() {
|
||||||
|
"dns" => 1100,
|
||||||
|
_ => 1350,
|
||||||
|
};
|
||||||
|
|
||||||
|
ProtocolConfig {
|
||||||
|
role: ostp_core::NoiseRole::Initiator,
|
||||||
|
psk: secrets.psk,
|
||||||
|
session_id,
|
||||||
|
handshake_payload: payload,
|
||||||
|
max_padding: 256,
|
||||||
|
padding_strategy: ostp_core::framing::PaddingStrategy::Adaptive,
|
||||||
|
obfuscation_key: secrets.obfuscation_key,
|
||||||
|
max_reorder: 16384,
|
||||||
|
max_reorder_buffer: 8192,
|
||||||
|
ack_delay_ms: 5,
|
||||||
|
rto_ms: 100,
|
||||||
|
max_retries: 8,
|
||||||
|
max_sent_history: 32768,
|
||||||
|
handshake_pad_min: secrets.handshake_pad_min,
|
||||||
|
handshake_pad_max: secrets.handshake_pad_max,
|
||||||
|
mtu,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn random_session_id() -> u32 {
|
||||||
|
use std::collections::hash_map::DefaultHasher;
|
||||||
|
use std::hash::{Hash, Hasher};
|
||||||
|
let mut h = DefaultHasher::new();
|
||||||
|
std::time::Instant::now().hash(&mut h);
|
||||||
|
std::thread::current().id().hash(&mut h);
|
||||||
|
h.finish() as u32
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn dial_tcp(
|
||||||
|
target_host: &str,
|
||||||
|
target_port: u16,
|
||||||
|
server: &str,
|
||||||
|
port: u16,
|
||||||
|
access_key: &str,
|
||||||
|
transport_cfg: &TransportConfig,
|
||||||
|
_multiplex: &MultiplexConfig,
|
||||||
|
) -> Result<TcpStream> {
|
||||||
|
tracing::info!("Dialing OSTP server {}:{} for target {}:{}", server, port, target_host, target_port);
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||||
|
let local_addr = listener.local_addr()?;
|
||||||
|
let client_stream = tokio::net::TcpStream::connect(local_addr).await?;
|
||||||
|
let (mut server_stream, _) = listener.accept().await?;
|
||||||
|
|
||||||
|
let transport = make_transport(transport_cfg, server, port).await?;
|
||||||
|
|
||||||
|
let session_id = random_session_id();
|
||||||
|
let config = make_initiator_config(session_id, access_key, transport_cfg);
|
||||||
|
let mut machine = ProtocolMachine::new(config).unwrap();
|
||||||
|
|
||||||
|
let target_host_str = target_host.to_string();
|
||||||
|
|
||||||
|
let server_str = server.to_string();
|
||||||
|
|
||||||
|
// Spawn bridge task
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// Send initial handshake
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Start) {
|
||||||
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for handshake response (server sends HandshakePayload back)
|
||||||
|
let mut buf = [0u8; 8192];
|
||||||
|
let mut handshake_success = false;
|
||||||
|
match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_millis(15000),
|
||||||
|
transport.recv(&mut buf),
|
||||||
|
).await {
|
||||||
|
Ok(Ok(n)) => {
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n]))) {
|
||||||
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
|
handshake_success = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
tracing::warn!("OSTP handshake timeout for {}:{}", server_str, port);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !handshake_success {
|
||||||
|
tracing::warn!("TCP handshake failed or protocol machine error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send connection request
|
||||||
|
let connect_msg = ostp_core::relay::RelayMessage::Connect(format!("{}:{}", target_host_str, target_port));
|
||||||
|
let connect_encoded = connect_msg.encode();
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(connect_encoded))) {
|
||||||
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Wait for ConnectOk before forwarding any data ─────────────────
|
||||||
|
// This is critical: if we enter the data loop immediately, the TLS
|
||||||
|
// ClientHello arrives at the server before it has established the
|
||||||
|
// outbound TCP connection, causing it to drop the packet as
|
||||||
|
// "Relay DATA for unknown stream".
|
||||||
|
// The kernel will buffer incoming data from server_stream while we wait.
|
||||||
|
let mut connect_ok = false;
|
||||||
|
match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(30),
|
||||||
|
async {
|
||||||
|
let mut wait_buf = [0u8; 8192];
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
Ok(n) = transport.recv(&mut wait_buf) => {
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Inbound(
|
||||||
|
bytes::Bytes::copy_from_slice(&wait_buf[..n]),
|
||||||
|
)) {
|
||||||
|
// Check for ConnectOk or Error before dispatching
|
||||||
|
let result = check_connect_result(&action);
|
||||||
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
|
match result {
|
||||||
|
Some(true) => return true,
|
||||||
|
Some(false) => return false,
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = tokio::time::sleep(std::time::Duration::from_millis(10)) => {
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Tick) {
|
||||||
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(true) => {
|
||||||
|
tracing::debug!("ConnectOk received for {}:{}, starting data forwarding", target_host_str, target_port);
|
||||||
|
connect_ok = true;
|
||||||
|
}
|
||||||
|
Ok(false) => {
|
||||||
|
tracing::warn!("Server refused connection to {}:{}", target_host_str, target_port);
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
tracing::warn!("ConnectOk timeout for {}:{}", target_host_str, target_port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !connect_ok {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Main bidirectional data forwarding loop ───────────────────────
|
||||||
|
let mut buf = [0u8; 65535];
|
||||||
|
let mut udp_buf = [0u8; 65535];
|
||||||
|
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
Ok(n) = server_stream.read(&mut buf) => {
|
||||||
|
if n == 0 { break; }
|
||||||
|
let data_msg = ostp_core::relay::RelayMessage::Data(buf[..n].to_vec());
|
||||||
|
let encoded = data_msg.encode();
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
|
||||||
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(n) = transport.recv(&mut udp_buf) => {
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&udp_buf[..n]))) {
|
||||||
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = tokio::time::sleep(std::time::Duration::from_millis(10)) => {
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Tick) {
|
||||||
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
Ok(client_stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_udp(
|
||||||
|
client_src: std::net::SocketAddr,
|
||||||
|
target_dst: std::net::SocketAddr,
|
||||||
|
payload: bytes::Bytes,
|
||||||
|
server: &str,
|
||||||
|
port: u16,
|
||||||
|
access_key: &str,
|
||||||
|
transport_cfg: &TransportConfig,
|
||||||
|
_multiplex: &MultiplexConfig,
|
||||||
|
) -> Result<()> {
|
||||||
|
let transport = make_transport(transport_cfg, server, port).await?;
|
||||||
|
|
||||||
|
// Derive session_id from client source addr for stable per-flow sessions
|
||||||
|
let ip_bytes = match client_src.ip() {
|
||||||
|
std::net::IpAddr::V4(v4) => {
|
||||||
|
let o = v4.octets();
|
||||||
|
u32::from_be_bytes(o)
|
||||||
|
}
|
||||||
|
std::net::IpAddr::V6(v6) => {
|
||||||
|
let o = v6.octets();
|
||||||
|
u32::from_be_bytes([o[12], o[13], o[14], o[15]])
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let session_id = ip_bytes ^ (client_src.port() as u32);
|
||||||
|
|
||||||
|
let config = make_initiator_config(session_id, access_key, transport_cfg);
|
||||||
|
let mut machine = ProtocolMachine::new(config)?;
|
||||||
|
|
||||||
|
// Send handshake first
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Start) {
|
||||||
|
handle_udp_action(action, &transport).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for handshake response (server sends HandshakePayload back)
|
||||||
|
let mut buf = [0u8; 8192];
|
||||||
|
match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_millis(15000),
|
||||||
|
transport.recv(&mut buf),
|
||||||
|
).await {
|
||||||
|
Ok(Ok(n)) => {
|
||||||
|
let _ = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n])));
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
tracing::warn!("OSTP handshake timeout for {}:{}", server, port);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send relay UdpAssociate + data
|
||||||
|
let assoc_msg = ostp_core::relay::RelayMessage::UdpAssociate;
|
||||||
|
let encoded = assoc_msg.encode();
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
|
||||||
|
handle_udp_action(action, &transport).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let data_msg = ostp_core::relay::RelayMessage::UdpData(
|
||||||
|
format!("{}:{}", target_dst.ip(), target_dst.port()),
|
||||||
|
payload.to_vec()
|
||||||
|
);
|
||||||
|
let encoded = data_msg.encode();
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
|
||||||
|
handle_udp_action(action, &transport).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep-alive for a short time to receive response
|
||||||
|
for _ in 0..5 {
|
||||||
|
match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_millis(100),
|
||||||
|
transport.recv(&mut buf),
|
||||||
|
).await {
|
||||||
|
Ok(Ok(n)) => {
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n]))) {
|
||||||
|
// Just process incoming UDP response internally
|
||||||
|
let _ = action;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn make_transport(
|
||||||
|
transport_cfg: &TransportConfig,
|
||||||
|
server: &str,
|
||||||
|
port: u16,
|
||||||
|
) -> Result<crate::transport::Transport> {
|
||||||
|
match transport_cfg.r#type.as_str() {
|
||||||
|
"dns" => {
|
||||||
|
let domain = transport_cfg.domain.clone()
|
||||||
|
.unwrap_or_else(|| "tunnel.example.com".to_string());
|
||||||
|
let resolver = transport_cfg.resolver.clone()
|
||||||
|
.unwrap_or_else(|| server.to_string());
|
||||||
|
let transport = crate::transport::dns::start_dns_transport(domain, resolver, transport_cfg.pubkey.clone()).await
|
||||||
|
.map_err(|e| anyhow::anyhow!(e))?;
|
||||||
|
Ok(transport)
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let udp = tokio::net::UdpSocket::bind("0.0.0.0:0").await?;
|
||||||
|
udp.connect((server, port)).await?;
|
||||||
|
Ok(crate::transport::Transport::Udp(std::sync::Arc::new(udp)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_udp_action(action: ProtocolAction, transport: &crate::transport::Transport) {
|
||||||
|
match action {
|
||||||
|
ProtocolAction::SendDatagram(data) => {
|
||||||
|
let _ = transport.send(&data).await;
|
||||||
|
}
|
||||||
|
ProtocolAction::Multiple(actions) => {
|
||||||
|
for a in actions {
|
||||||
|
if let ProtocolAction::SendDatagram(data) = a {
|
||||||
|
let _ = transport.send(&data).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_action(action: ProtocolAction, transport: &crate::transport::Transport, server_stream: &mut tokio::net::TcpStream) {
|
||||||
|
match action {
|
||||||
|
ProtocolAction::SendDatagram(data) => {
|
||||||
|
let _ = transport.send(&data).await;
|
||||||
|
}
|
||||||
|
ProtocolAction::DeliverApp(_stream_id, payload) => {
|
||||||
|
if let Ok(msg) = ostp_core::relay::RelayMessage::decode(&payload) {
|
||||||
|
match msg {
|
||||||
|
ostp_core::relay::RelayMessage::Data(data) => {
|
||||||
|
let _ = server_stream.write_all(&data).await;
|
||||||
|
}
|
||||||
|
ostp_core::relay::RelayMessage::ConnectOk => {
|
||||||
|
tracing::debug!("TCP Connection established successfully");
|
||||||
|
}
|
||||||
|
ostp_core::relay::RelayMessage::Error(err) => {
|
||||||
|
tracing::warn!("Server returned TCP connection error: {}", err);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ProtocolAction::Multiple(actions) => {
|
||||||
|
for a in actions {
|
||||||
|
Box::pin(handle_action(a, transport, server_stream)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inspect a ProtocolAction for ConnectOk / Error relay messages.
|
||||||
|
/// Returns Some(true) on ConnectOk, Some(false) on Error, None if neither.
|
||||||
|
/// Works recursively through Multiple actions.
|
||||||
|
fn check_connect_result(action: &ProtocolAction) -> Option<bool> {
|
||||||
|
match action {
|
||||||
|
ProtocolAction::DeliverApp(_stream_id, payload) => {
|
||||||
|
if let Ok(msg) = ostp_core::relay::RelayMessage::decode(payload) {
|
||||||
|
match msg {
|
||||||
|
ostp_core::relay::RelayMessage::ConnectOk => return Some(true),
|
||||||
|
ostp_core::relay::RelayMessage::Error(_) => return Some(false),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
ProtocolAction::Multiple(actions) => {
|
||||||
|
for a in actions {
|
||||||
|
if let Some(result) = check_connect_result(a) {
|
||||||
|
return Some(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
|
||||||
|
pub async fn dial_tcp(_target_host: &str, _target_port: u16, _server: &str, _port: u16) -> Result<TcpStream> {
|
||||||
|
// SOCKS5 dialer implementation stub
|
||||||
|
Err(anyhow!("SOCKS outbound TCP dialer not yet implemented"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_udp(
|
||||||
|
_client_src: std::net::SocketAddr,
|
||||||
|
_target_dst: std::net::SocketAddr,
|
||||||
|
_payload: bytes::Bytes,
|
||||||
|
_server: &str,
|
||||||
|
_port: u16,
|
||||||
|
) -> Result<()> {
|
||||||
|
Err(anyhow!("SOCKS outbound UDP handler not yet implemented"))
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,193 @@
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn get_process_name_from_port(port: u16) -> Option<String> {
|
||||||
|
use winapi::shared::minwindef::ULONG;
|
||||||
|
use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER;
|
||||||
|
use winapi::um::iphlpapi::GetExtendedTcpTable;
|
||||||
|
use winapi::shared::tcpmib::{MIB_TCPTABLE_OWNER_PID, MIB_TCPROW_OWNER_PID};
|
||||||
|
|
||||||
|
let mut size: ULONG = 0;
|
||||||
|
let table_class = 5; // TCP_TABLE_OWNER_PID_ALL
|
||||||
|
let mut table = vec![0u8; 1024];
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let mut ret = GetExtendedTcpTable(
|
||||||
|
table.as_mut_ptr() as *mut _,
|
||||||
|
&mut size,
|
||||||
|
0,
|
||||||
|
2, // AF_INET
|
||||||
|
table_class,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if ret == ERROR_INSUFFICIENT_BUFFER {
|
||||||
|
table.resize(size as usize, 0);
|
||||||
|
ret = GetExtendedTcpTable(
|
||||||
|
table.as_mut_ptr() as *mut _,
|
||||||
|
&mut size,
|
||||||
|
0,
|
||||||
|
2, // AF_INET
|
||||||
|
table_class,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ret == 0 {
|
||||||
|
let tcp_table = &*(table.as_ptr() as *const MIB_TCPTABLE_OWNER_PID);
|
||||||
|
let row_ptr = &tcp_table.table[0] as *const MIB_TCPROW_OWNER_PID;
|
||||||
|
for i in 0..tcp_table.dwNumEntries {
|
||||||
|
let row = &*row_ptr.add(i as usize);
|
||||||
|
// Local port is in network byte order
|
||||||
|
let local_port = u16::from_be(row.dwLocalPort as u16);
|
||||||
|
if local_port == port {
|
||||||
|
return get_process_name_from_pid(row.dwOwningPid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn get_process_name_from_port_udp(port: u16) -> Option<String> {
|
||||||
|
use winapi::shared::minwindef::ULONG;
|
||||||
|
use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER;
|
||||||
|
use winapi::um::iphlpapi::GetExtendedUdpTable;
|
||||||
|
use winapi::shared::udpmib::{MIB_UDPTABLE_OWNER_PID, MIB_UDPROW_OWNER_PID};
|
||||||
|
|
||||||
|
let mut size: ULONG = 0;
|
||||||
|
let table_class = 1; // UDP_TABLE_OWNER_PID
|
||||||
|
let mut table = vec![0u8; 1024];
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let mut ret = GetExtendedUdpTable(
|
||||||
|
table.as_mut_ptr() as *mut _,
|
||||||
|
&mut size,
|
||||||
|
0,
|
||||||
|
2, // AF_INET
|
||||||
|
table_class,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if ret == ERROR_INSUFFICIENT_BUFFER {
|
||||||
|
table.resize(size as usize, 0);
|
||||||
|
ret = GetExtendedUdpTable(
|
||||||
|
table.as_mut_ptr() as *mut _,
|
||||||
|
&mut size,
|
||||||
|
0,
|
||||||
|
2, // AF_INET
|
||||||
|
table_class,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ret == 0 {
|
||||||
|
let udp_table = &*(table.as_ptr() as *const MIB_UDPTABLE_OWNER_PID);
|
||||||
|
let row_ptr = &udp_table.table[0] as *const MIB_UDPROW_OWNER_PID;
|
||||||
|
for i in 0..udp_table.dwNumEntries {
|
||||||
|
let row = &*row_ptr.add(i as usize);
|
||||||
|
let local_port = u16::from_be(row.dwLocalPort as u16);
|
||||||
|
if local_port == port {
|
||||||
|
return get_process_name_from_pid(row.dwOwningPid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
fn get_process_name_from_pid(pid: u32) -> Option<String> {
|
||||||
|
use winapi::um::processthreadsapi::OpenProcess;
|
||||||
|
use winapi::um::psapi::GetModuleBaseNameW;
|
||||||
|
use winapi::um::winnt::{PROCESS_QUERY_INFORMATION, PROCESS_VM_READ};
|
||||||
|
use winapi::um::handleapi::CloseHandle;
|
||||||
|
use std::os::windows::ffi::OsStringExt;
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid);
|
||||||
|
if handle.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut buffer = [0u16; 1024];
|
||||||
|
let len = GetModuleBaseNameW(handle, std::ptr::null_mut(), buffer.as_mut_ptr(), buffer.len() as u32);
|
||||||
|
CloseHandle(handle);
|
||||||
|
|
||||||
|
if len > 0 {
|
||||||
|
let name = std::ffi::OsString::from_wide(&buffer[..len as usize]);
|
||||||
|
return Some(name.to_string_lossy().into_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
pub fn get_process_name_from_port(port: u16) -> Option<String> {
|
||||||
|
use std::fs;
|
||||||
|
use std::io::{BufRead, BufReader};
|
||||||
|
|
||||||
|
let hex_port = format!("{:04X}", port);
|
||||||
|
|
||||||
|
let check_net_file = |path: &str| -> Option<u64> {
|
||||||
|
let file = fs::File::open(path).ok()?;
|
||||||
|
let reader = BufReader::new(file);
|
||||||
|
for line in reader.lines().skip(1).filter_map(Result::ok) {
|
||||||
|
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||||
|
if parts.len() >= 10 {
|
||||||
|
let local_addr = parts[1];
|
||||||
|
if local_addr.ends_with(&format!(":{}", hex_port)) {
|
||||||
|
if let Ok(inode) = parts[9].parse::<u64>() {
|
||||||
|
return Some(inode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let target_inode = check_net_file("/proc/net/tcp")
|
||||||
|
.or_else(|| check_net_file("/proc/net/tcp6"))
|
||||||
|
.or_else(|| check_net_file("/proc/net/udp"))
|
||||||
|
.or_else(|| check_net_file("/proc/net/udp6"))?;
|
||||||
|
|
||||||
|
let socket_str = format!("socket:[{}]", target_inode);
|
||||||
|
|
||||||
|
for entry in fs::read_dir("/proc").ok()?.filter_map(Result::ok) {
|
||||||
|
let file_name = entry.file_name();
|
||||||
|
let pid_str = file_name.to_string_lossy();
|
||||||
|
if !pid_str.chars().all(char::is_numeric) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let fd_dir = entry.path().join("fd");
|
||||||
|
if let Ok(fd_entries) = fs::read_dir(fd_dir) {
|
||||||
|
for fd_entry in fd_entries.filter_map(Result::ok) {
|
||||||
|
if let Ok(target) = fs::read_link(fd_entry.path()) {
|
||||||
|
if target.to_string_lossy() == socket_str {
|
||||||
|
let exe_path = entry.path().join("exe");
|
||||||
|
if let Ok(exe_link) = fs::read_link(exe_path) {
|
||||||
|
if let Some(name) = exe_link.file_name() {
|
||||||
|
return Some(name.to_string_lossy().into_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(comm) = fs::read_to_string(entry.path().join("comm")) {
|
||||||
|
return Some(comm.trim().to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
|
||||||
|
pub fn get_process_name_from_port(_port: u16) -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
pub fn get_process_name_from_port_udp(port: u16) -> Option<String> {
|
||||||
|
get_process_name_from_port(port)
|
||||||
|
}
|
||||||
|
|
@ -1,566 +0,0 @@
|
||||||
use std::collections::HashMap;
|
|
||||||
use anyhow::{anyhow, Context, Result};
|
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
||||||
use tokio::net::{TcpListener, TcpStream};
|
|
||||||
use tokio::sync::{mpsc, watch};
|
|
||||||
use tokio::time::{timeout, Duration};
|
|
||||||
|
|
||||||
use crate::config::{ExclusionConfig, LocalProxyConfig, OstpConfig};
|
|
||||||
use crate::tunnel::{ProxyEvent, ProxyToClientMsg};
|
|
||||||
|
|
||||||
pub async fn run_local_socks5_proxy(
|
|
||||||
cfg: LocalProxyConfig,
|
|
||||||
_ostp: OstpConfig,
|
|
||||||
exclusions: ExclusionConfig,
|
|
||||||
debug: bool,
|
|
||||||
mut shutdown: watch::Receiver<bool>,
|
|
||||||
proxy_events_tx: mpsc::Sender<ProxyEvent>,
|
|
||||||
mut client_msgs_rx: mpsc::UnboundedReceiver<(u16, ProxyToClientMsg)>,
|
|
||||||
) -> Result<()> {
|
|
||||||
let connect_timeout = Duration::from_millis(cfg.connect_timeout_ms.max(1));
|
|
||||||
let listener = TcpListener::bind(&cfg.bind_addr)
|
|
||||||
.await
|
|
||||||
.with_context(|| format!("failed to bind local HTTP/SOCKS5 proxy at {}", cfg.bind_addr))?;
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
tracing::info!("local HTTP/SOCKS5 proxy listening at {}", cfg.bind_addr);
|
|
||||||
tracing::info!("Windows system proxy: set HTTP proxy to {}. tun2socks: SOCKS5 on same address.", cfg.bind_addr);
|
|
||||||
}
|
|
||||||
|
|
||||||
let matcher = ExclusionMatcher::new(&exclusions);
|
|
||||||
let (connect_tx, mut connect_rx) = mpsc::channel(128);
|
|
||||||
|
|
||||||
let mut next_stream_id: u16 = 1;
|
|
||||||
let mut active_streams: HashMap<u16, mpsc::UnboundedSender<ProxyToClientMsg>> = HashMap::new();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
_ = shutdown.changed() => {
|
|
||||||
if *shutdown.borrow() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
accepted = listener.accept() => {
|
|
||||||
let (socket, _) = accepted?;
|
|
||||||
let stream_id = next_stream_id;
|
|
||||||
// Advance, skipping zero and any stream_id still in active_streams
|
|
||||||
loop {
|
|
||||||
next_stream_id = next_stream_id.wrapping_add(1);
|
|
||||||
if next_stream_id == 0 { next_stream_id = 1; }
|
|
||||||
if !active_streams.contains_key(&next_stream_id) { break; }
|
|
||||||
}
|
|
||||||
|
|
||||||
let (tx, rx) = mpsc::unbounded_channel();
|
|
||||||
active_streams.insert(stream_id, tx);
|
|
||||||
|
|
||||||
let event_tx = proxy_events_tx.clone();
|
|
||||||
let c_tx = connect_tx.clone();
|
|
||||||
let matcher_clone = matcher.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if let Err(err) = handle_proxy_client(
|
|
||||||
socket,
|
|
||||||
stream_id,
|
|
||||||
event_tx,
|
|
||||||
rx,
|
|
||||||
c_tx,
|
|
||||||
connect_timeout,
|
|
||||||
debug,
|
|
||||||
matcher_clone,
|
|
||||||
).await {
|
|
||||||
let msg = err.to_string();
|
|
||||||
// Suppress routine disconnects and unsupported SOCKS5 command attempts (like UDP) from spam logs
|
|
||||||
if !msg.contains("UnexpectedEof")
|
|
||||||
&& !msg.contains("Connection reset")
|
|
||||||
&& !msg.contains("Broken pipe")
|
|
||||||
&& !msg.contains("unsupported SOCKS5 command")
|
|
||||||
&& debug {
|
|
||||||
tracing::warn!("proxy client error: {err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Some((stream_id, msg)) = client_msgs_rx.recv() => {
|
|
||||||
if stream_id == 0 {
|
|
||||||
if let ProxyToClientMsg::Close = msg {
|
|
||||||
if debug {
|
|
||||||
tracing::info!("Resetting all active proxy streams on reconnect");
|
|
||||||
}
|
|
||||||
for (_, tx) in active_streams.drain() {
|
|
||||||
let _ = tx.send(ProxyToClientMsg::Close);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if let Some(tx) = active_streams.get(&stream_id) {
|
|
||||||
if tx.send(msg).is_err() {
|
|
||||||
active_streams.remove(&stream_id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(stream_id) = connect_rx.recv() => {
|
|
||||||
active_streams.remove(&stream_id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extracts `host:port` from an HTTP absolute-URI like `http://example.com/path` or `https://example.com`.
|
|
||||||
/// Falls back to the raw target if already in `host:port` form.
|
|
||||||
fn extract_host_port(uri: &str, default_port: u16) -> String {
|
|
||||||
let without_scheme = if let Some(rest) = uri.strip_prefix("https://") {
|
|
||||||
rest
|
|
||||||
} else if let Some(rest) = uri.strip_prefix("http://") {
|
|
||||||
rest
|
|
||||||
} else {
|
|
||||||
uri
|
|
||||||
};
|
|
||||||
// Trim path/query fragment
|
|
||||||
let host_part = without_scheme.split('/').next().unwrap_or(without_scheme);
|
|
||||||
if host_part.contains(':') {
|
|
||||||
host_part.to_string()
|
|
||||||
} else {
|
|
||||||
format!("{}:{}", host_part, default_port)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct StreamGuard {
|
|
||||||
stream_id: u16,
|
|
||||||
close_tx: mpsc::Sender<u16>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for StreamGuard {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let tx = self.close_tx.clone();
|
|
||||||
let id = self.stream_id;
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let _ = tx.send(id).await;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_proxy_client(
|
|
||||||
mut client: TcpStream,
|
|
||||||
stream_id: u16,
|
|
||||||
event_tx: mpsc::Sender<ProxyEvent>,
|
|
||||||
mut rx: mpsc::UnboundedReceiver<ProxyToClientMsg>,
|
|
||||||
close_tx: mpsc::Sender<u16>,
|
|
||||||
connect_timeout: Duration,
|
|
||||||
debug: bool,
|
|
||||||
matcher: ExclusionMatcher,
|
|
||||||
) -> Result<()> {
|
|
||||||
let _guard = StreamGuard { stream_id, close_tx: close_tx.clone() };
|
|
||||||
|
|
||||||
// Peek the first byte to distinguish SOCKS5 (0x05) from HTTP (any printable ASCII)
|
|
||||||
let mut first_byte = [0_u8; 1];
|
|
||||||
client.read_exact(&mut first_byte).await?;
|
|
||||||
|
|
||||||
let target: String;
|
|
||||||
let is_socks5 = first_byte[0] == 0x05;
|
|
||||||
|
|
||||||
if is_socks5 {
|
|
||||||
// ── SOCKS5 Handshake ──────────────────────────────────────────
|
|
||||||
let mut second_byte = [0_u8; 1];
|
|
||||||
client.read_exact(&mut second_byte).await?;
|
|
||||||
let nmethods = second_byte[0] as usize;
|
|
||||||
if nmethods > 0 {
|
|
||||||
let mut methods_buf = vec![0_u8; nmethods];
|
|
||||||
client.read_exact(&mut methods_buf).await?;
|
|
||||||
}
|
|
||||||
// Reply: version=5, NO AUTHENTICATION
|
|
||||||
client.write_all(&[0x05, 0x00]).await?;
|
|
||||||
|
|
||||||
// ── SOCKS5 Request ────────────────────────────────────────────
|
|
||||||
let mut req = [0_u8; 4];
|
|
||||||
client.read_exact(&mut req).await?;
|
|
||||||
if req[0] != 0x05 {
|
|
||||||
return Err(anyhow!("SOCKS5 request version mismatch"));
|
|
||||||
}
|
|
||||||
if req[1] != 0x01 {
|
|
||||||
// Not CONNECT — send COMMAND NOT SUPPORTED
|
|
||||||
client.write_all(&[0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
|
|
||||||
return Err(anyhow!("unsupported SOCKS5 command {}", req[1]));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut addr_buf = [0_u8; 256];
|
|
||||||
target = match req[3] {
|
|
||||||
0x01 => {
|
|
||||||
// IPv4: 4 bytes address + 2 bytes port
|
|
||||||
client.read_exact(&mut addr_buf[0..6]).await?;
|
|
||||||
let ip = std::net::Ipv4Addr::new(addr_buf[0], addr_buf[1], addr_buf[2], addr_buf[3]);
|
|
||||||
let port = u16::from_be_bytes([addr_buf[4], addr_buf[5]]);
|
|
||||||
format!("{}:{}", ip, port)
|
|
||||||
}
|
|
||||||
0x03 => {
|
|
||||||
// Domain: 1 byte length, then domain, then 2 bytes port
|
|
||||||
client.read_exact(&mut addr_buf[0..1]).await?;
|
|
||||||
let domain_len = addr_buf[0] as usize;
|
|
||||||
client.read_exact(&mut addr_buf[0..domain_len + 2]).await?;
|
|
||||||
let domain = String::from_utf8_lossy(&addr_buf[0..domain_len]);
|
|
||||||
let port = u16::from_be_bytes([addr_buf[domain_len], addr_buf[domain_len + 1]]);
|
|
||||||
format!("{}:{}", domain, port)
|
|
||||||
}
|
|
||||||
0x04 => {
|
|
||||||
// IPv6: 16 bytes + 2 bytes port
|
|
||||||
client.read_exact(&mut addr_buf[0..18]).await?;
|
|
||||||
let mut octets = [0u8; 16];
|
|
||||||
octets.copy_from_slice(&addr_buf[0..16]);
|
|
||||||
let ip = std::net::Ipv6Addr::from(octets);
|
|
||||||
let port = u16::from_be_bytes([addr_buf[16], addr_buf[17]]);
|
|
||||||
format!("[{}]:{}", ip, port)
|
|
||||||
}
|
|
||||||
atyp => {
|
|
||||||
client.write_all(&[0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
|
|
||||||
return Err(anyhow!("unsupported SOCKS5 address type: {}", atyp));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
tracing::info!("proxy CONNECT stream_id={stream_id} target={target}");
|
|
||||||
}
|
|
||||||
if matcher.should_bypass(&target, connect_timeout).await {
|
|
||||||
return direct_connect_socks5(client, stream_id, &target, close_tx, debug).await;
|
|
||||||
}
|
|
||||||
event_tx.send(ProxyEvent::NewStream { stream_id, target: target.clone() }).await?;
|
|
||||||
|
|
||||||
match timeout(connect_timeout, rx.recv()).await {
|
|
||||||
Ok(Some(ProxyToClientMsg::ConnectOk)) => {
|
|
||||||
// SUCCESS: version, 0=success, reserved, IPv4 type, 4 bytes addr, 2 bytes port
|
|
||||||
client.write_all(&[0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
|
|
||||||
}
|
|
||||||
Ok(Some(ProxyToClientMsg::Error(msg))) => {
|
|
||||||
client.write_all(&[0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
return Err(anyhow!("SOCKS5 connect error: {msg}"));
|
|
||||||
}
|
|
||||||
Ok(_) => {
|
|
||||||
client.write_all(&[0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
return Err(anyhow!("connect dropped"));
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
client.write_all(&[0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
return Err(anyhow!("connect timeout"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// ── HTTP Proxy (CONNECT and plain GET/POST) ───────────────────
|
|
||||||
// Read the rest of the HTTP request headers byte-by-byte
|
|
||||||
let mut header_bytes = Vec::with_capacity(512);
|
|
||||||
header_bytes.push(first_byte[0]);
|
|
||||||
let mut chunk = [0_u8; 512];
|
|
||||||
loop {
|
|
||||||
let n = client.read(&mut chunk).await?;
|
|
||||||
if n == 0 {
|
|
||||||
return Err(anyhow!("connection closed during HTTP header read"));
|
|
||||||
}
|
|
||||||
header_bytes.extend_from_slice(&chunk[..n]);
|
|
||||||
if header_bytes.len() >= 4 {
|
|
||||||
let tail = &header_bytes[header_bytes.len().saturating_sub(4)..];
|
|
||||||
if tail.ends_with(b"\r\n\r\n") {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if header_bytes.len() > 8192 {
|
|
||||||
client.write_all(b"HTTP/1.1 431 Request Header Fields Too Large\r\n\r\n").await?;
|
|
||||||
return Err(anyhow!("HTTP header too large"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let req_str = String::from_utf8_lossy(&header_bytes);
|
|
||||||
let first_line = req_str.lines().next().unwrap_or("");
|
|
||||||
let parts: Vec<&str> = first_line.split_whitespace().collect();
|
|
||||||
if parts.len() < 2 {
|
|
||||||
client.write_all(b"HTTP/1.1 400 Bad Request\r\n\r\n").await?;
|
|
||||||
return Err(anyhow!("malformed HTTP request line: {:?}", first_line));
|
|
||||||
}
|
|
||||||
|
|
||||||
let method = parts[0].to_uppercase();
|
|
||||||
let raw_uri = parts[1];
|
|
||||||
|
|
||||||
target = if method == "CONNECT" {
|
|
||||||
// CONNECT uses host:port directly — e.g. "CONNECT example.com:443 HTTP/1.1"
|
|
||||||
if raw_uri.contains(':') {
|
|
||||||
raw_uri.to_string()
|
|
||||||
} else {
|
|
||||||
format!("{}:443", raw_uri)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Plain HTTP: absolute URI like "GET http://example.com/path HTTP/1.1"
|
|
||||||
let default_port = if raw_uri.starts_with("https://") { 443u16 } else { 80u16 };
|
|
||||||
extract_host_port(raw_uri, default_port)
|
|
||||||
};
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
tracing::info!("proxy CONNECT stream_id={stream_id} target={target}");
|
|
||||||
}
|
|
||||||
if matcher.should_bypass(&target, connect_timeout).await {
|
|
||||||
return direct_connect_http(
|
|
||||||
client,
|
|
||||||
stream_id,
|
|
||||||
&target,
|
|
||||||
method.as_str(),
|
|
||||||
header_bytes,
|
|
||||||
close_tx,
|
|
||||||
debug,
|
|
||||||
).await;
|
|
||||||
}
|
|
||||||
event_tx.send(ProxyEvent::NewStream { stream_id, target: target.clone() }).await?;
|
|
||||||
|
|
||||||
match timeout(connect_timeout, rx.recv()).await {
|
|
||||||
Ok(Some(ProxyToClientMsg::ConnectOk)) => {
|
|
||||||
if method == "CONNECT" {
|
|
||||||
// For CONNECT, tell client the tunnel is ready
|
|
||||||
client.write_all(b"HTTP/1.1 200 Connection Established\r\nProxy-Agent: ostp/1.0\r\n\r\n").await?;
|
|
||||||
} else {
|
|
||||||
// For plain HTTP (GET/POST), we MUST forward the request headers we consumed
|
|
||||||
// to the server over the newly established tunnel.
|
|
||||||
event_tx.send(ProxyEvent::Data {
|
|
||||||
stream_id,
|
|
||||||
payload: bytes::Bytes::copy_from_slice(&header_bytes),
|
|
||||||
}).await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(Some(ProxyToClientMsg::Error(msg))) => {
|
|
||||||
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await?;
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
return Err(anyhow!("HTTP connect error: {msg}"));
|
|
||||||
}
|
|
||||||
Ok(_) => {
|
|
||||||
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await?;
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
return Err(anyhow!("connect dropped"));
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
client.write_all(b"HTTP/1.1 504 Gateway Timeout\r\n\r\n").await?;
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
return Err(anyhow!("connect timeout"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Bidirectional raw data forwarding ─────────────────────────────
|
|
||||||
let mut tcp_buf = vec![0_u8; 1024];
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
read_res = client.read(&mut tcp_buf) => {
|
|
||||||
match read_res {
|
|
||||||
Ok(0) => {
|
|
||||||
let _ = event_tx.send(ProxyEvent::Close { stream_id }).await;
|
|
||||||
if debug {
|
|
||||||
tracing::info!("proxy CLOSE stream_id={stream_id}");
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Ok(n) => {
|
|
||||||
let _ = event_tx.send(ProxyEvent::Data {
|
|
||||||
stream_id,
|
|
||||||
payload: bytes::Bytes::copy_from_slice(&tcp_buf[..n]),
|
|
||||||
}).await;
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
let _ = event_tx.send(ProxyEvent::Close { stream_id }).await;
|
|
||||||
if debug {
|
|
||||||
tracing::info!("proxy CLOSE stream_id={stream_id}");
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
msg = rx.recv() => {
|
|
||||||
match msg {
|
|
||||||
Some(ProxyToClientMsg::Data(data)) => {
|
|
||||||
if client.write_all(&data).await.is_err() {
|
|
||||||
let _ = event_tx.send(ProxyEvent::Close { stream_id }).await;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(ProxyToClientMsg::Close) | Some(ProxyToClientMsg::Error(_)) | None => {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Some(ProxyToClientMsg::ConnectOk) => {} // ignored after connect phase
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct ExclusionMatcher {
|
|
||||||
domain_suffix: Vec<String>,
|
|
||||||
cidrs: Vec<Cidr>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ExclusionMatcher {
|
|
||||||
fn new(exclusions: &ExclusionConfig) -> Self {
|
|
||||||
let mut cidrs = Vec::new();
|
|
||||||
for ip in &exclusions.ips {
|
|
||||||
if let Some(cidr) = parse_cidr(ip) {
|
|
||||||
cidrs.push(cidr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Self {
|
|
||||||
domain_suffix: exclusions
|
|
||||||
.domains
|
|
||||||
.iter()
|
|
||||||
.map(|d| d.trim().trim_start_matches('.').to_lowercase())
|
|
||||||
.filter(|d| !d.is_empty())
|
|
||||||
.collect(),
|
|
||||||
cidrs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn should_bypass(&self, target: &str, timeout_value: Duration) -> bool {
|
|
||||||
let (host, port) = match split_host_port(target) {
|
|
||||||
Some(v) => v,
|
|
||||||
None => return false,
|
|
||||||
};
|
|
||||||
|
|
||||||
if self.match_domain(&host) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.cidrs.is_empty() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
|
|
||||||
return self.match_ip(&ip);
|
|
||||||
}
|
|
||||||
|
|
||||||
let lookup_target = (host.clone(), port);
|
|
||||||
match timeout(timeout_value, tokio::net::lookup_host(lookup_target)).await {
|
|
||||||
Ok(Ok(addrs)) => addrs.into_iter().any(|addr| self.match_ip(&addr.ip())),
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn match_domain(&self, host: &str) -> bool {
|
|
||||||
if self.domain_suffix.is_empty() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let host = host.trim_end_matches('.').to_lowercase();
|
|
||||||
self.domain_suffix.iter().any(|suffix| {
|
|
||||||
host == *suffix || host.ends_with(&format!(".{suffix}"))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn match_ip(&self, ip: &std::net::IpAddr) -> bool {
|
|
||||||
self.cidrs.iter().any(|cidr| cidr.contains(ip))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
enum Cidr {
|
|
||||||
V4(u32, u8),
|
|
||||||
V6(u128, u8),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Cidr {
|
|
||||||
fn contains(&self, ip: &std::net::IpAddr) -> bool {
|
|
||||||
match (self, ip) {
|
|
||||||
(Cidr::V4(net, bits), std::net::IpAddr::V4(addr)) => {
|
|
||||||
let mask = if *bits == 0 { 0 } else { u32::MAX << (32 - bits) };
|
|
||||||
let ip = u32::from_be_bytes(addr.octets());
|
|
||||||
(ip & mask) == (*net & mask)
|
|
||||||
}
|
|
||||||
(Cidr::V6(net, bits), std::net::IpAddr::V6(addr)) => {
|
|
||||||
let mask = if *bits == 0 { 0 } else { u128::MAX << (128 - bits) };
|
|
||||||
let ip = u128::from_be_bytes(addr.octets());
|
|
||||||
(ip & mask) == (*net & mask)
|
|
||||||
}
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_cidr(value: &str) -> Option<Cidr> {
|
|
||||||
let value = value.trim();
|
|
||||||
if value.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some((addr_str, bits_str)) = value.split_once('/') {
|
|
||||||
let bits: u8 = bits_str.parse().ok()?;
|
|
||||||
if let Ok(addr) = addr_str.parse::<std::net::IpAddr>() {
|
|
||||||
return match addr {
|
|
||||||
std::net::IpAddr::V4(v4) => Some(Cidr::V4(u32::from_be_bytes(v4.octets()), bits.min(32))),
|
|
||||||
std::net::IpAddr::V6(v6) => Some(Cidr::V6(u128::from_be_bytes(v6.octets()), bits.min(128))),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(addr) = value.parse::<std::net::IpAddr>() {
|
|
||||||
return match addr {
|
|
||||||
std::net::IpAddr::V4(v4) => Some(Cidr::V4(u32::from_be_bytes(v4.octets()), 32)),
|
|
||||||
std::net::IpAddr::V6(v6) => Some(Cidr::V6(u128::from_be_bytes(v6.octets()), 128)),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn split_host_port(target: &str) -> Option<(String, u16)> {
|
|
||||||
if let Some((host, port)) = target.rsplit_once(':') {
|
|
||||||
if host.starts_with('[') && host.ends_with(']') {
|
|
||||||
let host = host.trim_start_matches('[').trim_end_matches(']').to_string();
|
|
||||||
let port = port.parse().ok()?;
|
|
||||||
return Some((host, port));
|
|
||||||
}
|
|
||||||
if host.contains(':') {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let port = port.parse().ok()?;
|
|
||||||
return Some((host.to_string(), port));
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn direct_connect_socks5(
|
|
||||||
mut client: TcpStream,
|
|
||||||
stream_id: u16,
|
|
||||||
target: &str,
|
|
||||||
close_tx: mpsc::Sender<u16>,
|
|
||||||
debug: bool,
|
|
||||||
) -> Result<()> {
|
|
||||||
if debug {
|
|
||||||
tracing::info!("proxy BYPASS stream_id={stream_id} target={target}");
|
|
||||||
}
|
|
||||||
let mut remote = TcpStream::connect(target).await
|
|
||||||
.with_context(|| format!("direct connect failed: {target}"))?;
|
|
||||||
|
|
||||||
client.write_all(&[0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
|
|
||||||
let _ = tokio::io::copy_bidirectional(&mut client, &mut remote).await;
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn direct_connect_http(
|
|
||||||
mut client: TcpStream,
|
|
||||||
stream_id: u16,
|
|
||||||
target: &str,
|
|
||||||
method: &str,
|
|
||||||
header_bytes: Vec<u8>,
|
|
||||||
close_tx: mpsc::Sender<u16>,
|
|
||||||
debug: bool,
|
|
||||||
) -> Result<()> {
|
|
||||||
if debug {
|
|
||||||
tracing::info!("proxy BYPASS stream_id={stream_id} target={target}");
|
|
||||||
}
|
|
||||||
let mut remote = TcpStream::connect(target).await
|
|
||||||
.with_context(|| format!("direct connect failed: {target}"))?;
|
|
||||||
|
|
||||||
if method == "CONNECT" {
|
|
||||||
client.write_all(b"HTTP/1.1 200 Connection Established\r\nProxy-Agent: ostp/1.0\r\n\r\n").await?;
|
|
||||||
} else {
|
|
||||||
remote.write_all(&header_bytes).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = tokio::io::copy_bidirectional(&mut client, &mut remote).await;
|
|
||||||
let _ = close_tx.send(stream_id).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,158 @@
|
||||||
|
use std::net::IpAddr;
|
||||||
|
use crate::config::{RoutingConfig, RoutingRule};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Session {
|
||||||
|
pub inbound_tag: String,
|
||||||
|
pub source_ip: Option<IpAddr>,
|
||||||
|
pub destination_ip: Option<IpAddr>,
|
||||||
|
pub destination_port: u16,
|
||||||
|
pub protocol: String, // "tcp" or "udp"
|
||||||
|
pub sni: Option<String>,
|
||||||
|
pub process_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Router {
|
||||||
|
config: RoutingConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Router {
|
||||||
|
pub fn new(config: RoutingConfig) -> Self {
|
||||||
|
Self { config }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluates the session against routing rules and returns the outbound tag
|
||||||
|
pub fn route(&self, session: &Session) -> String {
|
||||||
|
for rule in &self.config.rules {
|
||||||
|
if self.match_rule(rule, session) {
|
||||||
|
return rule.outbound.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.config.default_outbound.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn match_rule(&self, rule: &RoutingRule, session: &Session) -> bool {
|
||||||
|
// All specified conditions in a rule must match (AND logic)
|
||||||
|
let mut matched_any_condition = false;
|
||||||
|
|
||||||
|
// 1. Inbound Tag match
|
||||||
|
if let Some(inbounds) = &rule.inbound_tag {
|
||||||
|
if !inbounds.iter().any(|tag| tag == &session.inbound_tag) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
matched_any_condition = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Domain / SNI match
|
||||||
|
if let Some(domains) = &rule.domain_suffix {
|
||||||
|
let mut domain_match = false;
|
||||||
|
if let Some(sni) = &session.sni {
|
||||||
|
let sni_lower = sni.to_lowercase();
|
||||||
|
domain_match = domains.iter().any(|d| {
|
||||||
|
let d_lower = d.to_lowercase();
|
||||||
|
sni_lower == d_lower || sni_lower.ends_with(&format!(".{}", d_lower))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if !domain_match {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
matched_any_condition = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Process match
|
||||||
|
if let Some(processes) = &rule.process_name {
|
||||||
|
let mut proc_match = false;
|
||||||
|
if let Some(proc) = &session.process_name {
|
||||||
|
let proc_lower = proc.to_lowercase();
|
||||||
|
proc_match = processes.iter().any(|p| {
|
||||||
|
let p_lower = p.to_lowercase();
|
||||||
|
proc_lower.contains(&p_lower)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if !proc_match {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
matched_any_condition = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. IP CIDR match
|
||||||
|
if let Some(cidrs) = &rule.ip_cidr {
|
||||||
|
let mut ip_match = false;
|
||||||
|
if let Some(dst_ip) = session.destination_ip {
|
||||||
|
ip_match = cidrs.iter().any(|cidr| {
|
||||||
|
match ipnet::IpNet::from_str(cidr) {
|
||||||
|
Ok(net) => net.contains(&dst_ip),
|
||||||
|
Err(_) => {
|
||||||
|
// fallback to exact ip match if not a valid CIDR
|
||||||
|
if let Ok(ip) = cidr.parse::<IpAddr>() {
|
||||||
|
ip == dst_ip
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if !ip_match {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
matched_any_condition = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A rule must have at least one condition to match
|
||||||
|
matched_any_condition
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_router() {
|
||||||
|
let rules = vec![
|
||||||
|
RoutingRule {
|
||||||
|
domain_suffix: Some(vec!["vk.com".to_string()]),
|
||||||
|
ip_cidr: None,
|
||||||
|
process_name: None,
|
||||||
|
inbound_tag: None,
|
||||||
|
outbound: "direct".to_string(),
|
||||||
|
},
|
||||||
|
RoutingRule {
|
||||||
|
domain_suffix: None,
|
||||||
|
ip_cidr: None,
|
||||||
|
process_name: Some(vec!["telegram.exe".to_string()]),
|
||||||
|
inbound_tag: None,
|
||||||
|
outbound: "proxy-group".to_string(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
let config = RoutingConfig {
|
||||||
|
rules,
|
||||||
|
default_outbound: "proxy-group".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let router = Router::new(config);
|
||||||
|
|
||||||
|
let mut session = Session {
|
||||||
|
inbound_tag: "tun-in".to_string(),
|
||||||
|
source_ip: None,
|
||||||
|
destination_ip: None,
|
||||||
|
destination_port: 443,
|
||||||
|
protocol: "tcp".to_string(),
|
||||||
|
sni: Some("api.vk.com".to_string()),
|
||||||
|
process_name: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(router.route(&session), "direct");
|
||||||
|
|
||||||
|
session.sni = None;
|
||||||
|
session.process_name = Some("C:\\App\\Telegram.exe".to_string());
|
||||||
|
assert_eq!(router.route(&session), "proxy-group");
|
||||||
|
|
||||||
|
session.process_name = Some("chrome.exe".to_string());
|
||||||
|
assert_eq!(router.route(&session), "proxy-group"); // fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,73 @@
|
||||||
|
pub fn extract_sni(data: &[u8]) -> Option<String> {
|
||||||
|
// Basic TLS ClientHello parser
|
||||||
|
// Must be at least 43 bytes to contain anything useful
|
||||||
|
if data.len() < 43 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// TLS Record layer: Handshake (22)
|
||||||
|
if data[0] != 0x16 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record layer version: 0x0301 (TLS 1.0) or 0x0303 (TLS 1.2)
|
||||||
|
if data[1] != 0x03 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handshake type: ClientHello (1)
|
||||||
|
if data[5] != 0x01 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pos = 43; // Skip fixed ClientHello header
|
||||||
|
|
||||||
|
// Skip Session ID
|
||||||
|
if pos >= data.len() { return None; }
|
||||||
|
let session_id_len = data[pos] as usize;
|
||||||
|
pos += 1 + session_id_len;
|
||||||
|
|
||||||
|
// Skip Cipher Suites
|
||||||
|
if pos + 2 > data.len() { return None; }
|
||||||
|
let cipher_suites_len = ((data[pos] as usize) << 8) | (data[pos + 1] as usize);
|
||||||
|
pos += 2 + cipher_suites_len;
|
||||||
|
|
||||||
|
// Skip Compression Methods
|
||||||
|
if pos >= data.len() { return None; }
|
||||||
|
let comp_methods_len = data[pos] as usize;
|
||||||
|
pos += 1 + comp_methods_len;
|
||||||
|
|
||||||
|
// Extensions
|
||||||
|
if pos + 2 > data.len() { return None; }
|
||||||
|
let extensions_len = ((data[pos] as usize) << 8) | (data[pos + 1] as usize);
|
||||||
|
pos += 2;
|
||||||
|
|
||||||
|
let extensions_end = pos + extensions_len;
|
||||||
|
if extensions_end > data.len() { return None; }
|
||||||
|
|
||||||
|
while pos + 4 <= extensions_end {
|
||||||
|
let ext_type = ((data[pos] as usize) << 8) | (data[pos + 1] as usize);
|
||||||
|
let ext_len = ((data[pos + 2] as usize) << 8) | (data[pos + 3] as usize);
|
||||||
|
pos += 4;
|
||||||
|
|
||||||
|
if ext_type == 0x0000 { // Server Name Indication (SNI)
|
||||||
|
if pos + 5 <= extensions_end {
|
||||||
|
let _list_len = ((data[pos] as usize) << 8) | (data[pos + 1] as usize);
|
||||||
|
let name_type = data[pos + 2];
|
||||||
|
if name_type == 0 { // Hostname
|
||||||
|
let name_len = ((data[pos + 3] as usize) << 8) | (data[pos + 4] as usize);
|
||||||
|
if pos + 5 + name_len <= extensions_end {
|
||||||
|
let sni_bytes = &data[pos + 5..pos + 5 + name_len];
|
||||||
|
if let Ok(sni) = std::str::from_utf8(sni_bytes) {
|
||||||
|
return Some(sni.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos += ext_len;
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
// Cleared for refactoring
|
||||||
|
|
@ -1,241 +0,0 @@
|
||||||
use anyhow::{anyhow, Result};
|
|
||||||
use tokio::sync::watch;
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
pub async fn run_wintun_tunnel(
|
|
||||||
config: crate::config::ClientConfig,
|
|
||||||
mut shutdown: watch::Receiver<bool>,
|
|
||||||
) -> Result<()> {
|
|
||||||
use std::net::ToSocketAddrs;
|
|
||||||
use std::process::{Command, Stdio, Child};
|
|
||||||
use std::os::windows::process::CommandExt;
|
|
||||||
|
|
||||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
|
||||||
const TUN_NAME: &str = "ostp_tun";
|
|
||||||
|
|
||||||
struct WintunGuard {
|
|
||||||
server_ip_str: String,
|
|
||||||
child: Option<Child>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for WintunGuard {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Some(mut child) = self.child.take() {
|
|
||||||
let _ = child.kill();
|
|
||||||
let _ = child.wait();
|
|
||||||
}
|
|
||||||
let cleanup_script = format!(
|
|
||||||
"$remote_ip = '{}'\n\
|
|
||||||
Remove-NetRoute -DestinationPrefix \"$remote_ip/32\" -Confirm:$false -ErrorAction SilentlyContinue\n\
|
|
||||||
Remove-NetRoute -DestinationPrefix \"1.1.1.1/32\" -Confirm:$false -ErrorAction SilentlyContinue\n\
|
|
||||||
Remove-NetFirewallRule -DisplayName 'OSTP Tunnel*' -ErrorAction SilentlyContinue\n\
|
|
||||||
netsh interface ipv4 set dnsservers name=\"{TUN_NAME}\" source=dhcp 2>$null\n",
|
|
||||||
self.server_ip_str
|
|
||||||
);
|
|
||||||
let _ = Command::new("powershell")
|
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
|
||||||
.args(["-NoProfile", "-Command", &cleanup_script])
|
|
||||||
.output();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let debug = config.debug;
|
|
||||||
|
|
||||||
tracing::info!("Initializing TUN tunnel...");
|
|
||||||
|
|
||||||
let exe = std::env::current_exe()?;
|
|
||||||
let dir = exe.parent().ok_or_else(|| anyhow!("failed to get binary directory"))?;
|
|
||||||
let tun2socks_exe = dir.join("tun2socks.exe");
|
|
||||||
|
|
||||||
if !tun2socks_exe.exists() {
|
|
||||||
return Err(anyhow!(
|
|
||||||
"CRITICAL: 'tun2socks.exe' binary is missing!\n\
|
|
||||||
OSTP requires tun2socks for TUN mode on Windows. Please download the appropriate binary from: \n\
|
|
||||||
https://github.com/xjasonlyu/tun2socks/releases \n\
|
|
||||||
and place it in the same directory as the ostp executable ({}).",
|
|
||||||
dir.display()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. Delete stale TUN adapter if it exists from a previous run.
|
|
||||||
// This prevents wintun from creating "ostp_tun 2", "ostp_tun 3", etc.
|
|
||||||
tracing::info!("Cleaning up stale TUN adapter...");
|
|
||||||
let _ = Command::new("powershell")
|
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
|
||||||
.args(["-NoProfile", "-Command", &format!(
|
|
||||||
"Get-NetAdapter -Name '{TUN_NAME}*' -ErrorAction SilentlyContinue | \
|
|
||||||
Disable-NetAdapter -Confirm:$false -ErrorAction SilentlyContinue; \
|
|
||||||
netsh interface set interface \"{TUN_NAME}\" admin=disable 2>$null"
|
|
||||||
)])
|
|
||||||
.output();
|
|
||||||
// Brief pause to let the driver release the adapter
|
|
||||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
|
||||||
|
|
||||||
// 2. Resolve Server IP for routing table exclusion
|
|
||||||
let server_ip = config.ostp.server_addr.to_socket_addrs()
|
|
||||||
.map_err(|e| anyhow!("Failed to resolve remote server IP: {}", e))?
|
|
||||||
.next()
|
|
||||||
.map(|addr| addr.ip())
|
|
||||||
.ok_or_else(|| anyhow!("Could not resolve host IP for routing exclusion"))?;
|
|
||||||
|
|
||||||
let server_ip_str = server_ip.to_string();
|
|
||||||
tracing::info!("Resolved server IP: {}", server_ip_str);
|
|
||||||
|
|
||||||
// 3. Prepare routing and firewall setup script
|
|
||||||
let current_exe = std::env::current_exe()?.to_string_lossy().into_owned();
|
|
||||||
|
|
||||||
let setup_script = format!(
|
|
||||||
"$remote_ip = '{}'\n\
|
|
||||||
$exe_path = '{}'\n\
|
|
||||||
$route = Find-NetRoute -RemoteIPAddress $remote_ip -ErrorAction SilentlyContinue | Select-Object -First 1\n\
|
|
||||||
if (-not $route) {{\n\
|
|
||||||
$route = Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Where-Object {{ $_.InterfaceAlias -notmatch 'tun' -and $_.InterfaceAlias -notmatch 'wintun' }} | Sort-Object RouteMetric | Select-Object -First 1\n\
|
|
||||||
}}\n\
|
|
||||||
$gw = $route.NextHop\n\
|
|
||||||
$ifIndex = $route.InterfaceIndex\n\
|
|
||||||
New-NetRoute -DestinationPrefix \"$remote_ip/32\" -NextHop $gw -InterfaceIndex $ifIndex -RouteMetric 1 -ErrorAction SilentlyContinue\n\
|
|
||||||
$dns_ips = Get-DnsClientServerAddress -InterfaceIndex $ifIndex | Select-Object -ExpandProperty ServerAddresses\n\
|
|
||||||
foreach ($dns in $dns_ips) {{\n\
|
|
||||||
if ($dns -match '^\\d+\\.\\d+\\.\\d+\\.\\d+$') {{\n\
|
|
||||||
New-NetRoute -DestinationPrefix \"$dns/32\" -NextHop $gw -InterfaceIndex $ifIndex -RouteMetric 1 -ErrorAction SilentlyContinue\n\
|
|
||||||
}}\n\
|
|
||||||
}}\n\
|
|
||||||
New-NetRoute -DestinationPrefix \"1.1.1.1/32\" -NextHop $gw -InterfaceIndex $ifIndex -RouteMetric 1 -ErrorAction SilentlyContinue\n\
|
|
||||||
New-NetFirewallRule -DisplayName 'OSTP Tunnel In' -Direction Inbound -Program $exe_path -Action Allow -Enabled True -ErrorAction SilentlyContinue\n\
|
|
||||||
New-NetFirewallRule -DisplayName 'OSTP Tunnel Out' -Direction Outbound -Program $exe_path -Action Allow -Enabled True -ErrorAction SilentlyContinue\n",
|
|
||||||
server_ip_str, current_exe
|
|
||||||
);
|
|
||||||
|
|
||||||
// 4. Launch tun2socks + route setup IN PARALLEL to save ~3 seconds
|
|
||||||
let proxy_url = format!("http://{}", config.local_proxy.bind_addr);
|
|
||||||
tracing::info!("Starting tun2socks (proxy={})", proxy_url);
|
|
||||||
|
|
||||||
// Spawn tun2socks immediately — it creates the adapter on its own
|
|
||||||
let mut child = Command::new(&tun2socks_exe)
|
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
|
||||||
.args([
|
|
||||||
"-device", TUN_NAME,
|
|
||||||
"-proxy", &proxy_url,
|
|
||||||
"-loglevel", if debug { "debug" } else { "error" }
|
|
||||||
])
|
|
||||||
.current_dir(dir)
|
|
||||||
.stdout(if debug { Stdio::piped() } else { Stdio::null() })
|
|
||||||
.stderr(if debug { Stdio::piped() } else { Stdio::null() })
|
|
||||||
.spawn()
|
|
||||||
.map_err(|e| anyhow!("Failed to launch tun2socks.exe: {}", e))?;
|
|
||||||
|
|
||||||
let mut _guard = WintunGuard {
|
|
||||||
server_ip_str: server_ip_str.clone(),
|
|
||||||
child: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Run route setup in parallel while tun2socks creates the adapter.
|
|
||||||
// Also poll for the adapter to appear (typically <1s).
|
|
||||||
let route_handle = {
|
|
||||||
let script = setup_script.clone();
|
|
||||||
tokio::task::spawn_blocking(move || {
|
|
||||||
Command::new("powershell")
|
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
|
||||||
.args(["-NoProfile", "-Command", &script])
|
|
||||||
.output()
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
// 5. Wait for TUN adapter to appear (poll with timeout instead of fixed 2s sleep)
|
|
||||||
let adapter_deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(8);
|
|
||||||
let mut adapter_ready = false;
|
|
||||||
while tokio::time::Instant::now() < adapter_deadline {
|
|
||||||
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
|
||||||
let check = Command::new("powershell")
|
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
|
||||||
.args(["-NoProfile", "-Command",
|
|
||||||
&format!("(Get-NetAdapter -Name '{TUN_NAME}' -ErrorAction SilentlyContinue).Status")])
|
|
||||||
.output();
|
|
||||||
if let Ok(out) = check {
|
|
||||||
let status = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
|
||||||
if debug {
|
|
||||||
tracing::info!("Adapter status: '{}'", status);
|
|
||||||
}
|
|
||||||
if status == "Up" || status == "Disconnected" || !status.is_empty() {
|
|
||||||
adapter_ready = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !adapter_ready {
|
|
||||||
tracing::warn!("WARNING: TUN adapter did not appear within timeout. Proceeding anyway.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for route setup to finish (should already be done by now)
|
|
||||||
let _ = route_handle.await;
|
|
||||||
|
|
||||||
// 6. Configure the adapter (IP, metric, MTU, DNS)
|
|
||||||
tracing::info!("Applying network configuration...");
|
|
||||||
let mut net_setup = format!(
|
|
||||||
"netsh interface ipv4 set address name=\"{TUN_NAME}\" static 10.1.0.2 255.255.255.0 10.1.0.1\n\
|
|
||||||
netsh interface ipv4 set subinterface \"{TUN_NAME}\" mtu={} store=persistent\n\
|
|
||||||
netsh interface ipv4 set interface name=\"{TUN_NAME}\" metric=5\n",
|
|
||||||
config.ostp.mtu
|
|
||||||
);
|
|
||||||
|
|
||||||
if let Some(ref dns) = config.dns_server {
|
|
||||||
if !dns.is_empty() {
|
|
||||||
tracing::info!("DNS server: {}", dns);
|
|
||||||
net_setup.push_str(&format!(
|
|
||||||
"netsh interface ipv4 set dnsservers name=\"{TUN_NAME}\" static {} primary\n", dns
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = Command::new("powershell")
|
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
|
||||||
.args(["-NoProfile", "-Command", &net_setup])
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
tracing::info!("TUN tunnel active. All traffic is routed through OSTP.");
|
|
||||||
|
|
||||||
// 7. Spawn debug log readers for tun2socks output
|
|
||||||
let mut stdout = child.stdout.take();
|
|
||||||
let mut stderr = child.stderr.take();
|
|
||||||
_guard.child = Some(child);
|
|
||||||
|
|
||||||
if debug {
|
|
||||||
std::thread::spawn(move || {
|
|
||||||
use std::io::{BufRead, BufReader};
|
|
||||||
if let Some(out) = stdout.take() {
|
|
||||||
let reader = BufReader::new(out);
|
|
||||||
for line in reader.lines().map_while(Result::ok) {
|
|
||||||
tracing::debug!("tun2socks: {}", line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
std::thread::spawn(move || {
|
|
||||||
use std::io::{BufRead, BufReader};
|
|
||||||
if let Some(err) = stderr.take() {
|
|
||||||
let reader = BufReader::new(err);
|
|
||||||
for line in reader.lines().map_while(Result::ok) {
|
|
||||||
tracing::warn!("tun2socks: {}", line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 8. Wait for shutdown signal
|
|
||||||
let _ = shutdown.changed().await;
|
|
||||||
|
|
||||||
tracing::info!("Deactivating TUN tunnel...");
|
|
||||||
drop(_guard);
|
|
||||||
tracing::info!("TUN tunnel stopped.");
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub async fn run_wintun_tunnel(
|
|
||||||
_config: crate::config::ClientConfig,
|
|
||||||
_shutdown: watch::Receiver<bool>,
|
|
||||||
) -> Result<()> {
|
|
||||||
Err(anyhow!("Wintun driver executed on a non-Windows host!"))
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
fn main() { let x: () = netstack_smoltcp::StackBuilder::default().build().unwrap(); }
|
||||||
|
After Width: | Height: | Size: 9.3 KiB |
|
|
@ -0,0 +1,24 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||||
|
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||||
|
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||||
|
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 4.9 KiB |
|
|
@ -0,0 +1,14 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="./favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>ostp-control</title>
|
||||||
|
<script type="module" crossorigin src="./assets/index-eeBKspfZ.js"></script>
|
||||||
|
<link rel="stylesheet" crossorigin href="./assets/index-DADo1Z55.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -12,5 +12,10 @@ rand.workspace = true
|
||||||
snow.workspace = true
|
snow.workspace = true
|
||||||
thiserror.workspace = true
|
thiserror.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
|
byteorder = "1.5"
|
||||||
sha2.workspace = true
|
sha2.workspace = true
|
||||||
hmac.workspace = true
|
hmac.workspace = true
|
||||||
|
x25519-dalek = { version = "2.0.1", features = ["static_secrets"] }
|
||||||
|
hkdf = "0.12.0"
|
||||||
|
tokio.workspace = true
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,6 @@
|
||||||
//! This replaces the fixed `retransmit_budget = 8` with an adaptive
|
//! This replaces the fixed `retransmit_budget = 8` with an adaptive
|
||||||
//! congestion window that responds to network conditions.
|
//! congestion window that responds to network conditions.
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
/// Congestion control state for a single OSTP session.
|
/// Congestion control state for a single OSTP session.
|
||||||
|
|
@ -16,14 +15,8 @@ pub struct CongestionController {
|
||||||
ssthresh: u64,
|
ssthresh: u64,
|
||||||
/// Current phase
|
/// Current phase
|
||||||
phase: Phase,
|
phase: Phase,
|
||||||
/// Minimum RTT observed (used for BDP calculation)
|
/// Minimum RTT observed
|
||||||
min_rtt: Duration,
|
min_rtt: Duration,
|
||||||
/// Maximum bandwidth observed (bytes/sec)
|
|
||||||
max_bandwidth: u64,
|
|
||||||
/// RTT samples for smoothing
|
|
||||||
rtt_samples: VecDeque<RttSample>,
|
|
||||||
/// Bandwidth samples
|
|
||||||
bw_samples: VecDeque<BwSample>,
|
|
||||||
/// Bytes currently in flight (unacknowledged)
|
/// Bytes currently in flight (unacknowledged)
|
||||||
bytes_in_flight: u64,
|
bytes_in_flight: u64,
|
||||||
/// Total bytes acknowledged (for bandwidth estimation)
|
/// Total bytes acknowledged (for bandwidth estimation)
|
||||||
|
|
@ -36,8 +29,6 @@ pub struct CongestionController {
|
||||||
pacing_rate: u64,
|
pacing_rate: u64,
|
||||||
/// MTU estimate (used for cwnd → packet count conversion)
|
/// MTU estimate (used for cwnd → packet count conversion)
|
||||||
mtu: u64,
|
mtu: u64,
|
||||||
/// Probe RTT phase timer
|
|
||||||
probe_rtt_timer: Option<Instant>,
|
|
||||||
/// Min RTT expiry: re-probe after 10 seconds
|
/// Min RTT expiry: re-probe after 10 seconds
|
||||||
min_rtt_stamp: Instant,
|
min_rtt_stamp: Instant,
|
||||||
}
|
}
|
||||||
|
|
@ -48,34 +39,14 @@ enum Phase {
|
||||||
SlowStart,
|
SlowStart,
|
||||||
/// Probe bandwidth: cycle through pacing gains
|
/// Probe bandwidth: cycle through pacing gains
|
||||||
ProbeBandwidth,
|
ProbeBandwidth,
|
||||||
/// Periodically drain the queue to measure true min RTT
|
|
||||||
ProbeRtt,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
#[allow(dead_code)]
|
|
||||||
struct RttSample {
|
|
||||||
rtt: Duration,
|
|
||||||
time: Instant,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
#[allow(dead_code)]
|
|
||||||
struct BwSample {
|
|
||||||
bytes_per_sec: u64,
|
|
||||||
time: Instant,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Maximum number of samples to keep for windowed min/max
|
|
||||||
const MAX_SAMPLES: usize = 32;
|
|
||||||
/// Initial congestion window: 10 packets × MTU
|
/// Initial congestion window: 10 packets × MTU
|
||||||
const INITIAL_CWND_PACKETS: u64 = 10;
|
const INITIAL_CWND_PACKETS: u64 = 10;
|
||||||
/// Minimum cwnd: 2 packets
|
/// Minimum cwnd: 2 packets
|
||||||
const MIN_CWND_PACKETS: u64 = 2;
|
const MIN_CWND_PACKETS: u64 = 2;
|
||||||
/// Min RTT expiry window (after which we re-probe)
|
/// Min RTT expiry window (after which we re-probe)
|
||||||
const MIN_RTT_EXPIRY: Duration = Duration::from_secs(10);
|
const MIN_RTT_EXPIRY: Duration = Duration::from_secs(10);
|
||||||
/// ProbeRTT drain duration
|
|
||||||
const PROBE_RTT_DURATION: Duration = Duration::from_millis(200);
|
|
||||||
|
|
||||||
impl CongestionController {
|
impl CongestionController {
|
||||||
pub fn new(mtu: u64) -> Self {
|
pub fn new(mtu: u64) -> Self {
|
||||||
|
|
@ -86,16 +57,12 @@ impl CongestionController {
|
||||||
ssthresh: u64::MAX,
|
ssthresh: u64::MAX,
|
||||||
phase: Phase::SlowStart,
|
phase: Phase::SlowStart,
|
||||||
min_rtt: Duration::from_millis(100), // Conservative initial estimate
|
min_rtt: Duration::from_millis(100), // Conservative initial estimate
|
||||||
max_bandwidth: 0,
|
|
||||||
rtt_samples: VecDeque::with_capacity(MAX_SAMPLES),
|
|
||||||
bw_samples: VecDeque::with_capacity(MAX_SAMPLES),
|
|
||||||
bytes_in_flight: 0,
|
bytes_in_flight: 0,
|
||||||
total_acked: 0,
|
total_acked: 0,
|
||||||
last_ack_time: now,
|
last_ack_time: now,
|
||||||
loss_count: 0,
|
loss_count: 0,
|
||||||
pacing_rate: initial_cwnd * 10, // initial: ~10 windows/sec
|
pacing_rate: initial_cwnd * 10, // initial: ~10 windows/sec
|
||||||
mtu,
|
mtu,
|
||||||
probe_rtt_timer: None,
|
|
||||||
min_rtt_stamp: now,
|
min_rtt_stamp: now,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -165,38 +132,9 @@ impl CongestionController {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Phase::ProbeBandwidth => {
|
Phase::ProbeBandwidth => {
|
||||||
// BBR-style: target cwnd = BDP * gain
|
// TCP Reno Additive Increase: increase cwnd by ~1 MTU per RTT
|
||||||
let bdp = self.bandwidth_delay_product();
|
self.cwnd = self.cwnd.saturating_add(bytes * self.mtu / self.cwnd.max(1));
|
||||||
// Apply gain of 1.25 during probe bandwidth
|
|
||||||
let target = (bdp * 5 / 4).max(MIN_CWND_PACKETS * self.mtu);
|
|
||||||
// Smooth transition
|
|
||||||
if self.cwnd < target {
|
|
||||||
self.cwnd = self.cwnd.saturating_add(bytes * self.mtu / self.cwnd.max(1));
|
|
||||||
} else {
|
|
||||||
self.cwnd = target;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Phase::ProbeRtt => {
|
|
||||||
// Drain down to 4 packets to measure true min RTT
|
|
||||||
self.cwnd = MIN_CWND_PACKETS * self.mtu * 2;
|
|
||||||
if let Some(timer) = self.probe_rtt_timer {
|
|
||||||
if now.duration_since(timer) >= PROBE_RTT_DURATION {
|
|
||||||
// ProbeRTT complete, return to ProbeBandwidth
|
|
||||||
self.phase = Phase::ProbeBandwidth;
|
|
||||||
self.probe_rtt_timer = None;
|
|
||||||
let bdp = self.bandwidth_delay_product();
|
|
||||||
self.cwnd = bdp.max(MIN_CWND_PACKETS * self.mtu);
|
|
||||||
tracing::debug!(cwnd = self.cwnd, min_rtt = ?self.min_rtt, "congestion: probe RTT complete");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Periodically enter ProbeRTT to refresh min_rtt
|
|
||||||
if now.duration_since(self.min_rtt_stamp) >= MIN_RTT_EXPIRY && self.phase != Phase::ProbeRtt {
|
|
||||||
self.phase = Phase::ProbeRtt;
|
|
||||||
self.probe_rtt_timer = Some(now);
|
|
||||||
tracing::debug!("congestion: entering probe RTT phase");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.update_pacing_rate();
|
self.update_pacing_rate();
|
||||||
|
|
@ -221,9 +159,6 @@ impl CongestionController {
|
||||||
self.cwnd = (self.cwnd * 7 / 10).max(MIN_CWND_PACKETS * self.mtu);
|
self.cwnd = (self.cwnd * 7 / 10).max(MIN_CWND_PACKETS * self.mtu);
|
||||||
tracing::debug!(cwnd = self.cwnd, "congestion: loss, cwnd reduced");
|
tracing::debug!(cwnd = self.cwnd, "congestion: loss, cwnd reduced");
|
||||||
}
|
}
|
||||||
Phase::ProbeRtt => {
|
|
||||||
// Don't react to loss during ProbeRTT
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.update_pacing_rate();
|
self.update_pacing_rate();
|
||||||
|
|
@ -242,39 +177,16 @@ impl CongestionController {
|
||||||
self.min_rtt = rtt;
|
self.min_rtt = rtt;
|
||||||
self.min_rtt_stamp = now;
|
self.min_rtt_stamp = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keep sample history
|
|
||||||
self.rtt_samples.push_back(RttSample { rtt, time: now });
|
|
||||||
while self.rtt_samples.len() > MAX_SAMPLES {
|
|
||||||
self.rtt_samples.pop_front();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_bandwidth(&mut self, acked_bytes: u64, now: Instant) {
|
fn update_bandwidth(&mut self, _acked_bytes: u64, now: Instant) {
|
||||||
let elapsed = now.duration_since(self.last_ack_time);
|
let elapsed = now.duration_since(self.last_ack_time);
|
||||||
if elapsed.as_micros() > 0 {
|
if elapsed.as_micros() > 0 {
|
||||||
let bw = acked_bytes * 1_000_000 / elapsed.as_micros() as u64;
|
// Removed bw_samples tracking
|
||||||
if bw > self.max_bandwidth {
|
|
||||||
self.max_bandwidth = bw;
|
|
||||||
}
|
|
||||||
self.bw_samples.push_back(BwSample { bytes_per_sec: bw, time: now });
|
|
||||||
while self.bw_samples.len() > MAX_SAMPLES {
|
|
||||||
self.bw_samples.pop_front();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bandwidth_delay_product(&self) -> u64 {
|
|
||||||
// BDP = max_bandwidth * min_rtt
|
|
||||||
let bw = if self.max_bandwidth > 0 {
|
|
||||||
self.max_bandwidth
|
|
||||||
} else {
|
|
||||||
// Fallback: assume 10 Mbps
|
|
||||||
1_250_000
|
|
||||||
};
|
|
||||||
let rtt_secs = self.min_rtt.as_secs_f64();
|
|
||||||
(bw as f64 * rtt_secs) as u64
|
|
||||||
}
|
|
||||||
|
|
||||||
fn update_pacing_rate(&mut self) {
|
fn update_pacing_rate(&mut self) {
|
||||||
// Pacing rate = cwnd / min_rtt (with gain)
|
// Pacing rate = cwnd / min_rtt (with gain)
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ pub mod aead;
|
||||||
pub mod noise;
|
pub mod noise;
|
||||||
pub mod obfuscation;
|
pub mod obfuscation;
|
||||||
|
|
||||||
|
|
||||||
pub use aead::SessionCipher;
|
pub use aead::SessionCipher;
|
||||||
pub use noise::{NoiseRole, NoiseSession};
|
pub use noise::{NoiseRole, NoiseSession};
|
||||||
pub use obfuscation::{
|
pub use obfuscation::{
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,279 @@
|
||||||
|
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||||
|
use chacha20poly1305::{aead::{Aead, KeyInit}, ChaCha20Poly1305, Nonce};
|
||||||
|
use hkdf::Hkdf;
|
||||||
|
use sha2::Sha256;
|
||||||
|
use x25519_dalek::{PublicKey, StaticSecret};
|
||||||
|
use rand::{rngs::OsRng, RngCore};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
const REALITY_INFO: &[u8] = b"ostp-reality-v1";
|
||||||
|
const RECORD_HEADER_LEN: usize = 5;
|
||||||
|
const HANDSHAKE_HEADER_LEN: usize = 4;
|
||||||
|
|
||||||
|
/// Number of TLS records sent by the server during the fake handshake phase.
|
||||||
|
/// Client must read and discard this many records before starting RealityStream.
|
||||||
|
/// Layout: 1× ServerHello (0x16) + 1× CCS (0x14) + 3× fake encrypted records (0x17)
|
||||||
|
pub const REALITY_SERVER_HANDSHAKE_RECORDS: usize = 5;
|
||||||
|
|
||||||
|
/// Generates an X25519 keypair
|
||||||
|
pub fn generate_x25519_keypair() -> (StaticSecret, PublicKey) {
|
||||||
|
let secret = StaticSecret::random_from_rng(OsRng);
|
||||||
|
let public = PublicKey::from(&secret);
|
||||||
|
(secret, public)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derives the Auth Key and Data Key from the X25519 shared secret
|
||||||
|
pub fn derive_keys(shared_secret: &[u8; 32]) -> (ChaCha20Poly1305, ChaCha20Poly1305) {
|
||||||
|
let hk = Hkdf::<Sha256>::new(None, shared_secret);
|
||||||
|
let mut okm = [0u8; 64];
|
||||||
|
hk.expand(REALITY_INFO, &mut okm).expect("HKDF expand failed");
|
||||||
|
|
||||||
|
let auth_key = ChaCha20Poly1305::new_from_slice(&okm[0..32]).unwrap();
|
||||||
|
let data_key = ChaCha20Poly1305::new_from_slice(&okm[32..64]).unwrap();
|
||||||
|
(auth_key, data_key)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an authenticated Session ID payload (32 bytes)
|
||||||
|
/// sid: 8 bytes, timestamp: 8 bytes. Encrypted with ChaCha20Poly1305 (16 byte tag). Total = 32 bytes.
|
||||||
|
pub fn generate_session_id(auth_aead: &ChaCha20Poly1305, sid: &[u8; 8]) -> [u8; 32] {
|
||||||
|
let ts = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
|
||||||
|
let mut plaintext = [0u8; 16];
|
||||||
|
plaintext[0..8].copy_from_slice(sid);
|
||||||
|
plaintext[8..16].copy_from_slice(&ts.to_be_bytes());
|
||||||
|
|
||||||
|
let nonce = Nonce::from_slice(&[0u8; 12]); // Fixed nonce since auth key is ephemeral per connection
|
||||||
|
let ciphertext = auth_aead.encrypt(nonce, plaintext.as_ref()).expect("encryption failed");
|
||||||
|
|
||||||
|
let mut session_id = [0u8; 32];
|
||||||
|
session_id.copy_from_slice(&ciphertext);
|
||||||
|
session_id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifies and decrypts the Session ID payload. Returns (sid, timestamp)
|
||||||
|
pub fn verify_session_id(auth_aead: &ChaCha20Poly1305, session_id: &[u8; 32]) -> Option<([u8; 8], u64)> {
|
||||||
|
let nonce = Nonce::from_slice(&[0u8; 12]);
|
||||||
|
let plaintext = auth_aead.decrypt(nonce, session_id.as_ref()).ok()?;
|
||||||
|
|
||||||
|
if plaintext.len() != 16 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sid = [0u8; 8];
|
||||||
|
sid.copy_from_slice(&plaintext[0..8]);
|
||||||
|
let mut ts_bytes = [0u8; 8];
|
||||||
|
ts_bytes.copy_from_slice(&plaintext[8..16]);
|
||||||
|
let ts = u64::from_be_bytes(ts_bytes);
|
||||||
|
|
||||||
|
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
|
||||||
|
// Allow up to 60 seconds of clock drift
|
||||||
|
if ts > now + 60 || ts < now.saturating_sub(60) {
|
||||||
|
return None; // Replay protection / stale connection
|
||||||
|
}
|
||||||
|
|
||||||
|
Some((sid, ts))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a fake TLS 1.3 ClientHello matching Chrome's fingerprint
|
||||||
|
pub fn build_client_hello(sni: &str, session_id: &[u8; 32], c_pub: &PublicKey) -> Bytes {
|
||||||
|
let mut ext = BytesMut::new();
|
||||||
|
|
||||||
|
// SNI Extension
|
||||||
|
let sni_bytes = sni.as_bytes();
|
||||||
|
ext.put_u16(0x0000); // Type: server_name
|
||||||
|
ext.put_u16((sni_bytes.len() + 5) as u16);
|
||||||
|
ext.put_u16((sni_bytes.len() + 3) as u16); // Server Name list length
|
||||||
|
ext.put_u8(0x00); // Name Type: host_name
|
||||||
|
ext.put_u16(sni_bytes.len() as u16);
|
||||||
|
ext.put_slice(sni_bytes);
|
||||||
|
|
||||||
|
// Supported Groups
|
||||||
|
ext.put_u16(0x000a); // Type
|
||||||
|
ext.put_u16(8); // Length
|
||||||
|
ext.put_u16(6); // List length
|
||||||
|
ext.put_u16(0x001d); // x25519
|
||||||
|
ext.put_u16(0x0017); // secp256r1
|
||||||
|
ext.put_u16(0x0018); // secp384r1
|
||||||
|
|
||||||
|
// Key Share
|
||||||
|
let pub_bytes = c_pub.as_bytes();
|
||||||
|
ext.put_u16(0x0033); // Type
|
||||||
|
ext.put_u16((pub_bytes.len() + 6) as u16); // Length
|
||||||
|
ext.put_u16((pub_bytes.len() + 4) as u16); // ClientShares length
|
||||||
|
ext.put_u16(0x001d); // Group: x25519
|
||||||
|
ext.put_u16(pub_bytes.len() as u16);
|
||||||
|
ext.put_slice(pub_bytes);
|
||||||
|
|
||||||
|
// Supported Versions
|
||||||
|
ext.put_u16(0x002b); // Type
|
||||||
|
ext.put_u16(5); // Length
|
||||||
|
ext.put_u8(4); // List length
|
||||||
|
ext.put_u16(0x0304); // TLS 1.3
|
||||||
|
ext.put_u16(0x0303); // TLS 1.2
|
||||||
|
|
||||||
|
// ALPN
|
||||||
|
let alpn = b"\x02h2\x08http/1.1";
|
||||||
|
ext.put_u16(0x0010); // Type
|
||||||
|
ext.put_u16((alpn.len() + 2) as u16);
|
||||||
|
ext.put_u16(alpn.len() as u16);
|
||||||
|
ext.put_slice(alpn);
|
||||||
|
|
||||||
|
// Signature Algorithms
|
||||||
|
ext.put_u16(0x000d); // Type
|
||||||
|
ext.put_u16(10); // Length
|
||||||
|
ext.put_u16(8); // List length
|
||||||
|
ext.put_u16(0x0403); // ecdsa_secp256r1_sha256
|
||||||
|
ext.put_u16(0x0804); // rsa_pss_rsae_sha256
|
||||||
|
ext.put_u16(0x0401); // rsa_pkcs1_sha256
|
||||||
|
ext.put_u16(0x0503); // ecdsa_secp384r1_sha384
|
||||||
|
|
||||||
|
let mut handshake = BytesMut::new();
|
||||||
|
handshake.put_u16(0x0303); // Client Version
|
||||||
|
let mut random = [0u8; 32];
|
||||||
|
OsRng.fill_bytes(&mut random);
|
||||||
|
handshake.put_slice(&random); // Random
|
||||||
|
|
||||||
|
handshake.put_u8(32); // Session ID length
|
||||||
|
handshake.put_slice(session_id); // Session ID
|
||||||
|
|
||||||
|
// Cipher Suites
|
||||||
|
handshake.put_u16(6); // Length
|
||||||
|
handshake.put_u16(0x1301); // TLS_AES_128_GCM_SHA256
|
||||||
|
handshake.put_u16(0x1303); // TLS_CHACHA20_POLY1305_SHA256
|
||||||
|
handshake.put_u16(0x1302); // TLS_AES_256_GCM_SHA384
|
||||||
|
|
||||||
|
// Compression
|
||||||
|
handshake.put_u8(1); // Length
|
||||||
|
handshake.put_u8(0); // null
|
||||||
|
|
||||||
|
// Extensions
|
||||||
|
handshake.put_u16(ext.len() as u16);
|
||||||
|
handshake.put_slice(&ext);
|
||||||
|
|
||||||
|
let handshake_len = handshake.len();
|
||||||
|
|
||||||
|
let mut record = BytesMut::new();
|
||||||
|
record.put_u8(0x16); // Handshake
|
||||||
|
record.put_u16(0x0301); // TLS 1.0 (Compatibility)
|
||||||
|
record.put_u16((handshake_len + HANDSHAKE_HEADER_LEN) as u16); // Length
|
||||||
|
|
||||||
|
record.put_u8(0x01); // ClientHello
|
||||||
|
record.put_u8((handshake_len >> 16) as u8);
|
||||||
|
record.put_u8((handshake_len >> 8) as u8);
|
||||||
|
record.put_u8(handshake_len as u8);
|
||||||
|
record.put_slice(&handshake);
|
||||||
|
|
||||||
|
// Append ChangeCipherSpec for TLS 1.3 middlebox compatibility (RFC 8446 §D.4)
|
||||||
|
// This makes the flow look like: ClientHello → ServerHello → CCS → AppData
|
||||||
|
// instead of the DPI-suspicious: ClientHello → AppData directly.
|
||||||
|
let mut out = BytesMut::new();
|
||||||
|
out.put_slice(&record);
|
||||||
|
out.put_slice(&[0x14, 0x03, 0x03, 0x00, 0x01, 0x01]);
|
||||||
|
out.freeze()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ParsedClientHello {
|
||||||
|
pub sni: String,
|
||||||
|
pub session_id: [u8; 32],
|
||||||
|
pub c_pub: PublicKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a TLS ClientHello. Returns None if invalid or missing required fields.
|
||||||
|
pub fn parse_client_hello(mut buf: &[u8]) -> Option<ParsedClientHello> {
|
||||||
|
if buf.len() < RECORD_HEADER_LEN + HANDSHAKE_HEADER_LEN {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record Header
|
||||||
|
let typ = buf.get_u8();
|
||||||
|
if typ != 0x16 { return None; } // Not a handshake
|
||||||
|
let _version = buf.get_u16();
|
||||||
|
let record_len = buf.get_u16() as usize;
|
||||||
|
|
||||||
|
if buf.len() < record_len {
|
||||||
|
return None; // Incomplete record
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut payload = &buf[..record_len];
|
||||||
|
|
||||||
|
// Handshake Header
|
||||||
|
let hs_type = payload.get_u8();
|
||||||
|
if hs_type != 0x01 { return None; } // Not ClientHello
|
||||||
|
let hs_len_hi = payload.get_u8() as usize;
|
||||||
|
let hs_len_mid = payload.get_u8() as usize;
|
||||||
|
let hs_len_lo = payload.get_u8() as usize;
|
||||||
|
let hs_len = (hs_len_hi << 16) | (hs_len_mid << 8) | hs_len_lo;
|
||||||
|
|
||||||
|
if payload.len() < hs_len { return None; }
|
||||||
|
|
||||||
|
let mut ch = &payload[..hs_len];
|
||||||
|
let _client_version = ch.get_u16();
|
||||||
|
if ch.len() < 32 { return None; }
|
||||||
|
ch.advance(32); // Skip Random
|
||||||
|
|
||||||
|
let sid_len = ch.get_u8() as usize;
|
||||||
|
if sid_len != 32 || ch.len() < 32 { return None; }
|
||||||
|
|
||||||
|
let mut session_id = [0u8; 32];
|
||||||
|
session_id.copy_from_slice(&ch[..32]);
|
||||||
|
ch.advance(32);
|
||||||
|
|
||||||
|
let ciphers_len = ch.get_u16() as usize;
|
||||||
|
if ch.len() < ciphers_len { return None; }
|
||||||
|
ch.advance(ciphers_len);
|
||||||
|
|
||||||
|
let comp_len = ch.get_u8() as usize;
|
||||||
|
if ch.len() < comp_len { return None; }
|
||||||
|
ch.advance(comp_len);
|
||||||
|
|
||||||
|
let ext_len = ch.get_u16() as usize;
|
||||||
|
if ch.len() < ext_len { return None; }
|
||||||
|
|
||||||
|
let mut exts = &ch[..ext_len];
|
||||||
|
|
||||||
|
let mut parsed_sni = None;
|
||||||
|
let mut parsed_c_pub = None;
|
||||||
|
|
||||||
|
while exts.len() >= 4 {
|
||||||
|
let ext_type = exts.get_u16();
|
||||||
|
let ext_len = exts.get_u16() as usize;
|
||||||
|
if exts.len() < ext_len { break; }
|
||||||
|
|
||||||
|
let mut ext_data = &exts[..ext_len];
|
||||||
|
|
||||||
|
if ext_type == 0x0000 { // SNI
|
||||||
|
let _list_len = ext_data.get_u16() as usize;
|
||||||
|
if ext_data.len() >= 3 {
|
||||||
|
let name_type = ext_data.get_u8();
|
||||||
|
if name_type == 0x00 { // Hostname
|
||||||
|
let name_len = ext_data.get_u16() as usize;
|
||||||
|
if ext_data.len() >= name_len {
|
||||||
|
if let Ok(name) = std::str::from_utf8(&ext_data[..name_len]) {
|
||||||
|
parsed_sni = Some(name.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if ext_type == 0x0033 { // Key Share
|
||||||
|
let _client_shares_len = ext_data.get_u16() as usize;
|
||||||
|
while ext_data.len() >= 4 {
|
||||||
|
let group = ext_data.get_u16();
|
||||||
|
let key_ex_len = ext_data.get_u16() as usize;
|
||||||
|
if ext_data.len() < key_ex_len { break; }
|
||||||
|
|
||||||
|
if group == 0x001d && key_ex_len == 32 { // X25519
|
||||||
|
let mut pub_bytes = [0u8; 32];
|
||||||
|
pub_bytes.copy_from_slice(&ext_data[..32]);
|
||||||
|
parsed_c_pub = Some(PublicKey::from(pub_bytes));
|
||||||
|
}
|
||||||
|
ext_data.advance(key_ex_len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
exts.advance(ext_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
match (parsed_sni, parsed_c_pub) {
|
||||||
|
(Some(sni), Some(c_pub)) => Some(ParsedClientHello { sni, session_id, c_pub }),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,413 @@
|
||||||
|
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
|
||||||
|
use std::io::{Cursor, Read};
|
||||||
|
|
||||||
|
const BASE32_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567";
|
||||||
|
|
||||||
|
/// Encodes a byte slice into Base32 (RFC 4648) without padding, lowercase.
|
||||||
|
pub fn base32_encode(data: &[u8]) -> String {
|
||||||
|
let mut result = String::with_capacity((data.len() * 8 + 4) / 5);
|
||||||
|
let mut buffer = 0u32;
|
||||||
|
let mut bits_left = 0;
|
||||||
|
|
||||||
|
for &b in data {
|
||||||
|
buffer = (buffer << 8) | (b as u32);
|
||||||
|
bits_left += 8;
|
||||||
|
while bits_left >= 5 {
|
||||||
|
bits_left -= 5;
|
||||||
|
let index = ((buffer >> bits_left) & 0x1F) as usize;
|
||||||
|
result.push(BASE32_ALPHABET[index] as char);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if bits_left > 0 {
|
||||||
|
let index = ((buffer << (5 - bits_left)) & 0x1F) as usize;
|
||||||
|
result.push(BASE32_ALPHABET[index] as char);
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a Base32 string (case-insensitive, no padding) into a byte vector.
|
||||||
|
pub fn base32_decode(encoded: &str) -> Option<Vec<u8>> {
|
||||||
|
let mut result = Vec::with_capacity(encoded.len() * 5 / 8);
|
||||||
|
let mut buffer = 0u32;
|
||||||
|
let mut bits_left = 0;
|
||||||
|
|
||||||
|
for c in encoded.bytes() {
|
||||||
|
let val = match c {
|
||||||
|
b'a'..=b'z' => c - b'a',
|
||||||
|
b'A'..=b'Z' => c - b'A',
|
||||||
|
b'2'..=b'7' => c - b'2' + 26,
|
||||||
|
_ => return None, // Invalid character
|
||||||
|
};
|
||||||
|
|
||||||
|
buffer = (buffer << 5) | (val as u32);
|
||||||
|
bits_left += 5;
|
||||||
|
|
||||||
|
if bits_left >= 8 {
|
||||||
|
bits_left -= 8;
|
||||||
|
result.push((buffer >> bits_left) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum DnsRecordType {
|
||||||
|
A,
|
||||||
|
CNAME,
|
||||||
|
NULL,
|
||||||
|
TXT,
|
||||||
|
AAAA,
|
||||||
|
Unknown(u16),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<u16> for DnsRecordType {
|
||||||
|
fn from(val: u16) -> Self {
|
||||||
|
match val {
|
||||||
|
1 => DnsRecordType::A,
|
||||||
|
5 => DnsRecordType::CNAME,
|
||||||
|
10 => DnsRecordType::NULL,
|
||||||
|
16 => DnsRecordType::TXT,
|
||||||
|
28 => DnsRecordType::AAAA,
|
||||||
|
_ => DnsRecordType::Unknown(val),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DnsRecordType {
|
||||||
|
pub fn as_u16(&self) -> u16 {
|
||||||
|
match self {
|
||||||
|
DnsRecordType::A => 1,
|
||||||
|
DnsRecordType::CNAME => 5,
|
||||||
|
DnsRecordType::NULL => 10,
|
||||||
|
DnsRecordType::TXT => 16,
|
||||||
|
DnsRecordType::AAAA => 28,
|
||||||
|
DnsRecordType::Unknown(v) => *v,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DnsQuestion {
|
||||||
|
pub name: String,
|
||||||
|
pub qtype: DnsRecordType,
|
||||||
|
pub qclass: u16, // Usually 1 (IN)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DnsAnswer {
|
||||||
|
pub name: String,
|
||||||
|
pub rtype: DnsRecordType,
|
||||||
|
pub rclass: u16,
|
||||||
|
pub ttl: u32,
|
||||||
|
pub rdata: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DnsPacket {
|
||||||
|
pub id: u16,
|
||||||
|
pub flags: u16,
|
||||||
|
pub questions: Vec<DnsQuestion>,
|
||||||
|
pub answers: Vec<DnsAnswer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DnsPacket {
|
||||||
|
pub fn new_query(id: u16, name: &str, qtype: DnsRecordType) -> Self {
|
||||||
|
DnsPacket {
|
||||||
|
id,
|
||||||
|
flags: 0x0100, // Standard query, recursion desired
|
||||||
|
questions: vec![DnsQuestion {
|
||||||
|
name: name.to_string(),
|
||||||
|
qtype,
|
||||||
|
qclass: 1, // IN
|
||||||
|
}],
|
||||||
|
answers: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_response(id: u16, name: &str, rtype: DnsRecordType, rdata: Vec<u8>) -> Self {
|
||||||
|
DnsPacket {
|
||||||
|
id,
|
||||||
|
flags: 0x8180, // Response, standard query, recursion desired, recursion available
|
||||||
|
questions: vec![DnsQuestion {
|
||||||
|
name: name.to_string(),
|
||||||
|
qtype: rtype.clone(),
|
||||||
|
qclass: 1, // IN
|
||||||
|
}],
|
||||||
|
answers: vec![DnsAnswer {
|
||||||
|
name: name.to_string(),
|
||||||
|
rtype,
|
||||||
|
rclass: 1,
|
||||||
|
ttl: 0, // No caching
|
||||||
|
rdata,
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode(&self) -> Vec<u8> {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
let _ = buf.write_u16::<BigEndian>(self.id);
|
||||||
|
let _ = buf.write_u16::<BigEndian>(self.flags);
|
||||||
|
let _ = buf.write_u16::<BigEndian>(self.questions.len() as u16);
|
||||||
|
let _ = buf.write_u16::<BigEndian>(self.answers.len() as u16);
|
||||||
|
let _ = buf.write_u16::<BigEndian>(0); // Authority PR
|
||||||
|
let _ = buf.write_u16::<BigEndian>(0); // Additional PR
|
||||||
|
|
||||||
|
for q in &self.questions {
|
||||||
|
encode_domain_name(&mut buf, &q.name);
|
||||||
|
let _ = buf.write_u16::<BigEndian>(q.qtype.as_u16());
|
||||||
|
let _ = buf.write_u16::<BigEndian>(q.qclass);
|
||||||
|
}
|
||||||
|
|
||||||
|
for a in &self.answers {
|
||||||
|
encode_domain_name(&mut buf, &a.name);
|
||||||
|
let _ = buf.write_u16::<BigEndian>(a.rtype.as_u16());
|
||||||
|
let _ = buf.write_u16::<BigEndian>(a.rclass);
|
||||||
|
let _ = buf.write_u32::<BigEndian>(a.ttl);
|
||||||
|
|
||||||
|
if a.rtype == DnsRecordType::TXT {
|
||||||
|
// TXT records have character-strings length-prefixed
|
||||||
|
// We split into chunks of up to 255 bytes
|
||||||
|
let mut txt_data = Vec::new();
|
||||||
|
for chunk in a.rdata.chunks(255) {
|
||||||
|
txt_data.push(chunk.len() as u8);
|
||||||
|
txt_data.extend_from_slice(chunk);
|
||||||
|
}
|
||||||
|
let _ = buf.write_u16::<BigEndian>(txt_data.len() as u16);
|
||||||
|
buf.extend_from_slice(&txt_data);
|
||||||
|
} else {
|
||||||
|
let _ = buf.write_u16::<BigEndian>(a.rdata.len() as u16);
|
||||||
|
buf.extend_from_slice(&a.rdata);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buf
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decode(data: &[u8]) -> Option<Self> {
|
||||||
|
if data.len() < 12 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut cursor = Cursor::new(data);
|
||||||
|
let id = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
let flags = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
let qdcount = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
let ancount = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
let _nscount = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
let _arcount = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
|
||||||
|
let mut questions = Vec::new();
|
||||||
|
for _ in 0..qdcount {
|
||||||
|
let name = decode_domain_name(&mut cursor, data)?;
|
||||||
|
let qtype = cursor.read_u16::<BigEndian>().ok()?.into();
|
||||||
|
let qclass = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
questions.push(DnsQuestion { name, qtype, qclass });
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut answers = Vec::new();
|
||||||
|
for _ in 0..ancount {
|
||||||
|
let name = decode_domain_name(&mut cursor, data)?;
|
||||||
|
let rtype: DnsRecordType = cursor.read_u16::<BigEndian>().ok()?.into();
|
||||||
|
let rclass = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
let ttl = cursor.read_u32::<BigEndian>().ok()?;
|
||||||
|
let rdlength = cursor.read_u16::<BigEndian>().ok()?;
|
||||||
|
|
||||||
|
let mut rdata = vec![0u8; rdlength as usize];
|
||||||
|
cursor.read_exact(&mut rdata).ok()?;
|
||||||
|
|
||||||
|
if rtype == DnsRecordType::TXT {
|
||||||
|
// Decode TXT string chunks
|
||||||
|
let mut decoded_txt = Vec::new();
|
||||||
|
let mut txt_cursor = Cursor::new(&rdata);
|
||||||
|
while txt_cursor.position() < rdata.len() as u64 {
|
||||||
|
if let Ok(len) = txt_cursor.read_u8() {
|
||||||
|
let mut chunk = vec![0u8; len as usize];
|
||||||
|
if txt_cursor.read_exact(&mut chunk).is_ok() {
|
||||||
|
decoded_txt.extend_from_slice(&chunk);
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rdata = decoded_txt;
|
||||||
|
}
|
||||||
|
|
||||||
|
answers.push(DnsAnswer {
|
||||||
|
name,
|
||||||
|
rtype,
|
||||||
|
rclass,
|
||||||
|
ttl,
|
||||||
|
rdata,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip authority and additional sections (not needed for basic payload extraction)
|
||||||
|
|
||||||
|
Some(DnsPacket {
|
||||||
|
id,
|
||||||
|
flags,
|
||||||
|
questions,
|
||||||
|
answers,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode_domain_name(buf: &mut Vec<u8>, name: &str) {
|
||||||
|
for part in name.split('.') {
|
||||||
|
if part.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let len = part.len().min(63) as u8;
|
||||||
|
buf.push(len);
|
||||||
|
buf.extend_from_slice(&part.as_bytes()[..len as usize]);
|
||||||
|
}
|
||||||
|
buf.push(0); // Root label
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_domain_name(cursor: &mut Cursor<&[u8]>, full_data: &[u8]) -> Option<String> {
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
let mut jumps = 0;
|
||||||
|
let mut current_pos = cursor.position();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if jumps > 100 {
|
||||||
|
return None; // Prevent infinite loops
|
||||||
|
}
|
||||||
|
|
||||||
|
if current_pos >= full_data.len() as u64 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let len = full_data[current_pos as usize];
|
||||||
|
if len == 0 {
|
||||||
|
if jumps == 0 {
|
||||||
|
cursor.set_position(current_pos + 1);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if len & 0xC0 == 0xC0 {
|
||||||
|
// Pointer
|
||||||
|
if current_pos + 1 >= full_data.len() as u64 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let pointer = (((len & 0x3F) as u16) << 8) | (full_data[current_pos as usize + 1] as u16);
|
||||||
|
if jumps == 0 {
|
||||||
|
cursor.set_position(current_pos + 2);
|
||||||
|
}
|
||||||
|
jumps += 1;
|
||||||
|
current_pos = pointer as u64;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
current_pos += 1;
|
||||||
|
if current_pos + len as u64 > full_data.len() as u64 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let part = &full_data[current_pos as usize..(current_pos + len as u64) as usize];
|
||||||
|
parts.push(String::from_utf8_lossy(part).into_owned());
|
||||||
|
current_pos += len as u64;
|
||||||
|
|
||||||
|
if jumps == 0 {
|
||||||
|
cursor.set_position(current_pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if parts.is_empty() {
|
||||||
|
Some(".".to_string())
|
||||||
|
} else {
|
||||||
|
Some(parts.join("."))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a payload into a list of subdomain labels and appends the base domain.
|
||||||
|
/// Each label is max 63 chars. The base32 string is chunked.
|
||||||
|
pub fn encode_payload_to_domain(payload: &[u8], base_domain: &str) -> String {
|
||||||
|
let encoded = base32_encode(payload);
|
||||||
|
let mut domain = String::new();
|
||||||
|
|
||||||
|
let mut start = 0;
|
||||||
|
while start < encoded.len() {
|
||||||
|
let end = (start + 63).min(encoded.len());
|
||||||
|
domain.push_str(&encoded[start..end]);
|
||||||
|
domain.push('.');
|
||||||
|
start = end;
|
||||||
|
}
|
||||||
|
|
||||||
|
domain.push_str(base_domain);
|
||||||
|
domain
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a payload from a subdomain string, ignoring the base domain.
|
||||||
|
pub fn decode_domain_to_payload(full_domain: &str, base_domain: &str) -> Option<Vec<u8>> {
|
||||||
|
// Strip base domain and trailing dots
|
||||||
|
let stripped = full_domain
|
||||||
|
.trim_end_matches('.')
|
||||||
|
.strip_suffix(base_domain)?;
|
||||||
|
|
||||||
|
let stripped = stripped.trim_end_matches('.');
|
||||||
|
|
||||||
|
let mut base32_str = String::with_capacity(stripped.len());
|
||||||
|
for part in stripped.split('.') {
|
||||||
|
base32_str.push_str(part);
|
||||||
|
}
|
||||||
|
|
||||||
|
base32_decode(&base32_str)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_base32() {
|
||||||
|
let data = b"Hello, OSTP DNS Tunnel!";
|
||||||
|
let encoded = base32_encode(data);
|
||||||
|
let decoded = base32_decode(&encoded).unwrap();
|
||||||
|
assert_eq!(data.as_ref(), decoded.as_slice());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_domain_encoding() {
|
||||||
|
let payload = vec![0x12; 20];
|
||||||
|
let base_domain = "tunnel.example.com";
|
||||||
|
let domain = encode_payload_to_domain(&payload, base_domain);
|
||||||
|
|
||||||
|
// Ensure no label is > 63 chars
|
||||||
|
for part in domain.split('.') {
|
||||||
|
assert!(part.len() <= 63);
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(domain.ends_with(base_domain));
|
||||||
|
|
||||||
|
let decoded = decode_domain_to_payload(&domain, base_domain).unwrap();
|
||||||
|
assert_eq!(payload, decoded);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_dns_packet() {
|
||||||
|
let payload = vec![1, 2, 3, 4, 5];
|
||||||
|
let domain = encode_payload_to_domain(&payload, "t.com");
|
||||||
|
|
||||||
|
let query = DnsPacket::new_query(1234, &domain, DnsRecordType::TXT);
|
||||||
|
let encoded_query = query.encode();
|
||||||
|
|
||||||
|
let decoded_query = DnsPacket::decode(&encoded_query).unwrap();
|
||||||
|
assert_eq!(decoded_query.id, 1234);
|
||||||
|
assert_eq!(decoded_query.questions[0].name, domain);
|
||||||
|
assert_eq!(decoded_query.questions[0].qtype, DnsRecordType::TXT);
|
||||||
|
|
||||||
|
let response_data = vec![5, 4, 3, 2, 1];
|
||||||
|
let response = DnsPacket::new_response(1234, &domain, DnsRecordType::TXT, response_data.clone());
|
||||||
|
let encoded_resp = response.encode();
|
||||||
|
|
||||||
|
let decoded_resp = DnsPacket::decode(&encoded_resp).unwrap();
|
||||||
|
assert_eq!(decoded_resp.answers[0].rdata, response_data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,94 @@
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::time::Instant;
|
||||||
|
use crate::dns::{DnsPacket, DnsRecordType, encode_payload_to_domain};
|
||||||
|
use rand::Rng;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
pub struct DnsProbeResult {
|
||||||
|
pub name: String,
|
||||||
|
pub ip: String,
|
||||||
|
pub latency_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const PUBLIC_DNS_SERVERS: &[(&str, &str)] = &[
|
||||||
|
("Cloudflare", "1.1.1.1"),
|
||||||
|
("Cloudflare2", "1.0.0.1"),
|
||||||
|
("Google", "8.8.8.8"),
|
||||||
|
("Google2", "8.8.4.4"),
|
||||||
|
("Quad9", "9.9.9.9"),
|
||||||
|
("AdGuard", "94.140.14.14"),
|
||||||
|
("Yandex", "77.88.8.8"),
|
||||||
|
("Yandex2", "77.88.8.1"),
|
||||||
|
("SkyDNS", "193.58.251.251"),
|
||||||
|
("AliDNS", "223.5.5.5"),
|
||||||
|
("Tencent", "119.29.29.29"),
|
||||||
|
("114DNS", "114.114.114.114"),
|
||||||
|
("Shecan", "178.22.122.100"),
|
||||||
|
("Electro", "78.157.42.100"),
|
||||||
|
("Begzar", "185.55.226.26"),
|
||||||
|
];
|
||||||
|
|
||||||
|
async fn probe_resolver(domain: &str, resolver_ip: &str) -> Option<u64> {
|
||||||
|
let (probe_bytes, id) = {
|
||||||
|
let mut rng = rand::thread_rng();
|
||||||
|
let probe_bytes: [u8; 4] = rng.gen();
|
||||||
|
let id: u16 = rng.gen();
|
||||||
|
(probe_bytes, id)
|
||||||
|
};
|
||||||
|
|
||||||
|
let fqdn = encode_payload_to_domain(&probe_bytes, domain);
|
||||||
|
let qtype = if rand::thread_rng().gen_bool(0.5) { DnsRecordType::TXT } else { DnsRecordType::NULL };
|
||||||
|
let packet = DnsPacket::new_query(id, &fqdn, qtype);
|
||||||
|
let encoded = packet.encode();
|
||||||
|
|
||||||
|
let sock = tokio::net::UdpSocket::bind("0.0.0.0:0").await.ok()?;
|
||||||
|
sock.connect(format!("{}:53", resolver_ip)).await.ok()?;
|
||||||
|
|
||||||
|
let start = Instant::now();
|
||||||
|
sock.send(&encoded).await.ok()?;
|
||||||
|
|
||||||
|
let mut buf = [0u8; 4096];
|
||||||
|
match tokio::time::timeout(Duration::from_secs(2), sock.recv(&mut buf)).await {
|
||||||
|
Ok(Ok(n)) => {
|
||||||
|
if let Some(resp) = DnsPacket::decode(&buf[..n]) {
|
||||||
|
// Check if RCODE == 0 (NOERROR) and it has answers
|
||||||
|
let rcode = resp.flags & 0x000F;
|
||||||
|
if rcode == 0 && !resp.answers.is_empty() {
|
||||||
|
return Some(start.elapsed().as_millis() as u64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
},
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run_dns_prober(domain: &str) -> Result<Vec<DnsProbeResult>, String> {
|
||||||
|
if domain.is_empty() {
|
||||||
|
return Err("Please enter the tunnel domain first (e.g. tunnel.myvpn.com)".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let tasks: Vec<_> = PUBLIC_DNS_SERVERS
|
||||||
|
.iter()
|
||||||
|
.map(|(name, ip)| {
|
||||||
|
let domain = domain.to_string();
|
||||||
|
let name = name.to_string();
|
||||||
|
let ip = ip.to_string();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let latency_ms = probe_resolver(&domain, &ip).await;
|
||||||
|
DnsProbeResult { name, ip, latency_ms }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut results = Vec::with_capacity(tasks.len());
|
||||||
|
for task in tasks {
|
||||||
|
if let Ok(r) = task.await {
|
||||||
|
results.push(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
results.sort_by_key(|r| r.latency_ms.unwrap_or(u64::MAX));
|
||||||
|
Ok(results)
|
||||||
|
}
|
||||||