Compare commits
58
Commits
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
# Windows: link the C runtime statically, so the agent and the tray start on a
|
||||||
|
# machine that has no Visual C++ redistributable installed. The installer ships
|
||||||
|
# nothing but our own files and Wintun.
|
||||||
|
[target.x86_64-pc-windows-msvc]
|
||||||
|
rustflags = ["-C", "target-feature=+crt-static"]
|
||||||
+146
-11
@@ -33,11 +33,28 @@ jobs:
|
|||||||
asset: tsunagi-linux-x86_64
|
asset: tsunagi-linux-x86_64
|
||||||
archive: tar.gz
|
archive: tar.gz
|
||||||
zig: true
|
zig: true
|
||||||
|
deb: true
|
||||||
|
deb_arch: amd64
|
||||||
|
pkg_arch: x86_64
|
||||||
|
gnu_target: x86_64-unknown-linux-gnu
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-latest
|
||||||
target: aarch64-unknown-linux-musl
|
target: aarch64-unknown-linux-musl
|
||||||
asset: tsunagi-linux-aarch64
|
asset: tsunagi-linux-aarch64
|
||||||
archive: tar.gz
|
archive: tar.gz
|
||||||
zig: true
|
zig: true
|
||||||
|
deb: true
|
||||||
|
deb_arch: arm64
|
||||||
|
pkg_arch: aarch64
|
||||||
|
# 32-bit ARM with hardware float (ARMv7, `v7l`): single-board and edge
|
||||||
|
# devices. Statically linked like the others.
|
||||||
|
- os: ubuntu-latest
|
||||||
|
target: armv7-unknown-linux-musleabihf
|
||||||
|
asset: tsunagi-linux-armv7
|
||||||
|
archive: tar.gz
|
||||||
|
zig: true
|
||||||
|
deb: true
|
||||||
|
deb_arch: armhf
|
||||||
|
pkg_arch: armv7h
|
||||||
- os: macos-latest
|
- os: macos-latest
|
||||||
target: aarch64-apple-darwin
|
target: aarch64-apple-darwin
|
||||||
asset: tsunagi-macos-aarch64
|
asset: tsunagi-macos-aarch64
|
||||||
@@ -63,9 +80,9 @@ jobs:
|
|||||||
# aws-lc-sys (iroh's rustls backend) and the bundled sqlite are C, and the
|
# aws-lc-sys (iroh's rustls backend) and the bundled sqlite are C, and the
|
||||||
# musl targets have no prebuilt bindings, so bindgen needs libclang and the
|
# musl targets have no prebuilt bindings, so bindgen needs libclang and the
|
||||||
# C build needs cmake. zig is the cross C compiler cargo-zigbuild drives.
|
# C build needs cmake. zig is the cross C compiler cargo-zigbuild drives.
|
||||||
- name: Install musl build tooling
|
- name: Install musl build and packaging tooling
|
||||||
if: matrix.zig
|
if: matrix.zig
|
||||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends cmake clang libclang-dev
|
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends cmake clang libclang-dev libarchive-tools zstd
|
||||||
- name: Install zig
|
- name: Install zig
|
||||||
if: matrix.zig
|
if: matrix.zig
|
||||||
uses: mlugg/setup-zig@v2
|
uses: mlugg/setup-zig@v2
|
||||||
@@ -91,9 +108,33 @@ jobs:
|
|||||||
# one lint to keep the musl build log clean. A real link error still
|
# one lint to keep the musl build log clean. A real link error still
|
||||||
# fails the build.
|
# fails the build.
|
||||||
export RUSTFLAGS="${RUSTFLAGS:-} -A linker_messages"
|
export RUSTFLAGS="${RUSTFLAGS:-} -A linker_messages"
|
||||||
cargo zigbuild --release --locked --target "${{ matrix.target }}" --bin tsunagi
|
cargo zigbuild --release --locked --target "${{ matrix.target }}" --bin tsng
|
||||||
else
|
else
|
||||||
cargo build --release --locked --target "${{ matrix.target }}" --bin tsunagi
|
cargo build --release --locked --target "${{ matrix.target }}" --bin tsng
|
||||||
|
fi
|
||||||
|
|
||||||
|
# The tray GUI. On Linux it is built against glibc (an old baseline for
|
||||||
|
# portability), not musl: a GUI must dlopen libGL/X11/Wayland at runtime,
|
||||||
|
# which a static musl binary cannot. macOS and Windows build it natively.
|
||||||
|
- name: Build the tray GUI
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [[ "${{ runner.os }}" == "Linux" ]]; then
|
||||||
|
if [[ -n "${{ matrix.gnu_target }}" ]]; then
|
||||||
|
# tray-icon links GTK and libappindicator through pkg-config, which
|
||||||
|
# has no cross story under zig, so the Linux GUI is built natively
|
||||||
|
# (x86_64 only) against the runner's glibc.
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y --no-install-recommends \
|
||||||
|
libgtk-3-dev libayatana-appindicator3-dev
|
||||||
|
cargo build --release --locked \
|
||||||
|
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
|
||||||
|
else
|
||||||
|
echo "no GUI build for ${{ matrix.target }}"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
cargo build --release --locked --target "${{ matrix.target }}" --bin tsunagi-tray
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Package
|
- name: Package
|
||||||
@@ -105,21 +146,37 @@ jobs:
|
|||||||
stage="dist/pkg/${{ matrix.asset }}"
|
stage="dist/pkg/${{ matrix.asset }}"
|
||||||
mkdir -p "$stage"
|
mkdir -p "$stage"
|
||||||
|
|
||||||
bin="tsunagi"
|
bin="tsng"
|
||||||
[[ "${{ runner.os }}" == "Windows" ]] && bin="tsunagi.exe"
|
[[ "${{ runner.os }}" == "Windows" ]] && bin="tsng.exe"
|
||||||
cp "target/${{ matrix.target }}/release/${bin}" "$stage/"
|
cp "target/${{ matrix.target }}/release/${bin}" "$stage/"
|
||||||
|
|
||||||
|
# The tray GUI alongside it, where it was built (Linux: x86_64 only).
|
||||||
|
tray="tsunagi-tray"
|
||||||
|
[[ "${{ runner.os }}" == "Windows" ]] && tray="tsunagi-tray.exe"
|
||||||
|
if [[ "${{ runner.os }}" == "Linux" ]]; then
|
||||||
|
if [[ -n "${{ matrix.gnu_target }}" ]]; then
|
||||||
|
cp "target/${{ matrix.gnu_target }}/release/${tray}" "$stage/"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
cp "target/${{ matrix.target }}/release/${tray}" "$stage/"
|
||||||
|
fi
|
||||||
|
|
||||||
# The top-level README, plus the per-OS install notes and integration
|
# The top-level README, plus the per-OS install notes and integration
|
||||||
# files, so the archive carries what the platform needs to set up.
|
# files, so the archive carries what the platform needs to set up.
|
||||||
cp README.md "$stage/"
|
cp README.md "$stage/"
|
||||||
case "${{ runner.os }}" in
|
case "${{ runner.os }}" in
|
||||||
Linux)
|
Linux)
|
||||||
cp dist/linux/tsunagi.service dist/linux/install.sh "$stage/"
|
cp dist/linux/tsunagi.service dist/linux/install.sh \
|
||||||
|
dist/linux/50-tsunagi-resolved.rules "$stage/"
|
||||||
cp dist/linux/README.md "$stage/INSTALL.md"
|
cp dist/linux/README.md "$stage/INSTALL.md"
|
||||||
;;
|
;;
|
||||||
macOS)
|
macOS)
|
||||||
cp dist/macos/cy.hexor.tsunagi.plist "$stage/"
|
cp dist/macos/cy.hexor.tsunagi.plist "$stage/"
|
||||||
cp dist/macos/README.md "$stage/INSTALL.md"
|
cp dist/macos/README.md "$stage/INSTALL.md"
|
||||||
|
# The tray as an application bundle, for the Homebrew cask.
|
||||||
|
bash dist/macos/build-app.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsunagi-tray" \
|
||||||
|
"$version" "$stage/Tsunagi.app"
|
||||||
;;
|
;;
|
||||||
Windows)
|
Windows)
|
||||||
cp dist/windows/README.md "$stage/INSTALL.md"
|
cp dist/windows/README.md "$stage/INSTALL.md"
|
||||||
@@ -133,13 +190,91 @@ jobs:
|
|||||||
tar -C dist/pkg -czf "${archive}" "${{ matrix.asset }}"
|
tar -C dist/pkg -czf "${archive}" "${{ matrix.asset }}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# The Windows installer: the agent as a service, Wintun, the tray and the
|
||||||
|
# PATH entry in one setup program. Wintun is the signed library from
|
||||||
|
# wintun.net, pinned by hash so a changed download fails the build.
|
||||||
|
- name: Build the Windows installer
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$version = $env:GITHUB_REF_NAME.TrimStart('v')
|
||||||
|
Invoke-WebRequest -Uri https://www.wintun.net/builds/wintun-0.14.1.zip -OutFile wintun.zip
|
||||||
|
$hash = (Get-FileHash wintun.zip -Algorithm SHA256).Hash
|
||||||
|
if ($hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') {
|
||||||
|
throw "wintun.zip has an unexpected hash: $hash"
|
||||||
|
}
|
||||||
|
Expand-Archive wintun.zip -DestinationPath wintun-dl
|
||||||
|
choco install innosetup -y --no-progress
|
||||||
|
$iscc = Join-Path ${env:ProgramFiles(x86)} 'Inno Setup 6\ISCC.exe'
|
||||||
|
$stage = Join-Path $PWD 'dist/pkg/${{ matrix.asset }}'
|
||||||
|
& $iscc "/DAppVersion=$version" "/DSourceDir=$stage" `
|
||||||
|
"/DWintunDir=$(Join-Path $PWD 'wintun-dl/wintun/bin/amd64')" `
|
||||||
|
"/O$PWD" dist/windows/tsunagi.iss
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "ISCC failed with $LASTEXITCODE" }
|
||||||
|
|
||||||
|
# A dependency-free .deb for the x86_64 and aarch64 Linux builds: it drops
|
||||||
|
# the static binary, the systemd service and the polkit rule. Built with
|
||||||
|
# dpkg-deb (present on the runner); see dist/deb/build-deb.sh.
|
||||||
|
- name: Build the Debian package
|
||||||
|
if: matrix.deb
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
version="${GITHUB_REF_NAME#v}"
|
||||||
|
bash dist/deb/build-deb.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
"${{ matrix.deb_arch }}" \
|
||||||
|
"$version" \
|
||||||
|
"tsunagi_${version}_${{ matrix.deb_arch }}.deb"
|
||||||
|
|
||||||
|
# A dependency-free Arch package (.pkg.tar.zst), assembled with bsdtar and
|
||||||
|
# zstd (no makepkg); same binary, service and polkit rule. See
|
||||||
|
# dist/arch/build-pkg.sh.
|
||||||
|
- name: Build the Arch package
|
||||||
|
if: matrix.pkg_arch
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
version="${GITHUB_REF_NAME#v}"
|
||||||
|
pkgver="${version//-/}"
|
||||||
|
bash dist/arch/build-pkg.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
"${{ matrix.pkg_arch }}" \
|
||||||
|
"$version" \
|
||||||
|
"tsunagi-${pkgver}-1-${{ matrix.pkg_arch }}.pkg.tar.zst"
|
||||||
|
|
||||||
|
# The GUI variants: the same agent plus the tray binary and a desktop
|
||||||
|
# launcher, named tsunagi-gui (conflicting with the headless packages).
|
||||||
|
- name: Build the GUI packages
|
||||||
|
if: matrix.gnu_target
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
version="${GITHUB_REF_NAME#v}"
|
||||||
|
pkgver="${version//-/}"
|
||||||
|
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
|
||||||
|
bash dist/deb/build-deb.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
"${{ matrix.deb_arch }}" "$version" \
|
||||||
|
"tsunagi-gui_${version}_${{ matrix.deb_arch }}.deb" "$tray"
|
||||||
|
bash dist/arch/build-pkg.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
"${{ matrix.pkg_arch }}" "$version" \
|
||||||
|
"tsunagi-gui-${pkgver}-1-${{ matrix.pkg_arch }}.pkg.tar.zst" "$tray"
|
||||||
|
|
||||||
# @v3 on purpose: Gitea does not support the v4 artifact backend. This is
|
# @v3 on purpose: Gitea does not support the v4 artifact backend. This is
|
||||||
# what makes the archive show up under the run and hands it to `publish`.
|
# what makes the archive (and the .deb, where built) show up under the run
|
||||||
- name: Upload the archive as a run artifact
|
# and hands it to `publish`.
|
||||||
|
- name: Upload the build outputs as run artifacts
|
||||||
uses: actions/upload-artifact@v3
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: ${{ matrix.asset }}
|
name: ${{ matrix.asset }}
|
||||||
path: ${{ matrix.asset }}-*.*
|
path: |
|
||||||
|
${{ matrix.asset }}-*.*
|
||||||
|
*.deb
|
||||||
|
*.pkg.tar.zst
|
||||||
|
tsunagi-setup-*.exe
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
|
|
||||||
publish:
|
publish:
|
||||||
@@ -211,5 +346,5 @@ jobs:
|
|||||||
cat up.json >&2 || true
|
cat up.json >&2 || true
|
||||||
rc=1
|
rc=1
|
||||||
fi
|
fi
|
||||||
done < <(find artifacts -type f \( -name '*.tar.gz' -o -name '*.zip' \) -print0)
|
done < <(find artifacts -type f \( -name '*.tar.gz' -o -name '*.zip' -o -name '*.deb' -o -name '*.pkg.tar.zst' -o -name 'tsunagi-setup-*.exe' \) -print0)
|
||||||
exit "$rc"
|
exit "$rc"
|
||||||
+323
-31
@@ -1,19 +1,13 @@
|
|||||||
name: Release
|
name: Release
|
||||||
|
|
||||||
# GitHub version of the release pipeline. The build half mirrors the Gitea one
|
# Desktop builds mirror .gitea/workflows/release.yml. GitHub also builds and
|
||||||
# in .gitea/workflows/release.yml (static musl Linux via cargo-zigbuild, native
|
# signs the Android APK and attaches all platform packages to the tag with gh.
|
||||||
# macOS and Windows); only the publish half differs: GitHub needs the v4
|
|
||||||
# artifact backend and fills the release with `gh`.
|
|
||||||
#
|
#
|
||||||
# Gitea reads both .gitea/workflows and .github/workflows, so without a guard it
|
# Every job is gated on `github.server_url == 'https://github.com'`, so this file
|
||||||
# would also try to run this file and fail on @v4 and `gh`. (Gitea reports
|
# runs only on GitHub. Gitea runs its own copy in .gitea/workflows (which pins
|
||||||
# github.server_url as https://github.com, so that cannot tell the two apart.)
|
# the older @v3 artifact actions it supports); should a Gitea instance also read
|
||||||
# Instead every job is gated on a repository variable GITHUB_RELEASE=true, which
|
# .github/workflows, the guard skips these jobs there so they never fail on the
|
||||||
# is set only in the GitHub repository's settings — so on Gitea, where it is
|
# artifact backend or `gh`.
|
||||||
# absent, these jobs are skipped and the .gitea file is the one that runs.
|
|
||||||
#
|
|
||||||
# To enable on GitHub: Settings → Secrets and variables → Actions → Variables →
|
|
||||||
# New variable, name GITHUB_RELEASE, value true.
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
tags: ["v*"]
|
tags: ["v*"]
|
||||||
@@ -28,22 +22,39 @@ env:
|
|||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
name: ${{ matrix.asset }}
|
name: ${{ matrix.asset }}
|
||||||
if: ${{ vars.GITHUB_RELEASE == 'true' }}
|
if: ${{ github.server_url == 'https://github.com' }}
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-26.04
|
||||||
target: x86_64-unknown-linux-musl
|
target: x86_64-unknown-linux-musl
|
||||||
asset: tsunagi-linux-x86_64
|
asset: tsunagi-linux-x86_64
|
||||||
archive: tar.gz
|
archive: tar.gz
|
||||||
zig: true
|
zig: true
|
||||||
|
deb: true
|
||||||
|
deb_arch: amd64
|
||||||
|
pkg_arch: x86_64
|
||||||
|
gnu_target: x86_64-unknown-linux-gnu
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-latest
|
||||||
target: aarch64-unknown-linux-musl
|
target: aarch64-unknown-linux-musl
|
||||||
asset: tsunagi-linux-aarch64
|
asset: tsunagi-linux-aarch64
|
||||||
archive: tar.gz
|
archive: tar.gz
|
||||||
zig: true
|
zig: true
|
||||||
|
deb: true
|
||||||
|
deb_arch: arm64
|
||||||
|
pkg_arch: aarch64
|
||||||
|
# 32-bit ARM with hardware float (ARMv7, `v7l`): single-board and edge
|
||||||
|
# devices. Statically linked like the others.
|
||||||
|
- os: ubuntu-latest
|
||||||
|
target: armv7-unknown-linux-musleabihf
|
||||||
|
asset: tsunagi-linux-armv7
|
||||||
|
archive: tar.gz
|
||||||
|
zig: true
|
||||||
|
deb: true
|
||||||
|
deb_arch: armhf
|
||||||
|
pkg_arch: armv7h
|
||||||
- os: macos-latest
|
- os: macos-latest
|
||||||
target: aarch64-apple-darwin
|
target: aarch64-apple-darwin
|
||||||
asset: tsunagi-macos-aarch64
|
asset: tsunagi-macos-aarch64
|
||||||
@@ -56,7 +67,7 @@ jobs:
|
|||||||
zig: false
|
zig: false
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
with:
|
||||||
@@ -69,9 +80,9 @@ jobs:
|
|||||||
# aws-lc-sys (iroh's rustls backend) and the bundled sqlite are C, and the
|
# aws-lc-sys (iroh's rustls backend) and the bundled sqlite are C, and the
|
||||||
# musl targets have no prebuilt bindings, so bindgen needs libclang and the
|
# musl targets have no prebuilt bindings, so bindgen needs libclang and the
|
||||||
# C build needs cmake. zig is the cross C compiler cargo-zigbuild drives.
|
# C build needs cmake. zig is the cross C compiler cargo-zigbuild drives.
|
||||||
- name: Install musl build tooling
|
- name: Install musl build and packaging tooling
|
||||||
if: matrix.zig
|
if: matrix.zig
|
||||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends cmake clang libclang-dev
|
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends cmake clang libclang-dev libarchive-tools zstd
|
||||||
- name: Install zig
|
- name: Install zig
|
||||||
if: matrix.zig
|
if: matrix.zig
|
||||||
uses: mlugg/setup-zig@v2
|
uses: mlugg/setup-zig@v2
|
||||||
@@ -97,9 +108,33 @@ jobs:
|
|||||||
# one lint to keep the musl build log clean. A real link error still
|
# one lint to keep the musl build log clean. A real link error still
|
||||||
# fails the build.
|
# fails the build.
|
||||||
export RUSTFLAGS="${RUSTFLAGS:-} -A linker_messages"
|
export RUSTFLAGS="${RUSTFLAGS:-} -A linker_messages"
|
||||||
cargo zigbuild --release --locked --target "${{ matrix.target }}" --bin tsunagi
|
cargo zigbuild --release --locked --target "${{ matrix.target }}" --bin tsng
|
||||||
else
|
else
|
||||||
cargo build --release --locked --target "${{ matrix.target }}" --bin tsunagi
|
cargo build --release --locked --target "${{ matrix.target }}" --bin tsng
|
||||||
|
fi
|
||||||
|
|
||||||
|
# The tray GUI. On Linux it is built against glibc (an old baseline for
|
||||||
|
# portability), not musl: a GUI must dlopen libGL/X11/Wayland at runtime,
|
||||||
|
# which a static musl binary cannot. macOS and Windows build it natively.
|
||||||
|
- name: Build the tray GUI
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [[ "${{ runner.os }}" == "Linux" ]]; then
|
||||||
|
if [[ -n "${{ matrix.gnu_target }}" ]]; then
|
||||||
|
# tray-icon links GTK and libappindicator through pkg-config, which
|
||||||
|
# has no cross story under zig, so the Linux GUI is built natively
|
||||||
|
# (x86_64 only) against the runner's glibc.
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y --no-install-recommends \
|
||||||
|
libgtk-3-dev libayatana-appindicator3-dev
|
||||||
|
cargo build --release --locked \
|
||||||
|
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
|
||||||
|
else
|
||||||
|
echo "no GUI build for ${{ matrix.target }}"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
cargo build --release --locked --target "${{ matrix.target }}" --bin tsunagi-tray
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Package
|
- name: Package
|
||||||
@@ -111,21 +146,37 @@ jobs:
|
|||||||
stage="dist/pkg/${{ matrix.asset }}"
|
stage="dist/pkg/${{ matrix.asset }}"
|
||||||
mkdir -p "$stage"
|
mkdir -p "$stage"
|
||||||
|
|
||||||
bin="tsunagi"
|
bin="tsng"
|
||||||
[[ "${{ runner.os }}" == "Windows" ]] && bin="tsunagi.exe"
|
[[ "${{ runner.os }}" == "Windows" ]] && bin="tsng.exe"
|
||||||
cp "target/${{ matrix.target }}/release/${bin}" "$stage/"
|
cp "target/${{ matrix.target }}/release/${bin}" "$stage/"
|
||||||
|
|
||||||
|
# The tray GUI alongside it, where it was built (Linux: x86_64 only).
|
||||||
|
tray="tsunagi-tray"
|
||||||
|
[[ "${{ runner.os }}" == "Windows" ]] && tray="tsunagi-tray.exe"
|
||||||
|
if [[ "${{ runner.os }}" == "Linux" ]]; then
|
||||||
|
if [[ -n "${{ matrix.gnu_target }}" ]]; then
|
||||||
|
cp "target/${{ matrix.gnu_target }}/release/${tray}" "$stage/"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
cp "target/${{ matrix.target }}/release/${tray}" "$stage/"
|
||||||
|
fi
|
||||||
|
|
||||||
# The top-level README, plus the per-OS install notes and integration
|
# The top-level README, plus the per-OS install notes and integration
|
||||||
# files, so the archive carries what the platform needs to set up.
|
# files, so the archive carries what the platform needs to set up.
|
||||||
cp README.md "$stage/"
|
cp README.md "$stage/"
|
||||||
case "${{ runner.os }}" in
|
case "${{ runner.os }}" in
|
||||||
Linux)
|
Linux)
|
||||||
cp dist/linux/tsunagi.service dist/linux/install.sh "$stage/"
|
cp dist/linux/tsunagi.service dist/linux/install.sh \
|
||||||
|
dist/linux/50-tsunagi-resolved.rules "$stage/"
|
||||||
cp dist/linux/README.md "$stage/INSTALL.md"
|
cp dist/linux/README.md "$stage/INSTALL.md"
|
||||||
;;
|
;;
|
||||||
macOS)
|
macOS)
|
||||||
cp dist/macos/cy.hexor.tsunagi.plist "$stage/"
|
cp dist/macos/cy.hexor.tsunagi.plist "$stage/"
|
||||||
cp dist/macos/README.md "$stage/INSTALL.md"
|
cp dist/macos/README.md "$stage/INSTALL.md"
|
||||||
|
# The tray as an application bundle, for the Homebrew cask.
|
||||||
|
bash dist/macos/build-app.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsunagi-tray" \
|
||||||
|
"$version" "$stage/Tsunagi.app"
|
||||||
;;
|
;;
|
||||||
Windows)
|
Windows)
|
||||||
cp dist/windows/README.md "$stage/INSTALL.md"
|
cp dist/windows/README.md "$stage/INSTALL.md"
|
||||||
@@ -139,23 +190,168 @@ jobs:
|
|||||||
tar -C dist/pkg -czf "${archive}" "${{ matrix.asset }}"
|
tar -C dist/pkg -czf "${archive}" "${{ matrix.asset }}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Upload the archive as a run artifact
|
# The Windows installer: the agent as a service, Wintun, the tray and the
|
||||||
uses: actions/upload-artifact@v4
|
# PATH entry in one setup program. Wintun is the signed library from
|
||||||
|
# wintun.net, pinned by hash so a changed download fails the build.
|
||||||
|
- name: Build the Windows installer
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$version = $env:GITHUB_REF_NAME.TrimStart('v')
|
||||||
|
Invoke-WebRequest -Uri https://www.wintun.net/builds/wintun-0.14.1.zip -OutFile wintun.zip
|
||||||
|
$hash = (Get-FileHash wintun.zip -Algorithm SHA256).Hash
|
||||||
|
if ($hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') {
|
||||||
|
throw "wintun.zip has an unexpected hash: $hash"
|
||||||
|
}
|
||||||
|
Expand-Archive wintun.zip -DestinationPath wintun-dl
|
||||||
|
choco install innosetup -y --no-progress
|
||||||
|
$iscc = Join-Path ${env:ProgramFiles(x86)} 'Inno Setup 6\ISCC.exe'
|
||||||
|
$stage = Join-Path $PWD 'dist/pkg/${{ matrix.asset }}'
|
||||||
|
& $iscc "/DAppVersion=$version" "/DSourceDir=$stage" `
|
||||||
|
"/DWintunDir=$(Join-Path $PWD 'wintun-dl/wintun/bin/amd64')" `
|
||||||
|
"/O$PWD" dist/windows/tsunagi.iss
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "ISCC failed with $LASTEXITCODE" }
|
||||||
|
|
||||||
|
# A dependency-free .deb for the x86_64 and aarch64 Linux builds: it drops
|
||||||
|
# the static binary, the systemd service and the polkit rule. Built with
|
||||||
|
# dpkg-deb (present on the runner); see dist/deb/build-deb.sh.
|
||||||
|
- name: Build the Debian package
|
||||||
|
if: matrix.deb
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
version="${GITHUB_REF_NAME#v}"
|
||||||
|
bash dist/deb/build-deb.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
"${{ matrix.deb_arch }}" \
|
||||||
|
"$version" \
|
||||||
|
"tsunagi_${version}_${{ matrix.deb_arch }}.deb"
|
||||||
|
|
||||||
|
# A dependency-free Arch package (.pkg.tar.zst), assembled with bsdtar and
|
||||||
|
# zstd (no makepkg); same binary, service and polkit rule. See
|
||||||
|
# dist/arch/build-pkg.sh.
|
||||||
|
- name: Build the Arch package
|
||||||
|
if: matrix.pkg_arch
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
version="${GITHUB_REF_NAME#v}"
|
||||||
|
pkgver="${version//-/}"
|
||||||
|
bash dist/arch/build-pkg.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
"${{ matrix.pkg_arch }}" \
|
||||||
|
"$version" \
|
||||||
|
"tsunagi-${pkgver}-1-${{ matrix.pkg_arch }}.pkg.tar.zst"
|
||||||
|
|
||||||
|
# The GUI variants: the same agent plus the tray binary and a desktop
|
||||||
|
# launcher, named tsunagi-gui (conflicting with the headless packages).
|
||||||
|
- name: Build the GUI packages
|
||||||
|
if: matrix.gnu_target
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
version="${GITHUB_REF_NAME#v}"
|
||||||
|
pkgver="${version//-/}"
|
||||||
|
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
|
||||||
|
bash dist/deb/build-deb.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
"${{ matrix.deb_arch }}" "$version" \
|
||||||
|
"tsunagi-gui_${version}_${{ matrix.deb_arch }}.deb" "$tray"
|
||||||
|
bash dist/arch/build-pkg.sh \
|
||||||
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
"${{ matrix.pkg_arch }}" "$version" \
|
||||||
|
"tsunagi-gui-${pkgver}-1-${{ matrix.pkg_arch }}.pkg.tar.zst" "$tray"
|
||||||
|
|
||||||
|
- name: Upload the build outputs as run artifacts
|
||||||
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
name: ${{ matrix.asset }}
|
name: ${{ matrix.asset }}
|
||||||
path: ${{ matrix.asset }}-*.*
|
path: |
|
||||||
|
${{ matrix.asset }}-*.*
|
||||||
|
*.deb
|
||||||
|
*.pkg.tar.zst
|
||||||
|
tsunagi-setup-*.exe
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
android:
|
||||||
|
name: Android ARM64 APK
|
||||||
|
if: ${{ github.server_url == 'https://github.com' }}
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
env:
|
||||||
|
NDK_VERSION: '30.0.16248370'
|
||||||
|
BUILD_TOOLS_VERSION: '36.0.0'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '21'
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
targets: aarch64-linux-android
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
key: android-arm64-${{ env.NDK_VERSION }}
|
||||||
|
|
||||||
|
- name: Install Android build tools
|
||||||
|
run: |
|
||||||
|
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
|
||||||
|
'platforms;android-35' "build-tools;$BUILD_TOOLS_VERSION" "ndk;$NDK_VERSION"
|
||||||
|
echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV"
|
||||||
|
cargo install --locked --version 4.1.2 cargo-ndk
|
||||||
|
|
||||||
|
- name: Build the ARM64 release APK
|
||||||
|
run: |
|
||||||
|
android/gradlew -p android --no-daemon :app:assembleRelease \
|
||||||
|
"-PtsunagiVersionName=${GITHUB_REF_NAME#v}" "-PtsunagiVersionCode=$GITHUB_RUN_NUMBER"
|
||||||
|
|
||||||
|
- name: Sign the APK
|
||||||
|
id: sign
|
||||||
|
env:
|
||||||
|
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||||
|
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
: "${ANDROID_KEYSTORE_BASE64:?Set the ANDROID_KEYSTORE_BASE64 Actions secret}"
|
||||||
|
: "${ANDROID_KEYSTORE_PASSWORD:?Set the ANDROID_KEYSTORE_PASSWORD Actions secret}"
|
||||||
|
umask 077
|
||||||
|
keystore=$(mktemp "$RUNNER_TEMP/tsunagi-keystore.XXXXXXXX")
|
||||||
|
trap 'rm -f "$keystore"' EXIT
|
||||||
|
printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > "$keystore"
|
||||||
|
apk="$RUNNER_TEMP/tsunagi-android-${GITHUB_REF_NAME#v}-arm64-v8a.apk"
|
||||||
|
"$ANDROID_HOME/build-tools/$BUILD_TOOLS_VERSION/apksigner" sign \
|
||||||
|
--ks "$keystore" --ks-pass env:ANDROID_KEYSTORE_PASSWORD --key-pass env:ANDROID_KEYSTORE_PASSWORD \
|
||||||
|
--v4-signing-enabled false --out "$apk" android/app/build/outputs/apk/release/app-release-unsigned.apk
|
||||||
|
echo "apk=$apk" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Test the signed APK
|
||||||
|
env:
|
||||||
|
APK: ${{ steps.sign.outputs.apk }}
|
||||||
|
run: |
|
||||||
|
bash android/test-release-apk.sh "$APK" "${GITHUB_REF_NAME#v}" "$GITHUB_RUN_NUMBER" \
|
||||||
|
"$ANDROID_HOME/build-tools/$BUILD_TOOLS_VERSION"
|
||||||
|
|
||||||
|
- uses: actions/upload-artifact@v7
|
||||||
|
with:
|
||||||
|
name: tsunagi-android
|
||||||
|
path: ${{ steps.sign.outputs.apk }}
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
|
|
||||||
publish:
|
publish:
|
||||||
name: Publish release
|
name: Publish release
|
||||||
needs: build
|
needs: [build, android]
|
||||||
if: ${{ vars.GITHUB_RELEASE == 'true' }}
|
if: ${{ github.server_url == 'https://github.com' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
steps:
|
steps:
|
||||||
- name: Download every build artifact
|
- name: Download every build artifact
|
||||||
uses: actions/download-artifact@v4
|
uses: actions/download-artifact@v8
|
||||||
with:
|
with:
|
||||||
path: artifacts
|
path: artifacts
|
||||||
|
|
||||||
@@ -170,9 +366,12 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
# download-artifact@v4 nests each artifact under its own directory, so
|
# download-artifact nests each artifact under its own directory, so
|
||||||
# the archives are artifacts/<asset>/<file>.
|
# the archives are artifacts/<asset>/<file>.
|
||||||
mapfile -t files < <(find artifacts -type f \( -name '*.tar.gz' -o -name '*.zip' \))
|
mapfile -t files < <(find artifacts -type f \( -name '*.tar.gz' -o -name '*.zip' -o -name '*.deb' -o -name '*.pkg.tar.zst' -o -name 'tsunagi-setup-*.exe' \))
|
||||||
|
apk="artifacts/tsunagi-android/tsunagi-android-${TAG#v}-arm64-v8a.apk"
|
||||||
|
[[ -s "$apk" ]] || { echo "::error::Missing release APK at $apk"; exit 1; }
|
||||||
|
files+=("$apk")
|
||||||
printf 'asset: %s\n' "${files[@]}"
|
printf 'asset: %s\n' "${files[@]}"
|
||||||
|
|
||||||
prerelease=()
|
prerelease=()
|
||||||
@@ -190,3 +389,96 @@ jobs:
|
|||||||
--verify-tag \
|
--verify-tag \
|
||||||
"${prerelease[@]}"
|
"${prerelease[@]}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
notify-arch-repository:
|
||||||
|
name: Publish packages to the Arch repository
|
||||||
|
needs: publish
|
||||||
|
if: ${{ github.server_url == 'https://github.com' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions: {}
|
||||||
|
steps:
|
||||||
|
- name: Notify arch_repo of the completed release
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.ARCH_REPO_TOKEN }}
|
||||||
|
RELEASE_TAG: ${{ github.ref_name }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [[ -z "$GH_TOKEN" ]]; then
|
||||||
|
echo '::error::Set the ARCH_REPO_TOKEN Actions secret with Contents: write access to house-of-vanity/arch_repo.'
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
jq -n --arg repository "$GITHUB_REPOSITORY" --arg tag "$RELEASE_TAG" \
|
||||||
|
'{event_type: "new_package", client_payload: {repository: $repository, tag: $tag}}' \
|
||||||
|
| gh api --method POST repos/house-of-vanity/arch_repo/dispatches --input -
|
||||||
|
|
||||||
|
publish-openartifact:
|
||||||
|
name: Publish APT and pacman packages
|
||||||
|
needs: publish
|
||||||
|
if: github.server_url == 'https://github.com'
|
||||||
|
runs-on: ubuntu-26.04
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
id-token: write
|
||||||
|
env:
|
||||||
|
OA_SERVER: https://repo.hexor.cy
|
||||||
|
APT_SUITE: resolute
|
||||||
|
steps:
|
||||||
|
- name: Download packages attached to this release
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
gh release download "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" \
|
||||||
|
--pattern '*.deb' --pattern '*.pkg.tar.zst' --dir packages
|
||||||
|
|
||||||
|
- name: Publish packages
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
id_token=$(curl -fsS -G --data-urlencode "audience=$OA_SERVER" \
|
||||||
|
-H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
|
||||||
|
"$ACTIONS_ID_TOKEN_REQUEST_URL" | jq -er '.value')
|
||||||
|
oa_token=$(jq -n --arg token "$id_token" \
|
||||||
|
'{token:$token,policy:"github-tsunagi-release"}' | \
|
||||||
|
curl -fsS --json @- "$OA_SERVER/api/v1/auth/oidc/exchange" | jq -er '.access_token')
|
||||||
|
echo "::add-mask::$oa_token"
|
||||||
|
auth=(-H "Authorization: Bearer $oa_token")
|
||||||
|
|
||||||
|
for file in packages/*.deb packages/*.pkg.tar.zst; do
|
||||||
|
[[ -f "$file" ]] || { echo "Missing release artifact: $file"; exit 1; }
|
||||||
|
name=${file##*/}
|
||||||
|
case "$name" in
|
||||||
|
*.deb)
|
||||||
|
arch=$(dpkg-deb -f "$file" Architecture)
|
||||||
|
status=$(curl -sS -o "$RUNNER_TEMP/oa-upload.json" -w '%{http_code}' \
|
||||||
|
"${auth[@]}" -F "file=@$file" -F "distribution=$APT_SUITE" -F component=main \
|
||||||
|
"$OA_SERVER/api/v1/repositories/hexor-apt/debs")
|
||||||
|
;;
|
||||||
|
*.pkg.tar.zst)
|
||||||
|
stem=${name%.pkg.tar.zst}
|
||||||
|
arch=${stem##*-}
|
||||||
|
url="$OA_SERVER/repos/hexor-pacman/os/$arch/$name"
|
||||||
|
status=$(curl -sS -o "$RUNNER_TEMP/oa-upload.json" -w '%{http_code}' \
|
||||||
|
"${auth[@]}" -T "$file" "$url")
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
case "$status" in
|
||||||
|
2??) echo "Published $name" ;;
|
||||||
|
409)
|
||||||
|
# An immutable version may already exist after a partial run.
|
||||||
|
digest=$(sha256sum "$file" | cut -d ' ' -f1)
|
||||||
|
if [[ "$name" == *.deb ]]; then
|
||||||
|
index="$OA_SERVER/repos/hexor-apt/dists/$APT_SUITE/main/binary-$arch/Packages"
|
||||||
|
curl -fsS "${auth[@]}" "$index" | grep -Fx "SHA256: $digest" >/dev/null || {
|
||||||
|
echo "Existing $name has different contents or is outside $APT_SUITE" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
else
|
||||||
|
remote=$(curl -fsS "${auth[@]}" "$url" | sha256sum | cut -d ' ' -f1)
|
||||||
|
[[ "$remote" == "$digest" ]] || { echo "Different bytes for $name"; exit 1; }
|
||||||
|
fi
|
||||||
|
echo "Already published with matching SHA-256: $name"
|
||||||
|
;;
|
||||||
|
*) echo "Upload of $name returned HTTP $status" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
@@ -1 +1,2 @@
|
|||||||
/target
|
/target
|
||||||
|
/.claude
|
||||||
@@ -8,7 +8,7 @@ before touching the code. Do not restate the full design here; follow the links.
|
|||||||
A proof-of-concept agent library for small private mesh networks. A user
|
A proof-of-concept agent library for small private mesh networks. A user
|
||||||
supplies a network name and one shared secret; agents derive the same network
|
supplies a network name and one shared secret; agents derive the same network
|
||||||
space independently, find each other, prove membership and exchange control
|
space independently, find each other, prove membership and exchange control
|
||||||
messages. Scope and non-scope are in [README.md](README.md).
|
messages. What it does and does not do is in [docs/architecture.md](docs/architecture.md) and [docs/threat-model.md](docs/threat-model.md).
|
||||||
|
|
||||||
There is no central server, no owner, no registration and no majority vote.
|
There is no central server, no owner, no registration and no majority vote.
|
||||||
Design accordingly: a majority is not a root of trust.
|
Design accordingly: a majority is not a root of trust.
|
||||||
@@ -30,7 +30,7 @@ scripts when improving the interactive workflow.
|
|||||||
Keep these separate. Crossing them is the main thing to review for.
|
Keep these separate. Crossing them is the main thing to review for.
|
||||||
|
|
||||||
- **Control plane vs data plane.** The separation is **logical, not physical**.
|
- **Control plane vs data plane.** The separation is **logical, not physical**.
|
||||||
The control protocol in `crates/tsunagi/src/proto/` knows nothing about
|
The control protocol in `crates/tsunagi-core/src/proto/` knows nothing about
|
||||||
packets, and a protocol crate knows nothing about the control protocol;
|
packets, and a protocol crate knows nothing about the control protocol;
|
||||||
either can be replaced on its own. Both may ride on iroh — refusing to
|
either can be replaced on its own. Both may ride on iroh — refusing to
|
||||||
would throw away iroh's NAT traversal and force the data plane to
|
would throw away iroh's NAT traversal and force the data plane to
|
||||||
@@ -59,8 +59,10 @@ Keep these separate. Crossing them is the main thing to review for.
|
|||||||
other peers goes link in, link out: it is never written to the middle's
|
other peers goes link in, link out: it is never written to the middle's
|
||||||
interface or decrypted there. Multihop routing has a bounded hop limit;
|
interface or decrypted there. Multihop routing has a bounded hop limit;
|
||||||
equal-cost next hops are chosen per flow. Reachability is first-hand and
|
equal-cost next hops are chosen per flow. Reachability is first-hand and
|
||||||
volatile: each authenticated member advertises its own protocol-specific
|
volatile: each authenticated member advertises its own direct links, of
|
||||||
links. Build routing tables on topology changes, never per packet. Transit
|
whatever kind. A link is a way to reach a neighbour and a protocol is an
|
||||||
|
end-to-end tunnel to a peer; the two meet only in the envelope, so a
|
||||||
|
tunnel never depends on which transports carry it. Build routing tables on topology changes, never per packet. Transit
|
||||||
must not acquire a routing mutex or wait for a protocol/TUN reader.
|
must not acquire a routing mutex or wait for a protocol/TUN reader.
|
||||||
- **Broadcast fanout belongs at local IP ingress.** Participation is local to
|
- **Broadcast fanout belongs at local IP ingress.** Participation is local to
|
||||||
each network, enabled by default, persisted and advertised to authenticated
|
each network, enabled by default, persisted and advertised to authenticated
|
||||||
@@ -70,9 +72,9 @@ Keep these separate. Crossing them is the main thing to review for.
|
|||||||
ownership checks or add broadcast flooding to encrypted transit.
|
ownership checks or add broadcast flooding to encrypted transit.
|
||||||
- **Plugins never learn reachability.** An `IpPlugin` is handed a `PacketLink`
|
- **Plugins never learn reachability.** An `IpPlugin` is handed a `PacketLink`
|
||||||
per peer and moves datagrams over it. Addresses, hole punching and relays
|
per peer and moves datagrams over it. Addresses, hole punching and relays
|
||||||
belong to `crates/tsunagi/src/dataplane/transport/`. A plugin announcement says *who*, never
|
belong to `crates/tsunagi-core/src/dataplane/transport/`. A plugin announcement says *who*, never
|
||||||
*where*.
|
*where*.
|
||||||
- **The core never parses a plugin payload.** See `crates/tsunagi/src/dataplane/mod.rs`. Only
|
- **The core never parses a plugin payload.** See `crates/tsunagi-core/src/dataplane/mod.rs`. Only
|
||||||
`crates/tsunagi-wg-quic/src/announcement.rs` interprets `wg-quic` payloads, and
|
`crates/tsunagi-wg-quic/src/announcement.rs` interprets `wg-quic` payloads, and
|
||||||
only after bounding every field. A data plane failure must never stop the
|
only after bounding every field. A data plane failure must never stop the
|
||||||
control plane.
|
control plane.
|
||||||
@@ -81,7 +83,7 @@ Keep these separate. Crossing them is the main thing to review for.
|
|||||||
inbound packets are dropped unless their source is the address derived for
|
inbound packets are dropped unless their source is the address derived for
|
||||||
the peer that sent them. Never trust an address a peer announces.
|
the peer that sent them. Never trust an address a peer announces.
|
||||||
- **Signed state is the only durable agreement.** A fact that must survive a
|
- **Signed state is the only durable agreement.** A fact that must survive a
|
||||||
participant being away goes in `crates/tsunagi/src/state/` as a record signed by its
|
participant being away goes in `crates/tsunagi-core/src/state/` as a record signed by its
|
||||||
author, never in a session. Merging is deterministic, an older version never
|
author, never in a session. Merging is deterministic, an older version never
|
||||||
rolls back a newer one, and absence from a snapshot is not deletion. Never
|
rolls back a newer one, and absence from a snapshot is not deletion. Never
|
||||||
add a vote or a quorum: a majority is not a trust root here, and it would
|
add a vote or a quorum: a majority is not a trust root here, and it would
|
||||||
@@ -115,7 +117,7 @@ Keep these separate. Crossing them is the main thing to review for.
|
|||||||
normal path *and* the important failures. See [docs/testing.md](docs/testing.md).
|
normal path *and* the important failures. See [docs/testing.md](docs/testing.md).
|
||||||
Do not add tests for getters or to move a coverage number.
|
Do not add tests for getters or to move a coverage number.
|
||||||
2. **Never change `IDENTITY_SCHEME`, the derivation labels, or the transcript
|
2. **Never change `IDENTITY_SCHEME`, the derivation labels, or the transcript
|
||||||
encoding** in `crates/tsunagi/src/identity/network.rs` and `crates/tsunagi/src/proto/handshake.rs` without
|
encoding** in `crates/tsunagi-core/src/identity/network.rs` and `crates/tsunagi-core/src/proto/handshake.rs` without
|
||||||
treating it as an incompatible protocol change. Bumping the crate version or
|
treating it as an incompatible protocol change. Bumping the crate version or
|
||||||
the control protocol version must not change an existing `NetworkId`.
|
the control protocol version must not change an existing `NetworkId`.
|
||||||
3. **Secrets never leak.** Not into logs, not into `Debug`, not into status
|
3. **Secrets never leak.** Not into logs, not into `Debug`, not into status
|
||||||
@@ -126,7 +128,7 @@ Keep these separate. Crossing them is the main thing to review for.
|
|||||||
the library; tests opt out explicitly at the top of each file.
|
the library; tests opt out explicitly at the top of each file.
|
||||||
5. **Bounds before allocation.** Frame lengths are checked against
|
5. **Bounds before allocation.** Frame lengths are checked against
|
||||||
`Limits::max_frame_len` before a buffer is allocated. Every string, list and
|
`Limits::max_frame_len` before a buffer is allocated. Every string, list and
|
||||||
queue has a limit in `crates/tsunagi/src/config.rs`.
|
queue has a limit in `crates/tsunagi-core/src/config.rs`.
|
||||||
6. **Failure is contained.** A bad signature, wrong secret, malformed packet or
|
6. **Failure is contained.** A bad signature, wrong secret, malformed packet or
|
||||||
unknown version rejects one message or one session. It never stops another
|
unknown version rejects one message or one session. It never stops another
|
||||||
network and never stops the agent. There is no irreversible global error
|
network and never stops the agent. There is no irreversible global error
|
||||||
@@ -150,18 +152,18 @@ Keep these separate. Crossing them is the main thing to review for.
|
|||||||
|
|
||||||
| path | responsibility |
|
| path | responsibility |
|
||||||
|---------------------|----------------|
|
|---------------------|----------------|
|
||||||
| `crates/tsunagi/src/identity/` | device identity; deterministic network space identity and derived keys |
|
| `crates/tsunagi-core/src/identity/` | device identity; deterministic network space identity and derived keys |
|
||||||
| `crates/tsunagi/src/storage/` | `state.sqlite`, `cache.sqlite`, directory ownership lock |
|
| `crates/tsunagi-core/src/storage/` | `state.sqlite`, `cache.sqlite`, directory ownership lock |
|
||||||
| `crates/tsunagi/src/discovery.rs` | candidate sources; test and static backends |
|
| `crates/tsunagi-core/src/discovery.rs` | candidate sources; test and static backends |
|
||||||
| `crates/tsunagi/src/proto/` | framing, message formats, membership handshake |
|
| `crates/tsunagi-core/src/proto/` | framing, message formats, membership handshake |
|
||||||
| `crates/tsunagi/src/net.rs` | iroh endpoint adapter and observability snapshots |
|
| `crates/tsunagi-core/src/net.rs` | iroh endpoint adapter and observability snapshots |
|
||||||
| `crates/tsunagi/src/agent/` | agent lifecycle, per-network runtimes, sessions, events, status |
|
| `crates/tsunagi-core/src/agent/` | agent lifecycle, per-network runtimes, sessions, events, status |
|
||||||
| `crates/tsunagi/src/state/` | signed records that outlive a session, their merge rules and address allocation |
|
| `crates/tsunagi-core/src/state/` | signed records that outlive a session, their merge rules and address allocation |
|
||||||
| `crates/tsunagi/src/overlay/` | the one interface an agent owns: provisioning, the TUN, routing, source checks, broadcast host rules |
|
| `crates/tsunagi-core/src/overlay/` | the one interface an agent owns: provisioning, the TUN, routing, source checks, broadcast host rules |
|
||||||
| `crates/tsunagi/src/dataplane/` | the protocol contract and the authenticated packet transport |
|
| `crates/tsunagi-core/src/dataplane/` | the protocol contract and the authenticated packet transport |
|
||||||
| `crates/tsunagi/src/dns/` | the DNS view of a network: zone, server, resolver publication |
|
| `crates/tsunagi-core/src/dns/` | the DNS view of a network: zone, server, resolver publication |
|
||||||
| `crates/tsunagi-wg-quic/` | the `wg-quic` protocol: its keys, its announcement, its tunnels |
|
| `crates/tsunagi-wg-quic/` | the single internal WireGuard cipher, keys and opaque announcement; historical crate name |
|
||||||
| `crates/tsunagi-cli/` | the command line agent; the only place that owns a runtime, a logger and signals |
|
| `crates/tsunagi/` | the command line agent, built as `tsng`; the only place that owns a runtime, a logger and signals |
|
||||||
| `tests/` | integration tests; `tests/common/` is the shared harness |
|
| `tests/` | integration tests; `tests/common/` is the shared harness |
|
||||||
|
|
||||||
Add abstractions only at real substitution or testing boundaries. Do not add a
|
Add abstractions only at real substitution or testing boundaries. Do not add a
|
||||||
|
|||||||
Generated
+2893
-123
File diff suppressed because it is too large.
Load diff
+5
-3
@@ -4,18 +4,20 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
exclude = ["vendor/mainline"]
|
exclude = ["vendor/mainline", "vendor/iroh"]
|
||||||
|
|
||||||
# Mainline 8.0.0 treats Windows UDP read timeouts as socket failures.
|
# Mainline 8.0.0 treats Windows UDP read timeouts as socket failures.
|
||||||
# Keep the small receive-loop correction reproducible until an upstream fix.
|
# Keep the small receive-loop correction reproducible until an upstream fix.
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
mainline = { path = "vendor/mainline" }
|
mainline = { path = "vendor/mainline" }
|
||||||
|
# Backport bounded path retries until an iroh release includes the OOM fix.
|
||||||
|
iroh = { path = "vendor/iroh" }
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.91"
|
rust-version = "1.91"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "WTFPL"
|
||||||
repository = "https://github.com/tsunagi-net/tsunagi"
|
repository = "https://github.com/house-of-vanity/tsunagi"
|
||||||
|
|
||||||
[workspace.lints.rust]
|
[workspace.lints.rust]
|
||||||
missing_docs = "warn"
|
missing_docs = "warn"
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
|
||||||
|
Version 2, December 2004
|
||||||
|
|
||||||
|
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
|
||||||
|
|
||||||
|
Everyone is permitted to copy and distribute verbatim or modified
|
||||||
|
copies of this license document, and changing it is allowed as long
|
||||||
|
as the name is changed.
|
||||||
|
|
||||||
|
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
|
||||||
|
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||||
|
|
||||||
|
0. You just DO WHAT THE FUCK YOU WANT TO.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
gradlew text eol=lf
|
||||||
|
gradlew.bat text eol=crlf
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
.gradle/
|
||||||
|
.kotlin/
|
||||||
|
.idea/
|
||||||
|
local.properties
|
||||||
|
**/build/
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Android client
|
||||||
|
|
||||||
|
Download `tsunagi-android-<version>-arm64-v8a.apk` from the project's GitHub release and open it on an ARM64 phone running Android 8 or later. If prompted, allow the app that opened the file to install it. Later releases can update the installed app and preserve the mesh identity. A prototype signed with a local debug key requires a fresh install to switch to the release signer. Uninstalling the prototype removes its local identity and saved networks. [GitHub Releases](https://github.com/house-of-vanity/tsunagi/releases)
|
||||||
|
|
||||||
|
## Build from source
|
||||||
|
|
||||||
|
Open this directory in Android Studio. The debug prototype targets ARM64 devices running Android 8 or later with OpenGL ES 3. Install SDK Platform 35 and the NDK with the SDK Manager. Point `ANDROID_HOME` at your SDK and `ANDROID_NDK_HOME` at the installed NDK directory. The Gradle launcher needs a JDK, such as the one bundled with Android Studio.
|
||||||
|
|
||||||
|
From the repository root, with Cargo and cargo-ndk on your PATH:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rustup target add aarch64-linux-android
|
||||||
|
cargo install cargo-ndk --version 4.1.2 --locked
|
||||||
|
cd android
|
||||||
|
./gradlew :app:assembleDebug
|
||||||
|
adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join with the existing network name and secret. Android keeps the established VPN service bound when the activity closes. **About → Stop VPN** disconnects it. The app-private state directory holds the device identity and its saved networks.
|
||||||
|
|
||||||
|
The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic.
|
||||||
|
|
||||||
|
Applications using Android’s system resolver can connect to `<member>.<network>` and `<vip>.<network>`, for example `k8s.tsng:6443`. The VPN answers UDP and TCP DNS questions locally using the same signed roster and service records as the desktop. Unknown names in a joined mesh receive an authoritative negative answer. Other names go to Android’s resolver on the underlying Wi-Fi or cellular network, including while using a remote exit. Android 10 and later support arbitrary external DNS record types. On Android 8 and 9 the system lookup API supplies external A and AAAA records.
|
||||||
|
|
||||||
|
The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard.
|
||||||
|
|
||||||
|
Open **Exit node…** on a network tile to compare remote gateways by control RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
|
||||||
|
|
||||||
|
## Configure GitHub release signing
|
||||||
|
|
||||||
|
The GitHub `Release` workflow builds and signs the ARM64 APK for each `v*` tag. The tag supplies the version name and the workflow run number supplies the Android version code. A rerun of the same workflow run keeps that code. The publish job attaches the verified APK alongside the desktop packages.
|
||||||
|
|
||||||
|
Before the first release, configure two repository Actions secrets. Use a dedicated single-key PKCS12 keystore with the same password for the keystore and key. Keep a private backup of the file and password so future releases can update existing installations. To create the first key, run this command once.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
keytool -genkeypair -storetype PKCS12 -keystore "$HOME/tsunagi-release.p12" \
|
||||||
|
-alias tsunagi -keyalg RSA -keysize 3072 -validity 10000
|
||||||
|
```
|
||||||
|
|
||||||
|
From this repository, upload the keystore. Enter its password when the second command prompts for it.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
base64 < "$HOME/tsunagi-release.p12" | gh secret set ANDROID_KEYSTORE_BASE64
|
||||||
|
gh secret set ANDROID_KEYSTORE_PASSWORD
|
||||||
|
```
|
||||||
|
|
||||||
|
Missing signing credentials or a failed APK check stop publication. After correcting the secrets, rerun the failed release jobs for the same tag.
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import groovy.json.JsonSlurper
|
||||||
|
|
||||||
|
plugins { id 'com.android.application' version '9.2.1' }
|
||||||
|
|
||||||
|
def workspace = rootProject.projectDir.parentFile
|
||||||
|
def abi = 'arm64-v8a'
|
||||||
|
android {
|
||||||
|
namespace 'cy.hexor.tsunagi'
|
||||||
|
compileSdk 35
|
||||||
|
def cargoNdk = providers.environmentVariable('ANDROID_NDK_HOME')
|
||||||
|
if (cargoNdk.isPresent()) {
|
||||||
|
ndkPath = cargoNdk.get()
|
||||||
|
def ndkProperties = new Properties()
|
||||||
|
file("$ndkPath/source.properties").withInputStream { ndkProperties.load(it) }
|
||||||
|
ndkVersion = ndkProperties.getProperty('Pkg.Revision')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cargo also builds standalone cdylibs for these dependencies. Their code
|
||||||
|
// is linked into tsunagi_android; the JVM loads only the application library.
|
||||||
|
packaging.jniLibs.excludes += ['**/libboringtun.so', '**/libiroh.so', '**/libiroh_relay.so']
|
||||||
|
defaultConfig {
|
||||||
|
applicationId 'cy.hexor.tsunagi'
|
||||||
|
minSdk 26
|
||||||
|
targetSdk 35
|
||||||
|
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
|
||||||
|
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.0')
|
||||||
|
ndk { abiFilters abi }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// rustls ships its Android trust manager as an AAR in the locked Cargo package.
|
||||||
|
def metadata = providers.exec {
|
||||||
|
workingDir workspace
|
||||||
|
commandLine 'cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'aarch64-linux-android'
|
||||||
|
}.standardOutput.asText.get()
|
||||||
|
def verifier = new JsonSlurper().parseText(metadata).packages.find { it.name == 'rustls-platform-verifier-android' }
|
||||||
|
repositories {
|
||||||
|
maven {
|
||||||
|
url new File(new File(verifier.manifest_path).parent, 'maven')
|
||||||
|
metadataSources { mavenPom() }
|
||||||
|
content { includeModule 'rustls', 'rustls-platform-verifier' }
|
||||||
|
}
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
dependencies { implementation "rustls:rustls-platform-verifier:${verifier.version}" }
|
||||||
|
|
||||||
|
abstract class BuildRust extends Exec {
|
||||||
|
@OutputDirectory abstract DirectoryProperty getJniLibs()
|
||||||
|
}
|
||||||
|
|
||||||
|
androidComponents.onVariants(androidComponents.selector().all()) { variant ->
|
||||||
|
def mode = variant.buildType
|
||||||
|
def libs = layout.buildDirectory.dir("generated/rust/${mode}")
|
||||||
|
def nativeBuild = tasks.register("cargo${mode.capitalize()}", BuildRust) {
|
||||||
|
workingDir workspace
|
||||||
|
inputs.files(fileTree(workspace) {
|
||||||
|
include 'Cargo.toml', 'Cargo.lock', '.cargo/**', 'crates/**/Cargo.toml', 'crates/**/src/**', 'vendor/**'
|
||||||
|
})
|
||||||
|
jniLibs.set(libs)
|
||||||
|
commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26', '-o', libs.get().asFile,
|
||||||
|
'build', '--locked', '--lib', '-p', 'tsunagi-android'
|
||||||
|
if (mode == 'release') args '--release'
|
||||||
|
}
|
||||||
|
variant.sources.jniLibs.addGeneratedSourceDirectory(nativeBuild) { it.jniLibs }
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||||
|
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
|
||||||
|
<application android:label="tsunagi" android:icon="@drawable/tsunagi"
|
||||||
|
android:enableOnBackInvokedCallback="false" android:allowBackup="false" android:theme="@android:style/Theme.Material.NoActionBar">
|
||||||
|
<activity android:name=".MainActivity" android:exported="true"
|
||||||
|
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<service android:name=".MeshVpn" android:permission="android.permission.BIND_VPN_SERVICE"
|
||||||
|
android:foregroundServiceType="systemExempted" android:exported="false">
|
||||||
|
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
|
||||||
|
<meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON" android:value="false" />
|
||||||
|
</service>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package cy.hexor.tsunagi
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.VpnService
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.WindowInsets
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
|
||||||
|
class MainActivity : Activity() {
|
||||||
|
private var askedForNotifications = false
|
||||||
|
internal fun requestExitNotifications() {
|
||||||
|
if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications &&
|
||||||
|
checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||||
|
askedForNotifications = true
|
||||||
|
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private lateinit var surface: MeshSurface
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
surface = MeshSurface(this)
|
||||||
|
val root = FrameLayout(this)
|
||||||
|
if (Build.VERSION.SDK_INT >= 30) {
|
||||||
|
window.setDecorFitsSystemWindows(false)
|
||||||
|
root.setOnApplyWindowInsetsListener { view, insets ->
|
||||||
|
val area = insets.getInsets(WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout() or WindowInsets.Type.ime())
|
||||||
|
view.setPadding(area.left, area.top, area.right, area.bottom)
|
||||||
|
insets
|
||||||
|
}
|
||||||
|
} else root.fitsSystemWindows = true
|
||||||
|
root.addView(surface)
|
||||||
|
setContentView(root)
|
||||||
|
}
|
||||||
|
internal fun requestVpn() {
|
||||||
|
val consent = VpnService.prepare(this)
|
||||||
|
if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java))
|
||||||
|
else startActivityForResult(consent, 1)
|
||||||
|
}
|
||||||
|
@Deprecated("Platform consent result")
|
||||||
|
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
|
||||||
|
super.onActivityResult(request, result, data)
|
||||||
|
if (request == 1) {
|
||||||
|
if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java))
|
||||||
|
else surface.input(5, "VPN permission was declined")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Deprecated("Forward system Back to the current Rust view")
|
||||||
|
override fun onBackPressed() { surface.dispatchBack() }
|
||||||
|
override fun onResume() { super.onResume(); surface.onResume() }
|
||||||
|
override fun onPause() { surface.onPause(); super.onPause() }
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package cy.hexor.tsunagi
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.opengl.GLSurfaceView
|
||||||
|
import android.text.InputType
|
||||||
|
import android.view.KeyEvent
|
||||||
|
import android.view.MotionEvent
|
||||||
|
import android.view.inputmethod.BaseInputConnection
|
||||||
|
import android.view.inputmethod.EditorInfo
|
||||||
|
import android.view.inputmethod.InputConnection
|
||||||
|
import android.view.inputmethod.InputMethodManager
|
||||||
|
import javax.microedition.khronos.egl.EGLConfig
|
||||||
|
import javax.microedition.khronos.opengles.GL10
|
||||||
|
|
||||||
|
/** Surface, input connection and clipboard bridge for egui. */
|
||||||
|
class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), GLSurfaceView.Renderer {
|
||||||
|
private val density get() = resources.displayMetrics.density
|
||||||
|
private val imm = activity.getSystemService(InputMethodManager::class.java)
|
||||||
|
private var imeMode = 0
|
||||||
|
private var widthPx = 0
|
||||||
|
private var heightPx = 0
|
||||||
|
private val repaint = Runnable { requestRender() }
|
||||||
|
init {
|
||||||
|
setEGLContextClientVersion(3)
|
||||||
|
preserveEGLContextOnPause = true
|
||||||
|
setRenderer(this)
|
||||||
|
renderMode = RENDERMODE_WHEN_DIRTY
|
||||||
|
isFocusableInTouchMode = true
|
||||||
|
requestFocus()
|
||||||
|
}
|
||||||
|
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
|
||||||
|
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
|
||||||
|
override fun onDrawFrame(gl: GL10?) {
|
||||||
|
val delay = Native.draw(this, widthPx, heightPx, density)
|
||||||
|
removeCallbacks(repaint)
|
||||||
|
postDelayed(repaint, delay.coerceAtLeast(16))
|
||||||
|
}
|
||||||
|
override fun onPause() { super.onPause(); removeCallbacks(repaint) }
|
||||||
|
override fun onTouchEvent(e: MotionEvent): Boolean {
|
||||||
|
val phase = when (e.actionMasked) {
|
||||||
|
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0
|
||||||
|
MotionEvent.ACTION_MOVE -> 1
|
||||||
|
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> 2
|
||||||
|
MotionEvent.ACTION_CANCEL -> 3
|
||||||
|
else -> return false
|
||||||
|
}
|
||||||
|
for (i in 0 until e.pointerCount) {
|
||||||
|
if ((phase == 0 || phase == 2) && i != e.actionIndex) continue
|
||||||
|
val id = e.getPointerId(i)
|
||||||
|
val x = e.getX(i) / density
|
||||||
|
val y = e.getY(i) / density
|
||||||
|
queueEvent { Native.touch(phase, id, x, y) }
|
||||||
|
}
|
||||||
|
requestRender()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startVpn() { post { activity.requestVpn() } }
|
||||||
|
fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } }
|
||||||
|
fun requestExitNotifications() { post { activity.requestExitNotifications() } }
|
||||||
|
fun closeScreen() { post { activity.finish() } }
|
||||||
|
fun openUrl(url: String) { post {
|
||||||
|
val uri = android.net.Uri.parse(url)
|
||||||
|
if (uri.scheme == "https") {
|
||||||
|
try { activity.startActivity(Intent(Intent.ACTION_VIEW, uri)) }
|
||||||
|
catch (_: android.content.ActivityNotFoundException) { }
|
||||||
|
}
|
||||||
|
} }
|
||||||
|
fun dispatchBack() { queueEvent { Native.back(this) }; requestRender() }
|
||||||
|
fun copyText(value: String) { post {
|
||||||
|
activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("tsunagi", value))
|
||||||
|
} }
|
||||||
|
fun copySecret(value: String) { post {
|
||||||
|
val clip = ClipData.newPlainText("tsunagi", value)
|
||||||
|
clip.description.extras = android.os.PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) }
|
||||||
|
activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(clip)
|
||||||
|
} }
|
||||||
|
fun pasteSecret() { post {
|
||||||
|
val clip = activity.getSystemService(ClipboardManager::class.java).primaryClip
|
||||||
|
val text = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
|
||||||
|
if (text != null && text.length <= 2048) input(4, text.toString())
|
||||||
|
} }
|
||||||
|
fun keyboard(mode: Int) { post {
|
||||||
|
imeMode = mode
|
||||||
|
if (mode == 0) {
|
||||||
|
imm.hideSoftInputFromWindow(windowToken, 0)
|
||||||
|
imm.restartInput(this)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
requestFocus()
|
||||||
|
imm.restartInput(this)
|
||||||
|
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
|
||||||
|
}
|
||||||
|
} }
|
||||||
|
fun input(kind: Int, value: String) {
|
||||||
|
queueEvent { Native.input(kind, value) }
|
||||||
|
requestRender()
|
||||||
|
}
|
||||||
|
private fun key(code: Int) { queueEvent { Native.key(code) }; requestRender() }
|
||||||
|
override fun onCheckIsTextEditor(): Boolean = imeMode != 0
|
||||||
|
override fun onCreateInputConnection(info: EditorInfo): InputConnection? {
|
||||||
|
if (imeMode == 0) return null
|
||||||
|
info.inputType = InputType.TYPE_CLASS_TEXT or (if (imeMode == 2) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)
|
||||||
|
info.imeOptions = EditorInfo.IME_ACTION_DONE or EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
|
||||||
|
return object : BaseInputConnection(this, false) {
|
||||||
|
private var composing: String? = null
|
||||||
|
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||||
|
if (composing == null) input(1, "")
|
||||||
|
composing = text?.toString().orEmpty()
|
||||||
|
input(2, composing.orEmpty())
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||||
|
input(if (composing == null) 0 else 3, text?.toString().orEmpty())
|
||||||
|
composing = null
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
override fun finishComposingText(): Boolean {
|
||||||
|
composing?.let { input(3, it) }
|
||||||
|
composing = null
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
override fun deleteSurroundingText(before: Int, after: Int): Boolean {
|
||||||
|
repeat(before.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_DEL) }
|
||||||
|
repeat(after.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_FORWARD_DEL) }
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
override fun sendKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event)
|
||||||
|
override fun performEditorAction(action: Int): Boolean { key(KeyEvent.KEYCODE_ENTER); return true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onKeyDown(code: Int, event: KeyEvent): Boolean {
|
||||||
|
when (code) {
|
||||||
|
KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_DEL,
|
||||||
|
KeyEvent.KEYCODE_FORWARD_DEL, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> key(code)
|
||||||
|
else -> {
|
||||||
|
val point = event.unicodeChar
|
||||||
|
if (point <= 0) return super.onKeyDown(code, event)
|
||||||
|
input(0, String(Character.toChars(point)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
package cy.hexor.tsunagi
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.DnsResolver
|
||||||
|
import android.net.Network
|
||||||
|
import android.net.LinkProperties
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.NetworkRequest
|
||||||
|
import android.net.VpnService
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.CancellationSignal
|
||||||
|
import android.os.Looper
|
||||||
|
import android.os.ParcelFileDescriptor
|
||||||
|
import android.system.OsConstants
|
||||||
|
import java.util.concurrent.CompletableFuture
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class MeshVpn : VpnService() {
|
||||||
|
companion object {
|
||||||
|
const val STOP_VPN = "cy.hexor.tsunagi.STOP_VPN"
|
||||||
|
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
|
||||||
|
private const val NOTIFICATION_ID = 1
|
||||||
|
private const val EXIT_CHANNEL = "exit-node"
|
||||||
|
}
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
private val notifications by lazy { getSystemService(NotificationManager::class.java) }
|
||||||
|
@Volatile private var instance = 0L
|
||||||
|
private var closed = false
|
||||||
|
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
|
||||||
|
@Volatile private var upstream: Network? = null
|
||||||
|
private var watching = false
|
||||||
|
private val changes = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) = useUnderlay(network)
|
||||||
|
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
|
||||||
|
if (network == upstream && !closed) updateAddresses(properties)
|
||||||
|
}
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
if (network != upstream || closed) return
|
||||||
|
upstream = null
|
||||||
|
// Keep the binding to the lost network until its replacement is ready.
|
||||||
|
// Falling back to the default network here could send iroh into its own TUN.
|
||||||
|
setUnderlyingNetworks(emptyArray())
|
||||||
|
physicalAddresses = ""
|
||||||
|
Native.networkChanged(instance, "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var physicalAddresses = ""
|
||||||
|
private fun addresses(properties: LinkProperties?) = properties?.linkAddresses.orEmpty()
|
||||||
|
.mapNotNull { it.address.hostAddress?.substringBefore('%') }.distinct().take(32).joinToString(",")
|
||||||
|
private fun updateAddresses(properties: LinkProperties) {
|
||||||
|
val next = addresses(properties)
|
||||||
|
if (next == physicalAddresses) return
|
||||||
|
physicalAddresses = next
|
||||||
|
Native.networkChanged(instance, next)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized private fun useUnderlay(network: Network) {
|
||||||
|
if (closed || !connectivity.bindProcessToNetwork(network)) return
|
||||||
|
upstream = network
|
||||||
|
setUnderlyingNetworks(arrayOf(network))
|
||||||
|
physicalAddresses = addresses(connectivity.getLinkProperties(network))
|
||||||
|
if (instance == 0L) {
|
||||||
|
Native.trust(applicationContext)
|
||||||
|
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses)
|
||||||
|
} else Native.networkChanged(instance, physicalAddresses)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
when (intent?.action) {
|
||||||
|
STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY }
|
||||||
|
DISCONNECT_EXIT -> {
|
||||||
|
val ids = intent.data?.pathSegments.orEmpty()
|
||||||
|
if (watching && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
|
||||||
|
if (!Native.disconnectExit(instance, ids[0], ids[1])) {
|
||||||
|
android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
} else if (!watching) stopSelf(startId)
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (watching) {
|
||||||
|
if (Native.failed(instance)) {
|
||||||
|
Native.stop(instance)
|
||||||
|
instance = 0
|
||||||
|
upstream?.let(::useUnderlay)
|
||||||
|
}
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
notifications.createNotificationChannel(NotificationChannel("vpn", "VPN", NotificationManager.IMPORTANCE_LOW))
|
||||||
|
notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW))
|
||||||
|
val startup = notification("vpn").setContentTitle("Starting mesh VPN")
|
||||||
|
if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
|
||||||
|
startForeground(NOTIFICATION_ID, startup.build())
|
||||||
|
watching = true
|
||||||
|
connectivity.requestNetwork(NetworkRequest.Builder()
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper()))
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notification(channel: String): Notification.Builder {
|
||||||
|
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
return Notification.Builder(this, channel).setSmallIcon(R.drawable.tsunagi)
|
||||||
|
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true).setShowWhen(false)
|
||||||
|
.setCategory(Notification.CATEGORY_SERVICE)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rust publishes a change even when the activity is closed. Android holds its
|
||||||
|
// own service binding for an established TUN, so mesh-only mode can leave
|
||||||
|
// foreground promotion and remove the app's notification.
|
||||||
|
fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String) {
|
||||||
|
main.post {
|
||||||
|
if (closed || session != instance) return@post
|
||||||
|
if (peer.isEmpty()) {
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
|
return@post
|
||||||
|
}
|
||||||
|
val target = android.net.Uri.Builder().scheme("tsunagi").authority("exit")
|
||||||
|
.appendPath(network).appendPath(peer).build()
|
||||||
|
val disconnect = PendingIntent.getService(this, 1,
|
||||||
|
Intent(this, MeshVpn::class.java).setAction(DISCONNECT_EXIT).setData(target).putExtra("instance", session),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
val notice = notification(EXIT_CHANNEL).setContentTitle(title).setContentText(text)
|
||||||
|
.addAction(Notification.Action.Builder(null, "Disconnect exit node", disconnect).build())
|
||||||
|
if (Build.VERSION.SDK_INT >= 31) notice.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
|
||||||
|
startForeground(NOTIFICATION_ID, notice.build())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called from Rust with the exhaustive local plan; detachFd transfers ownership.
|
||||||
|
@Synchronized fun establishTun(addresses: String, routes: String, dns: String, mtu: Int, fullTunnel: Boolean): Int {
|
||||||
|
if (closed) return -1
|
||||||
|
val builder = Builder().setSession("tsunagi").setMtu(mtu).setBlocking(false)
|
||||||
|
builder.setUnderlyingNetworks(upstream?.let { arrayOf(it) } ?: emptyArray())
|
||||||
|
addresses.split(',').forEach { builder.addAddress(it.substringBefore('/'), it.substringAfter('/').toInt()) }
|
||||||
|
routes.split(',').forEach { builder.addRoute(it.substringBefore('/'), it.substringAfter('/').toInt()) }
|
||||||
|
if (dns.isNotEmpty()) builder.addDnsServer(dns)
|
||||||
|
// Mesh exits currently carry IPv4. Android blocks an unconfigured family
|
||||||
|
// unless explicitly allowed. In split mode ordinary IPv6 should pass.
|
||||||
|
if (!fullTunnel) builder.allowFamily(OsConstants.AF_INET6)
|
||||||
|
return builder.establish()?.detachFd() ?: -1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called on a bounded Rust blocking worker, never on the UI or TUN reader.
|
||||||
|
@android.annotation.TargetApi(29)
|
||||||
|
fun resolveDns(query: ByteArray): ByteArray? {
|
||||||
|
val network = upstream ?: return null
|
||||||
|
val result = CompletableFuture<ByteArray>()
|
||||||
|
val cancel = CancellationSignal()
|
||||||
|
return try {
|
||||||
|
DnsResolver.getInstance().rawQuery(network, query, DnsResolver.FLAG_EMPTY, { it.run() }, cancel,
|
||||||
|
object : DnsResolver.Callback<ByteArray> {
|
||||||
|
override fun onAnswer(answer: ByteArray, rcode: Int) { result.complete(answer) }
|
||||||
|
override fun onError(error: DnsResolver.DnsException) { result.completeExceptionally(error) }
|
||||||
|
})
|
||||||
|
result.get(4, TimeUnit.SECONDS)
|
||||||
|
} catch (_: Exception) { null } finally { cancel.cancel() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Android 8 and 9 expose only address lookups through their system resolver.
|
||||||
|
fun resolveAddresses(host: String): String? = try {
|
||||||
|
upstream?.getAllByName(host)?.mapNotNull { it.hostAddress }?.joinToString(",")
|
||||||
|
} catch (_: java.net.UnknownHostException) { null }
|
||||||
|
|
||||||
|
// The endpoint uses the physical network. This one explicitly selected TCP
|
||||||
|
// socket must instead follow the same VPN as applications using the VIP.
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
fun bindOverlaySocket(fd: Int, source: String): Boolean {
|
||||||
|
val vpn = connectivity.allNetworks.firstOrNull { network ->
|
||||||
|
connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true &&
|
||||||
|
connectivity.getLinkProperties(network)?.linkAddresses?.any { it.address.hostAddress == source } == true
|
||||||
|
} ?: return false
|
||||||
|
return try {
|
||||||
|
ParcelFileDescriptor.fromFd(fd).use { vpn.bindSocket(it.fileDescriptor) }
|
||||||
|
true
|
||||||
|
} catch (_: java.io.IOException) { false }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onRevoke() { shutdown(); stopSelf() }
|
||||||
|
override fun onDestroy() { shutdown(); super.onDestroy() }
|
||||||
|
@Synchronized private fun shutdown() {
|
||||||
|
if (closed) return
|
||||||
|
closed = true
|
||||||
|
if (watching) connectivity.unregisterNetworkCallback(changes)
|
||||||
|
if (instance != 0L) Native.stop(instance)
|
||||||
|
connectivity.bindProcessToNetwork(null)
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package cy.hexor.tsunagi
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
|
||||||
|
/** OS entry points. Network commands and all views live in the Rust library. */
|
||||||
|
internal object Native {
|
||||||
|
init { System.loadLibrary("tsunagi_android") }
|
||||||
|
external fun trust(context: Context)
|
||||||
|
external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String): Long
|
||||||
|
external fun failed(instance: Long): Boolean
|
||||||
|
external fun stop(instance: Long)
|
||||||
|
external fun disconnectExit(instance: Long, network: String, peer: String): Boolean
|
||||||
|
external fun networkChanged(instance: Long, addresses: String)
|
||||||
|
|
||||||
|
external fun surface()
|
||||||
|
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long
|
||||||
|
external fun touch(action: Int, id: Int, x: Float, y: Float)
|
||||||
|
external fun input(kind: Int, value: String)
|
||||||
|
external fun key(key: Int)
|
||||||
|
external fun back(host: MeshSurface)
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="48dp" android:height="48dp" android:viewportWidth="128" android:viewportHeight="128">
|
||||||
|
<path android:fillColor="#2f80d8" android:pathData="M64,8a56,56 0,1 1,0 112a56,56 0,1 1,0 -112" />
|
||||||
|
<path android:strokeColor="#ffffff" android:strokeWidth="7" android:pathData="M64,34a30,30 0,1 1,0 60a30,30 0,1 1,0 -60" />
|
||||||
|
<path android:fillColor="#ffffff" android:pathData="M64,55a9,9 0,1 1,0 18a9,9 0,1 1,0 -18" />
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
android.useAndroidX=true
|
||||||
|
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
+248
@@ -0,0 +1,248 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015 the original authors.
|
||||||
|
#
|
||||||
|
# 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
|
||||||
|
#
|
||||||
|
# https://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.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+93
@@ -0,0 +1,93 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||||
|
rootProject.name = 'tsunagi-android'
|
||||||
|
include ':app'
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
apk=${1:?expected an APK}
|
||||||
|
version_name=${2:?expected the release version}
|
||||||
|
version_code=${3:?expected the Android version code}
|
||||||
|
build_tools=${4:?expected the Android SDK Build Tools directory}
|
||||||
|
|
||||||
|
badging=$("$build_tools/aapt" dump badging "$apk")
|
||||||
|
package="package: name='cy.hexor.tsunagi' versionCode='$version_code' versionName='$version_name'"
|
||||||
|
if [[ "$badging" != "$package "* ]]; then
|
||||||
|
echo "Expected tsunagi $version_name (version code $version_code) in the APK manifest" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if grep -Fxq 'application-debuggable' <<< "$badging"; then
|
||||||
|
echo "The release APK enables Android debugging" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! grep -Fxq "native-code: 'arm64-v8a'" <<< "$badging"; then
|
||||||
|
echo "Expected an arm64-v8a APK" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
library=$(mktemp)
|
||||||
|
trap 'rm -f "$library"' EXIT
|
||||||
|
unzip -p "$apk" lib/arm64-v8a/libtsunagi_android.so > "$library"
|
||||||
|
if [[ "$(LC_ALL=C file -b "$library")" != *"ARM aarch64"*", stripped"* ]]; then
|
||||||
|
echo "Expected a stripped ARM64 tsunagi native library" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
"$build_tools/zipalign" -c -P 16 4 "$apk"
|
||||||
|
"$build_tools/apksigner" verify --verbose --print-certs "$apk"
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsunagi-android"
|
||||||
|
version = "1.0.0"
|
||||||
|
description = "Android VPN client and egui views for tsunagi."
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.0" }
|
||||||
|
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||||
|
tsunagi-core = { path = "../tsunagi-core" }
|
||||||
|
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||||
|
egui = "0.31"
|
||||||
|
egui-phosphor = "0.9"
|
||||||
|
tokio.workspace = true
|
||||||
|
bytes.workspace = true
|
||||||
|
zeroize = "1.9"
|
||||||
|
simple-dns = "0.12"
|
||||||
|
|
||||||
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
rand = "0.10"
|
||||||
|
smoltcp = { version = "0.12", default-features = false, features = ["std", "medium-ip", "proto-ipv4", "socket-tcp", "socket-udp"] }
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "android")'.dependencies]
|
||||||
|
egui_glow = { version = "0.31", default-features = false }
|
||||||
|
jni = "0.21"
|
||||||
|
iroh.workspace = true
|
||||||
|
jni-verifier = { package = "jni", version = "0.22" }
|
||||||
|
rustls-platform-verifier = "0.7"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile.workspace = true
|
||||||
|
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets.
|
||||||
|
use crate::view::{Phone, SystemAction};
|
||||||
|
use egui::{
|
||||||
|
Event, ImeEvent, Key, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase,
|
||||||
|
};
|
||||||
|
use egui_glow::{Painter, glow};
|
||||||
|
use jni::{
|
||||||
|
JNIEnv,
|
||||||
|
objects::{JObject, JString, JValue},
|
||||||
|
sys::{jfloat, jint, jlong},
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
cell::RefCell,
|
||||||
|
ffi::{c_char, c_void},
|
||||||
|
sync::Arc,
|
||||||
|
time::Instant,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[link(name = "EGL")]
|
||||||
|
unsafe extern "C" {
|
||||||
|
fn eglGetProcAddress(name: *const c_char) -> *const c_void;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Display {
|
||||||
|
painter: Painter,
|
||||||
|
ctx: egui::Context,
|
||||||
|
ui: Phone,
|
||||||
|
events: Vec<Event>,
|
||||||
|
primary: Option<i32>,
|
||||||
|
start: Instant,
|
||||||
|
ime: i32,
|
||||||
|
exit_active: bool,
|
||||||
|
}
|
||||||
|
thread_local! { static DISPLAY: RefCell<Option<Display>> = const {RefCell::new(None)}; }
|
||||||
|
|
||||||
|
fn with_display<T: Default>(f: impl FnOnce(&mut Display) -> T) -> T {
|
||||||
|
DISPLAY.with_borrow_mut(|d| d.as_mut().map(f).unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) {
|
||||||
|
// SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current.
|
||||||
|
let gl = unsafe {
|
||||||
|
glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr()))
|
||||||
|
};
|
||||||
|
let Ok(painter) = Painter::new(Arc::new(gl), "", None, false) else {
|
||||||
|
let _ = env.throw_new(
|
||||||
|
"java/lang/IllegalStateException",
|
||||||
|
"Could not initialise OpenGL ES",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let ctx = egui::Context::default();
|
||||||
|
crate::view::configure(&ctx);
|
||||||
|
DISPLAY.with_borrow_mut(|d| {
|
||||||
|
// If Android discarded the old EGL context, its GPU resources are already gone.
|
||||||
|
let ui = d.take().map(|old| old.ui).unwrap_or_default();
|
||||||
|
*d = Some(Display {
|
||||||
|
painter,
|
||||||
|
ctx,
|
||||||
|
ui,
|
||||||
|
events: Vec::new(),
|
||||||
|
primary: None,
|
||||||
|
start: Instant::now(),
|
||||||
|
ime: -1,
|
||||||
|
exit_active: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
host: JObject,
|
||||||
|
w: jint,
|
||||||
|
h: jint,
|
||||||
|
scale: jfloat,
|
||||||
|
) -> jlong {
|
||||||
|
with_display(|d| {
|
||||||
|
let size = egui::vec2(w as f32, h as f32) / scale;
|
||||||
|
let mut input = egui::RawInput {
|
||||||
|
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
|
||||||
|
events: std::mem::take(&mut d.events),
|
||||||
|
time: Some(d.start.elapsed().as_secs_f64()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
if let Some(info) = input.viewports.get_mut(&egui::ViewportId::ROOT) {
|
||||||
|
info.native_pixels_per_point = Some(scale);
|
||||||
|
}
|
||||||
|
let mut action = None;
|
||||||
|
let state = super::status();
|
||||||
|
let exit_active = matches!(&state, crate::service::State::Ready(report, _) if report.networks.iter().any(|n| n.active && n.exit.via.is_some()));
|
||||||
|
if exit_active && !d.exit_active {
|
||||||
|
let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]);
|
||||||
|
}
|
||||||
|
d.exit_active = exit_active;
|
||||||
|
let output = d.ctx.run(input, |ctx| {
|
||||||
|
action = d.ui.draw(ctx, &state, super::send);
|
||||||
|
});
|
||||||
|
if let Some(action) = action {
|
||||||
|
let method = match action {
|
||||||
|
SystemAction::Start => "startVpn",
|
||||||
|
SystemAction::Stop => "stopVpn",
|
||||||
|
SystemAction::PasteSecret => "pasteSecret",
|
||||||
|
SystemAction::Finish => "closeScreen",
|
||||||
|
};
|
||||||
|
let _ = env.call_method(&host, method, "()V", &[]);
|
||||||
|
}
|
||||||
|
if let Some(secret) = d.ui.take_copied_secret()
|
||||||
|
&& let Ok(text) = env.new_string(secret.as_str())
|
||||||
|
{
|
||||||
|
let _ = env.call_method(
|
||||||
|
&host,
|
||||||
|
"copySecret",
|
||||||
|
"(Ljava/lang/String;)V",
|
||||||
|
&[JValue::Object(&text)],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for command in output.platform_output.commands {
|
||||||
|
let (method, value) = match command {
|
||||||
|
egui::OutputCommand::CopyText(text) => ("copyText", text),
|
||||||
|
egui::OutputCommand::OpenUrl(url) => ("openUrl", url.url),
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
if let Ok(text) = env.new_string(value) {
|
||||||
|
let _ = env.call_method(
|
||||||
|
&host,
|
||||||
|
method,
|
||||||
|
"(Ljava/lang/String;)V",
|
||||||
|
&[JValue::Object(&text)],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ime = if output.platform_output.ime.is_none() {
|
||||||
|
0
|
||||||
|
} else if d.ui.secret_focused(&d.ctx) {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
};
|
||||||
|
if ime != d.ime {
|
||||||
|
d.ime = ime;
|
||||||
|
let _ = env.call_method(&host, "keyboard", "(I)V", &[JValue::Int(ime)]);
|
||||||
|
}
|
||||||
|
let ppp = output.pixels_per_point;
|
||||||
|
let primitives = d.ctx.tessellate(output.shapes, ppp);
|
||||||
|
let pixels = [w as u32, h as u32];
|
||||||
|
d.painter.clear(pixels, [0.1, 0.1, 0.1, 1.0]);
|
||||||
|
d.painter
|
||||||
|
.paint_and_update_textures(pixels, ppp, &primitives, &output.textures_delta);
|
||||||
|
output
|
||||||
|
.viewport_output
|
||||||
|
.get(&egui::ViewportId::ROOT)
|
||||||
|
.map_or(1000, |v| {
|
||||||
|
v.repaint_delay.as_millis().clamp(16, 1000) as jlong
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_touch(
|
||||||
|
_: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
action: jint,
|
||||||
|
id: jint,
|
||||||
|
x: jfloat,
|
||||||
|
y: jfloat,
|
||||||
|
) {
|
||||||
|
with_display(|d| {
|
||||||
|
let pos = egui::pos2(x, y);
|
||||||
|
let phase = match action {
|
||||||
|
0 => TouchPhase::Start,
|
||||||
|
1 => TouchPhase::Move,
|
||||||
|
2 => TouchPhase::End,
|
||||||
|
_ => TouchPhase::Cancel,
|
||||||
|
};
|
||||||
|
d.events.push(Event::Touch {
|
||||||
|
device_id: TouchDeviceId(0),
|
||||||
|
id: TouchId(id as u64),
|
||||||
|
phase,
|
||||||
|
pos,
|
||||||
|
force: None,
|
||||||
|
});
|
||||||
|
if phase == TouchPhase::Start && d.primary.is_none() {
|
||||||
|
d.primary = Some(id);
|
||||||
|
}
|
||||||
|
if d.primary != Some(id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if phase != TouchPhase::Cancel {
|
||||||
|
d.events.push(Event::PointerMoved(pos));
|
||||||
|
}
|
||||||
|
if phase != TouchPhase::Move {
|
||||||
|
if phase == TouchPhase::Cancel {
|
||||||
|
d.events.push(Event::PointerGone);
|
||||||
|
}
|
||||||
|
d.events.push(Event::PointerButton {
|
||||||
|
pos,
|
||||||
|
button: PointerButton::Primary,
|
||||||
|
pressed: phase == TouchPhase::Start,
|
||||||
|
modifiers: Modifiers::NONE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if matches!(phase, TouchPhase::Cancel | TouchPhase::End) {
|
||||||
|
d.events.push(Event::PointerGone);
|
||||||
|
d.primary = None;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_input(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
kind: jint,
|
||||||
|
value: JString,
|
||||||
|
) {
|
||||||
|
let Ok(text) = env.get_string(&value) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let text = String::from(text);
|
||||||
|
with_display(|d| match kind {
|
||||||
|
0 => d.events.push(Event::Text(text)),
|
||||||
|
1 => d.events.push(Event::Ime(ImeEvent::Enabled)),
|
||||||
|
2 => d.events.push(Event::Ime(ImeEvent::Preedit(text))),
|
||||||
|
3 => {
|
||||||
|
d.events.push(Event::Ime(ImeEvent::Commit(text)));
|
||||||
|
d.events.push(Event::Ime(ImeEvent::Disabled));
|
||||||
|
}
|
||||||
|
4 => d.ui.paste_secret(text),
|
||||||
|
5 => d.ui.error(text),
|
||||||
|
_ => {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_key(_: JNIEnv, _: JObject, key: jint) {
|
||||||
|
let key = match key {
|
||||||
|
67 => Key::Backspace,
|
||||||
|
112 => Key::Delete,
|
||||||
|
66 => Key::Enter,
|
||||||
|
21 => Key::ArrowLeft,
|
||||||
|
22 => Key::ArrowRight,
|
||||||
|
61 => Key::Tab,
|
||||||
|
_ => return,
|
||||||
|
};
|
||||||
|
with_display(|d| {
|
||||||
|
for pressed in [true, false] {
|
||||||
|
d.events.push(Event::Key {
|
||||||
|
key,
|
||||||
|
physical_key: None,
|
||||||
|
pressed,
|
||||||
|
repeat: false,
|
||||||
|
modifiers: Modifiers::NONE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_back(mut env: JNIEnv, _: JObject, host: JObject) {
|
||||||
|
with_display(|d| {
|
||||||
|
if d.ui.back() == Some(SystemAction::Finish) {
|
||||||
|
let _ = env.call_method(&host, "closeScreen", "()V", &[]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
//! Android's physical-network resolver, including its Private DNS policy.
|
||||||
|
use crate::dns::Resolver;
|
||||||
|
use jni::{
|
||||||
|
JNIEnv, JavaVM,
|
||||||
|
objects::{GlobalRef, JByteArray, JString, JValue},
|
||||||
|
};
|
||||||
|
use simple_dns::{CLASS, Packet, PacketFlag, QTYPE, RCODE, ResourceRecord, TYPE, rdata::RData};
|
||||||
|
use std::{net::IpAddr, sync::Arc};
|
||||||
|
|
||||||
|
pub(super) fn resolver(vm: Arc<JavaVM>, service: GlobalRef, sdk: i32) -> Resolver {
|
||||||
|
Resolver::new(move |query| {
|
||||||
|
let mut env = vm.attach_current_thread().ok()?;
|
||||||
|
let response = env.with_local_frame(6, |env| {
|
||||||
|
if sdk < 29 {
|
||||||
|
return legacy(env, &service, query);
|
||||||
|
}
|
||||||
|
let bytes = env.byte_array_from_slice(query)?;
|
||||||
|
let reply = env
|
||||||
|
.call_method(&service, "resolveDns", "([B)[B", &[JValue::Object(&bytes)])?
|
||||||
|
.l()?;
|
||||||
|
if reply.is_null() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let reply = JByteArray::from(reply);
|
||||||
|
if env.get_array_length(&reply)? > i32::from(u16::MAX) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
env.convert_byte_array(reply).map(Some)
|
||||||
|
});
|
||||||
|
if env.exception_check().unwrap_or(false) {
|
||||||
|
let _ = env.exception_clear();
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
response.ok().flatten()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy(
|
||||||
|
env: &mut JNIEnv<'_>,
|
||||||
|
service: &GlobalRef,
|
||||||
|
query: &[u8],
|
||||||
|
) -> jni::errors::Result<Option<Vec<u8>>> {
|
||||||
|
let Some(packet) = Packet::parse(query).ok() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let [question] = packet.questions.as_slice() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let mut reply = Packet::new_reply(packet.id());
|
||||||
|
reply.questions.push(question.clone());
|
||||||
|
reply.set_flags(PacketFlag::RECURSION_AVAILABLE);
|
||||||
|
if packet.has_flags(PacketFlag::RECURSION_DESIRED) {
|
||||||
|
reply.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||||
|
}
|
||||||
|
if matches!(question.qtype, QTYPE::TYPE(TYPE::A | TYPE::AAAA)) {
|
||||||
|
let name = env.new_string(format!("{}.", question.qname))?;
|
||||||
|
let addresses = env
|
||||||
|
.call_method(
|
||||||
|
service,
|
||||||
|
"resolveAddresses",
|
||||||
|
"(Ljava/lang/String;)Ljava/lang/String;",
|
||||||
|
&[JValue::Object(&name)],
|
||||||
|
)?
|
||||||
|
.l()?;
|
||||||
|
if addresses.is_null() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let addresses: String = env.get_string(&JString::from(addresses))?.into();
|
||||||
|
for address in addresses
|
||||||
|
.split(',')
|
||||||
|
.take(128)
|
||||||
|
.filter_map(|s| s.parse::<IpAddr>().ok())
|
||||||
|
{
|
||||||
|
let data = match (question.qtype, address) {
|
||||||
|
(QTYPE::TYPE(TYPE::A), IpAddr::V4(v4)) => RData::A(v4.into()),
|
||||||
|
(QTYPE::TYPE(TYPE::AAAA), IpAddr::V6(v6)) => RData::AAAA(v6.into()),
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
reply.answers.push(ResourceRecord::new(
|
||||||
|
question.qname.clone(),
|
||||||
|
CLASS::IN,
|
||||||
|
0,
|
||||||
|
data,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
*reply.rcode_mut() = RCODE::NotImplemented;
|
||||||
|
}
|
||||||
|
Ok(reply.build_bytes_vec_compressed().ok())
|
||||||
|
}
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
//! Android process entry points. JNI owns references here, never in the core.
|
||||||
|
#![allow(unsafe_code)]
|
||||||
|
mod display;
|
||||||
|
mod dns;
|
||||||
|
use crate::{
|
||||||
|
plan::VpnPlan,
|
||||||
|
service::{Reply, Request, Response, State},
|
||||||
|
tun::AndroidTun,
|
||||||
|
};
|
||||||
|
use jni::{
|
||||||
|
JNIEnv, JavaVM,
|
||||||
|
objects::{GlobalRef, JObject, JString, JValue},
|
||||||
|
sys::jlong,
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
fs::File,
|
||||||
|
io,
|
||||||
|
os::fd::{AsRawFd, FromRawFd, OwnedFd},
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{Arc, Mutex, OnceLock},
|
||||||
|
};
|
||||||
|
use tokio::sync::{mpsc, oneshot, watch};
|
||||||
|
use tsunagi::{Agent, AgentConfig, StoragePaths, TransportPolicy, discovery::MainlineDiscovery};
|
||||||
|
use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin};
|
||||||
|
|
||||||
|
struct Session {
|
||||||
|
id: i64,
|
||||||
|
commands: mpsc::Sender<(Request, Reply)>,
|
||||||
|
state: watch::Receiver<State>,
|
||||||
|
underlay: watch::Sender<Vec<std::net::IpAddr>>,
|
||||||
|
stop: watch::Sender<bool>,
|
||||||
|
}
|
||||||
|
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||||
|
// Stop/start can cross on the Android main thread. The previous agent closes
|
||||||
|
// its fd, endpoint and directory lock before its successor opens that identity.
|
||||||
|
static LIFETIME: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
fn current() -> std::sync::MutexGuard<'static, Option<Session>> {
|
||||||
|
SESSION.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
fn status() -> State {
|
||||||
|
current()
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.state.borrow().clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||||
|
let (reply, result) = oneshot::channel();
|
||||||
|
current()
|
||||||
|
.as_ref()
|
||||||
|
.ok_or("VPN service stopped")?
|
||||||
|
.commands
|
||||||
|
.try_send((Request::Action(cmd), reply))
|
||||||
|
.map_err(|_| "VPN service is busy or stopped".to_owned())?;
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_trust(
|
||||||
|
mut env: jni_verifier::EnvUnowned,
|
||||||
|
_: jni_verifier::objects::JObject,
|
||||||
|
app: jni_verifier::objects::JObject,
|
||||||
|
) {
|
||||||
|
env.with_env(|env| rustls_platform_verifier::android::init_with_env(env, app))
|
||||||
|
.resolve::<jni_verifier::errors::ThrowRuntimeExAndDefault>();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn establish(vm: &JavaVM, service: &GlobalRef, plan: &VpnPlan) -> io::Result<File> {
|
||||||
|
let mut env = vm.attach_current_thread().map_err(io::Error::other)?;
|
||||||
|
let addresses = plan
|
||||||
|
.addresses_in_order()
|
||||||
|
.iter()
|
||||||
|
.map(ToString::to_string)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",");
|
||||||
|
let routes = plan.routes().join(",");
|
||||||
|
let result = env.with_local_frame(6, |env| -> jni::errors::Result<i32> {
|
||||||
|
let addresses = env.new_string(addresses)?;
|
||||||
|
let routes = env.new_string(routes)?;
|
||||||
|
let dns = env.new_string(
|
||||||
|
plan.dns_address()
|
||||||
|
.map(|a| a.to_string())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
)?;
|
||||||
|
env.call_method(
|
||||||
|
service,
|
||||||
|
"establishTun",
|
||||||
|
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)I",
|
||||||
|
&[
|
||||||
|
JValue::Object(&addresses),
|
||||||
|
JValue::Object(&routes),
|
||||||
|
JValue::Object(&dns),
|
||||||
|
JValue::Int(plan.mtu as i32),
|
||||||
|
JValue::Bool(plan.full_tunnel.into()),
|
||||||
|
],
|
||||||
|
)?
|
||||||
|
.i()
|
||||||
|
});
|
||||||
|
if env.exception_check().unwrap_or(false) {
|
||||||
|
let _ = env.exception_clear();
|
||||||
|
return Err(io::Error::other(
|
||||||
|
"Android could not establish the VPN. Check the VPN permission.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let fd = result.map_err(io::Error::other)?;
|
||||||
|
if fd < 0 {
|
||||||
|
return Err(io::Error::other("Android revoked the VPN permission"));
|
||||||
|
}
|
||||||
|
// SAFETY: establishTun transferred exclusive ownership with detachFd().
|
||||||
|
Ok(File::from(unsafe { OwnedFd::from_raw_fd(fd) }))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
service: JObject,
|
||||||
|
app: JObject,
|
||||||
|
state_dir: JString,
|
||||||
|
cache_dir: JString,
|
||||||
|
addresses: JString,
|
||||||
|
) -> jlong {
|
||||||
|
let result = (|| -> Result<i64, Box<dyn std::error::Error>> {
|
||||||
|
// Keep the application (never an activity) alive for DNS throughout the process.
|
||||||
|
static APPLICATION: OnceLock<GlobalRef> = OnceLock::new();
|
||||||
|
let vm = Arc::new(env.get_java_vm()?);
|
||||||
|
let application = env.new_global_ref(app)?;
|
||||||
|
if APPLICATION.set(application.clone()).is_ok() {
|
||||||
|
// SAFETY: the VM and this stored global reference live until process exit.
|
||||||
|
unsafe {
|
||||||
|
iroh::dns::install_android_jni_context(
|
||||||
|
vm.get_java_vm_pointer().cast(),
|
||||||
|
application.as_obj().as_raw().cast(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let service = env.new_global_ref(service)?;
|
||||||
|
let state_dir: String = env.get_string(&state_dir)?.into();
|
||||||
|
let cache_dir: String = env.get_string(&cache_dir)?.into();
|
||||||
|
let paths = StoragePaths::new(PathBuf::from(state_dir), PathBuf::from(cache_dir));
|
||||||
|
let tun_vm = vm.clone();
|
||||||
|
let tun_service = service.clone();
|
||||||
|
let notice_vm = vm.clone();
|
||||||
|
let notice_service = service.clone();
|
||||||
|
let sdk = env
|
||||||
|
.get_static_field("android/os/Build$VERSION", "SDK_INT", "I")?
|
||||||
|
.i()?;
|
||||||
|
let dns = dns::resolver(vm.clone(), service.clone(), sdk);
|
||||||
|
let factory = AndroidTun::new(
|
||||||
|
dns.clone(),
|
||||||
|
move |plan| establish(&tun_vm, &tun_service, plan),
|
||||||
|
move |socket, source| {
|
||||||
|
let mut env = vm.attach_current_thread().map_err(io::Error::other)?;
|
||||||
|
let result = env.with_local_frame(3, |env| -> jni::errors::Result<bool> {
|
||||||
|
let source = env.new_string(source.to_string())?;
|
||||||
|
env.call_method(
|
||||||
|
&service,
|
||||||
|
"bindOverlaySocket",
|
||||||
|
"(ILjava/lang/String;)Z",
|
||||||
|
&[JValue::Int(socket.as_raw_fd()), JValue::Object(&source)],
|
||||||
|
)?
|
||||||
|
.z()
|
||||||
|
});
|
||||||
|
if env.exception_check().unwrap_or(false) {
|
||||||
|
let _ = env.exception_clear();
|
||||||
|
return Err(io::Error::other("VPN socket binding failed"));
|
||||||
|
}
|
||||||
|
if result.map_err(io::Error::other)? {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(io::Error::other("VPN network is unavailable"))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let addresses: String = env.get_string(&addresses)?.into();
|
||||||
|
let (underlay, physical) = watch::channel(underlay_ips(&addresses));
|
||||||
|
let (commands, rx) = mpsc::channel(16);
|
||||||
|
let (state, state_rx) = watch::channel(State::Starting);
|
||||||
|
let (stop, stopped) = watch::channel(false);
|
||||||
|
static NEXT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
|
||||||
|
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
let mut slot = current();
|
||||||
|
if let Some(old) = slot.as_ref() {
|
||||||
|
old.stop.send_replace(true);
|
||||||
|
}
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name("tsunagi-agent".into())
|
||||||
|
.spawn(move || {
|
||||||
|
let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if *stopped.borrow() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let run = || -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(2)
|
||||||
|
.enable_all()
|
||||||
|
.build()?;
|
||||||
|
runtime.block_on(async {
|
||||||
|
let wg = WireguardPlugin::open(WireguardConfig::new(
|
||||||
|
paths.state_dir.join("wg-quic"),
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
|
let config = AgentConfig::new(paths)
|
||||||
|
.with_transport(TransportPolicy::N0Defaults)
|
||||||
|
.with_dht(MainlineDiscovery::default())
|
||||||
|
.with_interface(Arc::new(factory), "tsunagi-vpn", DEFAULT_MTU)
|
||||||
|
.with_tunnel(wg.clone());
|
||||||
|
let (config, carriers) = tsunagi_runtime::Carriers::configure(
|
||||||
|
config,
|
||||||
|
&[],
|
||||||
|
Some(physical),
|
||||||
|
|_| Vec::new(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let agent = Agent::spawn(config).await?;
|
||||||
|
let _listeners = carriers.listen(&agent);
|
||||||
|
crate::service::serve(agent, wg, dns, rx, &state, stopped, |notice| {
|
||||||
|
update_exit_notification(¬ice_vm, ¬ice_service, id, notice);
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
if let Err(e) = run() {
|
||||||
|
state.send_replace(State::Error(e.to_string()));
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
*slot = Some(Session {
|
||||||
|
id,
|
||||||
|
commands,
|
||||||
|
state: state_rx,
|
||||||
|
underlay,
|
||||||
|
stop,
|
||||||
|
});
|
||||||
|
Ok(id)
|
||||||
|
})();
|
||||||
|
match result {
|
||||||
|
Ok(id) => id,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = env.throw_new("java/lang/IllegalStateException", e.to_string());
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_exit_notification(
|
||||||
|
vm: &JavaVM,
|
||||||
|
service: &GlobalRef,
|
||||||
|
id: i64,
|
||||||
|
notice: Option<&crate::service::ExitNotice>,
|
||||||
|
) {
|
||||||
|
let Ok(mut env) = vm.attach_current_thread() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let _ = env.with_local_frame(6, |env| -> jni::errors::Result<()> {
|
||||||
|
let network = env.new_string(notice.map_or("", |n| &n.network))?;
|
||||||
|
let peer = env.new_string(notice.map_or("", |n| &n.peer))?;
|
||||||
|
let title = env.new_string(
|
||||||
|
notice
|
||||||
|
.map(|n| format!("Exit node · {}", n.name))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
)?;
|
||||||
|
let text = env.new_string(
|
||||||
|
notice
|
||||||
|
.map(|n| {
|
||||||
|
if n.online {
|
||||||
|
format!("IPv4 internet via {}", n.network_name)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"{} · Exit offline. IPv4 internet is blocked.",
|
||||||
|
n.network_name
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_default(),
|
||||||
|
)?;
|
||||||
|
env.call_method(
|
||||||
|
service,
|
||||||
|
"updateExitNotification",
|
||||||
|
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||||
|
&[
|
||||||
|
JValue::Long(id),
|
||||||
|
JValue::Object(&network),
|
||||||
|
JValue::Object(&peer),
|
||||||
|
JValue::Object(&title),
|
||||||
|
JValue::Object(&text),
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
if env.exception_check().unwrap_or(false) {
|
||||||
|
let _ = env.exception_clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_disconnectExit(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
id: jlong,
|
||||||
|
network: JString,
|
||||||
|
peer: JString,
|
||||||
|
) -> jni::sys::jboolean {
|
||||||
|
let (Ok(network), Ok(peer)) = (env.get_string(&network), env.get_string(&peer)) else {
|
||||||
|
return false.into();
|
||||||
|
};
|
||||||
|
current()
|
||||||
|
.as_ref()
|
||||||
|
.filter(|s| s.id == id)
|
||||||
|
.is_some_and(|s| {
|
||||||
|
s.commands
|
||||||
|
.try_send((
|
||||||
|
Request::DisconnectExit {
|
||||||
|
network: network.into(),
|
||||||
|
peer: peer.into(),
|
||||||
|
},
|
||||||
|
oneshot::channel().0,
|
||||||
|
))
|
||||||
|
.is_ok()
|
||||||
|
})
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_failed(
|
||||||
|
_: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
id: jlong,
|
||||||
|
) -> jni::sys::jboolean {
|
||||||
|
current()
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|s| s.id == id && matches!(*s.state.borrow(), State::Error(_)))
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_stop(_: JNIEnv, _: JObject, id: jlong) {
|
||||||
|
let mut slot = current();
|
||||||
|
if slot.as_ref().is_some_and(|s| s.id == id)
|
||||||
|
&& let Some(session) = slot.take()
|
||||||
|
{
|
||||||
|
session.stop.send_replace(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
|
||||||
|
addresses
|
||||||
|
.split(',')
|
||||||
|
.take(32)
|
||||||
|
.filter_map(|s| s.parse().ok())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_networkChanged(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
id: jlong,
|
||||||
|
addresses: JString,
|
||||||
|
) {
|
||||||
|
let Ok(raw) = env.get_string(&addresses) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if let Some(s) = current().as_ref().filter(|s| s.id == id) {
|
||||||
|
s.underlay.send_replace(underlay_ips(&String::from(raw)));
|
||||||
|
let _ = s
|
||||||
|
.commands
|
||||||
|
.try_send((Request::NetworkChanged, oneshot::channel().0));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
//! Device-local split DNS. Only questions outside the signed mesh zones reach Android's resolver.
|
||||||
|
use simple_dns::{Packet, PacketFlag, RCODE};
|
||||||
|
use std::{net::Ipv4Addr, sync::Arc, time::Duration};
|
||||||
|
use tokio::sync::{Semaphore, watch};
|
||||||
|
use tsunagi::dns::{
|
||||||
|
Zones,
|
||||||
|
server::{MAX_MESSAGE_LEN, Resolution, parse_message, resolve},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(crate) mod stack;
|
||||||
|
|
||||||
|
type Upstream = dyn Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync;
|
||||||
|
|
||||||
|
/// One view of all joined zones, shared across TUN replacements.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Resolver {
|
||||||
|
zones: watch::Sender<Option<Arc<Zones>>>,
|
||||||
|
listening: watch::Sender<Option<Ipv4Addr>>,
|
||||||
|
upstream: Arc<Upstream>,
|
||||||
|
pending: Arc<Semaphore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Resolver {
|
||||||
|
/// The platform callback resolves a wire question on the selected physical network.
|
||||||
|
pub fn new(upstream: impl Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync + 'static) -> Self {
|
||||||
|
Self {
|
||||||
|
zones: watch::channel(None).0,
|
||||||
|
listening: watch::channel(None).0,
|
||||||
|
upstream: Arc::new(upstream),
|
||||||
|
pending: Arc::new(Semaphore::new(16)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Withhold forwarding while configured zones are loading or changing.
|
||||||
|
pub fn replace(&self, zones: Option<Zones>) {
|
||||||
|
self.zones.send_replace(zones.map(Arc::new));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(crate) fn publish(&self, address: Option<Ipv4Addr>) {
|
||||||
|
self.listening.send_replace(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn refresh(&self, networks: &[tsunagi::NetworkStatus]) -> tsunagi::ipc::DnsReport {
|
||||||
|
let view = tsunagi::dns::RosterZones::from_networks(networks);
|
||||||
|
let names = view.zones.names() as u32;
|
||||||
|
self.replace(Some(view.zones));
|
||||||
|
let address = *self.listening.borrow();
|
||||||
|
tsunagi::ipc::DnsReport {
|
||||||
|
listening: address.map(|ip| format!("{ip}:53")).into_iter().collect(),
|
||||||
|
publish_error: (address.is_none() && !view.labels.is_empty())
|
||||||
|
.then(|| "Waiting for a VPN interface with a DNS address.".into()),
|
||||||
|
zones: view.labels,
|
||||||
|
zone_warnings: view.warnings,
|
||||||
|
names,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answer a local DNS request. Slow public lookups never block a mesh answer.
|
||||||
|
pub async fn answer(&self, query: &[u8]) -> Option<Vec<u8>> {
|
||||||
|
if query.len() > MAX_MESSAGE_LEN {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let zones = self.zones.borrow().clone();
|
||||||
|
let Some(zones) = zones else {
|
||||||
|
let question = parse_message(query)?;
|
||||||
|
if question.has_flags(PacketFlag::RESPONSE) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
return error_reply(&question, RCODE::ServerFailure);
|
||||||
|
};
|
||||||
|
match resolve(&zones, query)? {
|
||||||
|
Resolution::Local(reply) => Some(reply),
|
||||||
|
Resolution::Outside(_) => {
|
||||||
|
let question = parse_message(query)?;
|
||||||
|
if let Ok(permit) = self.pending.clone().try_acquire_owned() {
|
||||||
|
let upstream = self.upstream.clone();
|
||||||
|
let wire = query.to_vec();
|
||||||
|
let job = tokio::task::spawn_blocking(move || {
|
||||||
|
let _permit = permit;
|
||||||
|
upstream(&wire)
|
||||||
|
});
|
||||||
|
if let Ok(Ok(Some(mut wire))) =
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), job).await
|
||||||
|
&& wire.len() <= usize::from(u16::MAX)
|
||||||
|
&& parse_message(&wire).is_some_and(|p| {
|
||||||
|
let [received] = p.questions.as_slice() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let sent = &question.questions[0]; // Resolution::Outside has exactly one IN question.
|
||||||
|
p.has_flags(PacketFlag::RESPONSE)
|
||||||
|
&& received.qtype == sent.qtype
|
||||||
|
&& received.qclass == sent.qclass
|
||||||
|
&& received
|
||||||
|
.qname
|
||||||
|
.to_string()
|
||||||
|
.eq_ignore_ascii_case(&sent.qname.to_string())
|
||||||
|
})
|
||||||
|
{
|
||||||
|
// Android's upstream transaction may have used its own ID.
|
||||||
|
wire[..2].copy_from_slice(&question.id().to_be_bytes());
|
||||||
|
return Some(wire);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
error_reply(&question, RCODE::ServerFailure)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_reply(query: &Packet<'_>, code: RCODE) -> Option<Vec<u8>> {
|
||||||
|
let mut answer = Packet::new_reply(query.id());
|
||||||
|
answer.questions.clone_from(&query.questions);
|
||||||
|
if query.has_flags(PacketFlag::RECURSION_DESIRED) {
|
||||||
|
answer.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||||
|
}
|
||||||
|
answer.set_flags(PacketFlag::RECURSION_AVAILABLE);
|
||||||
|
*answer.rcode_mut() = code;
|
||||||
|
answer.build_bytes_vec_compressed().ok()
|
||||||
|
}
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
//! A DNS-only endpoint on the application side of one Android TUN descriptor.
|
||||||
|
//! The kernel reserves port 53. smoltcp terminates UDP and TCP without root.
|
||||||
|
use super::Resolver;
|
||||||
|
use smoltcp::{
|
||||||
|
iface::{Config, Interface, SocketHandle, SocketSet},
|
||||||
|
phy::{self, Device, DeviceCapabilities, Medium},
|
||||||
|
socket::{tcp, udp},
|
||||||
|
time::Instant as NetTime,
|
||||||
|
wire::{HardwareAddress, IpAddress, IpCidr, IpEndpoint},
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
fs::File,
|
||||||
|
io::Write,
|
||||||
|
net::{IpAddr, Ipv4Addr},
|
||||||
|
sync::Arc,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
io::{Interest, unix::AsyncFd},
|
||||||
|
sync::mpsc,
|
||||||
|
task::{JoinHandle, JoinSet},
|
||||||
|
};
|
||||||
|
use tsunagi::dns::server::{MAX_MESSAGE_LEN, truncate_for_udp};
|
||||||
|
|
||||||
|
const PORT: u16 = 53;
|
||||||
|
const QUEUE: usize = 32;
|
||||||
|
const TCP_CLIENTS: usize = 8;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
|
||||||
|
pub(crate) struct DnsPort {
|
||||||
|
address: Ipv4Addr,
|
||||||
|
input: mpsc::Sender<Vec<u8>>,
|
||||||
|
worker: JoinHandle<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DnsPort {
|
||||||
|
pub(crate) fn start(
|
||||||
|
address: Ipv4Addr,
|
||||||
|
mtu: usize,
|
||||||
|
resolver: Resolver,
|
||||||
|
fd: Arc<AsyncFd<File>>,
|
||||||
|
) -> Self {
|
||||||
|
let (input, packets) = mpsc::channel(QUEUE);
|
||||||
|
let worker = tokio::spawn(run(address, mtu, resolver, packets, fd));
|
||||||
|
Self {
|
||||||
|
address,
|
||||||
|
input,
|
||||||
|
worker,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Consume only packets sent to our private endpoint by a local VPN address.
|
||||||
|
pub(crate) fn intercept(&self, bytes: &[u8], local: &[IpAddr]) -> bool {
|
||||||
|
let Ok(packet) = smoltcp::wire::Ipv4Packet::new_checked(bytes) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if packet.version() != 4 || packet.dst_addr() != self.address {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if local.contains(&IpAddr::V4(packet.src_addr())) {
|
||||||
|
let _ = self.input.try_send(bytes.to_vec());
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for DnsPort {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.worker.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Wire {
|
||||||
|
mtu: usize,
|
||||||
|
input: Option<Vec<u8>>,
|
||||||
|
output: VecDeque<Vec<u8>>,
|
||||||
|
}
|
||||||
|
struct Rx(Vec<u8>);
|
||||||
|
impl phy::RxToken for Rx {
|
||||||
|
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
|
||||||
|
f(&self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Tx<'a>(&'a mut VecDeque<Vec<u8>>);
|
||||||
|
impl phy::TxToken for Tx<'_> {
|
||||||
|
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
|
||||||
|
let mut packet = vec![0; len];
|
||||||
|
let result = f(&mut packet);
|
||||||
|
self.0.push_back(packet);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Device for Wire {
|
||||||
|
type RxToken<'a> = Rx;
|
||||||
|
type TxToken<'a> = Tx<'a>;
|
||||||
|
fn receive(&mut self, _: NetTime) -> Option<(Rx, Tx<'_>)> {
|
||||||
|
self.input
|
||||||
|
.take()
|
||||||
|
.map(|packet| (Rx(packet), Tx(&mut self.output)))
|
||||||
|
}
|
||||||
|
fn transmit(&mut self, _: NetTime) -> Option<Tx<'_>> {
|
||||||
|
(self.output.len() < QUEUE).then_some(Tx(&mut self.output))
|
||||||
|
}
|
||||||
|
fn capabilities(&self) -> DeviceCapabilities {
|
||||||
|
let mut caps = DeviceCapabilities::default();
|
||||||
|
caps.medium = Medium::Ip;
|
||||||
|
caps.max_transmission_unit = self.mtu;
|
||||||
|
caps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TcpSlot {
|
||||||
|
handle: SocketHandle,
|
||||||
|
pending: Option<u64>,
|
||||||
|
}
|
||||||
|
enum Client {
|
||||||
|
Udp(IpEndpoint),
|
||||||
|
Tcp { slot: usize, request: u64 },
|
||||||
|
}
|
||||||
|
type Jobs = JoinSet<(Client, Option<Vec<u8>>)>;
|
||||||
|
|
||||||
|
struct Stack {
|
||||||
|
iface: Interface,
|
||||||
|
wire: Wire,
|
||||||
|
sockets: SocketSet<'static>,
|
||||||
|
udp: SocketHandle,
|
||||||
|
tcp: Vec<TcpSlot>,
|
||||||
|
next_request: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stack {
|
||||||
|
fn new(address: Ipv4Addr, mtu: usize) -> Self {
|
||||||
|
let mut wire = Wire {
|
||||||
|
mtu,
|
||||||
|
input: None,
|
||||||
|
output: VecDeque::new(),
|
||||||
|
};
|
||||||
|
let mut config = Config::new(HardwareAddress::Ip);
|
||||||
|
config.random_seed = rand::random();
|
||||||
|
let mut iface = Interface::new(config, &mut wire, NetTime::from_millis(0));
|
||||||
|
// This is a point-to-point IP device. Its only neighbour is Android, whatever
|
||||||
|
// the OS chose as the source address among the attached networks.
|
||||||
|
iface.update_ip_addrs(|addrs| {
|
||||||
|
let _ = addrs.push(IpCidr::new(IpAddress::Ipv4(address), 0));
|
||||||
|
});
|
||||||
|
let mut sockets = SocketSet::new(Vec::new());
|
||||||
|
let datagrams = || {
|
||||||
|
udp::PacketBuffer::new(
|
||||||
|
vec![udp::PacketMetadata::EMPTY; QUEUE],
|
||||||
|
vec![0; QUEUE * mtu],
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let mut socket = udp::Socket::new(datagrams(), datagrams());
|
||||||
|
let _ = socket.bind(PORT);
|
||||||
|
let udp = sockets.add(socket);
|
||||||
|
let tcp = (0..TCP_CLIENTS)
|
||||||
|
.map(|_| {
|
||||||
|
let mut socket = tcp::Socket::new(
|
||||||
|
tcp::SocketBuffer::new(vec![0; MAX_MESSAGE_LEN + 2]),
|
||||||
|
tcp::SocketBuffer::new(vec![0; usize::from(u16::MAX) + 2]),
|
||||||
|
);
|
||||||
|
socket.set_timeout(Some(smoltcp::time::Duration::from_secs(10)));
|
||||||
|
let _ = socket.listen(PORT);
|
||||||
|
TcpSlot {
|
||||||
|
handle: sockets.add(socket),
|
||||||
|
pending: None,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Self {
|
||||||
|
iface,
|
||||||
|
wire,
|
||||||
|
sockets,
|
||||||
|
udp,
|
||||||
|
tcp,
|
||||||
|
next_request: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll(&mut self, now: NetTime) {
|
||||||
|
self.iface.poll(now, &mut self.wire, &mut self.sockets);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch(&mut self, resolver: &Resolver, jobs: &mut Jobs) {
|
||||||
|
let udp = self.sockets.get_mut::<udp::Socket>(self.udp);
|
||||||
|
while let Ok((wire, metadata)) = udp.recv() {
|
||||||
|
if jobs.len() >= QUEUE || wire.len() > MAX_MESSAGE_LEN {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let resolver = resolver.clone();
|
||||||
|
let query = wire.to_vec();
|
||||||
|
let limit = self.wire.mtu.saturating_sub(28);
|
||||||
|
jobs.spawn(async move {
|
||||||
|
let reply = resolver
|
||||||
|
.answer(&query)
|
||||||
|
.await
|
||||||
|
.map(|reply| truncate_for_udp(&query, reply, limit));
|
||||||
|
(Client::Udp(metadata.endpoint), reply)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (index, slot) in self.tcp.iter_mut().enumerate() {
|
||||||
|
let tcp = self.sockets.get_mut::<tcp::Socket>(slot.handle);
|
||||||
|
if !tcp.is_open() {
|
||||||
|
slot.pending = None;
|
||||||
|
let _ = tcp.listen(PORT);
|
||||||
|
}
|
||||||
|
if slot.pending.is_some() || tcp.send_queue() != 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if tcp.state() == tcp::State::CloseWait && tcp.recv_queue() < 2 {
|
||||||
|
tcp.close();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut header = [0; 2];
|
||||||
|
if tcp.peek_slice(&mut header) != Ok(2) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let len = usize::from(u16::from_be_bytes(header));
|
||||||
|
if !(12..=MAX_MESSAGE_LEN).contains(&len) {
|
||||||
|
tcp.abort();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if tcp.recv_queue() < len + 2 || jobs.len() >= QUEUE {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut query = vec![0; len];
|
||||||
|
if tcp.recv_slice(&mut header) != Ok(2) || tcp.recv_slice(&mut query) != Ok(len) {
|
||||||
|
tcp.abort();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
self.next_request = self.next_request.wrapping_add(1);
|
||||||
|
let request = self.next_request;
|
||||||
|
slot.pending = Some(request);
|
||||||
|
let resolver = resolver.clone();
|
||||||
|
jobs.spawn(async move {
|
||||||
|
(
|
||||||
|
Client::Tcp {
|
||||||
|
slot: index,
|
||||||
|
request,
|
||||||
|
},
|
||||||
|
resolver.answer(&query).await,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver(&mut self, client: Client, reply: Option<Vec<u8>>) {
|
||||||
|
match client {
|
||||||
|
Client::Udp(peer) => {
|
||||||
|
if let Some(reply) = reply {
|
||||||
|
let _ = self
|
||||||
|
.sockets
|
||||||
|
.get_mut::<udp::Socket>(self.udp)
|
||||||
|
.send_slice(&reply, peer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Client::Tcp { slot, request } => {
|
||||||
|
let slot = &mut self.tcp[slot];
|
||||||
|
if slot.pending != Some(request) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
slot.pending = None;
|
||||||
|
let tcp = self.sockets.get_mut::<tcp::Socket>(slot.handle);
|
||||||
|
if let Some(reply) = reply
|
||||||
|
&& let Ok(len) = u16::try_from(reply.len())
|
||||||
|
&& tcp.send_slice(&len.to_be_bytes()) == Ok(2)
|
||||||
|
&& tcp.send_slice(&reply) == Ok(reply.len())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tcp.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(
|
||||||
|
address: Ipv4Addr,
|
||||||
|
mtu: usize,
|
||||||
|
resolver: Resolver,
|
||||||
|
mut input: mpsc::Receiver<Vec<u8>>,
|
||||||
|
fd: Arc<AsyncFd<File>>,
|
||||||
|
) {
|
||||||
|
let mut stack = Stack::new(address, mtu);
|
||||||
|
let mut jobs = Jobs::new();
|
||||||
|
let start = Instant::now();
|
||||||
|
loop {
|
||||||
|
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
|
||||||
|
stack.poll(now);
|
||||||
|
stack.dispatch(&resolver, &mut jobs);
|
||||||
|
stack.poll(now);
|
||||||
|
while let Some(packet) = stack.wire.output.pop_front() {
|
||||||
|
if !matches!(fd.async_io(Interest::WRITABLE, |mut file| file.write(&packet)).await, Ok(n) if n == packet.len())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let delay = stack
|
||||||
|
.iface
|
||||||
|
.poll_delay(now, &stack.sockets)
|
||||||
|
.map(Duration::from);
|
||||||
|
tokio::select! {
|
||||||
|
packet = input.recv() => match packet { Some(packet) => stack.wire.input = Some(packet), None => return },
|
||||||
|
Some(Ok((client, reply))) = jobs.join_next(), if !jobs.is_empty() => stack.deliver(client, reply),
|
||||||
|
_ = async { if let Some(delay) = delay { tokio::time::sleep(delay).await } else { std::future::pending().await } } => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, TYPE};
|
||||||
|
use std::os::{fd::OwnedFd, unix::net::UnixDatagram};
|
||||||
|
use tsunagi::dns::{Zone, ZoneName, Zones};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn android_tun_dns_truncates_udp_and_returns_the_complete_answer_over_tcp() {
|
||||||
|
let address = Ipv4Addr::new(192, 0, 2, 53);
|
||||||
|
let phone = Ipv4Addr::new(10, 10, 0, 1);
|
||||||
|
let (fd, os) = UnixDatagram::pair().unwrap();
|
||||||
|
fd.set_nonblocking(true).unwrap();
|
||||||
|
os.set_nonblocking(true).unwrap();
|
||||||
|
let fd = AsyncFd::new(File::from(OwnedFd::from(fd))).unwrap();
|
||||||
|
let os = tokio::net::UnixDatagram::from_std(os).unwrap();
|
||||||
|
let resolver = Resolver::new(|_| panic!("a mesh name went upstream"));
|
||||||
|
resolver.replace(Some(Zones::new([Zone::new(
|
||||||
|
ZoneName::new("tsng").unwrap(),
|
||||||
|
(1..=90).map(|host| ("api".into(), Ipv4Addr::new(10, 1, 2, host))),
|
||||||
|
)])));
|
||||||
|
let port = DnsPort::start(address, 1280, resolver, Arc::new(fd));
|
||||||
|
let mut wire = Wire {
|
||||||
|
mtu: 1280,
|
||||||
|
input: None,
|
||||||
|
output: VecDeque::new(),
|
||||||
|
};
|
||||||
|
let mut iface = Interface::new(
|
||||||
|
Config::new(HardwareAddress::Ip),
|
||||||
|
&mut wire,
|
||||||
|
NetTime::from_millis(0),
|
||||||
|
);
|
||||||
|
iface.update_ip_addrs(|a| a.push(IpCidr::new(IpAddress::Ipv4(phone), 0)).unwrap());
|
||||||
|
let mut sockets = SocketSet::new(Vec::new());
|
||||||
|
let buf = || udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY; 4], vec![0; 4096]);
|
||||||
|
let mut datagram = udp::Socket::new(buf(), buf());
|
||||||
|
datagram.bind(41000).unwrap();
|
||||||
|
let mut packet = Packet::new_query(42);
|
||||||
|
packet.questions.push(Question::new(
|
||||||
|
Name::new("api.tsng").unwrap(),
|
||||||
|
TYPE::A.into(),
|
||||||
|
CLASS::IN.into(),
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
let query = packet.build_bytes_vec().unwrap();
|
||||||
|
datagram.send_slice(&query, (address, PORT)).unwrap();
|
||||||
|
let udp = sockets.add(datagram);
|
||||||
|
let tcp = sockets.add(tcp::Socket::new(
|
||||||
|
tcp::SocketBuffer::new(vec![0; 8192]),
|
||||||
|
tcp::SocketBuffer::new(vec![0; 512]),
|
||||||
|
));
|
||||||
|
let mut sent = false;
|
||||||
|
let mut received = Vec::new();
|
||||||
|
let mut buf = [0; 1500];
|
||||||
|
let start = Instant::now();
|
||||||
|
tokio::time::timeout(Duration::from_secs(4), async {
|
||||||
|
loop {
|
||||||
|
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
|
||||||
|
iface.poll(now, &mut wire, &mut sockets);
|
||||||
|
if let Ok((reply, from)) = sockets.get_mut::<udp::Socket>(udp).recv() {
|
||||||
|
assert_eq!(from.endpoint, (address, PORT).into());
|
||||||
|
let reply = Packet::parse(reply).unwrap();
|
||||||
|
assert_eq!(reply.id(), 42);
|
||||||
|
assert!(reply.has_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER));
|
||||||
|
sockets
|
||||||
|
.get_mut::<tcp::Socket>(tcp)
|
||||||
|
.connect(iface.context(), (address, PORT), 41001)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let stream = sockets.get_mut::<tcp::Socket>(tcp);
|
||||||
|
if stream.can_send() && !sent {
|
||||||
|
let mut frame = (query.len() as u16).to_be_bytes().to_vec();
|
||||||
|
frame.extend_from_slice(&query);
|
||||||
|
assert_eq!(stream.send_slice(&frame).unwrap(), frame.len());
|
||||||
|
sent = true;
|
||||||
|
}
|
||||||
|
while stream.can_recv() {
|
||||||
|
let n = stream.recv_slice(&mut buf).unwrap();
|
||||||
|
received.extend_from_slice(&buf[..n]);
|
||||||
|
}
|
||||||
|
if let Some(prefix) = received.first_chunk::<2>()
|
||||||
|
&& received.len() == 2 + usize::from(u16::from_be_bytes(*prefix))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
iface.poll(now, &mut wire, &mut sockets);
|
||||||
|
for outgoing in wire.output.drain(..) {
|
||||||
|
assert!(port.intercept(&outgoing, &[phone.into()]));
|
||||||
|
}
|
||||||
|
let delay = iface
|
||||||
|
.poll_delay(now, &sockets)
|
||||||
|
.map(Duration::from)
|
||||||
|
.unwrap_or(Duration::from_secs(4));
|
||||||
|
tokio::select! {
|
||||||
|
n = os.recv(&mut buf) => wire.input = Some(buf[..n.unwrap()].to_vec()),
|
||||||
|
_ = tokio::time::sleep(delay) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("DNS over the Android packet device must complete");
|
||||||
|
let reply = Packet::parse(&received[2..]).unwrap();
|
||||||
|
assert_eq!(reply.id(), 42);
|
||||||
|
assert!(!reply.has_flags(PacketFlag::TRUNCATION));
|
||||||
|
assert_eq!(reply.answers.len(), 90);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
//! The Android application. Mesh state belongs to one service-owned Rust agent.
|
||||||
|
|
||||||
|
pub mod dns;
|
||||||
|
pub mod plan;
|
||||||
|
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
mod android;
|
||||||
|
pub mod service;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub mod tun;
|
||||||
|
pub mod view;
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
//! All addresses and routes installed in the one Android VPN.
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
|
use tsunagi::overlay::Cidr;
|
||||||
|
|
||||||
|
/// An exhaustive VpnService configuration, derived from local core policy.
|
||||||
|
#[derive(Clone, Default, Debug, PartialEq, Eq)]
|
||||||
|
pub struct VpnPlan {
|
||||||
|
/// One address in each active, non-overlapping network.
|
||||||
|
pub addresses: Vec<Cidr>,
|
||||||
|
/// Payload MTU for every attached network.
|
||||||
|
pub mtu: u32,
|
||||||
|
/// Capture IPv4 traffic outside the mesh.
|
||||||
|
pub full_tunnel: bool,
|
||||||
|
/// Preferred IPv4 source for the default route.
|
||||||
|
pub exit: Option<IpAddr>,
|
||||||
|
/// Capture the limited broadcast when requested by the core.
|
||||||
|
pub broadcast: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VpnPlan {
|
||||||
|
/// Device-local DNS endpoint. Never take an address from a joined mesh.
|
||||||
|
pub fn dns_address(&self) -> Option<Ipv4Addr> {
|
||||||
|
if self.addresses.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
[
|
||||||
|
Ipv4Addr::new(192, 0, 2, 53),
|
||||||
|
Ipv4Addr::new(198, 51, 100, 53),
|
||||||
|
Ipv4Addr::new(203, 0, 113, 53),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.find(|candidate| {
|
||||||
|
!self.addresses.iter().any(|cidr| {
|
||||||
|
let IpAddr::V4(base) = cidr.addr else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
tsunagi::state::Ipv4Range {
|
||||||
|
base,
|
||||||
|
prefix_len: cidr.prefix_len,
|
||||||
|
}
|
||||||
|
.contains(*candidate)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Android uses the first address as primary for unscoped IPv4 traffic.
|
||||||
|
pub fn addresses_in_order(&self) -> Vec<Cidr> {
|
||||||
|
let mut ordered = self.addresses.clone();
|
||||||
|
ordered.sort_by_key(|cidr| (Some(cidr.addr) != self.exit, *cidr));
|
||||||
|
ordered
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Explicitly route the entire agreed subnet, including its virtual services.
|
||||||
|
pub fn routes(&self) -> Vec<String> {
|
||||||
|
let mut routes: Vec<_> = self
|
||||||
|
.addresses
|
||||||
|
.iter()
|
||||||
|
.map(|cidr| {
|
||||||
|
let p = cidr.prefix_len;
|
||||||
|
let base = match cidr.addr {
|
||||||
|
IpAddr::V4(a) => IpAddr::V4(Ipv4Addr::from(
|
||||||
|
u32::from(a) & u32::MAX.checked_shl(u32::from(32 - p)).unwrap_or(0),
|
||||||
|
)),
|
||||||
|
IpAddr::V6(a) => IpAddr::V6(Ipv6Addr::from(
|
||||||
|
u128::from(a) & u128::MAX.checked_shl(u32::from(128 - p)).unwrap_or(0),
|
||||||
|
)),
|
||||||
|
};
|
||||||
|
format!("{base}/{p}")
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if let Some(dns) = self.dns_address() {
|
||||||
|
routes.push(format!("{dns}/32"));
|
||||||
|
}
|
||||||
|
if self.full_tunnel {
|
||||||
|
routes.push("0.0.0.0/0".into());
|
||||||
|
}
|
||||||
|
if self.broadcast {
|
||||||
|
routes.push("255.255.255.255/32".into());
|
||||||
|
}
|
||||||
|
routes.sort();
|
||||||
|
routes.dedup();
|
||||||
|
routes
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
//! Actions and status for the service-owned Rust agent.
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
use tokio::sync::{mpsc, watch};
|
||||||
|
use tsunagi::{
|
||||||
|
Agent, NetworkName, NetworkSecret,
|
||||||
|
ipc::{PrivilegeReport, ProtocolReport, StatusReport},
|
||||||
|
vip::VipStatus,
|
||||||
|
};
|
||||||
|
use tsunagi_ui::client::Command;
|
||||||
|
use tsunagi_wg_quic::WireguardPlugin;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// A platform notification or user gesture.
|
||||||
|
pub enum Request {
|
||||||
|
/// A command from the same form used by the tray.
|
||||||
|
Action(Command),
|
||||||
|
/// The physical network changed.
|
||||||
|
NetworkChanged,
|
||||||
|
/// Disable only the exit identified by the notification the user tapped.
|
||||||
|
DisconnectExit {
|
||||||
|
/// Network id captured in the immutable action.
|
||||||
|
network: String,
|
||||||
|
/// Endpoint id captured at the same time.
|
||||||
|
peer: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A configured default route stays visible if its remote peer goes offline.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ExitNotice {
|
||||||
|
/// Active network identity for the notification action.
|
||||||
|
pub network: String,
|
||||||
|
/// Selected remote device identity.
|
||||||
|
pub peer: String,
|
||||||
|
/// Human-readable mesh name.
|
||||||
|
pub network_name: String,
|
||||||
|
/// Same name shown in the exit chooser.
|
||||||
|
pub name: String,
|
||||||
|
/// Whether the peer still offers its exit.
|
||||||
|
pub online: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only an active network with a selected remote exit needs an ongoing notice.
|
||||||
|
pub fn exit_notice(report: &StatusReport) -> Option<ExitNotice> {
|
||||||
|
report.networks.iter().filter(|n| n.active).find_map(|n| {
|
||||||
|
let peer = n.exit.via.as_ref()?;
|
||||||
|
Some(ExitNotice {
|
||||||
|
network: n.network_id.clone(),
|
||||||
|
peer: peer.clone(),
|
||||||
|
network_name: n.name.clone(),
|
||||||
|
name: tsunagi_ui::devices::name_of(n, peer),
|
||||||
|
online: n.exit.via_online,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Actions are serialized in the service command loop. An old PendingIntent cannot
|
||||||
|
/// clear a replacement exit selected in this or another network.
|
||||||
|
pub async fn disconnect_exit(
|
||||||
|
agent: &Agent,
|
||||||
|
network: &str,
|
||||||
|
peer: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let network = network.parse()?;
|
||||||
|
let peer = peer.parse()?;
|
||||||
|
if agent.is_active(network).await && agent.network_status(network).await?.exit_via == Some(peer)
|
||||||
|
{
|
||||||
|
agent.set_exit_via(network, None).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Private reply delivered only to the UI that requested the action.
|
||||||
|
pub enum Outcome {
|
||||||
|
/// The agent has applied the action.
|
||||||
|
Applied,
|
||||||
|
/// Revisions returned by a successful signed write.
|
||||||
|
Saved(Vec<VipStatus>),
|
||||||
|
/// A user-requested, single-use clipboard export.
|
||||||
|
Clipboard(Zeroizing<String>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivery channel for a request.
|
||||||
|
pub type Reply = tokio::sync::oneshot::Sender<Result<Outcome, String>>;
|
||||||
|
/// Pending acknowledgement of a UI action.
|
||||||
|
pub type Response = tokio::sync::oneshot::Receiver<Result<Outcome, String>>;
|
||||||
|
|
||||||
|
/// Execute exactly the selection and revision supplied by the form.
|
||||||
|
pub async fn apply(
|
||||||
|
command: Command,
|
||||||
|
agent: &Agent,
|
||||||
|
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
match command {
|
||||||
|
Command::Join { name, secret } => {
|
||||||
|
agent
|
||||||
|
.join_network(&NetworkName::new(name)?, &NetworkSecret::decode(&secret)?)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Command::SetActive { network_id, active } => {
|
||||||
|
let id = network_id.parse()?;
|
||||||
|
if active {
|
||||||
|
agent.switch_network(id).await?;
|
||||||
|
} else {
|
||||||
|
agent.pause_network(id).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Leave { network_id } => {
|
||||||
|
agent.leave_network(network_id.parse()?).await?;
|
||||||
|
}
|
||||||
|
Command::SetBroadcast {
|
||||||
|
network_id,
|
||||||
|
enabled,
|
||||||
|
} => agent.set_broadcast(network_id.parse()?, enabled).await?,
|
||||||
|
Command::SetProtocols {
|
||||||
|
network_id,
|
||||||
|
protocols,
|
||||||
|
} => agent.set_protocols(network_id.parse()?, protocols).await?,
|
||||||
|
Command::SetHostname(hostname) => {
|
||||||
|
agent.set_hostname(&hostname).await?;
|
||||||
|
}
|
||||||
|
Command::ForgetNode {
|
||||||
|
network_id,
|
||||||
|
peer,
|
||||||
|
expected_version,
|
||||||
|
} => {
|
||||||
|
agent
|
||||||
|
.forget_node(network_id.parse()?, peer.parse()?, expected_version)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Command::SetExitNode { network_id, peer } => {
|
||||||
|
agent
|
||||||
|
.set_exit_via(network_id.parse()?, peer.map(|p| p.parse()).transpose()?)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
Command::SetExitOffer { .. } => {
|
||||||
|
return Err("This phone can only use a remote exit node.".into());
|
||||||
|
}
|
||||||
|
Command::SaveVip {
|
||||||
|
network_id,
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
return Ok(Outcome::Saved(
|
||||||
|
agent
|
||||||
|
.save_vip(network_id.parse()?, config, expected, delete)
|
||||||
|
.await?,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Command::CopySecret { network_id } => {
|
||||||
|
return Ok(Outcome::Clipboard(
|
||||||
|
agent.network_secret(network_id.parse()?).await?.encode(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Outcome::Applied)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// State visible to an activity which may be recreated while the service runs.
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub enum State {
|
||||||
|
/// The user can start the VPN.
|
||||||
|
#[default]
|
||||||
|
Off,
|
||||||
|
/// Opening the endpoint or waiting for connectivity.
|
||||||
|
Starting,
|
||||||
|
/// The last complete snapshot and its monotonic observation time.
|
||||||
|
Ready(Arc<StatusReport>, Instant),
|
||||||
|
/// Actionable startup or status error.
|
||||||
|
Error(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the same network and counter reports used by the desktop client.
|
||||||
|
pub async fn report(
|
||||||
|
agent: &Agent,
|
||||||
|
wg: Option<&WireguardPlugin>,
|
||||||
|
dns: &crate::dns::Resolver,
|
||||||
|
) -> tsunagi::Result<StatusReport> {
|
||||||
|
let status = agent.status().await?;
|
||||||
|
Ok(StatusReport {
|
||||||
|
networks: tsunagi_runtime::report::networks(&status, agent.overlay().as_ref(), wg),
|
||||||
|
dns: Some(dns.refresh(&status.networks)),
|
||||||
|
endpoint_id: status.endpoint_id.to_string(),
|
||||||
|
hostname: status.hostname,
|
||||||
|
bound_sockets: status
|
||||||
|
.bound_sockets
|
||||||
|
.iter()
|
||||||
|
.map(ToString::to_string)
|
||||||
|
.collect(),
|
||||||
|
cache_healthy: status.cache_healthy,
|
||||||
|
available_protocols: tsunagi_runtime::PROTOCOLS
|
||||||
|
.iter()
|
||||||
|
.map(|spec| ProtocolReport {
|
||||||
|
name: spec.name.into(),
|
||||||
|
summary: spec.summary.into(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
protocols: tsunagi_runtime::PROTOCOLS
|
||||||
|
.iter()
|
||||||
|
.map(|spec| format!("{} v{}", spec.name, spec.version))
|
||||||
|
.collect(),
|
||||||
|
privilege: PrivilegeReport::Available,
|
||||||
|
version: env!("CARGO_PKG_VERSION").into(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drive the agent until Android stops this service instance.
|
||||||
|
pub async fn serve(
|
||||||
|
agent: Agent,
|
||||||
|
wg: Arc<WireguardPlugin>,
|
||||||
|
dns: crate::dns::Resolver,
|
||||||
|
mut commands: mpsc::Receiver<(Request, Reply)>,
|
||||||
|
state: &watch::Sender<State>,
|
||||||
|
mut stop: watch::Receiver<bool>,
|
||||||
|
mut publish_exit: impl FnMut(Option<&ExitNotice>),
|
||||||
|
) {
|
||||||
|
let mut poll = tokio::time::interval(std::time::Duration::from_secs(2));
|
||||||
|
poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
let mut published_exit = None;
|
||||||
|
loop {
|
||||||
|
let reply = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = stop.wait_for(|stopped| *stopped) => break,
|
||||||
|
command = commands.recv() => {
|
||||||
|
let Some((request, reply)) = command else { break };
|
||||||
|
let result = match request {
|
||||||
|
Request::Action(cmd) => {
|
||||||
|
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||||
|
dns.replace(None);
|
||||||
|
}
|
||||||
|
apply(cmd, &agent).await.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
Request::NetworkChanged => {
|
||||||
|
agent.endpoint().network_change().await;
|
||||||
|
agent.recheck().await;
|
||||||
|
Ok(Outcome::Applied)
|
||||||
|
}
|
||||||
|
Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await
|
||||||
|
.map(|()| Outcome::Applied).map_err(|e| e.to_string()),
|
||||||
|
};
|
||||||
|
Some((reply, result))
|
||||||
|
}
|
||||||
|
_ = poll.tick() => None,
|
||||||
|
};
|
||||||
|
state.send_replace(match report(&agent, Some(&wg), &dns).await {
|
||||||
|
Ok(report) => {
|
||||||
|
let notice = exit_notice(&report);
|
||||||
|
if published_exit.as_ref() != Some(¬ice) {
|
||||||
|
publish_exit(notice.as_ref());
|
||||||
|
published_exit = Some(notice);
|
||||||
|
}
|
||||||
|
State::Ready(Arc::new(report), Instant::now())
|
||||||
|
}
|
||||||
|
Err(error) => State::Error(error.to_string()),
|
||||||
|
});
|
||||||
|
if let Some((reply, outcome)) = reply {
|
||||||
|
let _ = reply.send(outcome);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,651 @@
|
|||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use super::plan::VpnPlan;
|
||||||
|
use std::net::{IpAddr, Ipv4Addr};
|
||||||
|
use tsunagi::overlay::Cidr;
|
||||||
|
|
||||||
|
fn addr(octet: u8) -> Cidr {
|
||||||
|
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, octet, 42, 19)), 24).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() {
|
||||||
|
use crate::service::{disconnect_exit, exit_notice, report};
|
||||||
|
use tsunagi::{
|
||||||
|
discovery::SharedMemoryDiscovery,
|
||||||
|
testing::{TestAgent, network, wait_until},
|
||||||
|
};
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let phone = TestAgent::spawn(&discovery).await.unwrap();
|
||||||
|
let rules = std::sync::Arc::new(tsunagi::overlay::MockHostRules::new());
|
||||||
|
let tuns = tsunagi::overlay::MemoryTunFactory::new().with_host_rules(rules);
|
||||||
|
let exit = TestAgent::spawn_with(
|
||||||
|
|cfg| cfg.with_interface(std::sync::Arc::new(tuns), "gateway", 1280),
|
||||||
|
&discovery,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (name, secret) = network("travel");
|
||||||
|
let id = phone.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
exit.agent.set_hostname("gateway").await.unwrap();
|
||||||
|
exit.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
exit.agent.set_exit_offer(id, true).await.unwrap();
|
||||||
|
let peer = exit.agent.endpoint_id();
|
||||||
|
wait_until("authenticated exit offer", || async {
|
||||||
|
phone
|
||||||
|
.agent
|
||||||
|
.network_status(id)
|
||||||
|
.await
|
||||||
|
.ok()?
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.any(|p| p.endpoint_id == peer && p.exit_node)
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let dns = crate::dns::Resolver::new(|_| None);
|
||||||
|
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||||
|
phone.agent.set_exit_via(id, Some(peer)).await.unwrap();
|
||||||
|
let notice = exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).unwrap();
|
||||||
|
assert_eq!(notice.name, "gateway");
|
||||||
|
assert_eq!(notice.network_name, "travel");
|
||||||
|
assert!(notice.online);
|
||||||
|
disconnect_exit(
|
||||||
|
&phone.agent,
|
||||||
|
&id.to_string(),
|
||||||
|
&phone.agent.endpoint_id().to_string(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
phone.agent.network_status(id).await.unwrap().exit_via,
|
||||||
|
Some(peer)
|
||||||
|
);
|
||||||
|
exit.stop().await;
|
||||||
|
wait_until(
|
||||||
|
"offline exit remains selected in the notification",
|
||||||
|
|| async {
|
||||||
|
let report = report(&phone.agent, None, &dns).await.ok()?;
|
||||||
|
exit_notice(&report).filter(|n| !n.online)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||||
|
assert!(phone.agent.is_active(id).await);
|
||||||
|
phone.stop().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn vpn_dns_answers_hosts_and_vips_in_each_zone_and_only_forwards_external_names() {
|
||||||
|
use crate::dns::Resolver;
|
||||||
|
use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, RCODE, TYPE, rdata::RData};
|
||||||
|
use std::sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
};
|
||||||
|
use tsunagi::dns::{Zone, ZoneName, Zones};
|
||||||
|
|
||||||
|
fn query(name: &str, kind: TYPE) -> Vec<u8> {
|
||||||
|
let mut packet = Packet::new_query(119);
|
||||||
|
packet.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||||
|
packet.questions.push(Question::new(
|
||||||
|
Name::new(name).unwrap(),
|
||||||
|
kind.into(),
|
||||||
|
CLASS::IN.into(),
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
packet.build_bytes_vec().unwrap()
|
||||||
|
}
|
||||||
|
let calls = Arc::new(AtomicUsize::new(0));
|
||||||
|
let forwarded = calls.clone();
|
||||||
|
let resolver = Resolver::new(move |wire| {
|
||||||
|
forwarded.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let query = Packet::parse(wire).unwrap();
|
||||||
|
let mut answer = Packet::new_reply(999);
|
||||||
|
answer.questions = query.questions;
|
||||||
|
answer.build_bytes_vec().ok()
|
||||||
|
});
|
||||||
|
let private = query("k8s.tsng", TYPE::A);
|
||||||
|
let answer = resolver.answer(&private).await.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
Packet::parse(&answer).unwrap().rcode(),
|
||||||
|
RCODE::ServerFailure
|
||||||
|
);
|
||||||
|
let lab = |name, members| Zone::new(ZoneName::new(name).unwrap(), members);
|
||||||
|
resolver.replace(Some(Zones::new([
|
||||||
|
lab(
|
||||||
|
"tsng",
|
||||||
|
vec![
|
||||||
|
("ai".into(), [10, 1, 1, 100].into()),
|
||||||
|
("k8s".into(), [10, 1, 1, 106].into()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
lab("lab", vec![("ai".into(), [10, 2, 1, 100].into())]),
|
||||||
|
])));
|
||||||
|
for (name, ip) in [
|
||||||
|
("AI.TSNG", [10, 1, 1, 100]),
|
||||||
|
("k8s.tsng", [10, 1, 1, 106]),
|
||||||
|
("ai.lab", [10, 2, 1, 100]),
|
||||||
|
] {
|
||||||
|
let reply = resolver.answer(&query(name, TYPE::A)).await.unwrap();
|
||||||
|
let packet = Packet::parse(&reply).unwrap();
|
||||||
|
assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
|
||||||
|
assert!(
|
||||||
|
matches!(&packet.answers[0].rdata, RData::A(a) if Ipv4Addr::from(a.address) == Ipv4Addr::from(ip))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (name, kind, code) in [
|
||||||
|
("missing.tsng", TYPE::A, RCODE::NameError),
|
||||||
|
("k8s.tsng", TYPE::AAAA, RCODE::NoError),
|
||||||
|
] {
|
||||||
|
let reply = resolver.answer(&query(name, kind)).await.unwrap();
|
||||||
|
let packet = Packet::parse(&reply).unwrap();
|
||||||
|
assert_eq!(packet.rcode(), code);
|
||||||
|
assert!(packet.answers.is_empty());
|
||||||
|
assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
|
||||||
|
}
|
||||||
|
assert!(resolver.answer(b"invalid").await.is_none());
|
||||||
|
assert_eq!(calls.load(Ordering::Relaxed), 0);
|
||||||
|
let reply = resolver
|
||||||
|
.answer(&query("example.org", TYPE::HTTPS))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let packet = Packet::parse(&reply).unwrap();
|
||||||
|
assert_eq!(packet.id(), 119);
|
||||||
|
assert_eq!(packet.questions[0].qtype, TYPE::HTTPS.into());
|
||||||
|
assert_eq!(calls.load(Ordering::Relaxed), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_dns_address_is_routed_and_cannot_claim_an_overlay_ip() {
|
||||||
|
let mut plan = VpnPlan {
|
||||||
|
addresses: vec![addr(1)],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let dns = plan.dns_address().unwrap();
|
||||||
|
assert!(plan.routes().contains(&format!("{dns}/32")));
|
||||||
|
plan.addresses.push(Cidr::new(dns.into(), 24).unwrap());
|
||||||
|
let other = plan.dns_address().unwrap();
|
||||||
|
assert_ne!(other, dns);
|
||||||
|
assert!(plan.routes().contains(&format!("{other}/32")));
|
||||||
|
plan.addresses.clear();
|
||||||
|
assert!(plan.dns_address().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn service_dns_tracks_signed_hostnames_vip_deletion_and_reverse_ranges() {
|
||||||
|
use tsunagi::{
|
||||||
|
Agent,
|
||||||
|
dns::{Answer, Query, RosterZones},
|
||||||
|
testing,
|
||||||
|
vip::VipConfig,
|
||||||
|
};
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let agent = Agent::spawn(testing::local_config(dir.path()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (network, secret) = testing::network("tsng");
|
||||||
|
let id = agent.join_network(&network, &secret).await.unwrap();
|
||||||
|
agent.set_hostname("worker").await.unwrap();
|
||||||
|
let vip = agent
|
||||||
|
.save_vip(id, VipConfig::new("k8s"), None, false)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.remove(0);
|
||||||
|
let status = agent.status().await.unwrap();
|
||||||
|
let roster = RosterZones::from_networks(&status.networks);
|
||||||
|
let worker = status.networks[0]
|
||||||
|
.members
|
||||||
|
.iter()
|
||||||
|
.find(|m| m.hostname.as_deref() == Some("worker"))
|
||||||
|
.unwrap()
|
||||||
|
.overlay_address_v4
|
||||||
|
.unwrap();
|
||||||
|
for (name, ip) in [("worker.tsng", worker), ("k8s.tsng", vip.address.unwrap())] {
|
||||||
|
assert_eq!(
|
||||||
|
roster.zones.lookup(name, Query::A).unwrap().1,
|
||||||
|
Answer::Addresses(vec![ip])
|
||||||
|
);
|
||||||
|
let [a, b, c, d] = ip.octets();
|
||||||
|
assert_eq!(
|
||||||
|
roster
|
||||||
|
.zones
|
||||||
|
.lookup(&format!("{d}.{c}.{b}.{a}.in-addr.arpa"), Query::Ptr)
|
||||||
|
.unwrap()
|
||||||
|
.1,
|
||||||
|
Answer::Name(name.into())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
roster
|
||||||
|
.zones
|
||||||
|
.lookup("8.8.8.8.in-addr.arpa", Query::Ptr)
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
agent
|
||||||
|
.save_vip(id, vip.config, Some(vip.revision), true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let zones = RosterZones::from_networks(&agent.status().await.unwrap().networks).zones;
|
||||||
|
assert_eq!(
|
||||||
|
zones.lookup("k8s.tsng", Query::A).unwrap().1,
|
||||||
|
Answer::NoSuchName
|
||||||
|
);
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn changing_the_exit_keeps_every_mesh_route_and_prefers_the_selected_source() {
|
||||||
|
let first = addr(2);
|
||||||
|
let second = addr(5);
|
||||||
|
let mut plan = VpnPlan {
|
||||||
|
addresses: vec![first, second],
|
||||||
|
mtu: 1280,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
plan.routes(),
|
||||||
|
["10.2.42.0/24", "10.5.42.0/24", "192.0.2.53/32"]
|
||||||
|
);
|
||||||
|
assert_eq!(plan.addresses_in_order(), [first, second]);
|
||||||
|
plan.full_tunnel = true;
|
||||||
|
plan.exit = Some(second.addr);
|
||||||
|
assert_eq!(plan.addresses_in_order(), [second, first]);
|
||||||
|
assert!(plan.routes().contains(&"0.0.0.0/0".into()));
|
||||||
|
assert!(plan.routes().contains(&"10.2.42.0/24".into()));
|
||||||
|
plan.full_tunnel = false;
|
||||||
|
plan.exit = None;
|
||||||
|
plan.addresses.remove(0);
|
||||||
|
assert_eq!(plan.routes(), ["10.5.42.0/24", "192.0.2.53/32"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broadcast_route_is_only_present_when_requested() {
|
||||||
|
let mut plan = VpnPlan {
|
||||||
|
addresses: vec![addr(1)],
|
||||||
|
mtu: 1280,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
plan.broadcast = true;
|
||||||
|
assert!(plan.routes().contains(&"255.255.255.255/32".into()));
|
||||||
|
plan.broadcast = false;
|
||||||
|
assert_eq!(plan.routes(), ["10.1.42.0/24", "192.0.2.53/32"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preference() {
|
||||||
|
use tsunagi::{Agent, testing};
|
||||||
|
use tsunagi_runtime::{Carriers, PROTOCOLS};
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let names = ["wg", "awg", "wg-quic", "tcp-tls"];
|
||||||
|
let (network, secret) = testing::network("carriers");
|
||||||
|
for restart in [false, true] {
|
||||||
|
let config = testing::local_config(dir.path());
|
||||||
|
let (config, carriers) = Carriers::configure(config, &[], None, |spec| {
|
||||||
|
if spec.name == "tcp-tls" {
|
||||||
|
vec![("port".into(), "0".into())]
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
config
|
||||||
|
.carriers
|
||||||
|
.iter()
|
||||||
|
.map(|c| c.protocol_id())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
names
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
config
|
||||||
|
.carriers
|
||||||
|
.iter()
|
||||||
|
.zip(PROTOCOLS)
|
||||||
|
.all(|(c, spec)| c.protocol_version() == spec.version)
|
||||||
|
);
|
||||||
|
let agent = Agent::spawn(config).await.unwrap();
|
||||||
|
let _listeners = carriers.listen(&agent);
|
||||||
|
let id = agent.join_network(&network, &secret).await.unwrap();
|
||||||
|
let saved = agent.network_status(id).await.unwrap().protocols;
|
||||||
|
if restart {
|
||||||
|
assert_eq!(saved, ["tcp-tls", "wg"]);
|
||||||
|
} else {
|
||||||
|
assert_eq!(saved, names);
|
||||||
|
agent
|
||||||
|
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (other, secret) = testing::network("other");
|
||||||
|
let second = agent.join_network(&other, &secret).await.unwrap();
|
||||||
|
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
|
||||||
|
}
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn commands_scope_vip_edits_and_leaving_to_the_selected_network() {
|
||||||
|
use crate::service::apply;
|
||||||
|
use tsunagi::vip::VipConfig;
|
||||||
|
use tsunagi::{Agent, NetworkName, NetworkSecret, testing};
|
||||||
|
use tsunagi_ui::client::Command;
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let agent = Agent::spawn(testing::local_config(dir.path()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let name = NetworkName::new("shared-name").unwrap();
|
||||||
|
let one = NetworkSecret::generate();
|
||||||
|
let two = NetworkSecret::generate();
|
||||||
|
for secret in [&one, &two] {
|
||||||
|
apply(
|
||||||
|
Command::Join {
|
||||||
|
name: name.to_string(),
|
||||||
|
secret: secret.encode(),
|
||||||
|
},
|
||||||
|
&agent,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let first = tsunagi::identity::NetworkKeys::derive(&name, &one)
|
||||||
|
.network_id()
|
||||||
|
.to_string();
|
||||||
|
let second = tsunagi::identity::NetworkKeys::derive(&name, &two).network_id();
|
||||||
|
let config = VipConfig::new("web");
|
||||||
|
let save = |expected, delete| Command::SaveVip {
|
||||||
|
token: "draft".into(),
|
||||||
|
network_id: first.clone(),
|
||||||
|
config: config.clone(),
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
};
|
||||||
|
apply(save(None, false), &agent).await.unwrap();
|
||||||
|
assert!(
|
||||||
|
apply(save(Some("stale".into()), true), &agent)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
agent
|
||||||
|
.network_status(first.parse().unwrap())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.vips
|
||||||
|
.len(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert!(agent.network_status(second).await.unwrap().vips.is_empty());
|
||||||
|
assert!(
|
||||||
|
apply(
|
||||||
|
Command::SetExitNode {
|
||||||
|
network_id: second.to_string(),
|
||||||
|
peer: Some(agent.endpoint_id().to_string())
|
||||||
|
},
|
||||||
|
&agent
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
apply(
|
||||||
|
Command::SetExitOffer {
|
||||||
|
network_id: second.to_string(),
|
||||||
|
enabled: true
|
||||||
|
},
|
||||||
|
&agent
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
apply(Command::Leave { network_id: first }, &agent)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let saved = agent.list_networks().await.unwrap();
|
||||||
|
assert_eq!(saved.len(), 1);
|
||||||
|
assert_eq!(saved[0].network_id, second);
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tun_reader_survives_address_changes_failed_establish_and_last_network_leaving() {
|
||||||
|
use std::io;
|
||||||
|
use std::os::{fd::OwnedFd, unix::net::UnixDatagram};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tsunagi::overlay::{TunFactory, TunRequest};
|
||||||
|
let sockets = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let peers = sockets.clone();
|
||||||
|
let factory = crate::tun::AndroidTun::new(
|
||||||
|
crate::dns::Resolver::new(|_| None),
|
||||||
|
move |plan| {
|
||||||
|
if plan.addresses.contains(&addr(9)) {
|
||||||
|
return Err(io::Error::other("permission revoked"));
|
||||||
|
}
|
||||||
|
let (dev, os) = UnixDatagram::pair()?;
|
||||||
|
dev.set_nonblocking(true)?;
|
||||||
|
peers.lock().unwrap().push(os);
|
||||||
|
Ok(OwnedFd::from(dev).into())
|
||||||
|
},
|
||||||
|
|_, _| Ok(()),
|
||||||
|
);
|
||||||
|
let mut req = TunRequest::bare("tsun0", 1280);
|
||||||
|
let dev = factory.create(req.clone()).await.unwrap();
|
||||||
|
let reader = tokio::spawn({
|
||||||
|
let dev = dev.clone();
|
||||||
|
async move { dev.recv().await.unwrap() }
|
||||||
|
});
|
||||||
|
req.addresses = vec![addr(2)];
|
||||||
|
factory.reconfigure(req.clone()).await.unwrap();
|
||||||
|
assert_eq!(factory.assigned_addresses(), [addr(2).addr]);
|
||||||
|
req.addresses.push(addr(9));
|
||||||
|
assert!(factory.reconfigure(req.clone()).await.is_err());
|
||||||
|
assert_eq!(factory.assigned_addresses(), [addr(2).addr]);
|
||||||
|
sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.last()
|
||||||
|
.unwrap()
|
||||||
|
.send(b"first")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
&tokio::time::timeout(std::time::Duration::from_secs(2), reader)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()[..],
|
||||||
|
b"first"
|
||||||
|
);
|
||||||
|
req.addresses.clear();
|
||||||
|
factory.reconfigure(req.clone()).await.unwrap();
|
||||||
|
assert!(
|
||||||
|
dev.send(bytes::Bytes::from_static(b"offline"))
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(factory.assigned_addresses().is_empty());
|
||||||
|
req.addresses = vec![addr(5)];
|
||||||
|
factory.reconfigure(req).await.unwrap();
|
||||||
|
sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.last()
|
||||||
|
.unwrap()
|
||||||
|
.send(b"second")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(&dev.recv().await.unwrap()[..], b"second");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() {
|
||||||
|
use crate::{
|
||||||
|
service::{State, report},
|
||||||
|
view::{Phone, configure},
|
||||||
|
};
|
||||||
|
use egui::epaint::Shape;
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let agent = tsunagi::Agent::spawn(tsunagi::testing::local_config(dir.path()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (name, secret) = tsunagi::testing::network("layout");
|
||||||
|
agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
let mut sample = report(&agent, None, &crate::dns::Resolver::new(|_| None))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sample.networks[0].overlay = Some(tsunagi::ipc::OverlayReport {
|
||||||
|
address: Some("10.1.2.3".into()),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let state = State::Ready(Arc::new(sample), Instant::now());
|
||||||
|
let ctx = egui::Context::default();
|
||||||
|
configure(&ctx);
|
||||||
|
let mut phone = Phone::default();
|
||||||
|
let frame = ctx.run(
|
||||||
|
egui::RawInput {
|
||||||
|
screen_rect: Some(egui::Rect::from_min_size(
|
||||||
|
egui::Pos2::ZERO,
|
||||||
|
egui::vec2(360., 720.),
|
||||||
|
)),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
|ctx| {
|
||||||
|
phone.draw(ctx, &state, |_| {
|
||||||
|
panic!("drawing the overview issued a command")
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let y = |label: &str| {
|
||||||
|
frame
|
||||||
|
.shapes
|
||||||
|
.iter()
|
||||||
|
.find_map(|shape| match &shape.shape {
|
||||||
|
Shape::Text(text) if text.galley.text() == label => Some(text.pos.y),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| panic!("missing label {label}"))
|
||||||
|
};
|
||||||
|
assert!((0.0..=26.0).contains(&(y("host") - y("device"))));
|
||||||
|
assert!((0.0..=26.0).contains(&(y("range") - y("id"))));
|
||||||
|
assert!((0.0..=26.0).contains(&(y("peers") - y("addr"))));
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
|
||||||
|
use crate::service::State;
|
||||||
|
use crate::view::{Phone, configure};
|
||||||
|
use egui::{Event, PointerButton, Pos2, RawInput, Rect, Shape};
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
use tsunagi::{
|
||||||
|
ipc::{NetworkReport, StatusReport},
|
||||||
|
vip::{
|
||||||
|
Backend, BackendStatus, Counters, Listener, ListenerStatus, Protocol, VipConfig,
|
||||||
|
VipStatus,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let backend = Backend {
|
||||||
|
peer: "node".into(),
|
||||||
|
port: 8080,
|
||||||
|
};
|
||||||
|
let mut config = VipConfig::new("web");
|
||||||
|
let mut listener = Listener::new(Protocol::Tcp, 80);
|
||||||
|
listener.backends.push(backend.clone());
|
||||||
|
config.listeners.push(listener);
|
||||||
|
let network = NetworkReport {
|
||||||
|
active: true,
|
||||||
|
name: "lab".into(),
|
||||||
|
network_id: "network".into(),
|
||||||
|
vips: vec![VipStatus {
|
||||||
|
config,
|
||||||
|
address: None,
|
||||||
|
revision: "r1".into(),
|
||||||
|
error: None,
|
||||||
|
listeners: vec![ListenerStatus {
|
||||||
|
protocol: Protocol::Tcp,
|
||||||
|
port: 80,
|
||||||
|
selected: Some(backend.clone()),
|
||||||
|
counters: Counters::default(),
|
||||||
|
backends: vec![BackendStatus {
|
||||||
|
backend,
|
||||||
|
state: "ready".into(),
|
||||||
|
rtt_us: Some(1000),
|
||||||
|
measurement_age_ms: Some(1),
|
||||||
|
active_flows: 1,
|
||||||
|
counters: Counters::default(),
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let state = State::Ready(
|
||||||
|
Arc::new(StatusReport {
|
||||||
|
networks: vec![network],
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
Instant::now(),
|
||||||
|
);
|
||||||
|
let ctx = egui::Context::default();
|
||||||
|
configure(&ctx);
|
||||||
|
let mut phone = Phone::default();
|
||||||
|
let mut frame = |events| {
|
||||||
|
ctx.run(
|
||||||
|
RawInput {
|
||||||
|
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(360., 800.))),
|
||||||
|
events,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
|ctx| {
|
||||||
|
phone.draw(ctx, &state, |_| panic!("navigation wrote to the network"));
|
||||||
|
},
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let position = |output: &egui::FullOutput, label: &str| {
|
||||||
|
output
|
||||||
|
.shapes
|
||||||
|
.iter()
|
||||||
|
.find_map(|s| match &s.shape {
|
||||||
|
Shape::Text(t) if t.galley.text() == label => {
|
||||||
|
Some(t.pos + t.galley.rect.center().to_vec2())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| panic!("missing {label}"))
|
||||||
|
};
|
||||||
|
let mut click = |label: &str| {
|
||||||
|
frame(vec![]);
|
||||||
|
let p = position(&frame(vec![]), label);
|
||||||
|
for pressed in [true, false] {
|
||||||
|
frame(vec![
|
||||||
|
Event::PointerMoved(p),
|
||||||
|
Event::PointerButton {
|
||||||
|
pos: p,
|
||||||
|
button: PointerButton::Primary,
|
||||||
|
pressed,
|
||||||
|
modifiers: Default::default(),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
frame(vec![])
|
||||||
|
};
|
||||||
|
let live = click("VIP");
|
||||||
|
for label in ["Overview", "Configuration", "Next new flow", "node:8080"] {
|
||||||
|
let p = position(&live, label);
|
||||||
|
assert!(
|
||||||
|
(0.0..360.0).contains(&p.x),
|
||||||
|
"{label} is outside the portrait view"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let editor = click("Configuration");
|
||||||
|
for label in [
|
||||||
|
"Active TCP port checks",
|
||||||
|
"Checks and flow expiry",
|
||||||
|
"+ Backend",
|
||||||
|
"+ Listener",
|
||||||
|
] {
|
||||||
|
position(&editor, label);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
//! A stable packet device over the file descriptors replaced by VpnService.
|
||||||
|
use crate::dns::{Resolver, stack::DnsPort};
|
||||||
|
use crate::plan::VpnPlan;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use std::{
|
||||||
|
fmt,
|
||||||
|
fs::File,
|
||||||
|
io::{self, Read, Write},
|
||||||
|
sync::Arc,
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
io::unix::AsyncFd,
|
||||||
|
sync::{Mutex, watch},
|
||||||
|
};
|
||||||
|
use tsunagi::{
|
||||||
|
BoxFuture,
|
||||||
|
overlay::{
|
||||||
|
OverlayError, TunDevice, TunFactory, TunRequest,
|
||||||
|
hostrules::{
|
||||||
|
BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan,
|
||||||
|
ExitHostReport, ExitHostRules, RuleOutcome,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
type Establish = dyn Fn(&VpnPlan) -> io::Result<File> + Send + Sync;
|
||||||
|
type BindSocket =
|
||||||
|
dyn Fn(&tokio::net::TcpSocket, std::net::Ipv4Addr) -> io::Result<()> + Send + Sync;
|
||||||
|
struct Attachment {
|
||||||
|
device: Arc<AsyncFd<File>>,
|
||||||
|
addresses: Vec<std::net::IpAddr>,
|
||||||
|
dns: DnsPort,
|
||||||
|
}
|
||||||
|
type Descriptor = Option<Arc<Attachment>>;
|
||||||
|
|
||||||
|
/// The only OS call is supplied by the Android service. Tokio owns the detached fd.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AndroidTun(Arc<Inner>);
|
||||||
|
struct Inner {
|
||||||
|
establish: Box<Establish>,
|
||||||
|
bind: Box<BindSocket>,
|
||||||
|
resolver: Resolver,
|
||||||
|
plan: Mutex<VpnPlan>,
|
||||||
|
current: watch::Sender<Descriptor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for AndroidTun {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("AndroidTun")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl AndroidTun {
|
||||||
|
/// Attach a nonblocking device returned by Builder.establish().
|
||||||
|
pub fn new(
|
||||||
|
resolver: Resolver,
|
||||||
|
establish: impl Fn(&VpnPlan) -> io::Result<File> + Send + Sync + 'static,
|
||||||
|
bind: impl Fn(&tokio::net::TcpSocket, std::net::Ipv4Addr) -> io::Result<()>
|
||||||
|
+ Send
|
||||||
|
+ Sync
|
||||||
|
+ 'static,
|
||||||
|
) -> Self {
|
||||||
|
Self(Arc::new(Inner {
|
||||||
|
establish: Box::new(establish),
|
||||||
|
bind: Box::new(bind),
|
||||||
|
resolver,
|
||||||
|
plan: Mutex::default(),
|
||||||
|
current: watch::channel(None).0,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update(&self, edit: impl FnOnce(&mut VpnPlan)) -> Result<(), OverlayError> {
|
||||||
|
let mut applied = self.0.plan.lock().await;
|
||||||
|
let mut next = applied.clone();
|
||||||
|
edit(&mut next);
|
||||||
|
if *applied == next {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let dns_address = next.dns_address();
|
||||||
|
let fd = if next.addresses.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let address = dns_address.ok_or_else(|| OverlayError::Unavailable(
|
||||||
|
"Mesh ranges overlap every device-local DNS address. Choose a narrower mesh range.".into()
|
||||||
|
))?;
|
||||||
|
let file = (self.0.establish)(&next)
|
||||||
|
.and_then(AsyncFd::new)
|
||||||
|
.map(Arc::new)
|
||||||
|
.map_err(|err| OverlayError::Unavailable(err.to_string()))?;
|
||||||
|
let dns = DnsPort::start(
|
||||||
|
address,
|
||||||
|
next.mtu as usize,
|
||||||
|
self.0.resolver.clone(),
|
||||||
|
file.clone(),
|
||||||
|
);
|
||||||
|
Some(Arc::new(Attachment {
|
||||||
|
device: file,
|
||||||
|
addresses: next.addresses.iter().map(|a| a.addr).collect(),
|
||||||
|
dns,
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
self.0.current.send_replace(fd);
|
||||||
|
self.0.resolver.publish(dns_address);
|
||||||
|
*applied = next;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Device {
|
||||||
|
name: String,
|
||||||
|
mtu: u32,
|
||||||
|
tun: AndroidTun,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TunDevice for Device {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
fn mtu(&self) -> u32 {
|
||||||
|
self.mtu
|
||||||
|
}
|
||||||
|
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut rx = self.tun.0.current.subscribe();
|
||||||
|
let mut buffer = vec![0; self.mtu as usize + 1];
|
||||||
|
loop {
|
||||||
|
let fd = rx.borrow_and_update().clone();
|
||||||
|
if let Some(fd) = fd {
|
||||||
|
let result = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = rx.changed() => continue,
|
||||||
|
read = fd.device.async_io(tokio::io::Interest::READABLE, |mut file| file.read(&mut buffer)) => read,
|
||||||
|
};
|
||||||
|
if let Ok(len @ 1..) = result {
|
||||||
|
if fd.dns.intercept(&buffer[..len], &fd.addresses) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
buffer.truncate(len);
|
||||||
|
return Some(buffer.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No networks yet, last one left, or Android revoked this fd.
|
||||||
|
// A later establish wakes the same reader on the new device.
|
||||||
|
rx.changed().await.ok()?;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn send<'a>(&'a self, packet: Bytes) -> BoxFuture<'a, Result<(), OverlayError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut rx = self.tun.0.current.subscribe();
|
||||||
|
let fd = rx
|
||||||
|
.borrow_and_update()
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| OverlayError::Unavailable("VPN has no addresses".into()))?;
|
||||||
|
let len = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())),
|
||||||
|
write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) =>
|
||||||
|
write.map_err(|e| OverlayError::Other(e.to_string()))?,
|
||||||
|
};
|
||||||
|
if len != packet.len() {
|
||||||
|
return Err(OverlayError::Other("short VPN datagram write".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TunFactory for AndroidTun {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"Android VpnService"
|
||||||
|
}
|
||||||
|
fn bind_overlay_socket(
|
||||||
|
&self,
|
||||||
|
socket: &tokio::net::TcpSocket,
|
||||||
|
source: std::net::Ipv4Addr,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
(self.0.bind)(socket, source)?;
|
||||||
|
socket.bind((source, 0).into())
|
||||||
|
}
|
||||||
|
fn assigned_addresses(&self) -> Vec<std::net::IpAddr> {
|
||||||
|
self.0
|
||||||
|
.current
|
||||||
|
.borrow()
|
||||||
|
.as_ref()
|
||||||
|
.map(|fd| fd.addresses.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
fn on_host(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
fn create<'a>(
|
||||||
|
&'a self,
|
||||||
|
req: TunRequest,
|
||||||
|
) -> BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let dev = Device {
|
||||||
|
name: req.name.clone(),
|
||||||
|
mtu: req.mtu,
|
||||||
|
tun: self.clone(),
|
||||||
|
};
|
||||||
|
self.reconfigure(req).await?;
|
||||||
|
Ok(Arc::new(dev) as Arc<dyn TunDevice>)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn reconfigure<'a>(&'a self, req: TunRequest) -> BoxFuture<'a, Result<(), OverlayError>> {
|
||||||
|
Box::pin(self.update(move |plan| {
|
||||||
|
plan.addresses = req.addresses;
|
||||||
|
plan.mtu = req.mtu;
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
fn host_rules(&self) -> Option<Arc<dyn BroadcastHostRules>> {
|
||||||
|
Some(Arc::new(self.clone()))
|
||||||
|
}
|
||||||
|
fn destroy<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async {
|
||||||
|
let _ = self.update(|plan| *plan = VpnPlan::default()).await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outcome(result: Result<(), OverlayError>) -> RuleOutcome {
|
||||||
|
match result {
|
||||||
|
Ok(()) => RuleOutcome::Applied,
|
||||||
|
Err(error) => RuleOutcome::Failed(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl BroadcastHostRules for AndroidTun {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"Android VpnService"
|
||||||
|
}
|
||||||
|
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let route = outcome(self.update(|p| p.broadcast = true).await);
|
||||||
|
BroadcastRulesReport {
|
||||||
|
plan: plan.clone(),
|
||||||
|
route,
|
||||||
|
// Android delivers accepted traffic directly through the VPN fd.
|
||||||
|
firewall: RuleOutcome::Applied,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async {
|
||||||
|
let _ = self.update(|p| p.broadcast = false).await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl ExitHostRules for AndroidTun {
|
||||||
|
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let result = self
|
||||||
|
.update(|p| {
|
||||||
|
p.full_tunnel = plan.client;
|
||||||
|
p.exit = plan.client_source.map(Into::into);
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
ExitHostReport {
|
||||||
|
offer: plan
|
||||||
|
.offer
|
||||||
|
.iter()
|
||||||
|
.map(|range| {
|
||||||
|
(
|
||||||
|
*range,
|
||||||
|
RuleOutcome::Failed("Android supports exit clients only".into()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
forwarding: None,
|
||||||
|
client: plan.client.then(|| outcome(result)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async {
|
||||||
|
let _ = self
|
||||||
|
.update(|p| {
|
||||||
|
p.full_tunnel = false;
|
||||||
|
p.exit = None;
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,361 @@
|
|||||||
|
//! Android supplies navigation and the VPN lifecycle to the shared egui forms.
|
||||||
|
use crate::service::{Outcome, Response, State};
|
||||||
|
use egui::{Color32, Context};
|
||||||
|
use egui_phosphor::regular as icon;
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use tsunagi_ui::{
|
||||||
|
about,
|
||||||
|
client::{Client, Command, Snapshot, VipSaveResult},
|
||||||
|
devices,
|
||||||
|
home::{self, UiState},
|
||||||
|
stats::{Traffic, Unit},
|
||||||
|
vip,
|
||||||
|
};
|
||||||
|
use zeroize::{Zeroize, Zeroizing};
|
||||||
|
|
||||||
|
const BAD: Color32 = Color32::from_rgb(0xd0, 0x4a, 0x3c);
|
||||||
|
|
||||||
|
#[derive(Default, PartialEq, Eq)]
|
||||||
|
enum Page {
|
||||||
|
#[default]
|
||||||
|
Home,
|
||||||
|
About,
|
||||||
|
Join,
|
||||||
|
Devices(String),
|
||||||
|
Vips(String),
|
||||||
|
Exit(String),
|
||||||
|
Leave(String),
|
||||||
|
}
|
||||||
|
impl Page {
|
||||||
|
fn network(&self) -> Option<&str> {
|
||||||
|
match self {
|
||||||
|
Self::Devices(id) | Self::Vips(id) | Self::Exit(id) | Self::Leave(id) => Some(id),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn title(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Home => "tsunagi",
|
||||||
|
Self::About => "About",
|
||||||
|
Self::Join => "Join a network",
|
||||||
|
Self::Devices(_) => "Devices",
|
||||||
|
Self::Vips(_) => "VIP",
|
||||||
|
Self::Exit(_) => "Exit node",
|
||||||
|
Self::Leave(_) => "Leave network",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Operations that require the Android activity.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum SystemAction {
|
||||||
|
/// Request VPN consent and start the foreground service.
|
||||||
|
Start,
|
||||||
|
/// Stop the service while preserving this identity and its networks.
|
||||||
|
Stop,
|
||||||
|
/// Read the clipboard after a user gesture.
|
||||||
|
PasteSecret,
|
||||||
|
/// Return to the previous Android activity.
|
||||||
|
Finish,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Actions {
|
||||||
|
command: RefCell<Option<Command>>,
|
||||||
|
busy: bool,
|
||||||
|
}
|
||||||
|
impl Client for Actions {
|
||||||
|
fn send(&self, cmd: Command) {
|
||||||
|
if !self.busy() {
|
||||||
|
self.command.replace(Some(cmd));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn busy(&self) -> bool {
|
||||||
|
self.busy || self.command.borrow().is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Pending {
|
||||||
|
result: Response,
|
||||||
|
vip: Option<String>,
|
||||||
|
go_home: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Presentation state of the single Android viewport.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Phone {
|
||||||
|
page: Page,
|
||||||
|
forms: UiState,
|
||||||
|
traffic: Traffic,
|
||||||
|
snapshot: Snapshot,
|
||||||
|
pending: Option<Pending>,
|
||||||
|
error: Option<String>,
|
||||||
|
clipboard: Option<Zeroizing<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep reads at tray density. Extra hit area is reserved for the navigation bar.
|
||||||
|
pub fn configure(ctx: &Context) {
|
||||||
|
ctx.set_fonts(tsunagi_ui::app_fonts());
|
||||||
|
ctx.style_mut(|style| {
|
||||||
|
style.spacing.interact_size.y = 19.0;
|
||||||
|
style.spacing.button_padding = egui::vec2(6.0, 3.0);
|
||||||
|
style.spacing.item_spacing = egui::vec2(6.0, 3.0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Phone {
|
||||||
|
fn home(&mut self) {
|
||||||
|
if let Page::Vips(id) = &self.page {
|
||||||
|
self.forms.vip_windows.remove(id);
|
||||||
|
}
|
||||||
|
self.forms.join.name.clear();
|
||||||
|
self.forms.join.secret.zeroize();
|
||||||
|
self.forms.exit_confirm = None;
|
||||||
|
self.forms.forget_confirm = None;
|
||||||
|
self.page = Page::Home;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// System Back and toolbar Back use the same draft and confirmation state.
|
||||||
|
pub fn back(&mut self) -> Option<SystemAction> {
|
||||||
|
if self.pending.is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if self.forms.exit_confirm.take().is_some() || self.forms.forget_confirm.take().is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if let Page::Vips(id) = &self.page
|
||||||
|
&& let Some(editor) = self.forms.vip_windows.get_mut(id)
|
||||||
|
&& editor.dirty()
|
||||||
|
{
|
||||||
|
editor.request_close();
|
||||||
|
} else if self.page == Page::Home {
|
||||||
|
return Some(SystemAction::Finish);
|
||||||
|
} else {
|
||||||
|
self.home();
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
/// Accept a user-initiated paste into the join form.
|
||||||
|
pub fn paste_secret(&mut self, value: String) {
|
||||||
|
if self.page == Page::Join {
|
||||||
|
self.forms.join.secret.zeroize();
|
||||||
|
self.forms.join.secret = Zeroizing::new(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Request password input with IME suggestions disabled.
|
||||||
|
pub fn secret_focused(&self, ctx: &Context) -> bool {
|
||||||
|
ctx.memory(|m| m.has_focus("join-secret".into()))
|
||||||
|
}
|
||||||
|
/// Present an error from an Android operation.
|
||||||
|
pub fn error(&mut self, message: String) {
|
||||||
|
self.error = Some(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Take a secret once for the platform’s sensitive clipboard.
|
||||||
|
pub fn take_copied_secret(&mut self) -> Option<Zeroizing<String>> {
|
||||||
|
self.clipboard.take()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn acknowledge(&mut self) {
|
||||||
|
let Some(pending) = &mut self.pending else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let outcome = match pending.result.try_recv() {
|
||||||
|
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return,
|
||||||
|
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
|
||||||
|
Err("VPN service stopped".to_owned())
|
||||||
|
}
|
||||||
|
Ok(v) => v,
|
||||||
|
};
|
||||||
|
if let Some(token) = pending.vip.take() {
|
||||||
|
let result = outcome.and_then(|r| match r {
|
||||||
|
Outcome::Saved(vips) => Ok(vips),
|
||||||
|
_ => Err("Missing VIP save acknowledgement".into()),
|
||||||
|
});
|
||||||
|
self.snapshot.vip_result = Some(VipSaveResult { token, result });
|
||||||
|
} else {
|
||||||
|
match outcome {
|
||||||
|
Ok(Outcome::Clipboard(text)) => self.clipboard = Some(text),
|
||||||
|
Ok(_) if pending.go_home => self.home(),
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) => self.error = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.pending = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render a tray view in this viewport and send gestures to the service.
|
||||||
|
pub fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &Context,
|
||||||
|
state: &State,
|
||||||
|
mut submit: impl FnMut(Command) -> Result<Response, String>,
|
||||||
|
) -> Option<SystemAction> {
|
||||||
|
self.acknowledge();
|
||||||
|
let report = if let State::Ready(report, at) = state {
|
||||||
|
if self.snapshot.at != Some(*at) {
|
||||||
|
self.snapshot.generation = self.snapshot.generation.wrapping_add(1);
|
||||||
|
self.snapshot.at = Some(*at);
|
||||||
|
self.snapshot.status = Some(Ok(report.clone()));
|
||||||
|
self.traffic.observe(report, *at);
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.page
|
||||||
|
.network()
|
||||||
|
.is_some_and(|id| !report.networks.iter().any(|n| n.network_id == id))
|
||||||
|
{
|
||||||
|
self.home();
|
||||||
|
}
|
||||||
|
Some(report)
|
||||||
|
} else {
|
||||||
|
if self.page.network().is_some() || self.page == Page::Join {
|
||||||
|
self.home();
|
||||||
|
}
|
||||||
|
self.snapshot = Snapshot::default();
|
||||||
|
self.traffic = Traffic::default();
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let actions = Actions {
|
||||||
|
command: RefCell::default(),
|
||||||
|
busy: self.pending.is_some(),
|
||||||
|
};
|
||||||
|
let mut system = None;
|
||||||
|
egui::TopBottomPanel::top("navigation").show(ctx, |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.spacing_mut().interact_size.y = 32.0;
|
||||||
|
if self.page != Page::Home && ui.button(icon::ARROW_LEFT).clicked() {
|
||||||
|
system = self.back();
|
||||||
|
}
|
||||||
|
ui.heading(self.page.title());
|
||||||
|
if self.page == Page::Home {
|
||||||
|
ui.weak(env!("CARGO_PKG_VERSION"));
|
||||||
|
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||||
|
if ui.button(icon::INFO).clicked() {
|
||||||
|
self.page = Page::About;
|
||||||
|
}
|
||||||
|
if report.is_some() {
|
||||||
|
ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes");
|
||||||
|
ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if self.page == Page::About
|
||||||
|
&& !matches!(state, State::Off)
|
||||||
|
&& ui.button("Stop VPN").clicked()
|
||||||
|
{
|
||||||
|
system = Some(SystemAction::Stop);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let Some(error) = &self.error {
|
||||||
|
ui.colored_label(BAD, error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let selected = self
|
||||||
|
.page
|
||||||
|
.network()
|
||||||
|
.and_then(|id| report?.networks.iter().find(|n| n.network_id == id));
|
||||||
|
match (&self.page, selected) {
|
||||||
|
(Page::About, _) => about::show(ctx, None, &self.snapshot),
|
||||||
|
(Page::Vips(id), Some(network)) => {
|
||||||
|
let editor = self.forms.vip_windows.entry(id.clone()).or_default();
|
||||||
|
if vip::show(ctx, &actions, editor, network, &self.snapshot) {
|
||||||
|
self.home();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Page::Devices(_), Some(network)) => {
|
||||||
|
if let Some(report) = report {
|
||||||
|
devices::show(
|
||||||
|
ctx,
|
||||||
|
&actions,
|
||||||
|
&mut self.forms.unit,
|
||||||
|
(&mut self.forms.exit_confirm, &mut self.forms.forget_confirm),
|
||||||
|
network,
|
||||||
|
&report.endpoint_id,
|
||||||
|
&self.traffic,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
egui::CentralPanel::default().show(ctx, |ui| {
|
||||||
|
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||||
|
let Some(report) = report else {
|
||||||
|
match state {
|
||||||
|
State::Starting => {ui.spinner(); ui.label("Starting VPN…");}
|
||||||
|
_ => {
|
||||||
|
if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("VPN is stopped");}
|
||||||
|
if ui.button("Start VPN").clicked() {system = Some(SystemAction::Start);}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match &self.page {
|
||||||
|
Page::Home => {
|
||||||
|
home::draw_header(ui, &actions, &mut self.forms, report);
|
||||||
|
ui.separator();
|
||||||
|
if ui.button("Join or create a network").clicked() {self.page = Page::Join;}
|
||||||
|
for n in &report.networks {
|
||||||
|
if home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false) {self.page = Page::Exit(n.network_id.clone());}
|
||||||
|
if self.forms.open_devices.remove(&n.network_id) {self.page = Page::Devices(n.network_id.clone());}
|
||||||
|
if self.forms.vip_windows.contains_key(&n.network_id) {self.page = Page::Vips(n.network_id.clone());}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Page::Join => {
|
||||||
|
home::draw_join(ui, &actions, &mut self.forms.join);
|
||||||
|
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
|
||||||
|
}
|
||||||
|
Page::Exit(_) => {
|
||||||
|
if let Some(n) = selected && let Some(choice) = devices::choose_exit(ui, n, &report.endpoint_id) {
|
||||||
|
self.forms.exit_confirm = Some(choice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Page::Leave(id) => {
|
||||||
|
if let Some(n) = selected {
|
||||||
|
ui.label(format!("Leave {} on this phone? You will need its secret to join again.", n.name));
|
||||||
|
if ui.button("Leave network").clicked() {actions.send(Command::Leave {network_id: id.clone()});}
|
||||||
|
if ui.button("Cancel").clicked() {self.home();}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(command) = actions.command.into_inner() {
|
||||||
|
self.error = None;
|
||||||
|
if let Command::Leave { network_id } = &command
|
||||||
|
&& !matches!(self.page, Page::Leave(_))
|
||||||
|
{
|
||||||
|
self.page = Page::Leave(network_id.clone());
|
||||||
|
} else {
|
||||||
|
let token = match &command {
|
||||||
|
Command::SaveVip { token, .. } => Some(token.clone()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let go_home = matches!(
|
||||||
|
command,
|
||||||
|
Command::Join { .. } | Command::Leave { .. } | Command::SetExitNode { .. }
|
||||||
|
);
|
||||||
|
match submit(command) {
|
||||||
|
Ok(result) => {
|
||||||
|
self.pending = Some(Pending {
|
||||||
|
result,
|
||||||
|
vip: token,
|
||||||
|
go_home,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
if let Some(token) = token {
|
||||||
|
self.snapshot.vip_result = Some(VipSaveResult {
|
||||||
|
token,
|
||||||
|
result: Err(error),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
self.error = Some(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
system
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsunagi-awg"
|
||||||
|
version = "1.0.0"
|
||||||
|
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license = "WTFPL AND Apache-2.0"
|
||||||
|
repository.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tsunagi-wireguard = { path = "../tsunagi-wireguard" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||||
|
iroh.workspace = true
|
||||||
|
tokio = { workspace = true, features = ["net", "time", "sync", "macros"] }
|
||||||
|
bytes.workspace = true
|
||||||
|
rand = "0.10"
|
||||||
|
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
||||||
|
tempfile.workspace = true
|
||||||
|
smoltcp = { version = "0.12", default-features = false, features = ["std", "medium-ip", "proto-ipv4", "socket-tcp"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -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 2026 Friderika Coulson (NanoBee)
|
||||||
|
|
||||||
|
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,21 @@
|
|||||||
|
# Amnezia packet engine
|
||||||
|
|
||||||
|
`../tsunagi-wireguard/src/masking.rs` is adapted from `src/core/amnezia.rs` in
|
||||||
|
https://github.com/RunaRoo/AmneziaWG-RS at
|
||||||
|
`51579a7d6e8882d1d8d6d00822f09e18a9423b73`, under Apache-2.0.
|
||||||
|
The upstream license is retained in both packages as `LICENSE-AmneziaWG-RS`.
|
||||||
|
|
||||||
|
The adaptation replaces configuration-file loading with bounded typed pair
|
||||||
|
profiles, updates RNG calls to rand 0.10, removes an unnecessary unwrap, and
|
||||||
|
does not embed upstream's Node, global executors, OS interface operations or
|
||||||
|
detached tasks. Noise/WireGuard is supplied by boringtun, already used by
|
||||||
|
Tsunagi. Each pair owns one socket and one cancellable packet-engine task.
|
||||||
|
|
||||||
|
This is Tsunagi AWG wire version 2, not a claim of compatibility with external
|
||||||
|
Amnezia servers. The masking engine substitutes message headers outside the
|
||||||
|
standard WireGuard state machine and restores them before Noise validation.
|
||||||
|
There are no remote file paths, shell hooks, or persisted pair profiles.
|
||||||
|
|
||||||
|
The adapted masking source remains Apache-2.0. Newly written Tsunagi code
|
||||||
|
follows the repository's WTFPL. This package declares both licenses in Cargo
|
||||||
|
metadata; the workspace license alone does not describe its copied source.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//! Amnezia-masked UDP carrier using the independent per-neighbour WireGuard engine.
|
||||||
|
pub use tsunagi_wireguard::{
|
||||||
|
AWG_PROTOCOL, AWG_WIRE_VERSION, PairOverview, UdpCarrier as AwgPlugin,
|
||||||
|
UdpTransport as AwgTransport, profile,
|
||||||
|
};
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
//! A real userspace TCP stack attached to each memory TUN, without host routes.
|
||||||
|
use bytes::Bytes;
|
||||||
|
use smoltcp::{
|
||||||
|
iface::{Config, Interface, SocketHandle, SocketSet},
|
||||||
|
phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken},
|
||||||
|
socket::tcp,
|
||||||
|
time::Instant as TcpInstant,
|
||||||
|
wire::{HardwareAddress, IpAddress, IpCidr},
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
net::Ipv4Addr,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tsunagi::overlay::MemoryTun;
|
||||||
|
|
||||||
|
struct TunDevice {
|
||||||
|
input: Arc<Mutex<VecDeque<Vec<u8>>>>,
|
||||||
|
tun: Arc<MemoryTun>,
|
||||||
|
}
|
||||||
|
struct Rx(Vec<u8>);
|
||||||
|
impl RxToken for Rx {
|
||||||
|
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
|
||||||
|
f(&self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Tx(Arc<MemoryTun>);
|
||||||
|
impl TxToken for Tx {
|
||||||
|
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
|
||||||
|
let mut packet = vec![0; len];
|
||||||
|
let result = f(&mut packet);
|
||||||
|
self.0.push_from_os(Bytes::from(packet));
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Device for TunDevice {
|
||||||
|
type RxToken<'a>
|
||||||
|
= Rx
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
type TxToken<'a>
|
||||||
|
= Tx
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
fn receive(&mut self, _: TcpInstant) -> Option<(Rx, Tx)> {
|
||||||
|
self.input
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.pop_front()
|
||||||
|
.map(|packet| (Rx(packet), Tx(self.tun.clone())))
|
||||||
|
}
|
||||||
|
fn transmit(&mut self, _: TcpInstant) -> Option<Tx> {
|
||||||
|
Some(Tx(self.tun.clone()))
|
||||||
|
}
|
||||||
|
fn capabilities(&self) -> DeviceCapabilities {
|
||||||
|
let mut caps = DeviceCapabilities::default();
|
||||||
|
caps.medium = Medium::Ip;
|
||||||
|
caps.max_transmission_unit = 1280;
|
||||||
|
caps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Stack {
|
||||||
|
iface: Interface,
|
||||||
|
sockets: SocketSet<'static>,
|
||||||
|
socket: SocketHandle,
|
||||||
|
device: TunDevice,
|
||||||
|
reader: tokio::task::JoinHandle<()>,
|
||||||
|
}
|
||||||
|
impl Stack {
|
||||||
|
fn new(tun: Arc<MemoryTun>, address: Ipv4Addr) -> Self {
|
||||||
|
let input = Arc::new(Mutex::new(VecDeque::new()));
|
||||||
|
let queue = input.clone();
|
||||||
|
let received = tun.clone();
|
||||||
|
let reader = tokio::spawn(async move {
|
||||||
|
while let Some(packet) = received.pop_to_os().await {
|
||||||
|
let mut queue = queue.lock().unwrap();
|
||||||
|
assert!(queue.len() < 256);
|
||||||
|
queue.push_back(packet.to_vec());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let mut device = TunDevice { input, tun };
|
||||||
|
let mut config = Config::new(HardwareAddress::Ip);
|
||||||
|
config.random_seed = rand::random();
|
||||||
|
let mut iface = Interface::new(config, &mut device, TcpInstant::from_millis(0));
|
||||||
|
let [a, b, c, d] = address.octets();
|
||||||
|
iface.update_ip_addrs(|addresses| {
|
||||||
|
addresses
|
||||||
|
.push(IpCidr::new(IpAddress::v4(a, b, c, d), 24))
|
||||||
|
.unwrap()
|
||||||
|
});
|
||||||
|
let mut sockets = SocketSet::new(Vec::new());
|
||||||
|
let socket = sockets.add(tcp::Socket::new(
|
||||||
|
tcp::SocketBuffer::new(vec![0; 65536]),
|
||||||
|
tcp::SocketBuffer::new(vec![0; 65536]),
|
||||||
|
));
|
||||||
|
Self {
|
||||||
|
iface,
|
||||||
|
sockets,
|
||||||
|
socket,
|
||||||
|
device,
|
||||||
|
reader,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn tcp(&mut self) -> &mut tcp::Socket<'static> {
|
||||||
|
self.sockets.get_mut(self.socket)
|
||||||
|
}
|
||||||
|
fn poll(&mut self, now: TcpInstant) {
|
||||||
|
self.iface.poll(now, &mut self.device, &mut self.sockets);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for Stack {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.reader.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct TcpPair {
|
||||||
|
client: Stack,
|
||||||
|
server: Stack,
|
||||||
|
started: Instant,
|
||||||
|
}
|
||||||
|
impl TcpPair {
|
||||||
|
pub(super) async fn connect(
|
||||||
|
a: Arc<MemoryTun>,
|
||||||
|
a_ip: Ipv4Addr,
|
||||||
|
b: Arc<MemoryTun>,
|
||||||
|
b_ip: Ipv4Addr,
|
||||||
|
) -> Self {
|
||||||
|
let mut pair = Self {
|
||||||
|
client: Stack::new(a, a_ip),
|
||||||
|
server: Stack::new(b, b_ip),
|
||||||
|
started: Instant::now(),
|
||||||
|
};
|
||||||
|
pair.server.tcp().listen(22).unwrap();
|
||||||
|
let [a, b, c, d] = b_ip.octets();
|
||||||
|
pair.client
|
||||||
|
.sockets
|
||||||
|
.get_mut::<tcp::Socket>(pair.client.socket)
|
||||||
|
.connect(
|
||||||
|
pair.client.iface.context(),
|
||||||
|
(IpAddress::v4(a, b, c, d), 22),
|
||||||
|
40000,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
pair.until(|p| {
|
||||||
|
p.client.tcp().state() == tcp::State::Established
|
||||||
|
&& p.server.tcp().state() == tcp::State::Established
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
pair
|
||||||
|
}
|
||||||
|
fn poll(&mut self) {
|
||||||
|
let now = TcpInstant::from_millis(self.started.elapsed().as_millis() as i64);
|
||||||
|
self.client.poll(now);
|
||||||
|
self.server.poll(now);
|
||||||
|
}
|
||||||
|
async fn until(&mut self, mut ready: impl FnMut(&mut Self) -> bool) {
|
||||||
|
tokio::time::timeout(Duration::from_secs(10), async {
|
||||||
|
let mut ticks = tokio::time::interval(Duration::from_millis(2));
|
||||||
|
loop {
|
||||||
|
ticks.tick().await;
|
||||||
|
self.poll();
|
||||||
|
if ready(self) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("same TCP connection must progress across carrier/route changes");
|
||||||
|
}
|
||||||
|
pub(super) fn queue_while_unreachable(&mut self, payload: &[u8]) {
|
||||||
|
assert_eq!(
|
||||||
|
self.client.tcp().send_slice(payload).unwrap(),
|
||||||
|
payload.len()
|
||||||
|
);
|
||||||
|
self.poll();
|
||||||
|
}
|
||||||
|
pub(super) async fn receive_queued(&mut self, payload: &[u8]) {
|
||||||
|
let mut received = Vec::new();
|
||||||
|
self.until(|p| {
|
||||||
|
if p.server.tcp().can_recv() {
|
||||||
|
p.server
|
||||||
|
.tcp()
|
||||||
|
.recv(|bytes| {
|
||||||
|
received.extend_from_slice(bytes);
|
||||||
|
(bytes.len(), ())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
received.len() >= payload.len()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(received, payload);
|
||||||
|
assert_eq!(self.client.tcp().state(), tcp::State::Established);
|
||||||
|
assert_eq!(self.server.tcp().state(), tcp::State::Established);
|
||||||
|
}
|
||||||
|
pub(super) async fn exchange(&mut self, payload: &[u8]) {
|
||||||
|
self.queue_while_unreachable(payload);
|
||||||
|
self.receive_queued(payload).await;
|
||||||
|
assert_eq!(
|
||||||
|
self.server.tcp().send_slice(payload).unwrap(),
|
||||||
|
payload.len()
|
||||||
|
);
|
||||||
|
let mut received = Vec::new();
|
||||||
|
self.until(|p| {
|
||||||
|
if p.client.tcp().can_recv() {
|
||||||
|
p.client
|
||||||
|
.tcp()
|
||||||
|
.recv(|bytes| {
|
||||||
|
received.extend_from_slice(bytes);
|
||||||
|
(bytes.len(), ())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
received.len() >= payload.len()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(received, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,947 @@
|
|||||||
|
//! Real membership, UDP sockets, pair negotiation and nested WireGuard encryption.
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
#[path = "common/tcp.rs"]
|
||||||
|
mod tcp;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use std::{
|
||||||
|
net::Ipv4Addr,
|
||||||
|
path::Path,
|
||||||
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||||
|
},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
use tempfile::TempDir;
|
||||||
|
use tsunagi::dataplane::IpPlugin;
|
||||||
|
use tsunagi::dataplane::transport::{
|
||||||
|
ControlSender, PacketLink, PacketTransport, SharedLink, TransportError,
|
||||||
|
};
|
||||||
|
use tsunagi::discovery::SharedMemoryDiscovery;
|
||||||
|
use tsunagi::overlay::{MemoryTun, MemoryTunFactory};
|
||||||
|
use tsunagi::testing::{config_with, network, wait_for_peers, wait_until};
|
||||||
|
use tsunagi::{Agent, BoxFuture, NetworkId};
|
||||||
|
use tsunagi_awg::{AWG_PROTOCOL, AwgPlugin, AwgTransport};
|
||||||
|
use tsunagi_wg_quic::WireguardConfig;
|
||||||
|
|
||||||
|
struct Node {
|
||||||
|
agent: Agent,
|
||||||
|
plugin: Arc<tsunagi_wg_quic::WireguardPlugin>,
|
||||||
|
transport: Arc<AwgTransport>,
|
||||||
|
tuns: MemoryTunFactory,
|
||||||
|
loss: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
impl Node {
|
||||||
|
async fn open(root: &Path, discovery: &SharedMemoryDiscovery, interface: &str) -> Self {
|
||||||
|
Self::open_with_fallback(root, discovery, interface, false).await
|
||||||
|
}
|
||||||
|
async fn open_with_fallback(
|
||||||
|
root: &Path,
|
||||||
|
discovery: &SharedMemoryDiscovery,
|
||||||
|
interface: &str,
|
||||||
|
fallback: bool,
|
||||||
|
) -> Self {
|
||||||
|
Self::open_config(root, discovery, interface, fallback, 1280).await
|
||||||
|
}
|
||||||
|
async fn open_config(
|
||||||
|
root: &Path,
|
||||||
|
discovery: &SharedMemoryDiscovery,
|
||||||
|
interface: &str,
|
||||||
|
fallback: bool,
|
||||||
|
mtu: u32,
|
||||||
|
) -> Self {
|
||||||
|
Self::open_selected(root, discovery, interface, fallback, mtu, None).await
|
||||||
|
}
|
||||||
|
async fn open_selected(
|
||||||
|
root: &Path,
|
||||||
|
discovery: &SharedMemoryDiscovery,
|
||||||
|
interface: &str,
|
||||||
|
fallback: bool,
|
||||||
|
mtu: u32,
|
||||||
|
default_protocols: Option<Vec<String>>,
|
||||||
|
) -> Self {
|
||||||
|
let identity =
|
||||||
|
tsunagi::storage::StateStore::open(tsunagi::StoragePaths::under(root).state_db())
|
||||||
|
.unwrap()
|
||||||
|
.load_or_create_device_identity()
|
||||||
|
.unwrap();
|
||||||
|
let transport = AwgTransport::new(identity.endpoint_id(), Ipv4Addr::LOCALHOST);
|
||||||
|
let plugin = tsunagi_wg_quic::WireguardPlugin::open(
|
||||||
|
WireguardConfig::new(root.join("awg"))
|
||||||
|
.with_mtu(mtu)
|
||||||
|
.with_reconcile(Duration::from_millis(20), Duration::from_millis(250)),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let loss = Arc::new(AtomicBool::new(false));
|
||||||
|
let faults = Arc::new(FaultTransport {
|
||||||
|
inner: transport.clone(),
|
||||||
|
loss: loss.clone(),
|
||||||
|
});
|
||||||
|
let tuns = MemoryTunFactory::new();
|
||||||
|
let mut config = config_with(root, discovery)
|
||||||
|
.with_interface(Arc::new(tuns.clone()), interface, mtu)
|
||||||
|
.with_tunnel(plugin.clone() as Arc<dyn IpPlugin>)
|
||||||
|
.with_carrier(AwgPlugin::new(transport.clone()))
|
||||||
|
.with_custom_transport(AWG_PROTOCOL, faults);
|
||||||
|
if fallback {
|
||||||
|
config = config.with_carrier(Arc::new(
|
||||||
|
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
config.default_protocols = default_protocols;
|
||||||
|
let agent = Agent::spawn(config).await.unwrap();
|
||||||
|
let inbound_agent = agent.clone();
|
||||||
|
let inbound_transport = transport.clone();
|
||||||
|
let inbound_loss = loss.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Some(mut link) = inbound_transport.next_inbound().await {
|
||||||
|
link.link = impaired(link.link, inbound_loss.clone());
|
||||||
|
let _ = inbound_agent.install_inbound_link(link).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self {
|
||||||
|
agent,
|
||||||
|
plugin,
|
||||||
|
transport,
|
||||||
|
tuns,
|
||||||
|
loss,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn ready(&self, id: NetworkId, n: usize) {
|
||||||
|
wait_until("AWG outer paths and end-to-end handshakes", || async {
|
||||||
|
(self
|
||||||
|
.transport
|
||||||
|
.overview(id)
|
||||||
|
.iter()
|
||||||
|
.filter(|p| !p.closed && !p.path.contains("establishing"))
|
||||||
|
.count()
|
||||||
|
== n
|
||||||
|
&& self
|
||||||
|
.plugin
|
||||||
|
.overview(id)?
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.filter(|p| {
|
||||||
|
p.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|t| t.health.is_up() && t.path.contains("awg UDP via"))
|
||||||
|
})
|
||||||
|
.count()
|
||||||
|
== n)
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
fn tun(&self) -> Arc<MemoryTun> {
|
||||||
|
self.tuns
|
||||||
|
.device(&self.agent.overlay().unwrap().interface)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
fn addr(&self, id: NetworkId) -> Ipv4Addr {
|
||||||
|
self.plugin
|
||||||
|
.overview(id)
|
||||||
|
.unwrap()
|
||||||
|
.overlay_address_v4
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn packet(source: Ipv4Addr, dest: Ipv4Addr, len: usize) -> Bytes {
|
||||||
|
let mut bytes = vec![0; len];
|
||||||
|
bytes[0] = 0x45;
|
||||||
|
bytes[2..4].copy_from_slice(&(len as u16).to_be_bytes());
|
||||||
|
bytes[8] = 64;
|
||||||
|
bytes[9] = 253;
|
||||||
|
bytes[12..16].copy_from_slice(&source.octets());
|
||||||
|
bytes[16..20].copy_from_slice(&dest.octets());
|
||||||
|
rand::fill(&mut bytes[20..]);
|
||||||
|
Bytes::from(bytes)
|
||||||
|
}
|
||||||
|
async fn exchange(a: &Node, b: &Node, id: NetworkId) {
|
||||||
|
for len in [64, 1097, 1280] {
|
||||||
|
let bytes = packet(a.addr(id), b.addr(id), len);
|
||||||
|
a.tun().push_from_os(bytes.clone());
|
||||||
|
assert_eq!(
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), b.tun().pop_to_os())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap(),
|
||||||
|
bytes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_control_only_agent_enables_real_data_without_restart_and_cancels_stale_attempts() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
|
let a = Node::open_selected(
|
||||||
|
roots[0].path(),
|
||||||
|
&discovery,
|
||||||
|
"initial-none-a",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec![]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let b = Node::open_selected(
|
||||||
|
roots[1].path(),
|
||||||
|
&discovery,
|
||||||
|
"initial-none-b",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec![]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (name, secret) = network("enable-after-control-only");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
wait_for_peers(&a.agent, id, 1).await;
|
||||||
|
wait_for_peers(&b.agent, id, 1).await;
|
||||||
|
assert!(a.agent.overlay().is_none());
|
||||||
|
assert!(b.agent.overlay().is_none());
|
||||||
|
for node in [&a, &b] {
|
||||||
|
assert!(
|
||||||
|
node.agent
|
||||||
|
.network_status(id)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.protocols
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
node.agent
|
||||||
|
.set_protocols(id, vec!["awg".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(node.agent.overlay().is_some());
|
||||||
|
}
|
||||||
|
a.ready(id, 1).await;
|
||||||
|
b.ready(id, 1).await;
|
||||||
|
exchange(&a, &b, id).await;
|
||||||
|
let before = a.agent.overlay().unwrap().interface;
|
||||||
|
// Changes race unfinished opens and prepared plugin callbacks; the last
|
||||||
|
// selection must win even if an earlier open has completed in its queue.
|
||||||
|
for selection in [
|
||||||
|
vec!["wg-quic".into()],
|
||||||
|
vec![],
|
||||||
|
vec!["awg".into()],
|
||||||
|
vec![],
|
||||||
|
vec!["awg".into()],
|
||||||
|
] {
|
||||||
|
a.agent.set_protocols(id, selection).await.unwrap();
|
||||||
|
}
|
||||||
|
a.ready(id, 1).await;
|
||||||
|
b.ready(id, 1).await;
|
||||||
|
exchange(&a, &b, id).await;
|
||||||
|
assert_eq!(a.agent.overlay().unwrap().interface, before);
|
||||||
|
for node in [&a, &b] {
|
||||||
|
let status = node.agent.network_status(id).await.unwrap();
|
||||||
|
assert_eq!(status.protocols, ["awg"]);
|
||||||
|
assert_eq!(status.metrics.sessions_established, 1);
|
||||||
|
assert_eq!(status.metrics.disconnects, 0);
|
||||||
|
}
|
||||||
|
a.agent.shutdown().await;
|
||||||
|
b.agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn runtime_protocol_selection_preserves_real_tunnels_and_survives_restart() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
|
let a = Node::open_with_fallback(roots[0].path(), &discovery, "runtime-a", true).await;
|
||||||
|
let b = Node::open_with_fallback(roots[1].path(), &discovery, "runtime-b", true).await;
|
||||||
|
let (name, secret) = network("runtime-protocols");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
a.ready(id, 1).await;
|
||||||
|
b.ready(id, 1).await;
|
||||||
|
exchange(&a, &b, id).await;
|
||||||
|
let original_key = a.plugin.overview(id).unwrap().public_key;
|
||||||
|
let original_stats = a.plugin.overview(id).unwrap().peers[0]
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats;
|
||||||
|
|
||||||
|
let (other_name, other_secret, other_id) = loop {
|
||||||
|
let (name, secret) = network("unchanged-runtime-network");
|
||||||
|
let other_id = tsunagi::identity::NetworkKeys::derive(&name, &secret).network_id();
|
||||||
|
if tsunagi::state::derived_ipv4_range(id) != tsunagi::state::derived_ipv4_range(other_id) {
|
||||||
|
break (name, secret, other_id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
a.agent
|
||||||
|
.join_network(&other_name, &other_secret)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
b.agent
|
||||||
|
.join_network(&other_name, &other_secret)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
a.ready(other_id, 1).await;
|
||||||
|
b.ready(other_id, 1).await;
|
||||||
|
let other_before = a
|
||||||
|
.agent
|
||||||
|
.network_status(other_id)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.metrics
|
||||||
|
.data_links_established;
|
||||||
|
|
||||||
|
for node in [&a, &b] {
|
||||||
|
let before = node.agent.network_status(id).await.unwrap().protocols;
|
||||||
|
for invalid in [vec!["unknown".into()], vec!["awg".into(), "awg".into()]] {
|
||||||
|
assert!(node.agent.set_protocols(id, invalid).await.is_err());
|
||||||
|
assert_eq!(
|
||||||
|
node.agent.network_status(id).await.unwrap().protocols,
|
||||||
|
before
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Exercise updates initiated by either endpoint-id role, including an
|
||||||
|
// empty set. Membership and the control session stay alive throughout.
|
||||||
|
for node in [&a, &b] {
|
||||||
|
node.agent.set_protocols(id, Vec::new()).await.unwrap();
|
||||||
|
wait_until("peer accepts control-only selection", || async {
|
||||||
|
let other = if node.agent.endpoint_id() == a.agent.endpoint_id() {
|
||||||
|
&b
|
||||||
|
} else {
|
||||||
|
&a
|
||||||
|
};
|
||||||
|
let status = other.agent.network_status(id).await.ok()?;
|
||||||
|
(status.peers.len() == 1
|
||||||
|
&& status.peers[0].protocols.is_empty()
|
||||||
|
&& matches!(status.peers[0].data_path, tsunagi::agent::DataPath::None))
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(node.agent.network_status(id).await.unwrap().peers.len(), 1);
|
||||||
|
node.agent
|
||||||
|
.set_protocols(id, vec!["wg-quic".into(), "awg".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
a.agent
|
||||||
|
.set_protocols(id, vec!["wg-quic".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
wait_until("real QUIC replaces AWG", || async {
|
||||||
|
let a_status = a.agent.network_status(id).await.ok()?;
|
||||||
|
let b_status = b.agent.network_status(id).await.ok()?;
|
||||||
|
(a_status.peers[0].protocols == ["wg-quic"]
|
||||||
|
&& b_status.peers[0].protocols == ["wg-quic"]
|
||||||
|
&& !matches!(a_status.peers[0].data_path, tsunagi::agent::DataPath::None)
|
||||||
|
&& !matches!(b_status.peers[0].data_path, tsunagi::agent::DataPath::None)
|
||||||
|
&& a.transport.overview(id).iter().all(|p| p.closed)
|
||||||
|
&& b.transport.overview(id).iter().all(|p| p.closed))
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(a.plugin.overview(id).unwrap().public_key, original_key);
|
||||||
|
let stats = a.plugin.overview(id).unwrap().peers[0]
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats;
|
||||||
|
assert_eq!(stats.counter_epoch, original_stats.counter_epoch);
|
||||||
|
assert!(stats.tx_bytes >= original_stats.tx_bytes);
|
||||||
|
assert!(stats.rx_bytes >= original_stats.rx_bytes);
|
||||||
|
assert!(a.plugin.overview(id).unwrap().peers.iter().any(|peer| {
|
||||||
|
peer.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|tunnel| tunnel.health.is_up())
|
||||||
|
}));
|
||||||
|
// The same internal plugin supplies addresses and counters on the new carrier.
|
||||||
|
for (source, dest) in [(&a, &b), (&b, &a)] {
|
||||||
|
wait_until("QUIC end-to-end handshake", || async {
|
||||||
|
source
|
||||||
|
.plugin
|
||||||
|
.overview(id)?
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.any(|p| p.tunnel.as_ref().is_some_and(|t| t.health.is_up()))
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let addr = |n: &Node| n.plugin.overview(id).unwrap().overlay_address_v4.unwrap();
|
||||||
|
let bytes = packet(addr(source), addr(dest), 1280);
|
||||||
|
source.tun().push_from_os(bytes.clone());
|
||||||
|
assert_eq!(
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), dest.tun().pop_to_os())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap(),
|
||||||
|
bytes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
a.agent
|
||||||
|
.network_status(other_id)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.metrics
|
||||||
|
.data_links_established,
|
||||||
|
other_before
|
||||||
|
);
|
||||||
|
exchange(&a, &b, other_id).await;
|
||||||
|
a.agent.shutdown().await;
|
||||||
|
let restarted = Node::open_with_fallback(roots[0].path(), &discovery, "runtime-a", true).await;
|
||||||
|
wait_for_peers(&restarted.agent, id, 1).await;
|
||||||
|
assert_eq!(
|
||||||
|
restarted.agent.network_status(id).await.unwrap().protocols,
|
||||||
|
["wg-quic"]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
b.agent.network_status(other_id).await.unwrap().protocols,
|
||||||
|
["awg", "wg-quic"]
|
||||||
|
);
|
||||||
|
restarted.ready(other_id, 1).await;
|
||||||
|
b.ready(other_id, 1).await;
|
||||||
|
exchange(&restarted, &b, other_id).await;
|
||||||
|
restarted
|
||||||
|
.agent
|
||||||
|
.set_protocols(id, vec!["awg".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
restarted.ready(id, 1).await;
|
||||||
|
b.ready(id, 1).await;
|
||||||
|
exchange(&restarted, &b, id).await;
|
||||||
|
restarted.agent.shutdown().await;
|
||||||
|
b.agent.shutdown().await;
|
||||||
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
async fn real_pairs_carry_full_size_packets_and_restart_with_fresh_profiles() {
|
||||||
|
tsunagi::testing::init_tracing();
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
];
|
||||||
|
let a = Node::open(roots[0].path(), &discovery, "awga").await;
|
||||||
|
let b = Node::open(roots[1].path(), &discovery, "awgb").await;
|
||||||
|
let c = Node::open(roots[2].path(), &discovery, "awgc").await;
|
||||||
|
let (name, secret) = network("awg-pairs");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
c.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
for node in [&a, &b, &c] {
|
||||||
|
wait_for_peers(&node.agent, id, 2).await;
|
||||||
|
node.ready(id, 2).await;
|
||||||
|
}
|
||||||
|
let ids: std::collections::HashSet<_> = [&a, &b, &c]
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|n| n.transport.overview(id).into_iter().map(|p| p.attempt))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
ids.len(),
|
||||||
|
3,
|
||||||
|
"one independent profile for each of three pairs"
|
||||||
|
);
|
||||||
|
exchange(&a, &b, id).await;
|
||||||
|
exchange(&b, &a, id).await;
|
||||||
|
exchange(&a, &c, id).await;
|
||||||
|
let old_ports: Vec<_> = a
|
||||||
|
.transport
|
||||||
|
.overview(id)
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|p| p.local_port)
|
||||||
|
.collect();
|
||||||
|
a.agent.shutdown().await;
|
||||||
|
for port in old_ports {
|
||||||
|
wait_until("old pair socket released", || async {
|
||||||
|
tokio::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, port))
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
let restarted = Node::open(roots[0].path(), &discovery, "awga").await;
|
||||||
|
restarted.ready(id, 2).await;
|
||||||
|
assert!(
|
||||||
|
restarted
|
||||||
|
.transport
|
||||||
|
.overview(id)
|
||||||
|
.iter()
|
||||||
|
.all(|p| !ids.contains(&p.attempt))
|
||||||
|
);
|
||||||
|
exchange(&restarted, &b, id).await;
|
||||||
|
exchange(&c, &restarted, id).await;
|
||||||
|
restarted.agent.shutdown().await;
|
||||||
|
b.agent.shutdown().await;
|
||||||
|
c.agent.shutdown().await;
|
||||||
|
assert!(
|
||||||
|
tokio::time::timeout(Duration::from_secs(1), restarted.transport.next_inbound())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drops datagrams at the link boundary. Membership, control, sockets, crypto,
|
||||||
|
// addressing and storage remain real. This substitutes a lossy physical path.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct FaultTransport {
|
||||||
|
inner: Arc<AwgTransport>,
|
||||||
|
loss: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
impl PacketTransport for FaultTransport {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
AWG_PROTOCOL
|
||||||
|
}
|
||||||
|
fn as_any(&self) -> &dyn std::any::Any {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
fn attach_control(&self, sender: Arc<dyn ControlSender>) {
|
||||||
|
self.inner.attach_control(sender);
|
||||||
|
}
|
||||||
|
fn on_control(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: iroh::EndpointId,
|
||||||
|
protocol: &str,
|
||||||
|
bytes: &[u8],
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
self.inner.on_control(network, peer, protocol, bytes)
|
||||||
|
}
|
||||||
|
fn open<'a>(
|
||||||
|
&'a self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: iroh::EndpointId,
|
||||||
|
protocol: &'a str,
|
||||||
|
) -> BoxFuture<'a, Result<SharedLink, TransportError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
Ok(impaired(
|
||||||
|
self.inner.open(network, peer, protocol).await?,
|
||||||
|
self.loss.clone(),
|
||||||
|
))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn impaired(raw: SharedLink, loss: Arc<AtomicBool>) -> SharedLink {
|
||||||
|
Arc::new(FaultLink {
|
||||||
|
raw,
|
||||||
|
loss,
|
||||||
|
sequence: AtomicU64::new(0),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct FaultLink {
|
||||||
|
raw: SharedLink,
|
||||||
|
loss: Arc<AtomicBool>,
|
||||||
|
sequence: AtomicU64,
|
||||||
|
}
|
||||||
|
impl PacketLink for FaultLink {
|
||||||
|
fn network(&self) -> NetworkId {
|
||||||
|
self.raw.network()
|
||||||
|
}
|
||||||
|
fn peer(&self) -> iroh::EndpointId {
|
||||||
|
self.raw.peer()
|
||||||
|
}
|
||||||
|
fn max_datagram_size(&self) -> usize {
|
||||||
|
self.raw.max_datagram_size()
|
||||||
|
}
|
||||||
|
fn send(&self, bytes: Bytes) -> Result<(), TransportError> {
|
||||||
|
if self.loss.load(Ordering::Relaxed)
|
||||||
|
&& !self
|
||||||
|
.sequence
|
||||||
|
.fetch_add(1, Ordering::Relaxed)
|
||||||
|
.is_multiple_of(5)
|
||||||
|
{
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
self.raw.send(bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
|
||||||
|
self.raw.recv()
|
||||||
|
}
|
||||||
|
fn closed(&self) -> BoxFuture<'_, ()> {
|
||||||
|
self.raw.closed()
|
||||||
|
}
|
||||||
|
fn is_closed(&self) -> bool {
|
||||||
|
self.raw.is_closed()
|
||||||
|
}
|
||||||
|
fn close(&self) {
|
||||||
|
self.raw.close();
|
||||||
|
}
|
||||||
|
fn path_description(&self) -> String {
|
||||||
|
self.raw.path_description()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
async fn persistent_runtime_loss_retires_the_pair_and_negotiates_fresh_parameters() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
|
let a = Node::open(roots[0].path(), &discovery, "lossa").await;
|
||||||
|
let b = Node::open(roots[1].path(), &discovery, "lossb").await;
|
||||||
|
let (name, secret) = network("awg-loss");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
a.ready(id, 1).await;
|
||||||
|
b.ready(id, 1).await;
|
||||||
|
exchange(&a, &b, id).await;
|
||||||
|
let old = a.transport.overview(id)[0].attempt;
|
||||||
|
let mut events = a.agent.subscribe();
|
||||||
|
a.loss.store(true, Ordering::Relaxed);
|
||||||
|
tsunagi::testing::wait_event(&mut events, |event| match event {
|
||||||
|
tsunagi::Event::DataLinkDown {
|
||||||
|
network, reason, ..
|
||||||
|
} if *network == id && reason.contains("delivery checks") => Some(()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
a.loss.store(false, Ordering::Relaxed);
|
||||||
|
wait_until("fresh AWG profile after runtime loss", || async {
|
||||||
|
a.transport
|
||||||
|
.overview(id)
|
||||||
|
.iter()
|
||||||
|
.any(|p| p.attempt != old && !p.closed && !p.path.contains("establishing"))
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
a.ready(id, 1).await;
|
||||||
|
b.ready(id, 1).await;
|
||||||
|
let initiator = if a.agent.endpoint_id().as_bytes() < b.agent.endpoint_id().as_bytes() {
|
||||||
|
&a
|
||||||
|
} else {
|
||||||
|
&b
|
||||||
|
};
|
||||||
|
let attempt = initiator.transport.overview(id)[0].attempt;
|
||||||
|
let received = initiator.transport.overview(id)[0].delivery_checks;
|
||||||
|
wait_until(
|
||||||
|
"fresh physical delivery checks answered after installation",
|
||||||
|
|| async {
|
||||||
|
(initiator.transport.overview(id).first()?.delivery_checks >= received + 3)
|
||||||
|
.then_some(())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(initiator.transport.overview(id)[0].attempt, attempt);
|
||||||
|
wait_for_peers(&a.agent, id, 1).await;
|
||||||
|
exchange(&a, &b, id).await;
|
||||||
|
exchange(&b, &a, id).await;
|
||||||
|
a.agent.shutdown().await;
|
||||||
|
b.agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn runtime_loss_falls_back_to_real_iroh_without_interrupting_control_or_ip() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
|
let a = Node::open_with_fallback(roots[0].path(), &discovery, "fallba", true).await;
|
||||||
|
let b = Node::open_with_fallback(roots[1].path(), &discovery, "fallbb", true).await;
|
||||||
|
let (name, secret) = network("awg-fallback");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
a.ready(id, 1).await;
|
||||||
|
b.ready(id, 1).await;
|
||||||
|
exchange(&a, &b, id).await;
|
||||||
|
let mut events = a.agent.subscribe();
|
||||||
|
a.loss.store(true, Ordering::Relaxed);
|
||||||
|
tsunagi::testing::wait_event(&mut events, |event| match event {
|
||||||
|
tsunagi::Event::DataLinkDown {
|
||||||
|
network, reason, ..
|
||||||
|
} if *network == id && reason.contains("delivery checks") => Some(()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
for node in [&a, &b] {
|
||||||
|
wait_until("fallback carrier is wg-quic",||async {
|
||||||
|
let status=node.agent.status().await.ok()?;
|
||||||
|
let network=status.networks.iter().find(|n|n.network_id==id)?;
|
||||||
|
(network.members.iter().any(|m|matches!(&m.data_path,tsunagi::agent::DataPath::Direct{transport} if transport=="wg-quic"))).then_some(())
|
||||||
|
}).await;
|
||||||
|
wait_for_peers(&node.agent, id, 1).await;
|
||||||
|
}
|
||||||
|
exchange(&a, &b, id).await;
|
||||||
|
exchange(&b, &a, id).await;
|
||||||
|
a.agent.shutdown().await;
|
||||||
|
b.agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn opaque_pair_carrier_fragments_its_full_advertised_capacity() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
|
let mut nodes = Vec::new();
|
||||||
|
for root in &roots {
|
||||||
|
let identity = tsunagi::storage::StateStore::open(
|
||||||
|
tsunagi::StoragePaths::under(root.path()).state_db(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.load_or_create_device_identity()
|
||||||
|
.unwrap();
|
||||||
|
let transport = AwgTransport::new(identity.endpoint_id(), Ipv4Addr::LOCALHOST);
|
||||||
|
let agent = Agent::spawn(
|
||||||
|
config_with(root.path(), &discovery)
|
||||||
|
.with_custom_transport(AWG_PROTOCOL, transport.clone()),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
nodes.push((agent, transport));
|
||||||
|
}
|
||||||
|
let (name, secret) = network("awg-capacity");
|
||||||
|
let id = nodes[0].0.join_network(&name, &secret).await.unwrap();
|
||||||
|
nodes[1].0.join_network(&name, &secret).await.unwrap();
|
||||||
|
for (i, (agent, transport)) in nodes.iter().enumerate() {
|
||||||
|
wait_for_peers(agent, id, 1).await;
|
||||||
|
// This fixture tests only the transport contract: register the member
|
||||||
|
// after the real core has authenticated it, without an IP plugin/TUN.
|
||||||
|
transport.allow_peer(id, nodes[1 - i].0.endpoint_id());
|
||||||
|
}
|
||||||
|
nodes.sort_by_key(|(agent, _)| *agent.endpoint_id().as_bytes());
|
||||||
|
let outgoing = nodes[0]
|
||||||
|
.1
|
||||||
|
.open(id, nodes[1].0.endpoint_id(), AWG_PROTOCOL)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let incoming = tokio::time::timeout(Duration::from_secs(5), nodes[1].1.next_inbound())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.link;
|
||||||
|
for (from, to) in [(&outgoing, &incoming), (&incoming, &outgoing)] {
|
||||||
|
let mut bytes = vec![0; from.max_datagram_size()];
|
||||||
|
rand::fill(&mut bytes[..]);
|
||||||
|
let bytes = Bytes::from(bytes);
|
||||||
|
from.send(bytes.clone()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), to.recv())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap(),
|
||||||
|
bytes
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
from.send(Bytes::from(vec![0; from.max_datagram_size() + 1])),
|
||||||
|
Err(TransportError::TooLarge { .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
outgoing.close();
|
||||||
|
incoming.close();
|
||||||
|
for (agent, transport) in nodes {
|
||||||
|
transport.shutdown();
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn encrypted_health_checks_fit_a_smaller_peers_configured_interface_mtu() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
|
let a = Node::open_config(roots[0].path(), &discovery, "smalla", false, 1280).await;
|
||||||
|
let b = Node::open_config(roots[1].path(), &discovery, "smallb", false, 576).await;
|
||||||
|
let (name, secret) = network("awg-small-mtu");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
a.ready(id, 1).await;
|
||||||
|
b.ready(id, 1).await;
|
||||||
|
let bytes = packet(a.addr(id), b.addr(id), 576);
|
||||||
|
a.tun().push_from_os(bytes.clone());
|
||||||
|
assert_eq!(
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), b.tun().pop_to_os())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap(),
|
||||||
|
bytes
|
||||||
|
);
|
||||||
|
wait_until(
|
||||||
|
"physical delivery checks do not depend on overlay MTU",
|
||||||
|
|| async {
|
||||||
|
(a.transport.overview(id).first()?.delivery_checks >= 4
|
||||||
|
&& b.transport.overview(id).first()?.delivery_checks >= 4)
|
||||||
|
.then_some(())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
for node in [&a, &b] {
|
||||||
|
assert_eq!(
|
||||||
|
node.plugin.overview(id).unwrap().peers[0]
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.dropped_oversize,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
a.agent.shutdown().await;
|
||||||
|
b.agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn disjoint_external_policies_relay_the_same_internal_tunnel_and_keep_it_when_routes_change()
|
||||||
|
{
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
];
|
||||||
|
let a = Node::open_selected(
|
||||||
|
roots[0].path(),
|
||||||
|
&discovery,
|
||||||
|
"only-awg",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec!["awg".into()]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let b = Node::open_with_fallback(roots[1].path(), &discovery, "mixed-relay", true).await;
|
||||||
|
let c = Node::open_selected(
|
||||||
|
roots[2].path(),
|
||||||
|
&discovery,
|
||||||
|
"only-quic",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec!["wg-quic".into()]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (name, secret) = network("independent-internal-encryption");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
c.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
for node in [&a, &b, &c] {
|
||||||
|
wait_for_peers(&node.agent, id, 2).await;
|
||||||
|
}
|
||||||
|
wait_until("AWG-only to QUIC-only through an authenticated mixed relay", || async {
|
||||||
|
let status = a.agent.network_status(id).await.ok()?;
|
||||||
|
let peer = status.peers.iter().find(|p| p.endpoint_id == c.agent.endpoint_id())?;
|
||||||
|
(matches!(peer.data_path, tsunagi::agent::DataPath::Relayed { via, .. } if via == b.agent.endpoint_id()) && a.plugin.overview(id)?.established_peers() == 2 && c.plugin.overview(id)?.established_peers() == 2).then_some(())
|
||||||
|
}).await;
|
||||||
|
exchange(&a, &c, id).await;
|
||||||
|
exchange(&c, &a, id).await;
|
||||||
|
let mut tcp = tcp::TcpPair::connect(a.tun(), a.addr(id), c.tun(), c.addr(id)).await;
|
||||||
|
tcp.exchange(b"SSH-like TCP stream over the initial relay")
|
||||||
|
.await;
|
||||||
|
let key = a.plugin.overview(id).unwrap().public_key;
|
||||||
|
let before = a
|
||||||
|
.plugin
|
||||||
|
.overview(id)
|
||||||
|
.unwrap()
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.endpoint_id == c.agent.endpoint_id())
|
||||||
|
.unwrap()
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.tx_packets;
|
||||||
|
// A's additional permission creates a direct QUIC route without replacing its IP tunnel.
|
||||||
|
a.agent
|
||||||
|
.set_protocols(id, vec!["wg-quic".into(), "awg".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
wait_until("direct carrier replaces the relay", || async {
|
||||||
|
let status = a.agent.network_status(id).await.ok()?;
|
||||||
|
matches!(
|
||||||
|
status
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.endpoint_id == c.agent.endpoint_id())?
|
||||||
|
.data_path,
|
||||||
|
tsunagi::agent::DataPath::Direct { .. }
|
||||||
|
)
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
tcp.exchange(b"same TCP socket after changing the carrier and next hop")
|
||||||
|
.await;
|
||||||
|
assert_eq!(a.plugin.overview(id).unwrap().public_key, key);
|
||||||
|
assert!(
|
||||||
|
a.plugin
|
||||||
|
.overview(id)
|
||||||
|
.unwrap()
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.endpoint_id == c.agent.endpoint_id())
|
||||||
|
.unwrap()
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.tx_packets
|
||||||
|
> before
|
||||||
|
);
|
||||||
|
a.agent.set_protocols(id, Vec::new()).await.unwrap();
|
||||||
|
// Poll the actual TCP stack while the route is absent: its first transmission is lost.
|
||||||
|
let pending = b"TCP retransmission survives the temporary absence of every data carrier";
|
||||||
|
tcp.queue_while_unreachable(pending);
|
||||||
|
a.agent.set_protocols(id, vec!["awg".into()]).await.unwrap();
|
||||||
|
wait_until("forbidden QUIC removed and relay restored", || async {
|
||||||
|
let status = a.agent.network_status(id).await.ok()?;
|
||||||
|
matches!(
|
||||||
|
status
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.endpoint_id == c.agent.endpoint_id())?
|
||||||
|
.data_path,
|
||||||
|
tsunagi::agent::DataPath::Relayed { .. }
|
||||||
|
)
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(a.plugin.overview(id).unwrap().public_key, key);
|
||||||
|
tcp.receive_queued(pending).await;
|
||||||
|
tcp.exchange(b"same TCP connection after returning to AWG and the relay")
|
||||||
|
.await;
|
||||||
|
drop(tcp);
|
||||||
|
// Transit ciphertext must never be delivered to the middle agent's IP interface.
|
||||||
|
assert!(
|
||||||
|
tokio::time::timeout(Duration::from_millis(150), b.tun().pop_to_os())
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
for node in [&a, &b, &c] {
|
||||||
|
node.agent.shutdown().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn no_common_carrier_is_an_actionable_policy_error_without_disabling_control() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
|
let a = Node::open_selected(
|
||||||
|
roots[0].path(),
|
||||||
|
&discovery,
|
||||||
|
"awg-policy",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec!["awg".into()]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let b = Node::open_selected(
|
||||||
|
roots[1].path(),
|
||||||
|
&discovery,
|
||||||
|
"quic-policy",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec!["wg-quic".into()]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (name, secret) = network("no-common-carrier");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
wait_until("explain independent external policies", || async {
|
||||||
|
let status = a.agent.network_status(id).await.ok()?;
|
||||||
|
let peer = status.peers.first()?;
|
||||||
|
peer.data_error
|
||||||
|
.as_ref()?
|
||||||
|
.contains("no common external transport")
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
a.agent
|
||||||
|
.network_status(id)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.metrics
|
||||||
|
.data_links_established,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
a.agent.shutdown().await;
|
||||||
|
b.agent.shutdown().await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
//! Fresh and bounded masking profiles, and rejection of foreign/truncated wire packets.
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use tsunagi_awg::profile::PairProfile;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profiles_are_fresh_bounded_and_redacted() {
|
||||||
|
let profiles: Vec<_> = (0..128).map(|_| PairProfile::generate()).collect();
|
||||||
|
for (i, profile) in profiles.iter().enumerate() {
|
||||||
|
profile.validate().unwrap();
|
||||||
|
assert!(!format!("{profile:?}").contains(&format!("{:?}", profile.header_key())));
|
||||||
|
for other in &profiles[..i] {
|
||||||
|
assert_ne!(profile.header_key(), other.header_key());
|
||||||
|
assert_ne!(profile.id(), other.id());
|
||||||
|
}
|
||||||
|
for packet in profile.signature_packets() {
|
||||||
|
assert!(packet.len() < 1200);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn masked_packets_round_trip_and_reject_other_profiles_and_truncation() {
|
||||||
|
let profile = PairProfile::generate();
|
||||||
|
let other = PairProfile::generate();
|
||||||
|
for (kind, size) in [(1, 148), (2, 92), (3, 64), (4, 800)] {
|
||||||
|
let mut message = vec![0x7b; size];
|
||||||
|
message[..4].copy_from_slice(&(kind as u32).to_le_bytes());
|
||||||
|
let wire = profile.encode(&message).unwrap();
|
||||||
|
assert_ne!(&wire[..4], &message[..4]);
|
||||||
|
assert_eq!(profile.decode(&wire).unwrap(), message);
|
||||||
|
assert!(other.decode(&wire).is_none());
|
||||||
|
for length in 0..44 {
|
||||||
|
assert!(profile.decode(&wire[..length]).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "tsunagi-cli"
|
|
||||||
version = "0.1.0"
|
|
||||||
description = "The tsunagi command line agent."
|
|
||||||
edition.workspace = true
|
|
||||||
rust-version.workspace = true
|
|
||||||
license.workspace = true
|
|
||||||
repository.workspace = true
|
|
||||||
|
|
||||||
[[bin]]
|
|
||||||
name = "tsunagi"
|
|
||||||
path = "src/main.rs"
|
|
||||||
# The binary and the library share a name, which `cargo doc` cannot map to
|
|
||||||
# two directories. The command line is documented by `--help`, not rustdoc,
|
|
||||||
# so the library keeps the name and this opts out.
|
|
||||||
doc = false
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
tsunagi = { path = "../tsunagi", version = "0.1.0", features = ["tun-device", "dns-publish"] }
|
|
||||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "0.1.0" }
|
|
||||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "0.1.0" }
|
|
||||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "0.1.0" }
|
|
||||||
iroh.workspace = true
|
|
||||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
|
|
||||||
tracing.workspace = true
|
|
||||||
tracing-subscriber.workspace = true
|
|
||||||
clap = { version = "4.5", features = ["derive", "env"] }
|
|
||||||
# Already in the tree through clap. `anstream` strips the escapes when stdout
|
|
||||||
# is not a terminal and turns on virtual terminal processing on Windows, so
|
|
||||||
# colour is never written where it would show up as rubbish.
|
|
||||||
anstream = "1.0"
|
|
||||||
anstyle = "1.0"
|
|
||||||
# Local interface addresses, for the diagnostics in `status`.
|
|
||||||
netwatch = "0.19.3"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "process"] }
|
|
||||||
tempfile.workspace = true
|
|
||||||
simple-dns = "0.12"
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
//! What the command line says about this device, against a running agent.
|
|
||||||
//!
|
|
||||||
//! These drive the real binary, which is why they live beside it rather
|
|
||||||
//! than with the library's own tests: the library cannot depend on a binary
|
|
||||||
//! built from a crate that depends on it.
|
|
||||||
|
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
|
||||||
|
|
||||||
use tempfile::TempDir;
|
|
||||||
use tsunagi::Agent;
|
|
||||||
use tsunagi::config::{AgentConfig, StoragePaths, TransportPolicy};
|
|
||||||
|
|
||||||
/// Asking who this device is must not need the directory lock.
|
|
||||||
///
|
|
||||||
/// The lock belongs to the one agent allowed to *write* the state. `id` only
|
|
||||||
/// reads, so making it take the lock would mean the question could never be
|
|
||||||
/// answered while an agent was running — which is exactly when you want to
|
|
||||||
/// ask it.
|
|
||||||
#[tokio::test]
|
|
||||||
async fn identity_can_be_read_while_an_agent_holds_the_directory() {
|
|
||||||
let dir = TempDir::new().unwrap();
|
|
||||||
|
|
||||||
// Hold the directory the way a running agent does.
|
|
||||||
let agent = Agent::spawn(
|
|
||||||
AgentConfig::new(StoragePaths::under(dir.path()))
|
|
||||||
.with_transport(TransportPolicy::LocalOnly)
|
|
||||||
.with_loopback_bind(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let expected = agent.endpoint_id().to_string();
|
|
||||||
|
|
||||||
let output = tokio::process::Command::new(env!("CARGO_BIN_EXE_tsunagi"))
|
|
||||||
.arg("id")
|
|
||||||
// The same layout `StoragePaths::under` gives the agent above.
|
|
||||||
.arg("--state-dir")
|
|
||||||
.arg(dir.path().join("state"))
|
|
||||||
.arg("--cache-dir")
|
|
||||||
.arg(dir.path().join("cache"))
|
|
||||||
.output()
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
|
||||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
|
||||||
assert!(
|
|
||||||
output.status.success(),
|
|
||||||
"`id` failed while an agent was running:\n{stderr}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
stdout.contains(&expected),
|
|
||||||
"expected {expected} in:\n{stdout}"
|
|
||||||
);
|
|
||||||
|
|
||||||
agent.shutdown().await;
|
|
||||||
}
|
|
||||||
@@ -1,420 +0,0 @@
|
|||||||
//! Making and joining a network from the command line, against a real agent.
|
|
||||||
//!
|
|
||||||
//! The rules here are small and easy to get wrong in a way no unit test
|
|
||||||
//! notices: what a bare network name means, when a secret is invented, and
|
|
||||||
//! whether what is printed is enough for the other person to paste.
|
|
||||||
|
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use tempfile::TempDir;
|
|
||||||
|
|
||||||
/// An agent running as a real process, with its own directories.
|
|
||||||
struct Running {
|
|
||||||
child: std::process::Child,
|
|
||||||
dir: TempDir,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for Running {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let _ = self.child.kill();
|
|
||||||
let _ = self.child.wait();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Running {
|
|
||||||
fn run(&self, args: &[&str]) -> std::process::Output {
|
|
||||||
run_in(&self.dir, args)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_in(dir: &TempDir, args: &[&str]) -> std::process::Output {
|
|
||||||
std::process::Command::new(env!("CARGO_BIN_EXE_tsunagi"))
|
|
||||||
.args(args)
|
|
||||||
.arg("--state-dir")
|
|
||||||
.arg(dir.path().join("state"))
|
|
||||||
.arg("--cache-dir")
|
|
||||||
.arg(dir.path().join("cache"))
|
|
||||||
.output()
|
|
||||||
.expect("the agent binary runs")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_networks(dir: &TempDir) -> Vec<tsunagi::storage::StoredNetwork> {
|
|
||||||
tsunagi::storage::StateStore::open(dir.path().join("state/state.sqlite"))
|
|
||||||
.unwrap()
|
|
||||||
.list_networks()
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An agent with no network at all, the way a daemon is started before
|
|
||||||
/// anything has been decided.
|
|
||||||
fn start_bare(port: u16) -> Running {
|
|
||||||
let dir = TempDir::new().unwrap();
|
|
||||||
let child = std::process::Command::new(env!("CARGO_BIN_EXE_tsunagi"))
|
|
||||||
.arg("up")
|
|
||||||
.arg("--state-dir")
|
|
||||||
.arg(dir.path().join("state"))
|
|
||||||
.arg("--cache-dir")
|
|
||||||
.arg(dir.path().join("cache"))
|
|
||||||
.args(["--reach", "local", "--no-tun", "--no-dns"])
|
|
||||||
.arg("--bind")
|
|
||||||
.arg(format!("127.0.0.1:{port}"))
|
|
||||||
.args(["--log", "error", "--status-interval", "0"])
|
|
||||||
.stdout(std::process::Stdio::null())
|
|
||||||
.stderr(std::process::Stdio::null())
|
|
||||||
.spawn()
|
|
||||||
.expect("the agent binary starts");
|
|
||||||
std::thread::sleep(Duration::from_secs(2));
|
|
||||||
Running { child, dir }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An agent already in one network, the way most of these start.
|
|
||||||
fn start(network: &str, port: u16) -> Running {
|
|
||||||
let agent = start_bare(port);
|
|
||||||
let joined = agent.run(&[
|
|
||||||
"join",
|
|
||||||
"--network",
|
|
||||||
network,
|
|
||||||
"--secret",
|
|
||||||
"a-secret-for-the-cli-test",
|
|
||||||
]);
|
|
||||||
assert!(
|
|
||||||
joined.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&joined.stderr)
|
|
||||||
);
|
|
||||||
agent
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn joining_with_no_secret_makes_one_and_prints_what_to_send() {
|
|
||||||
// The hurry case: a network with somebody, for as long as it is needed,
|
|
||||||
// and then gone. Asking for a secret first is a step with no purpose,
|
|
||||||
// and a secret that is not printed is a network nobody else can join.
|
|
||||||
let agent = start("resident", 45071);
|
|
||||||
|
|
||||||
let joined = agent.run(&["network", "join", "--network", "spontaneous"]);
|
|
||||||
assert!(
|
|
||||||
joined.status.success(),
|
|
||||||
"joining failed: {}",
|
|
||||||
String::from_utf8_lossy(&joined.stderr)
|
|
||||||
);
|
|
||||||
let out = String::from_utf8_lossy(&joined.stdout);
|
|
||||||
assert!(out.contains("joined `spontaneous`"), "{out}");
|
|
||||||
|
|
||||||
// The secret in full, and one line the other side can paste as it is.
|
|
||||||
let secret = out
|
|
||||||
.lines()
|
|
||||||
.find_map(|line| line.trim().strip_prefix("secret "))
|
|
||||||
.expect("the invented secret is printed");
|
|
||||||
assert!(secret.starts_with("tsn1"), "{out}");
|
|
||||||
let command = out
|
|
||||||
.lines()
|
|
||||||
.find(|line| line.contains("tsunagi join --network spontaneous"))
|
|
||||||
.expect("a command to send");
|
|
||||||
assert!(command.contains(secret), "with the secret in it: {out}");
|
|
||||||
// And where to find this device, for an agent that is not up yet.
|
|
||||||
assert!(out.contains("--peer "), "somewhere to find us: {out}");
|
|
||||||
|
|
||||||
// Joining the same name again resumes it rather than making another
|
|
||||||
// network that merely looks the same.
|
|
||||||
let again = agent.run(&["network", "join", "--network", "spontaneous"]);
|
|
||||||
let out = String::from_utf8_lossy(&again.stdout);
|
|
||||||
assert!(again.status.success());
|
|
||||||
assert!(out.contains("already here"), "{out}");
|
|
||||||
assert!(!out.contains("secret tsn1"), "no second secret: {out}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_bare_name_resumes_the_network_of_that_name_rather_than_inventing_one() {
|
|
||||||
// `join --network resident` with no secret is the same rule: this device
|
|
||||||
// has exactly one network of that name, so that is the one meant.
|
|
||||||
let agent = start("resident", 45072);
|
|
||||||
let listed = agent.run(&["network"]);
|
|
||||||
let before = String::from_utf8_lossy(&listed.stdout).to_string();
|
|
||||||
let id = before
|
|
||||||
.lines()
|
|
||||||
.find(|line| line.contains("resident"))
|
|
||||||
.and_then(|line| line.split_whitespace().nth(1))
|
|
||||||
.expect("the network is listed")
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let joined = agent.run(&["network", "join", "--network", "resident"]);
|
|
||||||
assert!(joined.status.success());
|
|
||||||
let out = String::from_utf8_lossy(&joined.stdout);
|
|
||||||
assert!(out.contains(&id), "the same network, not a new one: {out}");
|
|
||||||
assert!(out.contains("already here"), "{out}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_network_can_be_stopped_and_resumed_without_losing_anything() {
|
|
||||||
// Leaving gives everything up; stopping is being away. The difference
|
|
||||||
// is what somebody wants when they will be back.
|
|
||||||
let agent = start("resident", 45073);
|
|
||||||
let listed = agent.run(&["network"]);
|
|
||||||
let out = String::from_utf8_lossy(&listed.stdout).to_string();
|
|
||||||
let id = out
|
|
||||||
.lines()
|
|
||||||
.find(|line| line.contains("resident"))
|
|
||||||
.and_then(|line| line.split_whitespace().nth(1))
|
|
||||||
.expect("the network is listed")
|
|
||||||
.to_string();
|
|
||||||
let secret_before = agent.run(&["network", "secret", &id[..10]]);
|
|
||||||
let secret_before = String::from_utf8_lossy(&secret_before.stdout)
|
|
||||||
.trim()
|
|
||||||
.to_string();
|
|
||||||
assert!(secret_before.starts_with("tsn1"));
|
|
||||||
|
|
||||||
let stopped = agent.run(&["network", "stop", "resident"]);
|
|
||||||
assert!(
|
|
||||||
stopped.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&stopped.stderr)
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
String::from_utf8_lossy(&stopped.stdout).contains("stopped `resident`"),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&stopped.stdout)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Still configured, and said to be stopped rather than missing.
|
|
||||||
let listed = String::from_utf8_lossy(&agent.run(&["network"]).stdout).to_string();
|
|
||||||
assert!(listed.contains(&id), "still configured: {listed}");
|
|
||||||
assert!(listed.contains("stopped"), "{listed}");
|
|
||||||
|
|
||||||
// Stopping what is stopped is the state asked for, not an error.
|
|
||||||
let again = agent.run(&["network", "stop", &id[..10]]);
|
|
||||||
assert!(again.status.success());
|
|
||||||
assert!(
|
|
||||||
String::from_utf8_lossy(&again.stdout).contains("already stopped"),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&again.stdout)
|
|
||||||
);
|
|
||||||
|
|
||||||
let started = agent.run(&["network", "start", "resident"]);
|
|
||||||
assert!(started.status.success());
|
|
||||||
assert!(
|
|
||||||
String::from_utf8_lossy(&started.stdout).contains("started `resident`"),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&started.stdout)
|
|
||||||
);
|
|
||||||
let listed = String::from_utf8_lossy(&agent.run(&["network"]).stdout).to_string();
|
|
||||||
assert!(listed.contains("running"), "{listed}");
|
|
||||||
|
|
||||||
// And nothing was given up on the way: the same network, same secret.
|
|
||||||
let secret_after = agent.run(&["network", "secret", "resident"]);
|
|
||||||
assert_eq!(
|
|
||||||
String::from_utf8_lossy(&secret_after.stdout).trim(),
|
|
||||||
secret_before,
|
|
||||||
"the secret is kept, so this is the same network"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_agent_starts_with_no_network_and_takes_one_later() {
|
|
||||||
// A daemon in one terminal and the deciding done in another: the
|
|
||||||
// agent is the identity, and which networks it is in is a separate
|
|
||||||
// question it can answer at any time.
|
|
||||||
let agent = start_bare(45074);
|
|
||||||
|
|
||||||
let listed = agent.run(&["network"]);
|
|
||||||
assert!(listed.status.success());
|
|
||||||
assert!(
|
|
||||||
String::from_utf8_lossy(&listed.stderr).contains("no network has been joined"),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&listed.stderr)
|
|
||||||
);
|
|
||||||
|
|
||||||
let joined = agent.run(&["network", "join", "--network", "afterwards"]);
|
|
||||||
assert!(
|
|
||||||
joined.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&joined.stderr)
|
|
||||||
);
|
|
||||||
let listed = String::from_utf8_lossy(&agent.run(&["network"]).stdout).to_string();
|
|
||||||
assert!(listed.contains("afterwards"), "{listed}");
|
|
||||||
assert!(listed.contains("running"), "and it is live: {listed}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn up_is_the_agent_and_takes_no_network_at_all() {
|
|
||||||
// The two commands are separate on purpose: `up` runs the device's
|
|
||||||
// agent, `join` decides what it is in. A network on `up` would be a
|
|
||||||
// second way to do the same thing, and the one that cannot be undone
|
|
||||||
// without a restart.
|
|
||||||
for argument in ["--network", "--secret"] {
|
|
||||||
let out = std::process::Command::new(env!("CARGO_BIN_EXE_tsunagi"))
|
|
||||||
.args(["up", argument, "whatever"])
|
|
||||||
.arg("--state-dir")
|
|
||||||
.arg(TempDir::new().unwrap().path().join("state"))
|
|
||||||
.output()
|
|
||||||
.expect("the agent binary runs");
|
|
||||||
assert!(
|
|
||||||
!out.status.success(),
|
|
||||||
"`up {argument}` should not be a thing"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
String::from_utf8_lossy(&out.stderr).contains("unexpected argument"),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&out.stderr)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn broadcast_choice_is_per_network_live_persistent_and_preserved_by_rejoin() {
|
|
||||||
let agent = start_bare(0);
|
|
||||||
for args in [
|
|
||||||
vec!["join", "-n", "broadcast-default"],
|
|
||||||
vec!["join", "-n", "broadcast-off", "--no-broadcast"],
|
|
||||||
] {
|
|
||||||
let result = agent.run(&args);
|
|
||||||
assert!(
|
|
||||||
result.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&result.stderr)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let read = || {
|
|
||||||
tsunagi::storage::StateStore::open(agent.dir.path().join("state/state.sqlite"))
|
|
||||||
.unwrap()
|
|
||||||
.list_networks()
|
|
||||||
.unwrap()
|
|
||||||
};
|
|
||||||
let networks = read();
|
|
||||||
let enabled = networks
|
|
||||||
.iter()
|
|
||||||
.find(|n| n.name.as_str() == "broadcast-default")
|
|
||||||
.unwrap();
|
|
||||||
let disabled = networks
|
|
||||||
.iter()
|
|
||||||
.find(|n| n.name.as_str() == "broadcast-off")
|
|
||||||
.unwrap();
|
|
||||||
assert!(enabled.broadcast);
|
|
||||||
assert!(!disabled.broadcast);
|
|
||||||
assert!(agent.run(&["join", "-n", "broadcast-off"]).status.success());
|
|
||||||
assert!(
|
|
||||||
!read()
|
|
||||||
.iter()
|
|
||||||
.find(|n| n.name.as_str() == "broadcast-off")
|
|
||||||
.unwrap()
|
|
||||||
.broadcast
|
|
||||||
);
|
|
||||||
let id = disabled.network_id.to_string();
|
|
||||||
let change = agent.run(&["network", "broadcast", "broadcast-off", "on"]);
|
|
||||||
assert!(
|
|
||||||
change.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&change.stderr)
|
|
||||||
);
|
|
||||||
assert!(read().iter().all(|n| n.broadcast));
|
|
||||||
let change = agent.run(&["join", "-n", "broadcast-off", "--no-broadcast"]);
|
|
||||||
assert!(
|
|
||||||
change.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&change.stderr)
|
|
||||||
);
|
|
||||||
let status = agent.run(&["network", "broadcast", &id]);
|
|
||||||
assert!(String::from_utf8_lossy(&status.stdout).contains("broadcast off"));
|
|
||||||
assert!(
|
|
||||||
!agent
|
|
||||||
.run(&["join", "-n", "conflict", "--broadcast", "--no-broadcast"])
|
|
||||||
.status
|
|
||||||
.success()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn leaving_by_name_removes_only_that_network_from_a_running_agent() {
|
|
||||||
let agent = start("resident", 0);
|
|
||||||
assert!(agent.run(&["join", "-n", "games"]).status.success());
|
|
||||||
let resident = read_networks(&agent.dir)
|
|
||||||
.into_iter()
|
|
||||||
.find(|network| network.name.as_str() == "resident")
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let left = agent.run(&["network", "leave", "games"]);
|
|
||||||
assert!(
|
|
||||||
left.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&left.stderr)
|
|
||||||
);
|
|
||||||
assert!(String::from_utf8_lossy(&left.stdout).contains("left `games`"));
|
|
||||||
let remaining = read_networks(&agent.dir);
|
|
||||||
assert_eq!(remaining.len(), 1);
|
|
||||||
assert_eq!(remaining[0].network_id, resident.network_id);
|
|
||||||
assert_eq!(
|
|
||||||
remaining[0].secret.encode().as_str(),
|
|
||||||
resident.secret.encode().as_str()
|
|
||||||
);
|
|
||||||
let status = agent.run(&["network"]);
|
|
||||||
assert!(status.status.success());
|
|
||||||
let out = String::from_utf8_lossy(&status.stdout);
|
|
||||||
assert!(out.contains("resident") && out.contains("running"), "{out}");
|
|
||||||
assert!(!out.contains("games"), "{out}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn leaving_by_name_offline_keeps_the_explicit_offline_requirement() {
|
|
||||||
let dir = TempDir::new().unwrap();
|
|
||||||
for name in ["resident", "games"] {
|
|
||||||
assert!(run_in(&dir, &["join", "-n", name]).status.success());
|
|
||||||
}
|
|
||||||
let refused = run_in(&dir, &["network", "leave", "games"]);
|
|
||||||
assert!(!refused.status.success());
|
|
||||||
assert!(String::from_utf8_lossy(&refused.stderr).contains("--offline"));
|
|
||||||
assert_eq!(read_networks(&dir).len(), 2);
|
|
||||||
|
|
||||||
let left = run_in(&dir, &["network", "leave", "games", "--offline"]);
|
|
||||||
assert!(
|
|
||||||
left.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&left.stderr)
|
|
||||||
);
|
|
||||||
let remaining = read_networks(&dir);
|
|
||||||
assert_eq!(remaining.len(), 1);
|
|
||||||
assert_eq!(remaining[0].name.as_str(), "resident");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ambiguous_and_unknown_names_leave_every_network_untouched() {
|
|
||||||
let agent = start_bare(0);
|
|
||||||
for secret in [
|
|
||||||
"first-secret-for-the-cli-test",
|
|
||||||
"second-secret-for-the-cli-test",
|
|
||||||
] {
|
|
||||||
assert!(
|
|
||||||
agent
|
|
||||||
.run(&["join", "-n", "games", "-s", secret])
|
|
||||||
.status
|
|
||||||
.success()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let before = read_networks(&agent.dir);
|
|
||||||
assert_eq!(before.len(), 2);
|
|
||||||
for name in ["games", "missing-network"] {
|
|
||||||
let result = agent.run(&["network", "leave", name]);
|
|
||||||
assert!(!result.status.success());
|
|
||||||
let err = String::from_utf8_lossy(&result.stderr);
|
|
||||||
if name == "games" {
|
|
||||||
assert!(err.contains("matches 2 networks"), "{err}");
|
|
||||||
for network in &before {
|
|
||||||
assert!(err.contains(&network.network_id.to_string()), "{err}");
|
|
||||||
assert!(!err.contains(network.secret.encode().as_str()), "{err}");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
assert!(err.contains("no configured network"), "{err}");
|
|
||||||
}
|
|
||||||
assert_eq!(read_networks(&agent.dir).len(), 2);
|
|
||||||
}
|
|
||||||
// The suggested full id still selects exactly one of the same-name networks.
|
|
||||||
let left = agent.run(&["network", "leave", &before[0].network_id.to_string()]);
|
|
||||||
assert!(
|
|
||||||
left.status.success(),
|
|
||||||
"{}",
|
|
||||||
String::from_utf8_lossy(&left.stderr)
|
|
||||||
);
|
|
||||||
let remaining = read_networks(&agent.dir);
|
|
||||||
assert_eq!(remaining.len(), 1);
|
|
||||||
assert_eq!(remaining[0].network_id, before[1].network_id);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsunagi-core"
|
||||||
|
version = "1.0.0"
|
||||||
|
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
|
||||||
|
readme = "../../README.md"
|
||||||
|
keywords = ["mesh", "p2p", "iroh", "networking"]
|
||||||
|
categories = ["network-programming"]
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "tsunagi"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = []
|
||||||
|
# A real TUN device, so a plugin can carry actual IP traffic. On Linux it
|
||||||
|
# needs CAP_NET_ADMIN; on Windows the process must run elevated and
|
||||||
|
# `wintun.dll` must be reachable. Without either the in-memory device serves
|
||||||
|
# tests. The platform-specific dependencies are declared per target, so
|
||||||
|
# enabling this only pulls what the target it is built for actually uses.
|
||||||
|
tun-device = [
|
||||||
|
"dep:tun",
|
||||||
|
"dep:rtnetlink",
|
||||||
|
"dep:caps",
|
||||||
|
"dep:futures-util",
|
||||||
|
]
|
||||||
|
# Telling the operating system where to send its DNS questions. systemd-resolved
|
||||||
|
# on Linux, the Name Resolution Policy Table on Windows; the zone and the
|
||||||
|
# server work without it either way.
|
||||||
|
dns-publish = ["dep:zbus"]
|
||||||
|
# The test harness in `testing`, for this crate's own tests and for a
|
||||||
|
# protocol crate's. Not on by default: it is only of use to a test.
|
||||||
|
testing = ["dep:tempfile", "dep:tracing-subscriber"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
arc-swap = "1.9"
|
||||||
|
iroh.workspace = true
|
||||||
|
# `net` for the local control interface: a Unix socket on Unix, a named pipe
|
||||||
|
# on Windows. Both live behind the same `net` feature.
|
||||||
|
tokio = { workspace = true, features = ["net"] }
|
||||||
|
tokio-stream = "0.1"
|
||||||
|
serde.workspace = true
|
||||||
|
postcard.workspace = true
|
||||||
|
bytes.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
hex.workspace = true
|
||||||
|
data-encoding.workspace = true
|
||||||
|
rusqlite = { version = "0.40", features = ["bundled"] }
|
||||||
|
hkdf = "0.13"
|
||||||
|
hmac = "0.13"
|
||||||
|
sha2 = "0.11"
|
||||||
|
subtle = "2.6"
|
||||||
|
zeroize = { version = "1.9", features = ["derive"] }
|
||||||
|
rand = "0.10"
|
||||||
|
# Already in the tree through iroh. A packet codec, not a DNS server: the
|
||||||
|
# zone logic is ours and a full server framework would be a large dependency
|
||||||
|
# for answering A records from memory.
|
||||||
|
simple-dns = "0.12"
|
||||||
|
# The IANA top-level domain list, compiled in: one function, no
|
||||||
|
# dependencies, no network. Used only to warn that a zone name shadows a
|
||||||
|
# real public domain, never to refuse one.
|
||||||
|
tld = "2.40"
|
||||||
|
fs4 = { version = "1.1", features = ["sync"] }
|
||||||
|
directories = "6.0"
|
||||||
|
# The real system hostname, without a libc call of our own: this crate is
|
||||||
|
# forbidden `unsafe` and will not make one.
|
||||||
|
gethostname = "1.1"
|
||||||
|
netwatch = "0.19.3"
|
||||||
|
netdev = "0.46"
|
||||||
|
mainline = "8.0"
|
||||||
|
futures-lite = "2.6"
|
||||||
|
tun = { version = "0.8", features = ["async"], optional = true }
|
||||||
|
# Only for the `testing` harness, which a protocol crate's tests use too.
|
||||||
|
tempfile = { version = "3.24", optional = true }
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter"], optional = true }
|
||||||
|
|
||||||
|
# Linux-only interface provisioning. `rtnetlink` configures the interface in
|
||||||
|
# process, so no `ip` invocation is ever needed; `caps` keeps CAP_NET_ADMIN
|
||||||
|
# out of the effective set except during the moments it is used.
|
||||||
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
|
rtnetlink = { version = "0.23", optional = true }
|
||||||
|
# Pure Rust D-Bus, no libdbus to link against. `tokio` rather than the
|
||||||
|
# default reactor, because the agent brings its own.
|
||||||
|
zbus = { version = "5.19", default-features = false, features = ["tokio"], optional = true }
|
||||||
|
caps = { version = "0.5", optional = true }
|
||||||
|
futures-util = { version = "0.3", default-features = false, optional = true }
|
||||||
|
|
||||||
|
# Windows-only interface provisioning. The Wintun adapter itself is created
|
||||||
|
# and driven through the `tun` dependency, whose safe wrapper is the only way
|
||||||
|
# in — loading `wintun.dll` is an `unsafe` call this crate forbids. `netdev`
|
||||||
|
# (already in the tree through `netwatch`) reads the interface table through a
|
||||||
|
# safe wrapper, which is how the provisioner observes an adapter by name
|
||||||
|
# before deciding what to change. Creating an adapter needs the process to be
|
||||||
|
# elevated and `wintun.dll` to be reachable at run time.
|
||||||
|
[target.'cfg(target_os = "windows")'.dependencies]
|
||||||
|
windows-sys = { version = "0.61", features = [
|
||||||
|
"Win32_Security",
|
||||||
|
"Win32_Security_Authorization",
|
||||||
|
"Win32_Foundation",
|
||||||
|
] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
# Its own tests use the harness it publishes.
|
||||||
|
tsunagi-core = { path = ".", features = ["testing"] }
|
||||||
|
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "process", "test-util"] }
|
||||||
|
tempfile.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -129,6 +129,19 @@ pub enum Event {
|
|||||||
/// Why it is not up.
|
/// Why it is not up.
|
||||||
reason: String,
|
reason: String,
|
||||||
},
|
},
|
||||||
|
/// The name this agent claimed was claimed first by another member.
|
||||||
|
///
|
||||||
|
/// Nothing stops working: this agent keeps its address and every
|
||||||
|
/// connection. It just is not found by that name until it is renamed or
|
||||||
|
/// the member that holds the name lets it go.
|
||||||
|
HostnameTaken {
|
||||||
|
/// The network.
|
||||||
|
network: NetworkId,
|
||||||
|
/// The name that is taken.
|
||||||
|
name: String,
|
||||||
|
/// The member that holds it.
|
||||||
|
holder: EndpointId,
|
||||||
|
},
|
||||||
/// An IP plugin reported an error. Never fatal.
|
/// An IP plugin reported an error. Never fatal.
|
||||||
PluginError {
|
PluginError {
|
||||||
/// The network the call was scoped to.
|
/// The network the call was scoped to.
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -70,10 +70,12 @@ pub(crate) struct Session {
|
|||||||
pub(crate) conn: Connection,
|
pub(crate) conn: Connection,
|
||||||
/// Already encoded frame payloads, so the runtime can account for the exact
|
/// Already encoded frame payloads, so the runtime can account for the exact
|
||||||
/// number of control bytes it queues.
|
/// number of control bytes it queues.
|
||||||
pub(crate) outbound: mpsc::Sender<Vec<u8>>,
|
pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>,
|
||||||
pub(crate) hostname: Option<String>,
|
pub(crate) hostname: Option<String>,
|
||||||
pub(crate) capabilities: Vec<PluginCapability>,
|
pub(crate) capabilities: Vec<PluginCapability>,
|
||||||
pub(crate) broadcast: bool,
|
pub(crate) broadcast: bool,
|
||||||
|
/// The peer offers itself as an exit node in this network.
|
||||||
|
pub(crate) exit_node: bool,
|
||||||
pub(crate) messages_sent: u64,
|
pub(crate) messages_sent: u64,
|
||||||
pub(crate) messages_received: u64,
|
pub(crate) messages_received: u64,
|
||||||
pub(crate) bytes_sent: u64,
|
pub(crate) bytes_sent: u64,
|
||||||
@@ -228,6 +230,7 @@ pub(crate) fn spawn(
|
|||||||
hostname: None,
|
hostname: None,
|
||||||
capabilities: Vec::new(),
|
capabilities: Vec::new(),
|
||||||
broadcast: false,
|
broadcast: false,
|
||||||
|
exit_node: false,
|
||||||
messages_sent: 0,
|
messages_sent: 0,
|
||||||
messages_received: 0,
|
messages_received: 0,
|
||||||
bytes_sent: 0,
|
bytes_sent: 0,
|
||||||
@@ -241,7 +244,7 @@ pub(crate) fn spawn(
|
|||||||
|
|
||||||
async fn writer_task(
|
async fn writer_task(
|
||||||
mut send: SendStream,
|
mut send: SendStream,
|
||||||
mut outbound: mpsc::Receiver<Vec<u8>>,
|
mut outbound: mpsc::Receiver<zeroize::Zeroizing<Vec<u8>>>,
|
||||||
limits: Arc<Limits>,
|
limits: Arc<Limits>,
|
||||||
shutdown: Shutdown,
|
shutdown: Shutdown,
|
||||||
parent: Shutdown,
|
parent: Shutdown,
|
||||||
@@ -328,6 +331,7 @@ async fn reader_task(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let payload = zeroize::Zeroizing::new(payload);
|
||||||
let bytes = payload.len();
|
let bytes = payload.len();
|
||||||
let envelope: Envelope = match decode(&payload) {
|
let envelope: Envelope = match decode(&payload) {
|
||||||
Ok(envelope) => envelope,
|
Ok(envelope) => envelope,
|
||||||
File renamed without changes.
@@ -59,6 +59,43 @@ pub struct OverlayStatus {
|
|||||||
pub broadcast_rules: Option<crate::overlay::BroadcastRulesReport>,
|
pub broadcast_rules: Option<crate::overlay::BroadcastRulesReport>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How packets reach a member right now.
|
||||||
|
///
|
||||||
|
/// Being reachable is one thing and being reachable well is another, and
|
||||||
|
/// the second is never a reason to call a member away: a member that can only
|
||||||
|
/// be reached through somebody else is online, over a longer path.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum DataPath {
|
||||||
|
/// Nothing carries packets to it yet. The member is connected for
|
||||||
|
/// control only, which is the state of a data path being set up.
|
||||||
|
None,
|
||||||
|
/// A direct link, of the named kind of transport.
|
||||||
|
Direct {
|
||||||
|
/// The kind of transport carrying it, e.g. `wg`.
|
||||||
|
transport: String,
|
||||||
|
},
|
||||||
|
/// Through other members.
|
||||||
|
Relayed {
|
||||||
|
/// Number of links on the way, at least two.
|
||||||
|
hops: u8,
|
||||||
|
/// The member the first of them goes to.
|
||||||
|
via: EndpointId,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name that a member claimed and somebody else holds.
|
||||||
|
///
|
||||||
|
/// A name belongs to whoever claimed it first. The member that claimed it
|
||||||
|
/// later is still a member and still reachable by its address; it is just
|
||||||
|
/// not found by that name, on any member of the network.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct HostnameConflict {
|
||||||
|
/// The name that is taken.
|
||||||
|
pub name: String,
|
||||||
|
/// The member that holds it.
|
||||||
|
pub holder: EndpointId,
|
||||||
|
}
|
||||||
|
|
||||||
/// A member the signed state knows about, connected or not.
|
/// A member the signed state knows about, connected or not.
|
||||||
///
|
///
|
||||||
/// This is the durable roster: it comes from signed records, so a member that
|
/// This is the durable roster: it comes from signed records, so a member that
|
||||||
@@ -71,6 +108,8 @@ pub struct OverlayStatus {
|
|||||||
/// connected.
|
/// connected.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct MemberStatus {
|
pub struct MemberStatus {
|
||||||
|
/// Current signed claim version, used to bind cleanup confirmation.
|
||||||
|
pub record_version: u64,
|
||||||
/// The member's device identity.
|
/// The member's device identity.
|
||||||
pub endpoint_id: EndpointId,
|
pub endpoint_id: EndpointId,
|
||||||
/// The IPv4 overlay address it claimed and signed for.
|
/// The IPv4 overlay address it claimed and signed for.
|
||||||
@@ -80,6 +119,20 @@ pub struct MemberStatus {
|
|||||||
/// Signed, so it is still known while the member is away — which is what
|
/// Signed, so it is still known while the member is away — which is what
|
||||||
/// lets an absent member be named rather than shown as a bare id.
|
/// lets an absent member be named rather than shown as a bare id.
|
||||||
pub hostname: Option<String>,
|
pub hostname: Option<String>,
|
||||||
|
/// The last name this agent saw it announce, whether or not it is here.
|
||||||
|
///
|
||||||
|
/// Not signed, so it is a convenience for naming a member that is away
|
||||||
|
/// and never a claim: the zone is served from `hostname`.
|
||||||
|
pub last_hostname: Option<String>,
|
||||||
|
/// The name it claimed, when somebody else claimed it first.
|
||||||
|
pub hostname_conflict: Option<HostnameConflict>,
|
||||||
|
/// Whether this agent can reach it now, by any path: a live control
|
||||||
|
/// session, or a data path through other members. The one answer to "is
|
||||||
|
/// it online" for every client, so that none of them has to work it out
|
||||||
|
/// from a different part of the picture. This agent counts as online.
|
||||||
|
pub online: bool,
|
||||||
|
/// How packets reach it. [`DataPath::None`] while it is offline.
|
||||||
|
pub data_path: DataPath,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Status of one authenticated session.
|
/// Status of one authenticated session.
|
||||||
@@ -87,6 +140,8 @@ pub struct MemberStatus {
|
|||||||
pub struct PeerStatus {
|
pub struct PeerStatus {
|
||||||
/// This authenticated peer accepts network broadcasts.
|
/// This authenticated peer accepts network broadcasts.
|
||||||
pub broadcast: bool,
|
pub broadcast: bool,
|
||||||
|
/// This authenticated peer offers itself as an exit node.
|
||||||
|
pub exit_node: bool,
|
||||||
/// Authenticated endpoint id.
|
/// Authenticated endpoint id.
|
||||||
pub endpoint_id: EndpointId,
|
pub endpoint_id: EndpointId,
|
||||||
/// Which side this agent played in the handshake.
|
/// Which side this agent played in the handshake.
|
||||||
@@ -103,6 +158,8 @@ pub struct PeerStatus {
|
|||||||
pub protocols: Vec<String>,
|
pub protocols: Vec<String>,
|
||||||
/// Capabilities the peer announced. Payloads stay opaque.
|
/// Capabilities the peer announced. Payloads stay opaque.
|
||||||
pub capabilities: Vec<PluginCapability>,
|
pub capabilities: Vec<PluginCapability>,
|
||||||
|
/// Why no data route is available, when known.
|
||||||
|
pub data_error: Option<String>,
|
||||||
/// How long the session has been up.
|
/// How long the session has been up.
|
||||||
pub connected_for: Duration,
|
pub connected_for: Duration,
|
||||||
/// Verified paths of the underlying connection.
|
/// Verified paths of the underlying connection.
|
||||||
@@ -121,6 +178,8 @@ pub struct PeerStatus {
|
|||||||
pub control_bytes_sent: u64,
|
pub control_bytes_sent: u64,
|
||||||
/// Control payload bytes read from this session.
|
/// Control payload bytes read from this session.
|
||||||
pub control_bytes_received: u64,
|
pub control_bytes_received: u64,
|
||||||
|
/// How packets reach this peer right now.
|
||||||
|
pub data_path: DataPath,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Counters scoped to one logical network.
|
/// Counters scoped to one logical network.
|
||||||
@@ -154,11 +213,36 @@ pub struct NetworkMetrics {
|
|||||||
pub data_link_failures: u64,
|
pub data_link_failures: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An active network preventing another network from starting locally.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct RangeConflict {
|
||||||
|
/// The blocking network's public identifier.
|
||||||
|
pub network_id: NetworkId,
|
||||||
|
/// Its configured name.
|
||||||
|
pub name: NetworkName,
|
||||||
|
/// Its overlapping overlay range.
|
||||||
|
pub range: crate::state::Ipv4Range,
|
||||||
|
}
|
||||||
|
|
||||||
/// Status of one network.
|
/// Status of one network.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct NetworkStatus {
|
pub struct NetworkStatus {
|
||||||
|
/// Shared service configuration with this client's routing observations.
|
||||||
|
pub vips: Vec<crate::vip::VipStatus>,
|
||||||
|
/// Enabled local data-plane protocols, in preference order.
|
||||||
|
pub protocols: Vec<String>,
|
||||||
|
/// Whether this network is requested to start or resume automatically.
|
||||||
|
pub auto_start: bool,
|
||||||
/// Local broadcast participation in this network.
|
/// Local broadcast participation in this network.
|
||||||
pub broadcast: bool,
|
pub broadcast: bool,
|
||||||
|
/// This agent offers itself as an exit node in this network.
|
||||||
|
pub exit_offer: bool,
|
||||||
|
/// The member this device sends all its internet traffic through.
|
||||||
|
pub exit_via: Option<EndpointId>,
|
||||||
|
/// Whether that member is connected and still offering to be one.
|
||||||
|
pub exit_via_online: bool,
|
||||||
|
/// What the host rules for the exit settings are doing.
|
||||||
|
pub exit_rules: crate::overlay::ExitRulesReport,
|
||||||
/// Immutable deterministic description of the network space.
|
/// Immutable deterministic description of the network space.
|
||||||
pub descriptor: NetworkDescriptor,
|
pub descriptor: NetworkDescriptor,
|
||||||
/// Network name, for convenience.
|
/// Network name, for convenience.
|
||||||
@@ -173,15 +257,16 @@ pub struct NetworkStatus {
|
|||||||
pub candidates: Vec<CandidateStatus>,
|
pub candidates: Vec<CandidateStatus>,
|
||||||
/// Members the signed state knows about, whether connected or not.
|
/// Members the signed state knows about, whether connected or not.
|
||||||
pub members: Vec<MemberStatus>,
|
pub members: Vec<MemberStatus>,
|
||||||
|
/// This agent's own name, when another member claimed it first and so
|
||||||
|
/// holds it. This agent keeps working by address; nobody finds it by
|
||||||
|
/// this name until it is renamed or the other member lets it go.
|
||||||
|
pub hostname_conflict: Option<HostnameConflict>,
|
||||||
/// The overlay range this network uses, once it has one.
|
/// The overlay range this network uses, once it has one.
|
||||||
pub range: Option<crate::state::Ipv4Range>,
|
pub range: Option<crate::state::Ipv4Range>,
|
||||||
/// The range it could not have, because another network on this agent
|
/// The first overlapping active range; `range_conflicts` identifies all blockers.
|
||||||
/// already holds it.
|
|
||||||
///
|
|
||||||
/// One agent has one interface, so an address belongs to one network.
|
|
||||||
/// This network waits to adopt whatever its members settle on instead of
|
|
||||||
/// proposing something it could not route.
|
|
||||||
pub range_conflict: Option<crate::state::Ipv4Range>,
|
pub range_conflict: Option<crate::state::Ipv4Range>,
|
||||||
|
/// Active networks that would be suspended by switching to this network.
|
||||||
|
pub range_conflicts: Vec<RangeConflict>,
|
||||||
/// Per-network counters.
|
/// Per-network counters.
|
||||||
pub metrics: NetworkMetrics,
|
pub metrics: NetworkMetrics,
|
||||||
/// What has gone through a peer in the middle, in both directions.
|
/// What has gone through a peer in the middle, in both directions.
|
||||||
@@ -158,6 +158,22 @@ pub enum TransportPolicy {
|
|||||||
/// object where that is possible (notably [`Limits::max_frame_len`]).
|
/// object where that is possible (notably [`Limits::max_frame_len`]).
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Limits {
|
pub struct Limits {
|
||||||
|
/// Maximum active VIP identities per network.
|
||||||
|
pub max_vips: usize,
|
||||||
|
/// Maximum permanent VIP deletion tombstones per network.
|
||||||
|
pub max_vip_tombstones: usize,
|
||||||
|
/// Maximum concurrent active TCP port checks across the agent.
|
||||||
|
pub max_vip_checks: usize,
|
||||||
|
/// Maximum signed fields per VIP, including removed fields.
|
||||||
|
pub max_vip_fields: usize,
|
||||||
|
/// Maximum listeners per VIP.
|
||||||
|
pub max_vip_listeners: usize,
|
||||||
|
/// Maximum backend endpoints per listener.
|
||||||
|
pub max_vip_backends: usize,
|
||||||
|
/// Maximum simultaneous local VIP flow bindings.
|
||||||
|
pub max_vip_flows: usize,
|
||||||
|
/// Maximum incomplete IPv4 datagrams per network in VIP reassembly.
|
||||||
|
pub max_vip_fragments: usize,
|
||||||
/// Largest accepted control frame payload, in bytes.
|
/// Largest accepted control frame payload, in bytes.
|
||||||
pub max_frame_len: usize,
|
pub max_frame_len: usize,
|
||||||
/// Largest accepted hostname, in bytes.
|
/// Largest accepted hostname, in bytes.
|
||||||
@@ -166,12 +182,16 @@ pub struct Limits {
|
|||||||
pub max_capabilities: usize,
|
pub max_capabilities: usize,
|
||||||
/// Largest opaque plugin payload, in bytes.
|
/// Largest opaque plugin payload, in bytes.
|
||||||
pub max_capability_data_len: usize,
|
pub max_capability_data_len: usize,
|
||||||
|
/// Largest private transport negotiation payload (also hard-capped at 4096 bytes).
|
||||||
|
pub max_transport_payload_len: usize,
|
||||||
/// Largest accepted echo payload in a ping/pong exchange, in bytes.
|
/// Largest accepted echo payload in a ping/pong exchange, in bytes.
|
||||||
pub max_echo_payload_len: usize,
|
pub max_echo_payload_len: usize,
|
||||||
/// Largest accepted free-text reason string, in bytes.
|
/// Largest accepted free-text reason string, in bytes.
|
||||||
pub max_reason_len: usize,
|
pub max_reason_len: usize,
|
||||||
/// Largest number of signed records accepted in one snapshot.
|
/// Largest number of signed records accepted in one snapshot.
|
||||||
pub max_state_records: usize,
|
pub max_state_records: usize,
|
||||||
|
/// Maximum durable retirement markers retained per network.
|
||||||
|
pub max_retirements: usize,
|
||||||
/// Deadline for the whole handshake.
|
/// Deadline for the whole handshake.
|
||||||
pub handshake_timeout: Duration,
|
pub handshake_timeout: Duration,
|
||||||
/// Deadline for one outbound dial attempt.
|
/// Deadline for one outbound dial attempt.
|
||||||
@@ -201,13 +221,23 @@ pub struct Limits {
|
|||||||
impl Default for Limits {
|
impl Default for Limits {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
max_vips: 64,
|
||||||
|
max_vip_tombstones: 1024,
|
||||||
|
max_vip_checks: 32,
|
||||||
|
max_vip_fields: 192,
|
||||||
|
max_vip_listeners: 16,
|
||||||
|
max_vip_backends: 32,
|
||||||
|
max_vip_flows: 4096,
|
||||||
|
max_vip_fragments: 64,
|
||||||
max_frame_len: 64 * 1024,
|
max_frame_len: 64 * 1024,
|
||||||
max_hostname_len: 255,
|
max_hostname_len: 255,
|
||||||
max_capabilities: 16,
|
max_capabilities: 16,
|
||||||
|
max_transport_payload_len: 4096,
|
||||||
max_capability_data_len: 4 * 1024,
|
max_capability_data_len: 4 * 1024,
|
||||||
max_echo_payload_len: 4 * 1024,
|
max_echo_payload_len: 4 * 1024,
|
||||||
max_reason_len: 256,
|
max_reason_len: 256,
|
||||||
max_state_records: crate::state::MAX_RECORDS_PER_MESSAGE,
|
max_state_records: crate::state::MAX_RECORDS_PER_MESSAGE,
|
||||||
|
max_retirements: 1024,
|
||||||
handshake_timeout: Duration::from_secs(10),
|
handshake_timeout: Duration::from_secs(10),
|
||||||
dial_timeout: Duration::from_secs(10),
|
dial_timeout: Duration::from_secs(10),
|
||||||
write_timeout: Duration::from_secs(30),
|
write_timeout: Duration::from_secs(30),
|
||||||
@@ -323,8 +353,13 @@ pub struct AgentConfig {
|
|||||||
pub limits: Limits,
|
pub limits: Limits,
|
||||||
/// Reconnect backoff policy.
|
/// Reconnect backoff policy.
|
||||||
pub reconnect: ReconnectPolicy,
|
pub reconnect: ReconnectPolicy,
|
||||||
/// IP plugins whose capabilities are announced and dispatched.
|
/// External data carriers whose capabilities are announced and dispatched.
|
||||||
pub plugins: Vec<SharedPlugin>,
|
pub carriers: Vec<crate::dataplane::transport::SharedCarrier>,
|
||||||
|
/// The single internal end-to-end engine, independent of carrier selection.
|
||||||
|
pub tunnel: Option<SharedPlugin>,
|
||||||
|
/// Initial ordered selection for networks without a saved override.
|
||||||
|
/// `None` enables all registered carriers; an empty list is control-only.
|
||||||
|
pub default_protocols: Option<Vec<String>>,
|
||||||
/// Custom packet transports registered per protocol.
|
/// Custom packet transports registered per protocol.
|
||||||
pub custom_transports:
|
pub custom_transports:
|
||||||
std::collections::HashMap<String, Arc<dyn crate::dataplane::PacketTransport>>,
|
std::collections::HashMap<String, Arc<dyn crate::dataplane::PacketTransport>>,
|
||||||
@@ -339,7 +374,11 @@ pub struct AgentConfig {
|
|||||||
pub interface_name: String,
|
pub interface_name: String,
|
||||||
/// The interface MTU.
|
/// The interface MTU.
|
||||||
pub interface_mtu: u32,
|
pub interface_mtu: u32,
|
||||||
/// The IPv4 overlay range this agent proposes.
|
/// Whether new networks derive their IPv4 range from their network id.
|
||||||
|
///
|
||||||
|
/// Enabled by default. Explicit ranges and IPv4 opt-out disable this.
|
||||||
|
pub overlay_ipv4_auto: bool,
|
||||||
|
/// The IPv4 overlay range this agent proposes when automatic selection is off.
|
||||||
///
|
///
|
||||||
/// Addresses are allocated from it and recorded in signed state, so a
|
/// Addresses are allocated from it and recorded in signed state, so a
|
||||||
/// participant keeps the same one across restarts. A network that has
|
/// participant keeps the same one across restarts. A network that has
|
||||||
@@ -368,12 +407,15 @@ impl AgentConfig {
|
|||||||
discovery_interval: Duration::from_secs(5),
|
discovery_interval: Duration::from_secs(5),
|
||||||
limits: Limits::default(),
|
limits: Limits::default(),
|
||||||
reconnect: ReconnectPolicy::default(),
|
reconnect: ReconnectPolicy::default(),
|
||||||
plugins: Vec::new(),
|
carriers: Vec::new(),
|
||||||
|
tunnel: None,
|
||||||
|
default_protocols: None,
|
||||||
custom_transports: std::collections::HashMap::new(),
|
custom_transports: std::collections::HashMap::new(),
|
||||||
tun_factory: None,
|
tun_factory: None,
|
||||||
interface_name: "tsun0".to_string(),
|
interface_name: "tsun0".to_string(),
|
||||||
interface_mtu: 1280,
|
interface_mtu: 1280,
|
||||||
overlay_ipv4_range: Some(crate::state::DEFAULT_IPV4_RANGE),
|
overlay_ipv4_auto: true,
|
||||||
|
overlay_ipv4_range: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -445,13 +487,20 @@ impl AgentConfig {
|
|||||||
|
|
||||||
/// Sets the IPv4 overlay range this agent proposes, or disables IPv4.
|
/// Sets the IPv4 overlay range this agent proposes, or disables IPv4.
|
||||||
pub fn with_overlay_ipv4_range(mut self, range: Option<crate::state::Ipv4Range>) -> Self {
|
pub fn with_overlay_ipv4_range(mut self, range: Option<crate::state::Ipv4Range>) -> Self {
|
||||||
|
self.overlay_ipv4_auto = false;
|
||||||
self.overlay_ipv4_range = range;
|
self.overlay_ipv4_range = range;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registers an IP plugin.
|
/// Registers an external data carrier.
|
||||||
pub fn with_plugin(mut self, plugin: SharedPlugin) -> Self {
|
pub fn with_carrier(mut self, plugin: crate::dataplane::transport::SharedCarrier) -> Self {
|
||||||
self.plugins.push(plugin);
|
self.carriers.push(plugin);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs the internal encryption engine. It is never a selectable carrier.
|
||||||
|
pub fn with_tunnel(mut self, tunnel: SharedPlugin) -> Self {
|
||||||
|
self.tunnel = Some(tunnel);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -505,9 +554,9 @@ impl std::fmt::Debug for AgentConfig {
|
|||||||
.field("limits", &self.limits)
|
.field("limits", &self.limits)
|
||||||
.field("reconnect", &self.reconnect)
|
.field("reconnect", &self.reconnect)
|
||||||
.field(
|
.field(
|
||||||
"plugins",
|
"carriers",
|
||||||
&self
|
&self
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.map(|p| p.protocol_id().to_string())
|
.map(|p| p.protocol_id().to_string())
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
@@ -1,28 +1,19 @@
|
|||||||
//! Boundary between the control plane core and future IP plugins.
|
//! Boundaries between the agent, one IP encryption tunnel, and external carriers.
|
||||||
//!
|
//!
|
||||||
//! The data plane is where actual IP connectivity is created. WireGuard is the
|
//! The core moves bounded opaque capabilities without parsing cipher payloads.
|
||||||
//! first planned plugin; none is implemented here.
|
//! An [`IpPlugin`] sees routed IP packets and a logical [`PacketLink`] per peer;
|
||||||
|
//! it never learns reachability or the network secret. The agent configures one
|
||||||
|
//! such plugin. Built-in agents use the same internal WireGuard cipher for every
|
||||||
|
//! peer, regardless of which external transports carry the encrypted bytes.
|
||||||
//!
|
//!
|
||||||
//! Two rules shape this module:
|
//! [`transport::DataCarrier`] owns external capability negotiation and lifecycle.
|
||||||
//!
|
//! It sees reachability but never plaintext overlay packets. A relay forwards
|
||||||
//! 1. **The core never parses plugin payloads.** A [`PluginCapability`] carries
|
//! the encrypted inner bytes without entering an IP plugin or the TUN.
|
||||||
//! a protocol id, a version, an enabled flag and a bounded opaque blob. The
|
//! Data-plane failure never stops control sessions or discovery.
|
||||||
//! core transports the blob and hands it to the matching plugin. It does not
|
|
||||||
//! know what a WireGuard configuration looks like.
|
|
||||||
//! 2. **Plugin keys and lifecycle are separate from iroh identity and from the
|
|
||||||
//! network secret.** A plugin owns its own keys and its own system objects.
|
|
||||||
//!
|
|
||||||
//! An iroh address is *not* automatically a WireGuard address. A future plugin
|
|
||||||
//! is expected to gather its own reachability information and ship it through
|
|
||||||
//! the control plane as its announcement payload.
|
|
||||||
//!
|
|
||||||
//! A data plane failure never stops the daemon: errors returned here are
|
|
||||||
//! recorded and surfaced, the control plane keeps running.
|
|
||||||
|
|
||||||
pub mod relay;
|
pub mod relay;
|
||||||
pub mod routing;
|
pub mod routing;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
pub mod tunnel;
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -35,11 +26,37 @@ use crate::identity::NetworkId;
|
|||||||
pub use transport::{
|
pub use transport::{
|
||||||
MultiPacketTransport, PacketLink, PacketTransport, SharedLink, TransportError,
|
MultiPacketTransport, PacketLink, PacketTransport, SharedLink, TransportError,
|
||||||
};
|
};
|
||||||
pub use tunnel::{GenericTunnelPlugin, TunnelCodec};
|
|
||||||
|
|
||||||
/// Maximum length of a plugin protocol identifier.
|
/// Maximum length of a plugin protocol identifier.
|
||||||
pub const MAX_PROTOCOL_ID_LEN: usize = 32;
|
pub const MAX_PROTOCOL_ID_LEN: usize = 32;
|
||||||
|
|
||||||
|
/// Validates bounded local protocol preferences before storing or applying them.
|
||||||
|
pub(crate) fn validate_protocols(protocols: &[String], max: usize) -> crate::error::Result<()> {
|
||||||
|
if protocols.len() > max {
|
||||||
|
return Err(crate::Error::InvalidProtocols(format!(
|
||||||
|
"at most {max} protocols are allowed"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
for (index, name) in protocols.iter().enumerate() {
|
||||||
|
if name.is_empty()
|
||||||
|
|| name.len() > MAX_PROTOCOL_ID_LEN
|
||||||
|
|| !name
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
|
||||||
|
{
|
||||||
|
return Err(crate::Error::InvalidProtocols(
|
||||||
|
"names must be 1–32 ASCII letters, digits, hyphens or underscores".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if protocols[..index].contains(name) {
|
||||||
|
return Err(crate::Error::InvalidProtocols(format!(
|
||||||
|
"`{name}` is listed more than once"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// An announcement of one IP plugin's capability.
|
/// An announcement of one IP plugin's capability.
|
||||||
///
|
///
|
||||||
/// `data` is opaque to the core. Nothing in it may be interpreted as a shell
|
/// `data` is opaque to the core. Nothing in it may be interpreted as a shell
|
||||||
@@ -411,7 +428,9 @@ pub trait IpPlugin: Send + Sync + std::fmt::Debug + 'static {
|
|||||||
/// Always preceded by [`IpPlugin::on_network_deactivated`], so this is
|
/// Always preceded by [`IpPlugin::on_network_deactivated`], so this is
|
||||||
/// only about what outlives a session. Defaulted to nothing, for a
|
/// only about what outlives a session. Defaulted to nothing, for a
|
||||||
/// plugin that stores nothing.
|
/// plugin that stores nothing.
|
||||||
fn on_network_forgotten(&self, _network: NetworkId) {}
|
fn on_network_forgotten(&self, _network: NetworkId) -> BoxFuture<'_, ()> {
|
||||||
|
Box::pin(async {})
|
||||||
|
}
|
||||||
|
|
||||||
/// Called once when the agent shuts down.
|
/// Called once when the agent shuts down.
|
||||||
///
|
///
|
||||||
+245
-105
@@ -67,10 +67,41 @@ impl Tally {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The links to one neighbour, best first. Which transport carries a frame
|
||||||
|
/// is decided here and nowhere else: the end-to-end protocol is in the
|
||||||
|
/// envelope and never depends on it.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct NextHop {
|
struct NextHop {
|
||||||
peer: PeerId,
|
peer: PeerId,
|
||||||
link: SharedLink,
|
links: Box<[SharedLink]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NextHop {
|
||||||
|
fn usable(&self) -> bool {
|
||||||
|
self.links.iter().any(|link| !link.is_closed())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first_open(&self) -> Option<&SharedLink> {
|
||||||
|
self.links.iter().find(|link| !link.is_closed())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands a frame to the best open link that accepts it. A link that
|
||||||
|
/// cannot carry the frame (too large for its path, closed a moment ago)
|
||||||
|
/// leaves it to the next one; the frame is only copied when there is
|
||||||
|
/// another to try.
|
||||||
|
fn send(&self, frame: Bytes) -> Result<(), TransportError> {
|
||||||
|
let mut open = self.links.iter().filter(|link| !link.is_closed());
|
||||||
|
let Some(mut current) = open.next() else {
|
||||||
|
return Err(TransportError::Closed);
|
||||||
|
};
|
||||||
|
for next in open {
|
||||||
|
if current.send(frame.clone()).is_ok() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
current.send(frame)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -82,21 +113,22 @@ struct ForwardRoute {
|
|||||||
impl ForwardRoute {
|
impl ForwardRoute {
|
||||||
fn select(&self, source: &PeerId, flow: FlowId) -> Option<&NextHop> {
|
fn select(&self, source: &PeerId, flow: FlowId) -> Option<&NextHop> {
|
||||||
if self.next.len() == 1 {
|
if self.next.len() == 1 {
|
||||||
return self.next.first().filter(|hop| !hop.link.is_closed());
|
return self.next.first().filter(|hop| hop.usable());
|
||||||
}
|
}
|
||||||
let seed = u64::from_le_bytes(source[..8].try_into().ok()?);
|
let seed = u64::from_le_bytes(source[..8].try_into().ok()?);
|
||||||
let start = mix64(flow ^ seed) as usize % self.next.len();
|
let start = mix64(flow ^ seed) as usize % self.next.len();
|
||||||
// Stable fallback if a link closed just before its table was replaced.
|
// Stable fallback if a link closed just before its table was replaced.
|
||||||
(0..self.next.len())
|
(0..self.next.len())
|
||||||
.map(|i| &self.next[(start + i) % self.next.len()])
|
.map(|i| &self.next[(start + i) % self.next.len()])
|
||||||
.find(|hop| !hop.link.is_closed())
|
.find(|hop| hop.usable())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
struct ForwardingTable {
|
struct ForwardingTable {
|
||||||
routes: HashMap<PeerId, ForwardRoute>,
|
routes: HashMap<PeerId, ForwardRoute>,
|
||||||
inboxes: HashMap<PeerId, mpsc::Sender<Bytes>>,
|
/// Local delivery, by who sent it and which end-to-end protocol it is.
|
||||||
|
inboxes: HashMap<(PeerId, u64), mpsc::Sender<Bytes>>,
|
||||||
members: HashSet<PeerId>,
|
members: HashSet<PeerId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,7 +153,7 @@ impl Plane {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if header.destination == self.local {
|
if header.destination == self.local {
|
||||||
let Some(inbox) = table.inboxes.get(&header.source) else {
|
let Some(inbox) = table.inboxes.get(&(header.source, header.protocol)) else {
|
||||||
self.tally.dropped_unknown.fetch_add(1, Ordering::Relaxed);
|
self.tally.dropped_unknown.fetch_add(1, Ordering::Relaxed);
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -144,7 +176,7 @@ impl Plane {
|
|||||||
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
if hop.link.send(envelope::decrement(frame)).is_ok() {
|
if hop.send(envelope::decrement(frame)).is_ok() {
|
||||||
self.tally.forwarded.fetch_add(1, Ordering::Relaxed);
|
self.tally.forwarded.fetch_add(1, Ordering::Relaxed);
|
||||||
} else {
|
} else {
|
||||||
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
||||||
@@ -152,27 +184,65 @@ impl Plane {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One physical link to a neighbour, of whatever kind of transport.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Protocol {
|
struct RawLink {
|
||||||
|
kind: String,
|
||||||
|
link: SharedLink,
|
||||||
|
reader: JoinHandle<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a destination is reached right now.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct RouteSummary {
|
||||||
|
/// Number of transport links to it. One is a direct link.
|
||||||
|
pub hops: u8,
|
||||||
|
/// The neighbour the first link goes to. For a direct link that is the
|
||||||
|
/// destination itself.
|
||||||
|
pub via: EndpointId,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct State {
|
||||||
plane: Arc<Plane>,
|
plane: Arc<Plane>,
|
||||||
|
/// Transport kinds, best first. A neighbour with several links is
|
||||||
|
/// reached over the first of these it has.
|
||||||
|
priority: Vec<String>,
|
||||||
graph: HashMap<PeerId, Vec<PeerId>>,
|
graph: HashMap<PeerId, Vec<PeerId>>,
|
||||||
members: HashSet<PeerId>,
|
members: HashSet<PeerId>,
|
||||||
raw: HashMap<PeerId, SharedLink>,
|
raw: HashMap<PeerId, Vec<RawLink>>,
|
||||||
readers: HashMap<PeerId, JoinHandle<()>>,
|
links: HashMap<(PeerId, String), Arc<PeerLink>>,
|
||||||
links: HashMap<PeerId, Arc<PeerLink>>,
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
fn rank(&self, kind: &str) -> usize {
|
||||||
|
self.priority
|
||||||
|
.iter()
|
||||||
|
.position(|known| known == kind)
|
||||||
|
.unwrap_or(usize::MAX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A neighbour's links, best kind first.
|
||||||
|
fn ordered(&self, peer: &PeerId) -> Vec<&RawLink> {
|
||||||
|
let mut links: Vec<&RawLink> = self
|
||||||
|
.raw
|
||||||
|
.get(peer)
|
||||||
|
.map(|links| links.iter().collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
links.sort_by_key(|raw| (self.rank(&raw.kind), raw.kind.clone()));
|
||||||
|
links
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Protocol {
|
|
||||||
fn publish(&self) {
|
fn publish(&self) {
|
||||||
let mut graph = self.graph.clone();
|
let mut graph = self.graph.clone();
|
||||||
graph.insert(
|
let mut neighbours: Vec<PeerId> = self
|
||||||
self.plane.local,
|
.raw
|
||||||
self.raw
|
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(_, link)| !link.is_closed())
|
.filter(|(_, links)| links.iter().any(|raw| !raw.link.is_closed()))
|
||||||
.map(|(peer, _)| *peer)
|
.map(|(peer, _)| *peer)
|
||||||
.collect(),
|
.collect();
|
||||||
);
|
neighbours.sort_unstable();
|
||||||
|
graph.insert(self.plane.local, neighbours);
|
||||||
let routing = RoutingTable::build(self.plane.local, &graph, ROUTING_HOP_LIMIT);
|
let routing = RoutingTable::build(self.plane.local, &graph, ROUTING_HOP_LIMIT);
|
||||||
let routes = routing
|
let routes = routing
|
||||||
.iter()
|
.iter()
|
||||||
@@ -181,10 +251,12 @@ impl Protocol {
|
|||||||
.next_hops
|
.next_hops
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|id| {
|
.filter_map(|id| {
|
||||||
self.raw.get(id).map(|link| NextHop {
|
let links: Box<[_]> = self
|
||||||
peer: *id,
|
.ordered(id)
|
||||||
link: link.clone(),
|
.into_iter()
|
||||||
})
|
.map(|raw| raw.link.clone())
|
||||||
|
.collect();
|
||||||
|
(!links.is_empty()).then_some(NextHop { peer: *id, links })
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
(!next.is_empty()).then_some((
|
(!next.is_empty()).then_some((
|
||||||
@@ -204,17 +276,21 @@ impl Protocol {
|
|||||||
inboxes: self
|
inboxes: self
|
||||||
.links
|
.links
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(peer, link)| (*peer, link.inbox_tx.clone()))
|
.map(|((peer, _), link)| ((*peer, link.tag), link.inbox_tx.clone()))
|
||||||
.collect(),
|
.collect(),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn stop_readers(&mut self) {
|
||||||
|
for raw in self.raw.values().flatten() {
|
||||||
|
raw.reader.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Protocol {
|
impl Drop for State {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
for task in self.readers.values() {
|
self.stop_readers();
|
||||||
task.abort();
|
|
||||||
}
|
|
||||||
for link in self.links.values() {
|
for link in self.links.values() {
|
||||||
link.close();
|
link.close();
|
||||||
}
|
}
|
||||||
@@ -222,12 +298,17 @@ impl Drop for Protocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One network's transport links and independently published protocol tables.
|
/// One network's transport links and its published forwarding table.
|
||||||
|
///
|
||||||
|
/// There is one table for the whole network, whatever protocols run over it.
|
||||||
|
/// A link is a way to reach a neighbour; a protocol is an end-to-end channel
|
||||||
|
/// to a peer. The two meet only in the envelope, which names the protocol, so
|
||||||
|
/// a tunnel keeps working over any mix of transports and a middle member
|
||||||
|
/// needs no protocol in common with either end.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct RelayHub {
|
pub struct RelayHub {
|
||||||
network: NetworkId,
|
network: NetworkId,
|
||||||
local: PeerId,
|
state: Mutex<State>,
|
||||||
protocols: Mutex<HashMap<String, Protocol>>,
|
|
||||||
tally: Arc<Tally>,
|
tally: Arc<Tally>,
|
||||||
changed: Arc<Notify>,
|
changed: Arc<Notify>,
|
||||||
}
|
}
|
||||||
@@ -235,40 +316,38 @@ pub struct RelayHub {
|
|||||||
impl RelayHub {
|
impl RelayHub {
|
||||||
/// Creates the router at this network's local endpoint.
|
/// Creates the router at this network's local endpoint.
|
||||||
pub fn new(network: NetworkId, local: EndpointId) -> Arc<Self> {
|
pub fn new(network: NetworkId, local: EndpointId) -> Arc<Self> {
|
||||||
|
let tally = Arc::new(Tally::default());
|
||||||
Arc::new(Self {
|
Arc::new(Self {
|
||||||
network,
|
network,
|
||||||
|
state: Mutex::new(State {
|
||||||
|
plane: Arc::new(Plane {
|
||||||
local: *local.as_bytes(),
|
local: *local.as_bytes(),
|
||||||
protocols: Mutex::default(),
|
table: ArcSwap::from_pointee(ForwardingTable::default()),
|
||||||
tally: Arc::default(),
|
tally: tally.clone(),
|
||||||
|
}),
|
||||||
|
priority: Vec::new(),
|
||||||
|
graph: HashMap::new(),
|
||||||
|
members: HashSet::new(),
|
||||||
|
raw: HashMap::new(),
|
||||||
|
links: HashMap::new(),
|
||||||
|
}),
|
||||||
|
tally,
|
||||||
changed: Arc::default(),
|
changed: Arc::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn protocols(&self) -> std::sync::MutexGuard<'_, HashMap<String, Protocol>> {
|
fn state(&self) -> std::sync::MutexGuard<'_, State> {
|
||||||
self.protocols
|
self.state.lock().unwrap_or_else(|error| error.into_inner())
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(|error| error.into_inner())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn protocol<'a>(
|
/// Sets which kinds of transport are preferred, best first, when a
|
||||||
&self,
|
/// neighbour can be reached over more than one.
|
||||||
protocols: &'a mut HashMap<String, Protocol>,
|
pub fn set_priority(&self, kinds: Vec<String>) {
|
||||||
name: &str,
|
let mut state = self.state();
|
||||||
) -> &'a mut Protocol {
|
if state.priority != kinds {
|
||||||
protocols
|
state.priority = kinds;
|
||||||
.entry(name.to_owned())
|
state.publish();
|
||||||
.or_insert_with(|| Protocol {
|
}
|
||||||
plane: Arc::new(Plane {
|
|
||||||
local: self.local,
|
|
||||||
table: ArcSwap::from_pointee(ForwardingTable::default()),
|
|
||||||
tally: self.tally.clone(),
|
|
||||||
}),
|
|
||||||
graph: HashMap::new(),
|
|
||||||
members: HashSet::new(),
|
|
||||||
raw: HashMap::new(),
|
|
||||||
readers: HashMap::new(),
|
|
||||||
links: HashMap::new(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wakes the control loop promptly when a transport reader ends.
|
/// Wakes the control loop promptly when a transport reader ends.
|
||||||
@@ -282,14 +361,11 @@ impl RelayHub {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Publishes authenticated topology. Refreshing identical state is cheap.
|
/// Publishes authenticated topology. Refreshing identical state is cheap.
|
||||||
pub fn set_topology(
|
///
|
||||||
&self,
|
/// Every row of `graph` is one member's own account of who it has a link
|
||||||
protocol: &str,
|
/// to; what kind of link it is does not matter here.
|
||||||
graph: HashMap<PeerId, Vec<PeerId>>,
|
pub fn set_topology(&self, graph: HashMap<PeerId, Vec<PeerId>>, members: HashSet<PeerId>) {
|
||||||
members: HashSet<PeerId>,
|
let mut state = self.state();
|
||||||
) {
|
|
||||||
let mut protocols = self.protocols();
|
|
||||||
let state = self.protocol(&mut protocols, protocol);
|
|
||||||
if state.graph != graph || state.members != members {
|
if state.graph != graph || state.members != members {
|
||||||
state.graph = graph;
|
state.graph = graph;
|
||||||
state.members = members;
|
state.members = members;
|
||||||
@@ -298,22 +374,44 @@ impl RelayHub {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the current table has a path to this destination.
|
/// Whether the current table has a path to this destination.
|
||||||
pub fn reachable(&self, peer: EndpointId, protocol: &str) -> bool {
|
pub fn reachable(&self, peer: EndpointId) -> bool {
|
||||||
self.protocols().get(protocol).is_some_and(|state| {
|
self.state()
|
||||||
state
|
|
||||||
.plane
|
.plane
|
||||||
.table
|
.table
|
||||||
.load()
|
.load()
|
||||||
.routes
|
.routes
|
||||||
.contains_key(peer.as_bytes())
|
.contains_key(peer.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a destination is reached right now, if it is.
|
||||||
|
pub fn route(&self, peer: EndpointId) -> Option<RouteSummary> {
|
||||||
|
let table = self.state().plane.table.load_full();
|
||||||
|
let route = table.routes.get(peer.as_bytes())?;
|
||||||
|
let via = EndpointId::from_bytes(&route.next.first()?.peer).ok()?;
|
||||||
|
Some(RouteSummary {
|
||||||
|
hops: route.hops,
|
||||||
|
via,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stable logical link, preserved across topology changes.
|
/// The kinds of transport with an open direct link to a peer, best
|
||||||
|
/// first.
|
||||||
|
pub fn direct_kinds(&self, peer: EndpointId) -> Vec<String> {
|
||||||
|
let state = self.state();
|
||||||
|
state
|
||||||
|
.ordered(peer.as_bytes())
|
||||||
|
.into_iter()
|
||||||
|
.filter(|raw| !raw.link.is_closed())
|
||||||
|
.map(|raw| raw.kind.clone())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stable end-to-end channel for a protocol, preserved across topology
|
||||||
|
/// and transport changes.
|
||||||
pub fn link(&self, peer: EndpointId, protocol: &str) -> Arc<PeerLink> {
|
pub fn link(&self, peer: EndpointId, protocol: &str) -> Arc<PeerLink> {
|
||||||
let mut protocols = self.protocols();
|
let mut state = self.state();
|
||||||
let state = self.protocol(&mut protocols, protocol);
|
let key = (*peer.as_bytes(), protocol.to_owned());
|
||||||
if let Some(link) = state.links.get(peer.as_bytes()) {
|
if let Some(link) = state.links.get(&key) {
|
||||||
return link.clone();
|
return link.clone();
|
||||||
}
|
}
|
||||||
let (inbox_tx, inbox_rx) = mpsc::channel(INBOX);
|
let (inbox_tx, inbox_rx) = mpsc::channel(INBOX);
|
||||||
@@ -321,43 +419,40 @@ impl RelayHub {
|
|||||||
let link = Arc::new(PeerLink {
|
let link = Arc::new(PeerLink {
|
||||||
network: self.network,
|
network: self.network,
|
||||||
peer,
|
peer,
|
||||||
|
tag: envelope::protocol_tag(protocol),
|
||||||
plane: state.plane.clone(),
|
plane: state.plane.clone(),
|
||||||
inbox_tx,
|
inbox_tx,
|
||||||
inbox_rx: tokio::sync::Mutex::new(inbox_rx),
|
inbox_rx: tokio::sync::Mutex::new(inbox_rx),
|
||||||
closed,
|
closed,
|
||||||
});
|
});
|
||||||
state.links.insert(*peer.as_bytes(), link.clone());
|
state.links.insert(key, link.clone());
|
||||||
state.publish();
|
state.publish();
|
||||||
link
|
link
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the protocol already owns its logical link.
|
/// Whether the protocol already owns its end-to-end channel to a peer.
|
||||||
pub fn has_link(&self, peer: EndpointId, protocol: &str) -> bool {
|
pub fn has_link(&self, peer: EndpointId, protocol: &str) -> bool {
|
||||||
self.protocols()
|
self.state()
|
||||||
.get(protocol)
|
.links
|
||||||
.is_some_and(|state| state.links.contains_key(peer.as_bytes()))
|
.contains_key(&(*peer.as_bytes(), protocol.to_owned()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Installs a raw transport link and starts its independent ingress reader.
|
/// Installs a raw transport link and starts its independent ingress reader.
|
||||||
pub fn set_direct(&self, peer: EndpointId, protocol: &str, raw: SharedLink) {
|
///
|
||||||
|
/// A neighbour may have one link per kind of transport; installing a
|
||||||
|
/// second of the same kind replaces the first.
|
||||||
|
pub fn set_direct(&self, peer: EndpointId, kind: &str, raw: SharedLink) {
|
||||||
if raw.network() != self.network || raw.peer() != peer {
|
if raw.network() != self.network || raw.peer() != peer {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let mut protocols = self.protocols();
|
let mut state = self.state();
|
||||||
let state = self.protocol(&mut protocols, protocol);
|
|
||||||
let id = *peer.as_bytes();
|
let id = *peer.as_bytes();
|
||||||
if let Some(old) = state.readers.remove(&id) {
|
|
||||||
old.abort();
|
|
||||||
}
|
|
||||||
state.raw.insert(id, raw.clone());
|
|
||||||
state.publish();
|
|
||||||
let plane = state.plane.clone();
|
let plane = state.plane.clone();
|
||||||
let changed = self.changed.clone();
|
let changed = self.changed.clone();
|
||||||
state.readers.insert(
|
let reader_link = raw.clone();
|
||||||
id,
|
let reader = tokio::spawn(async move {
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut batch = 0;
|
let mut batch = 0;
|
||||||
while let Some(frame) = raw.recv().await {
|
while let Some(frame) = reader_link.recv().await {
|
||||||
plane.receive(id, frame);
|
plane.receive(id, frame);
|
||||||
batch += 1;
|
batch += 1;
|
||||||
if batch == 64 {
|
if batch == 64 {
|
||||||
@@ -366,31 +461,64 @@ impl RelayHub {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
changed.notify_one();
|
changed.notify_one();
|
||||||
}),
|
});
|
||||||
);
|
let links = state.raw.entry(id).or_default();
|
||||||
|
if let Some(position) = links.iter().position(|known| known.kind == kind) {
|
||||||
|
links.remove(position).reader.abort();
|
||||||
|
}
|
||||||
|
links.push(RawLink {
|
||||||
|
kind: kind.to_owned(),
|
||||||
|
link: raw,
|
||||||
|
reader,
|
||||||
|
});
|
||||||
|
state.publish();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes a physical link without tearing down end-to-end protocol state.
|
/// Removes one physical link without tearing down end-to-end protocol state.
|
||||||
pub fn clear_direct(&self, peer: EndpointId, protocol: &str) {
|
pub fn clear_direct(&self, peer: EndpointId, kind: &str) {
|
||||||
if let Some(state) = self.protocols().get_mut(protocol) {
|
let mut state = self.state();
|
||||||
state.raw.remove(peer.as_bytes());
|
let mut changed = false;
|
||||||
if let Some(task) = state.readers.remove(peer.as_bytes()) {
|
if let Some(links) = state.raw.get_mut(peer.as_bytes()) {
|
||||||
task.abort();
|
if let Some(position) = links.iter().position(|known| known.kind == kind) {
|
||||||
|
links.remove(position).reader.abort();
|
||||||
|
changed = true;
|
||||||
}
|
}
|
||||||
|
if links.is_empty() {
|
||||||
|
state.raw.remove(peer.as_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if changed {
|
||||||
state.publish();
|
state.publish();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Revokes all links and topology involving a departed authenticated peer.
|
/// Retires data channels without removing an authenticated peer's topology.
|
||||||
pub fn remove_peer(&self, peer: EndpointId) {
|
pub fn clear_peer_links(&self, peer: EndpointId) {
|
||||||
for state in self.protocols().values_mut() {
|
let mut state = self.state();
|
||||||
state.raw.remove(peer.as_bytes());
|
if let Some(links) = state.raw.remove(peer.as_bytes()) {
|
||||||
if let Some(task) = state.readers.remove(peer.as_bytes()) {
|
for raw in links {
|
||||||
task.abort();
|
raw.link.close();
|
||||||
|
raw.reader.abort();
|
||||||
}
|
}
|
||||||
if let Some(link) = state.links.remove(peer.as_bytes()) {
|
}
|
||||||
|
let gone: Vec<_> = state
|
||||||
|
.links
|
||||||
|
.keys()
|
||||||
|
.filter(|(id, _)| id == peer.as_bytes())
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
for key in gone {
|
||||||
|
if let Some(link) = state.links.remove(&key) {
|
||||||
link.close();
|
link.close();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
state.publish();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Revokes all links and topology involving a departed authenticated peer.
|
||||||
|
pub fn remove_peer(&self, peer: EndpointId) {
|
||||||
|
self.clear_peer_links(peer);
|
||||||
|
let mut state = self.state();
|
||||||
state.members.remove(peer.as_bytes());
|
state.members.remove(peer.as_bytes());
|
||||||
state.graph.remove(peer.as_bytes());
|
state.graph.remove(peer.as_bytes());
|
||||||
for neighbors in state.graph.values_mut() {
|
for neighbors in state.graph.values_mut() {
|
||||||
@@ -398,11 +526,19 @@ impl RelayHub {
|
|||||||
}
|
}
|
||||||
state.publish();
|
state.publish();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Stops every reader and releases all transport handles.
|
/// Stops every reader and releases all transport handles.
|
||||||
pub fn close(&self) {
|
pub fn close(&self) {
|
||||||
self.protocols().clear();
|
let mut state = self.state();
|
||||||
|
state.stop_readers();
|
||||||
|
state.raw.clear();
|
||||||
|
for link in state.links.values() {
|
||||||
|
link.close();
|
||||||
|
}
|
||||||
|
state.links.clear();
|
||||||
|
state.graph.clear();
|
||||||
|
state.members.clear();
|
||||||
|
state.plane.table.store(Arc::default());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -411,6 +547,7 @@ impl RelayHub {
|
|||||||
pub struct PeerLink {
|
pub struct PeerLink {
|
||||||
network: NetworkId,
|
network: NetworkId,
|
||||||
peer: EndpointId,
|
peer: EndpointId,
|
||||||
|
tag: u64,
|
||||||
plane: Arc<Plane>,
|
plane: Arc<Plane>,
|
||||||
inbox_tx: mpsc::Sender<Bytes>,
|
inbox_tx: mpsc::Sender<Bytes>,
|
||||||
inbox_rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
inbox_rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||||
@@ -454,10 +591,11 @@ impl PacketLink for PeerLink {
|
|||||||
let hop = route
|
let hop = route
|
||||||
.select(&self.plane.local, flow)
|
.select(&self.plane.local, flow)
|
||||||
.ok_or(TransportError::Closed)?;
|
.ok_or(TransportError::Closed)?;
|
||||||
hop.link.send(envelope::encode(
|
hop.send(envelope::encode(
|
||||||
self.plane.local,
|
self.plane.local,
|
||||||
*self.peer.as_bytes(),
|
*self.peer.as_bytes(),
|
||||||
flow,
|
flow,
|
||||||
|
self.tag,
|
||||||
&payload,
|
&payload,
|
||||||
))?;
|
))?;
|
||||||
if route.hops > 1 {
|
if route.hops > 1 {
|
||||||
@@ -489,7 +627,9 @@ impl PacketLink for PeerLink {
|
|||||||
fn path_description(&self) -> String {
|
fn path_description(&self) -> String {
|
||||||
let table = self.plane.table.load();
|
let table = self.plane.table.load();
|
||||||
match table.routes.get(self.peer.as_bytes()) {
|
match table.routes.get(self.peer.as_bytes()) {
|
||||||
Some(route) if route.hops == 1 => route.next[0].link.path_description(),
|
Some(route) if route.hops == 1 => route.next[0]
|
||||||
|
.first_open()
|
||||||
|
.map_or_else(|| "unreachable".into(), |link| link.path_description()),
|
||||||
Some(route) => format!(
|
Some(route) => format!(
|
||||||
"relay {} hops via {} ({} equal paths)",
|
"relay {} hops via {} ({} equal paths)",
|
||||||
route.hops,
|
route.hops,
|
||||||
+147
-16
@@ -16,6 +16,9 @@ fn peer(seed: u8) -> EndpointId {
|
|||||||
fn id(seed: u8) -> PeerId {
|
fn id(seed: u8) -> PeerId {
|
||||||
*peer(seed).as_bytes()
|
*peer(seed).as_bytes()
|
||||||
}
|
}
|
||||||
|
fn tag() -> u64 {
|
||||||
|
envelope::protocol_tag("ip")
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Wire {
|
struct Wire {
|
||||||
@@ -78,9 +81,8 @@ impl PacketLink for Wire {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn topology(hub: &RelayHub, protocol: &str, edges: &[(u8, &[u8])], members: &[u8]) {
|
fn topology(hub: &RelayHub, edges: &[(u8, &[u8])], members: &[u8]) {
|
||||||
hub.set_topology(
|
hub.set_topology(
|
||||||
protocol,
|
|
||||||
edges
|
edges
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(a, bs)| (id(*a), bs.iter().map(|b| id(*b)).collect()))
|
.map(|(a, bs)| (id(*a), bs.iter().map(|b| id(*b)).collect()))
|
||||||
@@ -96,7 +98,7 @@ async fn ecmp_is_per_flow_direct_wins_and_existing_tunnel_survives_changes() {
|
|||||||
let c = Wire::new(3, true);
|
let c = Wire::new(3, true);
|
||||||
hub.set_direct(peer(2), "ip", b.clone());
|
hub.set_direct(peer(2), "ip", b.clone());
|
||||||
hub.set_direct(peer(3), "ip", c.clone());
|
hub.set_direct(peer(3), "ip", c.clone());
|
||||||
topology(&hub, "ip", &[(2, &[4]), (3, &[4])], &[1, 2, 3, 4]);
|
topology(&hub, &[(2, &[4]), (3, &[4])], &[1, 2, 3, 4]);
|
||||||
let link = hub.link(peer(4), "ip");
|
let link = hub.link(peer(4), "ip");
|
||||||
let mut chosen = HashMap::new();
|
let mut chosen = HashMap::new();
|
||||||
for _ in 0..8 {
|
for _ in 0..8 {
|
||||||
@@ -132,7 +134,7 @@ async fn ecmp_is_per_flow_direct_wins_and_existing_tunnel_survives_changes() {
|
|||||||
}
|
}
|
||||||
assert_eq!(c.take().len(), 100);
|
assert_eq!(c.take().len(), 100);
|
||||||
hub.clear_direct(peer(2), "ip");
|
hub.clear_direct(peer(2), "ip");
|
||||||
topology(&hub, "ip", &[(3, &[])], &[1, 2, 3, 4]);
|
topology(&hub, &[(3, &[])], &[1, 2, 3, 4]);
|
||||||
assert!(link.send(Bytes::new()).is_err());
|
assert!(link.send(Bytes::new()).is_err());
|
||||||
assert!(!link.is_closed());
|
assert!(!link.is_closed());
|
||||||
assert!(Arc::ptr_eq(&link, &hub.link(peer(4), "ip")));
|
assert!(Arc::ptr_eq(&link, &hub.link(peer(4), "ip")));
|
||||||
@@ -152,8 +154,8 @@ async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protoc
|
|||||||
let c = Wire::new(3, true);
|
let c = Wire::new(3, true);
|
||||||
hub.set_direct(peer(1), "ip", a.clone());
|
hub.set_direct(peer(1), "ip", a.clone());
|
||||||
hub.set_direct(peer(3), "ip", c.clone());
|
hub.set_direct(peer(3), "ip", c.clone());
|
||||||
topology(&hub, "ip", &[(3, &[4])], &[1, 2, 3, 4]);
|
topology(&hub, &[(3, &[4])], &[1, 2, 3, 4]);
|
||||||
let frame = envelope::encode(id(1), id(4), 91, b"end-to-end encrypted");
|
let frame = envelope::encode(id(1), id(4), 91, tag(), b"end-to-end encrypted");
|
||||||
let pointer = frame.as_ptr();
|
let pointer = frame.as_ptr();
|
||||||
a.feed.send(frame).await.unwrap();
|
a.feed.send(frame).await.unwrap();
|
||||||
tokio::time::timeout(std::time::Duration::from_secs(1), async {
|
tokio::time::timeout(std::time::Duration::from_secs(1), async {
|
||||||
@@ -170,12 +172,136 @@ async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protoc
|
|||||||
ROUTING_HOP_LIMIT - 1
|
ROUTING_HOP_LIMIT - 1
|
||||||
);
|
);
|
||||||
assert_eq!(&sent[0][RELAY_OVERHEAD..], b"end-to-end encrypted");
|
assert_eq!(&sent[0][RELAY_OVERHEAD..], b"end-to-end encrypted");
|
||||||
let isolated = hub.link(peer(4), "other-ip");
|
|
||||||
assert!(isolated.send(Bytes::new()).is_err());
|
|
||||||
assert_eq!(hub.counters().forwarded, 1);
|
assert_eq!(hub.counters().forwarded, 1);
|
||||||
hub.close();
|
hub.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_frame_is_delivered_only_to_the_protocol_it_names() {
|
||||||
|
let hub = RelayHub::new(network(), peer(2));
|
||||||
|
hub.set_direct(peer(1), "ip", Wire::new(1, true));
|
||||||
|
let ip = hub.link(peer(1), "ip");
|
||||||
|
let other = hub.link(peer(1), "other-ip");
|
||||||
|
let plane = ip.plane.clone();
|
||||||
|
plane.receive(id(1), envelope::encode(id(1), id(2), 0, tag(), b"for ip"));
|
||||||
|
plane.receive(
|
||||||
|
id(1),
|
||||||
|
envelope::encode(
|
||||||
|
id(1),
|
||||||
|
id(2),
|
||||||
|
0,
|
||||||
|
envelope::protocol_tag("other-ip"),
|
||||||
|
b"for other",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
plane.receive(
|
||||||
|
id(1),
|
||||||
|
envelope::encode(
|
||||||
|
id(1),
|
||||||
|
id(2),
|
||||||
|
0,
|
||||||
|
envelope::protocol_tag("nobody-runs-this"),
|
||||||
|
b"for nobody",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
assert_eq!(ip.recv().await.unwrap(), Bytes::from_static(b"for ip"));
|
||||||
|
assert_eq!(
|
||||||
|
other.recv().await.unwrap(),
|
||||||
|
Bytes::from_static(b"for other")
|
||||||
|
);
|
||||||
|
assert_eq!(hub.counters().dropped_unknown, 1);
|
||||||
|
hub.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A middle member joins two neighbours over different transports, and the
|
||||||
|
/// two ends share a protocol the middle has never heard of.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_tunnel_crosses_a_middle_member_whose_links_are_of_different_kinds() {
|
||||||
|
let a = RelayHub::new(network(), peer(1));
|
||||||
|
let c = RelayHub::new(network(), peer(3));
|
||||||
|
let b = RelayHub::new(network(), peer(2));
|
||||||
|
let a_to_c = Wire::new(3, true);
|
||||||
|
let c_to_a = Wire::new(1, true);
|
||||||
|
let c_to_b = Wire::new(2, true);
|
||||||
|
let b_to_c = Wire::new(3, true);
|
||||||
|
a.set_direct(peer(3), "wg", a_to_c.clone());
|
||||||
|
c.set_direct(peer(1), "wg", c_to_a);
|
||||||
|
c.set_direct(peer(2), "wg-quic", c_to_b.clone());
|
||||||
|
b.set_direct(peer(3), "wg-quic", b_to_c.clone());
|
||||||
|
topology(&a, &[(3, &[1, 2])], &[1, 2, 3]);
|
||||||
|
topology(&b, &[(3, &[1, 2])], &[1, 2, 3]);
|
||||||
|
topology(&c, &[(1, &[3]), (2, &[3])], &[1, 2, 3]);
|
||||||
|
|
||||||
|
let outgoing = a.link(peer(2), "tunnel");
|
||||||
|
let incoming = b.link(peer(1), "tunnel");
|
||||||
|
outgoing
|
||||||
|
.send_flow(Bytes::from_static(b"sealed"), 5)
|
||||||
|
.unwrap();
|
||||||
|
let frame = a_to_c.take().remove(0);
|
||||||
|
|
||||||
|
// The middle forwards it onto its other kind of link without looking
|
||||||
|
// inside.
|
||||||
|
c.state().plane.receive(id(1), frame);
|
||||||
|
let frame = c_to_b.take().remove(0);
|
||||||
|
assert_eq!(c.counters().forwarded, 1);
|
||||||
|
|
||||||
|
b.state().plane.receive(id(3), frame);
|
||||||
|
assert_eq!(
|
||||||
|
incoming.recv().await.unwrap(),
|
||||||
|
Bytes::from_static(b"sealed")
|
||||||
|
);
|
||||||
|
assert_eq!(b.counters().received_via, 1);
|
||||||
|
assert_eq!(
|
||||||
|
b.route(peer(1)),
|
||||||
|
Some(RouteSummary {
|
||||||
|
hops: 2,
|
||||||
|
via: peer(3)
|
||||||
|
})
|
||||||
|
);
|
||||||
|
a.close();
|
||||||
|
b.close();
|
||||||
|
c.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_neighbour_is_reached_over_the_preferred_kind_and_falls_back_when_it_is_lost() {
|
||||||
|
let hub = RelayHub::new(network(), peer(1));
|
||||||
|
hub.set_priority(vec!["wg".into(), "tcp-tls".into(), "wg-quic".into()]);
|
||||||
|
let slow = Wire::new(2, true);
|
||||||
|
let fast = Wire::new(2, true);
|
||||||
|
hub.set_direct(peer(2), "wg-quic", slow.clone());
|
||||||
|
let link = hub.link(peer(2), "tunnel");
|
||||||
|
link.send(Bytes::from_static(b"one")).unwrap();
|
||||||
|
assert_eq!(slow.take().len(), 1);
|
||||||
|
assert_eq!(hub.direct_kinds(peer(2)), ["wg-quic"]);
|
||||||
|
|
||||||
|
// A better kind appears: traffic moves to it with nothing to redo.
|
||||||
|
hub.set_direct(peer(2), "wg", fast.clone());
|
||||||
|
assert_eq!(hub.direct_kinds(peer(2)), ["wg", "wg-quic"]);
|
||||||
|
link.send(Bytes::from_static(b"two")).unwrap();
|
||||||
|
assert_eq!(fast.take().len(), 1);
|
||||||
|
assert!(slow.take().is_empty());
|
||||||
|
|
||||||
|
// It dies: the worse one carries on, and the logical link is untouched.
|
||||||
|
fast.dead.store(true, Ordering::Relaxed);
|
||||||
|
link.send(Bytes::from_static(b"three")).unwrap();
|
||||||
|
assert_eq!(slow.take().len(), 1);
|
||||||
|
assert!(!link.is_closed());
|
||||||
|
assert_eq!(
|
||||||
|
hub.route(peer(2)),
|
||||||
|
Some(RouteSummary {
|
||||||
|
hops: 1,
|
||||||
|
via: peer(2)
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
hub.clear_direct(peer(2), "wg-quic");
|
||||||
|
hub.clear_direct(peer(2), "wg");
|
||||||
|
assert!(!hub.reachable(peer(2)));
|
||||||
|
assert!(Arc::ptr_eq(&link, &hub.link(peer(2), "tunnel")));
|
||||||
|
hub.close();
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn local_delivery_is_bounded_and_malformed_or_unknown_sources_are_dropped() {
|
async fn local_delivery_is_bounded_and_malformed_or_unknown_sources_are_dropped() {
|
||||||
let hub = RelayHub::new(network(), peer(2));
|
let hub = RelayHub::new(network(), peer(2));
|
||||||
@@ -184,18 +310,21 @@ async fn local_delivery_is_bounded_and_malformed_or_unknown_sources_are_dropped(
|
|||||||
let link = hub.link(peer(1), "ip");
|
let link = hub.link(peer(1), "ip");
|
||||||
let plane = link.plane.clone();
|
let plane = link.plane.clone();
|
||||||
for _ in 0..INBOX + 1 {
|
for _ in 0..INBOX + 1 {
|
||||||
plane.receive(id(1), envelope::encode(id(1), id(2), 0, b"ip"));
|
plane.receive(id(1), envelope::encode(id(1), id(2), 0, tag(), b"ip"));
|
||||||
}
|
}
|
||||||
assert_eq!(hub.counters().dropped_congested, 1);
|
assert_eq!(hub.counters().dropped_congested, 1);
|
||||||
for _ in 0..INBOX {
|
for _ in 0..INBOX {
|
||||||
assert_eq!(link.recv().await.unwrap(), Bytes::from_static(b"ip"));
|
assert_eq!(link.recv().await.unwrap(), Bytes::from_static(b"ip"));
|
||||||
}
|
}
|
||||||
plane.receive(id(1), Bytes::from_static(b"broken"));
|
plane.receive(id(1), Bytes::from_static(b"broken"));
|
||||||
plane.receive(id(1), envelope::encode(id(9), id(2), 0, b"unknown member"));
|
plane.receive(
|
||||||
|
id(1),
|
||||||
|
envelope::encode(id(9), id(2), 0, tag(), b"unknown member"),
|
||||||
|
);
|
||||||
assert_eq!(hub.counters().dropped_unknown, 2);
|
assert_eq!(hub.counters().dropped_unknown, 2);
|
||||||
plane.receive(
|
plane.receive(
|
||||||
id(1),
|
id(1),
|
||||||
envelope::encode(id(1), id(9), 0, b"unknown destination"),
|
envelope::encode(id(1), id(9), 0, tag(), b"unknown destination"),
|
||||||
);
|
);
|
||||||
assert_eq!(hub.counters().dropped_no_link, 1);
|
assert_eq!(hub.counters().dropped_no_link, 1);
|
||||||
hub.close();
|
hub.close();
|
||||||
@@ -210,11 +339,11 @@ async fn inconsistent_tables_cannot_loop_beyond_the_hop_limit() {
|
|||||||
a.set_direct(peer(2), "ip", ab.clone());
|
a.set_direct(peer(2), "ip", ab.clone());
|
||||||
b.set_direct(peer(1), "ip", ba.clone());
|
b.set_direct(peer(1), "ip", ba.clone());
|
||||||
// Deliberately inconsistent snapshots while updates are in flight.
|
// Deliberately inconsistent snapshots while updates are in flight.
|
||||||
topology(&a, "ip", &[(2, &[4])], &[1, 2, 3, 4]);
|
topology(&a, &[(2, &[4])], &[1, 2, 3, 4]);
|
||||||
topology(&b, "ip", &[(1, &[4])], &[1, 2, 3, 4]);
|
topology(&b, &[(1, &[4])], &[1, 2, 3, 4]);
|
||||||
let ap = a.link(peer(4), "ip").plane.clone();
|
let ap = a.link(peer(4), "ip").plane.clone();
|
||||||
let bp = b.link(peer(4), "ip").plane.clone();
|
let bp = b.link(peer(4), "ip").plane.clone();
|
||||||
let mut frame = envelope::encode(id(3), id(4), 7, b"transit");
|
let mut frame = envelope::encode(id(3), id(4), 7, tag(), b"transit");
|
||||||
for turn in 0..ROUTING_HOP_LIMIT {
|
for turn in 0..ROUTING_HOP_LIMIT {
|
||||||
let (plane, incoming, wire) = if turn % 2 == 0 {
|
let (plane, incoming, wire) = if turn % 2 == 0 {
|
||||||
(&ap, id(2), &ab)
|
(&ap, id(2), &ab)
|
||||||
@@ -253,7 +382,7 @@ async fn forwarding_benchmark() {
|
|||||||
hub.set_direct(peer(3), "ip", wire.clone());
|
hub.set_direct(peer(3), "ip", wire.clone());
|
||||||
let alternate = Wire::new(5, false);
|
let alternate = Wire::new(5, false);
|
||||||
hub.set_direct(peer(5), "ip", alternate.clone());
|
hub.set_direct(peer(5), "ip", alternate.clone());
|
||||||
topology(&hub, "ip", &[(3, &[4]), (5, &[4])], &[1, 2, 3, 4, 5]);
|
topology(&hub, &[(3, &[4]), (5, &[4])], &[1, 2, 3, 4, 5]);
|
||||||
let plane = hub.link(peer(4), "ip").plane.clone();
|
let plane = hub.link(peer(4), "ip").plane.clone();
|
||||||
let source = id(1);
|
let source = id(1);
|
||||||
let destination = id(4);
|
let destination = id(4);
|
||||||
@@ -264,7 +393,9 @@ async fn forwarding_benchmark() {
|
|||||||
const BATCHES: usize = 100;
|
const BATCHES: usize = 100;
|
||||||
for _ in 0..BATCHES {
|
for _ in 0..BATCHES {
|
||||||
let frames: Vec<_> = (0..COUNT)
|
let frames: Vec<_> = (0..COUNT)
|
||||||
.map(|flow| envelope::encode(source, destination, flow as u64, &vec![42; size]))
|
.map(|flow| {
|
||||||
|
envelope::encode(source, destination, flow as u64, tag(), &vec![42; size])
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let start = std::time::Instant::now();
|
let start = std::time::Instant::now();
|
||||||
for frame in frames {
|
for frame in frames {
|
||||||
+25
-5
@@ -3,8 +3,8 @@ use super::{FlowId, PeerId};
|
|||||||
use crate::config::{MAX_DATA_DATAGRAM, ROUTING_HOP_LIMIT};
|
use crate::config::{MAX_DATA_DATAGRAM, ROUTING_HOP_LIMIT};
|
||||||
use bytes::{BufMut, Bytes, BytesMut};
|
use bytes::{BufMut, Bytes, BytesMut};
|
||||||
|
|
||||||
pub(crate) const HEADER: usize = 2 + 32 + 32 + 8;
|
pub(crate) const HEADER: usize = 2 + 32 + 32 + 8 + 8;
|
||||||
const VERSION: u8 = 1;
|
const VERSION: u8 = 2;
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub(crate) struct Header {
|
pub(crate) struct Header {
|
||||||
@@ -12,6 +12,15 @@ pub(crate) struct Header {
|
|||||||
pub destination: PeerId,
|
pub destination: PeerId,
|
||||||
pub remaining: u8,
|
pub remaining: u8,
|
||||||
pub flow: FlowId,
|
pub flow: FlowId,
|
||||||
|
/// Which end-to-end protocol the payload belongs to, whatever links carry it.
|
||||||
|
pub protocol: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A stable 64-bit tag for a protocol id (FNV-1a), the same on every member.
|
||||||
|
pub(crate) fn protocol_tag(name: &str) -> u64 {
|
||||||
|
name.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
|
||||||
|
(hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn decode(bytes: &[u8]) -> Option<Header> {
|
pub(crate) fn decode(bytes: &[u8]) -> Option<Header> {
|
||||||
@@ -28,16 +37,24 @@ pub(crate) fn decode(bytes: &[u8]) -> Option<Header> {
|
|||||||
destination: bytes[34..66].try_into().ok()?,
|
destination: bytes[34..66].try_into().ok()?,
|
||||||
remaining: bytes[1],
|
remaining: bytes[1],
|
||||||
flow: u64::from_be_bytes(bytes[66..74].try_into().ok()?),
|
flow: u64::from_be_bytes(bytes[66..74].try_into().ok()?),
|
||||||
|
protocol: u64::from_be_bytes(bytes[74..82].try_into().ok()?),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn encode(source: PeerId, destination: PeerId, flow: FlowId, payload: &[u8]) -> Bytes {
|
pub(crate) fn encode(
|
||||||
|
source: PeerId,
|
||||||
|
destination: PeerId,
|
||||||
|
flow: FlowId,
|
||||||
|
protocol: u64,
|
||||||
|
payload: &[u8],
|
||||||
|
) -> Bytes {
|
||||||
let mut bytes = BytesMut::with_capacity(HEADER + payload.len());
|
let mut bytes = BytesMut::with_capacity(HEADER + payload.len());
|
||||||
bytes.put_u8(VERSION);
|
bytes.put_u8(VERSION);
|
||||||
bytes.put_u8(ROUTING_HOP_LIMIT);
|
bytes.put_u8(ROUTING_HOP_LIMIT);
|
||||||
bytes.extend_from_slice(&source);
|
bytes.extend_from_slice(&source);
|
||||||
bytes.extend_from_slice(&destination);
|
bytes.extend_from_slice(&destination);
|
||||||
bytes.put_u64(flow);
|
bytes.put_u64(flow);
|
||||||
|
bytes.put_u64(protocol);
|
||||||
bytes.extend_from_slice(payload);
|
bytes.extend_from_slice(payload);
|
||||||
bytes.freeze()
|
bytes.freeze()
|
||||||
}
|
}
|
||||||
@@ -58,7 +75,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
#[test]
|
#[test]
|
||||||
fn transit_reuses_the_buffer_and_rejects_invalid_headers() {
|
fn transit_reuses_the_buffer_and_rejects_invalid_headers() {
|
||||||
let frame = encode([1; 32], [2; 32], 17, &[42; 1280]);
|
let frame = encode([1; 32], [2; 32], 17, protocol_tag("wg"), &[42; 1280]);
|
||||||
let address = frame.as_ptr();
|
let address = frame.as_ptr();
|
||||||
let frame = decrement(frame);
|
let frame = decrement(frame);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -66,7 +83,10 @@ mod tests {
|
|||||||
address,
|
address,
|
||||||
"no payload copy for an owned buffer"
|
"no payload copy for an owned buffer"
|
||||||
);
|
);
|
||||||
assert_eq!(decode(&frame).unwrap().remaining, ROUTING_HOP_LIMIT - 1);
|
let header = decode(&frame).unwrap();
|
||||||
|
assert_eq!(header.remaining, ROUTING_HOP_LIMIT - 1);
|
||||||
|
assert_eq!(header.protocol, protocol_tag("wg"));
|
||||||
|
assert_ne!(protocol_tag("wg"), protocol_tag("wg-quic"));
|
||||||
assert_eq!(&frame[HEADER..], &[42; 1280]);
|
assert_eq!(&frame[HEADER..], &[42; 1280]);
|
||||||
for length in 0..HEADER {
|
for length in 0..HEADER {
|
||||||
assert!(decode(&frame[..length]).is_none());
|
assert!(decode(&frame[..length]).is_none());
|
||||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,44 @@
|
|||||||
|
//! External link negotiation, deliberately separate from the IP encryption plugin.
|
||||||
|
use crate::dataplane::{PluginCapability, PluginError, ProtocolOption};
|
||||||
|
use crate::{BoxFuture, NetworkId};
|
||||||
|
use iroh::EndpointId;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
/// Capability and lifecycle of one external data carrier.
|
||||||
|
/// Only this layer sees reachability. It never receives plaintext overlay IP packets.
|
||||||
|
pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
|
||||||
|
/// External protocol identifier used in local policy and peer negotiation.
|
||||||
|
fn protocol_id(&self) -> &str;
|
||||||
|
/// Wire version, independent of software releases and the internal tunnel.
|
||||||
|
fn protocol_version(&self) -> u16;
|
||||||
|
/// Supported carrier settings.
|
||||||
|
fn options(&self) -> &'static [ProtocolOption] {
|
||||||
|
&[]
|
||||||
|
}
|
||||||
|
/// Bounded opaque reachability/negotiation capability for one network.
|
||||||
|
fn local_capability(&self, network: NetworkId)
|
||||||
|
-> Result<Option<PluginCapability>, PluginError>;
|
||||||
|
/// Installs a capability received through an authenticated membership session.
|
||||||
|
fn on_peer_capability(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: EndpointId,
|
||||||
|
capability: &PluginCapability,
|
||||||
|
) -> Result<(), PluginError>;
|
||||||
|
/// Supplies the actual owned interface name, including kernel-assigned names.
|
||||||
|
fn on_interface_ready(&self, _name: &str) {}
|
||||||
|
/// Activates this carrier for one local network.
|
||||||
|
fn on_network_activated(&self, _network: NetworkId) {}
|
||||||
|
/// Retires all negotiation and links for this member.
|
||||||
|
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId);
|
||||||
|
/// Retires this network's sockets and negotiations.
|
||||||
|
fn on_network_deactivated(&self, network: NetworkId);
|
||||||
|
/// Forgets durable carrier settings, if any.
|
||||||
|
fn on_network_forgotten(&self, _network: NetworkId) {}
|
||||||
|
/// Stops carrier tasks, with the agent enforcing a shutdown deadline.
|
||||||
|
fn shutdown(&self) -> BoxFuture<'_, ()> {
|
||||||
|
Box::pin(async {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// One shared carrier adapter.
|
||||||
|
pub type SharedCarrier = Arc<dyn DataCarrier>;
|
||||||
File renamed without changes.
@@ -0,0 +1,286 @@
|
|||||||
|
//! Authenticated probes of the actual data link, independent of control RTT.
|
||||||
|
//! Keys are negotiated privately for each physical link. No fixed wire magic.
|
||||||
|
use super::{PacketLink, SharedLink, TransportError};
|
||||||
|
use crate::{BoxFuture, NetworkId};
|
||||||
|
use bytes::Bytes;
|
||||||
|
use hmac::{Hmac, KeyInit, Mac};
|
||||||
|
use iroh::EndpointId;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::Sha256;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
use tokio::sync::{mpsc, watch};
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize, zeroize::ZeroizeOnDrop)]
|
||||||
|
pub(crate) struct Settings {
|
||||||
|
marker: [u8; 16],
|
||||||
|
key: [u8; 32],
|
||||||
|
}
|
||||||
|
impl Settings {
|
||||||
|
pub(crate) fn fresh() -> Self {
|
||||||
|
Self {
|
||||||
|
marker: rand::random(),
|
||||||
|
key: rand::random(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl std::fmt::Debug for Settings {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("HealthSettings([REDACTED])")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Samples {
|
||||||
|
pending: VecDeque<(u64, Instant)>,
|
||||||
|
recent: VecDeque<bool>,
|
||||||
|
}
|
||||||
|
impl Samples {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
pending: VecDeque::new(),
|
||||||
|
recent: VecDeque::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn sent(&mut self, seq: u64, now: Instant) {
|
||||||
|
self.pending.push_back((seq, now));
|
||||||
|
}
|
||||||
|
fn acknowledge(&mut self, seq: u64) {
|
||||||
|
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq) {
|
||||||
|
self.pending.remove(i);
|
||||||
|
self.recent.push_back(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn expire(&mut self, now: Instant) {
|
||||||
|
while self
|
||||||
|
.pending
|
||||||
|
.front()
|
||||||
|
.is_some_and(|(_, at)| now.duration_since(*at) >= Duration::from_secs(3))
|
||||||
|
{
|
||||||
|
self.pending.pop_front();
|
||||||
|
self.recent.push_back(false);
|
||||||
|
}
|
||||||
|
while self.recent.len() > 20 {
|
||||||
|
self.recent.pop_front();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn degraded(&self) -> bool {
|
||||||
|
self.recent.len() >= 15
|
||||||
|
&& self.recent.iter().filter(|ok| !**ok).count() * 100 >= self.recent.len() * 60
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// A monitored physical link. It forwards application bytes unchanged.
|
||||||
|
pub(crate) struct HealthLink {
|
||||||
|
raw: SharedLink,
|
||||||
|
settings: Mutex<Option<Settings>>,
|
||||||
|
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||||
|
stop: watch::Sender<bool>,
|
||||||
|
reason: Mutex<Option<String>>,
|
||||||
|
}
|
||||||
|
impl std::fmt::Debug for HealthLink {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("HealthLink")
|
||||||
|
.field("raw", &self.raw)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||||
|
match m.lock() {
|
||||||
|
Ok(g) => g,
|
||||||
|
Err(p) => p.into_inner(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl HealthLink {
|
||||||
|
pub(crate) fn new(raw: SharedLink, local: EndpointId, settings: Option<Settings>) -> Arc<Self> {
|
||||||
|
let (tx, rx) = mpsc::channel(64);
|
||||||
|
let (stop, _) = watch::channel(false);
|
||||||
|
let link = Arc::new(Self {
|
||||||
|
raw: raw.clone(),
|
||||||
|
settings: Mutex::new(settings),
|
||||||
|
rx: tokio::sync::Mutex::new(rx),
|
||||||
|
stop,
|
||||||
|
reason: Mutex::new(None),
|
||||||
|
});
|
||||||
|
let weak = Arc::downgrade(&link);
|
||||||
|
let mut stopped = link.stop.subscribe();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut interval = tokio::time::interval(Duration::from_secs(1));
|
||||||
|
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
let mut samples = Samples::new();
|
||||||
|
let mut sequence = rand::random::<u64>();
|
||||||
|
let mut since: Option<Instant> = None;
|
||||||
|
let mut marker = None;
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
biased;
|
||||||
|
_=stopped.changed()=>break,
|
||||||
|
_=interval.tick()=>{
|
||||||
|
let Some(link)=weak.upgrade()else{break;};let Some(settings)=lock(&link.settings).clone()else{continue;};
|
||||||
|
if marker != Some(settings.marker) { marker = Some(settings.marker); samples = Samples::new(); since = None; }
|
||||||
|
let start=*since.get_or_insert_with(Instant::now);let now=Instant::now();samples.expire(now);
|
||||||
|
if now.duration_since(start)>=Duration::from_secs(20) && samples.degraded() {
|
||||||
|
*lock(&link.reason)=Some("data delivery checks: at least 60% loss over the last 20 probes".into());break;
|
||||||
|
}
|
||||||
|
sequence=sequence.wrapping_add(1);
|
||||||
|
let size=raw.max_datagram_size();
|
||||||
|
let packet=probe(&settings,local,1,sequence,size.min(1000));
|
||||||
|
samples.sent(sequence,now);
|
||||||
|
let _=raw.send(packet);
|
||||||
|
}
|
||||||
|
packet=raw.recv()=>{
|
||||||
|
let Some(packet)=packet else{break;};let Some(link)=weak.upgrade()else{break;};
|
||||||
|
let settings=lock(&link.settings).clone();
|
||||||
|
if let Some(settings)=settings && packet.starts_with(&settings.marker) {
|
||||||
|
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
|
||||||
|
if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));}
|
||||||
|
else if kind==2 {samples.acknowledge(seq);}
|
||||||
|
}
|
||||||
|
} else {let _=tx.try_send(packet);}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw.close();
|
||||||
|
if let Some(link) = weak.upgrade() {
|
||||||
|
link.stop.send_replace(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
link
|
||||||
|
}
|
||||||
|
pub(crate) fn configure(&self, settings: Settings) {
|
||||||
|
*lock(&self.settings) = Some(settings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn probe(settings: &Settings, sender: EndpointId, kind: u8, seq: u64, size: usize) -> Bytes {
|
||||||
|
let mut bytes = vec![0; size.max(57)];
|
||||||
|
bytes[..16].copy_from_slice(&settings.marker);
|
||||||
|
bytes[16] = kind;
|
||||||
|
bytes[17..25].copy_from_slice(&seq.to_be_bytes());
|
||||||
|
rand::fill(&mut bytes[25..size.max(57) - 32]);
|
||||||
|
let tail = bytes.len() - 32;
|
||||||
|
if let Ok(mut mac) = <Hmac<Sha256> as KeyInit>::new_from_slice(&settings.key) {
|
||||||
|
mac.update(sender.as_bytes());
|
||||||
|
mac.update(&bytes[..tail]);
|
||||||
|
bytes[tail..].copy_from_slice(&mac.finalize().into_bytes());
|
||||||
|
}
|
||||||
|
Bytes::from(bytes)
|
||||||
|
}
|
||||||
|
fn verify(settings: &Settings, sender: EndpointId, bytes: &[u8]) -> Option<(u8, u64)> {
|
||||||
|
if bytes.len() < 57 || !bytes.starts_with(&settings.marker) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&settings.key).ok()?;
|
||||||
|
let tail = bytes.len() - 32;
|
||||||
|
mac.update(sender.as_bytes());
|
||||||
|
mac.update(&bytes[..tail]);
|
||||||
|
mac.verify_slice(&bytes[tail..]).ok()?;
|
||||||
|
Some((
|
||||||
|
bytes[16],
|
||||||
|
u64::from_be_bytes(bytes.get(17..25)?.try_into().ok()?),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
impl PacketLink for HealthLink {
|
||||||
|
fn network(&self) -> NetworkId {
|
||||||
|
self.raw.network()
|
||||||
|
}
|
||||||
|
fn peer(&self) -> EndpointId {
|
||||||
|
self.raw.peer()
|
||||||
|
}
|
||||||
|
fn max_datagram_size(&self) -> usize {
|
||||||
|
self.raw.max_datagram_size()
|
||||||
|
}
|
||||||
|
fn send(&self, payload: Bytes) -> Result<(), TransportError> {
|
||||||
|
if self.is_closed() {
|
||||||
|
Err(TransportError::Closed)
|
||||||
|
} else {
|
||||||
|
self.raw.send(payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn send_flow(
|
||||||
|
&self,
|
||||||
|
payload: Bytes,
|
||||||
|
flow: super::super::routing::FlowId,
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
if self.is_closed() {
|
||||||
|
Err(TransportError::Closed)
|
||||||
|
} else {
|
||||||
|
self.raw.send_flow(payload, flow)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut stop = self.stop.subscribe();
|
||||||
|
if *stop.borrow() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut rx = self.rx.lock().await;
|
||||||
|
tokio::select! {biased;_=stop.changed()=>None,packet=rx.recv()=>packet}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn closed(&self) -> BoxFuture<'_, ()> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut stop = self.stop.subscribe();
|
||||||
|
if !*stop.borrow() {
|
||||||
|
let _ = stop.changed().await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn is_closed(&self) -> bool {
|
||||||
|
*self.stop.borrow() || self.raw.is_closed()
|
||||||
|
}
|
||||||
|
fn close(&self) {
|
||||||
|
self.stop.send_replace(true);
|
||||||
|
self.raw.close();
|
||||||
|
}
|
||||||
|
fn failure_reason(&self) -> Option<String> {
|
||||||
|
lock(&self.reason)
|
||||||
|
.clone()
|
||||||
|
.or_else(|| self.raw.failure_reason())
|
||||||
|
}
|
||||||
|
fn path_description(&self) -> String {
|
||||||
|
self.raw.path_description()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for HealthLink {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.stop.send_replace(true);
|
||||||
|
self.raw.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn no_false_failure_before_window_but_persistent_loss_is_detected() {
|
||||||
|
let mut samples = Samples::new();
|
||||||
|
let now = Instant::now();
|
||||||
|
for seq in 0..20 {
|
||||||
|
samples.sent(seq, now);
|
||||||
|
if seq % 5 == 0 {
|
||||||
|
samples.acknowledge(seq);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(!samples.degraded());
|
||||||
|
samples.expire(now + Duration::from_secs(4));
|
||||||
|
assert!(samples.degraded());
|
||||||
|
for seq in 20..40 {
|
||||||
|
samples.sent(seq, now);
|
||||||
|
samples.acknowledge(seq);
|
||||||
|
}
|
||||||
|
samples.expire(now + Duration::from_secs(4));
|
||||||
|
assert!(!samples.degraded());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_forged_or_reflected_probe_cannot_claim_delivery() {
|
||||||
|
let a = crate::identity::DeviceIdentity::generate().endpoint_id();
|
||||||
|
let b = crate::identity::DeviceIdentity::generate().endpoint_id();
|
||||||
|
let settings = Settings::fresh();
|
||||||
|
let packet = probe(&settings, a, 1, 42, 1100);
|
||||||
|
assert_eq!(verify(&settings, a, &packet), Some((1, 42)));
|
||||||
|
assert!(verify(&settings, b, &packet).is_none());
|
||||||
|
let mut forged = packet.to_vec();
|
||||||
|
forged[16] = 2;
|
||||||
|
assert!(verify(&settings, a, &forged).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
+58
-1
@@ -40,6 +40,49 @@ use crate::proto::{read_frame, write_frame};
|
|||||||
use super::fragments::{self, Reassembler};
|
use super::fragments::{self, Reassembler};
|
||||||
use super::{InboundLink, PacketLink, PacketTransport, SharedLink, TransportError};
|
use super::{InboundLink, PacketLink, PacketTransport, SharedLink, TransportError};
|
||||||
|
|
||||||
|
/// QUIC carrier capability. Encryption of end-to-end IP packets is independent.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct IrohCarrier;
|
||||||
|
|
||||||
|
impl super::DataCarrier for IrohCarrier {
|
||||||
|
fn protocol_id(&self) -> &str {
|
||||||
|
"wg-quic"
|
||||||
|
}
|
||||||
|
fn protocol_version(&self) -> u16 {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
fn local_capability(
|
||||||
|
&self,
|
||||||
|
_: NetworkId,
|
||||||
|
) -> Result<Option<crate::dataplane::PluginCapability>, crate::dataplane::PluginError> {
|
||||||
|
Ok(Some(crate::dataplane::PluginCapability {
|
||||||
|
protocol: self.protocol_id().into(),
|
||||||
|
version: self.protocol_version(),
|
||||||
|
enabled: true,
|
||||||
|
data: Vec::new(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
fn on_peer_capability(
|
||||||
|
&self,
|
||||||
|
_: NetworkId,
|
||||||
|
_: EndpointId,
|
||||||
|
capability: &crate::dataplane::PluginCapability,
|
||||||
|
) -> Result<(), crate::dataplane::PluginError> {
|
||||||
|
if capability.protocol != self.protocol_id()
|
||||||
|
|| capability.version != self.protocol_version()
|
||||||
|
|| !capability.enabled
|
||||||
|
|| !capability.data.is_empty()
|
||||||
|
{
|
||||||
|
return Err(crate::dataplane::PluginError::Rejected(
|
||||||
|
"unsupported QUIC carrier capability".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn on_peer_gone(&self, _: NetworkId, _: EndpointId) {}
|
||||||
|
fn on_network_deactivated(&self, _: NetworkId) {}
|
||||||
|
}
|
||||||
|
|
||||||
/// What the iroh transport needs from the agent.
|
/// What the iroh transport needs from the agent.
|
||||||
///
|
///
|
||||||
/// Implemented by the agent, which is the only thing that knows which networks
|
/// Implemented by the agent, which is the only thing that knows which networks
|
||||||
@@ -97,6 +140,9 @@ impl IrohLink {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PacketLink for IrohLink {
|
impl PacketLink for IrohLink {
|
||||||
|
fn close(&self) {
|
||||||
|
self.conn.close(0u32.into(), b"data link retired");
|
||||||
|
}
|
||||||
fn network(&self) -> NetworkId {
|
fn network(&self) -> NetworkId {
|
||||||
self.network
|
self.network
|
||||||
}
|
}
|
||||||
@@ -187,6 +233,10 @@ impl PacketLink for IrohLink {
|
|||||||
self.conn.close_reason().is_some()
|
self.conn.close_reason().is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn failure_reason(&self) -> Option<String> {
|
||||||
|
self.conn.close_reason().map(|reason| reason.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
fn path_description(&self) -> String {
|
fn path_description(&self) -> String {
|
||||||
// Report what iroh actually knows, never a guess.
|
// Report what iroh actually knows, never a guess.
|
||||||
let snapshot = crate::net::snapshot_connection(&self.conn);
|
let snapshot = crate::net::snapshot_connection(&self.conn);
|
||||||
@@ -261,7 +311,8 @@ impl IrohTransport {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let serves = self.lookup.serves(outcome.network_id, &open.protocol).await;
|
let serves = open.protocol == "wg-quic"
|
||||||
|
&& self.lookup.serves(outcome.network_id, &open.protocol).await;
|
||||||
if open.max_datagram == 0 || conn.max_datagram_size().is_none() {
|
if open.max_datagram == 0 || conn.max_datagram_size().is_none() {
|
||||||
return Err(TransportError::Other(
|
return Err(TransportError::Other(
|
||||||
"data channel has no datagram support".into(),
|
"data channel has no datagram support".into(),
|
||||||
@@ -322,6 +373,12 @@ impl PacketTransport for IrohTransport {
|
|||||||
"data channel protocol id is out of bounds".into(),
|
"data channel protocol id is out of bounds".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
// This default must never impersonate a missing native carrier.
|
||||||
|
if protocol != "wg-quic" {
|
||||||
|
return Err(TransportError::Declined(format!(
|
||||||
|
"no native `{protocol}` data transport registered"
|
||||||
|
)));
|
||||||
|
}
|
||||||
let keys = self
|
let keys = self
|
||||||
.lookup
|
.lookup
|
||||||
.snapshot()
|
.snapshot()
|
||||||
+113
@@ -30,12 +30,17 @@
|
|||||||
//! one plugin protocol.
|
//! one plugin protocol.
|
||||||
|
|
||||||
mod fragments;
|
mod fragments;
|
||||||
|
pub(crate) mod health;
|
||||||
pub mod iroh_link;
|
pub mod iroh_link;
|
||||||
|
|
||||||
|
pub mod carrier;
|
||||||
|
pub use carrier::{DataCarrier, SharedCarrier};
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use iroh::EndpointId;
|
use iroh::EndpointId;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::BoxFuture;
|
use crate::BoxFuture;
|
||||||
use crate::identity::NetworkId;
|
use crate::identity::NetworkId;
|
||||||
@@ -112,6 +117,14 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
|
|||||||
/// keeping a task parked on [`PacketLink::closed`].
|
/// keeping a task parked on [`PacketLink::closed`].
|
||||||
fn is_closed(&self) -> bool;
|
fn is_closed(&self) -> bool;
|
||||||
|
|
||||||
|
/// Explicitly retires a physical link. Implementations should wake readers.
|
||||||
|
fn close(&self) {}
|
||||||
|
|
||||||
|
/// Observed reason for retiring this link, if available.
|
||||||
|
fn failure_reason(&self) -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
/// A short description of the path in use, for diagnostics.
|
/// A short description of the path in use, for diagnostics.
|
||||||
///
|
///
|
||||||
/// Reports what the transport actually knows. It must not invent a value.
|
/// Reports what the transport actually knows. It must not invent a value.
|
||||||
@@ -121,6 +134,76 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
|
|||||||
/// A shared handle to a link.
|
/// A shared handle to a link.
|
||||||
pub type SharedLink = std::sync::Arc<dyn PacketLink>;
|
pub type SharedLink = std::sync::Arc<dyn PacketLink>;
|
||||||
|
|
||||||
|
/// Maximum opaque pair-negotiation payload.
|
||||||
|
pub const MAX_TRANSPORT_PAYLOAD: usize = 4096;
|
||||||
|
|
||||||
|
/// Private transport bytes, never included in Debug output.
|
||||||
|
#[derive(Clone, PartialEq, Eq, Serialize, zeroize::ZeroizeOnDrop)]
|
||||||
|
pub struct TransportPayload(Vec<u8>);
|
||||||
|
|
||||||
|
impl<'de> Deserialize<'de> for TransportPayload {
|
||||||
|
fn deserialize<D: serde::Deserializer<'de>>(
|
||||||
|
deserializer: D,
|
||||||
|
) -> std::result::Result<Self, D::Error> {
|
||||||
|
struct Visitor;
|
||||||
|
impl<'de> serde::de::Visitor<'de> for Visitor {
|
||||||
|
type Value = TransportPayload;
|
||||||
|
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "at most {MAX_TRANSPORT_PAYLOAD} private transport bytes")
|
||||||
|
}
|
||||||
|
fn visit_seq<A: serde::de::SeqAccess<'de>>(
|
||||||
|
self,
|
||||||
|
mut sequence: A,
|
||||||
|
) -> std::result::Result<Self::Value, A::Error> {
|
||||||
|
if sequence
|
||||||
|
.size_hint()
|
||||||
|
.is_some_and(|size| size > MAX_TRANSPORT_PAYLOAD)
|
||||||
|
{
|
||||||
|
return Err(serde::de::Error::custom("transport payload too large"));
|
||||||
|
}
|
||||||
|
let mut payload = TransportPayload(Vec::with_capacity(
|
||||||
|
sequence.size_hint().unwrap_or(0).min(MAX_TRANSPORT_PAYLOAD),
|
||||||
|
));
|
||||||
|
while let Some(byte) = sequence.next_element::<u8>()? {
|
||||||
|
if payload.0.len() == MAX_TRANSPORT_PAYLOAD {
|
||||||
|
return Err(serde::de::Error::custom("transport payload too large"));
|
||||||
|
}
|
||||||
|
payload.0.push(byte);
|
||||||
|
}
|
||||||
|
Ok(payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
deserializer.deserialize_seq(Visitor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl TransportPayload {
|
||||||
|
/// Wraps bytes for one authenticated control session.
|
||||||
|
pub fn new(bytes: Vec<u8>) -> Self {
|
||||||
|
Self(bytes)
|
||||||
|
}
|
||||||
|
/// Borrows private bytes; callers must not log them.
|
||||||
|
pub fn as_bytes(&self) -> &[u8] {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl std::fmt::Debug for TransportPayload {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("TransportPayload([REDACTED])")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Private control-plane sender for transports. Contains no network secret.
|
||||||
|
pub trait ControlSender: Send + Sync + std::fmt::Debug + 'static {
|
||||||
|
/// Queues a bounded message to one authenticated member of one network.
|
||||||
|
fn send<'a>(
|
||||||
|
&'a self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: EndpointId,
|
||||||
|
protocol: &'a str,
|
||||||
|
payload: TransportPayload,
|
||||||
|
) -> BoxFuture<'a, Result<(), TransportError>>;
|
||||||
|
}
|
||||||
|
|
||||||
/// An inbound link a peer opened towards us.
|
/// An inbound link a peer opened towards us.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct InboundLink {
|
pub struct InboundLink {
|
||||||
@@ -139,6 +222,18 @@ pub struct InboundLink {
|
|||||||
/// The agent owns one of these and hands links to plugins; plugins never call
|
/// The agent owns one of these and hands links to plugins; plugins never call
|
||||||
/// it directly.
|
/// it directly.
|
||||||
pub trait PacketTransport: Send + Sync + std::fmt::Debug + 'static {
|
pub trait PacketTransport: Send + Sync + std::fmt::Debug + 'static {
|
||||||
|
/// Supplies a private sender before network activation.
|
||||||
|
fn attach_control(&self, _control: Arc<dyn ControlSender>) {}
|
||||||
|
/// Validates and queues private negotiation received from an authenticated member.
|
||||||
|
fn on_control(
|
||||||
|
&self,
|
||||||
|
_network: NetworkId,
|
||||||
|
_peer: EndpointId,
|
||||||
|
_protocol: &str,
|
||||||
|
_payload: &[u8],
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
Err(TransportError::Declined(self.name().into()))
|
||||||
|
}
|
||||||
/// A short name used in diagnostics.
|
/// A short name used in diagnostics.
|
||||||
fn name(&self) -> &str;
|
fn name(&self) -> &str;
|
||||||
|
|
||||||
@@ -184,6 +279,24 @@ impl MultiPacketTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PacketTransport for MultiPacketTransport {
|
impl PacketTransport for MultiPacketTransport {
|
||||||
|
fn attach_control(&self, control: Arc<dyn ControlSender>) {
|
||||||
|
self.default.attach_control(control.clone());
|
||||||
|
for transport in self.by_protocol.values() {
|
||||||
|
transport.attach_control(control.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn on_control(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: EndpointId,
|
||||||
|
protocol: &str,
|
||||||
|
payload: &[u8],
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
match self.by_protocol.get(protocol) {
|
||||||
|
Some(transport) => transport.on_control(network, peer, protocol, payload),
|
||||||
|
None => Err(TransportError::Declined(protocol.into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"multi"
|
"multi"
|
||||||
}
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -59,6 +59,56 @@ pub fn listen_plan(port: u16) -> ListenPlan {
|
|||||||
pub use server::{DnsServer, SharedZone};
|
pub use server::{DnsServer, SharedZone};
|
||||||
pub use zone::{Answer, Query, Zone, ZoneError, ZoneName, Zones};
|
pub use zone::{Answer, Query, Zone, ZoneError, ZoneName, Zones};
|
||||||
|
|
||||||
|
/// Authoritative zones and the publication diagnostics for one agent snapshot.
|
||||||
|
pub struct RosterZones {
|
||||||
|
/// Member and service records indexed by zone.
|
||||||
|
pub zones: Zones,
|
||||||
|
/// Zone names in configured-network order.
|
||||||
|
pub labels: Vec<String>,
|
||||||
|
/// Unusable or potentially conflicting zone names.
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RosterZones {
|
||||||
|
/// Build the desktop and mobile DNS view from the same signed state.
|
||||||
|
pub fn from_networks(networks: &[crate::NetworkStatus]) -> Self {
|
||||||
|
let mut zones = Vec::new();
|
||||||
|
let mut labels = Vec::new();
|
||||||
|
let mut warnings = Vec::new();
|
||||||
|
for network in networks {
|
||||||
|
let zone = match ZoneName::new(network.name.as_str()) {
|
||||||
|
Ok(zone) => zone,
|
||||||
|
Err(err) => {
|
||||||
|
warnings.push(format!(
|
||||||
|
"`{}` cannot be a zone, so its members have no names: {err}",
|
||||||
|
network.name
|
||||||
|
));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(warning) = zone.collision() {
|
||||||
|
warnings.push(warning);
|
||||||
|
}
|
||||||
|
labels.push(zone.as_str().to_string());
|
||||||
|
let members = network
|
||||||
|
.members
|
||||||
|
.iter()
|
||||||
|
.filter_map(|member| Some((member.hostname.clone()?, member.overlay_address_v4?)));
|
||||||
|
let services = network
|
||||||
|
.vips
|
||||||
|
.iter()
|
||||||
|
.filter(|vip| vip.error.is_none())
|
||||||
|
.filter_map(|vip| Some((vip.config.name.clone(), vip.address?)));
|
||||||
|
zones.push(Zone::new(zone, members.chain(services)).with_reverse_range(network.range));
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
zones: Zones::new(zones),
|
||||||
|
labels,
|
||||||
|
warnings,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -81,7 +81,22 @@ impl SharedZone {
|
|||||||
/// server should reply to, and replying anyway would make this a useful
|
/// server should reply to, and replying anyway would make this a useful
|
||||||
/// amplifier for somebody spoofing a source address.
|
/// amplifier for somebody spoofing a source address.
|
||||||
pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
||||||
let packet = simple_dns::Packet::parse(query).ok()?;
|
match resolve(zones, query)? {
|
||||||
|
Resolution::Local(reply) | Resolution::Outside(reply) => Some(reply),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An authoritative decision for a host resolver that also handles external domains.
|
||||||
|
pub enum Resolution {
|
||||||
|
/// Answer locally, including authoritative denials and protocol errors.
|
||||||
|
Local(Vec<u8>),
|
||||||
|
/// A well-formed question outside all mesh zones, with the authoritative server's REFUSED reply.
|
||||||
|
Outside(Vec<u8>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Distinguish an external question from an unknown name inside a mesh zone.
|
||||||
|
pub fn resolve(zones: &Zones, query: &[u8]) -> Option<Resolution> {
|
||||||
|
let packet = parse_message(query)?;
|
||||||
if packet.has_flags(PacketFlag::RESPONSE) {
|
if packet.has_flags(PacketFlag::RESPONSE) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -95,18 +110,18 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
|||||||
|
|
||||||
if packet.opcode() != simple_dns::OPCODE::StandardQuery {
|
if packet.opcode() != simple_dns::OPCODE::StandardQuery {
|
||||||
*reply.rcode_mut() = RCODE::NotImplemented;
|
*reply.rcode_mut() = RCODE::NotImplemented;
|
||||||
return reply.build_bytes_vec().ok();
|
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exactly one question. Zero is nothing to answer; more than one has no
|
// Exactly one question. Zero is nothing to answer; more than one has no
|
||||||
// agreed meaning and every real server rejects it.
|
// agreed meaning and every real server rejects it.
|
||||||
let [question] = packet.questions.as_slice() else {
|
let [question] = packet.questions.as_slice() else {
|
||||||
*reply.rcode_mut() = RCODE::FormatError;
|
*reply.rcode_mut() = RCODE::FormatError;
|
||||||
return reply.build_bytes_vec().ok();
|
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||||
};
|
};
|
||||||
if !matches!(question.qclass, QCLASS::CLASS(simple_dns::CLASS::IN)) {
|
if !matches!(question.qclass, QCLASS::CLASS(simple_dns::CLASS::IN)) {
|
||||||
*reply.rcode_mut() = RCODE::Refused;
|
*reply.rcode_mut() = RCODE::Refused;
|
||||||
return reply.build_bytes_vec().ok();
|
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||||
}
|
}
|
||||||
|
|
||||||
let qname = question.qname.to_string();
|
let qname = question.qname.to_string();
|
||||||
@@ -117,7 +132,10 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
|||||||
None => {
|
None => {
|
||||||
reply.questions.push(question.clone());
|
reply.questions.push(question.clone());
|
||||||
*reply.rcode_mut() = RCODE::Refused;
|
*reply.rcode_mut() = RCODE::Refused;
|
||||||
return reply.build_bytes_vec_compressed().ok();
|
return reply
|
||||||
|
.build_bytes_vec_compressed()
|
||||||
|
.ok()
|
||||||
|
.map(Resolution::Outside);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
reply.questions.push(question.clone());
|
reply.questions.push(question.clone());
|
||||||
@@ -163,7 +181,22 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reply.build_bytes_vec_compressed().ok()
|
reply
|
||||||
|
.build_bytes_vec_compressed()
|
||||||
|
.ok()
|
||||||
|
.map(Resolution::Local)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse a DNS message only after bounding its section allocations against the bytes received.
|
||||||
|
pub fn parse_message(wire: &[u8]) -> Option<simple_dns::Packet<'_>> {
|
||||||
|
let header = wire.get(..12)?;
|
||||||
|
let counts = |at: usize| usize::from(u16::from_be_bytes([header[at], header[at + 1]]));
|
||||||
|
// Even a root question needs five bytes. An empty root resource record needs eleven.
|
||||||
|
let minimum = 12 + counts(4) * 5 + (counts(6) + counts(8) + counts(10)) * 11;
|
||||||
|
if wire.len() < minimum || wire.len() > usize::from(u16::MAX) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
simple_dns::Packet::parse(wire).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The zone's start of authority.
|
/// The zone's start of authority.
|
||||||
@@ -202,8 +235,7 @@ fn query_kind(qtype: QTYPE) -> Query {
|
|||||||
|
|
||||||
/// Whether the client offered EDNS, and so how large an answer it will take.
|
/// Whether the client offered EDNS, and so how large an answer it will take.
|
||||||
fn udp_limit(query: &[u8]) -> usize {
|
fn udp_limit(query: &[u8]) -> usize {
|
||||||
simple_dns::Packet::parse(query)
|
parse_message(query)
|
||||||
.ok()
|
|
||||||
.and_then(|packet| packet.opt().map(|opt| opt.udp_packet_size as usize))
|
.and_then(|packet| packet.opt().map(|opt| opt.udp_packet_size as usize))
|
||||||
.unwrap_or(CLASSIC_UDP_LIMIT as u16 as usize)
|
.unwrap_or(CLASSIC_UDP_LIMIT as u16 as usize)
|
||||||
.clamp(CLASSIC_UDP_LIMIT, MAX_MESSAGE_LEN)
|
.clamp(CLASSIC_UDP_LIMIT, MAX_MESSAGE_LEN)
|
||||||
@@ -214,20 +246,19 @@ fn udp_limit(query: &[u8]) -> usize {
|
|||||||
/// The records are dropped and the truncated bit set, which tells a resolver
|
/// The records are dropped and the truncated bit set, which tells a resolver
|
||||||
/// to ask again over TCP. Sending a reply it cannot reassemble would just
|
/// to ask again over TCP. Sending a reply it cannot reassemble would just
|
||||||
/// look like packet loss.
|
/// look like packet loss.
|
||||||
fn truncate_for_udp(query: &[u8], reply: Vec<u8>) -> Vec<u8> {
|
pub fn truncate_for_udp(query: &[u8], reply: Vec<u8>, payload_limit: usize) -> Vec<u8> {
|
||||||
let limit = udp_limit(query);
|
let limit = udp_limit(query).min(payload_limit);
|
||||||
if reply.len() <= limit {
|
if reply.len() <= limit {
|
||||||
return reply;
|
return reply;
|
||||||
}
|
}
|
||||||
let Ok(parsed) = simple_dns::Packet::parse(&reply) else {
|
let Some(mut short) = parse_message(&reply) else {
|
||||||
return reply;
|
return reply;
|
||||||
};
|
};
|
||||||
let mut short = simple_dns::Packet::new_reply(parsed.id());
|
short.set_flags(PacketFlag::TRUNCATION);
|
||||||
short.set_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER);
|
short.answers.clear();
|
||||||
*short.rcode_mut() = parsed.rcode();
|
short.name_servers.clear();
|
||||||
for question in &parsed.questions {
|
short.additional_records.clear();
|
||||||
short.questions.push(question.clone());
|
*short.opt_mut() = None;
|
||||||
}
|
|
||||||
short.build_bytes_vec().unwrap_or(reply)
|
short.build_bytes_vec().unwrap_or(reply)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,7 +295,7 @@ impl DnsServer {
|
|||||||
let Some(reply) = respond(&udp_zone.get(), query) else {
|
let Some(reply) = respond(&udp_zone.get(), query) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let reply = truncate_for_udp(query, reply);
|
let reply = truncate_for_udp(query, reply, MAX_MESSAGE_LEN);
|
||||||
if let Err(err) = udp.send_to(&reply, from).await {
|
if let Err(err) = udp.send_to(&reply, from).await {
|
||||||
tracing::debug!(%err, "dns udp reply failed");
|
tracing::debug!(%err, "dns udp reply failed");
|
||||||
}
|
}
|
||||||
@@ -494,7 +525,7 @@ mod tests {
|
|||||||
"the test needs a big answer"
|
"the test needs a big answer"
|
||||||
);
|
);
|
||||||
|
|
||||||
let short = truncate_for_udp(&query, full);
|
let short = truncate_for_udp(&query, full, MAX_MESSAGE_LEN);
|
||||||
assert!(short.len() <= CLASSIC_UDP_LIMIT);
|
assert!(short.len() <= CLASSIC_UDP_LIMIT);
|
||||||
let parsed = simple_dns::Packet::parse(&short).unwrap();
|
let parsed = simple_dns::Packet::parse(&short).unwrap();
|
||||||
assert!(parsed.has_flags(PacketFlag::TRUNCATION));
|
assert!(parsed.has_flags(PacketFlag::TRUNCATION));
|
||||||
@@ -208,6 +208,7 @@ pub enum Answer {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Zone {
|
pub struct Zone {
|
||||||
origin: ZoneName,
|
origin: ZoneName,
|
||||||
|
reverse_range: Option<crate::state::Ipv4Range>,
|
||||||
/// Name relative to the origin, to the addresses it answers to.
|
/// Name relative to the origin, to the addresses it answers to.
|
||||||
hosts: BTreeMap<String, Vec<Ipv4Addr>>,
|
hosts: BTreeMap<String, Vec<Ipv4Addr>>,
|
||||||
/// Address to the name that holds it.
|
/// Address to the name that holds it.
|
||||||
@@ -246,12 +247,23 @@ impl Zone {
|
|||||||
let serial = content_serial(&hosts);
|
let serial = content_serial(&hosts);
|
||||||
Self {
|
Self {
|
||||||
origin,
|
origin,
|
||||||
|
// Standalone authoritative zones retain their original broad PTR view.
|
||||||
|
// Agent snapshots scope the authority to each network's actual range.
|
||||||
|
reverse_range: Some(crate::state::Ipv4Range {
|
||||||
|
base: Ipv4Addr::UNSPECIFIED,
|
||||||
|
prefix_len: 0,
|
||||||
|
}),
|
||||||
hosts,
|
hosts,
|
||||||
names,
|
names,
|
||||||
serial,
|
serial,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn with_reverse_range(mut self, range: Option<crate::state::Ipv4Range>) -> Self {
|
||||||
|
self.reverse_range = range;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// The zone's origin.
|
/// The zone's origin.
|
||||||
pub fn origin(&self) -> &ZoneName {
|
pub fn origin(&self) -> &ZoneName {
|
||||||
&self.origin
|
&self.origin
|
||||||
@@ -300,6 +312,12 @@ impl Zone {
|
|||||||
/// Answers one question.
|
/// Answers one question.
|
||||||
pub fn lookup(&self, qname: &str, query: Query) -> Answer {
|
pub fn lookup(&self, qname: &str, query: Query) -> Answer {
|
||||||
if let Some(address) = reverse_address(qname) {
|
if let Some(address) = reverse_address(qname) {
|
||||||
|
if !self
|
||||||
|
.reverse_range
|
||||||
|
.is_some_and(|range| range.contains(address))
|
||||||
|
{
|
||||||
|
return Answer::NotOurs;
|
||||||
|
}
|
||||||
return match self.names.get(&address) {
|
return match self.names.get(&address) {
|
||||||
Some(name) if query == Query::Ptr => {
|
Some(name) if query == Query::Ptr => {
|
||||||
Answer::Name(format!("{name}.{}", self.origin.as_str()))
|
Answer::Name(format!("{name}.{}", self.origin.as_str()))
|
||||||
@@ -15,6 +15,12 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
|
|||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
|
/// A node-history cleanup is unsafe, stale or cannot be performed.
|
||||||
|
#[error("cannot forget node: {0}")]
|
||||||
|
ForgetNode(String),
|
||||||
|
/// An ordered local data-plane protocol selection is invalid.
|
||||||
|
#[error("invalid protocol selection: {0}")]
|
||||||
|
InvalidProtocols(String),
|
||||||
/// The supplied network name does not satisfy the documented rules.
|
/// The supplied network name does not satisfy the documented rules.
|
||||||
#[error("invalid network name: {0}")]
|
#[error("invalid network name: {0}")]
|
||||||
InvalidNetworkName(&'static str),
|
InvalidNetworkName(&'static str),
|
||||||
@@ -97,6 +103,19 @@ pub enum Error {
|
|||||||
#[error("network {0} is not configured")]
|
#[error("network {0} is not configured")]
|
||||||
NetworkUnknown(NetworkId),
|
NetworkUnknown(NetworkId),
|
||||||
|
|
||||||
|
/// An overlay range overlaps networks already active on this agent.
|
||||||
|
#[error(
|
||||||
|
"network {network} cannot start: {range} overlaps active networks {conflicts:?}; switch to it to suspend those networks"
|
||||||
|
)]
|
||||||
|
NetworkRangeConflict {
|
||||||
|
/// Network that could not start.
|
||||||
|
network: NetworkId,
|
||||||
|
/// Its agreed or proposed range.
|
||||||
|
range: crate::state::Ipv4Range,
|
||||||
|
/// Active networks that must be suspended first.
|
||||||
|
conflicts: Vec<NetworkId>,
|
||||||
|
},
|
||||||
|
|
||||||
/// No session with that peer exists in the given network.
|
/// No session with that peer exists in the given network.
|
||||||
#[error("no authenticated session with peer {peer} in network {network}")]
|
#[error("no authenticated session with peer {peer} in network {network}")]
|
||||||
NoSuchPeer {
|
NoSuchPeer {
|
||||||
@@ -120,6 +139,13 @@ pub enum Error {
|
|||||||
what: String,
|
what: String,
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/// The request is understood and cannot be done as things stand.
|
||||||
|
#[error("{reason}")]
|
||||||
|
Rejected {
|
||||||
|
/// Why, phrased so the message stands on its own.
|
||||||
|
reason: String,
|
||||||
|
},
|
||||||
|
|
||||||
/// Discovery backend failure. Never fatal for the agent.
|
/// Discovery backend failure. Never fatal for the agent.
|
||||||
#[error("discovery error: {0}")]
|
#[error("discovery error: {0}")]
|
||||||
Discovery(String),
|
Discovery(String),
|
||||||
File renamed without changes.
File renamed without changes.
@@ -44,6 +44,21 @@ use windows as transport;
|
|||||||
#[cfg(any(unix, windows))]
|
#[cfg(any(unix, windows))]
|
||||||
pub use transport::ControlSocket;
|
pub use transport::ControlSocket;
|
||||||
|
|
||||||
|
/// Who may open the local control socket.
|
||||||
|
///
|
||||||
|
/// The default is owner-only. A system service shares its socket with a GUI or
|
||||||
|
/// CLI running as another user by granting a group; the agent sets that on the
|
||||||
|
/// socket when it binds it, so the access is correct from creation rather than
|
||||||
|
/// patched afterwards.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum ControlSocketAccess {
|
||||||
|
/// Owner only — mode `0600`. The per-user agent's default.
|
||||||
|
Private,
|
||||||
|
/// The owner and members of this group — the socket's group is set to this
|
||||||
|
/// gid and the mode to `0660`. The caller resolves a group name to its gid.
|
||||||
|
Group(u32),
|
||||||
|
}
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -58,6 +73,31 @@ use crate::error::{Error, Result};
|
|||||||
/// Largest accepted local control message.
|
/// Largest accepted local control message.
|
||||||
pub const MAX_MESSAGE_LEN: usize = 1024 * 1024;
|
pub const MAX_MESSAGE_LEN: usize = 1024 * 1024;
|
||||||
|
|
||||||
|
/// A string the control protocol must carry but that must never appear in a
|
||||||
|
/// log: it serialises transparently (the text crosses the socket intact) but
|
||||||
|
/// its `Debug` is redacted. Used for a network secret handed back to a local
|
||||||
|
/// client that asked to copy it.
|
||||||
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct RedactedText(String);
|
||||||
|
|
||||||
|
impl RedactedText {
|
||||||
|
/// Wraps a string.
|
||||||
|
pub fn new(text: impl Into<String>) -> Self {
|
||||||
|
Self(text.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unwraps to the plain string.
|
||||||
|
pub fn into_string(self) -> String {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for RedactedText {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("<redacted>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Where the control socket for a state directory lives.
|
/// Where the control socket for a state directory lives.
|
||||||
///
|
///
|
||||||
/// A Unix socket path is limited to around 100 bytes, which a state directory
|
/// A Unix socket path is limited to around 100 bytes, which a state directory
|
||||||
@@ -108,10 +148,17 @@ pub fn default_control_socket_path() -> PathBuf {
|
|||||||
}
|
}
|
||||||
#[cfg(all(unix, not(target_os = "macos")))]
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
{
|
{
|
||||||
|
// Prefer a running system service's socket when it is present, so a
|
||||||
|
// GUI or CLI reaches the packaged daemon with no configuration; fall
|
||||||
|
// back to the per-user location otherwise.
|
||||||
|
let system = PathBuf::from("/run/tsunagi/agent.sock");
|
||||||
|
if system.exists() {
|
||||||
|
return system;
|
||||||
|
}
|
||||||
if let Ok(paths) = crate::config::StoragePaths::user_default() {
|
if let Ok(paths) = crate::config::StoragePaths::user_default() {
|
||||||
control_socket_path(&paths.state_dir)
|
control_socket_path(&paths.state_dir)
|
||||||
} else {
|
} else {
|
||||||
PathBuf::from("/run/tsunagi/agent.sock")
|
system
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,6 +171,33 @@ pub fn default_control_socket_path() -> PathBuf {
|
|||||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum Request {
|
pub enum Request {
|
||||||
|
/// Save a complete version-checked service draft or its deletion.
|
||||||
|
SaveVip {
|
||||||
|
/// Exact network id.
|
||||||
|
network_id: String,
|
||||||
|
/// Entire desired configuration.
|
||||||
|
config: crate::vip::VipConfig,
|
||||||
|
/// Revision originally displayed; absent for creation.
|
||||||
|
expected: Option<String>,
|
||||||
|
/// Remove the service permanently.
|
||||||
|
delete: bool,
|
||||||
|
},
|
||||||
|
/// Retire the selected offline member's observed claim.
|
||||||
|
ForgetNode {
|
||||||
|
/// Exact public network id.
|
||||||
|
network_id: String,
|
||||||
|
/// Exact device identity selected by the client.
|
||||||
|
peer: String,
|
||||||
|
/// Claim version displayed when the user selected the node.
|
||||||
|
expected_version: u64,
|
||||||
|
},
|
||||||
|
/// Replace one network's ordered local data-plane selection.
|
||||||
|
SetProtocols {
|
||||||
|
/// Public network identifier.
|
||||||
|
network_id: String,
|
||||||
|
/// Protocol names, best first; empty selects control only.
|
||||||
|
protocols: Vec<String>,
|
||||||
|
},
|
||||||
/// Report what the agent is doing.
|
/// Report what the agent is doing.
|
||||||
Status,
|
Status,
|
||||||
/// Set local broadcast participation in one configured network.
|
/// Set local broadcast participation in one configured network.
|
||||||
@@ -167,7 +241,7 @@ pub enum Request {
|
|||||||
///
|
///
|
||||||
/// Asked of the running agent because that is the only way to add a
|
/// Asked of the running agent because that is the only way to add a
|
||||||
/// network to an agent that is already up: the state directory belongs
|
/// network to an agent that is already up: the state directory belongs
|
||||||
/// to one live agent, so a second `tsunagi up` cannot.
|
/// to one live agent, so a second `tsng up` cannot.
|
||||||
Join {
|
Join {
|
||||||
/// The network name.
|
/// The network name.
|
||||||
name: String,
|
name: String,
|
||||||
@@ -180,11 +254,52 @@ pub enum Request {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
broadcast: Option<bool>,
|
broadcast: Option<bool>,
|
||||||
},
|
},
|
||||||
|
/// Ask for a configured network's shared secret, in its `tsn1…` text form,
|
||||||
|
/// so a local GUI or script can copy it to re-share. The reply travels only
|
||||||
|
/// over the owner/group socket and the secret is never logged.
|
||||||
|
Secret {
|
||||||
|
/// Which network, by the id text `status` prints.
|
||||||
|
network_id: String,
|
||||||
|
},
|
||||||
|
/// Offer this agent as an exit node in one network, or stop. Off unless
|
||||||
|
/// asked.
|
||||||
|
SetExitOffer {
|
||||||
|
/// Public network identifier.
|
||||||
|
network_id: String,
|
||||||
|
/// Whether members may send their internet traffic through this agent.
|
||||||
|
enabled: bool,
|
||||||
|
},
|
||||||
|
/// Send all this device's internet traffic through a member of one
|
||||||
|
/// network, or back the ordinary way.
|
||||||
|
SetExitNode {
|
||||||
|
/// Public network identifier.
|
||||||
|
network_id: String,
|
||||||
|
/// The member's endpoint id, or `None` to stop using an exit node.
|
||||||
|
peer: Option<String>,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for Request {
|
impl std::fmt::Debug for Request {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
|
Request::SaveVip {
|
||||||
|
network_id, config, ..
|
||||||
|
} => write!(f, "SaveVip {{ {network_id}, {} }}", config.id),
|
||||||
|
Request::ForgetNode {
|
||||||
|
network_id,
|
||||||
|
peer,
|
||||||
|
expected_version,
|
||||||
|
} => write!(
|
||||||
|
f,
|
||||||
|
"ForgetNode {{ {network_id}, peer: {peer}, version: {expected_version} }}"
|
||||||
|
),
|
||||||
|
Request::SetProtocols {
|
||||||
|
network_id,
|
||||||
|
protocols,
|
||||||
|
} => write!(
|
||||||
|
f,
|
||||||
|
"SetProtocols {{ {network_id}, protocols: {protocols:?} }}"
|
||||||
|
),
|
||||||
Request::Status => f.write_str("Status"),
|
Request::Status => f.write_str("Status"),
|
||||||
Request::SetBroadcast {
|
Request::SetBroadcast {
|
||||||
network_id,
|
network_id,
|
||||||
@@ -200,6 +315,14 @@ impl std::fmt::Debug for Request {
|
|||||||
write!(f, "Dns {{ enable: {enable}, port: {port:?} }}")
|
write!(f, "Dns {{ enable: {enable}, port: {port:?} }}")
|
||||||
}
|
}
|
||||||
Request::Join { name, .. } => write!(f, "Join {{ name: {name}, secret: <redacted> }}"),
|
Request::Join { name, .. } => write!(f, "Join {{ name: {name}, secret: <redacted> }}"),
|
||||||
|
Request::Secret { network_id } => write!(f, "Secret {{ {network_id} }}"),
|
||||||
|
Request::SetExitOffer {
|
||||||
|
network_id,
|
||||||
|
enabled,
|
||||||
|
} => write!(f, "SetExitOffer {{ {network_id}, enabled: {enabled} }}"),
|
||||||
|
Request::SetExitNode { network_id, peer } => {
|
||||||
|
write!(f, "SetExitNode {{ {network_id}, peer: {peer:?} }}")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,6 +331,12 @@ impl std::fmt::Debug for Request {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum Response {
|
pub enum Response {
|
||||||
|
/// Accepted configuration with fresh local routing observations.
|
||||||
|
Vips(Vec<crate::vip::VipStatus>),
|
||||||
|
/// An observed offline claim was durably retired.
|
||||||
|
NodeForgotten(ForgottenNodeReport),
|
||||||
|
/// Accepted ordered protocol selection.
|
||||||
|
Protocols(Vec<String>),
|
||||||
/// A status report.
|
/// A status report.
|
||||||
Status(Box<StatusReport>),
|
Status(Box<StatusReport>),
|
||||||
/// Accepted local broadcast participation.
|
/// Accepted local broadcast participation.
|
||||||
@@ -224,10 +353,202 @@ pub enum Response {
|
|||||||
///
|
///
|
||||||
/// `None` means it is not serving at all.
|
/// `None` means it is not serving at all.
|
||||||
Dns(Option<DnsReport>),
|
Dns(Option<DnsReport>),
|
||||||
|
/// A network's shared secret, redacted in `Debug`.
|
||||||
|
Secret(RedactedText),
|
||||||
|
/// Whether this agent now offers itself as an exit node.
|
||||||
|
ExitOffer(bool),
|
||||||
|
/// The member this device now sends its internet traffic through.
|
||||||
|
ExitNode(Option<String>),
|
||||||
/// The request could not be served.
|
/// The request could not be served.
|
||||||
Error(String),
|
Error(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The durable result of an offline-node cleanup.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ForgottenNodeReport {
|
||||||
|
/// Selected device identity.
|
||||||
|
pub peer: String,
|
||||||
|
/// The retired claim version, not a future-version ban.
|
||||||
|
pub record_version: u64,
|
||||||
|
/// Peers to which cleanup was immediately queued.
|
||||||
|
pub peers_told: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves a whole VIP draft through the running agent.
|
||||||
|
pub async fn save_vip(
|
||||||
|
socket: &Path,
|
||||||
|
network_id: &str,
|
||||||
|
config: crate::vip::VipConfig,
|
||||||
|
expected: Option<String>,
|
||||||
|
delete: bool,
|
||||||
|
) -> Result<Vec<crate::vip::VipStatus>> {
|
||||||
|
match exchange(
|
||||||
|
socket,
|
||||||
|
&Request::SaveVip {
|
||||||
|
network_id: network_id.into(),
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
},
|
||||||
|
EXCHANGE_TIMEOUT,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
Response::Vips(vips) => Ok(vips),
|
||||||
|
Response::Error(reason) => Err(Error::Rejected { reason }),
|
||||||
|
_ => Err(Error::Rejected {
|
||||||
|
reason: "unexpected VIP response".into(),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Resolves a service by exact name, full id or unique id prefix.
|
||||||
|
pub fn resolve_vip<'a>(
|
||||||
|
network: &'a NetworkReport,
|
||||||
|
selector: &str,
|
||||||
|
) -> std::result::Result<&'a crate::vip::VipStatus, String> {
|
||||||
|
let matches: Vec<_> = network
|
||||||
|
.vips
|
||||||
|
.iter()
|
||||||
|
.filter(|v| v.config.name == selector || v.config.id.starts_with(selector))
|
||||||
|
.collect();
|
||||||
|
match matches.as_slice() {
|
||||||
|
[vip] => Ok(vip),
|
||||||
|
[] => Err(format!("no VIP matches `{selector}`")),
|
||||||
|
_ => Err(format!(
|
||||||
|
"ambiguous VIP `{selector}`: {}",
|
||||||
|
matches
|
||||||
|
.iter()
|
||||||
|
.map(|v| format!("{} ({})", v.config.name, v.config.id))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves a node by exact hostname, full id, unique id prefix or overlay IPv4.
|
||||||
|
/// Ambiguity is reported with names and full ids and never guessed.
|
||||||
|
pub fn resolve_node<'a>(
|
||||||
|
network: &'a NetworkReport,
|
||||||
|
selector: &str,
|
||||||
|
) -> std::result::Result<&'a MemberReport, String> {
|
||||||
|
let selector = selector.trim();
|
||||||
|
if selector.is_empty() {
|
||||||
|
return Err("select a node by name, id or IPv4 address".into());
|
||||||
|
}
|
||||||
|
if let Some(member) = network.members.iter().find(|m| m.endpoint_id == selector) {
|
||||||
|
return Ok(member);
|
||||||
|
}
|
||||||
|
let prefix = selector.trim_end_matches('…');
|
||||||
|
let matches: Vec<_> = network
|
||||||
|
.members
|
||||||
|
.iter()
|
||||||
|
.filter(|m| {
|
||||||
|
m.hostname.as_deref() == Some(selector)
|
||||||
|
|| m.overlay_address_v4.as_deref() == Some(selector)
|
||||||
|
|| (!prefix.is_empty() && m.endpoint_id.starts_with(prefix))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
match matches.as_slice() {
|
||||||
|
[one] => Ok(one),
|
||||||
|
[] => Err(format!(
|
||||||
|
"no signed node matches `{selector}` in `{}`",
|
||||||
|
network.name
|
||||||
|
)),
|
||||||
|
many => Err(format!(
|
||||||
|
"`{selector}` is ambiguous; use a full id or unique id prefix:\n{}",
|
||||||
|
many.iter()
|
||||||
|
.map(|m| format!(
|
||||||
|
" {} {} {}",
|
||||||
|
m.hostname.as_deref().unwrap_or("unnamed"),
|
||||||
|
m.endpoint_id,
|
||||||
|
m.overlay_address_v4.as_deref().unwrap_or("no IPv4")
|
||||||
|
))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retires an exact selected claim; an online or changed target is rejected.
|
||||||
|
pub async fn forget_node(
|
||||||
|
socket: &Path,
|
||||||
|
network: &str,
|
||||||
|
peer: &str,
|
||||||
|
expected_version: u64,
|
||||||
|
) -> Result<ForgottenNodeReport> {
|
||||||
|
let request = Request::ForgetNode {
|
||||||
|
network_id: network.into(),
|
||||||
|
peer: peer.into(),
|
||||||
|
expected_version,
|
||||||
|
};
|
||||||
|
match exchange(socket, &request, EXCHANGE_TIMEOUT).await? {
|
||||||
|
Response::NodeForgotten(report) => Ok(report),
|
||||||
|
Response::Error(reason) => Err(Error::ForgetNode(reason)),
|
||||||
|
other => Err(Error::Storage(format!("unexpected response: {other:?}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod node_selector_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exact_names_addresses_and_unique_prefixes_select_the_same_signed_node() {
|
||||||
|
let node = MemberReport {
|
||||||
|
endpoint_id: "abcdef01".into(),
|
||||||
|
hostname: Some("laptop".into()),
|
||||||
|
overlay_address_v4: Some("10.2.0.3".into()),
|
||||||
|
record_version: 42,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let network = NetworkReport {
|
||||||
|
name: "home".into(),
|
||||||
|
members: vec![node.clone()],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
for selector in ["laptop", "10.2.0.3", "abcdef01", "abc…"] {
|
||||||
|
assert_eq!(resolve_node(&network, selector), Ok(&node));
|
||||||
|
}
|
||||||
|
for selector in ["", "LAPTOP", "missing"] {
|
||||||
|
assert!(resolve_node(&network, selector).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn collisions_between_names_addresses_and_prefixes_require_an_explicit_identity() {
|
||||||
|
let first = MemberReport {
|
||||||
|
endpoint_id: "abcdef01".into(),
|
||||||
|
hostname: Some("duplicate".into()),
|
||||||
|
overlay_address_v4: Some("10.2.0.3".into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let second = MemberReport {
|
||||||
|
endpoint_id: "abcdef02".into(),
|
||||||
|
hostname: Some("duplicate".into()),
|
||||||
|
overlay_address_v4: Some("10.2.0.3".into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let third = MemberReport {
|
||||||
|
endpoint_id: "12345678".into(),
|
||||||
|
hostname: Some("abc".into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let network = NetworkReport {
|
||||||
|
name: "home".into(),
|
||||||
|
members: vec![first.clone(), second, third],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
for selector in ["duplicate", "10.2.0.3", "abc"] {
|
||||||
|
let result = resolve_node(&network, selector);
|
||||||
|
assert!(result.is_err_and(|error| error.contains("ambiguous")
|
||||||
|
&& error.contains("abcdef01")
|
||||||
|
&& error.contains("abcdef02")
|
||||||
|
&& error.contains("duplicate")));
|
||||||
|
}
|
||||||
|
assert_eq!(resolve_node(&network, "abcdef01"), Ok(&first));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// What happened when a network was stopped or started.
|
/// What happened when a network was stopped or started.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct ActiveReport {
|
pub struct ActiveReport {
|
||||||
@@ -240,6 +561,9 @@ pub struct ActiveReport {
|
|||||||
/// Stopping something already stopped is not an error — it is the state
|
/// Stopping something already stopped is not an error — it is the state
|
||||||
/// asked for — but it is worth saying which happened.
|
/// asked for — but it is worth saying which happened.
|
||||||
pub changed: bool,
|
pub changed: bool,
|
||||||
|
/// Networks suspended by switching to this network.
|
||||||
|
#[serde(default)]
|
||||||
|
pub suspended: Vec<RangeConflictReport>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What happened when a network was joined.
|
/// What happened when a network was joined.
|
||||||
@@ -261,6 +585,13 @@ pub struct JoinedReport {
|
|||||||
/// Almost always a mistyped secret, and the one thing that makes two
|
/// Almost always a mistyped secret, and the one thing that makes two
|
||||||
/// sections of a report look like one network.
|
/// sections of a report look like one network.
|
||||||
pub name_shared_with: Option<String>,
|
pub name_shared_with: Option<String>,
|
||||||
|
/// Whether it started; false means it is configured but blocked by overlap.
|
||||||
|
#[serde(default = "joined_active_default")]
|
||||||
|
pub active: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn joined_active_default() -> bool {
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What happened when a network was left.
|
/// What happened when a network was left.
|
||||||
@@ -283,6 +614,8 @@ pub struct LeftReport {
|
|||||||
/// Everything the agent is doing, in one snapshot.
|
/// Everything the agent is doing, in one snapshot.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct StatusReport {
|
pub struct StatusReport {
|
||||||
|
/// Data-plane protocols this agent can enable at runtime.
|
||||||
|
pub available_protocols: Vec<ProtocolReport>,
|
||||||
/// This device's persistent endpoint id.
|
/// This device's persistent endpoint id.
|
||||||
pub endpoint_id: String,
|
pub endpoint_id: String,
|
||||||
/// Hostname announced to peers.
|
/// Hostname announced to peers.
|
||||||
@@ -295,6 +628,38 @@ pub struct StatusReport {
|
|||||||
pub networks: Vec<NetworkReport>,
|
pub networks: Vec<NetworkReport>,
|
||||||
/// The local DNS service, when one was asked for.
|
/// The local DNS service, when one was asked for.
|
||||||
pub dns: Option<DnsReport>,
|
pub dns: Option<DnsReport>,
|
||||||
|
/// The state directory the agent is actually using.
|
||||||
|
///
|
||||||
|
/// A client that was not told one would look in its own default, which is
|
||||||
|
/// not the agent's when the agent runs as a service under another user.
|
||||||
|
pub state_dir: String,
|
||||||
|
/// The cache directory the agent is actually using.
|
||||||
|
pub cache_dir: String,
|
||||||
|
/// The executable the agent runs, which is what needs the capability.
|
||||||
|
pub program: String,
|
||||||
|
/// Whether the agent itself can manage the overlay interface.
|
||||||
|
///
|
||||||
|
/// It is the agent that creates the interface, so the client's own
|
||||||
|
/// capabilities say nothing about it.
|
||||||
|
pub privilege: PrivilegeReport,
|
||||||
|
/// The version of the agent's software.
|
||||||
|
pub version: String,
|
||||||
|
/// The data plane protocols it has, each as `name vN` (wire version).
|
||||||
|
pub protocols: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the agent found when it checked whether it may manage an interface.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum PrivilegeReport {
|
||||||
|
/// Not checked.
|
||||||
|
#[default]
|
||||||
|
Unknown,
|
||||||
|
/// It can.
|
||||||
|
Available,
|
||||||
|
/// It cannot, with what was found.
|
||||||
|
Missing(String),
|
||||||
|
/// This platform has no provisioner yet.
|
||||||
|
Unsupported,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The local DNS service.
|
/// The local DNS service.
|
||||||
@@ -321,9 +686,37 @@ pub struct DnsReport {
|
|||||||
pub names: u32,
|
pub names: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An active network with an overlapping overlay range.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct RangeConflictReport {
|
||||||
|
/// Public network id, for unambiguous selection.
|
||||||
|
pub network_id: String,
|
||||||
|
/// Configured network name.
|
||||||
|
pub name: String,
|
||||||
|
/// The overlapping range.
|
||||||
|
pub range: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A data-plane protocol available in the running agent.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ProtocolReport {
|
||||||
|
/// Stable protocol name used by the CLI and network negotiation.
|
||||||
|
pub name: String,
|
||||||
|
/// A short description of encryption and transport.
|
||||||
|
pub summary: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// One network.
|
/// One network.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct NetworkReport {
|
pub struct NetworkReport {
|
||||||
|
/// Shared VIPs and this client's routing observations.
|
||||||
|
#[serde(default)]
|
||||||
|
pub vips: Vec<crate::vip::VipStatus>,
|
||||||
|
/// Enabled local data-plane protocols, in preference order.
|
||||||
|
pub protocols: Vec<String>,
|
||||||
|
/// Whether the network starts or resumes automatically when its range is free.
|
||||||
|
#[serde(default)]
|
||||||
|
pub auto_start: bool,
|
||||||
/// Whether this agent participates in LAN broadcasts in this network.
|
/// Whether this agent participates in LAN broadcasts in this network.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub broadcast: bool,
|
pub broadcast: bool,
|
||||||
@@ -366,24 +759,77 @@ pub struct NetworkReport {
|
|||||||
/// The range it could not have, because another network on this agent
|
/// The range it could not have, because another network on this agent
|
||||||
/// already holds it.
|
/// already holds it.
|
||||||
pub range_conflict: Option<String>,
|
pub range_conflict: Option<String>,
|
||||||
|
/// Networks that switching to this network would suspend.
|
||||||
|
#[serde(default)]
|
||||||
|
pub range_conflicts: Vec<RangeConflictReport>,
|
||||||
/// The overlay, when a protocol is running one.
|
/// The overlay, when a protocol is running one.
|
||||||
pub overlay: Option<OverlayReport>,
|
pub overlay: Option<OverlayReport>,
|
||||||
|
/// This agent's own name, when another member claimed it first.
|
||||||
|
pub hostname_conflict: Option<HostnameConflictReport>,
|
||||||
|
/// Exit-node settings: whether this agent offers one, and whether it
|
||||||
|
/// uses one.
|
||||||
|
pub exit: ExitReport,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How packets reach a member right now.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum DataPathReport {
|
||||||
|
/// Nothing carries packets to it: it is away, or only connected for
|
||||||
|
/// control while a data path is being set up.
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
/// A direct link.
|
||||||
|
Direct {
|
||||||
|
/// The kind of transport carrying it, e.g. `wg`.
|
||||||
|
transport: String,
|
||||||
|
},
|
||||||
|
/// Through other members.
|
||||||
|
Relayed {
|
||||||
|
/// Number of links on the way, at least two.
|
||||||
|
hops: u8,
|
||||||
|
/// The member the first of them goes to, as an endpoint id.
|
||||||
|
via: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name somebody else claimed first.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct HostnameConflictReport {
|
||||||
|
/// The name that is taken.
|
||||||
|
pub name: String,
|
||||||
|
/// The member that holds it, as an endpoint id.
|
||||||
|
pub holder: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One member of the network, from signed state.
|
/// One member of the network, from signed state.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct MemberReport {
|
pub struct MemberReport {
|
||||||
|
/// Signed claim version used to reject stale cleanup requests.
|
||||||
|
pub record_version: u64,
|
||||||
/// The member's device identity.
|
/// The member's device identity.
|
||||||
pub endpoint_id: String,
|
pub endpoint_id: String,
|
||||||
/// The IPv4 overlay address it claimed and signed for.
|
/// The IPv4 overlay address it claimed and signed for.
|
||||||
pub overlay_address_v4: Option<String>,
|
pub overlay_address_v4: Option<String>,
|
||||||
/// Consecutive failed dial attempts, when this agent is trying to reach it.
|
/// Consecutive failed dial attempts, when this agent is trying to reach it.
|
||||||
pub failed_dials: u32,
|
pub failed_dials: u32,
|
||||||
|
/// The last hostname this agent saw it announce, kept while it is away.
|
||||||
|
pub hostname: Option<String>,
|
||||||
|
/// Whether this agent can reach it now, by any path. The one answer
|
||||||
|
/// every client gives to "is it online": a member reached through
|
||||||
|
/// others is online, over a longer path.
|
||||||
|
pub online: bool,
|
||||||
|
/// How packets reach it.
|
||||||
|
pub path: DataPathReport,
|
||||||
|
/// The name it claimed, when somebody else claimed it first. It still
|
||||||
|
/// works by address; it is not found by that name.
|
||||||
|
pub hostname_conflict: Option<HostnameConflictReport>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One control plane peer.
|
/// One control plane peer.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct PeerReport {
|
pub struct PeerReport {
|
||||||
|
/// Actionable carrier failure or policy mismatch; absent for a usable route.
|
||||||
|
pub data_error: Option<String>,
|
||||||
/// The peer's endpoint id.
|
/// The peer's endpoint id.
|
||||||
pub endpoint_id: String,
|
pub endpoint_id: String,
|
||||||
/// Hostname it announced, if any.
|
/// Hostname it announced, if any.
|
||||||
@@ -393,6 +839,10 @@ pub struct PeerReport {
|
|||||||
pub transport: String,
|
pub transport: String,
|
||||||
/// Round-trip time in milliseconds, when a path is selected.
|
/// Round-trip time in milliseconds, when a path is selected.
|
||||||
pub rtt_ms: Option<u64>,
|
pub rtt_ms: Option<u64>,
|
||||||
|
/// The peer offers itself as an exit node in this network.
|
||||||
|
pub exit_node: bool,
|
||||||
|
/// How packets reach it.
|
||||||
|
pub path: DataPathReport,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The WireGuard overlay of one network.
|
/// The WireGuard overlay of one network.
|
||||||
@@ -425,6 +875,35 @@ pub struct OverlayReport {
|
|||||||
pub broadcast_rules: Option<HostRulesReport>,
|
pub broadcast_rules: Option<HostRulesReport>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How one set of exit-node host rules went.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct RuleSetReport {
|
||||||
|
/// Whether every step took.
|
||||||
|
pub ok: bool,
|
||||||
|
/// One line: what is in place, or what is missing and why.
|
||||||
|
pub detail: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One network's exit-node settings and what they are doing.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ExitReport {
|
||||||
|
/// This agent offers itself as an exit node in this network.
|
||||||
|
pub offering: bool,
|
||||||
|
/// Masquerading and forwarding rules for members' traffic, when offering.
|
||||||
|
pub offer_rules: Option<RuleSetReport>,
|
||||||
|
/// Whether the kernel forwards packets for the overlay interface.
|
||||||
|
/// `Some(false)` means the rules are in place and nothing passes until it
|
||||||
|
/// is turned on. `None` when unknown.
|
||||||
|
pub forwarding: Option<bool>,
|
||||||
|
/// The member this device sends its internet traffic through, as an
|
||||||
|
/// endpoint id.
|
||||||
|
pub via: Option<String>,
|
||||||
|
/// Whether that member is connected and still offering to be one.
|
||||||
|
pub via_online: bool,
|
||||||
|
/// The routes that send this device's traffic through it.
|
||||||
|
pub client_rules: Option<RuleSetReport>,
|
||||||
|
}
|
||||||
|
|
||||||
/// What the agent installed on the host so LAN broadcast reaches the overlay.
|
/// What the agent installed on the host so LAN broadcast reaches the overlay.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct HostRulesReport {
|
pub struct HostRulesReport {
|
||||||
@@ -440,10 +919,12 @@ pub struct HostRulesReport {
|
|||||||
/// One overlay peer.
|
/// One overlay peer.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct OverlayPeerReport {
|
pub struct OverlayPeerReport {
|
||||||
|
/// Opaque counter lifetime. A new tunnel or agent restart starts a new epoch.
|
||||||
|
pub counter_epoch: u64,
|
||||||
/// The peer's control plane identity, so a tunnel can be matched to the
|
/// The peer's control plane identity, so a tunnel can be matched to the
|
||||||
/// session and the member it belongs to.
|
/// session and the member it belongs to.
|
||||||
pub endpoint_id: String,
|
pub endpoint_id: String,
|
||||||
/// Protocol carrying overlay traffic for this peer (e.g. "tcp-tls", "wg-quic").
|
/// Reserved legacy field; the internal encryption protocol is not user selectable.
|
||||||
pub protocol: String,
|
pub protocol: String,
|
||||||
/// The peer's WireGuard public key (if applicable).
|
/// The peer's WireGuard public key (if applicable).
|
||||||
pub public_key: String,
|
pub public_key: String,
|
||||||
@@ -457,6 +938,10 @@ pub struct OverlayPeerReport {
|
|||||||
pub tx_packets: u64,
|
pub tx_packets: u64,
|
||||||
/// Packets decrypted from this peer.
|
/// Packets decrypted from this peer.
|
||||||
pub rx_packets: u64,
|
pub rx_packets: u64,
|
||||||
|
/// Plaintext bytes encrypted and sent to this peer.
|
||||||
|
pub tx_bytes: u64,
|
||||||
|
/// Plaintext bytes decrypted from this peer.
|
||||||
|
pub rx_bytes: u64,
|
||||||
/// Data packets dropped: wrong source address, or too large for the path.
|
/// Data packets dropped: wrong source address, or too large for the path.
|
||||||
pub dropped: u64,
|
pub dropped: u64,
|
||||||
/// WireGuard protocol errors.
|
/// WireGuard protocol errors.
|
||||||
@@ -494,6 +979,33 @@ impl OverlayPeerReport {
|
|||||||
/// running and what they can report or change. That is what keeps this module
|
/// running and what they can report or change. That is what keeps this module
|
||||||
/// free of any knowledge of them.
|
/// free of any knowledge of them.
|
||||||
pub trait ReportSource: Send + Sync + 'static {
|
pub trait ReportSource: Send + Sync + 'static {
|
||||||
|
/// Atomically saves a complete VIP draft using its original revision.
|
||||||
|
fn save_vip(
|
||||||
|
&self,
|
||||||
|
_network: String,
|
||||||
|
_config: crate::vip::VipConfig,
|
||||||
|
_expected: Option<String>,
|
||||||
|
_delete: bool,
|
||||||
|
) -> BoxFuture<'_, std::result::Result<Vec<crate::vip::VipStatus>, String>> {
|
||||||
|
Box::pin(async { Err("this agent cannot manage VIPs".into()) })
|
||||||
|
}
|
||||||
|
/// Persists and announces a version-scoped node cleanup.
|
||||||
|
fn forget_node(
|
||||||
|
&self,
|
||||||
|
_network: String,
|
||||||
|
_peer: String,
|
||||||
|
_expected_version: u64,
|
||||||
|
) -> BoxFuture<'_, std::result::Result<ForgottenNodeReport, String>> {
|
||||||
|
Box::pin(async { Err("this agent cannot forget node history".into()) })
|
||||||
|
}
|
||||||
|
/// Saves and applies a local ordered protocol set for one network.
|
||||||
|
fn set_protocols(
|
||||||
|
&self,
|
||||||
|
_network_id: String,
|
||||||
|
_protocols: Vec<String>,
|
||||||
|
) -> BoxFuture<'_, std::result::Result<Vec<String>, String>> {
|
||||||
|
Box::pin(async { Err("this agent cannot change protocols".into()) })
|
||||||
|
}
|
||||||
/// Produces a fresh report.
|
/// Produces a fresh report.
|
||||||
fn report(&self) -> BoxFuture<'_, StatusReport>;
|
fn report(&self) -> BoxFuture<'_, StatusReport>;
|
||||||
|
|
||||||
@@ -560,6 +1072,39 @@ pub trait ReportSource: Send + Sync + 'static {
|
|||||||
) -> BoxFuture<'_, std::result::Result<Option<DnsReport>, String>> {
|
) -> BoxFuture<'_, std::result::Result<Option<DnsReport>, String>> {
|
||||||
Box::pin(async move { Err("this agent cannot serve DNS".to_string()) })
|
Box::pin(async move { Err("this agent cannot serve DNS".to_string()) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns a configured network's shared secret in its `tsn1…` text form.
|
||||||
|
///
|
||||||
|
/// Defaulted to a refusal, like the others. An implementor reads it from
|
||||||
|
/// local state; it must never be logged.
|
||||||
|
fn network_secret(
|
||||||
|
&self,
|
||||||
|
_network_id: String,
|
||||||
|
) -> BoxFuture<'_, std::result::Result<String, String>> {
|
||||||
|
Box::pin(async move { Err("this agent cannot read secrets".to_string()) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Offers this agent as an exit node in a network, or stops.
|
||||||
|
///
|
||||||
|
/// Defaulted to a refusal, like the others.
|
||||||
|
fn set_exit_offer(
|
||||||
|
&self,
|
||||||
|
_network_id: String,
|
||||||
|
_enabled: bool,
|
||||||
|
) -> BoxFuture<'_, std::result::Result<bool, String>> {
|
||||||
|
Box::pin(async move { Err("this agent cannot be an exit node".to_string()) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends this device's internet traffic through a member, or stops.
|
||||||
|
///
|
||||||
|
/// Defaulted to a refusal, like the others.
|
||||||
|
fn set_exit_node(
|
||||||
|
&self,
|
||||||
|
_network_id: String,
|
||||||
|
_peer: Option<String>,
|
||||||
|
) -> BoxFuture<'_, std::result::Result<Option<String>, String>> {
|
||||||
|
Box::pin(async move { Err("this agent cannot use an exit node".to_string()) })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F> ReportSource for F
|
impl<F> ReportSource for F
|
||||||
@@ -575,7 +1120,7 @@ where
|
|||||||
///
|
///
|
||||||
/// A local answer comes from memory, so anything this slow means the agent is
|
/// A local answer comes from memory, so anything this slow means the agent is
|
||||||
/// wedged rather than busy. Saying so beats waiting: unbounded, one wedged
|
/// wedged rather than busy. Saying so beats waiting: unbounded, one wedged
|
||||||
/// runtime leaves `tsunagi status` hanging with nothing on screen and no way
|
/// runtime leaves `tsng status` hanging with nothing on screen and no way
|
||||||
/// out but Ctrl-C.
|
/// out but Ctrl-C.
|
||||||
pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
@@ -590,7 +1135,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
|||||||
///
|
///
|
||||||
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
||||||
/// changes shape.
|
/// changes shape.
|
||||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 15]);
|
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 23]);
|
||||||
|
|
||||||
/// Reads one request off an accepted stream, answers it, writes the response.
|
/// Reads one request off an accepted stream, answers it, writes the response.
|
||||||
///
|
///
|
||||||
@@ -614,6 +1159,30 @@ where
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let response = match request {
|
let response = match request {
|
||||||
|
Request::SaveVip {
|
||||||
|
network_id,
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
} => match source.save_vip(network_id, config, expected, delete).await {
|
||||||
|
Ok(vips) => Response::Vips(vips),
|
||||||
|
Err(reason) => Response::Error(reason),
|
||||||
|
},
|
||||||
|
Request::ForgetNode {
|
||||||
|
network_id,
|
||||||
|
peer,
|
||||||
|
expected_version,
|
||||||
|
} => match source.forget_node(network_id, peer, expected_version).await {
|
||||||
|
Ok(report) => Response::NodeForgotten(report),
|
||||||
|
Err(reason) => Response::Error(reason),
|
||||||
|
},
|
||||||
|
Request::SetProtocols {
|
||||||
|
network_id,
|
||||||
|
protocols,
|
||||||
|
} => match source.set_protocols(network_id, protocols).await {
|
||||||
|
Ok(protocols) => Response::Protocols(protocols),
|
||||||
|
Err(reason) => Response::Error(reason),
|
||||||
|
},
|
||||||
Request::Status => Response::Status(Box::new(source.report().await)),
|
Request::Status => Response::Status(Box::new(source.report().await)),
|
||||||
Request::SetBroadcast {
|
Request::SetBroadcast {
|
||||||
network_id,
|
network_id,
|
||||||
@@ -648,6 +1217,23 @@ where
|
|||||||
Ok(report) => Response::Dns(report),
|
Ok(report) => Response::Dns(report),
|
||||||
Err(reason) => Response::Error(reason),
|
Err(reason) => Response::Error(reason),
|
||||||
},
|
},
|
||||||
|
Request::Secret { network_id } => match source.network_secret(network_id).await {
|
||||||
|
Ok(secret) => Response::Secret(RedactedText::new(secret)),
|
||||||
|
Err(reason) => Response::Error(reason),
|
||||||
|
},
|
||||||
|
Request::SetExitOffer {
|
||||||
|
network_id,
|
||||||
|
enabled,
|
||||||
|
} => match source.set_exit_offer(network_id, enabled).await {
|
||||||
|
Ok(enabled) => Response::ExitOffer(enabled),
|
||||||
|
Err(reason) => Response::Error(reason),
|
||||||
|
},
|
||||||
|
Request::SetExitNode { network_id, peer } => {
|
||||||
|
match source.set_exit_node(network_id, peer).await {
|
||||||
|
Ok(peer) => Response::ExitNode(peer),
|
||||||
|
Err(reason) => Response::Error(reason),
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
write_message(&mut stream, &response).await
|
write_message(&mut stream, &response).await
|
||||||
}
|
}
|
||||||
@@ -752,7 +1338,24 @@ pub async fn join_network_with_broadcast(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Changes one network's broadcast participation while the agent runs.
|
/// Replaces the enabled data-plane protocols of one configured network.
|
||||||
|
pub async fn set_protocols(
|
||||||
|
socket: &Path,
|
||||||
|
network_id: &str,
|
||||||
|
protocols: Vec<String>,
|
||||||
|
) -> Result<Vec<String>> {
|
||||||
|
let request = Request::SetProtocols {
|
||||||
|
network_id: network_id.to_owned(),
|
||||||
|
protocols,
|
||||||
|
};
|
||||||
|
match exchange(socket, &request, EXCHANGE_TIMEOUT).await? {
|
||||||
|
Response::Protocols(protocols) => Ok(protocols),
|
||||||
|
Response::Error(reason) => Err(Error::Storage(reason)),
|
||||||
|
other => Err(Error::Storage(format!("unexpected response: {other:?}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes local broadcast participation in a network.
|
||||||
pub async fn set_broadcast(
|
pub async fn set_broadcast(
|
||||||
path: impl AsRef<Path>,
|
path: impl AsRef<Path>,
|
||||||
network_id: &str,
|
network_id: &str,
|
||||||
@@ -802,6 +1405,56 @@ pub async fn set_dns(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Offers the running agent as an exit node in one network, or stops.
|
||||||
|
pub async fn set_exit_offer(
|
||||||
|
path: impl AsRef<Path>,
|
||||||
|
network_id: &str,
|
||||||
|
enabled: bool,
|
||||||
|
) -> Result<bool> {
|
||||||
|
let request = Request::SetExitOffer {
|
||||||
|
network_id: network_id.to_owned(),
|
||||||
|
enabled,
|
||||||
|
};
|
||||||
|
match exchange(path.as_ref(), &request, EXCHANGE_TIMEOUT).await? {
|
||||||
|
Response::ExitOffer(enabled) => Ok(enabled),
|
||||||
|
Response::Error(message) => Err(Error::Storage(message)),
|
||||||
|
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends the running agent's internet traffic through a member of one
|
||||||
|
/// network, or back the ordinary way with `None`.
|
||||||
|
pub async fn set_exit_node(
|
||||||
|
path: impl AsRef<Path>,
|
||||||
|
network_id: &str,
|
||||||
|
peer: Option<&str>,
|
||||||
|
) -> Result<Option<String>> {
|
||||||
|
let request = Request::SetExitNode {
|
||||||
|
network_id: network_id.to_owned(),
|
||||||
|
peer: peer.map(str::to_owned),
|
||||||
|
};
|
||||||
|
match exchange(path.as_ref(), &request, EXCHANGE_TIMEOUT).await? {
|
||||||
|
Response::ExitNode(peer) => Ok(peer),
|
||||||
|
Response::Error(message) => Err(Error::Storage(message)),
|
||||||
|
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks a running agent for a configured network's shared secret, in its
|
||||||
|
/// `tsn1…` text form, so a local client can copy it. The secret is never
|
||||||
|
/// logged by this path.
|
||||||
|
pub async fn network_secret(path: impl AsRef<Path>, network_id: &str) -> Result<String> {
|
||||||
|
let path = path.as_ref();
|
||||||
|
let request = Request::Secret {
|
||||||
|
network_id: network_id.to_string(),
|
||||||
|
};
|
||||||
|
match exchange(path, &request, EXCHANGE_TIMEOUT).await? {
|
||||||
|
Response::Secret(secret) => Ok(secret.into_string()),
|
||||||
|
Response::Error(reason) => Err(Error::Storage(reason)),
|
||||||
|
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn write_message<S, T>(stream: &mut S, value: &T) -> Result<()>
|
pub(crate) async fn write_message<S, T>(stream: &mut S, value: &T) -> Result<()>
|
||||||
where
|
where
|
||||||
S: AsyncWrite + Unpin,
|
S: AsyncWrite + Unpin,
|
||||||
@@ -22,8 +22,8 @@ use crate::error::{Error, Result};
|
|||||||
// The transport-agnostic surface, re-exported so this module is a complete
|
// The transport-agnostic surface, re-exported so this module is a complete
|
||||||
// view of the local control interface on its own.
|
// view of the local control interface on its own.
|
||||||
pub use super::{
|
pub use super::{
|
||||||
CONTROL_PROTOCOL, EXCHANGE_TIMEOUT, ReportSource, is_serving, join_network, leave_network,
|
CONTROL_PROTOCOL, ControlSocketAccess, EXCHANGE_TIMEOUT, ReportSource, is_serving,
|
||||||
request_status, set_active, set_dns, set_hostname,
|
join_network, leave_network, request_status, set_active, set_dns, set_hostname,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Serves the local control interface on a Unix socket.
|
/// Serves the local control interface on a Unix socket.
|
||||||
@@ -39,11 +39,15 @@ impl ControlSocket {
|
|||||||
/// A socket file left behind by a crashed agent is replaced, but only
|
/// A socket file left behind by a crashed agent is replaced, but only
|
||||||
/// after checking that nothing is listening on it, so two live agents
|
/// after checking that nothing is listening on it, so two live agents
|
||||||
/// never fight over one path.
|
/// never fight over one path.
|
||||||
pub async fn bind(path: impl AsRef<Path>, source: Arc<dyn ReportSource>) -> Result<Self> {
|
pub async fn bind(
|
||||||
|
path: impl AsRef<Path>,
|
||||||
|
source: Arc<dyn ReportSource>,
|
||||||
|
access: ControlSocketAccess,
|
||||||
|
) -> Result<Self> {
|
||||||
let path = path.as_ref().to_path_buf();
|
let path = path.as_ref().to_path_buf();
|
||||||
|
|
||||||
if let Some(parent) = path.parent() {
|
if let Some(parent) = path.parent() {
|
||||||
crate::storage::create_dir(parent)?;
|
create_parent(parent, &access)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if path.exists() {
|
if path.exists() {
|
||||||
@@ -61,7 +65,7 @@ impl ControlSocket {
|
|||||||
path: path.clone(),
|
path: path.clone(),
|
||||||
source,
|
source,
|
||||||
})?;
|
})?;
|
||||||
restrict(&path)?;
|
apply_access(&path, &access)?;
|
||||||
|
|
||||||
let task = tokio::spawn(serve(listener, source));
|
let task = tokio::spawn(serve(listener, source));
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
@@ -94,9 +98,48 @@ impl Drop for ControlSocket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn restrict(path: &Path) -> Result<()> {
|
/// Creates the socket's parent directory.
|
||||||
|
///
|
||||||
|
/// A group-shared socket must sit in a directory the group can traverse, so it
|
||||||
|
/// is `0755`; a private socket keeps the owner-only state-directory default.
|
||||||
|
fn create_parent(parent: &Path, access: &ControlSocketAccess) -> Result<()> {
|
||||||
|
match access {
|
||||||
|
ControlSocketAccess::Private => crate::storage::create_dir(parent),
|
||||||
|
ControlSocketAccess::Group(_) => {
|
||||||
|
std::fs::create_dir_all(parent).map_err(|source| Error::Io {
|
||||||
|
path: parent.to_path_buf(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
set_mode(parent, 0o755)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies the access policy to the bound socket.
|
||||||
|
///
|
||||||
|
/// Private is owner-only `0600`. Group sets the socket's group to the gid and
|
||||||
|
/// the mode to `0660`; if the group cannot be set — the agent is not a member,
|
||||||
|
/// say — it falls back to owner-only rather than leaving the group wrong, so
|
||||||
|
/// the socket is never more open than intended.
|
||||||
|
fn apply_access(path: &Path, access: &ControlSocketAccess) -> Result<()> {
|
||||||
|
match access {
|
||||||
|
ControlSocketAccess::Private => set_mode(path, 0o600),
|
||||||
|
ControlSocketAccess::Group(gid) => {
|
||||||
|
if let Err(source) = std::os::unix::fs::chown(path, None, Some(*gid)) {
|
||||||
|
tracing::warn!(
|
||||||
|
path = %path.display(), gid, %source,
|
||||||
|
"cannot set the control socket group; keeping it owner-only"
|
||||||
|
);
|
||||||
|
return set_mode(path, 0o600);
|
||||||
|
}
|
||||||
|
set_mode(path, 0o660)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_mode(path: &Path, mode: u32) -> Result<()> {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|source| {
|
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).map_err(|source| {
|
||||||
Error::Io {
|
Error::Io {
|
||||||
path: path.to_path_buf(),
|
path: path.to_path_buf(),
|
||||||
source,
|
source,
|
||||||
@@ -170,7 +213,9 @@ mod tests {
|
|||||||
let source: Arc<dyn ReportSource> = Arc::new(|| -> BoxFuture<'static, StatusReport> {
|
let source: Arc<dyn ReportSource> = Arc::new(|| -> BoxFuture<'static, StatusReport> {
|
||||||
Box::pin(async { StatusReport::default() })
|
Box::pin(async { StatusReport::default() })
|
||||||
});
|
});
|
||||||
let control = ControlSocket::bind(&path, source).await.unwrap();
|
let control = ControlSocket::bind(&path, source, ControlSocketAccess::Private)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let answer = exchange(&path, &Request::Status, EXCHANGE_TIMEOUT)
|
let answer = exchange(&path, &Request::Status, EXCHANGE_TIMEOUT)
|
||||||
.await
|
.await
|
||||||
@@ -40,8 +40,8 @@ use tokio::task::JoinHandle;
|
|||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
pub use super::{
|
pub use super::{
|
||||||
CONTROL_PROTOCOL, EXCHANGE_TIMEOUT, ReportSource, is_serving, join_network, leave_network,
|
CONTROL_PROTOCOL, ControlSocketAccess, EXCHANGE_TIMEOUT, ReportSource, is_serving,
|
||||||
request_status, set_active, set_dns, set_hostname,
|
join_network, leave_network, request_status, set_active, set_dns, set_hostname,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// `ERROR_ACCESS_DENIED`: creating a first instance finds an existing pipe,
|
/// `ERROR_ACCESS_DENIED`: creating a first instance finds an existing pipe,
|
||||||
@@ -149,7 +149,16 @@ impl ControlSocket {
|
|||||||
/// Claiming the first instance of the name is what detects a second agent:
|
/// Claiming the first instance of the name is what detects a second agent:
|
||||||
/// if the name already exists, the create is refused and that is reported
|
/// if the name already exists, the create is refused and that is reported
|
||||||
/// as the state being locked, so two live agents never share one pipe.
|
/// as the state being locked, so two live agents never share one pipe.
|
||||||
pub async fn bind(path: impl AsRef<Path>, source: Arc<dyn ReportSource>) -> Result<Self> {
|
///
|
||||||
|
/// `_access` is accepted for parity with the Unix socket; granting a group
|
||||||
|
/// here means a pipe security descriptor and is a separate follow-up, so for
|
||||||
|
/// now the pipe keeps its default (creator plus the built-in access the
|
||||||
|
/// `PipeSecurityAttributes` set).
|
||||||
|
pub async fn bind(
|
||||||
|
path: impl AsRef<Path>,
|
||||||
|
source: Arc<dyn ReportSource>,
|
||||||
|
_access: ControlSocketAccess,
|
||||||
|
) -> Result<Self> {
|
||||||
let path = path.as_ref().to_path_buf();
|
let path = path.as_ref().to_path_buf();
|
||||||
let name = pipe_name(&path);
|
let name = pipe_name(&path);
|
||||||
|
|
||||||
@@ -201,7 +210,7 @@ impl Drop for ControlSocket {
|
|||||||
/// Accepts one client at a time, keeping a fresh instance ready for the next.
|
/// Accepts one client at a time, keeping a fresh instance ready for the next.
|
||||||
///
|
///
|
||||||
/// A named pipe server instance serves a single client, so a new instance is
|
/// A named pipe server instance serves a single client, so a new instance is
|
||||||
/// created as soon as one is taken — otherwise a second `tsunagi status` while
|
/// created as soon as one is taken — otherwise a second `tsng status` while
|
||||||
/// the first is mid-flight would find nothing listening.
|
/// the first is mid-flight would find nothing listening.
|
||||||
async fn serve(
|
async fn serve(
|
||||||
name: String,
|
name: String,
|
||||||
@@ -285,7 +294,7 @@ pub(crate) async fn connect(path: &Path) -> Result<NamedPipeClient> {
|
|||||||
format!(
|
format!(
|
||||||
"the agent's control pipe exists, but Windows denied access. \
|
"the agent's control pipe exists, but Windows denied access. \
|
||||||
Run this command as the same Windows user and with the same \
|
Run this command as the same Windows user and with the same \
|
||||||
elevation as `tsunagi up` (use an administrator terminal if \
|
elevation as `tsng up` (use an administrator terminal if \
|
||||||
the agent is elevated). Windows error: {err}"
|
the agent is elevated). Windows error: {err}"
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -51,6 +51,7 @@ pub mod storage;
|
|||||||
pub mod task;
|
pub mod task;
|
||||||
#[cfg(feature = "testing")]
|
#[cfg(feature = "testing")]
|
||||||
pub mod testing;
|
pub mod testing;
|
||||||
|
pub mod vip;
|
||||||
|
|
||||||
pub use agent::{Agent, AgentStatus, Event, NetworkStatus, PeerStatus};
|
pub use agent::{Agent, AgentStatus, Event, NetworkStatus, PeerStatus};
|
||||||
pub use config::{AgentConfig, Limits, ReconnectPolicy, StoragePaths, TransportPolicy};
|
pub use config::{AgentConfig, Limits, ReconnectPolicy, StoragePaths, TransportPolicy};
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
//! own reachability data.
|
//! own reachability data.
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use iroh::endpoint::{
|
use iroh::endpoint::{
|
||||||
@@ -221,9 +222,18 @@ fn local_addr_string(addr: &iroh::endpoint::LocalTransportAddr) -> Option<String
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct EndpointAdapter {
|
pub struct EndpointAdapter {
|
||||||
endpoint: Endpoint,
|
endpoint: Endpoint,
|
||||||
|
owned_interface: Arc<std::sync::RwLock<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EndpointAdapter {
|
impl EndpointAdapter {
|
||||||
|
/// Excludes the real name after interface creation (macOS assigns utunN).
|
||||||
|
pub(crate) fn exclude_interface(&self, name: &str) {
|
||||||
|
*self
|
||||||
|
.owned_interface
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(|p| p.into_inner()) = name.to_lowercase();
|
||||||
|
}
|
||||||
|
|
||||||
/// Binds an endpoint according to `config`, reusing the persistent device key.
|
/// Binds an endpoint according to `config`, reusing the persistent device key.
|
||||||
pub async fn bind(config: &AgentConfig, identity: &DeviceIdentity) -> Result<Self> {
|
pub async fn bind(config: &AgentConfig, identity: &DeviceIdentity) -> Result<Self> {
|
||||||
let mut builder = Endpoint::builder(presets::Minimal)
|
let mut builder = Endpoint::builder(presets::Minimal)
|
||||||
@@ -240,12 +250,20 @@ impl EndpointAdapter {
|
|||||||
TransportPolicy::N0Defaults => builder.preset(presets::N0),
|
TransportPolicy::N0Defaults => builder.preset(presets::N0),
|
||||||
};
|
};
|
||||||
|
|
||||||
if matches!(
|
let owned_interface =
|
||||||
config.transport,
|
Arc::new(std::sync::RwLock::new(config.interface_name.to_lowercase()));
|
||||||
TransportPolicy::N0Defaults | TransportPolicy::DirectOnly
|
{
|
||||||
) {
|
let interface_filter = Arc::clone(&owned_interface);
|
||||||
let filter = iroh::address_lookup::AddrFilter::new(|addrs| {
|
let factory = config.tun_factory.clone();
|
||||||
|
let filter = iroh::address_lookup::AddrFilter::new(move |addrs| {
|
||||||
|
let owned_interface = interface_filter
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.clone();
|
||||||
let mut overlay_ips = std::collections::HashSet::new();
|
let mut overlay_ips = std::collections::HashSet::new();
|
||||||
|
if let Some(factory) = &factory {
|
||||||
|
overlay_ips.extend(factory.assigned_addresses());
|
||||||
|
}
|
||||||
for iface in netdev::get_interfaces() {
|
for iface in netdev::get_interfaces() {
|
||||||
let name = iface.name.to_lowercase();
|
let name = iface.name.to_lowercase();
|
||||||
let friendly = iface
|
let friendly = iface
|
||||||
@@ -258,7 +276,9 @@ impl EndpointAdapter {
|
|||||||
.as_deref()
|
.as_deref()
|
||||||
.map(str::to_lowercase)
|
.map(str::to_lowercase)
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
if name.starts_with("tsun")
|
if name == owned_interface
|
||||||
|
|| friendly == owned_interface
|
||||||
|
|| name.starts_with("tsun")
|
||||||
|| name.contains("tsunagi")
|
|| name.contains("tsunagi")
|
||||||
|| name.contains("wintun")
|
|| name.contains("wintun")
|
||||||
|| friendly.starts_with("tsun")
|
|| friendly.starts_with("tsun")
|
||||||
@@ -288,7 +308,9 @@ impl EndpointAdapter {
|
|||||||
.collect();
|
.collect();
|
||||||
std::borrow::Cow::Owned(filtered)
|
std::borrow::Cow::Owned(filtered)
|
||||||
});
|
});
|
||||||
builder = builder.addr_filter(filter);
|
builder = builder
|
||||||
|
.direct_addr_filter(filter.clone())
|
||||||
|
.addr_filter(filter);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "testing")]
|
#[cfg(feature = "testing")]
|
||||||
@@ -395,7 +417,10 @@ impl EndpointAdapter {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(Self { endpoint })
|
Ok(Self {
|
||||||
|
endpoint,
|
||||||
|
owned_interface,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The underlying iroh endpoint.
|
/// The underlying iroh endpoint.
|
||||||
@@ -140,6 +140,7 @@ mod tests {
|
|||||||
fn limited_and_directed_broadcasts_never_cross_domains_or_target_disabled_peers() {
|
fn limited_and_directed_broadcasts_never_cross_domains_or_target_disabled_peers() {
|
||||||
let peer = iroh::SecretKey::from_bytes(&[8; 32]).public();
|
let peer = iroh::SecretKey::from_bytes(&[8; 32]).public();
|
||||||
let a = NetworkRoutes {
|
let a = NetworkRoutes {
|
||||||
|
exit: Default::default(),
|
||||||
range: Some("10.0.0.0/24".parse().unwrap()),
|
range: Some("10.0.0.0/24".parse().unwrap()),
|
||||||
local: Some("10.0.0.1".parse().unwrap()),
|
local: Some("10.0.0.1".parse().unwrap()),
|
||||||
peers: vec![("10.0.0.2".parse().unwrap(), peer)],
|
peers: vec![("10.0.0.2".parse().unwrap(), peer)],
|
||||||
@@ -149,6 +150,7 @@ mod tests {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
let b = NetworkRoutes {
|
let b = NetworkRoutes {
|
||||||
|
exit: Default::default(),
|
||||||
range: Some("10.1.0.0/24".parse().unwrap()),
|
range: Some("10.1.0.0/24".parse().unwrap()),
|
||||||
local: Some("10.1.0.1".parse().unwrap()),
|
local: Some("10.1.0.1".parse().unwrap()),
|
||||||
peers: vec![("10.1.0.2".parse().unwrap(), peer)],
|
peers: vec![("10.1.0.2".parse().unwrap(), peer)],
|
||||||
@@ -185,6 +187,7 @@ mod tests {
|
|||||||
assert!(!table.accepts(id("b"), peer, Ipv4Addr::BROADCAST));
|
assert!(!table.accepts(id("b"), peer, Ipv4Addr::BROADCAST));
|
||||||
assert!(table.accepts(id("a"), peer, Ipv4Addr::BROADCAST));
|
assert!(table.accepts(id("a"), peer, Ipv4Addr::BROADCAST));
|
||||||
let disabled = NetworkRoutes {
|
let disabled = NetworkRoutes {
|
||||||
|
exit: Default::default(),
|
||||||
broadcast: BroadcastPolicy {
|
broadcast: BroadcastPolicy {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
..a.broadcast.clone()
|
..a.broadcast.clone()
|
||||||
File renamed without changes.
@@ -0,0 +1,32 @@
|
|||||||
|
//! Exit-node host rules: what makes this device an exit node for others, and
|
||||||
|
//! what sends this device's own traffic through one.
|
||||||
|
//!
|
||||||
|
//! The packet side lives in [`super::router`]; this is the side the operating
|
||||||
|
//! system sees. It is kept apart from the broadcast rules, which have a
|
||||||
|
//! different lifetime and different tags.
|
||||||
|
|
||||||
|
/// How one set of host rules went.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct RuleSetReport {
|
||||||
|
/// Whether every step took.
|
||||||
|
pub ok: bool,
|
||||||
|
/// One line: what is in place, or what is missing and why.
|
||||||
|
pub detail: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the host rules of one network's exit-node settings are doing.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct ExitRulesReport {
|
||||||
|
/// Masquerading and forwarding for members' traffic, when this agent
|
||||||
|
/// offers itself as an exit node here. `None` means none are wanted.
|
||||||
|
pub offer: Option<RuleSetReport>,
|
||||||
|
/// Whether the kernel forwards packets for the overlay interface.
|
||||||
|
///
|
||||||
|
/// `Some(false)` means the rules are in place but nothing passes until
|
||||||
|
/// forwarding is turned on, which the agent never does itself. `None`
|
||||||
|
/// when it could not be read.
|
||||||
|
pub forwarding: Option<bool>,
|
||||||
|
/// The routes that send this device's traffic through its exit node.
|
||||||
|
/// `None` means it uses none through this network.
|
||||||
|
pub client: Option<RuleSetReport>,
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
//! Host rules for exit nodes: what the operating system needs for this agent
|
||||||
|
//! to carry other members' internet traffic, and for this device's own
|
||||||
|
//! traffic to go through a member.
|
||||||
|
//!
|
||||||
|
//! Two independent halves, planned together because one interface carries
|
||||||
|
//! both:
|
||||||
|
//!
|
||||||
|
//! * **Offering** — one set of rules per network that offers this agent as an
|
||||||
|
//! exit node, chosen by that network's range: masquerade the range out of
|
||||||
|
//! every other interface and let it through the forward chain. A network
|
||||||
|
//! that does not offer has no rules, so its members' packets are dropped by
|
||||||
|
//! the firewall as well as by the agent.
|
||||||
|
//! * **Using** — policy routing that sends everything the host does not have
|
||||||
|
//! a more specific route for into the overlay interface, while the agent's
|
||||||
|
//! own sockets keep the ordinary route (see `linux_exit`).
|
||||||
|
//!
|
||||||
|
//! Nothing a peer announces becomes a host setting. Offering is the owner's
|
||||||
|
//! switch; using is the user's choice of a member. Every object is tagged,
|
||||||
|
//! reversible, and removed when it is no longer wanted, when the network
|
||||||
|
//! leaves or stops, and when the agent stops.
|
||||||
|
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use crate::BoxFuture;
|
||||||
|
use crate::state::Ipv4Range;
|
||||||
|
|
||||||
|
use super::RuleOutcome;
|
||||||
|
|
||||||
|
/// What the host should hold for one interface's exit settings.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct ExitHostPlan {
|
||||||
|
/// The overlay interface.
|
||||||
|
pub interface: String,
|
||||||
|
/// The ranges of every network that offers this agent as an exit node.
|
||||||
|
pub offer: Vec<Ipv4Range>,
|
||||||
|
/// Whether this device sends its internet traffic through a member.
|
||||||
|
pub client: bool,
|
||||||
|
/// Local address in the selected exit network, for hosts that choose a primary address.
|
||||||
|
pub client_source: Option<std::net::Ipv4Addr>,
|
||||||
|
/// The range of every network on the interface. Only the using side
|
||||||
|
/// reads it, to keep this agent's own traffic *to* the overlay inside it
|
||||||
|
/// where the host has no per-user routing (macOS).
|
||||||
|
pub overlay: Vec<Ipv4Range>,
|
||||||
|
/// Underlay addresses this agent talks to directly and must keep reaching
|
||||||
|
/// outside the overlay's default route. Only filled while `client` is set
|
||||||
|
/// and only for hosts that report [`ExitHostRules::needs_bypass`].
|
||||||
|
pub bypass: Vec<std::net::Ipv4Addr>,
|
||||||
|
/// Host names (relay servers) that must stay reachable the same way; the
|
||||||
|
/// host rules resolve them.
|
||||||
|
pub bypass_hosts: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExitHostPlan {
|
||||||
|
/// Whether there is nothing to hold.
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.offer.is_empty() && !self.client
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What applying a plan achieved.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct ExitHostReport {
|
||||||
|
/// One outcome per offered range: its masquerade and forward rules.
|
||||||
|
pub offer: Vec<(Ipv4Range, RuleOutcome)>,
|
||||||
|
/// Whether the kernel forwards packets for the interface. `None` when it
|
||||||
|
/// could not be read. The agent only reads this: turning forwarding on is
|
||||||
|
/// the owner's decision.
|
||||||
|
pub forwarding: Option<bool>,
|
||||||
|
/// The routes and rules that send this device's traffic through the
|
||||||
|
/// interface, when the plan asked for them.
|
||||||
|
pub client: Option<RuleOutcome>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs and removes exit-node rules for an overlay interface.
|
||||||
|
///
|
||||||
|
/// Like the broadcast rules, no call fails as a whole: a step that cannot be
|
||||||
|
/// done is in the report, because the caller's only useful response is to
|
||||||
|
/// say so.
|
||||||
|
pub trait ExitHostRules: Send + Sync + std::fmt::Debug + 'static {
|
||||||
|
/// Makes the host match the plan, replacing what this agent put there
|
||||||
|
/// for the interface before.
|
||||||
|
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport>;
|
||||||
|
|
||||||
|
/// Removes everything this agent put there for the interface. Succeeds
|
||||||
|
/// when nothing is there: it runs on the shutdown path, and once at
|
||||||
|
/// startup to take away what a crashed run left.
|
||||||
|
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()>;
|
||||||
|
|
||||||
|
/// Refreshes volatile local socket protection without replacing exit routes.
|
||||||
|
fn refresh<'a>(&'a self, _plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
|
||||||
|
Box::pin(async { None })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether using an exit node on this host needs the underlay addresses
|
||||||
|
/// the agent talks to, because the host cannot exempt the agent's own
|
||||||
|
/// traffic from the default route by user id (Windows). The default is no.
|
||||||
|
fn needs_bypass(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tag every firewall object of one offered range carries.
|
||||||
|
pub fn exit_tag(interface: &str, range: &Ipv4Range) -> String {
|
||||||
|
format!("{}{range}", exit_tag_prefix(interface))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The start of every tag for an interface; what cleanup selects by.
|
||||||
|
pub fn exit_tag_prefix(interface: &str) -> String {
|
||||||
|
format!("tsunagi-exit:{interface}:")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one-line detail for a set of offer outcomes.
|
||||||
|
pub fn offer_detail(outcome: &RuleOutcome, range: &Ipv4Range) -> String {
|
||||||
|
match outcome {
|
||||||
|
RuleOutcome::Applied => format!("masquerade + forward for {range} in place"),
|
||||||
|
RuleOutcome::Failed(reason) => reason.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An in-memory host for exit rules, for tests: nothing is touched.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct MockExitRules {
|
||||||
|
state: Arc<Mutex<Option<ExitHostPlan>>>,
|
||||||
|
calls: Arc<Mutex<Vec<String>>>,
|
||||||
|
forwarding: Arc<Mutex<Option<bool>>>,
|
||||||
|
failure: Arc<Mutex<Option<String>>>,
|
||||||
|
needs_bypass: Arc<Mutex<bool>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MockExitRules {
|
||||||
|
/// An empty host with forwarding turned on.
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let rules = Self::default();
|
||||||
|
*lock(&rules.forwarding) = Some(true);
|
||||||
|
rules
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the host reports for kernel forwarding from now on.
|
||||||
|
pub fn set_forwarding(&self, forwarding: Option<bool>) {
|
||||||
|
*lock(&self.forwarding) = forwarding;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this host asks for the underlay addresses, like Windows.
|
||||||
|
pub fn set_needs_bypass(&self, needs: bool) {
|
||||||
|
*lock(&self.needs_bypass) = needs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes every step fail with this reason from now on.
|
||||||
|
pub fn fail_with(&self, reason: Option<String>) {
|
||||||
|
*lock(&self.failure) = reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What is installed now.
|
||||||
|
pub fn installed(&self) -> Option<ExitHostPlan> {
|
||||||
|
lock(&self.state).clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every `apply:<interface>` / `clear:<interface>` call, in order.
|
||||||
|
pub fn calls(&self) -> Vec<String> {
|
||||||
|
lock(&self.calls).clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||||
|
match mutex.lock() {
|
||||||
|
Ok(guard) => guard,
|
||||||
|
Err(poisoned) => poisoned.into_inner(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExitHostRules for MockExitRules {
|
||||||
|
fn needs_bypass(&self) -> bool {
|
||||||
|
*lock(&self.needs_bypass)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||||
|
Box::pin(async move {
|
||||||
|
lock(&self.calls).push(format!("apply:{}", plan.interface));
|
||||||
|
let outcome = match lock(&self.failure).clone() {
|
||||||
|
Some(reason) => RuleOutcome::Failed(reason),
|
||||||
|
None => {
|
||||||
|
*lock(&self.state) = Some(plan.clone());
|
||||||
|
RuleOutcome::Applied
|
||||||
|
}
|
||||||
|
};
|
||||||
|
ExitHostReport {
|
||||||
|
offer: plan
|
||||||
|
.offer
|
||||||
|
.iter()
|
||||||
|
.map(|range| (*range, outcome.clone()))
|
||||||
|
.collect(),
|
||||||
|
forwarding: *lock(&self.forwarding),
|
||||||
|
client: plan.client.then_some(outcome),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async move {
|
||||||
|
lock(&self.calls).push(format!("clear:{interface}"));
|
||||||
|
*lock(&self.state) = None;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn range() -> Ipv4Range {
|
||||||
|
"10.13.37.0/24".parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tags_name_the_interface_and_the_range() {
|
||||||
|
assert_eq!(
|
||||||
|
exit_tag("tsun0", &range()),
|
||||||
|
"tsunagi-exit:tsun0:10.13.37.0/24"
|
||||||
|
);
|
||||||
|
assert!(exit_tag("tsun0", &range()).starts_with(&exit_tag_prefix("tsun0")));
|
||||||
|
// Another interface's tag never matches this one's prefix.
|
||||||
|
assert!(!exit_tag("tsun01", &range()).starts_with(&exit_tag_prefix("tsun0")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_empty_plan_is_nothing_to_hold() {
|
||||||
|
let mut plan = ExitHostPlan::default();
|
||||||
|
assert!(plan.is_empty());
|
||||||
|
plan.client = true;
|
||||||
|
assert!(!plan.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_mock_applies_reports_and_clears() {
|
||||||
|
let rules = MockExitRules::new();
|
||||||
|
let plan = ExitHostPlan {
|
||||||
|
interface: "tsun0".into(),
|
||||||
|
offer: vec![range()],
|
||||||
|
client: true,
|
||||||
|
overlay: vec![range()],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let report = rules.apply(&plan).await;
|
||||||
|
assert_eq!(report.offer[0].1, RuleOutcome::Applied);
|
||||||
|
assert_eq!(report.forwarding, Some(true));
|
||||||
|
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||||
|
assert_eq!(rules.installed(), Some(plan));
|
||||||
|
|
||||||
|
rules.set_forwarding(Some(false));
|
||||||
|
rules.fail_with(Some("denied".into()));
|
||||||
|
let report = rules
|
||||||
|
.apply(&ExitHostPlan {
|
||||||
|
interface: "tsun0".into(),
|
||||||
|
offer: vec![range()],
|
||||||
|
client: false,
|
||||||
|
overlay: Vec::new(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(report.forwarding, Some(false));
|
||||||
|
assert!(matches!(report.offer[0].1, RuleOutcome::Failed(_)));
|
||||||
|
assert_eq!(report.client, None);
|
||||||
|
|
||||||
|
rules.clear("tsun0").await;
|
||||||
|
assert_eq!(rules.installed(), None);
|
||||||
|
assert_eq!(rules.calls(), ["apply:tsun0", "apply:tsun0", "clear:tsun0"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
+176
-32
@@ -33,12 +33,13 @@ const CHAIN: &str = "INPUT";
|
|||||||
|
|
||||||
/// Fixed places `iptables` is installed. Never `PATH`: the agent is
|
/// Fixed places `iptables` is installed. Never `PATH`: the agent is
|
||||||
/// privileged and a directory a user controls must not decide what it runs.
|
/// privileged and a directory a user controls must not decide what it runs.
|
||||||
const IPTABLES_DIRECTORIES: [&str; 5] = [
|
const IPTABLES_DIRECTORIES: [&str; 6] = [
|
||||||
"/usr/sbin/iptables",
|
"/usr/sbin/iptables",
|
||||||
"/sbin/iptables",
|
"/sbin/iptables",
|
||||||
"/usr/bin/iptables",
|
"/usr/bin/iptables",
|
||||||
"/bin/iptables",
|
"/bin/iptables",
|
||||||
"/usr/local/sbin/iptables",
|
"/usr/local/sbin/iptables",
|
||||||
|
"/run/current-system/sw/bin/iptables",
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The first candidate that exists.
|
/// The first candidate that exists.
|
||||||
@@ -50,7 +51,7 @@ fn pick_iptables(exists: impl Fn(&str) -> bool) -> Option<&'static str> {
|
|||||||
|
|
||||||
/// What running `iptables` produced.
|
/// What running `iptables` produced.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
enum Ran {
|
pub(super) enum Ran {
|
||||||
/// There is no `iptables` to run.
|
/// There is no `iptables` to run.
|
||||||
Missing,
|
Missing,
|
||||||
/// It ran, and exited like this.
|
/// It ran, and exited like this.
|
||||||
@@ -63,32 +64,76 @@ enum Ran {
|
|||||||
|
|
||||||
/// Runs `iptables` with these arguments. A function value so the flow below
|
/// Runs `iptables` with these arguments. A function value so the flow below
|
||||||
/// can be tested without touching the host.
|
/// can be tested without touching the host.
|
||||||
type Run<'a> = &'a dyn Fn(&[String]) -> Ran;
|
pub(super) type Run<'a> = &'a dyn Fn(&[String]) -> Ran;
|
||||||
|
|
||||||
/// The match and target of the rule, without the chain or position.
|
/// The match and target of the rule, without the chain or position.
|
||||||
fn rule_spec(plan: &BroadcastRulesPlan) -> Vec<String> {
|
///
|
||||||
|
/// `comment` false leaves the tag off, for a kernel that has no `comment`
|
||||||
|
/// match; the rule is then recognised by its shape, see [`tagged_deletions`].
|
||||||
|
fn rule_spec(plan: &BroadcastRulesPlan, comment: bool) -> Vec<String> {
|
||||||
|
let range = plan.range.to_string();
|
||||||
|
let tag = plan.tag();
|
||||||
|
let mut words = vec!["-i", plan.interface.as_str(), "-p", "udp", "-s", &range];
|
||||||
|
if comment {
|
||||||
|
words.extend(["-m", "comment", "--comment", &tag]);
|
||||||
|
}
|
||||||
|
words.extend(["-j", "ACCEPT"]);
|
||||||
|
words.into_iter().map(str::to_string).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the kernel has the `comment` match, which a rule needs to carry
|
||||||
|
/// its tag. Asked of iptables itself: checking a rule that does not exist
|
||||||
|
/// fails either way, but only a missing match says so.
|
||||||
|
pub(super) fn comment_supported(run: Run<'_>) -> bool {
|
||||||
|
let probe = locked(
|
||||||
[
|
[
|
||||||
"-i",
|
"-t",
|
||||||
plan.interface.as_str(),
|
"filter",
|
||||||
"-p",
|
"-C",
|
||||||
"udp",
|
"FORWARD",
|
||||||
"-s",
|
|
||||||
&plan.range.to_string(),
|
|
||||||
"-m",
|
"-m",
|
||||||
"comment",
|
"comment",
|
||||||
"--comment",
|
"--comment",
|
||||||
&plan.tag(),
|
"tsunagi-probe",
|
||||||
"-j",
|
"-j",
|
||||||
"ACCEPT",
|
"ACCEPT",
|
||||||
]
|
]
|
||||||
.into_iter()
|
.map(str::to_string),
|
||||||
.map(str::to_string)
|
);
|
||||||
.collect()
|
match run(&probe) {
|
||||||
|
Ran::Exited {
|
||||||
|
success: false,
|
||||||
|
stderr,
|
||||||
|
..
|
||||||
|
} => !stderr.contains("No chain/target/match by that name"),
|
||||||
|
_ => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `iptables -S` words as option clauses: an option with its value, a negated
|
||||||
|
/// one with its `!`. It prints the options in its own order, not the one a
|
||||||
|
/// rule was written in, so rules are compared by their clauses, sorted.
|
||||||
|
fn clauses(words: &[String]) -> Vec<String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut at = 0;
|
||||||
|
while at < words.len() {
|
||||||
|
let take = if words[at] == "!" { 3 } else { 2 };
|
||||||
|
let end = (at + take).min(words.len());
|
||||||
|
out.push(words[at..end].join(" "));
|
||||||
|
at = end;
|
||||||
|
}
|
||||||
|
out.sort();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether two rules say the same thing, whatever order they list it in.
|
||||||
|
pub(super) fn same_rule(a: &[String], b: &[String]) -> bool {
|
||||||
|
clauses(a) == clauses(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Waits briefly for the xtables lock instead of failing when another tool
|
/// Waits briefly for the xtables lock instead of failing when another tool
|
||||||
/// holds it.
|
/// holds it.
|
||||||
fn locked(args: impl IntoIterator<Item = String>) -> Vec<String> {
|
pub(super) fn locked(args: impl IntoIterator<Item = String>) -> Vec<String> {
|
||||||
["-w", "5"]
|
["-w", "5"]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(str::to_string)
|
.map(str::to_string)
|
||||||
@@ -96,19 +141,19 @@ fn locked(args: impl IntoIterator<Item = String>) -> Vec<String> {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_args(plan: &BroadcastRulesPlan) -> Vec<String> {
|
fn check_args(plan: &BroadcastRulesPlan, comment: bool) -> Vec<String> {
|
||||||
locked(
|
locked(
|
||||||
["-C".to_string(), CHAIN.to_string()]
|
["-C".to_string(), CHAIN.to_string()]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(rule_spec(plan)),
|
.chain(rule_spec(plan, comment)),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn insert_args(plan: &BroadcastRulesPlan) -> Vec<String> {
|
fn insert_args(plan: &BroadcastRulesPlan, comment: bool) -> Vec<String> {
|
||||||
locked(
|
locked(
|
||||||
["-I".to_string(), CHAIN.to_string(), "1".to_string()]
|
["-I".to_string(), CHAIN.to_string(), "1".to_string()]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.chain(rule_spec(plan)),
|
.chain(rule_spec(plan, comment)),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +163,7 @@ fn list_args() -> Vec<String> {
|
|||||||
|
|
||||||
/// Splits one `iptables -S` line into words, honouring double quotes, which
|
/// Splits one `iptables -S` line into words, honouring double quotes, which
|
||||||
/// `iptables` puts around comments that need them.
|
/// `iptables` puts around comments that need them.
|
||||||
fn split_rule_line(line: &str) -> Vec<String> {
|
pub(super) fn split_rule_line(line: &str) -> Vec<String> {
|
||||||
let mut words = Vec::new();
|
let mut words = Vec::new();
|
||||||
let mut current = String::new();
|
let mut current = String::new();
|
||||||
let mut quoted = false;
|
let mut quoted = false;
|
||||||
@@ -147,8 +192,28 @@ fn split_rule_line(line: &str) -> Vec<String> {
|
|||||||
words
|
words
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a rule is the one this module writes for some range of the
|
||||||
|
/// interface the tag belongs to, with no comment on it.
|
||||||
|
fn is_uncommented_rule(tag: &str, rest: &[String]) -> bool {
|
||||||
|
let Some(interface) = tag.strip_prefix("tsunagi:") else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(range) = rest
|
||||||
|
.windows(2)
|
||||||
|
.find(|pair| pair[0] == "-s")
|
||||||
|
.map(|pair| pair[1].as_str())
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let ours: Vec<String> = ["-i", interface, "-p", "udp", "-s", range, "-j", "ACCEPT"]
|
||||||
|
.map(str::to_string)
|
||||||
|
.to_vec();
|
||||||
|
same_rule(&ours, rest)
|
||||||
|
}
|
||||||
|
|
||||||
/// The delete commands for every rule in an `iptables -S INPUT` listing that
|
/// The delete commands for every rule in an `iptables -S INPUT` listing that
|
||||||
/// carries exactly this tag. Anything else in the chain is left alone.
|
/// carries exactly this tag, or, with no `comment` match in the kernel, is
|
||||||
|
/// exactly the rule written for some range. Anything else is left alone.
|
||||||
fn tagged_deletions(listing: &str, tag: &str) -> Vec<Vec<String>> {
|
fn tagged_deletions(listing: &str, tag: &str) -> Vec<Vec<String>> {
|
||||||
listing
|
listing
|
||||||
.lines()
|
.lines()
|
||||||
@@ -162,7 +227,8 @@ fn tagged_deletions(listing: &str, tag: &str) -> Vec<Vec<String>> {
|
|||||||
}
|
}
|
||||||
let tagged = rest
|
let tagged = rest
|
||||||
.windows(2)
|
.windows(2)
|
||||||
.any(|pair| pair[0] == "--comment" && pair[1] == tag);
|
.any(|pair| pair[0] == "--comment" && pair[1] == tag)
|
||||||
|
|| is_uncommented_rule(tag, rest);
|
||||||
tagged.then(|| {
|
tagged.then(|| {
|
||||||
locked(
|
locked(
|
||||||
["-D".to_string(), CHAIN.to_string()]
|
["-D".to_string(), CHAIN.to_string()]
|
||||||
@@ -175,7 +241,7 @@ fn tagged_deletions(listing: &str, tag: &str) -> Vec<Vec<String>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A failure message with the likely fix for the likely cause.
|
/// A failure message with the likely fix for the likely cause.
|
||||||
fn failure(stderr: &str) -> String {
|
pub(super) fn failure(stderr: &str) -> String {
|
||||||
let text = stderr.trim();
|
let text = stderr.trim();
|
||||||
let lower = text.to_ascii_lowercase();
|
let lower = text.to_ascii_lowercase();
|
||||||
if lower.contains("permission denied") || lower.contains("must be root") {
|
if lower.contains("permission denied") || lower.contains("must be root") {
|
||||||
@@ -197,7 +263,8 @@ fn missing(plan: &BroadcastRulesPlan) -> String {
|
|||||||
|
|
||||||
/// Makes the firewall hold exactly one rule for this interface, the planned one.
|
/// Makes the firewall hold exactly one rule for this interface, the planned one.
|
||||||
fn apply_firewall(run: Run<'_>, plan: &BroadcastRulesPlan) -> RuleOutcome {
|
fn apply_firewall(run: Run<'_>, plan: &BroadcastRulesPlan) -> RuleOutcome {
|
||||||
let present = match run(&check_args(plan)) {
|
let comment = comment_supported(run);
|
||||||
|
let present = match run(&check_args(plan, comment)) {
|
||||||
Ran::Missing => return RuleOutcome::Failed(missing(plan)),
|
Ran::Missing => return RuleOutcome::Failed(missing(plan)),
|
||||||
Ran::Exited { success, .. } => success,
|
Ran::Exited { success, .. } => success,
|
||||||
};
|
};
|
||||||
@@ -227,7 +294,7 @@ fn apply_firewall(run: Run<'_>, plan: &BroadcastRulesPlan) -> RuleOutcome {
|
|||||||
return RuleOutcome::Failed(failure(&stderr));
|
return RuleOutcome::Failed(failure(&stderr));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
match run(&insert_args(plan)) {
|
match run(&insert_args(plan, comment)) {
|
||||||
Ran::Missing => RuleOutcome::Failed(missing(plan)),
|
Ran::Missing => RuleOutcome::Failed(missing(plan)),
|
||||||
Ran::Exited { success: true, .. } => RuleOutcome::Applied,
|
Ran::Exited { success: true, .. } => RuleOutcome::Applied,
|
||||||
Ran::Exited { stderr, .. } => RuleOutcome::Failed(failure(&stderr)),
|
Ran::Exited { stderr, .. } => RuleOutcome::Failed(failure(&stderr)),
|
||||||
@@ -261,8 +328,24 @@ fn clear_firewall(run: Run<'_>, interface: &str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Runs the real `iptables`.
|
/// Runs the real `iptables`.
|
||||||
fn run_iptables(args: &[String]) -> Ran {
|
pub(super) fn run_iptables(args: &[String]) -> Ran {
|
||||||
let Some(program) = pick_iptables(|path| std::path::Path::new(path).is_file()) else {
|
run_firewall(false, args)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn run_firewall(ipv6: bool, args: &[String]) -> Ran {
|
||||||
|
let v6_paths: Vec<_> = IPTABLES_DIRECTORIES
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.replace("iptables", "ip6tables"))
|
||||||
|
.collect();
|
||||||
|
let v6_program = v6_paths
|
||||||
|
.iter()
|
||||||
|
.find(|path| std::path::Path::new(path).is_file());
|
||||||
|
let program = if ipv6 {
|
||||||
|
v6_program.map(String::as_str)
|
||||||
|
} else {
|
||||||
|
pick_iptables(|path| std::path::Path::new(path).is_file())
|
||||||
|
};
|
||||||
|
let Some(program) = program else {
|
||||||
return Ran::Missing;
|
return Ran::Missing;
|
||||||
};
|
};
|
||||||
match std::process::Command::new(program).args(args).output() {
|
match std::process::Command::new(program).args(args).output() {
|
||||||
@@ -283,12 +366,18 @@ fn run_iptables(args: &[String]) -> Ran {
|
|||||||
/// The Linux implementation: netlink for the route, `iptables` for the rule.
|
/// The Linux implementation: netlink for the route, `iptables` for the rule.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct LinuxHostRules {
|
pub struct LinuxHostRules {
|
||||||
route: RouteHandle,
|
pub(super) route: RouteHandle,
|
||||||
|
/// Interface, sorted socket snapshot and whether exit routes committed.
|
||||||
|
pub(super) underlay_sockets:
|
||||||
|
std::sync::Mutex<Option<(String, Vec<super::linux_exit_mark::Listener>, bool)>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LinuxHostRules {
|
impl LinuxHostRules {
|
||||||
pub(crate) fn new(route: RouteHandle) -> Self {
|
pub(crate) fn new(route: RouteHandle) -> Self {
|
||||||
Self { route }
|
Self {
|
||||||
|
route,
|
||||||
|
underlay_sockets: std::sync::Mutex::new(None),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn set_route(&self, interface: String, source: Ipv4Addr) -> RuleOutcome {
|
async fn set_route(&self, interface: String, source: Ipv4Addr) -> RuleOutcome {
|
||||||
@@ -306,6 +395,10 @@ impl BroadcastHostRules for LinuxHostRules {
|
|||||||
"netlink+iptables"
|
"netlink+iptables"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn exit_rules(&self) -> Option<&dyn super::ExitHostRules> {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
|
||||||
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let route = self.set_route(plan.interface.clone(), plan.source).await;
|
let route = self.set_route(plan.interface.clone(), plan.source).await;
|
||||||
@@ -361,7 +454,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_rule_is_udp_only_from_the_overlay_range_on_this_interface() {
|
fn the_rule_is_udp_only_from_the_overlay_range_on_this_interface() {
|
||||||
let spec = words(&rule_spec(&plan()));
|
let spec = words(&rule_spec(&plan(), true));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
spec,
|
spec,
|
||||||
"-i tsun0 -p udp -s 10.13.37.0/24 -m comment --comment tsunagi:tsun0 -j ACCEPT"
|
"-i tsun0 -p udp -s 10.13.37.0/24 -m comment --comment tsunagi:tsun0 -j ACCEPT"
|
||||||
@@ -369,8 +462,8 @@ mod tests {
|
|||||||
// Nothing here may widen to other protocols or every source.
|
// Nothing here may widen to other protocols or every source.
|
||||||
assert!(spec.contains("-p udp"));
|
assert!(spec.contains("-p udp"));
|
||||||
assert!(!spec.contains("0.0.0.0/0"));
|
assert!(!spec.contains("0.0.0.0/0"));
|
||||||
assert!(words(&insert_args(&plan())).starts_with("-w 5 -I INPUT 1 -i tsun0"));
|
assert!(words(&insert_args(&plan(), true)).starts_with("-w 5 -I INPUT 1 -i tsun0"));
|
||||||
assert!(words(&check_args(&plan())).starts_with("-w 5 -C INPUT -i tsun0"));
|
assert!(words(&check_args(&plan(), true)).starts_with("-w 5 -C INPUT -i tsun0"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -404,6 +497,49 @@ mod tests {
|
|||||||
assert!(tagged_deletions("", "tsunagi:tsun0").is_empty());
|
assert!(tagged_deletions("", "tsunagi:tsun0").is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_kernel_without_the_comment_match_says_so_in_its_error() {
|
||||||
|
let answer = |stderr: &'static str| {
|
||||||
|
move |_: &[String]| Ran::Exited {
|
||||||
|
success: false,
|
||||||
|
stdout: String::new(),
|
||||||
|
stderr: stderr.to_string(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assert!(!comment_supported(&answer(
|
||||||
|
"iptables: No chain/target/match by that name."
|
||||||
|
)));
|
||||||
|
assert!(comment_supported(&answer(
|
||||||
|
"iptables: Bad rule (does a matching rule exist in that chain?)."
|
||||||
|
)));
|
||||||
|
assert!(comment_supported(&|_: &[String]| Ran::Missing));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_rule_written_without_a_comment_is_found_by_its_shape() {
|
||||||
|
// Listed the way iptables prints it: its own option order.
|
||||||
|
let listing = "\
|
||||||
|
-P INPUT ACCEPT
|
||||||
|
-A INPUT -s 10.13.37.0/24 -i tsun0 -p udp -j ACCEPT
|
||||||
|
-A INPUT -s 10.99.0.0/16 -i tsun0 -p udp -j ACCEPT
|
||||||
|
-A INPUT -s 10.13.37.0/24 -i tsun1 -p udp -j ACCEPT
|
||||||
|
-A INPUT -s 10.13.37.0/24 -i tsun0 -p udp -j DROP
|
||||||
|
-A INPUT -s 10.13.37.0/24 -i tsun0 -p tcp -j ACCEPT
|
||||||
|
";
|
||||||
|
let deletions = tagged_deletions(listing, "tsunagi:tsun0");
|
||||||
|
assert_eq!(deletions.len(), 2, "{deletions:?}");
|
||||||
|
assert!(words(&deletions[0]).ends_with("-s 10.13.37.0/24 -i tsun0 -p udp -j ACCEPT"));
|
||||||
|
assert!(words(&deletions[1]).contains("10.99.0.0/16"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn without_a_comment_the_rule_has_none() {
|
||||||
|
let with = words(&rule_spec(&plan(), true));
|
||||||
|
let without = words(&rule_spec(&plan(), false));
|
||||||
|
assert!(with.contains("-m comment --comment tsunagi:tsun0"));
|
||||||
|
assert_eq!(without, "-i tsun0 -p udp -s 10.13.37.0/24 -j ACCEPT");
|
||||||
|
}
|
||||||
|
|
||||||
/// A scripted `iptables`: answers by the leading verb, records every call.
|
/// A scripted `iptables`: answers by the leading verb, records every call.
|
||||||
struct Fake {
|
struct Fake {
|
||||||
calls: RefCell<Vec<String>>,
|
calls: RefCell<Vec<String>>,
|
||||||
@@ -424,6 +560,14 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn run(&self, args: &[String]) -> Ran {
|
fn run(&self, args: &[String]) -> Ran {
|
||||||
|
// The probe for the `comment` match: not part of what is tested.
|
||||||
|
if args.iter().any(|word| word == "tsunagi-probe") {
|
||||||
|
return Ran::Exited {
|
||||||
|
success: false,
|
||||||
|
stdout: String::new(),
|
||||||
|
stderr: "Bad rule".into(),
|
||||||
|
};
|
||||||
|
}
|
||||||
self.calls.borrow_mut().push(words(args));
|
self.calls.borrow_mut().push(words(args));
|
||||||
if self.missing {
|
if self.missing {
|
||||||
return Ran::Missing;
|
return Ran::Missing;
|
||||||
@@ -0,0 +1,968 @@
|
|||||||
|
//! Exit-node host rules on Linux: `iptables` for the offering side, policy
|
||||||
|
//! routing over netlink for the using side.
|
||||||
|
//!
|
||||||
|
//! # Offering
|
||||||
|
//!
|
||||||
|
//! For every network that offers this agent as an exit node, three rules,
|
||||||
|
//! selected by that network's range and carrying the tag
|
||||||
|
//! `tsunagi-exit:<if>:<range>`:
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! -t nat POSTROUTING -s <range> ! -o <if> -j MASQUERADE
|
||||||
|
//! -t filter FORWARD -i <if> -s <range> ! -o <if> -j ACCEPT
|
||||||
|
//! -t filter FORWARD -o <if> -d <range> -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! `! -o <if>` is the egress without naming it: whatever interface the
|
||||||
|
//! default route uses, now or after it changes. Kernel forwarding is only
|
||||||
|
//! *read*. Turning it on changes how the whole host behaves, which is the
|
||||||
|
//! owner's decision, so when it is off the rules are installed anyway and the
|
||||||
|
//! report says so.
|
||||||
|
//!
|
||||||
|
//! # Using
|
||||||
|
//!
|
||||||
|
//! Policy routing, with no `/1` routes and nothing in the main table:
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! table 0x7473: default dev <if>
|
||||||
|
//! 5205: from all fwmark 0x40000000/0x40000000 lookup main
|
||||||
|
//! 5206: from all uidrange <euid>-<euid> lookup main
|
||||||
|
//! 5290: from all lookup main suppress_prefixlength 0
|
||||||
|
//! 5300: from all lookup 0x7473
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! The first two keep the agent's *own* sockets and marked replies off the tunnel: its QUIC, relay,
|
||||||
|
//! DHT and DNS traffic would otherwise be routed into the interface it is
|
||||||
|
//! carrying, a loop. The specific-route rule lets the LAN, another
|
||||||
|
//! VPN, a tunnel to somewhere else — keep working, because only the default
|
||||||
|
//! route is suppressed. Mark/UID bypass precedes Tailscale; application rules follow it.
|
||||||
|
//!
|
||||||
|
//! The UID rule exempts a *user id*, so it is only right when the agent has
|
||||||
|
//! one of its own, as the packaged service does. An agent started from a login
|
||||||
|
//! session would take that user's own applications out of the tunnel with it,
|
||||||
|
//! and the exit node would silently do nothing for them. That is refused, not
|
||||||
|
//! guessed at: see [`client_refusal`].
|
||||||
|
|
||||||
|
use crate::BoxFuture;
|
||||||
|
use crate::state::Ipv4Range;
|
||||||
|
|
||||||
|
use super::RuleOutcome;
|
||||||
|
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules, exit_tag, exit_tag_prefix};
|
||||||
|
use super::linux::{
|
||||||
|
LinuxHostRules, Ran, Run, comment_supported, failure, locked, run_firewall, run_iptables,
|
||||||
|
same_rule, split_rule_line,
|
||||||
|
};
|
||||||
|
use super::linux_exit_mark;
|
||||||
|
|
||||||
|
/// The chains the offering rules live in: `(table, chain)`.
|
||||||
|
const CHAINS: [(&str, &str); 2] = [("nat", "POSTROUTING"), ("filter", "FORWARD")];
|
||||||
|
|
||||||
|
/// One firewall rule: where it goes, and its match and target.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct Rule {
|
||||||
|
table: &'static str,
|
||||||
|
chain: &'static str,
|
||||||
|
spec: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned(words: &[&str]) -> Vec<String> {
|
||||||
|
words.iter().map(|word| word.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The three rules of one offered range.
|
||||||
|
///
|
||||||
|
/// Each carries a comment naming its interface and range, which is how it is
|
||||||
|
/// found again. A kernel without the `comment` match (small router builds
|
||||||
|
/// leave it out) cannot take that, so `comment` false leaves it off and the
|
||||||
|
/// rules are recognised by their shape instead; see [`tagged_rules`].
|
||||||
|
fn offer_rules(interface: &str, range: &Ipv4Range, comment: bool) -> Vec<Rule> {
|
||||||
|
let range_text = range.to_string();
|
||||||
|
let tag = exit_tag(interface, range);
|
||||||
|
let comment: Vec<String> = if comment {
|
||||||
|
owned(&["-m", "comment", "--comment", tag.as_str()])
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
let spec = |head: &[&str], tail: &[&str]| -> Vec<String> {
|
||||||
|
owned(head)
|
||||||
|
.into_iter()
|
||||||
|
.chain(comment.iter().cloned())
|
||||||
|
.chain(owned(tail))
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
vec![
|
||||||
|
Rule {
|
||||||
|
table: "nat",
|
||||||
|
chain: "POSTROUTING",
|
||||||
|
spec: spec(
|
||||||
|
&["-s", &range_text, "!", "-o", interface],
|
||||||
|
&["-j", "MASQUERADE"],
|
||||||
|
),
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
table: "filter",
|
||||||
|
chain: "FORWARD",
|
||||||
|
spec: spec(
|
||||||
|
&["-i", interface, "-s", &range_text, "!", "-o", interface],
|
||||||
|
&["-j", "ACCEPT"],
|
||||||
|
),
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
table: "filter",
|
||||||
|
chain: "FORWARD",
|
||||||
|
spec: spec(
|
||||||
|
&[
|
||||||
|
"-o",
|
||||||
|
interface,
|
||||||
|
"-d",
|
||||||
|
&range_text,
|
||||||
|
"-m",
|
||||||
|
"conntrack",
|
||||||
|
"--ctstate",
|
||||||
|
"RELATED,ESTABLISHED",
|
||||||
|
],
|
||||||
|
&["-j", "ACCEPT"],
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_args(rule: &Rule) -> Vec<String> {
|
||||||
|
locked(
|
||||||
|
owned(&["-t", rule.table, "-C", rule.chain])
|
||||||
|
.into_iter()
|
||||||
|
.chain(rule.spec.iter().cloned()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_args(rule: &Rule) -> Vec<String> {
|
||||||
|
locked(
|
||||||
|
owned(&["-t", rule.table, "-I", rule.chain, "1"])
|
||||||
|
.into_iter()
|
||||||
|
.chain(rule.spec.iter().cloned()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_args(table: &str, chain: &str) -> Vec<String> {
|
||||||
|
locked(owned(&["-t", table, "-S", chain]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A rule found in a listing whose comment starts with our prefix.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct Found {
|
||||||
|
/// The whole tag.
|
||||||
|
tag: String,
|
||||||
|
/// The words after `-A <chain>`, which is what `-D` needs.
|
||||||
|
rest: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every rule in an `iptables -S <chain>` listing that is ours: carrying a
|
||||||
|
/// tag that starts with `prefix`, or, on a kernel with no `comment` match,
|
||||||
|
/// being exactly one of the three rules this module writes for some range.
|
||||||
|
/// Anything else in the chain is left alone.
|
||||||
|
fn tagged_rules(listing: &str, chain: &str, prefix: &str) -> Vec<Found> {
|
||||||
|
// `tsunagi-exit:<interface>:`
|
||||||
|
let interface = prefix
|
||||||
|
.strip_prefix("tsunagi-exit:")
|
||||||
|
.and_then(|rest| rest.strip_suffix(':'))
|
||||||
|
.unwrap_or_default();
|
||||||
|
listing
|
||||||
|
.lines()
|
||||||
|
.filter_map(|line| {
|
||||||
|
let words = split_rule_line(line);
|
||||||
|
let [append, found_chain, rest @ ..] = words.as_slice() else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
if append != "-A" || found_chain != chain {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let tag = rest
|
||||||
|
.windows(2)
|
||||||
|
.find(|pair| pair[0] == "--comment" && pair[1].starts_with(prefix))
|
||||||
|
.map(|pair| pair[1].clone())
|
||||||
|
.or_else(|| uncommented_tag(interface, chain, rest))?;
|
||||||
|
Some(Found {
|
||||||
|
tag,
|
||||||
|
rest: rest.to_vec(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tag a rule would have carried, when it is one of ours written without
|
||||||
|
/// a comment: its words are those of the rule for the range it names.
|
||||||
|
fn uncommented_tag(interface: &str, chain: &str, rest: &[String]) -> Option<String> {
|
||||||
|
if interface.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let range: Ipv4Range = rest
|
||||||
|
.windows(2)
|
||||||
|
.find(|pair| pair[0] == "-s" || pair[0] == "-d")
|
||||||
|
.and_then(|pair| pair[1].parse().ok())?;
|
||||||
|
offer_rules(interface, &range, false)
|
||||||
|
.iter()
|
||||||
|
.any(|rule| rule.chain == chain && same_rule(&rule.spec, rest))
|
||||||
|
.then(|| exit_tag(interface, &range))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn delete_args(table: &str, chain: &str, found: &Found) -> Vec<String> {
|
||||||
|
locked(
|
||||||
|
owned(&["-t", table, "-D", chain])
|
||||||
|
.into_iter()
|
||||||
|
.chain(found.rest.iter().cloned()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn missing_iptables(range: &Ipv4Range, interface: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"iptables not found; install it (the iptables-nft package is enough), or masquerade \
|
||||||
|
{range} out of every interface but `{interface}` and forward it yourself"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads one chain, or says why not.
|
||||||
|
fn read_chain(run: Run<'_>, table: &str, chain: &str) -> Result<String, Failure> {
|
||||||
|
match run(&list_args(table, chain)) {
|
||||||
|
Ran::Missing => Err(Failure::Missing),
|
||||||
|
Ran::Exited {
|
||||||
|
success: true,
|
||||||
|
stdout,
|
||||||
|
..
|
||||||
|
} => Ok(stdout),
|
||||||
|
Ran::Exited { stderr, .. } => Err(Failure::Failed(failure(&stderr))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Failure {
|
||||||
|
Missing,
|
||||||
|
Failed(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes found rules; the first failure ends it.
|
||||||
|
fn delete_all(
|
||||||
|
run: Run<'_>,
|
||||||
|
table: &str,
|
||||||
|
chain: &str,
|
||||||
|
found: &[Found],
|
||||||
|
keep: impl Fn(&Found) -> bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
for rule in found.iter().filter(|rule| !keep(rule)) {
|
||||||
|
if let Ran::Exited {
|
||||||
|
success: false,
|
||||||
|
stderr,
|
||||||
|
..
|
||||||
|
} = run(&delete_args(table, chain, rule))
|
||||||
|
{
|
||||||
|
return Err(failure(&stderr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes the firewall hold exactly the offering rules of these ranges for the
|
||||||
|
/// interface, and no others of ours.
|
||||||
|
fn apply_offer(
|
||||||
|
run: Run<'_>,
|
||||||
|
interface: &str,
|
||||||
|
ranges: &[Ipv4Range],
|
||||||
|
) -> Vec<(Ipv4Range, RuleOutcome)> {
|
||||||
|
let fail_all = |reason: String| -> Vec<(Ipv4Range, RuleOutcome)> {
|
||||||
|
ranges
|
||||||
|
.iter()
|
||||||
|
.map(|range| (*range, RuleOutcome::Failed(reason.clone())))
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let prefix = exit_tag_prefix(interface);
|
||||||
|
let wanted: Vec<String> = ranges.iter().map(|r| exit_tag(interface, r)).collect();
|
||||||
|
let comment = comment_supported(run);
|
||||||
|
|
||||||
|
// What is there now, per chain.
|
||||||
|
let mut present: Vec<(&str, &str, Vec<Found>)> = Vec::new();
|
||||||
|
for (table, chain) in CHAINS {
|
||||||
|
match read_chain(run, table, chain) {
|
||||||
|
Ok(listing) => present.push((table, chain, tagged_rules(&listing, chain, &prefix))),
|
||||||
|
Err(Failure::Missing) => {
|
||||||
|
return match ranges.first() {
|
||||||
|
Some(range) => fail_all(missing_iptables(range, interface)),
|
||||||
|
None => Vec::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Err(Failure::Failed(reason)) => return fail_all(reason),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rules for a range no longer offered, or left by an earlier run.
|
||||||
|
for (table, chain, found) in &present {
|
||||||
|
if let Err(reason) = delete_all(run, table, chain, found, |rule| wanted.contains(&rule.tag))
|
||||||
|
{
|
||||||
|
return fail_all(reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ranges
|
||||||
|
.iter()
|
||||||
|
.map(|range| {
|
||||||
|
let rules = offer_rules(interface, range, comment);
|
||||||
|
let tag = exit_tag(interface, range);
|
||||||
|
let in_place = rules
|
||||||
|
.iter()
|
||||||
|
.all(|rule| matches!(run(&check_args(rule)), Ran::Exited { success: true, .. }))
|
||||||
|
&& present.iter().all(|(_, chain, found)| {
|
||||||
|
let have = found.iter().filter(|rule| rule.tag == tag).count();
|
||||||
|
have == rules.iter().filter(|rule| rule.chain == *chain).count()
|
||||||
|
});
|
||||||
|
if in_place {
|
||||||
|
return (*range, RuleOutcome::Applied);
|
||||||
|
}
|
||||||
|
// Start this range from a clean slate: a half-installed set, or
|
||||||
|
// one that differs from the plan, is replaced as a whole.
|
||||||
|
for (table, chain, found) in &present {
|
||||||
|
if let Err(reason) = delete_all(run, table, chain, found, |rule| rule.tag != tag) {
|
||||||
|
return (*range, RuleOutcome::Failed(reason));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for rule in &rules {
|
||||||
|
match run(&insert_args(rule)) {
|
||||||
|
Ran::Missing => {
|
||||||
|
return (
|
||||||
|
*range,
|
||||||
|
RuleOutcome::Failed(missing_iptables(range, interface)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ran::Exited { success: true, .. } => {}
|
||||||
|
Ran::Exited { stderr, .. } => {
|
||||||
|
return (*range, RuleOutcome::Failed(failure(&stderr)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(*range, RuleOutcome::Applied)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes every offering rule of ours for the interface. Best effort.
|
||||||
|
fn clear_offer(run: Run<'_>, interface: &str) {
|
||||||
|
let prefix = exit_tag_prefix(interface);
|
||||||
|
for (table, chain) in CHAINS {
|
||||||
|
let Ok(listing) = read_chain(run, table, chain) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let found = tagged_rules(&listing, chain, &prefix);
|
||||||
|
if let Err(reason) = delete_all(run, table, chain, &found, |_| false) {
|
||||||
|
tracing::warn!(
|
||||||
|
interface,
|
||||||
|
"cannot remove an exit node firewall rule: {reason}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The kernel's forwarding switch for packets arriving on the interface,
|
||||||
|
/// read from the text of the sysctl files. Never written.
|
||||||
|
fn forwarding_state(read: impl Fn(&str) -> Option<String>, interface: &str) -> Option<bool> {
|
||||||
|
let flag = |text: String| match text.trim() {
|
||||||
|
"1" => Some(true),
|
||||||
|
"0" => Some(false),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
// The name is derived here, but it ends up in a path.
|
||||||
|
if !interface.is_empty() && !interface.contains(['/', '\0']) && interface != ".." {
|
||||||
|
let per_interface = format!("/proc/sys/net/ipv4/conf/{interface}/forwarding");
|
||||||
|
if let Some(state) = read(&per_interface).and_then(flag) {
|
||||||
|
return Some(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
read("/proc/sys/net/ipv4/ip_forward").and_then(flag)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_sysctl(path: &str) -> Option<String> {
|
||||||
|
std::fs::read_to_string(path).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_kernel_rpf(overlay: &str) -> Result<(), String> {
|
||||||
|
let directory = "/proc/sys/net/ipv4/conf";
|
||||||
|
let value = |name: &str, setting: &str| -> Result<u32, String> {
|
||||||
|
read_sysctl(&format!("{directory}/{name}/{setting}"))
|
||||||
|
.and_then(|s| s.trim().parse().ok())
|
||||||
|
.ok_or_else(|| format!("cannot check {name}/{setting} before installing exit routes"))
|
||||||
|
};
|
||||||
|
let mut interfaces = Vec::new();
|
||||||
|
for entry in std::fs::read_dir(directory).map_err(|err| err.to_string())? {
|
||||||
|
let entry = entry.map_err(|err| err.to_string())?;
|
||||||
|
let name = entry.file_name().to_string_lossy().into_owned();
|
||||||
|
if name != "all" && name != "default" && name != "lo" && name != overlay {
|
||||||
|
interfaces.push((
|
||||||
|
name.clone(),
|
||||||
|
value(&name, "rp_filter")?,
|
||||||
|
value(&name, "src_valid_mark")?,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
linux_exit_mark::check_kernel_rpf(
|
||||||
|
value("all", "rp_filter")?,
|
||||||
|
value("all", "src_valid_mark")?,
|
||||||
|
&interfaces,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The effective user id from the text of `/proc/self/status`.
|
||||||
|
fn parse_euid(status: &str) -> Option<u32> {
|
||||||
|
status
|
||||||
|
.lines()
|
||||||
|
.find_map(|line| line.strip_prefix("Uid:"))
|
||||||
|
.and_then(|rest| rest.split_whitespace().nth(1))
|
||||||
|
.and_then(|effective| effective.parse().ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why the using side must not be installed for this process, if it must not.
|
||||||
|
///
|
||||||
|
/// The bypass rule exempts this process's *user id* from the tunnel. That is
|
||||||
|
/// right for a service with an id of its own and wrong for a process started
|
||||||
|
/// from somebody's login session, which shares its id with every application
|
||||||
|
/// that person runs. A login session is recognised by `XDG_RUNTIME_DIR`,
|
||||||
|
/// which `systemd --user` and the login managers set and a system service
|
||||||
|
/// does not. Crude on purpose: refusing a service that was started oddly is
|
||||||
|
/// a message, and exempting a user's applications is a silent failure.
|
||||||
|
fn client_refusal(xdg_runtime_dir: Option<&str>) -> Option<String> {
|
||||||
|
xdg_runtime_dir.filter(|dir| !dir.is_empty()).map(|_| {
|
||||||
|
"the exit node needs the agent to run as a system service with a user of its own: \
|
||||||
|
this agent was started from a login session, so routing everything through the \
|
||||||
|
overlay would take that user's own applications out of the tunnel with it"
|
||||||
|
.to_string()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LinuxHostRules {
|
||||||
|
async fn blocking<T: Send + 'static>(
|
||||||
|
work: impl FnOnce() -> T + Send + 'static,
|
||||||
|
) -> Result<T, String> {
|
||||||
|
tokio::task::spawn_blocking(work)
|
||||||
|
.await
|
||||||
|
.map_err(|err| format!("the task failed: {err}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn apply_client(&self, interface: &str) -> RuleOutcome {
|
||||||
|
let xdg = std::env::var("XDG_RUNTIME_DIR").ok();
|
||||||
|
if let Some(reason) = client_refusal(xdg.as_deref()) {
|
||||||
|
// Whatever an earlier run left must not stay in force.
|
||||||
|
let _ = self.clear_client(interface).await;
|
||||||
|
return RuleOutcome::Failed(reason);
|
||||||
|
}
|
||||||
|
let Some(euid) = std::fs::read_to_string("/proc/self/status")
|
||||||
|
.ok()
|
||||||
|
.and_then(|status| parse_euid(&status))
|
||||||
|
else {
|
||||||
|
return RuleOutcome::Failed("cannot tell which user this agent runs as".to_string());
|
||||||
|
};
|
||||||
|
let installed = self
|
||||||
|
.underlay_sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(name, _, routed)| name == interface && *routed);
|
||||||
|
if installed {
|
||||||
|
// A failed socket refresh must never remove an active exit route.
|
||||||
|
return self
|
||||||
|
.refresh_sockets(interface)
|
||||||
|
.await
|
||||||
|
.unwrap_or(RuleOutcome::Applied);
|
||||||
|
}
|
||||||
|
if let Err(reason) = self.clear_client(interface).await {
|
||||||
|
return RuleOutcome::Failed(reason);
|
||||||
|
}
|
||||||
|
let name = interface.to_string();
|
||||||
|
let prepared = Self::blocking(move || {
|
||||||
|
check_kernel_rpf(&name)?;
|
||||||
|
linux_exit_mark::install(
|
||||||
|
&run_firewall,
|
||||||
|
&name,
|
||||||
|
euid,
|
||||||
|
std::path::Path::new("/proc/sys/net/ipv6").is_dir(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match prepared {
|
||||||
|
Ok(Ok(sockets)) => {
|
||||||
|
*self
|
||||||
|
.underlay_sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner()) = Some((interface.into(), sockets, false));
|
||||||
|
}
|
||||||
|
Ok(Err(reason)) | Err(reason) => return RuleOutcome::Failed(reason),
|
||||||
|
}
|
||||||
|
let route = self.route.clone();
|
||||||
|
let name = interface.to_string();
|
||||||
|
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid)).await {
|
||||||
|
Ok(Ok(())) => RuleOutcome::Applied,
|
||||||
|
Ok(Err(err)) => RuleOutcome::Failed(err.to_string()),
|
||||||
|
Err(reason) => RuleOutcome::Failed(reason),
|
||||||
|
};
|
||||||
|
if let RuleOutcome::Failed(reason) = outcome {
|
||||||
|
let reason = match self.clear_client(interface).await {
|
||||||
|
Ok(()) => reason,
|
||||||
|
Err(cleanup) => format!("{reason}; cannot roll back exit rules: {cleanup}"),
|
||||||
|
};
|
||||||
|
RuleOutcome::Failed(reason)
|
||||||
|
} else {
|
||||||
|
if let Some((_, _, routed)) = self
|
||||||
|
.underlay_sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.as_mut()
|
||||||
|
{
|
||||||
|
*routed = true;
|
||||||
|
}
|
||||||
|
outcome
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn clear_client(&self, interface: &str) -> Result<(), String> {
|
||||||
|
let route = self.route.clone();
|
||||||
|
Self::blocking(move || route.clear_exit_client())
|
||||||
|
.await?
|
||||||
|
.map_err(|err| err.to_string())?;
|
||||||
|
// Route removal must precede removing reply protection.
|
||||||
|
let name = interface.to_string();
|
||||||
|
Self::blocking(move || {
|
||||||
|
linux_exit_mark::clear(
|
||||||
|
&run_firewall,
|
||||||
|
&name,
|
||||||
|
std::path::Path::new("/proc/sys/net/ipv6").is_dir(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await??;
|
||||||
|
*self
|
||||||
|
.underlay_sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner()) = None;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn refresh_sockets(&self, interface: &str) -> Option<RuleOutcome> {
|
||||||
|
let previous = self
|
||||||
|
.underlay_sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.clone();
|
||||||
|
if previous
|
||||||
|
.as_ref()
|
||||||
|
.is_none_or(|(name, _, routed)| name != interface || !routed)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let name = interface.to_string();
|
||||||
|
let work_name = name.clone();
|
||||||
|
let result = Self::blocking(move || {
|
||||||
|
let uid = std::fs::read_to_string("/proc/self/status")
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| parse_euid(&s))
|
||||||
|
.ok_or("cannot read agent UID")?;
|
||||||
|
check_kernel_rpf(&work_name)?;
|
||||||
|
let v6 = std::path::Path::new("/proc/sys/net/ipv6").is_dir();
|
||||||
|
let sockets = linux_exit_mark::local_sockets(uid, v6)?;
|
||||||
|
if previous
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(name, old, _)| name == &work_name && old == &sockets)
|
||||||
|
{
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
linux_exit_mark::refresh(&run_firewall, &work_name, v6, &sockets)?;
|
||||||
|
Ok(Some(sockets))
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match result {
|
||||||
|
Ok(Ok(None)) => None,
|
||||||
|
Ok(Ok(Some(sockets))) => {
|
||||||
|
*self
|
||||||
|
.underlay_sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner()) = Some((name, sockets, true));
|
||||||
|
Some(RuleOutcome::Applied)
|
||||||
|
}
|
||||||
|
Ok(Err(reason)) | Err(reason) => Some(RuleOutcome::Failed(reason)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExitHostRules for LinuxHostRules {
|
||||||
|
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
if plan.client {
|
||||||
|
self.refresh_sockets(&plan.interface).await
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let interface = plan.interface.clone();
|
||||||
|
let ranges = plan.offer.clone();
|
||||||
|
let offer = {
|
||||||
|
let (job_interface, job_ranges) = (interface.clone(), ranges.clone());
|
||||||
|
Self::blocking(move || apply_offer(&run_iptables, &job_interface, &job_ranges))
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|reason| {
|
||||||
|
ranges
|
||||||
|
.iter()
|
||||||
|
.map(|range| (*range, RuleOutcome::Failed(reason.clone())))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let forwarding = if ranges.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
forwarding_state(read_sysctl, &interface)
|
||||||
|
};
|
||||||
|
let client = if plan.client {
|
||||||
|
Some(self.apply_client(&interface).await)
|
||||||
|
} else {
|
||||||
|
if let Err(reason) = self.clear_client(&interface).await {
|
||||||
|
tracing::warn!(%reason, "cannot remove exit-client rules");
|
||||||
|
}
|
||||||
|
None
|
||||||
|
};
|
||||||
|
ExitHostReport {
|
||||||
|
offer,
|
||||||
|
forwarding,
|
||||||
|
client,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let name = interface.to_string();
|
||||||
|
let _ = Self::blocking(move || clear_offer(&run_iptables, &name)).await;
|
||||||
|
if let Err(reason) = self.clear_client(interface).await {
|
||||||
|
tracing::warn!(%reason, "cannot remove exit-client rules");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::cell::RefCell;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn range() -> Ipv4Range {
|
||||||
|
"10.13.37.0/24".parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn words(args: &[String]) -> String {
|
||||||
|
args.join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_rules_masquerade_the_range_out_of_every_other_interface_and_forward_it() {
|
||||||
|
let rules = offer_rules("tsun0", &range(), true);
|
||||||
|
assert_eq!(rules.len(), 3);
|
||||||
|
assert_eq!(
|
||||||
|
words(&rules[0].spec),
|
||||||
|
"-s 10.13.37.0/24 ! -o tsun0 -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j MASQUERADE"
|
||||||
|
);
|
||||||
|
assert_eq!((rules[0].table, rules[0].chain), ("nat", "POSTROUTING"));
|
||||||
|
assert_eq!(
|
||||||
|
words(&rules[1].spec),
|
||||||
|
"-i tsun0 -s 10.13.37.0/24 ! -o tsun0 -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j ACCEPT"
|
||||||
|
);
|
||||||
|
assert_eq!((rules[1].table, rules[1].chain), ("filter", "FORWARD"));
|
||||||
|
assert_eq!(
|
||||||
|
words(&rules[2].spec),
|
||||||
|
"-o tsun0 -d 10.13.37.0/24 -m conntrack --ctstate RELATED,ESTABLISHED -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j ACCEPT"
|
||||||
|
);
|
||||||
|
// Nothing may widen to every source or to the other direction.
|
||||||
|
for rule in &rules {
|
||||||
|
assert!(!words(&rule.spec).contains("0.0.0.0/0"));
|
||||||
|
}
|
||||||
|
assert!(words(&insert_args(&rules[1])).starts_with("-w 5 -t filter -I FORWARD 1 -i tsun0"));
|
||||||
|
assert!(words(&check_args(&rules[0])).starts_with("-w 5 -t nat -C POSTROUTING -s"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_rules_with_our_tag_for_this_interface_are_selected() {
|
||||||
|
let listing = "\
|
||||||
|
-P FORWARD DROP
|
||||||
|
-A FORWARD -i tsun0 -s 10.13.37.0/24 ! -o tsun0 -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j ACCEPT
|
||||||
|
-A FORWARD -i tsun1 -m comment --comment tsunagi-exit:tsun1:10.99.0.0/24 -j ACCEPT
|
||||||
|
-A FORWARD -i tsun01 -m comment --comment tsunagi-exit:tsun01:10.5.0.0/24 -j ACCEPT
|
||||||
|
-A FORWARD -m comment --comment \"allow tsunagi-exit:tsun0:x\" -j ACCEPT
|
||||||
|
-A FORWARD -m comment --comment tsunagi:tsun0 -j ACCEPT
|
||||||
|
-A INPUT -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j ACCEPT
|
||||||
|
-A FORWARD -j ACCEPT
|
||||||
|
";
|
||||||
|
let found = tagged_rules(listing, "FORWARD", &exit_tag_prefix("tsun0"));
|
||||||
|
assert_eq!(found.len(), 1, "{found:?}");
|
||||||
|
assert_eq!(found[0].tag, "tsunagi-exit:tsun0:10.13.37.0/24");
|
||||||
|
assert_eq!(
|
||||||
|
words(&delete_args("filter", "FORWARD", &found[0])),
|
||||||
|
"-w 5 -t filter -D FORWARD -i tsun0 -s 10.13.37.0/24 ! -o tsun0 -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j ACCEPT"
|
||||||
|
);
|
||||||
|
assert!(tagged_rules("", "FORWARD", "tsunagi-exit:tsun0:").is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A scripted `iptables` that remembers which rules it was given.
|
||||||
|
struct Fake {
|
||||||
|
calls: RefCell<Vec<String>>,
|
||||||
|
/// Rules present, as `-S` lines per `(table, chain)`.
|
||||||
|
listing: RefCell<Vec<(String, String)>>,
|
||||||
|
missing: bool,
|
||||||
|
check_ok: bool,
|
||||||
|
/// A kernel with no `comment` match, as small router builds have.
|
||||||
|
no_comment: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fake {
|
||||||
|
fn new(check_ok: bool) -> Self {
|
||||||
|
Self {
|
||||||
|
calls: RefCell::new(Vec::new()),
|
||||||
|
listing: RefCell::new(Vec::new()),
|
||||||
|
missing: false,
|
||||||
|
check_ok,
|
||||||
|
no_comment: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_rule(self, table: &str, line: &str) -> Self {
|
||||||
|
self.listing
|
||||||
|
.borrow_mut()
|
||||||
|
.push((table.to_string(), line.to_string()));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, args: &[String]) -> Ran {
|
||||||
|
if self.missing {
|
||||||
|
return Ran::Missing;
|
||||||
|
}
|
||||||
|
let line = args.join(" ");
|
||||||
|
self.calls.borrow_mut().push(line.clone());
|
||||||
|
let table = args
|
||||||
|
.iter()
|
||||||
|
.position(|word| word == "-t")
|
||||||
|
.map(|at| args[at + 1].clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let ok = |stdout: String| Ran::Exited {
|
||||||
|
success: true,
|
||||||
|
stdout,
|
||||||
|
stderr: String::new(),
|
||||||
|
};
|
||||||
|
if self.no_comment && line.contains("-m comment") {
|
||||||
|
return Ran::Exited {
|
||||||
|
success: false,
|
||||||
|
stdout: String::new(),
|
||||||
|
stderr: "iptables: No chain/target/match by that name.".to_string(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if line.contains(" -S ") {
|
||||||
|
let listing: Vec<String> = self
|
||||||
|
.listing
|
||||||
|
.borrow()
|
||||||
|
.iter()
|
||||||
|
.filter(|(t, _)| *t == table)
|
||||||
|
.map(|(_, l)| l.clone())
|
||||||
|
.collect();
|
||||||
|
return ok(listing.join("\n"));
|
||||||
|
}
|
||||||
|
if line.contains(" -C ") {
|
||||||
|
return Ran::Exited {
|
||||||
|
success: self.check_ok,
|
||||||
|
stdout: String::new(),
|
||||||
|
stderr: String::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
ok(String::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verbs(&self, verb: &str) -> Vec<String> {
|
||||||
|
self.calls
|
||||||
|
.borrow()
|
||||||
|
.iter()
|
||||||
|
.filter(|call| call.contains(&format!(" {verb} ")))
|
||||||
|
.cloned()
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_kernel_without_the_comment_match_gets_the_rules_without_comments() {
|
||||||
|
let mut fake = Fake::new(false);
|
||||||
|
fake.no_comment = true;
|
||||||
|
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||||
|
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||||
|
let inserted = fake.verbs("-I");
|
||||||
|
assert_eq!(inserted.len(), 3, "{inserted:?}");
|
||||||
|
assert!(
|
||||||
|
inserted.iter().all(|call| !call.contains("comment")),
|
||||||
|
"{inserted:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rules_written_without_a_comment_are_ours_and_are_removed_with_them() {
|
||||||
|
// The way iptables prints them: its own option order.
|
||||||
|
let listing = "\
|
||||||
|
-P FORWARD ACCEPT
|
||||||
|
-A FORWARD -s 10.13.37.0/24 -i tsun0 ! -o tsun0 -j ACCEPT
|
||||||
|
-A FORWARD -d 10.13.37.0/24 -o tsun0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
|
||||||
|
-A FORWARD -i tsun0 -j ACCEPT
|
||||||
|
-A FORWARD -s 10.13.37.0/24 -i tsun1 ! -o tsun1 -j ACCEPT
|
||||||
|
";
|
||||||
|
let found = tagged_rules(listing, "FORWARD", &exit_tag_prefix("tsun0"));
|
||||||
|
assert_eq!(found.len(), 2, "{found:?}");
|
||||||
|
assert!(
|
||||||
|
found
|
||||||
|
.iter()
|
||||||
|
.all(|rule| rule.tag == exit_tag("tsun0", &range()))
|
||||||
|
);
|
||||||
|
let nat = "-A POSTROUTING -s 10.13.37.0/24 ! -o tsun0 -j MASQUERADE\n";
|
||||||
|
assert_eq!(
|
||||||
|
tagged_rules(nat, "POSTROUTING", &exit_tag_prefix("tsun0")).len(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_fresh_host_gets_the_three_rules() {
|
||||||
|
let fake = Fake::new(false);
|
||||||
|
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||||
|
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||||
|
let inserted = fake.verbs("-I");
|
||||||
|
assert_eq!(inserted.len(), 3, "{inserted:?}");
|
||||||
|
assert!(inserted[0].contains("-t nat -I POSTROUTING 1"));
|
||||||
|
assert!(fake.verbs("-D").is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rules_already_in_place_are_left_alone() {
|
||||||
|
let tag = exit_tag("tsun0", &range());
|
||||||
|
let fake = Fake::new(true)
|
||||||
|
.with_rule(
|
||||||
|
"nat",
|
||||||
|
&format!("-A POSTROUTING -s 10.13.37.0/24 ! -o tsun0 -m comment --comment {tag} -j MASQUERADE"),
|
||||||
|
)
|
||||||
|
.with_rule("filter", &format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"))
|
||||||
|
.with_rule("filter", &format!("-A FORWARD -o tsun0 -m comment --comment {tag} -j ACCEPT"));
|
||||||
|
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||||
|
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||||
|
assert!(fake.verbs("-I").is_empty());
|
||||||
|
assert!(fake.verbs("-D").is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stale_range_is_removed_and_a_half_installed_set_is_replaced() {
|
||||||
|
let old: Ipv4Range = "10.99.0.0/24".parse().unwrap();
|
||||||
|
let old_tag = exit_tag("tsun0", &old);
|
||||||
|
let tag = exit_tag("tsun0", &range());
|
||||||
|
let fake = Fake::new(true)
|
||||||
|
.with_rule(
|
||||||
|
"nat",
|
||||||
|
&format!(
|
||||||
|
"-A POSTROUTING -s 10.99.0.0/24 -m comment --comment {old_tag} -j MASQUERADE"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
// Only one of the three for the current range.
|
||||||
|
.with_rule(
|
||||||
|
"filter",
|
||||||
|
&format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"),
|
||||||
|
)
|
||||||
|
// Somebody else's rule, which must survive.
|
||||||
|
.with_rule("filter", "-A FORWARD -i eth0 -j ACCEPT");
|
||||||
|
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||||
|
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||||
|
let deleted = fake.verbs("-D");
|
||||||
|
assert!(
|
||||||
|
deleted.iter().any(|call| call.contains(&old_tag)),
|
||||||
|
"{deleted:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
deleted.iter().any(|call| call.contains(&tag)),
|
||||||
|
"{deleted:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
deleted.iter().all(|call| !call.contains("eth0")),
|
||||||
|
"{deleted:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(fake.verbs("-I").len(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clearing_removes_only_our_rules_for_the_interface() {
|
||||||
|
let tag = exit_tag("tsun0", &range());
|
||||||
|
let other = exit_tag("tsun1", &range());
|
||||||
|
let fake = Fake::new(true)
|
||||||
|
.with_rule(
|
||||||
|
"nat",
|
||||||
|
&format!("-A POSTROUTING -m comment --comment {tag} -j MASQUERADE"),
|
||||||
|
)
|
||||||
|
.with_rule(
|
||||||
|
"nat",
|
||||||
|
&format!("-A POSTROUTING -m comment --comment {other} -j MASQUERADE"),
|
||||||
|
)
|
||||||
|
.with_rule("filter", "-A FORWARD -j ACCEPT");
|
||||||
|
clear_offer(&|args| fake.run(args), "tsun0");
|
||||||
|
let deleted = fake.verbs("-D");
|
||||||
|
assert_eq!(deleted.len(), 1, "{deleted:?}");
|
||||||
|
assert!(deleted[0].contains(&tag));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_missing_iptables_is_a_failure_that_says_what_to_do() {
|
||||||
|
let mut fake = Fake::new(false);
|
||||||
|
fake.missing = true;
|
||||||
|
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||||
|
let RuleOutcome::Failed(reason) = &outcome[0].1 else {
|
||||||
|
panic!("{outcome:?}");
|
||||||
|
};
|
||||||
|
assert!(reason.contains("iptables not found"), "{reason}");
|
||||||
|
assert!(reason.contains("10.13.37.0/24"), "{reason}");
|
||||||
|
// Nothing wanted and nothing to run is not a failure of anything.
|
||||||
|
assert!(apply_offer(&|args| fake.run(args), "tsun0", &[]).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn forwarding_is_read_per_interface_then_globally_and_never_written() {
|
||||||
|
let files = |per: Option<&'static str>, global: Option<&'static str>| {
|
||||||
|
move |path: &str| match path {
|
||||||
|
"/proc/sys/net/ipv4/conf/tsun0/forwarding" => per.map(str::to_string),
|
||||||
|
"/proc/sys/net/ipv4/ip_forward" => global.map(str::to_string),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
forwarding_state(files(Some("1\n"), Some("0\n")), "tsun0"),
|
||||||
|
Some(true)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
forwarding_state(files(Some("0\n"), Some("1\n")), "tsun0"),
|
||||||
|
Some(false)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
forwarding_state(files(None, Some("1\n")), "tsun0"),
|
||||||
|
Some(true)
|
||||||
|
);
|
||||||
|
assert_eq!(forwarding_state(files(None, None), "tsun0"), None);
|
||||||
|
assert_eq!(forwarding_state(files(Some("junk"), None), "tsun0"), None);
|
||||||
|
// A name that would leave the directory is not looked up.
|
||||||
|
assert_eq!(forwarding_state(files(Some("1"), None), "../../x"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_effective_uid_is_the_second_field() {
|
||||||
|
let status = "Name:\ttsunagi\nUid:\t1001\t1002\t1001\t1001\nGid:\t5\t5\t5\t5\n";
|
||||||
|
assert_eq!(parse_euid(status), Some(1002));
|
||||||
|
assert_eq!(parse_euid("Name:\tx\n"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_login_session_is_refused_and_a_service_is_not() {
|
||||||
|
let reason = client_refusal(Some("/run/user/1000")).unwrap();
|
||||||
|
assert!(reason.contains("system service"), "{reason}");
|
||||||
|
assert!(client_refusal(None).is_none());
|
||||||
|
assert!(client_refusal(Some("")).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,439 @@
|
|||||||
|
//! Privileged routing regression, isolated from the host in named namespaces.
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::io::{BufRead, BufReader, Read, Write};
|
||||||
|
use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket};
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
use std::process::{Child, Command};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use super::linux::run_firewall;
|
||||||
|
use super::linux_exit_mark::{clear, install, local_sockets, refresh};
|
||||||
|
use crate::overlay::NetlinkProvisioner;
|
||||||
|
|
||||||
|
const TEST: &str = "overlay::hostrules::linux_exit_kernel::strict_firewall_preserves_underlay_and_application_exit_routing";
|
||||||
|
const ROLE: &str = "TSUNAGI_EXIT_KERNEL_TEST_ROLE";
|
||||||
|
|
||||||
|
fn ip(arguments: &[&str]) -> String {
|
||||||
|
let result = Command::new("ip").args(arguments).output().unwrap();
|
||||||
|
assert!(
|
||||||
|
result.status.success(),
|
||||||
|
"ip {arguments:?}: {}",
|
||||||
|
String::from_utf8_lossy(&result.stderr)
|
||||||
|
);
|
||||||
|
String::from_utf8_lossy(&result.stdout).into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Namespace(String);
|
||||||
|
impl Drop for Namespace {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = Command::new("ip").args(["netns", "del", &self.0]).status();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Echo(Child);
|
||||||
|
impl Drop for Echo {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = self.0.kill();
|
||||||
|
let _ = self.0.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn probes() {
|
||||||
|
let should_pass = std::env::var("TSUNAGI_EXIT_KERNEL_EXPECT").unwrap() == "pass";
|
||||||
|
for address in ["198.51.100.2:42000", "[2001:db8:2::2]:42000"] {
|
||||||
|
let address: SocketAddr = address.parse().unwrap();
|
||||||
|
let socket = UdpSocket::bind(if address.is_ipv4() {
|
||||||
|
"0.0.0.0:0"
|
||||||
|
} else {
|
||||||
|
"[::]:0"
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
socket
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(1)))
|
||||||
|
.unwrap();
|
||||||
|
socket.send_to(b"rpf", address).unwrap();
|
||||||
|
let mut packet = [0u8; 3];
|
||||||
|
assert_eq!(
|
||||||
|
socket.recv(&mut packet).is_ok(),
|
||||||
|
should_pass,
|
||||||
|
"UDP {address}"
|
||||||
|
);
|
||||||
|
if should_pass {
|
||||||
|
assert_eq!(&packet, b"rpf");
|
||||||
|
}
|
||||||
|
let connected = TcpStream::connect_timeout(&address, Duration::from_secs(1));
|
||||||
|
assert_eq!(connected.is_ok(), should_pass, "TCP {address}");
|
||||||
|
if let Ok(mut stream) = connected {
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(1)))
|
||||||
|
.unwrap();
|
||||||
|
stream.write_all(b"rpf").unwrap();
|
||||||
|
stream.read_exact(&mut packet).unwrap();
|
||||||
|
assert_eq!(&packet, b"rpf");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_probes(expect: &str) {
|
||||||
|
let result = Command::new(std::env::current_exe().unwrap())
|
||||||
|
.args(["--ignored", "--exact", TEST, "--nocapture"])
|
||||||
|
.env(ROLE, "probe")
|
||||||
|
.env("TSUNAGI_EXIT_KERNEL_EXPECT", expect)
|
||||||
|
.uid(990)
|
||||||
|
.gid(990)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
result.status.success(),
|
||||||
|
"{}\n{}",
|
||||||
|
String::from_utf8_lossy(&result.stdout),
|
||||||
|
String::from_utf8_lossy(&result.stderr)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn passive_listener() {
|
||||||
|
let listeners: Vec<_> = ["192.0.2.1:42010", "[2001:db8:1::1]:42010"]
|
||||||
|
.into_iter()
|
||||||
|
.map(|address| TcpListener::bind(address).unwrap())
|
||||||
|
.collect();
|
||||||
|
println!("PASSIVE_READY");
|
||||||
|
let tasks: Vec<_> = listeners
|
||||||
|
.into_iter()
|
||||||
|
.map(|listener| {
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let (mut socket, _) = listener.accept().unwrap();
|
||||||
|
socket
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||||
|
.unwrap();
|
||||||
|
let mut bytes = [0; 3];
|
||||||
|
socket.read_exact(&mut bytes).unwrap();
|
||||||
|
socket.write_all(&bytes).unwrap();
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
for task in tasks {
|
||||||
|
task.join().unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn udp_listener() {
|
||||||
|
let sockets: Vec<_> = ["192.0.2.1:42011", "[2001:db8:1::1]:42011"]
|
||||||
|
.into_iter()
|
||||||
|
.map(|a| UdpSocket::bind(a).unwrap())
|
||||||
|
.collect();
|
||||||
|
println!("PASSIVE_READY");
|
||||||
|
let tasks: Vec<_> = sockets
|
||||||
|
.into_iter()
|
||||||
|
.map(|socket| {
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
socket
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||||
|
.unwrap();
|
||||||
|
let mut bytes = [0; 3];
|
||||||
|
let (len, peer) = socket.recv_from(&mut bytes).unwrap();
|
||||||
|
socket.send_to(&bytes[..len], peer).unwrap();
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
for task in tasks {
|
||||||
|
task.join().unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_listener(role: &str) -> Echo {
|
||||||
|
let process = Command::new(std::env::current_exe().unwrap())
|
||||||
|
.args(["--ignored", "--exact", TEST, "--nocapture"])
|
||||||
|
.env(ROLE, role)
|
||||||
|
.uid(990)
|
||||||
|
.gid(990)
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
let mut child = Echo(process);
|
||||||
|
let mut output = BufReader::new(child.0.stdout.take().unwrap());
|
||||||
|
loop {
|
||||||
|
let mut line = String::new();
|
||||||
|
assert_ne!(
|
||||||
|
output.read_line(&mut line).unwrap(),
|
||||||
|
0,
|
||||||
|
"listener exited before readiness"
|
||||||
|
);
|
||||||
|
if line.contains("PASSIVE_READY") {
|
||||||
|
// Keep the reader open for libtest's final status after the socket
|
||||||
|
// worker finishes; closing it here makes success a broken pipe.
|
||||||
|
child.0.stdout = Some(output.into_inner());
|
||||||
|
return child;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client() {
|
||||||
|
for setting in ["rp_filter", "src_valid_mark"] {
|
||||||
|
std::fs::write(format!("/proc/sys/net/ipv4/conf/all/{setting}"), b"1").unwrap();
|
||||||
|
}
|
||||||
|
std::fs::write("/proc/sys/net/ipv4/conf/rpf-c/rp_filter", b"1").unwrap();
|
||||||
|
for family in [false, true] {
|
||||||
|
let args: Vec<_> = [
|
||||||
|
"-t",
|
||||||
|
"mangle",
|
||||||
|
"-A",
|
||||||
|
"PREROUTING",
|
||||||
|
"-m",
|
||||||
|
"rpfilter",
|
||||||
|
"--invert",
|
||||||
|
"--validmark",
|
||||||
|
"-j",
|
||||||
|
"DROP",
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(str::to_string)
|
||||||
|
.collect();
|
||||||
|
let result = run_firewall(family, &args);
|
||||||
|
assert!(
|
||||||
|
matches!(result, super::linux::Ran::Exited { success: true, .. }),
|
||||||
|
"{result:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let provisioner = NetlinkProvisioner::new().unwrap();
|
||||||
|
let route = provisioner.host_rules().route;
|
||||||
|
// Model Tailscale's earlier lookup, without running another VPN daemon.
|
||||||
|
ip(&["-4", "rule", "add", "priority", "5270", "table", "52"]);
|
||||||
|
ip(&[
|
||||||
|
"-4", "route", "add", "default", "dev", "tsun0", "table", "52",
|
||||||
|
]);
|
||||||
|
ip(&["-6", "rule", "add", "priority", "5270", "table", "52"]);
|
||||||
|
ip(&[
|
||||||
|
"-6",
|
||||||
|
"route",
|
||||||
|
"add",
|
||||||
|
"unreachable",
|
||||||
|
"default",
|
||||||
|
"table",
|
||||||
|
"52",
|
||||||
|
]);
|
||||||
|
// A foreign VPN must leave neighbour discovery and connected LAN paths
|
||||||
|
// usable; otherwise the fixture itself cannot resolve its uplink neighbour.
|
||||||
|
for prefix in ["fe80::/64", "2001:db8:1::/64"] {
|
||||||
|
ip(&["-6", "route", "add", "throw", prefix, "table", "52"]);
|
||||||
|
}
|
||||||
|
let mut passive = spawn_listener("listener");
|
||||||
|
route.set_exit_client("tsun0", 990).unwrap();
|
||||||
|
// uid bypass alone cannot protect reverse lookups, reproducing the bug.
|
||||||
|
run_probes("blocked");
|
||||||
|
install(&run_firewall, "tsun0", 990, true).unwrap();
|
||||||
|
run_probes("pass");
|
||||||
|
// Pair transports may bind fresh UDP ports after exit activation.
|
||||||
|
let mut dynamic_udp = spawn_listener("udp-listener");
|
||||||
|
refresh(
|
||||||
|
&run_firewall,
|
||||||
|
"tsun0",
|
||||||
|
true,
|
||||||
|
&local_sockets(990, true).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let server = std::env::var("TSUNAGI_EXIT_KERNEL_SERVER").unwrap();
|
||||||
|
let incoming = Command::new("ip").args(["netns", "exec", &server, "python3", "-c", r#"import socket
|
||||||
|
for family,source,target in [(socket.AF_INET,'198.51.100.2','192.0.2.1'),(socket.AF_INET6,'2001:db8:2::2','2001:db8:1::1')]:
|
||||||
|
for kind,port in [(socket.SOCK_STREAM,42010),(socket.SOCK_DGRAM,42011)]:
|
||||||
|
s=socket.socket(family,kind); s.settimeout(2); s.bind((source,0)); s.connect((target,port)); s.sendall(b'rpf'); assert s.recv(3)==b'rpf'; s.close()
|
||||||
|
"#]).output().unwrap();
|
||||||
|
assert!(
|
||||||
|
incoming.status.success(),
|
||||||
|
"first inbound TCP/UDP must be protected: {}",
|
||||||
|
String::from_utf8_lossy(&incoming.stderr)
|
||||||
|
);
|
||||||
|
assert!(passive.0.wait().unwrap().success());
|
||||||
|
assert!(dynamic_udp.0.wait().unwrap().success());
|
||||||
|
// Repeated apply remains usable, and does not redirect application sockets.
|
||||||
|
install(&run_firewall, "tsun0", 990, true).unwrap();
|
||||||
|
run_probes("pass");
|
||||||
|
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("dev tsun0"));
|
||||||
|
let blocked = Command::new("ip")
|
||||||
|
.args(["-6", "route", "get", "2001:db8:2::2", "uid", "991"])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
!blocked.status.success(),
|
||||||
|
"application IPv6 must stay blocked"
|
||||||
|
);
|
||||||
|
route.clear_exit_client().unwrap();
|
||||||
|
clear(&run_firewall, "tsun0", true).unwrap();
|
||||||
|
for family in ["-4", "-6"] {
|
||||||
|
assert!(
|
||||||
|
ip(&[family, "rule", "show"]).contains("5270:"),
|
||||||
|
"foreign routing rules survive cleanup"
|
||||||
|
);
|
||||||
|
ip(&[family, "rule", "del", "priority", "5270"]);
|
||||||
|
}
|
||||||
|
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("dev rpf-c"));
|
||||||
|
assert!(ip(&["-6", "route", "get", "2001:db8:2::2", "uid", "991"]).contains("dev rpf-c"));
|
||||||
|
for family in [false, true] {
|
||||||
|
let result = run_firewall(family, &["-t".into(), "mangle".into(), "-S".into()]);
|
||||||
|
if let super::linux::Ran::Exited { stdout, .. } = result {
|
||||||
|
assert!(!stdout.contains("tsunagi-exit-underlay:"));
|
||||||
|
assert!(!stdout.contains("tsunagi-exit-sockets:"));
|
||||||
|
assert!(
|
||||||
|
stdout.contains("rpfilter"),
|
||||||
|
"strict host filtering is retained"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "needs root, iproute2, iptables/ip6tables and Python; changes only temporary namespaces"]
|
||||||
|
fn strict_firewall_preserves_underlay_and_application_exit_routing() {
|
||||||
|
match std::env::var(ROLE).as_deref() {
|
||||||
|
Ok("probe") => {
|
||||||
|
probes();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Ok("client") => {
|
||||||
|
client();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Ok("listener") => {
|
||||||
|
passive_listener();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Ok("udp-listener") => {
|
||||||
|
udp_listener();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
let suffix = std::process::id();
|
||||||
|
let client_name = format!("tsng-rpf-c-{suffix}");
|
||||||
|
let server_name = format!("tsng-rpf-s-{suffix}");
|
||||||
|
ip(&["netns", "add", &client_name]);
|
||||||
|
let _client = Namespace(client_name.clone());
|
||||||
|
ip(&["netns", "add", &server_name]);
|
||||||
|
let _server = Namespace(server_name.clone());
|
||||||
|
ip(&[
|
||||||
|
"link",
|
||||||
|
"add",
|
||||||
|
"rpf-c",
|
||||||
|
"netns",
|
||||||
|
&client_name,
|
||||||
|
"type",
|
||||||
|
"veth",
|
||||||
|
"peer",
|
||||||
|
"name",
|
||||||
|
"rpf-s",
|
||||||
|
"netns",
|
||||||
|
&server_name,
|
||||||
|
]);
|
||||||
|
for (namespace, interface, v4, v6) in [
|
||||||
|
(&client_name, "rpf-c", "192.0.2.1/24", "2001:db8:1::1/64"),
|
||||||
|
(&server_name, "rpf-s", "192.0.2.2/24", "2001:db8:1::2/64"),
|
||||||
|
] {
|
||||||
|
ip(&["-n", namespace, "link", "set", "lo", "up"]);
|
||||||
|
ip(&["-n", namespace, "addr", "add", v4, "dev", interface]);
|
||||||
|
ip(&[
|
||||||
|
"-n", namespace, "-6", "addr", "add", v6, "dev", interface, "nodad",
|
||||||
|
]);
|
||||||
|
ip(&["-n", namespace, "link", "set", interface, "up"]);
|
||||||
|
}
|
||||||
|
ip(&[
|
||||||
|
"-n",
|
||||||
|
&server_name,
|
||||||
|
"addr",
|
||||||
|
"add",
|
||||||
|
"198.51.100.2/32",
|
||||||
|
"dev",
|
||||||
|
"lo",
|
||||||
|
]);
|
||||||
|
ip(&[
|
||||||
|
"-n",
|
||||||
|
&server_name,
|
||||||
|
"-6",
|
||||||
|
"addr",
|
||||||
|
"add",
|
||||||
|
"2001:db8:2::2/128",
|
||||||
|
"dev",
|
||||||
|
"lo",
|
||||||
|
"nodad",
|
||||||
|
]);
|
||||||
|
ip(&[
|
||||||
|
"-n",
|
||||||
|
&client_name,
|
||||||
|
"route",
|
||||||
|
"add",
|
||||||
|
"default",
|
||||||
|
"via",
|
||||||
|
"192.0.2.2",
|
||||||
|
]);
|
||||||
|
ip(&[
|
||||||
|
"-n",
|
||||||
|
&client_name,
|
||||||
|
"-6",
|
||||||
|
"route",
|
||||||
|
"add",
|
||||||
|
"default",
|
||||||
|
"via",
|
||||||
|
"2001:db8:1::2",
|
||||||
|
]);
|
||||||
|
ip(&["-n", &client_name, "link", "add", "tsun0", "type", "dummy"]);
|
||||||
|
ip(&[
|
||||||
|
"-n",
|
||||||
|
&client_name,
|
||||||
|
"addr",
|
||||||
|
"add",
|
||||||
|
"10.13.37.1/24",
|
||||||
|
"dev",
|
||||||
|
"tsun0",
|
||||||
|
]);
|
||||||
|
ip(&["-n", &client_name, "link", "set", "tsun0", "up"]);
|
||||||
|
let echo_code = r#"import socket,selectors,sys
|
||||||
|
selector=selectors.DefaultSelector()
|
||||||
|
for family in [socket.AF_INET,socket.AF_INET6]:
|
||||||
|
for kind in [socket.SOCK_DGRAM,socket.SOCK_STREAM]:
|
||||||
|
sock=socket.socket(family,kind)
|
||||||
|
if family==socket.AF_INET6: sock.setsockopt(socket.IPPROTO_IPV6,socket.IPV6_V6ONLY,1)
|
||||||
|
sock.bind(('198.51.100.2' if family==socket.AF_INET else '2001:db8:2::2',42000))
|
||||||
|
if kind==socket.SOCK_STREAM: sock.listen()
|
||||||
|
selector.register(sock,selectors.EVENT_READ,kind)
|
||||||
|
print('ready',flush=True)
|
||||||
|
while True:
|
||||||
|
for key,_ in selector.select():
|
||||||
|
if key.data==socket.SOCK_DGRAM:
|
||||||
|
data,address=key.fileobj.recvfrom(128); key.fileobj.sendto(data,address)
|
||||||
|
else:
|
||||||
|
conn,_=key.fileobj.accept(); conn.settimeout(2)
|
||||||
|
try: conn.sendall(conn.recv(128))
|
||||||
|
finally: conn.close()
|
||||||
|
"#;
|
||||||
|
let child = Command::new("ip")
|
||||||
|
.args([
|
||||||
|
"netns",
|
||||||
|
"exec",
|
||||||
|
&server_name,
|
||||||
|
"python3",
|
||||||
|
"-u",
|
||||||
|
"-c",
|
||||||
|
echo_code,
|
||||||
|
])
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
let mut echo = Echo(child);
|
||||||
|
let mut ready = String::new();
|
||||||
|
BufReader::new(echo.0.stdout.take().unwrap())
|
||||||
|
.read_line(&mut ready)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(ready.trim(), "ready");
|
||||||
|
let result = Command::new("ip")
|
||||||
|
.args(["netns", "exec", &client_name])
|
||||||
|
.arg(std::env::current_exe().unwrap())
|
||||||
|
.args(["--ignored", "--exact", TEST, "--nocapture"])
|
||||||
|
.env(ROLE, "client")
|
||||||
|
.env("TSUNAGI_EXIT_KERNEL_SERVER", &server_name)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
result.status.success(),
|
||||||
|
"{}\n{}",
|
||||||
|
String::from_utf8_lossy(&result.stdout),
|
||||||
|
String::from_utf8_lossy(&result.stderr)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,535 @@
|
|||||||
|
//! Own-bit connection marks for exit-client underlay traffic.
|
||||||
|
//! Reply marks are restored before host reverse-path filtering, never accepted
|
||||||
|
//! around it. No peer address becomes a host route or firewall argument.
|
||||||
|
|
||||||
|
use super::linux::{Ran, failure, locked, split_rule_line};
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
|
/// Outside Tailscale's 0xff0000 mask and ordinary low-bit WireGuard marks.
|
||||||
|
pub(crate) const UNDERLAY_MARK: u32 = 0x4000_0000;
|
||||||
|
pub(crate) const UNDERLAY_MASK: u32 = UNDERLAY_MARK;
|
||||||
|
const MARK: &str = "0x40000000/0x40000000";
|
||||||
|
const MASK: &str = "0x40000000";
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub(super) struct Listener {
|
||||||
|
address: IpAddr,
|
||||||
|
port: u16,
|
||||||
|
tcp: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_listeners(listing: &str, uid: u32, v6: bool, tcp: bool) -> Result<Vec<Listener>, String> {
|
||||||
|
let mut result = Vec::new();
|
||||||
|
for line in listing.lines().skip(1) {
|
||||||
|
let fields: Vec<_> = line.split_whitespace().collect();
|
||||||
|
if (tcp && fields.get(3) != Some(&"0A"))
|
||||||
|
|| fields.get(7).and_then(|s| s.parse::<u32>().ok()) != Some(uid)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (address, port) = fields
|
||||||
|
.get(1)
|
||||||
|
.and_then(|s| s.split_once(':'))
|
||||||
|
.ok_or("malformed local socket")?;
|
||||||
|
let port = u16::from_str_radix(port, 16).map_err(|e| e.to_string())?;
|
||||||
|
let address = if v6 {
|
||||||
|
let mut bytes = [0; 16];
|
||||||
|
for (word, chunk) in bytes.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||||
|
let hex = address
|
||||||
|
.get(word * 8..word * 8 + 8)
|
||||||
|
.ok_or("malformed local IPv6 listener")?;
|
||||||
|
chunk.copy_from_slice(
|
||||||
|
&u32::from_str_radix(hex, 16)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.to_ne_bytes(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
IpAddr::V6(Ipv6Addr::from(bytes))
|
||||||
|
} else {
|
||||||
|
IpAddr::V4(Ipv4Addr::from(
|
||||||
|
u32::from_str_radix(address, 16)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.to_ne_bytes(),
|
||||||
|
))
|
||||||
|
};
|
||||||
|
if result.len() == 128 {
|
||||||
|
return Err("too many local sockets for exit protection".into());
|
||||||
|
}
|
||||||
|
if port != 0 {
|
||||||
|
result.push(Listener { address, port, tcp });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn local_sockets(uid: u32, v6: bool) -> Result<Vec<Listener>, String> {
|
||||||
|
let mut listeners = Vec::new();
|
||||||
|
for (protocol, tcp) in [("tcp", true), ("udp", false)] {
|
||||||
|
for family in [false, true].into_iter().filter(|f| !f || v6) {
|
||||||
|
let path = format!("/proc/net/{protocol}{}", if family { "6" } else { "" });
|
||||||
|
listeners.extend(parse_listeners(
|
||||||
|
&std::fs::read_to_string(path).map_err(|e| e.to_string())?,
|
||||||
|
uid,
|
||||||
|
family,
|
||||||
|
tcp,
|
||||||
|
)?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
listeners.sort();
|
||||||
|
listeners.dedup();
|
||||||
|
Ok(listeners)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn listener_rules(interface: &str, listener: &Listener) -> Vec<Vec<String>> {
|
||||||
|
let mut base = words(&[
|
||||||
|
"!",
|
||||||
|
"-i",
|
||||||
|
interface,
|
||||||
|
"-p",
|
||||||
|
if listener.tcp { "tcp" } else { "udp" },
|
||||||
|
"--dport",
|
||||||
|
&listener.port.to_string(),
|
||||||
|
]);
|
||||||
|
if !listener.address.is_unspecified() {
|
||||||
|
base.extend(words(&["-d", &listener.address.to_string()]));
|
||||||
|
}
|
||||||
|
// Match an actual local socket, not just a destination port. Listening
|
||||||
|
// sockets need protection on the first packet, before any outbound connmark.
|
||||||
|
base.extend(words(&[
|
||||||
|
"-m",
|
||||||
|
"socket",
|
||||||
|
"--nowildcard",
|
||||||
|
"-m",
|
||||||
|
"comment",
|
||||||
|
"--comment",
|
||||||
|
&listener_tag(interface),
|
||||||
|
]));
|
||||||
|
let save = base
|
||||||
|
.iter()
|
||||||
|
.cloned()
|
||||||
|
.chain(words(&[
|
||||||
|
"-m",
|
||||||
|
"mark",
|
||||||
|
"--mark",
|
||||||
|
MARK,
|
||||||
|
"-j",
|
||||||
|
"CONNMARK",
|
||||||
|
"--save-mark",
|
||||||
|
"--nfmask",
|
||||||
|
MASK,
|
||||||
|
"--ctmask",
|
||||||
|
MASK,
|
||||||
|
]))
|
||||||
|
.collect();
|
||||||
|
let mark = base
|
||||||
|
.into_iter()
|
||||||
|
.chain(words(&["-j", "MARK", "--set-xmark", MARK]))
|
||||||
|
.collect();
|
||||||
|
vec![save, mark]
|
||||||
|
}
|
||||||
|
pub(super) type RunFamily<'a> = &'a dyn Fn(bool, &[String]) -> Ran;
|
||||||
|
|
||||||
|
fn tag(interface: &str) -> String {
|
||||||
|
format!("tsunagi-exit-underlay:{interface}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn listener_tag(interface: &str) -> String {
|
||||||
|
format!("tsunagi-exit-sockets:{interface}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn words(values: &[&str]) -> Vec<String> {
|
||||||
|
values.iter().map(|s| (*s).into()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||||
|
let tag = tag(interface);
|
||||||
|
let uid = uid.to_string();
|
||||||
|
// Insert at position one in this order: final OUTPUT order is MARK, SAVE.
|
||||||
|
vec![
|
||||||
|
(
|
||||||
|
"PREROUTING",
|
||||||
|
words(&[
|
||||||
|
"!",
|
||||||
|
"-i",
|
||||||
|
interface,
|
||||||
|
"-m",
|
||||||
|
"connmark",
|
||||||
|
"--mark",
|
||||||
|
MARK,
|
||||||
|
"-m",
|
||||||
|
"comment",
|
||||||
|
"--comment",
|
||||||
|
&tag,
|
||||||
|
"-j",
|
||||||
|
"CONNMARK",
|
||||||
|
"--restore-mark",
|
||||||
|
"--nfmask",
|
||||||
|
MASK,
|
||||||
|
"--ctmask",
|
||||||
|
MASK,
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"OUTPUT",
|
||||||
|
words(&[
|
||||||
|
"-m",
|
||||||
|
"owner",
|
||||||
|
"--uid-owner",
|
||||||
|
&uid,
|
||||||
|
"-m",
|
||||||
|
"mark",
|
||||||
|
"--mark",
|
||||||
|
MARK,
|
||||||
|
"-m",
|
||||||
|
"comment",
|
||||||
|
"--comment",
|
||||||
|
&tag,
|
||||||
|
"-j",
|
||||||
|
"CONNMARK",
|
||||||
|
"--save-mark",
|
||||||
|
"--nfmask",
|
||||||
|
MASK,
|
||||||
|
"--ctmask",
|
||||||
|
MASK,
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"OUTPUT",
|
||||||
|
words(&[
|
||||||
|
"-m",
|
||||||
|
"owner",
|
||||||
|
"--uid-owner",
|
||||||
|
&uid,
|
||||||
|
"-m",
|
||||||
|
"comment",
|
||||||
|
"--comment",
|
||||||
|
&tag,
|
||||||
|
"-j",
|
||||||
|
"MARK",
|
||||||
|
"--set-xmark",
|
||||||
|
MARK,
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(run: RunFamily<'_>, v6: bool, args: Vec<String>) -> Result<String, String> {
|
||||||
|
match run(v6, &locked(args)) {
|
||||||
|
Ran::Exited {
|
||||||
|
success: true,
|
||||||
|
stdout,
|
||||||
|
..
|
||||||
|
} => Ok(stdout),
|
||||||
|
Ran::Exited { stderr, .. } => Err(failure(&stderr)),
|
||||||
|
Ran::Missing => Err(format!(
|
||||||
|
"{} is required for exit-node connection marks",
|
||||||
|
if v6 { "ip6tables" } else { "iptables" }
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes only exact interface tags, retaining other agents and host rules.
|
||||||
|
pub(super) fn clear(run: RunFamily<'_>, interface: &str, v6: bool) -> Result<(), String> {
|
||||||
|
clear_tags(run, interface, v6, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_tags(
|
||||||
|
run: RunFamily<'_>,
|
||||||
|
interface: &str,
|
||||||
|
v6: bool,
|
||||||
|
sockets_only: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let wanted = tag(interface);
|
||||||
|
let sockets = listener_tag(interface);
|
||||||
|
for family in [false, true].into_iter().filter(|family| !family || v6) {
|
||||||
|
let chains: &[&str] = if sockets_only {
|
||||||
|
&["PREROUTING"]
|
||||||
|
} else {
|
||||||
|
&["OUTPUT", "PREROUTING"]
|
||||||
|
};
|
||||||
|
for chain in chains {
|
||||||
|
let listing = execute(run, family, words(&["-t", "mangle", "-S", chain]))?;
|
||||||
|
for line in listing.lines() {
|
||||||
|
let tokens = split_rule_line(line);
|
||||||
|
let [append, listed_chain, rest @ ..] = tokens.as_slice() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if append == "-A"
|
||||||
|
&& listed_chain == *chain
|
||||||
|
&& rest.windows(2).any(|pair| {
|
||||||
|
pair[0] == "--comment"
|
||||||
|
&& (pair[1] == sockets || (!sockets_only && pair[1] == wanted))
|
||||||
|
})
|
||||||
|
{
|
||||||
|
let args = words(&["-t", "mangle", "-D", chain])
|
||||||
|
.into_iter()
|
||||||
|
.chain(rest.iter().cloned())
|
||||||
|
.collect();
|
||||||
|
execute(run, family, args)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establishes protection before routing may redirect application traffic.
|
||||||
|
pub(super) fn install(
|
||||||
|
run: RunFamily<'_>,
|
||||||
|
interface: &str,
|
||||||
|
uid: u32,
|
||||||
|
v6: bool,
|
||||||
|
) -> Result<Vec<Listener>, String> {
|
||||||
|
let listeners = local_sockets(uid, v6)?;
|
||||||
|
install_with_listeners(run, interface, uid, v6, &listeners)?;
|
||||||
|
Ok(listeners)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install_with_listeners(
|
||||||
|
run: RunFamily<'_>,
|
||||||
|
interface: &str,
|
||||||
|
uid: u32,
|
||||||
|
v6: bool,
|
||||||
|
listeners: &[Listener],
|
||||||
|
) -> Result<(), String> {
|
||||||
|
clear(run, interface, v6)?;
|
||||||
|
let result = (|| {
|
||||||
|
for family in [false, true].into_iter().filter(|family| !family || v6) {
|
||||||
|
for (chain, spec) in rules(interface, uid) {
|
||||||
|
let args = words(&["-t", "mangle", "-I", chain, "1"])
|
||||||
|
.into_iter()
|
||||||
|
.chain(spec)
|
||||||
|
.collect();
|
||||||
|
execute(run, family, args)?;
|
||||||
|
}
|
||||||
|
for listener in listeners.iter().filter(|s| s.address.is_ipv6() == family) {
|
||||||
|
for spec in listener_rules(interface, listener) {
|
||||||
|
execute(
|
||||||
|
run,
|
||||||
|
family,
|
||||||
|
words(&["-t", "mangle", "-I", "PREROUTING", "1"])
|
||||||
|
.into_iter()
|
||||||
|
.chain(spec)
|
||||||
|
.collect(),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if result.is_err()
|
||||||
|
&& let Err(cleanup) = clear(run, interface, v6)
|
||||||
|
{
|
||||||
|
return Err(format!(
|
||||||
|
"{}; cannot roll back connection marks: {cleanup}",
|
||||||
|
result.err().unwrap_or_default()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates passive protection without interrupting established connmark rules.
|
||||||
|
pub(super) fn refresh(
|
||||||
|
run: RunFamily<'_>,
|
||||||
|
interface: &str,
|
||||||
|
v6: bool,
|
||||||
|
listeners: &[Listener],
|
||||||
|
) -> Result<(), String> {
|
||||||
|
clear_tags(run, interface, v6, true)?;
|
||||||
|
for family in [false, true].into_iter().filter(|f| !f || v6) {
|
||||||
|
for listener in listeners.iter().filter(|s| s.address.is_ipv6() == family) {
|
||||||
|
for spec in listener_rules(interface, listener) {
|
||||||
|
execute(
|
||||||
|
run,
|
||||||
|
family,
|
||||||
|
words(&["-t", "mangle", "-I", "PREROUTING", "1"])
|
||||||
|
.into_iter()
|
||||||
|
.chain(spec)
|
||||||
|
.collect(),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Kernel strict RPF must include the restored mark, independently of iptables.
|
||||||
|
pub(super) fn check_kernel_rpf(
|
||||||
|
all_rpf: u32,
|
||||||
|
all_valid: u32,
|
||||||
|
interfaces: &[(String, u32, u32)],
|
||||||
|
) -> Result<(), String> {
|
||||||
|
for (interface, rpf, valid) in interfaces {
|
||||||
|
if all_rpf.max(*rpf) == 1 && all_valid.max(*valid) == 0 {
|
||||||
|
return Err(format!(
|
||||||
|
"strict rp_filter on `{interface}` ignores connection marks; enable net.ipv4.conf.all.src_valid_mark=1 before using an exit node (rp_filter stays enabled)"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
use std::cell::RefCell;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn both_families_restore_before_firewall_and_preserve_foreign_mark_bits() {
|
||||||
|
let calls = RefCell::new(Vec::new());
|
||||||
|
let run = |v6, args: &[String]| {
|
||||||
|
calls.borrow_mut().push((v6, args.to_vec()));
|
||||||
|
Ran::Exited {
|
||||||
|
success: true,
|
||||||
|
stdout: String::new(),
|
||||||
|
stderr: String::new(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
install_with_listeners(&run, "tsun0", 990, true, &[]).unwrap();
|
||||||
|
let calls = calls.borrow();
|
||||||
|
for family in [false, true] {
|
||||||
|
let inserts: Vec<_> = calls
|
||||||
|
.iter()
|
||||||
|
.filter(|(v6, a)| *v6 == family && a.iter().any(|s| s == "-I"))
|
||||||
|
.map(|(_, a)| a.join(" "))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(inserts.len(), 3);
|
||||||
|
assert!(inserts[0].contains("-I PREROUTING 1 ! -i tsun0 -m connmark"));
|
||||||
|
assert!(inserts[0].contains("--restore-mark --nfmask 0x40000000 --ctmask 0x40000000"));
|
||||||
|
assert!(inserts[1].contains("--uid-owner 990"));
|
||||||
|
assert!(inserts[1].contains("--save-mark"));
|
||||||
|
assert!(inserts[2].contains("--set-xmark 0x40000000/0x40000000"));
|
||||||
|
assert!(
|
||||||
|
!inserts
|
||||||
|
.iter()
|
||||||
|
.any(|s| s.contains("-j ACCEPT") || s.contains("-j RETURN"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(UNDERLAY_MASK & 0x00ff_0000, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cleanup_retains_other_interfaces_and_rolls_back_partial_ipv6_installation() {
|
||||||
|
let calls = RefCell::new(Vec::new());
|
||||||
|
let run = |v6, args: &[String]| {
|
||||||
|
calls.borrow_mut().push((v6, args.to_vec()));
|
||||||
|
let listing = "-A OUTPUT -m comment --comment tsunagi-exit-underlay:tsun0 -j MARK --set-xmark 0x40000000/0x40000000\n-A OUTPUT -m comment --comment tsunagi-exit-underlay:tsun1 -j MARK --set-xmark 0x40000000/0x40000000\n-A OUTPUT -m comment --comment unrelated -j RETURN\n";
|
||||||
|
Ran::Exited {
|
||||||
|
success: !(v6 && args.iter().any(|s| s == "-I")),
|
||||||
|
stdout: if args.iter().any(|s| s == "-S") {
|
||||||
|
listing.into()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
},
|
||||||
|
stderr: "injected IPv6 failure".into(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assert!(install_with_listeners(&run, "tsun0", 990, true, &[]).is_err());
|
||||||
|
let calls = calls.borrow();
|
||||||
|
let deletions: Vec<_> = calls
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, a)| a.iter().any(|s| s == "-D"))
|
||||||
|
.collect();
|
||||||
|
assert!(
|
||||||
|
deletions.len() >= 4,
|
||||||
|
"both initial and rollback cleanup run"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
deletions
|
||||||
|
.iter()
|
||||||
|
.all(|(_, a)| a.iter().any(|s| s == "tsunagi-exit-underlay:tsun0"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn kernel_strict_validation_requires_mark_awareness_without_weakening_rpf() {
|
||||||
|
let interfaces = vec![("eth0".into(), 1, 0)];
|
||||||
|
assert!(check_kernel_rpf(0, 0, &interfaces).is_err());
|
||||||
|
assert!(check_kernel_rpf(0, 1, &interfaces).is_ok());
|
||||||
|
assert!(check_kernel_rpf(2, 0, &interfaces).is_ok());
|
||||||
|
assert!(check_kernel_rpf(0, 0, &[("eth0".into(), 1, 1)]).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn passive_tcp_protection_uses_only_locally_owned_listeners() {
|
||||||
|
let listing = "header\n0: 00000000:01BB 00000000:0000 0A 0:0 0:0 0 990 0 1\n1: 0100007F:1111 00000000:0000 0A 0:0 0:0 0 1000 0 2\n2: 0100007F:2222 00000000:0000 01 0:0 0:0 0 990 0 3\n";
|
||||||
|
let listeners = parse_listeners(listing, 990, false, true).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
listeners,
|
||||||
|
vec![Listener {
|
||||||
|
address: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
|
||||||
|
port: 443,
|
||||||
|
tcp: true
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
let rules = listener_rules("tsun0", &listeners[0]);
|
||||||
|
assert!(
|
||||||
|
rules[0]
|
||||||
|
.join(" ")
|
||||||
|
.contains("-p tcp --dport 443 -m socket --nowildcard")
|
||||||
|
);
|
||||||
|
assert!(rules[0].join(" ").contains("--save-mark"));
|
||||||
|
assert!(rules[1].join(" ").contains("--set-xmark"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn listener_parser_checks_family_encoding_and_bounds() {
|
||||||
|
let loopback = Ipv6Addr::LOCALHOST.octets();
|
||||||
|
let hex: String = loopback
|
||||||
|
.as_chunks::<4>()
|
||||||
|
.0
|
||||||
|
.iter()
|
||||||
|
.map(|bytes| format!("{:08X}", u32::from_ne_bytes(*bytes)))
|
||||||
|
.collect();
|
||||||
|
let listing = format!("header\n0: {hex}:01BB 0:0 0A 0:0 0:0 0 990 0 1\n");
|
||||||
|
assert_eq!(
|
||||||
|
parse_listeners(&listing, 990, true, true).unwrap(),
|
||||||
|
vec![Listener {
|
||||||
|
address: IpAddr::V6(Ipv6Addr::LOCALHOST),
|
||||||
|
port: 443,
|
||||||
|
tcp: true
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
parse_listeners(
|
||||||
|
"header\n0: BAD:01BB 0:0 0A 0:0 0:0 0 990 0 1",
|
||||||
|
990,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
let huge = format!(
|
||||||
|
"header\n{}",
|
||||||
|
"0: 00000000:01BB 0:0 0A 0:0 0:0 0 990 0 1\n".repeat(129)
|
||||||
|
);
|
||||||
|
assert!(parse_listeners(&huge, 990, false, true).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn udp_refresh_preserves_general_connmark_protection_and_other_interfaces() {
|
||||||
|
let listing = "header\n0: 00000000:ABA0 0:0 07 0:0 0:0 0 990 0 1\n1: 00000000:0000 0:0 07 0:0 0:0 0 990 0 2\n";
|
||||||
|
let sockets = parse_listeners(listing, 990, false, false).unwrap();
|
||||||
|
assert_eq!(sockets.len(), 1);
|
||||||
|
assert!(!sockets[0].tcp);
|
||||||
|
let calls = RefCell::new(Vec::new());
|
||||||
|
let run = |v6, args: &[String]| {
|
||||||
|
calls.borrow_mut().push((v6, args.join(" ")));
|
||||||
|
Ran::Exited { success: true, stdout: "-A PREROUTING -m comment --comment tsunagi-exit-underlay:tsun0 -j CONNMARK --restore-mark\n-A PREROUTING -m comment --comment tsunagi-exit-sockets:tsun0 -j MARK\n-A PREROUTING -m comment --comment tsunagi-exit-sockets:tsun1 -j MARK\n".into(), stderr: String::new() }
|
||||||
|
};
|
||||||
|
refresh(&run, "tsun0", false, &sockets).unwrap();
|
||||||
|
let calls = calls.borrow();
|
||||||
|
assert!(
|
||||||
|
calls
|
||||||
|
.iter()
|
||||||
|
.any(|(_, a)| a.contains("-I PREROUTING 1") && a.contains("-p udp"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
calls
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, a)| a.contains("-D"))
|
||||||
|
.all(|(_, a)| a.contains("tsunagi-exit-sockets:tsun0"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+47
-3
@@ -19,6 +19,10 @@
|
|||||||
|
|
||||||
use crate::BoxFuture;
|
use crate::BoxFuture;
|
||||||
|
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
|
||||||
|
use super::macos_exit::{apply_plan, clear_all, run_tool};
|
||||||
use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome};
|
use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome};
|
||||||
|
|
||||||
/// The limited-broadcast destination routed through the overlay interface.
|
/// The limited-broadcast destination routed through the overlay interface.
|
||||||
@@ -60,14 +64,19 @@ fn firewall_todo(plan: &BroadcastRulesPlan) -> String {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The macOS implementation: `route` for the route, no firewall yet.
|
/// The macOS implementation: `route` for the route, no firewall yet, and
|
||||||
|
/// `pf` plus `route` for exit nodes (see [`super::macos_exit`]).
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct MacosHostRules;
|
pub struct MacosHostRules {
|
||||||
|
/// The reference `pfctl -E` handed out, held while exit-node rules need
|
||||||
|
/// `pf` on and released when they are removed.
|
||||||
|
pub(super) pf_token: Arc<Mutex<Option<String>>>,
|
||||||
|
}
|
||||||
|
|
||||||
impl MacosHostRules {
|
impl MacosHostRules {
|
||||||
/// Creates the host rules.
|
/// Creates the host rules.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self
|
Self::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Installs the route, replacing one this agent added earlier so the call
|
/// Installs the route, replacing one this agent added earlier so the call
|
||||||
@@ -82,11 +91,46 @@ impl MacosHostRules {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ExitHostRules for MacosHostRules {
|
||||||
|
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let job_plan = plan.clone();
|
||||||
|
let token = Arc::clone(&self.pf_token);
|
||||||
|
tokio::task::spawn_blocking(move || apply_plan(&run_tool, &token, &job_plan))
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|err| {
|
||||||
|
let failed = RuleOutcome::Failed(format!("the task failed: {err}"));
|
||||||
|
ExitHostReport {
|
||||||
|
offer: plan
|
||||||
|
.offer
|
||||||
|
.iter()
|
||||||
|
.map(|range| (*range, failed.clone()))
|
||||||
|
.collect(),
|
||||||
|
forwarding: None,
|
||||||
|
client: plan.client.then_some(failed),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let name = interface.to_string();
|
||||||
|
let token = Arc::clone(&self.pf_token);
|
||||||
|
let _ = tokio::task::spawn_blocking(move || clear_all(&run_tool, &token, &name)).await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl BroadcastHostRules for MacosHostRules {
|
impl BroadcastHostRules for MacosHostRules {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"route"
|
"route"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
|
||||||
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let route = self.set_route(plan.interface.clone()).await;
|
let route = self.set_route(plan.interface.clone()).await;
|
||||||
@@ -0,0 +1,915 @@
|
|||||||
|
//! Exit-node host rules on macOS: a `pf` anchor and `route` entries.
|
||||||
|
//!
|
||||||
|
//! Compiled on every platform so the rule text and the parsers are tested
|
||||||
|
//! everywhere; only `MacosHostRules` runs them, and only on macOS.
|
||||||
|
//!
|
||||||
|
//! # Offering
|
||||||
|
//!
|
||||||
|
//! Per offered range, in the anchor `com.apple/tsunagi-exit-<if>`:
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! nat on <egress> inet from <range> to any -> (<egress>)
|
||||||
|
//! pass in quick on <if> inet from <range> to ! <range>
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! The anchor lives under `com.apple/` on purpose: the stock `/etc/pf.conf`
|
||||||
|
//! evaluates `nat-anchor "com.apple/*"` and `anchor "com.apple/*"`, so the
|
||||||
|
//! rules take effect without editing the user's ruleset. `pf` cannot say
|
||||||
|
//! "every interface but one" in a translation address, so the egress is the
|
||||||
|
//! interface of the default route **when the rules are applied**; after the
|
||||||
|
//! default route moves (Wi-Fi to Ethernet) the rules are re-applied by
|
||||||
|
//! switching the exit node off and on, or restarting the agent.
|
||||||
|
//!
|
||||||
|
//! The kernel's `net.inet.ip.forwarding` is only read, never written: it
|
||||||
|
//! changes how the whole host behaves, which is the owner's decision.
|
||||||
|
//!
|
||||||
|
//! # Using
|
||||||
|
//!
|
||||||
|
//! macOS has no `uidrange` policy routing, and the agent is root, so the
|
||||||
|
//! Linux scheme does not carry over. Instead:
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! route add -net 0.0.0.0/1 -interface <if>
|
||||||
|
//! route add -net 128.0.0.0/1 -interface <if>
|
||||||
|
//! pass out quick on <if> route-to (<egress> <gateway>) inet proto { tcp udp }
|
||||||
|
//! from any to ! <overlay ranges> user <agent uid>
|
||||||
|
//! nat on <egress> inet from (<if>) to any -> (<egress>)
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! The two halves outrank the default route without replacing it, and every
|
||||||
|
//! more specific route (LAN, another VPN) keeps working. The `route-to` rule
|
||||||
|
//! sends the *agent's own* traffic — QUIC, relay, DHT, which would otherwise
|
||||||
|
//! loop into the tunnel it carries — back out the physical interface, and the
|
||||||
|
//! translation gives it that interface's address, since an unbound socket
|
||||||
|
//! picked the overlay address when the route pointed at the overlay. Like the
|
||||||
|
//! Linux exemption this is by user id, so anything else running as root also
|
||||||
|
//! bypasses the tunnel.
|
||||||
|
//!
|
||||||
|
//! IPv6 is blocked while an exit node is in use, as on Linux: `::/1` and
|
||||||
|
//! `8000::/1` are rejecting routes, so applications fall back to IPv4 at once
|
||||||
|
//! instead of leaking.
|
||||||
|
//!
|
||||||
|
//! Every object is derived from local state and the interface the agent owns;
|
||||||
|
//! none of it comes from a peer.
|
||||||
|
|
||||||
|
use std::net::Ipv4Addr;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use crate::state::Ipv4Range;
|
||||||
|
|
||||||
|
use super::RuleOutcome;
|
||||||
|
use super::exit::{ExitHostPlan, ExitHostReport};
|
||||||
|
|
||||||
|
/// The programs this module runs, always by absolute path.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub(super) enum Tool {
|
||||||
|
Route,
|
||||||
|
Pfctl,
|
||||||
|
Sysctl,
|
||||||
|
Id,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Tool {
|
||||||
|
fn path(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Route => "/sbin/route",
|
||||||
|
Self::Pfctl => "/sbin/pfctl",
|
||||||
|
Self::Sysctl => "/usr/sbin/sysctl",
|
||||||
|
Self::Id => "/usr/bin/id",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What running a tool came to.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(super) enum Ran {
|
||||||
|
/// The program is not there.
|
||||||
|
Missing,
|
||||||
|
/// It ran.
|
||||||
|
Exited {
|
||||||
|
success: bool,
|
||||||
|
stdout: String,
|
||||||
|
stderr: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a tool with optional standard input; injectable so the logic is
|
||||||
|
/// tested without touching the host.
|
||||||
|
pub(super) type Run<'a> = &'a dyn Fn(Tool, &[String], Option<&str>) -> Ran;
|
||||||
|
|
||||||
|
/// Runs a real tool. Blocking: callers use `spawn_blocking`.
|
||||||
|
pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran {
|
||||||
|
use std::io::Write;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
|
||||||
|
let mut command = Command::new(tool.path());
|
||||||
|
command
|
||||||
|
.args(args)
|
||||||
|
.stdin(if stdin.is_some() {
|
||||||
|
Stdio::piped()
|
||||||
|
} else {
|
||||||
|
Stdio::null()
|
||||||
|
})
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped());
|
||||||
|
let mut child = match command.spawn() {
|
||||||
|
Ok(child) => child,
|
||||||
|
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ran::Missing,
|
||||||
|
Err(err) => {
|
||||||
|
return Ran::Exited {
|
||||||
|
success: false,
|
||||||
|
stdout: String::new(),
|
||||||
|
stderr: format!("could not run {}: {err}", tool.path()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
|
||||||
|
// A write error shows up as the tool's own failure below.
|
||||||
|
let _ = pipe.write_all(text.as_bytes());
|
||||||
|
}
|
||||||
|
match child.wait_with_output() {
|
||||||
|
Ok(output) => Ran::Exited {
|
||||||
|
success: output.status.success(),
|
||||||
|
stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
|
||||||
|
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||||
|
},
|
||||||
|
Err(err) => Ran::Exited {
|
||||||
|
success: false,
|
||||||
|
stdout: String::new(),
|
||||||
|
stderr: format!("could not run {}: {err}", tool.path()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned(words: &[&str]) -> Vec<String> {
|
||||||
|
words.iter().map(|word| word.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name that is safe in a `pf` rule, an anchor path and a table name.
|
||||||
|
fn safe_name(name: &str) -> bool {
|
||||||
|
!name.is_empty() && name.len() <= 32 && name.chars().all(|c| c.is_ascii_alphanumeric())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The anchor holding every rule of one interface.
|
||||||
|
fn anchor_name(interface: &str) -> Result<String, String> {
|
||||||
|
if safe_name(interface) {
|
||||||
|
Ok(format!("com.apple/tsunagi-exit-{interface}"))
|
||||||
|
} else {
|
||||||
|
Err(format!(
|
||||||
|
"`{interface}` is not an interface name this agent can write a pf rule for"
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The default route as `route -n get default` reports it.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(super) struct DefaultRoute {
|
||||||
|
pub interface: String,
|
||||||
|
pub gateway: Option<Ipv4Addr>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads `interface:` and `gateway:` out of `route -n get default`.
|
||||||
|
fn parse_default_route(text: &str) -> Option<DefaultRoute> {
|
||||||
|
let field = |name: &str| {
|
||||||
|
text.lines().find_map(|line| {
|
||||||
|
let (key, value) = line.split_once(':')?;
|
||||||
|
(key.trim() == name).then(|| value.trim().to_string())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let interface = field("interface").filter(|name| safe_name(name))?;
|
||||||
|
let gateway = field("gateway").and_then(|value| value.parse().ok());
|
||||||
|
Some(DefaultRoute { interface, gateway })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failure(stderr: &str, stdout: &str) -> String {
|
||||||
|
let text = if stderr.trim().is_empty() {
|
||||||
|
stdout.trim()
|
||||||
|
} else {
|
||||||
|
stderr.trim()
|
||||||
|
};
|
||||||
|
if text.is_empty() {
|
||||||
|
"the command failed without saying why".to_string()
|
||||||
|
} else {
|
||||||
|
text.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a tool and turns a failure into a sentence a person can act on.
|
||||||
|
fn run_ok(
|
||||||
|
run: Run<'_>,
|
||||||
|
tool: Tool,
|
||||||
|
args: &[String],
|
||||||
|
stdin: Option<&str>,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
match run(tool, args, stdin) {
|
||||||
|
Ran::Missing => Err(format!("{} not found", tool.path())),
|
||||||
|
Ran::Exited {
|
||||||
|
success: true,
|
||||||
|
stdout,
|
||||||
|
..
|
||||||
|
} => Ok(stdout),
|
||||||
|
Ran::Exited { stderr, stdout, .. } => Err(format!(
|
||||||
|
"{} {} failed: {}",
|
||||||
|
tool.path(),
|
||||||
|
args.join(" "),
|
||||||
|
failure(&stderr, &stdout)
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The route traffic leaves by now, which is the egress for translation and
|
||||||
|
/// for the agent's own sockets. Read *before* the overlay routes are added.
|
||||||
|
fn default_route(run: Run<'_>, overlay: &str) -> Result<DefaultRoute, String> {
|
||||||
|
let out = run_ok(run, Tool::Route, &owned(&["-n", "get", "default"]), None)
|
||||||
|
.map_err(|why| format!("cannot find the default route: {why}"))?;
|
||||||
|
let route = parse_default_route(&out)
|
||||||
|
.ok_or_else(|| "the host has no default route to send traffic out of".to_string())?;
|
||||||
|
if route.interface == overlay {
|
||||||
|
return Err(format!(
|
||||||
|
"the default route already goes through `{overlay}`"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(route)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the kernel forwards IPv4. Read only.
|
||||||
|
fn forwarding_state(run: Run<'_>) -> Option<bool> {
|
||||||
|
let out = run_ok(
|
||||||
|
run,
|
||||||
|
Tool::Sysctl,
|
||||||
|
&owned(&["-n", "net.inet.ip.forwarding"]),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.ok()?;
|
||||||
|
match out.trim() {
|
||||||
|
"1" => Some(true),
|
||||||
|
"0" => Some(false),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The effective user id of this process, from `id -u`.
|
||||||
|
fn agent_uid(run: Run<'_>) -> Result<u32, String> {
|
||||||
|
run_ok(run, Tool::Id, &owned(&["-u"]), None)
|
||||||
|
.ok()
|
||||||
|
.and_then(|out| out.trim().parse().ok())
|
||||||
|
.ok_or_else(|| "cannot tell which user this agent runs as".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the using side adds to the rules.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct ClientRules<'a> {
|
||||||
|
uid: u32,
|
||||||
|
/// Every overlay range: the agent's own traffic *to* those still goes
|
||||||
|
/// through the interface.
|
||||||
|
overlay: &'a [Ipv4Range],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text of the anchor: translation first, filtering after, which is the
|
||||||
|
/// order `pf` insists on.
|
||||||
|
fn pf_rules(
|
||||||
|
interface: &str,
|
||||||
|
egress: &DefaultRoute,
|
||||||
|
offer: &[Ipv4Range],
|
||||||
|
client: Option<&ClientRules<'_>>,
|
||||||
|
) -> String {
|
||||||
|
let out = &egress.interface;
|
||||||
|
let mut nat = Vec::new();
|
||||||
|
let mut filter = Vec::new();
|
||||||
|
for range in offer {
|
||||||
|
nat.push(format!("nat on {out} inet from {range} to any -> ({out})"));
|
||||||
|
filter.push(format!(
|
||||||
|
"pass in quick on {interface} inet from {range} to ! {range}"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut tables = Vec::new();
|
||||||
|
if let Some(client) = client {
|
||||||
|
nat.push(format!(
|
||||||
|
"nat on {out} inet from ({interface}) to any -> ({out})"
|
||||||
|
));
|
||||||
|
let target = if client.overlay.is_empty() {
|
||||||
|
"any".to_string()
|
||||||
|
} else {
|
||||||
|
let ranges: Vec<String> = client.overlay.iter().map(|r| r.to_string()).collect();
|
||||||
|
// A table, because `! { a, b }` expands to one rule per element
|
||||||
|
// in older `pf`, which matches everything.
|
||||||
|
tables.push(format!(
|
||||||
|
"table <tsunagi_overlay_{interface}> const {{ {} }}",
|
||||||
|
ranges.join(", ")
|
||||||
|
));
|
||||||
|
format!("! <tsunagi_overlay_{interface}>")
|
||||||
|
};
|
||||||
|
let via = match egress.gateway {
|
||||||
|
Some(gateway) => format!("({out} {gateway})"),
|
||||||
|
None => out.clone(),
|
||||||
|
};
|
||||||
|
filter.push(format!(
|
||||||
|
"pass out quick on {interface} route-to {via} inet proto {{ tcp udp }} \
|
||||||
|
from any to {target} user {}",
|
||||||
|
client.uid
|
||||||
|
));
|
||||||
|
}
|
||||||
|
tables
|
||||||
|
.into_iter()
|
||||||
|
.chain(nat)
|
||||||
|
.chain(filter)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
+ "\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turns `pf` on if nobody has, holding the reference `pfctl` hands out so it
|
||||||
|
/// can be released when the agent is done. One reference at most.
|
||||||
|
fn acquire_pf(run: Run<'_>, slot: &Mutex<Option<String>>) -> Result<(), String> {
|
||||||
|
if lock(slot).is_some() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
match run(Tool::Pfctl, &owned(&["-E"]), None) {
|
||||||
|
Ran::Missing => Err(format!("{} not found", Tool::Pfctl.path())),
|
||||||
|
Ran::Exited {
|
||||||
|
success,
|
||||||
|
stdout,
|
||||||
|
stderr,
|
||||||
|
} => {
|
||||||
|
// `pfctl -E` reports `Token : <n>` on stderr, and also says so
|
||||||
|
// when pf is already enabled.
|
||||||
|
let token = stdout.lines().chain(stderr.lines()).find_map(parse_token);
|
||||||
|
if !success && token.is_none() {
|
||||||
|
return Err(format!("cannot enable pf: {}", failure(&stderr, &stdout)));
|
||||||
|
}
|
||||||
|
*lock(slot) = token;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_token(line: &str) -> Option<String> {
|
||||||
|
let (key, value) = line.split_once(':')?;
|
||||||
|
let value = value.trim();
|
||||||
|
(key.trim().eq_ignore_ascii_case("token")
|
||||||
|
&& !value.is_empty()
|
||||||
|
&& value.chars().all(|c| c.is_ascii_digit()))
|
||||||
|
.then(|| value.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release_pf(run: Run<'_>, slot: &Mutex<Option<String>>) {
|
||||||
|
if let Some(token) = lock(slot).take()
|
||||||
|
&& let Err(why) = run_ok(run, Tool::Pfctl, &["-X".to_string(), token], None)
|
||||||
|
{
|
||||||
|
tracing::debug!(%why, "cannot release the pf reference");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||||
|
match mutex.lock() {
|
||||||
|
Ok(guard) => guard,
|
||||||
|
Err(poisoned) => poisoned.into_inner(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush_args(anchor: &str) -> Vec<String> {
|
||||||
|
owned(&["-q", "-a", anchor, "-F", "all"])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_args(anchor: &str) -> Vec<String> {
|
||||||
|
owned(&["-q", "-a", anchor, "-f", "-"])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The two halves that out-rank the default route.
|
||||||
|
const HALVES: [&str; 2] = ["0.0.0.0/1", "128.0.0.0/1"];
|
||||||
|
/// The IPv6 halves, made unreachable.
|
||||||
|
const HALVES_V6: [&str; 2] = ["::/1", "8000::/1"];
|
||||||
|
|
||||||
|
fn route_add_args(half: &str, interface: &str) -> Vec<String> {
|
||||||
|
owned(&["-q", "-n", "add", "-net", half, "-interface", interface])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route_del_args(half: &str, interface: &str) -> Vec<String> {
|
||||||
|
owned(&["-q", "-n", "delete", "-net", half, "-interface", interface])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route_add_v6_args(half: &str) -> Vec<String> {
|
||||||
|
owned(&["-q", "-n", "add", "-inet6", "-net", half, "::1", "-reject"])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route_del_v6_args(half: &str) -> Vec<String> {
|
||||||
|
owned(&["-q", "-n", "delete", "-inet6", "-net", half, "::1"])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes away the overlay default routes. Best effort: what is not there is
|
||||||
|
/// the state wanted.
|
||||||
|
fn clear_routes(run: Run<'_>, interface: &str) {
|
||||||
|
for half in HALVES {
|
||||||
|
let _ = run(Tool::Route, &route_del_args(half, interface), None);
|
||||||
|
}
|
||||||
|
for half in HALVES_V6 {
|
||||||
|
let _ = run(Tool::Route, &route_del_v6_args(half), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_routes(run: Run<'_>, interface: &str) -> Result<(), String> {
|
||||||
|
clear_routes(run, interface);
|
||||||
|
for half in HALVES {
|
||||||
|
if let Err(why) = run_ok(run, Tool::Route, &route_add_args(half, interface), None) {
|
||||||
|
clear_routes(run, interface);
|
||||||
|
return Err(why);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for half in HALVES_V6 {
|
||||||
|
// A host without IPv6 has nothing to block; not a failure.
|
||||||
|
if let Err(why) = run_ok(run, Tool::Route, &route_add_v6_args(half), None) {
|
||||||
|
tracing::debug!(%why, "cannot block IPv6 for the exit node");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes the host match the plan.
|
||||||
|
pub(super) fn apply_plan(
|
||||||
|
run: Run<'_>,
|
||||||
|
token: &Mutex<Option<String>>,
|
||||||
|
plan: &ExitHostPlan,
|
||||||
|
) -> ExitHostReport {
|
||||||
|
let forwarding = if plan.offer.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
forwarding_state(run)
|
||||||
|
};
|
||||||
|
let outcome = apply_rules(run, token, plan);
|
||||||
|
let verdict = |ok: bool, why: &str| {
|
||||||
|
if ok {
|
||||||
|
RuleOutcome::Applied
|
||||||
|
} else {
|
||||||
|
RuleOutcome::Failed(why.to_string())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match outcome {
|
||||||
|
Ok(()) => ExitHostReport {
|
||||||
|
offer: plan
|
||||||
|
.offer
|
||||||
|
.iter()
|
||||||
|
.map(|range| (*range, RuleOutcome::Applied))
|
||||||
|
.collect(),
|
||||||
|
forwarding,
|
||||||
|
client: plan.client.then_some(RuleOutcome::Applied),
|
||||||
|
},
|
||||||
|
Err(why) => ExitHostReport {
|
||||||
|
offer: plan
|
||||||
|
.offer
|
||||||
|
.iter()
|
||||||
|
.map(|range| (*range, verdict(false, &why)))
|
||||||
|
.collect(),
|
||||||
|
forwarding,
|
||||||
|
client: plan.client.then(|| verdict(false, &why)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_rules(
|
||||||
|
run: Run<'_>,
|
||||||
|
token: &Mutex<Option<String>>,
|
||||||
|
plan: &ExitHostPlan,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let interface = plan.interface.as_str();
|
||||||
|
let anchor = anchor_name(interface)?;
|
||||||
|
let egress = default_route(run, interface)?;
|
||||||
|
let uid = if plan.client {
|
||||||
|
Some(agent_uid(run)?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let client = uid.map(|uid| ClientRules {
|
||||||
|
uid,
|
||||||
|
overlay: &plan.overlay,
|
||||||
|
});
|
||||||
|
let rules = pf_rules(interface, &egress, &plan.offer, client.as_ref());
|
||||||
|
|
||||||
|
acquire_pf(run, token)?;
|
||||||
|
run_ok(run, Tool::Pfctl, &load_args(&anchor), Some(&rules))
|
||||||
|
.map_err(|why| format!("cannot load the pf rules: {why}"))?;
|
||||||
|
// The routes come after the rules that keep the agent's own traffic off
|
||||||
|
// them: the other order would loop for as long as it takes.
|
||||||
|
if plan.client {
|
||||||
|
set_routes(run, interface)?;
|
||||||
|
} else {
|
||||||
|
clear_routes(run, interface);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes everything this agent put there for the interface.
|
||||||
|
pub(super) fn clear_all(run: Run<'_>, token: &Mutex<Option<String>>, interface: &str) {
|
||||||
|
clear_routes(run, interface);
|
||||||
|
if let Ok(anchor) = anchor_name(interface) {
|
||||||
|
// Flushing an anchor nothing was ever loaded into is not an error
|
||||||
|
// worth reporting.
|
||||||
|
if let Err(why) = run_ok(run, Tool::Pfctl, &flush_args(&anchor), None) {
|
||||||
|
tracing::debug!(%why, "cannot flush the exit node pf anchor");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
release_pf(run, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::cell::RefCell;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn range() -> Ipv4Range {
|
||||||
|
"10.13.37.0/24".parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_ROUTE: &str = " route to: default\n\
|
||||||
|
destination: default\n\
|
||||||
|
mask: default\n\
|
||||||
|
gateway: 192.168.1.1\n\
|
||||||
|
interface: en0\n\
|
||||||
|
flags: <UP,GATEWAY,DONE,STATIC,PRCLONING,GLOBAL>\n";
|
||||||
|
|
||||||
|
fn egress() -> DefaultRoute {
|
||||||
|
DefaultRoute {
|
||||||
|
interface: "en0".into(),
|
||||||
|
gateway: Some(Ipv4Addr::new(192, 168, 1, 1)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A scripted host that records every call.
|
||||||
|
struct Fake {
|
||||||
|
calls: RefCell<Vec<String>>,
|
||||||
|
stdins: RefCell<Vec<String>>,
|
||||||
|
default_route: Option<String>,
|
||||||
|
forwarding: &'static str,
|
||||||
|
pf_missing: bool,
|
||||||
|
pf_load_fails: bool,
|
||||||
|
route_add_fails: bool,
|
||||||
|
pf_enable_output: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fake {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
calls: RefCell::new(Vec::new()),
|
||||||
|
stdins: RefCell::new(Vec::new()),
|
||||||
|
default_route: Some(DEFAULT_ROUTE.to_string()),
|
||||||
|
forwarding: "1\n",
|
||||||
|
pf_missing: false,
|
||||||
|
pf_load_fails: false,
|
||||||
|
route_add_fails: false,
|
||||||
|
pf_enable_output: "pf enabled\nToken : 4242\n",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, tool: Tool, args: &[String], stdin: Option<&str>) -> Ran {
|
||||||
|
let line = format!("{:?} {}", tool, args.join(" "));
|
||||||
|
self.calls.borrow_mut().push(line);
|
||||||
|
if let Some(text) = stdin {
|
||||||
|
self.stdins.borrow_mut().push(text.to_string());
|
||||||
|
}
|
||||||
|
let ok = |stdout: &str, stderr: &str| Ran::Exited {
|
||||||
|
success: true,
|
||||||
|
stdout: stdout.to_string(),
|
||||||
|
stderr: stderr.to_string(),
|
||||||
|
};
|
||||||
|
let fail = |why: &str| Ran::Exited {
|
||||||
|
success: false,
|
||||||
|
stdout: String::new(),
|
||||||
|
stderr: why.to_string(),
|
||||||
|
};
|
||||||
|
match tool {
|
||||||
|
Tool::Id => ok("0\n", ""),
|
||||||
|
Tool::Sysctl => ok(self.forwarding, ""),
|
||||||
|
Tool::Route if args.first().map(String::as_str) == Some("-n") => {
|
||||||
|
match &self.default_route {
|
||||||
|
Some(text) => ok(text, ""),
|
||||||
|
None => fail("route: writing to routing socket: not in table"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Tool::Route if args.contains(&"add".to_string()) && self.route_add_fails => {
|
||||||
|
fail("route: writing to routing socket: File exists")
|
||||||
|
}
|
||||||
|
Tool::Route => ok("", ""),
|
||||||
|
Tool::Pfctl if self.pf_missing => Ran::Missing,
|
||||||
|
Tool::Pfctl if args == ["-E"] => ok("", self.pf_enable_output),
|
||||||
|
Tool::Pfctl if args.contains(&"-f".to_string()) && self.pf_load_fails => {
|
||||||
|
fail("pfctl: Syntax error")
|
||||||
|
}
|
||||||
|
Tool::Pfctl => ok("", ""),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calls(&self) -> Vec<String> {
|
||||||
|
self.calls.borrow().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn position(&self, needle: &str) -> Option<usize> {
|
||||||
|
self.calls.borrow().iter().position(|c| c.contains(needle))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count(&self, needle: &str) -> usize {
|
||||||
|
self.calls
|
||||||
|
.borrow()
|
||||||
|
.iter()
|
||||||
|
.filter(|c| c.contains(needle))
|
||||||
|
.count()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plan(offer: bool, client: bool) -> ExitHostPlan {
|
||||||
|
ExitHostPlan {
|
||||||
|
interface: "utun5".into(),
|
||||||
|
offer: if offer { vec![range()] } else { Vec::new() },
|
||||||
|
client,
|
||||||
|
overlay: vec![range()],
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_default_route_is_read_from_route_output() {
|
||||||
|
assert_eq!(parse_default_route(DEFAULT_ROUTE), Some(egress()));
|
||||||
|
// A point-to-point default has no gateway line to use.
|
||||||
|
let ppp = "destination: default\n interface: ppp0\n";
|
||||||
|
assert_eq!(
|
||||||
|
parse_default_route(ppp),
|
||||||
|
Some(DefaultRoute {
|
||||||
|
interface: "ppp0".into(),
|
||||||
|
gateway: None
|
||||||
|
})
|
||||||
|
);
|
||||||
|
assert_eq!(parse_default_route("route: not in table"), None);
|
||||||
|
// An interface name that is not plain letters and digits never ends
|
||||||
|
// up in a rule.
|
||||||
|
assert_eq!(parse_default_route("interface: en0; pass all\n"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_anchor_is_under_com_apple_and_only_for_plain_names() {
|
||||||
|
assert_eq!(
|
||||||
|
anchor_name("utun5").unwrap(),
|
||||||
|
"com.apple/tsunagi-exit-utun5"
|
||||||
|
);
|
||||||
|
assert!(anchor_name("").is_err());
|
||||||
|
assert!(anchor_name("utun5 pass all").is_err());
|
||||||
|
assert!(anchor_name("../x").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offering_translates_the_range_and_admits_it_in() {
|
||||||
|
let text = pf_rules("utun5", &egress(), &[range()], None);
|
||||||
|
assert_eq!(
|
||||||
|
text,
|
||||||
|
"nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\
|
||||||
|
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\n"
|
||||||
|
);
|
||||||
|
// Translation precedes filtering, as pf requires.
|
||||||
|
assert!(text.find("nat on").unwrap() < text.find("pass in").unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn using_sends_the_agents_own_traffic_back_out_the_physical_interface() {
|
||||||
|
let other: Ipv4Range = "10.99.0.0/16".parse().unwrap();
|
||||||
|
let overlay = [range(), other];
|
||||||
|
let client = ClientRules {
|
||||||
|
uid: 0,
|
||||||
|
overlay: &overlay,
|
||||||
|
};
|
||||||
|
let text = pf_rules("utun5", &egress(), &[], Some(&client));
|
||||||
|
assert!(
|
||||||
|
text.starts_with(
|
||||||
|
"table <tsunagi_overlay_utun5> const { 10.13.37.0/24, 10.99.0.0/16 }\n"
|
||||||
|
),
|
||||||
|
"{text}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
text.contains("nat on en0 inet from (utun5) to any -> (en0)\n"),
|
||||||
|
"{text}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
text.contains(
|
||||||
|
"pass out quick on utun5 route-to (en0 192.168.1.1) inet proto { tcp udp } \
|
||||||
|
from any to ! <tsunagi_overlay_utun5> user 0\n"
|
||||||
|
),
|
||||||
|
"{text}"
|
||||||
|
);
|
||||||
|
// Only the agent's user, and only what is not the overlay.
|
||||||
|
assert!(!text.contains("from any to any"));
|
||||||
|
|
||||||
|
let direct = DefaultRoute {
|
||||||
|
interface: "ppp0".into(),
|
||||||
|
gateway: None,
|
||||||
|
};
|
||||||
|
let text = pf_rules(
|
||||||
|
"utun5",
|
||||||
|
&direct,
|
||||||
|
&[],
|
||||||
|
Some(&ClientRules {
|
||||||
|
uid: 501,
|
||||||
|
overlay: &[],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert!(text.contains("route-to ppp0 inet"), "{text}");
|
||||||
|
assert!(text.contains("to any user 501"), "{text}");
|
||||||
|
assert!(!text.contains("table"), "{text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_overlay_default_routes_are_halves_and_ipv6_is_rejected() {
|
||||||
|
assert_eq!(
|
||||||
|
route_add_args("0.0.0.0/1", "utun5").join(" "),
|
||||||
|
"-q -n add -net 0.0.0.0/1 -interface utun5"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
route_del_args("128.0.0.0/1", "utun5").join(" "),
|
||||||
|
"-q -n delete -net 128.0.0.0/1 -interface utun5"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
route_add_v6_args("8000::/1").join(" "),
|
||||||
|
"-q -n add -inet6 -net 8000::/1 ::1 -reject"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
route_del_v6_args("::/1").join(" "),
|
||||||
|
"-q -n delete -inet6 -net ::/1 ::1"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_pf_token_is_found_in_either_stream() {
|
||||||
|
assert_eq!(parse_token("Token : 1234"), Some("1234".into()));
|
||||||
|
assert_eq!(parse_token("token: 9"), Some("9".into()));
|
||||||
|
assert_eq!(parse_token("pf enabled"), None);
|
||||||
|
assert_eq!(parse_token("Token : x; rm"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offering_loads_the_anchor_and_reads_but_never_writes_forwarding() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||||
|
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
|
||||||
|
assert_eq!(report.forwarding, Some(true));
|
||||||
|
assert_eq!(report.client, None);
|
||||||
|
let calls = fake.calls();
|
||||||
|
assert!(
|
||||||
|
calls
|
||||||
|
.iter()
|
||||||
|
.any(|c| c == "Pfctl -q -a com.apple/tsunagi-exit-utun5 -f -"),
|
||||||
|
"{calls:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fake.stdins.borrow()[0],
|
||||||
|
"nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\
|
||||||
|
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\n"
|
||||||
|
);
|
||||||
|
// sysctl is only ever asked, never told.
|
||||||
|
assert!(
|
||||||
|
calls
|
||||||
|
.iter()
|
||||||
|
.filter(|c| c.starts_with("Sysctl"))
|
||||||
|
.all(|c| c == "Sysctl -n net.inet.ip.forwarding"),
|
||||||
|
"{calls:?}"
|
||||||
|
);
|
||||||
|
// No client routes were added for an offer alone.
|
||||||
|
assert_eq!(fake.count(" add "), 0);
|
||||||
|
assert_eq!(token.lock().unwrap().as_deref(), Some("4242"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn forwarding_off_is_reported_and_unreadable_is_none() {
|
||||||
|
let mut fake = Fake::new();
|
||||||
|
fake.forwarding = "0\n";
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||||
|
assert_eq!(report.forwarding, Some(false));
|
||||||
|
fake.forwarding = "junk";
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||||
|
assert_eq!(report.forwarding, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_client_rules_are_loaded_before_the_routes_that_need_them() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true));
|
||||||
|
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||||
|
assert!(report.offer.is_empty());
|
||||||
|
let load = fake.position("-f -").unwrap();
|
||||||
|
let add = fake.position(" add -net 0.0.0.0/1").unwrap();
|
||||||
|
assert!(load < add, "{:?}", fake.calls());
|
||||||
|
assert!(fake.position("add -net 128.0.0.0/1").is_some());
|
||||||
|
assert!(fake.position("-inet6 -net ::/1 ::1 -reject").is_some());
|
||||||
|
assert!(fake.stdins.borrow()[0].contains("user 0"));
|
||||||
|
// The default route was read before any overlay route existed.
|
||||||
|
assert!(fake.position("-n get default").unwrap() < add);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_routes_are_added_when_the_rules_did_not_load() {
|
||||||
|
let mut fake = Fake::new();
|
||||||
|
fake.pf_load_fails = true;
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true));
|
||||||
|
let Some(RuleOutcome::Failed(why)) = report.client else {
|
||||||
|
panic!("{report:?}");
|
||||||
|
};
|
||||||
|
assert!(why.contains("cannot load the pf rules"), "{why}");
|
||||||
|
assert!(why.contains("Syntax error"), "{why}");
|
||||||
|
assert!(matches!(report.offer[0].1, RuleOutcome::Failed(_)));
|
||||||
|
// Nothing sent the host's traffic into a tunnel it could not exempt
|
||||||
|
// the agent from.
|
||||||
|
assert_eq!(fake.count(" add "), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failing_route_is_a_failure_and_leaves_nothing_behind() {
|
||||||
|
let mut fake = Fake::new();
|
||||||
|
fake.route_add_fails = true;
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true));
|
||||||
|
let Some(RuleOutcome::Failed(why)) = report.client else {
|
||||||
|
panic!("{report:?}");
|
||||||
|
};
|
||||||
|
assert!(why.contains("File exists"), "{why}");
|
||||||
|
// The cleanup after the failed add removed whatever did land.
|
||||||
|
let last_add = fake
|
||||||
|
.calls()
|
||||||
|
.iter()
|
||||||
|
.rposition(|c| c.contains(" add "))
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
fake.calls()[last_add..]
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.contains("delete"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_missing_pfctl_or_default_route_says_what_is_wrong() {
|
||||||
|
let mut fake = Fake::new();
|
||||||
|
fake.pf_missing = true;
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||||
|
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
|
||||||
|
panic!("{report:?}");
|
||||||
|
};
|
||||||
|
assert!(why.contains("/sbin/pfctl not found"), "{why}");
|
||||||
|
|
||||||
|
let mut fake = Fake::new();
|
||||||
|
fake.default_route = None;
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||||
|
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
|
||||||
|
panic!("{report:?}");
|
||||||
|
};
|
||||||
|
assert!(why.contains("default route"), "{why}");
|
||||||
|
assert_eq!(fake.count("-f -"), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_default_route_through_the_overlay_is_refused() {
|
||||||
|
let mut fake = Fake::new();
|
||||||
|
fake.default_route = Some("gateway: 10.13.37.1\ninterface: utun5\n".into());
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||||
|
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
|
||||||
|
panic!("{report:?}");
|
||||||
|
};
|
||||||
|
assert!(why.contains("already goes through"), "{why}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pf_is_enabled_once_and_released_once_on_clear() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||||
|
apply_plan(&run, &token, &plan(true, false));
|
||||||
|
apply_plan(&run, &token, &plan(true, true));
|
||||||
|
assert_eq!(fake.count("Pfctl -E"), 1, "{:?}", fake.calls());
|
||||||
|
|
||||||
|
clear_all(&run, &token, "utun5");
|
||||||
|
assert_eq!(fake.count("Pfctl -X 4242"), 1);
|
||||||
|
assert!(
|
||||||
|
fake.position("-a com.apple/tsunagi-exit-utun5 -F all")
|
||||||
|
.is_some()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
fake.position("delete -net 0.0.0.0/1 -interface utun5")
|
||||||
|
.is_some()
|
||||||
|
);
|
||||||
|
assert_eq!(*token.lock().unwrap(), None);
|
||||||
|
// A second clear has nothing to release and still succeeds.
|
||||||
|
clear_all(&run, &token, "utun5");
|
||||||
|
assert_eq!(fake.count("Pfctl -X"), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dropping_the_client_removes_its_routes() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let token = Mutex::new(None);
|
||||||
|
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||||
|
apply_plan(&run, &token, &plan(true, false));
|
||||||
|
assert!(fake.position("delete -net 0.0.0.0/1").is_some());
|
||||||
|
assert_eq!(fake.count(" add "), 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
+40
-1
@@ -45,19 +45,36 @@ use std::sync::{Arc, Mutex};
|
|||||||
use crate::BoxFuture;
|
use crate::BoxFuture;
|
||||||
use crate::state::Ipv4Range;
|
use crate::state::Ipv4Range;
|
||||||
|
|
||||||
|
mod exit;
|
||||||
|
pub use exit::{
|
||||||
|
ExitHostPlan, ExitHostReport, ExitHostRules, MockExitRules, exit_tag, exit_tag_prefix,
|
||||||
|
offer_detail,
|
||||||
|
};
|
||||||
|
|
||||||
#[cfg(all(feature = "tun-device", target_os = "linux"))]
|
#[cfg(all(feature = "tun-device", target_os = "linux"))]
|
||||||
mod linux;
|
mod linux;
|
||||||
#[cfg(all(feature = "tun-device", target_os = "linux"))]
|
#[cfg(all(feature = "tun-device", target_os = "linux"))]
|
||||||
|
mod linux_exit;
|
||||||
|
#[cfg(all(test, feature = "tun-device", target_os = "linux"))]
|
||||||
|
mod linux_exit_kernel;
|
||||||
|
#[cfg(all(feature = "tun-device", target_os = "linux"))]
|
||||||
|
pub(in crate::overlay) mod linux_exit_mark;
|
||||||
|
#[cfg(all(feature = "tun-device", target_os = "linux"))]
|
||||||
pub use linux::LinuxHostRules;
|
pub use linux::LinuxHostRules;
|
||||||
|
|
||||||
// Compiled everywhere so the scripts it builds are tested everywhere; only
|
// Compiled everywhere so the scripts it builds are tested everywhere; only
|
||||||
// the type that runs them is exported on Windows.
|
// the type that runs them is exported on Windows.
|
||||||
mod windows;
|
mod windows;
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
mod windows_exit;
|
||||||
#[cfg(all(feature = "tun-device", target_os = "windows"))]
|
#[cfg(all(feature = "tun-device", target_os = "windows"))]
|
||||||
pub use windows::WindowsHostRules;
|
pub use windows::WindowsHostRules;
|
||||||
|
|
||||||
|
// Compiled everywhere so its rule text and parsers are tested everywhere.
|
||||||
#[cfg(all(feature = "tun-device", target_os = "macos"))]
|
#[cfg(all(feature = "tun-device", target_os = "macos"))]
|
||||||
mod macos;
|
mod macos;
|
||||||
|
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||||
|
mod macos_exit;
|
||||||
#[cfg(all(feature = "tun-device", target_os = "macos"))]
|
#[cfg(all(feature = "tun-device", target_os = "macos"))]
|
||||||
pub use macos::MacosHostRules;
|
pub use macos::MacosHostRules;
|
||||||
|
|
||||||
@@ -159,6 +176,15 @@ pub trait BroadcastHostRules: Send + Sync + std::fmt::Debug + 'static {
|
|||||||
/// Removes what this agent put there for the interface. Succeeds when
|
/// Removes what this agent put there for the interface. Succeeds when
|
||||||
/// nothing is there: it runs on the shutdown path.
|
/// nothing is there: it runs on the shutdown path.
|
||||||
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()>;
|
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()>;
|
||||||
|
|
||||||
|
/// The exit-node rules that go with these, when the platform has them.
|
||||||
|
///
|
||||||
|
/// One object per host, because both halves need the same privileged
|
||||||
|
/// helpers; the default is that this platform has none, which is said
|
||||||
|
/// where it matters rather than pretended.
|
||||||
|
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The platform has no implementation, which is said rather than pretended.
|
/// The platform has no implementation, which is said rather than pretended.
|
||||||
@@ -195,6 +221,7 @@ pub type MockRulesState = std::collections::BTreeMap<String, BroadcastRulesPlan>
|
|||||||
/// An in-memory host, for tests: nothing is touched.
|
/// An in-memory host, for tests: nothing is touched.
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct MockHostRules {
|
pub struct MockHostRules {
|
||||||
|
exit: MockExitRules,
|
||||||
state: Arc<Mutex<MockRulesState>>,
|
state: Arc<Mutex<MockRulesState>>,
|
||||||
calls: Arc<Mutex<Vec<String>>>,
|
calls: Arc<Mutex<Vec<String>>>,
|
||||||
firewall_failure: Arc<Mutex<Option<String>>>,
|
firewall_failure: Arc<Mutex<Option<String>>>,
|
||||||
@@ -203,7 +230,15 @@ pub struct MockHostRules {
|
|||||||
impl MockHostRules {
|
impl MockHostRules {
|
||||||
/// An empty host.
|
/// An empty host.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self::default()
|
Self {
|
||||||
|
exit: MockExitRules::new(),
|
||||||
|
..Self::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The exit-node half of this host, for inspecting and steering tests.
|
||||||
|
pub fn exit(&self) -> &MockExitRules {
|
||||||
|
&self.exit
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Makes the firewall step fail with this reason from now on.
|
/// Makes the firewall step fail with this reason from now on.
|
||||||
@@ -234,6 +269,10 @@ impl BroadcastHostRules for MockHostRules {
|
|||||||
"mock"
|
"mock"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
|
||||||
|
Some(&self.exit)
|
||||||
|
}
|
||||||
|
|
||||||
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
lock(&self.calls).push(format!("apply:{}", plan.interface));
|
lock(&self.calls).push(format!("apply:{}", plan.interface));
|
||||||
+71
-2
@@ -29,6 +29,8 @@
|
|||||||
|
|
||||||
use crate::BoxFuture;
|
use crate::BoxFuture;
|
||||||
|
|
||||||
|
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
|
||||||
|
use super::windows_exit;
|
||||||
use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome, tag_for};
|
use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome, tag_for};
|
||||||
|
|
||||||
/// A PowerShell single-quoted literal, with any embedded quote doubled.
|
/// A PowerShell single-quoted literal, with any embedded quote doubled.
|
||||||
@@ -90,7 +92,7 @@ fn classify(what: &str, text: &str) -> String {
|
|||||||
|| lower.contains("run as administrator")
|
|| lower.contains("run as administrator")
|
||||||
|| lower.contains("permissiondenied")
|
|| lower.contains("permissiondenied")
|
||||||
{
|
{
|
||||||
format!("{what}: Windows refused; run tsunagi from an elevated (administrator) process")
|
format!("{what}: Windows refused; run tsng from an elevated (administrator) process")
|
||||||
} else if lower.contains("is not recognized") || lower.contains("commandnotfound") {
|
} else if lower.contains("is not recognized") || lower.contains("commandnotfound") {
|
||||||
format!("{what}: the NetTCPIP/NetSecurity PowerShell modules are not available: {text}")
|
format!("{what}: the NetTCPIP/NetSecurity PowerShell modules are not available: {text}")
|
||||||
} else if text.is_empty() {
|
} else if text.is_empty() {
|
||||||
@@ -113,6 +115,11 @@ fn powershell_path() -> std::path::PathBuf {
|
|||||||
|
|
||||||
/// Runs a script and returns what it said on failure.
|
/// Runs a script and returns what it said on failure.
|
||||||
fn run_powershell(script: &str) -> Result<(), String> {
|
fn run_powershell(script: &str) -> Result<(), String> {
|
||||||
|
run_powershell_output(script).map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a script and returns what it printed, or what it said on failure.
|
||||||
|
fn run_powershell_output(script: &str) -> Result<String, String> {
|
||||||
let output = std::process::Command::new(powershell_path())
|
let output = std::process::Command::new(powershell_path())
|
||||||
.args([
|
.args([
|
||||||
"-NoProfile",
|
"-NoProfile",
|
||||||
@@ -125,7 +132,7 @@ fn run_powershell(script: &str) -> Result<(), String> {
|
|||||||
.output()
|
.output()
|
||||||
.map_err(|err| format!("could not run PowerShell: {err}"))?;
|
.map_err(|err| format!("could not run PowerShell: {err}"))?;
|
||||||
if output.status.success() {
|
if output.status.success() {
|
||||||
return Ok(());
|
return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
|
||||||
}
|
}
|
||||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
let text = if stderr.trim().is_empty() {
|
let text = if stderr.trim().is_empty() {
|
||||||
@@ -155,11 +162,73 @@ impl WindowsHostRules {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The IPv4 addresses a host name resolves to; empty when it does not.
|
||||||
|
fn resolve_host(host: &str) -> Vec<std::net::Ipv4Addr> {
|
||||||
|
use std::net::{IpAddr, ToSocketAddrs};
|
||||||
|
(host, 443)
|
||||||
|
.to_socket_addrs()
|
||||||
|
.map(|addrs| {
|
||||||
|
addrs
|
||||||
|
.filter_map(|addr| match addr.ip() {
|
||||||
|
IpAddr::V4(ip) => Some(ip),
|
||||||
|
IpAddr::V6(_) => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExitHostRules for WindowsHostRules {
|
||||||
|
fn needs_bypass(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let job = plan.clone();
|
||||||
|
tokio::task::spawn_blocking(move || {
|
||||||
|
windows_exit::apply_plan(
|
||||||
|
&|script| run_powershell_output(script),
|
||||||
|
&resolve_host,
|
||||||
|
&job,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|err| {
|
||||||
|
let failed = RuleOutcome::Failed(format!("the task failed: {err}"));
|
||||||
|
ExitHostReport {
|
||||||
|
offer: plan
|
||||||
|
.offer
|
||||||
|
.iter()
|
||||||
|
.map(|range| (*range, failed.clone()))
|
||||||
|
.collect(),
|
||||||
|
forwarding: None,
|
||||||
|
client: plan.client.then_some(failed),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let name = interface.to_string();
|
||||||
|
let _ = tokio::task::spawn_blocking(move || {
|
||||||
|
windows_exit::clear_all(&|script| run_powershell_output(script), &name)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl BroadcastHostRules for WindowsHostRules {
|
impl BroadcastHostRules for WindowsHostRules {
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"windows-netsecurity"
|
"windows-netsecurity"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
|
||||||
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let route = step("route", route_script(plan)).await;
|
let route = step("route", route_script(plan)).await;
|
||||||
Loaded 100 of 335 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user