Compare commits
182
Commits
5cc92d7067
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f60c11fc20 | ||
|
|
87fa83e482 | ||
|
|
a966152143 | ||
|
|
6e71d8cf8c | ||
|
|
16d7f82af5 | ||
|
|
68f19d1758 | ||
|
|
8e0cfc97ac | ||
|
|
7b83aec3be | ||
|
|
21de427c62 | ||
|
|
a1da4bf498 | ||
|
|
9920d4c10f | ||
|
|
7dacc4517e | ||
|
|
43894612ee | ||
|
|
d8b7787430 | ||
|
|
b47acb8321 | ||
|
|
e3b74babba | ||
|
|
7afed15f76 | ||
|
|
e7de9b44af | ||
|
|
200e716c28 | ||
|
|
fb7a959d23 | ||
|
|
6a0a87e76c | ||
|
|
e3e6089d0b | ||
|
|
50c0ecea45 | ||
|
|
8c4c2fa34e | ||
|
|
f9f67f88b1 | ||
|
|
a189d0ad3e | ||
|
|
32aa73721a | ||
|
|
21b8381fa3 | ||
|
|
ee77ddb9ac | ||
|
|
219bd018db | ||
|
|
15a4e45710 | ||
|
|
972b98363d | ||
|
|
2e83483f00 | ||
|
|
27e29cf8a7 | ||
|
|
8d107cf0e9 | ||
|
|
01b51081c3 | ||
|
|
d72e8886d6 | ||
|
|
e3a86aa9d3 | ||
|
|
42c25f29ec | ||
|
|
04b5ebc1a0 | ||
|
|
429fa36e3e | ||
|
|
ef67e1c0ae | ||
|
|
9dec056349 | ||
|
|
91227afbac | ||
|
|
66206544b0 | ||
|
|
2166ba4800 | ||
|
|
8a6216bccb | ||
|
|
2e7e238459 | ||
|
|
23af1a2d9d | ||
|
|
94318e7c16 | ||
|
|
2b0c938487 | ||
|
|
4e235cbac6 | ||
|
|
2631eb6975 | ||
|
|
90ef5cefec | ||
|
|
13bdcaf98d | ||
|
|
d941cdac7a | ||
|
|
e701986a39 | ||
|
|
ed28e86748 | ||
|
|
781e359775 | ||
|
|
d5e02ec256 | ||
|
|
97377e3703 | ||
|
|
c184ef0914 | ||
|
|
e6ec62bcba | ||
|
|
21328bf818 | ||
|
|
7c176e0b74 | ||
|
|
637915600e | ||
|
|
47c5d38d0c | ||
|
|
0cfc1cbafc | ||
|
|
c9c653023d | ||
|
|
9966b50407 | ||
|
|
bb38562b0a | ||
|
|
b2431d7eb1 | ||
|
|
c62d29fa14 | ||
|
|
a6d9edabee | ||
|
|
2f7f9980c7 | ||
|
|
2e178a6f9d | ||
|
|
f4dcdec662 | ||
|
|
69310108f4 | ||
|
|
e7dff34ec2 | ||
|
|
a55ea883a1 | ||
|
|
3e066f991f | ||
|
|
3752419075 | ||
|
|
f63343a6a0 | ||
|
|
d13bb00623 | ||
|
|
2a0a8abd60 | ||
|
|
db01c58a6f | ||
|
|
de56258eb1 | ||
|
|
8f5ce21ce9 | ||
|
|
0a344c1b4f | ||
|
|
2cda56e1f8 | ||
|
|
d1de61ba29 | ||
|
|
19509dc833 | ||
|
|
de8e48bee7 | ||
|
|
8c812e6874 | ||
|
|
63178574ce | ||
|
|
a3856eed3b | ||
|
|
eac54f8c79 | ||
|
|
a8dfd7017b | ||
|
|
99f4cf0220 | ||
|
|
69263b2dd9 | ||
|
|
20444013c0 | ||
|
|
2196f6635b | ||
|
|
6438982d45 | ||
|
|
21b619388c | ||
|
|
d1ab993dd2 | ||
|
|
da7ce1dca1 | ||
|
|
4d2f8a54ec | ||
|
|
c3a6201ee2 | ||
|
|
533921059a | ||
|
|
d2778f0b5a | ||
|
|
8cfece9479 | ||
|
|
3930dff2dc | ||
|
|
35acc4d231 | ||
|
|
c791102ad9 | ||
|
|
f80841da63 | ||
|
|
7070a16104 | ||
|
|
46575d0899 | ||
|
|
a89e65475d | ||
|
|
2ed447ae86 | ||
|
|
ac5a1596ef | ||
|
|
192ab25bbd | ||
|
|
c0a76f1942 | ||
|
|
510116afb9 | ||
|
|
e24548b3b0 | ||
|
|
a4e341cd66 | ||
|
|
41990c9934 | ||
|
|
254a25ebd6 | ||
|
|
5495cb5b34 | ||
|
|
fac3bd7bb9 | ||
|
|
db9015b26c | ||
|
|
c724981bfd | ||
|
|
b4f3e57c8d | ||
|
|
d1a0eca723 | ||
|
|
686c74a3bd | ||
|
|
9698f21d55 | ||
|
|
72eaf9a228 | ||
|
|
e735151d62 | ||
|
|
458051f47d | ||
|
|
83d3445b7e | ||
|
|
3581feb9b9 | ||
|
|
3044e592bd | ||
|
|
9b240672e6 | ||
|
|
1b2f050c05 | ||
|
|
637e2f74e4 | ||
|
|
415b6a6667 | ||
|
|
0f97d60854 | ||
|
|
44a799faee | ||
|
|
41604225ba | ||
|
|
fae3816bbf | ||
|
|
0b3915d52b | ||
|
|
4c84cc9e4b | ||
|
|
990b9f2e0f | ||
|
|
142fdf995c | ||
|
|
ff7e235414 | ||
|
|
7c1be332e3 | ||
|
|
9415866193 | ||
|
|
c852de2c78 | ||
|
|
a80a014f20 | ||
|
|
41d5f554c7 | ||
|
|
745bbaea06 | ||
|
|
5bee148497 | ||
|
|
60e6b263d1 | ||
|
|
ca8759c023 | ||
|
|
75b37fdda3 | ||
|
|
240e471c88 | ||
|
|
43e8ac8159 | ||
|
|
776eedc669 | ||
|
|
8a6fb39689 | ||
|
|
3e83e33313 | ||
|
|
4759e47e31 | ||
|
|
b23e832a73 | ||
|
|
944d98389f | ||
|
|
8b333455f1 | ||
|
|
84c06c6cac | ||
|
|
ce64264027 | ||
|
|
cfab38824d | ||
|
|
be459e5bd0 | ||
|
|
d2e336f2f9 | ||
|
|
38beb762d8 | ||
|
|
0f8a4eb485 | ||
|
|
1dd7507bf4 | ||
|
|
fae62892e0 |
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"]
|
||||
@@ -0,0 +1,350 @@
|
||||
name: Release
|
||||
|
||||
# Build the agent for every supported target on a version tag, leave each build
|
||||
# as a run artifact, and then — only after every target has built — attach the
|
||||
# archives to the release. Linux is a fully static musl binary (built with
|
||||
# cargo-zigbuild) so one artifact runs on any distro and can be repackaged
|
||||
# however a distro prefers.
|
||||
#
|
||||
# Targeted at Gitea Actions: artifacts use @v3 (the v4 backend is not available
|
||||
# on Gitea/GHES), and the release is filled through Gitea's own API with curl
|
||||
# rather than `gh`, which speaks only to github.com.
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_NET_RETRY: "10"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: ${{ matrix.asset }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-musl
|
||||
asset: tsunagi-linux-x86_64
|
||||
archive: tar.gz
|
||||
zig: true
|
||||
deb: true
|
||||
deb_arch: amd64
|
||||
pkg_arch: x86_64
|
||||
gnu_target: x86_64-unknown-linux-gnu
|
||||
- os: ubuntu-latest
|
||||
target: aarch64-unknown-linux-musl
|
||||
asset: tsunagi-linux-aarch64
|
||||
archive: tar.gz
|
||||
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
|
||||
target: aarch64-apple-darwin
|
||||
asset: tsunagi-macos-aarch64
|
||||
archive: tar.gz
|
||||
zig: false
|
||||
- os: windows-latest
|
||||
target: x86_64-pc-windows-msvc
|
||||
asset: tsunagi-windows-x86_64
|
||||
archive: zip
|
||||
zig: false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: ${{ matrix.target }}
|
||||
|
||||
# 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
|
||||
# C build needs cmake. zig is the cross C compiler cargo-zigbuild drives.
|
||||
- name: Install musl build and packaging tooling
|
||||
if: matrix.zig
|
||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends cmake clang libclang-dev libarchive-tools zstd
|
||||
- name: Install zig
|
||||
if: matrix.zig
|
||||
uses: mlugg/setup-zig@v2
|
||||
with:
|
||||
# Pin a real, archived Zig release. Left unpinned the action resolves
|
||||
# to the newest version it knows of (a yet-unreleased 0.16.0-dev),
|
||||
# whose tarball 404s on ziglang.org while the community mirrors flake.
|
||||
version: 0.14.1
|
||||
- name: Install cargo-zigbuild
|
||||
if: matrix.zig
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: cargo-zigbuild
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ "${{ matrix.zig }}" == "true" ]]; then
|
||||
# zig's linker ignores the `-O1` GNU-ld optimization flag Rust passes
|
||||
# and says so on stderr, which rustc now surfaces as a linker_messages
|
||||
# warning. It is cosmetic — the binary is correct — so quiet just that
|
||||
# one lint to keep the musl build log clean. A real link error still
|
||||
# fails the build.
|
||||
export RUSTFLAGS="${RUSTFLAGS:-} -A linker_messages"
|
||||
cargo zigbuild --release --locked --target "${{ matrix.target }}" --bin tsng
|
||||
else
|
||||
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
|
||||
|
||||
- name: Package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
version="${GITHUB_REF_NAME#v}"
|
||||
stage="dist/pkg/${{ matrix.asset }}"
|
||||
mkdir -p "$stage"
|
||||
|
||||
bin="tsng"
|
||||
[[ "${{ runner.os }}" == "Windows" ]] && bin="tsng.exe"
|
||||
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
|
||||
# files, so the archive carries what the platform needs to set up.
|
||||
cp README.md "$stage/"
|
||||
case "${{ runner.os }}" in
|
||||
Linux)
|
||||
cp dist/linux/tsunagi.service dist/linux/install.sh \
|
||||
dist/linux/50-tsunagi-resolved.rules "$stage/"
|
||||
cp dist/linux/README.md "$stage/INSTALL.md"
|
||||
;;
|
||||
macOS)
|
||||
cp dist/macos/cy.hexor.tsunagi.plist "$stage/"
|
||||
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)
|
||||
cp dist/windows/README.md "$stage/INSTALL.md"
|
||||
;;
|
||||
esac
|
||||
|
||||
archive="${{ matrix.asset }}-${version}.${{ matrix.archive }}"
|
||||
if [[ "${{ matrix.archive }}" == "zip" ]]; then
|
||||
(cd dist/pkg && 7z a "../../${archive}" "${{ matrix.asset }}")
|
||||
else
|
||||
tar -C dist/pkg -czf "${archive}" "${{ matrix.asset }}"
|
||||
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
|
||||
# what makes the archive (and the .deb, where built) show up under the run
|
||||
# and hands it to `publish`.
|
||||
- name: Upload the build outputs as run artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ matrix.asset }}
|
||||
path: |
|
||||
${{ matrix.asset }}-*.*
|
||||
*.deb
|
||||
*.pkg.tar.zst
|
||||
tsunagi-setup-*.exe
|
||||
if-no-files-found: error
|
||||
|
||||
publish:
|
||||
name: Publish release
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Download every build artifact
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Show what was collected
|
||||
run: find artifacts -type f
|
||||
|
||||
- name: Create the release and upload the archives
|
||||
shell: bash
|
||||
env:
|
||||
# Gitea injects this with access to the current repository. If the
|
||||
# release calls below return 403, the repo/runner is configured to
|
||||
# hand Actions a read-only token — grant it write access to releases.
|
||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -u
|
||||
|
||||
tag="${GITHUB_REF_NAME}"
|
||||
# Gitea sets GITHUB_API_URL to its own API root (…/api/v1); fall back
|
||||
# to building it from the server URL if it is absent.
|
||||
base="${GITHUB_API_URL:-${GITHUB_SERVER_URL}/api/v1}"
|
||||
api="${base}/repos/${GITHUB_REPOSITORY}"
|
||||
auth="Authorization: token ${TOKEN}"
|
||||
echo "release API: $api"
|
||||
|
||||
prerelease=false
|
||||
case "$tag" in *-*) prerelease=true ;; esac
|
||||
|
||||
# The release id for this tag, if it already exists.
|
||||
code=$(curl -sS -o resp.json -w '%{http_code}' -H "$auth" "$api/releases/tags/$tag" || true)
|
||||
echo "get release by tag: HTTP $code"
|
||||
id=$(grep -o '"id":[0-9]*' resp.json 2>/dev/null | head -n1 | cut -d: -f2 || true)
|
||||
|
||||
if [ -z "$id" ]; then
|
||||
code=$(curl -sS -o resp.json -w '%{http_code}' -X POST -H "$auth" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"tag_name\":\"$tag\",\"name\":\"tsunagi $tag\",\"prerelease\":$prerelease}" \
|
||||
"$api/releases" || true)
|
||||
echo "create release: HTTP $code"
|
||||
id=$(grep -o '"id":[0-9]*' resp.json 2>/dev/null | head -n1 | cut -d: -f2 || true)
|
||||
if [ -z "$id" ]; then
|
||||
echo "could not create the release; response was:" >&2
|
||||
cat resp.json >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
echo "release id: $id"
|
||||
|
||||
# download-artifact@v3 nests each artifact in a directory named after
|
||||
# its upload, with the single archive inside. The read loop runs in
|
||||
# this shell (process substitution, not a pipe) so a failed upload
|
||||
# actually fails the job.
|
||||
rc=0
|
||||
while IFS= read -r -d '' f; do
|
||||
name=$(basename "$f")
|
||||
code=$(curl -sS -o up.json -w '%{http_code}' -X POST -H "$auth" \
|
||||
-F "attachment=@${f}" \
|
||||
"$api/releases/$id/assets?name=${name}" || true)
|
||||
echo "upload $name: HTTP $code"
|
||||
if [ "$code" -lt 200 ] || [ "$code" -ge 300 ]; then
|
||||
cat up.json >&2 || true
|
||||
rc=1
|
||||
fi
|
||||
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"
|
||||
@@ -0,0 +1,42 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from update_homebrew import update_tap
|
||||
|
||||
|
||||
class UpdateTapTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.tap = Path(directory.name)
|
||||
self.formula = self.tap / "Formula/tsunagi.rb"
|
||||
self.cask = self.tap / "Casks/tsunagi-gui.rb"
|
||||
self.formula.parent.mkdir()
|
||||
self.cask.parent.mkdir()
|
||||
self.old_hash = "a" * 64
|
||||
self.new_hash = "b" * 64
|
||||
self.formula.write_text(f' VERSION = "1.9.0"\n SHA256 = "{self.old_hash}"\n')
|
||||
self.cask.write_text(f' version "1.9.0"\n sha256 "{self.old_hash}"\n')
|
||||
|
||||
def test_updates_both_packages_and_allows_retry(self):
|
||||
for _ in range(2):
|
||||
update_tap(self.tap, "v1.10.0", self.new_hash)
|
||||
self.assertEqual(self.formula.read_text(), f' VERSION = "1.10.0"\n SHA256 = "{self.new_hash}"\n')
|
||||
self.assertEqual(self.cask.read_text(), f' version "1.10.0"\n sha256 "{self.new_hash}"\n')
|
||||
|
||||
def test_older_release_does_not_replace_either_package(self):
|
||||
before = self.formula.read_bytes(), self.cask.read_bytes()
|
||||
update_tap(self.tap, "v1.8.9", self.new_hash)
|
||||
self.assertEqual((self.formula.read_bytes(), self.cask.read_bytes()), before)
|
||||
|
||||
def test_invalid_release_or_cask_leaves_formula_untouched(self):
|
||||
before = self.formula.read_bytes()
|
||||
with self.assertRaises(ValueError):
|
||||
update_tap(self.tap, "v1.10.0-rc.1", self.new_hash)
|
||||
with self.assertRaises(ValueError):
|
||||
update_tap(self.tap, "v1.10.0", "invalid")
|
||||
self.cask.write_text(' version "1.9.0"\n')
|
||||
with self.assertRaises(ValueError):
|
||||
update_tap(self.tap, "v1.10.0", self.new_hash)
|
||||
self.assertEqual(self.formula.read_bytes(), before)
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Update the tap's formula and cask for a verified macOS release archive."""
|
||||
|
||||
import argparse
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
VERSION = r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}"
|
||||
SHA256 = r"[0-9a-f]{64}"
|
||||
|
||||
|
||||
def update_tap(tap: Path, tag: str, checksum: str) -> None:
|
||||
if not re.fullmatch(f"v{VERSION}", tag):
|
||||
raise ValueError("expected a stable vMAJOR.MINOR.PATCH release")
|
||||
if not re.fullmatch(SHA256, checksum):
|
||||
raise ValueError("expected a SHA-256 digest")
|
||||
|
||||
version = tag[1:]
|
||||
updates = {}
|
||||
for filename, version_field, hash_field in (
|
||||
("Formula/tsunagi.rb", "VERSION = ", "SHA256 = "),
|
||||
("Casks/tsunagi-gui.rb", "version ", "sha256 "),
|
||||
):
|
||||
path = tap / filename
|
||||
original = path.read_text()
|
||||
version_pattern = rf'^( {version_field}")({VERSION})(")$'
|
||||
hash_pattern = rf'^( {hash_field}")({SHA256})(")$'
|
||||
current = re.findall(version_pattern, original, re.MULTILINE)
|
||||
if len(current) != 1 or len(re.findall(hash_pattern, original, re.MULTILINE)) != 1:
|
||||
raise ValueError(f"expected one version and one SHA-256 in {filename}")
|
||||
if tuple(map(int, version.split("."))) < tuple(map(int, current[0][1].split("."))):
|
||||
print(f"Skipping older release {tag}: {filename} already has {current[0][1]}")
|
||||
return
|
||||
updated = re.sub(version_pattern, rf"\g<1>{version}\g<3>", original, flags=re.MULTILINE)
|
||||
updated = re.sub(hash_pattern, rf"\g<1>{checksum}\g<3>", updated, flags=re.MULTILINE)
|
||||
updates[path] = (original, updated)
|
||||
|
||||
for path, (original, updated) in updates.items():
|
||||
if updated != original:
|
||||
path.write_text(updated)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("tap", type=Path)
|
||||
parser.add_argument("tag")
|
||||
parser.add_argument("checksum")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
update_tap(args.tap, args.tag, args.checksum)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.exit(1, f"{error}\n")
|
||||
@@ -2,7 +2,7 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [master, main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -23,8 +23,16 @@ jobs:
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- &linux-tray-deps
|
||||
name: Install GTK and AppIndicator development files
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends libgtk-3-dev libayatana-appindicator3-dev
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
- name: Check Debian release candidate upgrade ordering
|
||||
run: bash dist/deb/test-deb.sh
|
||||
|
||||
test:
|
||||
name: test (${{ matrix.os }})
|
||||
@@ -37,11 +45,11 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo test --locked --workspace --all-targets
|
||||
- name: run the examples
|
||||
run: |
|
||||
cargo run --locked --example two_agents
|
||||
cargo run --locked --example wireguard_mesh
|
||||
- *linux-tray-deps
|
||||
- name: Test the workspace, including peer exchange and WireGuard integration
|
||||
run: cargo test --locked --workspace --all-targets
|
||||
- name: Start the command line client
|
||||
run: cargo run --locked --bin tsng -- --version
|
||||
|
||||
# The library must keep building without the command line binary and
|
||||
# without interface support, for embedders that want neither.
|
||||
@@ -52,7 +60,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo check --locked --no-default-features --lib
|
||||
- run: cargo check --locked -p tsunagi-core --no-default-features --lib
|
||||
|
||||
docs:
|
||||
name: rustdoc
|
||||
@@ -61,6 +69,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- *linux-tray-deps
|
||||
- run: cargo doc --locked --workspace --no-deps
|
||||
env:
|
||||
RUSTDOCFLAGS: -D warnings
|
||||
@@ -72,4 +81,5 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@1.91.0
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- *linux-tray-deps
|
||||
- run: cargo check --locked --workspace --all-targets
|
||||
@@ -0,0 +1,582 @@
|
||||
name: Release
|
||||
|
||||
# Desktop builds mirror .gitea/workflows/release.yml. GitHub also builds and
|
||||
# signs the Android APK and attaches all platform packages to the tag with gh.
|
||||
#
|
||||
# Every job is gated on `github.server_url == 'https://github.com'`, so this file
|
||||
# runs only on GitHub. Gitea runs its own copy in .gitea/workflows (which pins
|
||||
# the older @v3 artifact actions it supports); should a Gitea instance also read
|
||||
# .github/workflows, the guard skips these jobs there so they never fail on the
|
||||
# artifact backend or `gh`.
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_NET_RETRY: "10"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: ${{ matrix.asset }}
|
||||
if: ${{ github.server_url == 'https://github.com' }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-26.04
|
||||
target: x86_64-unknown-linux-musl
|
||||
asset: tsunagi-linux-x86_64
|
||||
archive: tar.gz
|
||||
zig: true
|
||||
deb: true
|
||||
deb_arch: amd64
|
||||
pkg_arch: x86_64
|
||||
gnu_target: x86_64-unknown-linux-gnu
|
||||
- os: ubuntu-latest
|
||||
target: aarch64-unknown-linux-musl
|
||||
asset: tsunagi-linux-aarch64
|
||||
archive: tar.gz
|
||||
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
|
||||
target: aarch64-apple-darwin
|
||||
asset: tsunagi-macos-aarch64
|
||||
archive: tar.gz
|
||||
zig: false
|
||||
- os: windows-latest
|
||||
target: x86_64-pc-windows-msvc
|
||||
asset: tsunagi-windows-x86_64
|
||||
archive: zip
|
||||
zig: false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: ${{ matrix.target }}
|
||||
|
||||
# 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
|
||||
# C build needs cmake. zig is the cross C compiler cargo-zigbuild drives.
|
||||
- name: Install musl build and packaging tooling
|
||||
if: matrix.zig
|
||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends cmake clang libclang-dev libarchive-tools zstd
|
||||
- name: Install zig
|
||||
if: matrix.zig
|
||||
uses: mlugg/setup-zig@v2
|
||||
with:
|
||||
# Pin a real, archived Zig release. Left unpinned the action resolves
|
||||
# to the newest version it knows of (a yet-unreleased 0.16.0-dev),
|
||||
# whose tarball 404s on ziglang.org while the community mirrors flake.
|
||||
version: 0.14.1
|
||||
- name: Install cargo-zigbuild
|
||||
if: matrix.zig
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: cargo-zigbuild
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ "${{ matrix.zig }}" == "true" ]]; then
|
||||
# zig's linker ignores the `-O1` GNU-ld optimization flag Rust passes
|
||||
# and says so on stderr, which rustc now surfaces as a linker_messages
|
||||
# warning. It is cosmetic — the binary is correct — so quiet just that
|
||||
# one lint to keep the musl build log clean. A real link error still
|
||||
# fails the build.
|
||||
export RUSTFLAGS="${RUSTFLAGS:-} -A linker_messages"
|
||||
cargo zigbuild --release --locked --target "${{ matrix.target }}" --bin tsng
|
||||
else
|
||||
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
|
||||
|
||||
- name: Package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
version="${GITHUB_REF_NAME#v}"
|
||||
stage="dist/pkg/${{ matrix.asset }}"
|
||||
mkdir -p "$stage"
|
||||
|
||||
bin="tsng"
|
||||
[[ "${{ runner.os }}" == "Windows" ]] && bin="tsng.exe"
|
||||
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
|
||||
# files, so the archive carries what the platform needs to set up.
|
||||
cp README.md "$stage/"
|
||||
case "${{ runner.os }}" in
|
||||
Linux)
|
||||
cp dist/linux/tsunagi.service dist/linux/install.sh \
|
||||
dist/linux/50-tsunagi-resolved.rules "$stage/"
|
||||
cp dist/linux/README.md "$stage/INSTALL.md"
|
||||
;;
|
||||
macOS)
|
||||
cp dist/macos/cy.hexor.tsunagi.plist "$stage/"
|
||||
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)
|
||||
cp dist/windows/README.md "$stage/INSTALL.md"
|
||||
;;
|
||||
esac
|
||||
|
||||
archive="${{ matrix.asset }}-${version}.${{ matrix.archive }}"
|
||||
if [[ "${{ matrix.archive }}" == "zip" ]]; then
|
||||
(cd dist/pkg && 7z a "../../${archive}" "${{ matrix.asset }}")
|
||||
else
|
||||
tar -C dist/pkg -czf "${archive}" "${{ matrix.asset }}"
|
||||
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"
|
||||
|
||||
- name: Upload the build outputs as run artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ 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
|
||||
|
||||
publish:
|
||||
name: Publish release
|
||||
needs: [build, android]
|
||||
if: ${{ github.server_url == 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Download every build artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Show what was collected
|
||||
run: find artifacts -type f
|
||||
|
||||
- name: Create the release and upload the archives
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# download-artifact nests each artifact under its own directory, so
|
||||
# the archives are artifacts/<asset>/<file>.
|
||||
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[@]}"
|
||||
|
||||
prerelease=()
|
||||
case "$TAG" in *-*) prerelease=(--prerelease) ;; esac
|
||||
|
||||
# Create the release on the first run; on a re-run, add/replace assets
|
||||
# on the release that is already there.
|
||||
if gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
||||
gh release upload "$TAG" "${files[@]}" --repo "$GITHUB_REPOSITORY" --clobber
|
||||
else
|
||||
gh release create "$TAG" "${files[@]}" \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--title "tsunagi $TAG" \
|
||||
--generate-notes \
|
||||
--verify-tag \
|
||||
"${prerelease[@]}"
|
||||
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 -
|
||||
|
||||
update-homebrew:
|
||||
name: Update the Homebrew tap
|
||||
needs: publish
|
||||
if: github.server_url == 'https://github.com' && github.repository == 'house-of-vanity/tsunagi'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
steps:
|
||||
- name: Check the release tag and tap credentials
|
||||
id: stable
|
||||
env:
|
||||
TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then
|
||||
echo "Skipping Homebrew for non-stable tag $RELEASE_TAG"
|
||||
exit 0
|
||||
fi
|
||||
if [[ -z "$TAP_TOKEN" ]]; then
|
||||
echo '::error::Set HOMEBREW_TAP_TOKEN with Contents: write access to house-of-vanity/homebrew-tap.'
|
||||
exit 1
|
||||
fi
|
||||
echo "publish=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.stable.outputs.publish == 'true'
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Verify the published macOS archive
|
||||
if: steps.stable.outputs.publish == 'true'
|
||||
id: archive
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
archive="tsunagi-macos-aarch64-${RELEASE_TAG#v}.tar.gz"
|
||||
digest=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" \
|
||||
| jq -er --arg archive "$archive" '
|
||||
select(.draft == false and .prerelease == false)
|
||||
| .assets[] | select(.name == $archive and .state == "uploaded")
|
||||
| .digest | select(type == "string" and test("^sha256:[0-9a-f]{64}$"))
|
||||
')
|
||||
gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \
|
||||
--pattern "$archive" --dir "$RUNNER_TEMP"
|
||||
hash="${digest#sha256:}"
|
||||
actual=$(sha256sum "$RUNNER_TEMP/$archive")
|
||||
if [[ "${actual%% *}" != "$hash" ]]; then
|
||||
echo "::error::SHA-256 mismatch for $archive."
|
||||
exit 1
|
||||
fi
|
||||
echo "hash=$hash" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.stable.outputs.publish == 'true'
|
||||
with:
|
||||
repository: house-of-vanity/homebrew-tap
|
||||
ref: main
|
||||
path: homebrew-tap
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
|
||||
- name: Update and push the formula and cask
|
||||
if: steps.stable.outputs.publish == 'true'
|
||||
env:
|
||||
ARCHIVE_SHA256: ${{ steps.archive.outputs.hash }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Retry from the latest tap state if another publisher pushes first.
|
||||
for attempt in 1 2 3; do
|
||||
git -C homebrew-tap fetch origin main
|
||||
git -C homebrew-tap checkout --detach --force FETCH_HEAD
|
||||
python3 .github/scripts/update_homebrew.py homebrew-tap "$RELEASE_TAG" "$ARCHIVE_SHA256"
|
||||
cd homebrew-tap
|
||||
ruby -c Formula/tsunagi.rb
|
||||
ruby -c Casks/tsunagi-gui.rb
|
||||
if git diff --quiet -- Formula/tsunagi.rb Casks/tsunagi-gui.rb; then
|
||||
exit 0
|
||||
fi
|
||||
git config user.name 'github-actions[bot]'
|
||||
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
|
||||
git add -- Formula/tsunagi.rb Casks/tsunagi-gui.rb
|
||||
git commit -m "tsunagi ${RELEASE_TAG#v}"
|
||||
if git push origin HEAD:main; then
|
||||
exit 0
|
||||
fi
|
||||
echo "Push to the Homebrew tap failed on attempt $attempt of 3." >&2
|
||||
cd ..
|
||||
done
|
||||
echo '::error::Could not push the updated formula and cask to the tap.'
|
||||
exit 1
|
||||
|
||||
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)
|
||||
# Release asset names omit the epoch. OpenArtifact matches the
|
||||
# upload path against the full version recorded in .PKGINFO.
|
||||
pkginfo=$(tar --zstd -xOf "$file" .PKGINFO)
|
||||
pkg=$(sed -n 's/^pkgname = //p' <<< "$pkginfo")
|
||||
version=$(sed -n 's/^pkgver = //p' <<< "$pkginfo")
|
||||
arch=$(sed -n 's/^arch = //p' <<< "$pkginfo")
|
||||
: "${pkg:?missing pkgname}" "${version:?missing pkgver}" "${arch:?missing arch}"
|
||||
url="$OA_SERVER/repos/hexor-pacman/os/$arch/$pkg-$version-$arch.pkg.tar.zst"
|
||||
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
|
||||
@@ -0,0 +1,121 @@
|
||||
name: Native subnet source selection
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
paths:
|
||||
- '.github/workflows/subnet-source.yml'
|
||||
- 'crates/tsunagi-core/src/overlay/egress.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/egress/**'
|
||||
- 'crates/tsunagi-core/src/overlay/interface.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/router.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/linux_exit*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/linux.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/macos*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/macos/**'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/windows*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/macos.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/windows.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/mod.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/factory.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/tun.rs'
|
||||
- 'crates/tsunagi-core/src/net.rs'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
source:
|
||||
if: github.server_url == 'https://github.com'
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
test: overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit
|
||||
- os: macos-latest
|
||||
test: overlay::provision::macos::tests::unbound_sockets_choose_each_networks_source_on_one_real_utun
|
||||
- os: windows-latest
|
||||
test: overlay::provision::windows::tests::two_windows_subnets_choose_their_own_source_and_survive_removal
|
||||
env:
|
||||
TEST_NAME: ${{ matrix.test }}
|
||||
CARGO_PROFILE_TEST_DEBUG: '0'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: Build and locate the native test
|
||||
shell: pwsh
|
||||
run: |
|
||||
$artifacts = @(cargo test --locked -p tsunagi-core --lib --features tun-device --no-run --message-format=json-render-diagnostics |
|
||||
ForEach-Object { ConvertFrom-Json -InputObject $_ } |
|
||||
Where-Object { $_.reason -eq 'compiler-artifact' -and $_.target.name -eq 'tsunagi' -and $_.profile.test -and $_.executable })
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
if ($artifacts.Count -ne 1) { throw "Expected one core test binary, found $($artifacts.Count)" }
|
||||
$binary = $artifacts[0].executable
|
||||
$tests = @(& $binary --ignored --exact $env:TEST_NAME --list)
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
if ($tests -notcontains "$($env:TEST_NAME): test") { throw "Missing ignored test: $env:TEST_NAME" }
|
||||
"TEST_BINARY=$binary" >> $env:GITHUB_ENV
|
||||
- name: Verify separate forwarding and local egress in Linux namespaces
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
# The invoking login and the service inside namespace B have distinct environments.
|
||||
run: sudo -n -- env XDG_RUNTIME_DIR="/run/user/$(id -u)" "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
|
||||
- name: Verify source selection on a real utun
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
|
||||
- name: Verify exit routing and PF translation on two real utuns
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
timeout-minutes: 2
|
||||
env:
|
||||
EXIT_TEST: overlay::hostrules::macos_exit::kernel::exit_preserves_underlay_and_both_meshes
|
||||
run: |
|
||||
"$TEST_BINARY" --ignored --exact "$EXIT_TEST" --list | grep -Fx "$EXIT_TEST: test"
|
||||
previous=$(sysctl -n net.inet.ip.forwarding)
|
||||
trap 'sudo -n sysctl -w "net.inet.ip.forwarding=$previous"' EXIT
|
||||
sudo -n sysctl -w net.inet.ip.forwarding=0
|
||||
sudo -n -- "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --nocapture
|
||||
- name: Verify source selection on a real Wintun adapter
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$zip = Join-Path $env:RUNNER_TEMP 'wintun.zip'
|
||||
Invoke-WebRequest -Uri https://www.wintun.net/builds/wintun-0.14.1.zip -OutFile $zip
|
||||
# This is the signed Wintun distribution pinned by the Windows installer.
|
||||
if ((Get-FileHash $zip -Algorithm SHA256).Hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') {
|
||||
throw 'Unexpected Wintun archive checksum'
|
||||
}
|
||||
$directory = Join-Path $env:RUNNER_TEMP 'wintun-dl'
|
||||
Expand-Archive -Path $zip -DestinationPath $directory
|
||||
Copy-Item (Join-Path $directory 'wintun/bin/amd64/wintun.dll') (Split-Path -Parent $env:TEST_BINARY)
|
||||
& $env:TEST_BINARY --ignored --exact $env:TEST_NAME --nocapture
|
||||
exit $LASTEXITCODE
|
||||
- name: Verify forwarded and local traffic to the same destination
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
timeout-minutes: 2
|
||||
run: |
|
||||
$test = 'overlay::egress::tests::physical_member_sockets_survive_a_more_specific_wintun_route'
|
||||
$listing = @(& $env:TEST_BINARY --ignored --exact $test --list)
|
||||
if ($listing -notcontains "${test}: test") { throw "Missing ignored test $test" }
|
||||
& $env:TEST_BINARY --ignored --exact $test --nocapture
|
||||
exit $LASTEXITCODE
|
||||
- name: Verify one Windows exit bypass route through the physical gateway
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
timeout-minutes: 2
|
||||
run: |
|
||||
$test = 'overlay::hostrules::windows_exit::tests::windows_refresh_installs_only_the_external_test_address'
|
||||
$listing = @(& $env:TEST_BINARY --ignored --exact $test --list)
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
if ($listing -notcontains "${test}: test") { throw "Missing ignored test: $test" }
|
||||
& $env:TEST_BINARY --ignored --exact $test --nocapture
|
||||
exit $LASTEXITCODE
|
||||
@@ -1 +1,2 @@
|
||||
/target
|
||||
/.claude
|
||||
@@ -8,36 +8,96 @@ 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
|
||||
supplies a network name and one shared secret; agents derive the same network
|
||||
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.
|
||||
Design accordingly: a majority is not a root of trust.
|
||||
|
||||
## User experience
|
||||
|
||||
User convenience is a core requirement. The CLI should feel logical and
|
||||
predictable to an experienced administrator: use consistent selectors and
|
||||
flags, sensible defaults, and actionable errors. Let users refer to configured
|
||||
networks by their exact name as well as by id or a unique id prefix; do not
|
||||
make them copy an opaque identifier when the stored name identifies one network.
|
||||
When a selector is ambiguous, list the matching names and ids and change
|
||||
nothing. Never guess which resource a destructive command should affect.
|
||||
Keep help text and examples in sync with behavior, and preserve existing
|
||||
scripts when improving the interactive workflow.
|
||||
|
||||
## Architectural boundaries
|
||||
|
||||
Keep these separate. Crossing them is the main thing to review for.
|
||||
|
||||
- **Control plane vs data plane.** The separation is **logical, not physical**.
|
||||
The control protocol in `src/proto/` knows nothing about packets, and
|
||||
`src/dataplane/` knows nothing about the control protocol; 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 reimplement it. They use
|
||||
different ALPNs and different connections, so a busy or broken data plane
|
||||
cannot disturb control traffic.
|
||||
The control protocol in `crates/tsunagi-core/src/proto/` knows nothing about
|
||||
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
|
||||
would throw away iroh's NAT traversal and force the data plane to
|
||||
reimplement it. They use different ALPNs and different connections, so a
|
||||
busy or broken data plane cannot disturb control traffic.
|
||||
- **One agent, one interface.** It belongs to the system level, along with
|
||||
the addresses on it and the decision of whose packet is whose. Several
|
||||
protocols may be carrying traffic at once and none of them owns the thing
|
||||
they carry it for. A protocol is handed a routed packet and hands back a
|
||||
decrypted one; it never creates an interface and never picks an address.
|
||||
- **One state directory, one identity, one live agent — many networks.** A
|
||||
network is added to the agent that is already running, never by starting a
|
||||
second one on the same directory. A second agent is a second identity and
|
||||
is isolated: its own directories, its own interface, its own runtime. Do
|
||||
not add anything that lets two agents share a directory, and do not make a
|
||||
network's lifetime depend on the process that happened to start it.
|
||||
- **A protocol is a separate crate with its own version.** The version peers
|
||||
compare is the *wire* version, never the software version: two peers on
|
||||
different releases work together for as long as the bytes between them
|
||||
have not changed. Nothing negotiated may be derived from anything that
|
||||
moves with a release.
|
||||
- **A protocol never sees the network secret.** It proves who is at the other
|
||||
end of a tunnel; proving membership of a network stays in the core, which
|
||||
is why the authenticated transport does too.
|
||||
- **A relay carries bytes, never packets.** A datagram passed on for two
|
||||
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;
|
||||
equal-cost next hops are chosen per flow. Reachability is first-hand and
|
||||
volatile: each authenticated member advertises its own direct links, of
|
||||
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.
|
||||
- **Broadcast fanout belongs at local IP ingress.** Participation is local to
|
||||
each network, enabled by default, persisted and advertised to authenticated
|
||||
peers. Resolve one source domain and target only its willing members. Remote
|
||||
delivery never triggers another fanout. Physical LAN exports must extend
|
||||
explicit ingress and source/destination admission policies; never bypass
|
||||
ownership checks or add broadcast flooding to encrypted transit.
|
||||
- **Plugins never learn reachability.** An `IpPlugin` is handed a `PacketLink`
|
||||
per peer and moves datagrams over it. Addresses, hole punching and relays
|
||||
belong to `src/dataplane/transport/`. A plugin announcement says *who*, never
|
||||
belong to `crates/tsunagi-core/src/dataplane/transport/`. A plugin announcement says *who*, never
|
||||
*where*.
|
||||
- **The core never parses a plugin payload.** See `src/dataplane/mod.rs`. Only
|
||||
`src/dataplane/wireguard/announcement.rs` interprets WireGuard payloads, and
|
||||
- **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
|
||||
only after bounding every field. A data plane failure must never stop the
|
||||
control plane.
|
||||
- **Derived, not claimed.** A peer's overlay address is derived from its public
|
||||
key. Outbound packets are routed to the owner of the destination address;
|
||||
inbound packets are dropped unless their source is the address derived for
|
||||
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
|
||||
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
|
||||
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
|
||||
stall with one peer online.
|
||||
- **A record and the author's own version counter commit together**, in one
|
||||
transaction, **before** the record is announced.
|
||||
- **Plugins own their system objects.** A plugin creates and removes its own
|
||||
interface and nothing else. Never touch routing, DNS or firewall settings.
|
||||
The one exception is the system level, not a plugin: while a network's
|
||||
broadcast is on, `overlay::hostrules` may install exactly a
|
||||
`255.255.255.255/32` route and an inbound UDP firewall allowance (overlay range
|
||||
only) for the interface the agent owns. Both are tagged `tsunagi:<interface>`,
|
||||
reversible, removed on broadcast off, leave and shutdown, and computed from
|
||||
local state, never from a remote announcement.
|
||||
- **Device identity vs network identity.** The iroh endpoint id is the device's
|
||||
public key. `NetworkId` is derived from name + secret only. Never conflate
|
||||
them, and never let one change the other.
|
||||
@@ -57,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).
|
||||
Do not add tests for getters or to move a coverage number.
|
||||
2. **Never change `IDENTITY_SCHEME`, the derivation labels, or the transcript
|
||||
encoding** in `src/identity/network.rs` and `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
|
||||
the control protocol version must not change an existing `NetworkId`.
|
||||
3. **Secrets never leak.** Not into logs, not into `Debug`, not into status
|
||||
@@ -68,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.
|
||||
5. **Bounds before allocation.** Frame lengths are checked against
|
||||
`Limits::max_frame_len` before a buffer is allocated. Every string, list and
|
||||
queue has a limit in `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
|
||||
unknown version rejects one message or one session. It never stops another
|
||||
network and never stops the agent. There is no irreversible global error
|
||||
@@ -85,24 +145,35 @@ Keep these separate. Crossing them is the main thing to review for.
|
||||
up shutdown. Wind tasks down with a grace period and then abort.
|
||||
10. **Nothing from a remote announcement becomes a shell command, a filesystem
|
||||
path or an OS setting.** The agent never touches interfaces or OS settings
|
||||
it did not create.
|
||||
it did not create (the tagged broadcast host rules above are for its own
|
||||
interface).
|
||||
|
||||
## Where things live
|
||||
|
||||
| path | responsibility |
|
||||
|---------------------|----------------|
|
||||
| `src/identity/` | device identity; deterministic network space identity and derived keys |
|
||||
| `src/storage/` | `state.sqlite`, `cache.sqlite`, directory ownership lock |
|
||||
| `src/discovery.rs` | candidate sources; test and static backends |
|
||||
| `src/proto/` | framing, message formats, membership handshake |
|
||||
| `src/net.rs` | iroh endpoint adapter and observability snapshots |
|
||||
| `src/agent/` | agent lifecycle, per-network runtimes, sessions, events, status |
|
||||
| `src/dataplane/` | the plugin contract, the packet transport, and the WireGuard plugin |
|
||||
| `src/bin/tsunagi.rs`| the command line agent; the only place that owns a runtime, a logger and signals |
|
||||
| `crates/tsunagi-core/src/identity/` | device identity; deterministic network space identity and derived keys |
|
||||
| `crates/tsunagi-core/src/storage/` | `state.sqlite`, `cache.sqlite`, directory ownership lock |
|
||||
| `crates/tsunagi-core/src/discovery.rs` | candidate sources; test and static backends |
|
||||
| `crates/tsunagi-core/src/proto/` | framing, message formats, membership handshake |
|
||||
| `crates/tsunagi-core/src/net.rs` | iroh endpoint adapter and observability snapshots |
|
||||
| `crates/tsunagi-core/src/agent/` | agent lifecycle, per-network runtimes, sessions, events, status |
|
||||
| `crates/tsunagi-core/src/state/` | signed records that outlive a session, their merge rules and address allocation |
|
||||
| `crates/tsunagi-core/src/overlay/` | the one interface an agent owns: provisioning, the TUN, routing, source checks, broadcast host rules |
|
||||
| `crates/tsunagi-core/src/dataplane/` | the protocol contract and the authenticated packet transport |
|
||||
| `crates/tsunagi-core/src/dns/` | the DNS view of a network: zone, server, resolver publication |
|
||||
| `crates/tsunagi-wg-quic/` | the single internal WireGuard cipher, keys and opaque announcement; historical crate name |
|
||||
| `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 |
|
||||
|
||||
Add abstractions only at real substitution or testing boundaries. Do not add a
|
||||
trait per struct. Prefer one crate with clear modules over many small crates.
|
||||
trait per struct.
|
||||
|
||||
**The system level and its plugins are separate crates**, so that boundary is
|
||||
checked by the compiler and not by discipline: a plugin can reach only what
|
||||
`tsunagi` makes public, and carries its own version. Everything else stays
|
||||
one crate with clear modules — do not split further without a reason of that
|
||||
kind.
|
||||
|
||||
## Testing rules
|
||||
|
||||
@@ -124,7 +195,26 @@ trait per struct. Prefer one crate with clear modules over many small crates.
|
||||
- Running several library instances in one process is not a test of several
|
||||
system processes; do not describe it as one.
|
||||
|
||||
## Before you open a change
|
||||
## Commit every completed change
|
||||
|
||||
Agents must create a Git commit before finishing any task that changes this
|
||||
repository. Do not leave the user to make the commit. Inspect recent commit
|
||||
messages and follow their style: a short English subject stating the change,
|
||||
then a useful body explaining the problem, final behavior, architectural
|
||||
decisions, compatibility/migration effects, and checks actually performed.
|
||||
Write enough context for a future maintainer or LLM to understand why the code
|
||||
exists. Record failed or skipped checks honestly; never claim unrun tests.
|
||||
|
||||
Before committing, inspect the diff and stage only this task's changes. Preserve
|
||||
unrelated user changes and never commit secrets or generated build artifacts.
|
||||
If Git has no effective author name or email, set only the missing repository-
|
||||
local values to `AB` and `ab@hexor.cy`. Do not override an existing identity or
|
||||
change global Git configuration. Report the resulting commit hash.
|
||||
|
||||
Version bumps, release tags, and pushing commits/tags belong to the user unless
|
||||
they explicitly ask the agent to do them. Read-only tasks need no empty commit.
|
||||
|
||||
## Required validation
|
||||
|
||||
```bash
|
||||
cargo fmt --all -- --check
|
||||
|
||||
Generated
+3827
-101
File diff suppressed because it is too large.
Load diff
+34
-56
@@ -1,64 +1,42 @@
|
||||
[package]
|
||||
name = "tsunagi"
|
||||
version = "0.1.0"
|
||||
# The system level and its plugins are separate crates, so the boundary
|
||||
# between them is checked by the compiler rather than by discipline: a plugin
|
||||
# can reach only what the core makes public, and carries its own version.
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*"]
|
||||
exclude = ["vendor/mainline", "vendor/iroh"]
|
||||
|
||||
# Mainline 8.0.0 treats Windows UDP read timeouts as socket failures.
|
||||
# Keep the small receive-loop correction reproducible until an upstream fix.
|
||||
[patch.crates-io]
|
||||
mainline = { path = "vendor/mainline" }
|
||||
# Backport bounded path retries until an iroh release includes the OOM fix.
|
||||
iroh = { path = "vendor/iroh" }
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Proof-of-concept library for small private mesh networks: persistent agent identity, deterministic network spaces, iroh-based control plane."
|
||||
repository = "https://github.com/tsunagi-net/tsunagi"
|
||||
readme = "README.md"
|
||||
keywords = ["mesh", "p2p", "iroh", "networking"]
|
||||
categories = ["network-programming"]
|
||||
license = "WTFPL"
|
||||
repository = "https://github.com/house-of-vanity/tsunagi"
|
||||
|
||||
[features]
|
||||
default = ["cli"]
|
||||
# The `tsunagi` command line binary. Library users can opt out.
|
||||
cli = ["dep:clap", "dep:tracing-subscriber", "tokio/signal", "tun-device"]
|
||||
# A real TUN device, so the WireGuard plugin can carry actual IP traffic.
|
||||
# Needs CAP_NET_ADMIN at run time; without it the plugin still runs and its
|
||||
# in-memory device can be used for tests.
|
||||
tun-device = ["dep:tun"]
|
||||
|
||||
[[bin]]
|
||||
name = "tsunagi"
|
||||
path = "src/bin/tsunagi.rs"
|
||||
required-features = ["cli"]
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5", features = ["derive", "env"], optional = true }
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"], optional = true }
|
||||
iroh = { version = "1.2", default-features = false, features = ["tls-ring"] }
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
|
||||
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"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
|
||||
data-encoding = "2.11"
|
||||
hex = "0.4"
|
||||
thiserror = "2.0"
|
||||
tracing = "0.1"
|
||||
fs4 = { version = "1.1", features = ["sync"] }
|
||||
directories = "6.0"
|
||||
netwatch = "0.19.3"
|
||||
bytes = "1.12.1"
|
||||
boringtun = { version = "0.7.1", default-features = false }
|
||||
tun = { version = "0.8", features = ["async"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "process"] }
|
||||
tempfile = "3.24"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[lints.rust]
|
||||
[workspace.lints.rust]
|
||||
missing_docs = "warn"
|
||||
unsafe_code = "forbid"
|
||||
unsafe_code = "deny"
|
||||
|
||||
[lints.clippy]
|
||||
[workspace.lints.clippy]
|
||||
unwrap_used = "warn"
|
||||
expect_used = "warn"
|
||||
panic = "warn"
|
||||
|
||||
[workspace.dependencies]
|
||||
iroh = { version = "1.2", default-features = false, features = ["tls-ring", "portmapper"] }
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
|
||||
bytes = "1.12.1"
|
||||
thiserror = "2.0"
|
||||
tracing = "0.1"
|
||||
hex = "0.4"
|
||||
data-encoding = "2.11"
|
||||
tempfile = "3.24"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
@@ -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.
|
||||
@@ -1,256 +1,351 @@
|
||||
# tsunagi
|
||||
<p align="center">
|
||||
<img src="dist/linux/tsunagi.svg" width="96" alt="">
|
||||
</p>
|
||||
|
||||
A proof-of-concept Rust library for **small private mesh networks** — a handful
|
||||
of friends, home machines, a few servers. Units to dozens of participants, not
|
||||
thousands.
|
||||
<h1 align="center">tsunagi</h1>
|
||||
|
||||
The end user configures exactly two things:
|
||||
<p align="center">
|
||||
<b>A mesh VPN with no server.</b><br>
|
||||
Pick a network name, share a secret, and your machines are on one private network.
|
||||
</p>
|
||||
|
||||
```text
|
||||
network_name
|
||||
secret # one shared secret; "password" and "secret" mean the same value
|
||||
<p align="center">
|
||||
<a href="https://github.com/house-of-vanity/tsunagi/releases/latest"><img alt="release" src="https://img.shields.io/github/v/release/house-of-vanity/tsunagi?include_prereleases"></a>
|
||||
<a href="https://github.com/house-of-vanity/tsunagi/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/house-of-vanity/tsunagi/actions/workflows/ci.yml/badge.svg"></a>
|
||||
<a href="LICENSE"><img alt="license" src="https://img.shields.io/badge/license-WTFPL-blue"></a>
|
||||
</p>
|
||||
|
||||
```console
|
||||
laptop$ tsng join -n home
|
||||
joined `home`
|
||||
secret tsn1u7c…
|
||||
|
||||
server$ tsng join -n home -s tsn1u7c…
|
||||
server$ tsng id hostname server
|
||||
|
||||
laptop$ ssh server.home
|
||||
```
|
||||
|
||||
From those, every agent independently derives the same network space. There is
|
||||
no central server, no network owner with special powers, no registration and no
|
||||
majority vote. Anyone who knows the parameters can join; nobody has to trust
|
||||
anybody else.
|
||||
No account, no coordination server, no admin console, no keys to approve.
|
||||
Anyone who knows the **name** and the **secret** is in. Nobody else can find
|
||||
the network, let alone enter it.
|
||||
|
||||
## What this proof of concept actually does
|
||||
## Why
|
||||
|
||||
A working library with **real iroh connections** and integration tests:
|
||||
Tailscale, Headscale and ZeroTier are great, but each needs a control server:
|
||||
theirs, or one you have to run and keep alive. tsunagi doesn't. Machines find
|
||||
each other through the public BitTorrent DHT, connect directly (hole punching,
|
||||
with relay fallback), and keep the network state among themselves.
|
||||
|
||||
- persistent device identity stored in SQLite, stable across restarts;
|
||||
- several independent networks at once in one agent;
|
||||
- deterministic network identity derived from name + secret;
|
||||
- candidates supplied by a replaceable discovery component;
|
||||
- real iroh connections plus an explicit mutual proof of network membership;
|
||||
- a small versioned control protocol: handshake, hostname/capability
|
||||
announcement, ping/pong;
|
||||
- automatic reconnect with bounded exponential backoff and jitter;
|
||||
- status snapshots, an event stream and honest diagnostics;
|
||||
- configuration restored after a restart;
|
||||
- correct behaviour when the disposable cache is missing or corrupt;
|
||||
- a **WireGuard data plane**, in userspace: its own key per network,
|
||||
deterministic IPv6 overlay addressing, real tunnels carried over iroh, and
|
||||
address ownership enforced rather than believed;
|
||||
- a **command line agent**, `tsunagi`.
|
||||
| | Tailscale | Headscale | ZeroTier | **tsunagi** |
|
||||
| ---------------------- | ------------------ | ---------------- | ------------------- | ------------------- |
|
||||
| Control server | hosted by vendor | you run it | hosted or self-run | **none** |
|
||||
| Account / sign-in | yes | yes | yes | **no** |
|
||||
| To join a network | sign in, get approved | pre-auth key | network ID, approval | **name + secret** |
|
||||
| Direct connections | yes | yes | yes | yes |
|
||||
| Exit nodes | yes | yes | via routes | yes |
|
||||
|
||||
### What it deliberately does **not** do
|
||||
## Features
|
||||
|
||||
Not implemented, and not pretended to be: Mainline DHT, DNS, routing through
|
||||
intermediate participants, a full CRDT, dynamically loaded plugins, a system
|
||||
service, a complete CLI, or a local control socket. Snapshot synchronisation
|
||||
and signed revocations are designed for but not implemented — see
|
||||
[docs/sync-model.md](docs/sync-model.md). The WireGuard plugin's own limits,
|
||||
including that its system backend is Linux-only, are in
|
||||
[docs/wireguard.md](docs/wireguard.md#limits-and-future-work).
|
||||
- **Two things to know:** a network name and a secret. A secret is generated for you when you make a network.
|
||||
- **Direct, encrypted links** between members (WireGuard cryptography), with relay fallback behind strict NATs.
|
||||
- **Names for machines:** `server.home` just works, even while `server` is switched off. A name belongs to whoever claimed it first; a later device with the same name keeps working by address and is told so.
|
||||
- **Exit nodes:** send all your internet traffic through any member that offers one.
|
||||
- **Multi-hop:** members that can't reach each other directly are routed through a member that can, over whatever kind of link each hop has. A member reached that way is online, and shown as relayed; traffic moves to a direct link by itself the moment one comes up.
|
||||
- **LAN games:** UDP broadcasts are relayed, so "LAN" lobbies show up across the mesh.
|
||||
- **Several networks at once** on one device.
|
||||
- **Tray app** for Windows, macOS and Linux; a command line for everything.
|
||||
- **Android prototype** for ARM64 phones, with the same egui forms and a foreground VPN service. [Build and run the Android client](android/README.md).
|
||||
|
||||
**Control and data are separated logically, not physically.** Both ride on
|
||||
iroh, on different ALPNs and different connections, so the data plane inherits
|
||||
iroh's hole punching and relay fallback instead of reimplementing them — while
|
||||
the control protocol still knows nothing about packets and can keep a different
|
||||
transport underneath it later. Filtering user traffic remains the operating
|
||||
system's and the user's responsibility, not this library's.
|
||||
## Install
|
||||
|
||||
## Requirements
|
||||
Grab a build from the [latest release](https://github.com/house-of-vanity/tsunagi/releases/latest).
|
||||
|
||||
- Rust 1.91 or newer (iroh 1.2 requires it), edition 2024. Pinned dependencies
|
||||
in `Cargo.lock`.
|
||||
- No internet, no DHT, no public relay, no administrator rights and no changes
|
||||
to OS network settings are needed to build or test.
|
||||
- WireGuard runs in userspace (boringtun): **no kernel module and no `wg`
|
||||
tool**. Only creating a real network interface needs `CAP_NET_ADMIN`, and
|
||||
`--no-tun` skips even that.
|
||||
| Platform | How |
|
||||
| --------------------- | -------------------------------------------------------------------------------- |
|
||||
| **Windows** | Run `tsunagi-setup-<version>-x86_64.exe`. Installs the service, the tray and `tsng`. |
|
||||
| **Android** | Open `tsunagi-android-<version>-arm64-v8a.apk` on an ARM64 phone running Android 8 or later. |
|
||||
| **macOS** | `brew tap house-of-vanity/tap && brew install --cask tsunagi-gui`<br>CLI only: `brew install tsunagi` |
|
||||
| **Debian / Ubuntu** | `sudo apt install ./tsunagi-gui_<version>_amd64.deb` (`tsunagi_…` for no tray) |
|
||||
| **Arch** | `sudo pacman -U tsunagi-gui-<version>-1-x86_64.pkg.tar.zst` |
|
||||
| **NixOS** | [Flake and module](#nixos) below |
|
||||
| **Any other Linux** | Unpack the tarball, then `sudo ./install.sh && sudo systemctl enable --now tsunagi` |
|
||||
|
||||
## Trying it on two machines
|
||||
Linux packages run the agent as an unprivileged service user. Add yourself to
|
||||
the `tsunagi` group (`sudo usermod -aG tsunagi $USER`, then log in again) to
|
||||
use `tsng` and the tray without `sudo`.
|
||||
|
||||
On the first machine:
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cargo build --release
|
||||
./target/release/tsunagi secret # prints tsn1...; share it privately
|
||||
./target/release/tsunagi doctor # what this host can and cannot do
|
||||
|
||||
./target/release/tsunagi up --network lab --secret "$SECRET" --wireguard
|
||||
```sh
|
||||
tsng join -n home # first machine: makes the network and prints a secret
|
||||
tsng join -n home -s tsn1… # every other machine
|
||||
tsng status # who is online, over which path
|
||||
```
|
||||
|
||||
It prints its endpoint id and then waits. On the second machine, pass that id:
|
||||
Every new network gets a stable pseudorandom `/24` in `10.0.0.0/8`, derived
|
||||
from its network id. Its members agree on that range even when starting offline,
|
||||
and each gets a name like `<host>.home`. Existing signed ranges are preserved.
|
||||
|
||||
```bash
|
||||
./target/release/tsunagi up --network lab --secret "$SECRET" --wireguard \
|
||||
--peer <endpoint-id-from-the-first-machine>
|
||||
If two configured networks have overlapping ranges, the agent runs only one.
|
||||
`tsng status`, `tsng network` and the tray show which network blocks the
|
||||
other. `tsng network start <name-or-id>` or the tray’s “Switch to this network”
|
||||
button suspends the conflicting networks. They resume automatically when the
|
||||
selected network stops; the selection survives restarting the agent. Explicitly
|
||||
stopping a suspended network cancels its automatic resume.
|
||||
|
||||
Machines are called `tsunagi-<id>` until you rename them: `tsng id hostname laptop`.
|
||||
|
||||
### Virtual services
|
||||
|
||||
```sh
|
||||
tsng vip create home api
|
||||
tsng vip port add home api tcp/443 --backend server1:6443 --backend server2:7443
|
||||
tsng vip status home api --watch
|
||||
```
|
||||
|
||||
Within a few seconds both print something like:
|
||||
Use `api.home:443`. Each client selects the available backend with the lowest
|
||||
measured data-plane RTT. A VIP can have multiple independent TCP and UDP ports.
|
||||
Every member may edit it; the tray's **VIP** button opens a draft editor with
|
||||
explicit Save. [Commands, health, metrics and limits](docs/vip.md).
|
||||
|
||||
```text
|
||||
+ peer b47c958462 connected over Direct rtt=Some(4.5ms)
|
||||
+ data link to b47c958462 for wireguard: Direct via Ip(…), datagram 1382
|
||||
### Exit nodes
|
||||
|
||||
--- status ---
|
||||
control: 1 peer(s), 0 dial failure(s), 0 handshake failure(s)
|
||||
wireguard: tsunkkcp43lmdje on fd15:1d9e:fa21:f201:…/64 mtu 1100, 1/1 tunnel(s) established
|
||||
4jO4kx9Z fd15:1d9e:fa21:f201:… handshake 3s ago tx=0 rx=0 dropped=0 path=Direct via Ip(…)
|
||||
```sh
|
||||
tsng network exit-node home on # on the machine that should be the exit
|
||||
tsng exit-node # on another one: who offers an exit
|
||||
tsng exit-node laptop # send internet traffic through it
|
||||
tsng exit-node off
|
||||
```
|
||||
|
||||
`1/1 tunnel(s) established` means a real WireGuard handshake completed. Then
|
||||
`ping6` the peer's overlay address.
|
||||
One exit serves the whole agent. Peers in every active Tsunagi network stay
|
||||
reachable on their own mesh routes.
|
||||
|
||||
Notes:
|
||||
The tray does the same with a checkbox. An exit node sees everything you send
|
||||
through it, so use only members you trust. The folded network card shows its
|
||||
status and recent traffic. Expand it to see who is using this device for internet
|
||||
access.
|
||||
[Details and per-OS notes](docs/exit-node.md).
|
||||
|
||||
- Only one side needs `--peer`; the link is bidirectional.
|
||||
- The default `--transport n0` uses iroh's public address lookup and relays, so
|
||||
two machines behind NAT find each other. `--transport local` keeps everything
|
||||
on the local network. See *How peers find each other* below — it is worth
|
||||
understanding what gets published.
|
||||
- Without `CAP_NET_ADMIN`, add `--no-tun`: the mesh, the data links and the
|
||||
WireGuard handshakes all still run and are visible in the status output, only
|
||||
traffic does not reach the operating system. That is the quickest way to
|
||||
confirm the network forms.
|
||||
- Run as root (or grant `CAP_NET_ADMIN`) to get a real interface.
|
||||
The initial data transport order is `wg,awg,wg-quic,tcp-tls,vless-xhttp,ss2022` by default. AWG negotiates a
|
||||
fresh masking profile and outer keys for each pair connection attempt, including
|
||||
reentry after fallback. Sustained data loss triggers switching independently of
|
||||
the iroh control connection. [Configuration and limits](docs/amnezia.md).
|
||||
|
||||
## Checks
|
||||
The **Shoes** family adds two embedded TCP carriers. `vless-xhttp` uses VLESS
|
||||
over XHTTP stream-one with HTTP/2 and pinned TLS 1.3 (preferred port 9443).
|
||||
`ss2022` uses Shadowsocks 2022 with AES-128-GCM or AES-256-GCM (9444).
|
||||
Peers agree fresh credentials over their authenticated control connection on
|
||||
every attempt. The native `tcp-tls` listener prefers TCP 9442. To use all three
|
||||
on a public server, allow inbound TCP 9442–9444. For a second agent on the
|
||||
same host, set its listeners explicitly, for example
|
||||
`tsng up -o tcp-tls:port=10442 -o vless-xhttp:port=10443 -o ss2022:port=10444`,
|
||||
and allow TCP 10442–10444 for that instance.
|
||||
|
||||
```bash
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace --all-targets
|
||||
With two updated peers, `tcp-tls` and both Shoes carriers try the opposite dial
|
||||
direction if the first fails. One reachable TCP listener suffices. If neither
|
||||
side accepts TCP, the mesh can use another enabled carrier or an available
|
||||
relay route. [Wire profiles and compatibility](docs/shoes.md).
|
||||
|
||||
Change a network's protocol selection without editing its service or restarting:
|
||||
|
||||
```sh
|
||||
tsng protocols # available protocols and settings
|
||||
tsng protocols home # this device's choice for home
|
||||
tsng protocols home awg,wg-quic # enable AWG and QUIC, try AWG first
|
||||
tsng protocols home none # control plane only
|
||||
```
|
||||
|
||||
The whole suite runs offline on loopback. Set `TSUNAGI_TEST_LOG=tsunagi=debug`
|
||||
to see agent logs while a test runs.
|
||||
Exact network names, full ids and unique id prefixes work here. The choice is
|
||||
local to this device, saved per network and applied immediately; an offline
|
||||
change applies on the next start. In the tray or on Android, click the network
|
||||
name to expand its card. Open **Data transports** to toggle a family or expand it to select individual
|
||||
transports. Checking a partial or unchecked family enables every member. The
|
||||
number beside an enabled transport is its priority across all groups. The arrow
|
||||
buttons change it. Hover or tap the information icon for protocol details. **Show devices** lists peers and their reported
|
||||
Tsunagi versions. On Android, tap a device to see its version and traffic.
|
||||
|
||||
There are also two runnable demos, which are demos and not substitutes for the
|
||||
tests:
|
||||
Select a peer’s speedometer in **Devices** to measure download and upload
|
||||
through its current encrypted mesh path. A test becomes available after a
|
||||
round trip to the peer succeeds over that path, directly or through relay
|
||||
members. The control connection coordinates the test and returns its results.
|
||||
Only packets received over the data path count towards the rate in Mbit/s.
|
||||
Select the result to test again, or use **Test exits** to check the network’s
|
||||
online, compatible exit nodes one at a time. The test ends at the peer, so its
|
||||
Internet uplink beyond that peer is outside the measurement. Hover or long-press
|
||||
the result for details. “At least” means the receiver sustained that rate and
|
||||
the test ended before it could confirm the limit. A missing direction means
|
||||
the sample was too short. Both peers need speed-test support.
|
||||
|
||||
```bash
|
||||
cargo run --example two_agents # control plane only
|
||||
cargo run --example wireguard_mesh # a WireGuard overlay carrying a real packet
|
||||
A test runs for up to five seconds. It raises the offered rate in steps and
|
||||
tries a higher rate again after a slow start. The receiver counts unique payload
|
||||
bytes across sustained trains of packets, including the last train before the
|
||||
traffic budget runs out. The traffic ceiling is 96 MiB per direction for one
|
||||
peer, or 8 MiB when either endpoint reports a metered link.
|
||||
A batch shares 128 MiB per direction among its exits, or 16 MiB on a metered
|
||||
initiator. These ceilings count probe IP packets before tunnel overhead.
|
||||
|
||||
Adjacent peers need a common external transport at the same wire version.
|
||||
Peers that both support link comparison probe another mutually enabled transport
|
||||
while traffic continues on the current one. They can switch to a faster healthy link.
|
||||
`tsng status` and Devices show the round trip of an encrypted probe to the
|
||||
destination, including any mesh relay hops. The previous measurement stays
|
||||
visible while the next probe is in flight. Losing the route or missing two
|
||||
consecutive probes clears the measurement. Devices shows **Ready** or **Idle**
|
||||
only while the data path is confirmed and the tunnel has a usable session key.
|
||||
Control RTT is shown separately.
|
||||
Selection applies to this device's incoming and outgoing data links; control and
|
||||
discovery are independent. A relay's next hop may use a different transport.
|
||||
Every pair uses one internal WireGuard cipher, hidden from these controls.
|
||||
Changing transport or moving direct → relay → direct preserves that channel,
|
||||
addresses and interface. An existing TCP connection can resume after temporary
|
||||
loss, subject to its own timeouts. `tsng up --protocol` supplies the
|
||||
initial defaults for networks without a saved choice; it does not restrict
|
||||
which built-in protocols can be enabled later.
|
||||
|
||||
Remove an obsolete offline device from a network's shared history:
|
||||
|
||||
```sh
|
||||
tsng network forget-node home old-laptop
|
||||
tsng network forget-node home 10.13.37.143
|
||||
```
|
||||
|
||||
Both run with no privileges and change nothing on the host.
|
||||
Networks accept exact names, full ids or unique id prefixes; nodes accept those
|
||||
id selectors, exact hostnames or overlay IPv4 addresses. Ambiguous selectors
|
||||
change nothing. Start the network first if it is stopped. In **Show devices**,
|
||||
click **Forget** beside an offline node and confirm its identity.
|
||||
|
||||
## Usage
|
||||
Every member has the same cleanup right. The signed cleanup frees the observed
|
||||
claim's name and IPv4 reservation, survives restarts and reaches offline replicas
|
||||
when they reconnect. It does not ban the device: a newer signed claim can return.
|
||||
Online nodes and the currently selected exit node cannot be forgotten.
|
||||
[State and limits](docs/sync-model.md#offline-node-cleanup).
|
||||
|
||||
```rust,no_run
|
||||
use std::sync::Arc;
|
||||
use tsunagi::config::{AgentConfig, StoragePaths, TransportPolicy};
|
||||
use tsunagi::discovery::SharedMemoryDiscovery;
|
||||
use tsunagi::identity::{NetworkName, NetworkSecret};
|
||||
use tsunagi::proto::ControlMessage;
|
||||
use tsunagi::{Agent, Result};
|
||||
### Traffic monitor
|
||||
|
||||
// The library never starts a runtime, installs a logger, handles signals,
|
||||
// forks, or calls process::exit. The binary owns all of that.
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let config = AgentConfig::new(StoragePaths::user_default()?)
|
||||
.with_transport(TransportPolicy::N0Defaults)
|
||||
.with_discovery(Arc::new(SharedMemoryDiscovery::new()));
|
||||
Open **Traffic monitor** (the pulse icon in the tray window or Android header) to
|
||||
start an empty live capture. **IP flows** groups both directions of a TCP or UDP
|
||||
address/port pair and repeated ICMP echoes for an address pair into one row. Select a network and peer, protocol or
|
||||
role to narrow it down. **Via exit node** shows your outgoing internet traffic.
|
||||
**Serving exit** shows traffic your device forwards for another peer.
|
||||
|
||||
let agent = Agent::spawn(config).await?;
|
||||
**Resolve names** shows known peers and VIPs by their network names in the
|
||||
endpoint columns. Hover over a name, or press and hold on Android, to see the
|
||||
IP address. Clear the checkbox to show all endpoints numerically.
|
||||
|
||||
let name = NetworkName::new("kitchen-table")?;
|
||||
let secret = NetworkSecret::generate(); // 32 random bytes
|
||||
println!("share this: {}", secret.encode().as_str());
|
||||
**Transport** shows authenticated control sessions and encrypted datagrams
|
||||
forwarded between two other endpoints. For relay rows the arrows follow the
|
||||
two displayed endpoints in order. Rates update once per second. Use the
|
||||
**TX packets** and **RX packets** columns to see packet counts. The monitor
|
||||
records header metadata and counters only.
|
||||
|
||||
let network = agent.join_network(&name, &secret).await?;
|
||||
Inactive rows expire after 60 seconds. **Keep until close** retains flows in a
|
||||
private temporary table owned by the window. Closing it discards the table and
|
||||
ends collection. Android pauses collection while the activity is in the background.
|
||||
Under heavy load the monitor displays the number of missed observations.
|
||||
|
||||
let mut events = agent.subscribe();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(event) = events.recv().await {
|
||||
println!("{event:?}");
|
||||
## Platforms
|
||||
|
||||
| Platform | Build | CLI `tsng` | Tray | Exit node: offer / use | Packages |
|
||||
| ------------------------- | ------------ | :--------: | :--: | :--------------------: | ----------------------------------- |
|
||||
| Linux x86_64 | release | ✔ | ✔ | ✔ / ✔ | `.deb`, `.pkg.tar.zst`, tarball, Nix |
|
||||
| Linux aarch64 | release | ✔ | –¹ | ✔ / ✔ | `.deb`, `.pkg.tar.zst`, tarball, Nix |
|
||||
| Linux armv7 | release | ✔ | –¹ | ✔ / ✔ | `.deb`, `.pkg.tar.zst`, tarball |
|
||||
| macOS, Apple silicon | release | ✔ | ✔ | ✔ / ✔² | Homebrew, tarball |
|
||||
| macOS, Intel | from source | ✔³ | ✔³ | ✔ / ✔²³ | – |
|
||||
| Windows x86_64 | release | ✔ | ✔ | ✔ / ✔² | installer, zip |
|
||||
|
||||
<sup>¹ Not in the release; builds from source (and through Nix).
|
||||
² Newer and less battle-tested than on Linux.
|
||||
³ Builds from source, not covered by CI.</sup>
|
||||
|
||||
The Linux release CLI is a single static musl binary, independent of the
|
||||
distribution's libc. The tray uses dynamic desktop libraries.
|
||||
|
||||
## NixOS
|
||||
|
||||
The repository is a flake with a package and a module.
|
||||
|
||||
```nix
|
||||
# flake.nix
|
||||
{
|
||||
inputs.tsunagi.url = "github:house-of-vanity/tsunagi";
|
||||
|
||||
outputs = { nixpkgs, tsunagi, ... }: {
|
||||
nixosConfigurations.myhost = nixpkgs.lib.nixosSystem {
|
||||
modules = [
|
||||
tsunagi.nixosModules.default
|
||||
{
|
||||
services.tsunagi = {
|
||||
enable = true;
|
||||
tray.enable = true; # optional, for desktops
|
||||
users = [ "alice" ]; # may use tsng and the tray without sudo
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
for peer in agent.network_status(network).await?.connected_peers() {
|
||||
agent
|
||||
.send(network, peer, ControlMessage::Ping { seq: 1, payload: vec![] })
|
||||
.await?;
|
||||
}
|
||||
|
||||
agent.shutdown().await;
|
||||
Ok(())
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
`TransportPolicy::LocalOnly` is the default, so a plain `AgentConfig::new` never
|
||||
reaches the internet by accident. Opt into `DirectOnly` or `N0Defaults`
|
||||
explicitly.
|
||||
Just trying it: `nix run github:house-of-vanity/tsunagi#tsunagi-cli -- --help`.
|
||||
`packages.<system>.tsunagi` (with the tray) and `tsunagi-cli` are also exported,
|
||||
along with `overlays.default`.
|
||||
|
||||
## How peers find each other
|
||||
For development from a checkout, `nix develop` also exposes the tray's native
|
||||
runtime libraries, including AppIndicator and graphics/windowing libraries.
|
||||
Cargo-built binaries such as `target/debug/tsunagi-tray` can run directly inside
|
||||
this shell, without installing the packaged wrapper.
|
||||
|
||||
Two different lookups are involved, and only one of them is this project's:
|
||||
## Build from source
|
||||
|
||||
**1. Resolving one endpoint's address — iroh's, and it works today.**
|
||||
With `--transport n0` or `--transport direct`, iroh publishes a signed record
|
||||
of this endpoint's addresses, keyed by its endpoint id, to Number 0's public
|
||||
service (`dns.iroh.link`, over pkarr and DNS) and resolves other endpoints the
|
||||
same way. That is why `--peer <endpoint-id>` works with no address attached:
|
||||
iroh looks it up. None of that code is ours.
|
||||
Rust 1.91 or newer.
|
||||
|
||||
**2. Finding who is in a network — ours, and it is still manual.**
|
||||
`NetworkDiscovery` maps a secret-derived `DiscoveryKey` to a set of *candidate*
|
||||
members. Two backends exist: `StaticBootstrap` (what `--peer` feeds) and an
|
||||
in-memory one for tests. The planned Mainline DHT backend, which would let
|
||||
members find each other from the network secret alone, is **not implemented**.
|
||||
So today you bootstrap by passing one peer's id; after that the mesh is
|
||||
whatever those agents reach.
|
||||
```sh
|
||||
cargo build --release --bin tsng # the agent and CLI
|
||||
cargo build --release --bin tsunagi-tray # the tray (Linux needs GTK 3 and libayatana-appindicator)
|
||||
```
|
||||
|
||||
What this means in practice:
|
||||
These commands use the host target. On a glibc-based Linux distribution,
|
||||
`target/release/tsng` is dynamically linked. For the static x86_64 Linux CLI,
|
||||
release CI uses Zig 0.14.1 and `cargo-zigbuild` (with CMake, Clang and libclang
|
||||
installed):
|
||||
|
||||
- With `n0` or `direct`, **your endpoint id and IP addresses are published to a
|
||||
public third-party service.** They are not secret, and the network secret is
|
||||
never published, but an observer of that service learns that your endpoint
|
||||
exists and where it is. `--transport local` publishes nothing.
|
||||
- A relay, when one is needed, sees the volume and timing of your traffic — not
|
||||
its contents.
|
||||
```sh
|
||||
rustup target add x86_64-unknown-linux-musl
|
||||
cargo zigbuild --release --locked --target x86_64-unknown-linux-musl --bin tsng
|
||||
```
|
||||
|
||||
## Storage
|
||||
The static binary is `target/x86_64-unknown-linux-musl/release/tsng`.
|
||||
|
||||
Two physically separate SQLite files, placed wherever the library's
|
||||
configuration says (`StoragePaths`). A future system service supplies its own
|
||||
paths; tests always use temporary directories.
|
||||
Windows needs [Wintun](https://www.wintun.net) next to `tsng.exe`.
|
||||
Per-platform notes: [Linux](dist/linux/README.md), [Arch](dist/arch/README.md),
|
||||
[macOS](dist/macos/README.md), [Windows](dist/windows/README.md).
|
||||
|
||||
| file | holds | when damaged |
|
||||
|----------------|--------------------------------------------------|-------------------------|
|
||||
| `state.sqlite` | device identity, network configuration, hostname | clear error, never reset |
|
||||
| `cache.sqlite` | address hints and other recoverable data | discarded and recreated |
|
||||
## How it works
|
||||
|
||||
The WireGuard plugin keeps its own keys in its own `wireguard.sqlite`, wherever
|
||||
its configuration points, because plugin keys are neither the iroh identity nor
|
||||
the network secret.
|
||||
- Your name and secret derive a network identity. Members publish signed
|
||||
contact records to the public Mainline DHT under it, and find each other there.
|
||||
- Every connection proves knowledge of the secret before it's accepted.
|
||||
Traffic between members is end-to-end encrypted, relays included.
|
||||
- Addresses and names are claimed with each device's own key and replicated
|
||||
between members. There is no one in charge, so nothing to be taken down.
|
||||
|
||||
The command line agent puts everything under the platform's per-user
|
||||
directories by default; `--state-dir` and `--cache-dir` override them.
|
||||
|
||||
One state directory belongs to one live agent, enforced with a real OS file
|
||||
lock rather than an existence check.
|
||||
The secret is the only key, so make it a good one (the generated ones are).
|
||||
The [threat model](docs/threat-model.md) says what this does and doesn't protect against.
|
||||
|
||||
## Documentation
|
||||
|
||||
- [docs/architecture.md](docs/architecture.md) — module boundaries and runtime.
|
||||
- [docs/wireguard.md](docs/wireguard.md) — the WireGuard plugin: overlay
|
||||
addressing, announcements, backends, reconciliation.
|
||||
- [docs/protocol.md](docs/protocol.md) — identity derivation, framing, handshake.
|
||||
- [docs/sync-model.md](docs/sync-model.md) — the planned signed-state model and
|
||||
what is deliberately not built yet.
|
||||
- [docs/threat-model.md](docs/threat-model.md) — threat model and known limits.
|
||||
- [docs/testing.md](docs/testing.md) — what the suite covers and what it does not.
|
||||
- [AGENTS.md](AGENTS.md) — rules for anyone (human or agent) changing this repo.
|
||||
|
||||
## Security in one paragraph
|
||||
|
||||
Membership is proved by an HMAC over a transcript keyed by a value derived from
|
||||
the shared secret, bound to the specific iroh connection through the TLS
|
||||
exporter, to the network id, to both endpoint identities and to distinct role
|
||||
labels. This targets high-entropy secrets: there is no PAKE here, so a short
|
||||
human passphrase is guessable offline by anyone who can reach the handshake.
|
||||
Anyone who knows the secret is a full participant and can create many
|
||||
identities. Read [docs/threat-model.md](docs/threat-model.md) before relying on
|
||||
any of this.
|
||||
[Architecture](docs/architecture.md) ·
|
||||
[Protocol](docs/protocol.md) ·
|
||||
[WireGuard data plane](docs/wireguard.md) ·
|
||||
[Pairwise Amnezia transport](docs/amnezia.md) ·
|
||||
[Routing](docs/routing.md) ·
|
||||
[Exit nodes](docs/exit-node.md) ·
|
||||
[Virtual services](docs/vip.md) ·
|
||||
[Threat model](docs/threat-model.md) ·
|
||||
[Contributing](AGENTS.md)
|
||||
|
||||
## Licence
|
||||
|
||||
MIT OR Apache-2.0.
|
||||
[WTFPL](LICENSE): 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,67 @@
|
||||
# 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** to start the agent. On first launch, accept Android’s VPN permission prompt so the agent can create its mesh interface. Join with the existing network name and secret. The service continues when the activity closes. Mesh changes update split DNS and the selected-exit notification in the background. Opening the activity also requests live traffic counters. **About → Stop Tsunagi Agent** keeps it stopped across launches. After stopping or declining consent, tap **Start Tsunagi Agent** to enable automatic startup again. 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.
|
||||
|
||||
When Android chooses the first VPN address for a connection to another mesh, tsunagi translates TCP, UDP and ICMP echo traffic to that mesh’s address and returns replies to the original socket. Applications using other IPv4 protocols should bind to the address of their target mesh. If two sockets would use the same addresses, ports and protocol on the wire, the existing flow keeps its binding.
|
||||
|
||||
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.
|
||||
|
||||
Rotate the phone to select a network on the left and see its settings on the right. **Show devices** opens a table sized to the screen. Tap a peer for its version, data path and traffic. A green check marks a ready data channel, an amber spinning arc indicates a pending connection, and a red warning opens the error details. Hold an icon for its label. Rotating the phone keeps the selected peer and any edits in the VIP editor.
|
||||
|
||||
Tap the round exit button at the bottom right of the home screen. The list groups available gateways by network and shows each peer’s measured data RTT and path. **No exit node** returns to this phone’s internet connection. 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)
|
||||
|
||||
Tap the speedometer beside a network name in the exit list to test its compatible online exits one at a time. Each row shows download and upload in Mbit/s. The stop button ends the test and skips queued peers. Testing keeps the current exit selection.
|
||||
|
||||
To switch the exit from the notification shade, edit Android Quick Settings and add **Tsunagi Exit**. The first tap opens the exit chooser if you have never used one. Subsequent taps disconnect the selected exit or reconnect the last peer in its original network. The tile shows the peer name and whether the selected peer is offline. Mesh access stays available when the exit is off.
|
||||
|
||||
## Check two networks on an emulator
|
||||
|
||||
Use a disposable ARM64 emulator. The test establishes a temporary VPN, sends UDP and system pings through the production TUN adapter to a local echo peer in each subnet, and checks that the originating applications receive their replies. Set `ANDROID_SERIAL` to that emulator's serial and run from the `android` directory.
|
||||
|
||||
```sh
|
||||
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest
|
||||
adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
|
||||
adb -s "$ANDROID_SERIAL" shell appops set cy.hexor.tsunagi ACTIVATE_VPN allow
|
||||
adb -s "$ANDROID_SERIAL" shell am instrument -w cy.hexor.tsunagi.test/androidx.test.runner.AndroidJUnitRunner
|
||||
```
|
||||
|
||||
## 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,88 @@
|
||||
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
|
||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.12')
|
||||
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 cargoMetadata = new JsonSlurper().parseText(metadata)
|
||||
def verifier = cargoMetadata.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}"
|
||||
androidTestImplementation 'androidx.test:runner:1.5.2'
|
||||
androidTestImplementation 'junit:junit:4.13.2'
|
||||
}
|
||||
|
||||
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 }
|
||||
if (variant.androidTest != null) {
|
||||
def probe = tasks.register('cargoVpnSourceProbe', BuildRust) {
|
||||
workingDir workspace
|
||||
jniLibs.set(layout.buildDirectory.dir('generated/rust/vpnSourceTest'))
|
||||
inputs.files(nativeBuild.map { it.inputs.files }, fileTree("${workspace}/crates/tsunagi-android/examples"))
|
||||
commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26',
|
||||
'build', '--locked', '--example', 'vpn_source_probe', '-p', 'tsunagi-android'
|
||||
doLast {
|
||||
project.copy {
|
||||
from "${cargoMetadata.target_directory}/aarch64-linux-android/debug/examples/libvpn_source_probe.so"
|
||||
into jniLibs.dir(abi)
|
||||
}
|
||||
}
|
||||
}
|
||||
variant.androidTest.sources.jniLibs.addGeneratedSourceDirectory(probe) { it.jniLibs }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.SystemClock
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Test
|
||||
|
||||
class AgentStartupTest {
|
||||
@Suppress("DEPRECATION")
|
||||
@Test fun launchStartsAgentAndExplicitStopSurvivesReopening() {
|
||||
val test = InstrumentationRegistry.getInstrumentation()
|
||||
val context = test.targetContext
|
||||
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
|
||||
val manager = context.getSystemService(ActivityManager::class.java)
|
||||
fun running() = manager.getRunningServices(Int.MAX_VALUE).any {
|
||||
it.service.className == MeshVpn::class.java.name && it.started
|
||||
}
|
||||
fun awaitRunning(expected: Boolean) {
|
||||
val deadline = SystemClock.elapsedRealtime() + 5000
|
||||
while (running() != expected) {
|
||||
check(SystemClock.elapsedRealtime() < deadline) { "Agent did not reach started=$expected" }
|
||||
SystemClock.sleep(25)
|
||||
}
|
||||
}
|
||||
fun launch() = test.startActivitySync(Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
|
||||
|
||||
val settings = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
|
||||
val old = settings.getBoolean("auto_start", true)
|
||||
var activity: MainActivity? = null
|
||||
try {
|
||||
settings.edit().remove("auto_start").commit()
|
||||
activity = launch()
|
||||
awaitRunning(true)
|
||||
test.runOnMainSync { activity!!.stopAgent(); activity!!.finish() }
|
||||
awaitRunning(false)
|
||||
activity = launch()
|
||||
test.waitForIdleSync()
|
||||
check(!running())
|
||||
test.runOnMainSync { activity!!.requestAgent() }
|
||||
awaitRunning(true)
|
||||
} finally {
|
||||
test.runOnMainSync { activity?.stopAgent(); activity?.finish() }
|
||||
awaitRunning(false)
|
||||
settings.edit().putBoolean("auto_start", old).commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Test
|
||||
|
||||
class ExitTileTest {
|
||||
@Test fun tileKeepsTheExactLastSelectionOnlyAfterTheAgentConfirmsIt() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
val info = context.packageManager.getServiceInfo(ComponentName(context, ExitTile::class.java), 0)
|
||||
check(info.permission == "android.permission.BIND_QUICK_SETTINGS_TILE")
|
||||
check(!context.packageManager.getActivityInfo(ExitTile.entry(context), 0).exported)
|
||||
check(Native.tileExit(0, "network", "peer", true, false) == "Tsunagi Agent stopped")
|
||||
val isolated = context.createDeviceProtectedStorageContext()
|
||||
val settings = isolated.getSharedPreferences("exit_tile", Context.MODE_PRIVATE)
|
||||
settings.edit().clear().commit()
|
||||
val first = ExitTile.Target("network-a", "peer", "Gateway")
|
||||
val last = ExitTile.Target("network-b", "peer", "Gateway")
|
||||
try {
|
||||
check(ExitTile.last(isolated) == null)
|
||||
ExitTile.publish(isolated, 1L, first, true)
|
||||
ExitTile.publish(isolated, 1L, last, true)
|
||||
ExitTile.publish(isolated, 1L, null, false)
|
||||
check(ExitTile.last(isolated) == last)
|
||||
ExitTile.reset(isolated)
|
||||
check(ExitTile.last(isolated) == last)
|
||||
} finally {
|
||||
ExitTile.reset(isolated)
|
||||
settings.edit().clear().commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.VpnService
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.SystemClock
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Test
|
||||
|
||||
class VpnSourceTest {
|
||||
private external fun checkSockets(fd: Int, networkCount: Int)
|
||||
|
||||
@Test fun udpAndPingReceiveFromBothNetworksAfterAddingTheSecond() {
|
||||
System.loadLibrary("vpn_source_probe")
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
|
||||
val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||
// Android requires the manifest-declared service class. Attach it under the
|
||||
// application UID without starting the agent and binding this process to the underlay.
|
||||
val vpn = MeshVpn()
|
||||
ContextWrapper::class.java.getDeclaredMethod("attachBaseContext", Context::class.java)
|
||||
.apply { isAccessible = true }.invoke(vpn, context)
|
||||
MeshVpn::class.java.getDeclaredField("upstream").apply { isAccessible = true }
|
||||
.set(vpn, connectivity.activeNetwork)
|
||||
val hosts = listOf("198.18.234.1/24", "198.19.234.1/24")
|
||||
val routes = listOf("198.18.234.0/24", "198.19.234.0/24")
|
||||
fun establish(count: Int): ParcelFileDescriptor {
|
||||
val fd = vpn.establishTun(hosts.take(count).joinToString(","),
|
||||
routes.take(count).joinToString(","), "", 1280, false)
|
||||
check(fd >= 0) { "VPN establishment failed" }
|
||||
return ParcelFileDescriptor.adoptFd(fd)
|
||||
}
|
||||
fun checkVpn(fd: ParcelFileDescriptor, count: Int) {
|
||||
val deadline = SystemClock.elapsedRealtime() + 5000
|
||||
while (true) {
|
||||
val active = connectivity.activeNetwork
|
||||
if (connectivity.getNetworkCapabilities(active)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
|
||||
&& connectivity.getLinkProperties(active)?.linkAddresses?.size == count) break
|
||||
check(SystemClock.elapsedRealtime() < deadline) { "Timed out waiting for VPN routes" }
|
||||
SystemClock.sleep(25)
|
||||
}
|
||||
checkSockets(ParcelFileDescriptor.dup(fd.fileDescriptor).detachFd(), count)
|
||||
}
|
||||
establish(1).use { first ->
|
||||
checkVpn(first, 1)
|
||||
establish(2).use { both -> checkVpn(both, 2) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<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>
|
||||
<activity-alias android:name=".OpenExit" android:targetActivity=".MainActivity" android:exported="false" />
|
||||
<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>
|
||||
<service android:name=".ExitTile" android:exported="true"
|
||||
android:label="Tsunagi Exit" android:icon="@drawable/exit_tile"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter><action android:name="android.service.quicksettings.action.QS_TILE" /></intent-filter>
|
||||
<meta-data android:name="android.service.quicksettings.ACTIVE_TILE" android:value="true" />
|
||||
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="true" />
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,113 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
import android.widget.Toast
|
||||
|
||||
/** Quick Settings changes the internet exit of the existing mesh agent. */
|
||||
class ExitTile : TileService() {
|
||||
internal data class Target(val network: String, val peer: String, val name: String)
|
||||
private data class Snapshot(val session: Long, val active: Target?, val online: Boolean)
|
||||
|
||||
companion object {
|
||||
internal fun entry(context: Context) = ComponentName(context, "${context.packageName}.OpenExit")
|
||||
private var live = Snapshot(0, null, false)
|
||||
private var pending = false
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
internal fun last(context: Context): Target? {
|
||||
val prefs = context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE)
|
||||
val network = prefs.getString("network", null) ?: return null
|
||||
val peer = prefs.getString("peer", null) ?: return null
|
||||
return Target(network, peer, prefs.getString("name", null) ?: peer.take(12))
|
||||
}
|
||||
private fun refresh(context: Context) {
|
||||
requestListeningState(context, ComponentName(context, ExitTile::class.java))
|
||||
}
|
||||
internal fun publish(context: Context, session: Long, active: Target?, online: Boolean) {
|
||||
// Only confirmed agent status updates the last selection. Clearing an exit or
|
||||
// stopping the process leaves the exact network and peer available for reuse.
|
||||
if (active != null && last(context) != active) {
|
||||
context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE).edit()
|
||||
.putString("network", active.network).putString("peer", active.peer)
|
||||
.putString("name", active.name).apply()
|
||||
}
|
||||
live = Snapshot(session, active, online)
|
||||
refresh(context)
|
||||
}
|
||||
internal fun reset(context: Context) {
|
||||
live = Snapshot(0, null, false)
|
||||
refresh(context)
|
||||
}
|
||||
internal fun restoreIfReady(context: Context, target: Target): Boolean {
|
||||
if (live.session == 0L) return false
|
||||
if (live.active == null) change(context, live.session, target, true, waitForDiscovery = true)
|
||||
return true
|
||||
}
|
||||
private fun change(context: Context, session: Long, target: Target, connect: Boolean, waitForDiscovery: Boolean = false) {
|
||||
if (pending) return
|
||||
pending = true
|
||||
refresh(context)
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val error = Native.tileExit(session, target.network, target.peer, connect, waitForDiscovery)
|
||||
main.post {
|
||||
pending = false
|
||||
if (error != null) Toast.makeText(app, error, Toast.LENGTH_LONG).show()
|
||||
refresh(app)
|
||||
}
|
||||
}, "tsunagi-exit-tile").start()
|
||||
}
|
||||
}
|
||||
|
||||
private var displayed = live
|
||||
private var remembered: Target? = null
|
||||
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
displayed = live
|
||||
remembered = last(this)
|
||||
val tile = qsTile ?: return
|
||||
val active = displayed.active
|
||||
val peer = active ?: remembered
|
||||
val subtitle = when {
|
||||
pending -> "Updating…"
|
||||
active != null && !displayed.online -> "${active.name} · offline"
|
||||
peer != null -> peer.name
|
||||
else -> "Choose exit node"
|
||||
}
|
||||
tile.state = when {
|
||||
pending -> Tile.STATE_UNAVAILABLE
|
||||
active != null -> Tile.STATE_ACTIVE
|
||||
else -> Tile.STATE_INACTIVE
|
||||
}
|
||||
tile.label = if (Build.VERSION.SDK_INT < 29 && peer != null) "Exit · ${peer.name}" else "Tsunagi Exit"
|
||||
if (Build.VERSION.SDK_INT >= 29) tile.subtitle = subtitle
|
||||
tile.contentDescription = "Tsunagi exit node, $subtitle"
|
||||
tile.updateTile()
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
if (pending || displayed != live) { onStartListening(); return }
|
||||
val target = displayed.active ?: remembered
|
||||
if (displayed.session != 0L && target != null) {
|
||||
change(this, displayed.session, target, displayed.active == null)
|
||||
return
|
||||
}
|
||||
// Consent, a stopped service, or the first selection needs an activity.
|
||||
val open = Intent().setComponent(entry(this))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
if (Build.VERSION.SDK_INT >= 34) {
|
||||
startActivityAndCollapse(PendingIntent.getActivity(this, 2, open, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT))
|
||||
} else startActivityAndCollapse(open)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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 val settings by lazy { getSharedPreferences("agent", MODE_PRIVATE) }
|
||||
private var checkedAutoStart = false
|
||||
private var consentPending = false
|
||||
private var tileRequested = false
|
||||
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)
|
||||
consentPending = savedInstanceState?.getBoolean("consent_pending") == true
|
||||
tileRequested = savedInstanceState?.getBoolean("exit_tile") ?: (intent.component == ExitTile.entry(this))
|
||||
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)
|
||||
}
|
||||
override fun onPostResume() {
|
||||
super.onPostResume()
|
||||
if (tileRequested && !consentPending) {
|
||||
checkedAutoStart = true
|
||||
requestAgent()
|
||||
return
|
||||
}
|
||||
if (checkedAutoStart) return
|
||||
checkedAutoStart = true
|
||||
if (!MeshVpn.started && settings.getBoolean("auto_start", true)) requestAgent()
|
||||
}
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
outState.putBoolean("consent_pending", consentPending)
|
||||
outState.putBoolean("exit_tile", tileRequested)
|
||||
}
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
if (intent.component == ExitTile.entry(this)) tileRequested = true
|
||||
}
|
||||
internal fun requestAgent() {
|
||||
if (consentPending) return
|
||||
val consent = VpnService.prepare(this)
|
||||
if (consent == null) startAgent() else {
|
||||
consentPending = true
|
||||
startActivityForResult(consent, 1)
|
||||
}
|
||||
}
|
||||
private fun startAgent() {
|
||||
settings.edit().putBoolean("auto_start", true).apply()
|
||||
val service = Intent(this, MeshVpn::class.java)
|
||||
if (tileRequested) {
|
||||
tileRequested = false
|
||||
if (ExitTile.last(this) != null) service.action = MeshVpn.RESTORE_EXIT
|
||||
else surface.openExitPicker()
|
||||
}
|
||||
// A retry of an existing service may already have left foreground mode.
|
||||
if (MeshVpn.started) startService(service) else startForegroundService(service)
|
||||
}
|
||||
internal fun stopAgent() {
|
||||
settings.edit().putBoolean("auto_start", false).apply()
|
||||
startService(Intent(this, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN))
|
||||
}
|
||||
@Deprecated("Platform consent result")
|
||||
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
|
||||
super.onActivityResult(request, result, data)
|
||||
if (request == 1) {
|
||||
consentPending = false
|
||||
if (result == RESULT_OK) startAgent() else {
|
||||
tileRequested = false
|
||||
settings.edit().putBoolean("auto_start", false).apply()
|
||||
surface.input(5, "Android 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,159 @@
|
||||
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)
|
||||
@Volatile private var paused = false
|
||||
private var imeMode = 0
|
||||
private var widthPx = 0
|
||||
private var heightPx = 0
|
||||
private val repaint = Runnable { requestRender() }
|
||||
private val pickExit = java.util.concurrent.atomic.AtomicBoolean()
|
||||
fun openExitPicker() { pickExit.set(true); requestRender() }
|
||||
init {
|
||||
setEGLContextClientVersion(3)
|
||||
preserveEGLContextOnPause = true
|
||||
setRenderer(this)
|
||||
renderMode = RENDERMODE_WHEN_DIRTY
|
||||
isFocusableInTouchMode = true
|
||||
requestFocus()
|
||||
}
|
||||
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface(context.cacheDir.absolutePath)
|
||||
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
|
||||
override fun onDrawFrame(gl: GL10?) {
|
||||
if (paused) return
|
||||
if (pickExit.getAndSet(false)) Native.input(6, "")
|
||||
val landscape = resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE
|
||||
val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started, landscape)
|
||||
removeCallbacks(repaint)
|
||||
postDelayed(repaint, delay.coerceAtLeast(16))
|
||||
}
|
||||
override fun onPause() {
|
||||
paused = true
|
||||
queueEvent { Native.pauseTraffic() }
|
||||
super.onPause()
|
||||
removeCallbacks(repaint)
|
||||
}
|
||||
override fun onResume() { paused = false; super.onResume(); requestRender() }
|
||||
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 startAgent() { post { activity.requestAgent() } }
|
||||
fun stopAgent() { post { activity.stopAgent() } }
|
||||
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,225 @@
|
||||
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"
|
||||
const val RESTORE_EXIT = "cy.hexor.tsunagi.RESTORE_EXIT"
|
||||
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
|
||||
private const val NOTIFICATION_ID = 1
|
||||
private const val EXIT_CHANNEL = "exit-node"
|
||||
@Volatile var started = false
|
||||
private set
|
||||
}
|
||||
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 var restore: ExitTile.Target? = null
|
||||
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
|
||||
@Volatile private var upstream: Network? = null
|
||||
private val changes = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) = useUnderlay(network)
|
||||
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
|
||||
if (network == upstream && !closed) Native.setMetered(instance, isMetered(capabilities))
|
||||
}
|
||||
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.setMetered(instance, true)
|
||||
Native.networkChanged(instance, "")
|
||||
}
|
||||
}
|
||||
|
||||
private var physicalAddresses = ""
|
||||
// Query the network the agent actually uses, even while its VPN is the app default.
|
||||
private fun isMetered(capabilities: NetworkCapabilities?) =
|
||||
capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) != true
|
||||
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))
|
||||
val metered = isMetered(connectivity.getNetworkCapabilities(network))
|
||||
if (instance == 0L) {
|
||||
Native.trust(applicationContext)
|
||||
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses, metered)
|
||||
} else {
|
||||
Native.setMetered(instance, metered)
|
||||
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 }
|
||||
RESTORE_EXIT -> {
|
||||
restore = ExitTile.last(this)
|
||||
restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null }
|
||||
}
|
||||
DISCONNECT_EXIT -> {
|
||||
val ids = intent.data?.pathSegments.orEmpty()
|
||||
if (started && 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 (!started) stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
if (started) {
|
||||
if (Native.failed(instance)) {
|
||||
Native.stop(instance)
|
||||
instance = 0
|
||||
upstream?.let(::useUnderlay)
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
closed = false
|
||||
notifications.createNotificationChannel(NotificationChannel("vpn", "Tsunagi Agent", NotificationManager.IMPORTANCE_LOW))
|
||||
notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW))
|
||||
val startup = notification("vpn").setContentTitle("Starting Tsunagi Agent")
|
||||
if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
|
||||
startForeground(NOTIFICATION_ID, startup.build())
|
||||
started = 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, name: String, online: Boolean) {
|
||||
main.post {
|
||||
if (closed || session != instance) return@post
|
||||
val selected = if (peer.isEmpty()) null else ExitTile.Target(network, peer, name)
|
||||
ExitTile.publish(this, session, selected, online)
|
||||
restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null }
|
||||
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
|
||||
restore = null
|
||||
ExitTile.reset(this)
|
||||
if (started) connectivity.unregisterNetworkCallback(changes)
|
||||
started = false
|
||||
if (instance != 0L) Native.stop(instance)
|
||||
instance = 0L
|
||||
upstream = null
|
||||
physicalAddresses = ""
|
||||
connectivity.bindProcessToNetwork(null)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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, metered: Boolean): Long
|
||||
external fun failed(instance: Long): Boolean
|
||||
external fun stop(instance: Long)
|
||||
external fun disconnectExit(instance: Long, network: String, peer: String): Boolean
|
||||
external fun tileExit(instance: Long, network: String, peer: String, connect: Boolean, waitForDiscovery: Boolean): String?
|
||||
external fun networkChanged(instance: Long, addresses: String)
|
||||
external fun setMetered(instance: Long, metered: Boolean)
|
||||
|
||||
external fun surface(cacheDir: String)
|
||||
external fun pauseTraffic()
|
||||
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean, landscape: Boolean): 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="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:strokeColor="#ffffff" android:strokeWidth="2"
|
||||
android:strokeLineCap="round" android:strokeLineJoin="round"
|
||||
android:pathData="M12,3H4v18h8 M9,12h12 M17,8l4,4l-4,4" />
|
||||
</vector>
|
||||
@@ -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,46 @@
|
||||
[package]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.12"
|
||||
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"]
|
||||
|
||||
[[example]]
|
||||
name = "vpn_source_probe"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.12" }
|
||||
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,142 @@
|
||||
//! Peer for the Android instrumentation test. Only the test APK packages it.
|
||||
#![cfg(target_os = "android")]
|
||||
|
||||
use jni::{JNIEnv, objects::JObject};
|
||||
use std::{
|
||||
fs::File,
|
||||
io,
|
||||
net::Ipv4Addr,
|
||||
os::fd::{FromRawFd, OwnedFd},
|
||||
process::Command,
|
||||
time::Duration,
|
||||
};
|
||||
use tsunagi::overlay::{Cidr, TunDevice, TunFactory, TunRequest};
|
||||
use tsunagi_android::{dns::Resolver, tun::AndroidTun};
|
||||
|
||||
#[allow(unsafe_code)]
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_VpnSourceTest_checkSockets(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
fd: i32,
|
||||
count: i32,
|
||||
) {
|
||||
// SAFETY: the instrumentation test transfers a duplicate with detachFd().
|
||||
let file = File::from(unsafe { OwnedFd::from_raw_fd(fd) });
|
||||
let result = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.and_then(|rt| rt.block_on(check(file, count)));
|
||||
if let Err(error) = result {
|
||||
let _ = env.throw_new("java/lang/AssertionError", error.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
async fn check(file: File, count: i32) -> io::Result<()> {
|
||||
let factory = AndroidTun::new(
|
||||
Resolver::new(|_| None),
|
||||
move |_| file.try_clone(),
|
||||
|_, _| Ok(()),
|
||||
);
|
||||
let locals = [
|
||||
Ipv4Addr::new(198, 18, 234, 1),
|
||||
Ipv4Addr::new(198, 19, 234, 1),
|
||||
];
|
||||
let mut req = TunRequest::bare("vpn", 1280);
|
||||
for &local in locals.iter().take(count as usize) {
|
||||
req.addresses
|
||||
.push(Cidr::new(local.into(), 24).map_err(io::Error::other)?);
|
||||
}
|
||||
let tun = factory.create(req).await.map_err(io::Error::other)?;
|
||||
for &local in locals.iter().take(count as usize) {
|
||||
let mut octets = local.octets();
|
||||
octets[3] = 2;
|
||||
let remote = Ipv4Addr::from(octets);
|
||||
let exchange = async {
|
||||
udp(tun.as_ref(), local, remote).await?;
|
||||
ping(tun.as_ref(), local, remote).await
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(8), exchange)
|
||||
.await
|
||||
.map_err(|_| io::Error::other(format!("echo timed out on network {local}")))??;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn echo(
|
||||
tun: &dyn TunDevice,
|
||||
local: Ipv4Addr,
|
||||
remote: Ipv4Addr,
|
||||
protocol: u8,
|
||||
) -> io::Result<()> {
|
||||
use smoltcp::wire::{Icmpv4Message, Icmpv4Packet};
|
||||
loop {
|
||||
let mut pkt = tun
|
||||
.recv()
|
||||
.await
|
||||
.ok_or_else(|| io::Error::other("VPN closed"))?
|
||||
.to_vec();
|
||||
if pkt.len() < 28 || pkt[0] != 0x45 || pkt[9] != protocol || pkt[16..20] != remote.octets()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if protocol == 17 {
|
||||
if pkt[22..24] != 45678u16.to_be_bytes() || &pkt[28..] != b"mesh probe" {
|
||||
continue;
|
||||
}
|
||||
// Swapping ports preserves the UDP checksum.
|
||||
pkt[20..24].rotate_left(2);
|
||||
} else {
|
||||
let mut icmp = Icmpv4Packet::new_checked(&mut pkt[20..]).map_err(io::Error::other)?;
|
||||
if icmp.msg_type() != Icmpv4Message::EchoRequest {
|
||||
continue;
|
||||
}
|
||||
icmp.set_msg_type(Icmpv4Message::EchoReply);
|
||||
icmp.fill_checksum();
|
||||
}
|
||||
if pkt[12..16] != local.octets() {
|
||||
return Err(io::Error::other(format!(
|
||||
"peer {remote} saw source {:?}, expected {local}",
|
||||
&pkt[12..16]
|
||||
)));
|
||||
}
|
||||
// Swapping addresses preserves the IPv4 checksum and the pseudo-header sum.
|
||||
pkt[12..20].rotate_left(4);
|
||||
return tun.send(pkt.into()).await.map_err(io::Error::other);
|
||||
}
|
||||
}
|
||||
|
||||
async fn udp(tun: &dyn TunDevice, local: Ipv4Addr, remote: Ipv4Addr) -> io::Result<()> {
|
||||
let socket = tokio::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?;
|
||||
socket.connect((remote, 45678)).await?;
|
||||
socket.send(b"mesh probe").await?;
|
||||
echo(tun, local, remote, 17).await?;
|
||||
let mut reply = [0; 64];
|
||||
let n = socket.recv(&mut reply).await?;
|
||||
if &reply[..n] != b"mesh probe" {
|
||||
return Err(io::Error::other("UDP echo payload changed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ping(tun: &dyn TunDevice, local: Ipv4Addr, remote: Ipv4Addr) -> io::Result<()> {
|
||||
let command = async {
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
Command::new("/system/bin/ping")
|
||||
.args(["-n", "-c", "1", "-w", "4"])
|
||||
.arg(remote.to_string())
|
||||
.output()
|
||||
})
|
||||
.await??;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"ping {remote} failed: {}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
tokio::try_join!(command, echo(tun, local, remote, 1))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets.
|
||||
use crate::{
|
||||
touch::TouchInput,
|
||||
view::{Phone, SystemAction},
|
||||
};
|
||||
use egui::{Event, ImeEvent, Key, Modifiers, Pos2, TouchPhase};
|
||||
use egui_glow::{Painter, glow};
|
||||
use jni::{
|
||||
JNIEnv,
|
||||
objects::{JObject, JString, JValue},
|
||||
sys::{jboolean, 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>,
|
||||
touch: TouchInput,
|
||||
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_pauseTraffic(_: JNIEnv, _: JObject) {
|
||||
with_display(|d| d.ui.pause_monitor());
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
cache: JString,
|
||||
) {
|
||||
// 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);
|
||||
let cache = env.get_string(&cache).ok().map(String::from);
|
||||
DISPLAY.with_borrow_mut(|d| {
|
||||
// If Android discarded the old EGL context, its GPU resources are already gone.
|
||||
let mut ui = d
|
||||
.take()
|
||||
.map(|old| {
|
||||
// A rotation can recreate EGL. Keep expanded peers and scroll positions
|
||||
// while the new context uploads its own font atlas.
|
||||
let data = old.ctx.data_mut(std::mem::take);
|
||||
ctx.data_mut(|current| *current = data);
|
||||
old.ui
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(cache) = cache {
|
||||
ui.set_cache_dir(cache.into());
|
||||
}
|
||||
*d = Some(Display {
|
||||
painter,
|
||||
ctx,
|
||||
ui,
|
||||
events: Vec::new(),
|
||||
touch: TouchInput::default(),
|
||||
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,
|
||||
service_started: jboolean,
|
||||
landscape: jboolean,
|
||||
) -> jlong {
|
||||
with_display(|d| {
|
||||
tsunagi_ui::widgets::set_landscape(&d.ctx, landscape != 0);
|
||||
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: d.touch.take_frame(&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 = match super::status() {
|
||||
crate::service::State::Off if service_started != 0 => crate::service::State::Starting,
|
||||
state => state,
|
||||
};
|
||||
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| {
|
||||
if !d.events.is_empty() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
action = d.ui.draw(ctx, &state, super::send).or(action);
|
||||
});
|
||||
d.ui.poll_monitor(|| super::submit(crate::service::Request::WatchTraffic));
|
||||
if let Some(action) = action {
|
||||
let method = match action {
|
||||
SystemAction::Start => "startAgent",
|
||||
SystemAction::Stop => "stopAgent",
|
||||
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.touch.push(&mut d.events, phase, id, pos);
|
||||
});
|
||||
}
|
||||
#[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),
|
||||
6 => d.ui.request_exit_picker(),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
#[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,456 @@
|
||||
//! 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, ServiceSignals, 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,
|
||||
last_refresh: Option<std::time::Instant>,
|
||||
commands: mpsc::Sender<(Request, Reply)>,
|
||||
state: watch::Receiver<State>,
|
||||
underlay: watch::Sender<Vec<std::net::IpAddr>>,
|
||||
signals: watch::Sender<ServiceSignals>,
|
||||
}
|
||||
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 {
|
||||
let mut current = current();
|
||||
let Some(session) = current.as_mut() else {
|
||||
return State::Off;
|
||||
};
|
||||
let state = session.state.borrow().clone();
|
||||
let report = match &state {
|
||||
State::Ready(report, _) => Some(report.as_ref()),
|
||||
_ => None,
|
||||
};
|
||||
if session
|
||||
.last_refresh
|
||||
.is_none_or(|last| last.elapsed() >= tsunagi_ui::client::status_poll_interval(report))
|
||||
&& session
|
||||
.commands
|
||||
.try_send((Request::Refresh, oneshot::channel().0))
|
||||
.is_ok()
|
||||
{
|
||||
session.last_refresh = Some(std::time::Instant::now());
|
||||
}
|
||||
state
|
||||
}
|
||||
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||
submit(Request::Action(cmd))
|
||||
}
|
||||
fn submit(request: Request) -> Result<Response, String> {
|
||||
let (reply, result) = oneshot::channel();
|
||||
current()
|
||||
.as_ref()
|
||||
.ok_or("Tsunagi Agent stopped")?
|
||||
.commands
|
||||
.try_send((request, reply))
|
||||
.map_err(|_| "Tsunagi Agent 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,
|
||||
metered: jni::sys::jboolean,
|
||||
) -> 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 (signals, updates) = watch::channel(ServiceSignals {
|
||||
stopped: false,
|
||||
metered: metered != 0,
|
||||
});
|
||||
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.signals.send_modify(|s| s.stopped = true);
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name("tsunagi-agent".into())
|
||||
.spawn(move || {
|
||||
let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if updates.borrow().stopped {
|
||||
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, updates, |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,
|
||||
last_refresh: None,
|
||||
commands,
|
||||
state: state_rx,
|
||||
underlay,
|
||||
signals,
|
||||
});
|
||||
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(8, |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 name = env.new_string(notice.map_or("", |n| &n.name))?;
|
||||
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;Ljava/lang/String;Z)V",
|
||||
&[
|
||||
JValue::Long(id),
|
||||
JValue::Object(&network),
|
||||
JValue::Object(&peer),
|
||||
JValue::Object(&title),
|
||||
JValue::Object(&text),
|
||||
JValue::Object(&name),
|
||||
JValue::Bool(notice.is_some_and(|n| n.online).into()),
|
||||
],
|
||||
)?;
|
||||
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_tileExit(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
id: jlong,
|
||||
network: JString,
|
||||
peer: JString,
|
||||
connect: jni::sys::jboolean,
|
||||
wait_for_discovery: jni::sys::jboolean,
|
||||
) -> jni::sys::jstring {
|
||||
// Called on the tile's background worker. Never hold the session lock while awaiting the agent.
|
||||
let mut run = || -> Result<(), String> {
|
||||
let network: String = env.get_string(&network).map_err(|e| e.to_string())?.into();
|
||||
let peer: String = env.get_string(&peer).map_err(|e| e.to_string())?.into();
|
||||
let (commands, mut state) = current()
|
||||
.as_ref()
|
||||
.filter(|s| s.id == id)
|
||||
.map(|s| (s.commands.clone(), s.state.clone()))
|
||||
.ok_or("Tsunagi Agent stopped")?;
|
||||
if connect != 0 && wait_for_discovery != 0 {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?
|
||||
.block_on(crate::service::wait_for_exit_offer(
|
||||
&mut state, &network, &peer,
|
||||
))?;
|
||||
}
|
||||
let request = if connect != 0 {
|
||||
Request::RestoreExit { network, peer }
|
||||
} else {
|
||||
Request::DisconnectExit { network, peer }
|
||||
};
|
||||
let (reply, result) = oneshot::channel();
|
||||
commands
|
||||
.try_send((request, reply))
|
||||
.map_err(|_| "Tsunagi Agent is busy or stopped")?;
|
||||
result
|
||||
.blocking_recv()
|
||||
.map_err(|_| "Tsunagi Agent stopped")??;
|
||||
Ok(())
|
||||
};
|
||||
run()
|
||||
.err()
|
||||
.and_then(|e| env.new_string(e).ok())
|
||||
.map_or(std::ptr::null_mut(), JString::into_raw)
|
||||
}
|
||||
#[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.signals.send_modify(|s| s.stopped = 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_setMetered(
|
||||
_: JNIEnv,
|
||||
_: JObject,
|
||||
id: jlong,
|
||||
metered: jni::sys::jboolean,
|
||||
) {
|
||||
if let Some(s) = current().as_ref().filter(|s| s.id == id) {
|
||||
s.signals.send_if_modified(|signals| {
|
||||
let changed = signals.metered != (metered != 0);
|
||||
signals.metered = metered != 0;
|
||||
changed
|
||||
});
|
||||
}
|
||||
}
|
||||
#[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,129 @@
|
||||
//! 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));
|
||||
tsunagi::ipc::DnsReport {
|
||||
zones: view.labels,
|
||||
zone_warnings: view.warnings,
|
||||
names,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_listener(
|
||||
&self,
|
||||
mut report: tsunagi::ipc::DnsReport,
|
||||
) -> tsunagi::ipc::DnsReport {
|
||||
let address = *self.listening.borrow();
|
||||
report.listening = address.map(|ip| format!("{ip}:53")).into_iter().collect();
|
||||
report.publish_error = (address.is_none() && !report.zones.is_empty())
|
||||
.then(|| "Waiting for a VPN interface with a DNS address.".into());
|
||||
report
|
||||
}
|
||||
|
||||
/// 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,16 @@
|
||||
//! The Android application. Mesh state belongs to one service-owned Rust agent.
|
||||
|
||||
pub mod dns;
|
||||
mod monitor;
|
||||
pub mod plan;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
mod android;
|
||||
pub mod service;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
mod touch;
|
||||
#[cfg(unix)]
|
||||
pub mod tun;
|
||||
pub mod view;
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The GL thread holds a service subscription only while the inspector is visible.
|
||||
use crate::service::{Outcome, Response};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::oneshot::error::TryRecvError;
|
||||
use tsunagi::traffic::TrafficSubscription;
|
||||
use tsunagi_ui::monitor::Window;
|
||||
|
||||
pub(super) struct Monitor {
|
||||
pub view: Window,
|
||||
pending: Option<Response>,
|
||||
subscription: Option<TrafficSubscription>,
|
||||
next: Instant,
|
||||
failed: bool,
|
||||
}
|
||||
impl Monitor {
|
||||
pub fn new(cache: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
view: Window::new(cache),
|
||||
pending: None,
|
||||
subscription: None,
|
||||
next: Instant::now(),
|
||||
failed: false,
|
||||
}
|
||||
}
|
||||
pub fn pause(&mut self) {
|
||||
self.pending = None;
|
||||
self.subscription = None;
|
||||
}
|
||||
pub fn poll(&mut self, open: impl FnOnce() -> Result<Response, String>) {
|
||||
if self.failed {
|
||||
return;
|
||||
}
|
||||
if let Some(sub) = &self.subscription {
|
||||
if Instant::now() >= self.next {
|
||||
self.next = Instant::now() + Duration::from_secs(1);
|
||||
if !self.view.feed().sample(sub.snapshot()) {
|
||||
self.pause();
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let result = match &mut self.pending {
|
||||
Some(rx) => match rx.try_recv() {
|
||||
Ok(Ok(Outcome::Traffic(sub))) => {
|
||||
// Time spent in the background must expire old rows before new traffic can refresh them.
|
||||
self.view.feed().sample(Default::default());
|
||||
self.subscription = Some(sub);
|
||||
self.next = Instant::now() + Duration::from_secs(1);
|
||||
self.pending = None;
|
||||
return;
|
||||
}
|
||||
Ok(Err(e)) => Err(e),
|
||||
Err(TryRecvError::Empty) => return,
|
||||
_ => Err("Tsunagi Agent stopped".into()),
|
||||
},
|
||||
None => open().map(|r| self.pending = Some(r)),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
self.pending = None;
|
||||
self.failed = true;
|
||||
self.view.feed().error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,408 @@
|
||||
//! 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::{DnsReport, PrivilegeReport, 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 visible monitor requested its own fresh observation interval.
|
||||
WatchTraffic,
|
||||
/// A command from the same form used by the tray.
|
||||
Action(Command),
|
||||
/// The visible activity requested current counters.
|
||||
Refresh,
|
||||
/// 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,
|
||||
},
|
||||
/// Restore a remembered network/peer pair only while no other exit is selected.
|
||||
RestoreExit {
|
||||
/// Network saved at the last successful selection.
|
||||
network: String,
|
||||
/// Peer used in that network.
|
||||
peer: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// The latest service lifecycle and cost of the physical network Android selected.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct ServiceSignals {
|
||||
/// End this instance.
|
||||
pub stopped: bool,
|
||||
/// Android reports that data on the current underlay may be billed.
|
||||
pub metered: bool,
|
||||
}
|
||||
|
||||
/// 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(())
|
||||
}
|
||||
|
||||
async fn restore_exit(agent: &Agent, network: &str, peer: &str) -> Result<Outcome, String> {
|
||||
let network = network.parse().map_err(|_| "Invalid saved network ID")?;
|
||||
let peer = peer.parse().map_err(|_| "Invalid saved peer ID")?;
|
||||
let status = agent.status().await.map_err(|e| e.to_string())?;
|
||||
for n in &status.networks {
|
||||
if n.state == tsunagi::agent::NetworkState::Active
|
||||
&& let Some(current) = n.exit_via
|
||||
{
|
||||
return if n.network_id == network && current == peer {
|
||||
Ok(Outcome::Applied)
|
||||
} else {
|
||||
Err("Another exit is already selected".into())
|
||||
};
|
||||
}
|
||||
}
|
||||
agent
|
||||
.set_exit_via(network, Some(peer))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Outcome::Applied)
|
||||
}
|
||||
|
||||
// On cold start the first snapshot often precedes peer discovery. Wait on the
|
||||
// service's roster notifications, outside the command loop, then let the usual
|
||||
// serialized command validate the selection again before touching the route.
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
pub(crate) async fn wait_for_exit_offer(
|
||||
state: &mut watch::Receiver<State>,
|
||||
network: &str,
|
||||
peer: &str,
|
||||
) -> Result<(), String> {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||
loop {
|
||||
match &*state.borrow_and_update() {
|
||||
State::Ready(report, _) => {
|
||||
let n = report
|
||||
.networks
|
||||
.iter()
|
||||
.find(|n| n.network_id == network && n.active)
|
||||
.ok_or("The saved exit network is no longer active")?;
|
||||
if report
|
||||
.networks
|
||||
.iter()
|
||||
.any(|n| n.active && n.exit.via.is_some())
|
||||
|| n.peers.iter().any(|p| p.endpoint_id == peer && p.exit_node)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
State::Off => return Err("Tsunagi Agent stopped".into()),
|
||||
State::Error(error) => return Err(error.clone()),
|
||||
State::Starting => {}
|
||||
}
|
||||
state.changed().await.map_err(|_| "Tsunagi Agent stopped")?;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "The saved peer is offline or no longer offers an exit")?
|
||||
}
|
||||
|
||||
/// Private reply delivered only to the UI that requested the action.
|
||||
pub enum Outcome {
|
||||
/// Owned by one traffic screen and dropped when capture stops.
|
||||
Traffic(tsunagi::traffic::TrafficSubscription),
|
||||
/// 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>> {
|
||||
apply_on_link(command, agent, false).await
|
||||
}
|
||||
|
||||
async fn apply_on_link(
|
||||
command: Command,
|
||||
agent: &Agent,
|
||||
metered: bool,
|
||||
) -> 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::StartSpeedTest { network_id, peer } => {
|
||||
agent
|
||||
.start_speed_test(
|
||||
network_id.parse()?,
|
||||
peer.map(|p| p.parse()).transpose()?,
|
||||
metered,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Command::StopSpeedTest { network_id } => agent.stop_speed_test(network_id.parse()?),
|
||||
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> {
|
||||
snapshot(agent, wg, dns, None).await
|
||||
}
|
||||
|
||||
async fn snapshot(
|
||||
agent: &Agent,
|
||||
wg: Option<&WireguardPlugin>,
|
||||
dns: &crate::dns::Resolver,
|
||||
cached_zones: Option<DnsReport>,
|
||||
) -> tsunagi::Result<StatusReport> {
|
||||
let status = agent.status().await?;
|
||||
let overlay = agent.overlay();
|
||||
Ok(StatusReport {
|
||||
networks: tsunagi_runtime::report::networks(&status, overlay.as_ref(), wg),
|
||||
overlay_config_error: overlay.and_then(|state| state.address_error),
|
||||
dns: Some(dns.with_listener(cached_zones.unwrap_or_else(|| 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| spec.report())
|
||||
.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 signals: watch::Receiver<ServiceSignals>,
|
||||
mut publish_exit: impl FnMut(Option<&ExitNotice>),
|
||||
) {
|
||||
let mut roster = agent.watch_roster();
|
||||
roster.mark_changed(); // Load the initial zones before waiting for any actions.
|
||||
let mut cached_zones = None;
|
||||
let mut retry = false;
|
||||
let mut published_exit = None;
|
||||
let mut link = *signals.borrow_and_update();
|
||||
agent.set_speed_test_metered(link.metered);
|
||||
loop {
|
||||
if link.stopped {
|
||||
break;
|
||||
}
|
||||
let (reply, mut refresh_zones) = tokio::select! {
|
||||
biased;
|
||||
changed = signals.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
link = *signals.borrow_and_update();
|
||||
agent.set_speed_test_metered(link.metered);
|
||||
continue;
|
||||
}
|
||||
command = commands.recv() => {
|
||||
let Some((request, reply)) = command else { break };
|
||||
let refresh_zones = !matches!(request, Request::Refresh);
|
||||
let result = match request {
|
||||
Request::WatchTraffic => {
|
||||
let _ = reply.send(agent.subscribe_traffic().map(Outcome::Traffic));
|
||||
continue;
|
||||
}
|
||||
Request::Refresh => Ok(Outcome::Applied),
|
||||
Request::Action(cmd) => {
|
||||
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||
dns.replace(None);
|
||||
}
|
||||
apply_on_link(cmd, &agent, link.metered).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()),
|
||||
Request::RestoreExit {network, peer} => restore_exit(&agent, &network, &peer).await,
|
||||
};
|
||||
(Some((reply, result)), refresh_zones)
|
||||
}
|
||||
changed = roster.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
(None, true)
|
||||
}
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(2)), if retry => (None, true),
|
||||
};
|
||||
// A command may itself have changed the roster. Consume notifications
|
||||
// before taking the snapshot so changes during the read stay pending.
|
||||
refresh_zones |= roster.has_changed().unwrap_or(false);
|
||||
if refresh_zones {
|
||||
roster.borrow_and_update();
|
||||
cached_zones = None;
|
||||
}
|
||||
state.send_replace(
|
||||
match snapshot(&agent, Some(&wg), &dns, cached_zones.take()).await {
|
||||
Ok(report) => {
|
||||
retry = false;
|
||||
cached_zones.clone_from(&report.dns);
|
||||
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) => {
|
||||
retry = true;
|
||||
State::Error(error.to_string())
|
||||
}
|
||||
},
|
||||
);
|
||||
if let Some((reply, outcome)) = reply {
|
||||
let _ = reply.send(outcome);
|
||||
}
|
||||
}
|
||||
agent.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,987 @@
|
||||
#![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 a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand() {
|
||||
use crate::service::{Request, State, serve};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tsunagi::{
|
||||
discovery::SharedMemoryDiscovery,
|
||||
testing::{TestAgent, network},
|
||||
};
|
||||
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let phone = TestAgent::spawn(&discovery).await.unwrap();
|
||||
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
|
||||
.await
|
||||
.unwrap();
|
||||
let (state, mut snapshots) = watch::channel(State::Starting);
|
||||
let (stop, stopped) = watch::channel(crate::service::ServiceSignals::default());
|
||||
let (commands, requests) = mpsc::channel(4);
|
||||
let agent = phone.agent.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
serve(
|
||||
agent,
|
||||
wg,
|
||||
crate::dns::Resolver::new(|_| None),
|
||||
requests,
|
||||
&state,
|
||||
stopped,
|
||||
|_| {},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(5), snapshots.changed())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matches!(*snapshots.borrow_and_update(), State::Ready(..)));
|
||||
// Occupy the other reader slots so this test observes the real service subscription
|
||||
// being acquired on screen open and released on both background and close.
|
||||
let other_windows: Vec<_> = (0..3)
|
||||
.map(|_| phone.agent.subscribe_traffic().unwrap())
|
||||
.collect();
|
||||
let mut monitor = crate::monitor::Monitor::new(None);
|
||||
for _ in 0..2 {
|
||||
monitor.poll(|| {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
commands.try_send((Request::WatchTraffic, tx)).unwrap();
|
||||
Ok(rx)
|
||||
});
|
||||
tsunagi::testing::wait_until("the visible Android monitor subscribed", || async {
|
||||
phone.agent.subscribe_traffic().is_err().then_some(())
|
||||
})
|
||||
.await;
|
||||
monitor.poll(|| panic!("a visible monitor must reuse its subscription"));
|
||||
monitor.pause();
|
||||
assert!(phone.agent.subscribe_traffic().is_ok());
|
||||
}
|
||||
drop((monitor, other_windows));
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(2200), snapshots.changed())
|
||||
.await
|
||||
.is_err(),
|
||||
"a hidden, idle service rebuilt the status"
|
||||
);
|
||||
let (tx, rx) = oneshot::channel();
|
||||
commands.send((Request::Refresh, tx)).await.unwrap();
|
||||
rx.await.unwrap().unwrap();
|
||||
assert!(snapshots.has_changed().unwrap());
|
||||
let (name, secret) = network("background-mesh");
|
||||
phone.agent.join_network(&name, &secret).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), snapshots.wait_for(|s| {
|
||||
matches!(s, State::Ready(r, _) if r.dns.as_ref().is_some_and(|d| d.zones.iter().any(|z| z == "background-mesh")))
|
||||
})).await.unwrap().unwrap();
|
||||
stop.send_modify(|s| s.stopped = true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() {
|
||||
use crate::service::{ExitNotice, Request, State, disconnect_exit, serve, wait_for_exit_offer};
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||
async fn notice_matching(
|
||||
notices: &mut watch::Receiver<Option<ExitNotice>>,
|
||||
predicate: impl Fn(&Option<ExitNotice>) -> bool,
|
||||
) -> Option<ExitNotice> {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
notices.wait_for(predicate),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.clone()
|
||||
}
|
||||
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 wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
|
||||
.await
|
||||
.unwrap();
|
||||
let agent = phone.agent.clone();
|
||||
let (commands, requests) = mpsc::channel(4);
|
||||
let (stop, stopped) = watch::channel(crate::service::ServiceSignals::default());
|
||||
let (published, mut notices) = watch::channel(None);
|
||||
let (state, mut live) = watch::channel(State::Starting);
|
||||
let task = tokio::spawn(async move {
|
||||
serve(
|
||||
agent,
|
||||
wg,
|
||||
crate::dns::Resolver::new(|_| None),
|
||||
requests,
|
||||
&state,
|
||||
stopped,
|
||||
|notice| {
|
||||
published.send_replace(notice.cloned());
|
||||
},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
phone.agent.set_exit_via(id, Some(peer)).await.unwrap();
|
||||
let notice = notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(notice.name, "gateway");
|
||||
assert_eq!(notice.network_name, "travel");
|
||||
assert!(notice.online);
|
||||
let restore = |peer: String| {
|
||||
let commands = commands.clone();
|
||||
let network = notice.network.clone();
|
||||
async move {
|
||||
let (reply, result) = oneshot::channel();
|
||||
commands
|
||||
.send((Request::RestoreExit { network, peer }, reply))
|
||||
.await
|
||||
.unwrap();
|
||||
result.await.unwrap()
|
||||
}
|
||||
};
|
||||
disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer)
|
||||
.await
|
||||
.unwrap();
|
||||
notice_matching(&mut notices, Option::is_none).await;
|
||||
assert!(
|
||||
restore(phone.agent.endpoint_id().to_string())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
phone
|
||||
.agent
|
||||
.network_status(id)
|
||||
.await
|
||||
.unwrap()
|
||||
.exit_via
|
||||
.is_none()
|
||||
);
|
||||
// A cold service can publish its first status before the gateway advertises.
|
||||
// Keep the command loop available while waiting for this exact peer.
|
||||
exit.agent.set_exit_offer(id, false).await.unwrap();
|
||||
drop(
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
live.wait_for(|s| {
|
||||
matches!(s, State::Ready(report, _) if
|
||||
report.networks[0].peers.iter().any(|p| p.endpoint_id == notice.peer && !p.exit_node))
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
);
|
||||
let waiting = wait_for_exit_offer(&mut live, ¬ice.network, ¬ice.peer);
|
||||
tokio::pin!(waiting);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = &mut waiting => panic!("restored before the peer offered an exit"),
|
||||
result = exit.agent.set_exit_offer(id, true) => result.unwrap(),
|
||||
}
|
||||
waiting.await.unwrap();
|
||||
assert!(restore(notice.peer.clone()).await.is_ok());
|
||||
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online)).await;
|
||||
assert!(
|
||||
restore(phone.agent.endpoint_id().to_string())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
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.agent.set_hostname("renamed-gateway").await.unwrap();
|
||||
notice_matching(&mut notices, |n| {
|
||||
n.as_ref().is_some_and(|n| n.name == "renamed-gateway")
|
||||
})
|
||||
.await;
|
||||
exit.stop().await;
|
||||
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| !n.online)).await;
|
||||
disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer)
|
||||
.await
|
||||
.unwrap();
|
||||
notice_matching(&mut notices, Option::is_none).await;
|
||||
assert!(phone.agent.is_active(id).await);
|
||||
stop.send_modify(|s| s.stopped = true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[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_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", "vless-xhttp", "ss2022"];
|
||||
assert_eq!(
|
||||
PROTOCOLS.iter().map(|spec| spec.group).collect::<Vec<_>>(),
|
||||
["WireGuard", "WireGuard", "iroh", "Native", "Shoes", "Shoes"]
|
||||
);
|
||||
let (network, secret) = testing::network("carriers");
|
||||
let (other, other_secret) = testing::network("other");
|
||||
for restart in [false, true] {
|
||||
let config = testing::local_config(dir.path());
|
||||
let (config, carriers) = Carriers::configure(config, &[], None, |spec| {
|
||||
if matches!(spec.name, "tcp-tls" | "vless-xhttp" | "ss2022") {
|
||||
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"]);
|
||||
let second = agent.join_network(&other, &other_secret).await.unwrap();
|
||||
assert!(
|
||||
agent
|
||||
.network_status(second)
|
||||
.await
|
||||
.unwrap()
|
||||
.protocols
|
||||
.is_empty()
|
||||
);
|
||||
} else {
|
||||
assert_eq!(saved, names);
|
||||
agent
|
||||
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
|
||||
.await
|
||||
.unwrap();
|
||||
let second = agent.join_network(&other, &other_secret).await.unwrap();
|
||||
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
|
||||
agent.set_protocols(second, vec![]).await.unwrap();
|
||||
}
|
||||
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 network_cards_start_closed_and_keep_exit_traffic_visible_when_folded() {
|
||||
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 mut other = sample.networks[0].clone();
|
||||
other.network_id = "another-network".into();
|
||||
sample.networks.push(other);
|
||||
sample.networks[0].peers.push(tsunagi::ipc::PeerReport {
|
||||
endpoint_id: "exit-endpoint-id".into(),
|
||||
hostname: Some("gateway".into()),
|
||||
..Default::default()
|
||||
});
|
||||
sample.networks[0].exit = tsunagi::ipc::ExitReport {
|
||||
via: Some("exit-endpoint-id".into()),
|
||||
via_online: true,
|
||||
traffic: Some(tsunagi::overlay::exit::ExitTraffic {
|
||||
tx_bytes: 2048,
|
||||
rx_bytes: 512,
|
||||
}),
|
||||
client_rules: Some(tsunagi::ipc::RuleSetReport {
|
||||
ok: true,
|
||||
detail: String::new(),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let state = State::Ready(Arc::new(sample), Instant::now());
|
||||
let ctx = egui::Context::default();
|
||||
configure(&ctx);
|
||||
let mut phone = Phone::default();
|
||||
let mut frame = |events| {
|
||||
ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(360., 720.),
|
||||
)),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
phone.draw(ctx, &state, |_| {
|
||||
panic!("drawing the overview issued a command")
|
||||
});
|
||||
},
|
||||
)
|
||||
};
|
||||
let positions = |frame: &egui::FullOutput, label: &str| {
|
||||
frame
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match &shape.shape {
|
||||
Shape::Text(text) if text.galley.text() == label => {
|
||||
Some(text.pos + text.galley.rect.center().to_vec2())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
frame(vec![]);
|
||||
let closed = frame(vec![]);
|
||||
let titles = positions(&closed, name.as_str());
|
||||
assert_eq!(titles.len(), 2);
|
||||
assert!(positions(&closed, "Show devices").is_empty());
|
||||
use egui_phosphor::regular::{ARROW_DOWN, ARROW_UP};
|
||||
let font = egui::TextStyle::Body.resolve(&ctx.style());
|
||||
for icon in [ARROW_UP, ARROW_DOWN] {
|
||||
assert!(ctx.fonts(|fonts| fonts.has_glyphs(&font, icon)));
|
||||
}
|
||||
for label in [
|
||||
"Exit via gateway".to_owned(),
|
||||
format!("{ARROW_UP} 2.0 kB"),
|
||||
format!("{ARROW_DOWN} 512 B"),
|
||||
] {
|
||||
assert_eq!(positions(&closed, &label).len(), 1, "missing {label}");
|
||||
}
|
||||
let mut click = |pos| {
|
||||
for pressed in [true, false] {
|
||||
frame(vec![
|
||||
egui::Event::PointerMoved(pos),
|
||||
egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
frame(vec![])
|
||||
};
|
||||
let opened = click(titles[0]);
|
||||
assert_eq!(positions(&opened, "Show devices").len(), 1);
|
||||
assert!(positions(&opened, "Exit node…").is_empty());
|
||||
use egui_phosphor::regular as icon;
|
||||
let vip = format!("{} VIP", icon::NETWORK);
|
||||
let y = |label: &str| positions(&opened, label)[0].y;
|
||||
assert!((0.0..=26.0).contains(&(y(icon::DESKTOP_TOWER) - y(icon::FINGERPRINT))));
|
||||
assert!((0.0..=26.0).contains(&(y(icon::TREE_STRUCTURE) - y(icon::HASH))));
|
||||
assert!((0.0..=26.0).contains(&(y(icon::DEVICES) - y(icon::DEVICE_MOBILE))));
|
||||
assert!((y(&vip) - y("Show devices")).abs() < 2.0);
|
||||
assert!((y(&vip) - y(&format!("{} Copy secret", egui_phosphor::regular::COPY))).abs() < 2.0);
|
||||
let folded = click(positions(&opened, name.as_str())[0]);
|
||||
assert!(positions(&folded, "Show devices").is_empty());
|
||||
assert_eq!(positions(&folded, "Exit via gateway").len(), 1);
|
||||
let fab = positions(&folded, icon::SIGN_OUT)
|
||||
.into_iter()
|
||||
.find(|p| p.y > 625. && p.x > 265.)
|
||||
.expect("fixed exit button");
|
||||
let picker = click(fab);
|
||||
assert_eq!(positions(&picker, "No exit node").len(), 1);
|
||||
assert_eq!(positions(&picker, "gateway").len(), 1);
|
||||
let dialog = click(positions(&picker, "No exit node")[0]);
|
||||
assert_eq!(positions(&dialog, "Disconnect").len(), 1);
|
||||
let picker = click(positions(&dialog, "Cancel")[0]);
|
||||
assert!(positions(&picker, "Disconnect").is_empty());
|
||||
assert_eq!(positions(&picker, "gateway").len(), 1);
|
||||
agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_name() {
|
||||
use crate::{
|
||||
service::State,
|
||||
view::{Phone, configure},
|
||||
};
|
||||
use std::{sync::Arc, time::Instant};
|
||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||
let ctx = egui::Context::default();
|
||||
configure(&ctx);
|
||||
let mut phone = Phone::default();
|
||||
let draw = |phone: &mut Phone, state: &State| {
|
||||
let out = ctx.run(egui::RawInput::default(), |ctx| {
|
||||
phone.draw(ctx, state, |_| panic!("opening the tile selected a route"));
|
||||
});
|
||||
out.shapes
|
||||
.into_iter()
|
||||
.filter_map(|s| match s.shape {
|
||||
egui::Shape::Text(t) => Some(t.galley.text().to_owned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
phone.request_exit_picker();
|
||||
draw(&mut phone, &State::Starting);
|
||||
let networks =
|
||||
[("alpha", true), ("bravo", true), ("paused", false)].map(|(id, active)| NetworkReport {
|
||||
network_id: id.into(),
|
||||
name: "home".into(),
|
||||
peers: vec![tsunagi::ipc::PeerReport {
|
||||
endpoint_id: "same-device".into(),
|
||||
hostname: Some(format!("gateway-{id}")),
|
||||
exit_node: true,
|
||||
..Default::default()
|
||||
}],
|
||||
active,
|
||||
..Default::default()
|
||||
});
|
||||
let state = State::Ready(
|
||||
Arc::new(StatusReport {
|
||||
networks: networks.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
Instant::now(),
|
||||
);
|
||||
draw(&mut phone, &state);
|
||||
let chooser = draw(&mut phone, &state);
|
||||
assert!(chooser.iter().any(|s| s == "home · alpha"));
|
||||
assert!(chooser.iter().any(|s| s == "home · bravo"));
|
||||
assert!(chooser.iter().any(|s| s == "gateway-alpha"));
|
||||
assert!(chooser.iter().any(|s| s == "gateway-bravo"));
|
||||
assert_eq!(chooser.iter().filter(|s| *s == "No exit node").count(), 1);
|
||||
assert!(!chooser.iter().any(|s| s.contains("paused")));
|
||||
assert!(phone.back().is_none());
|
||||
assert!(draw(&mut phone, &state).iter().any(|s| s == "tsunagi"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotating_the_phone_keeps_the_selected_network_and_unsaved_vip_draft() {
|
||||
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 name_field = egui::Id::new(("vip-name", &config.id));
|
||||
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 size = std::cell::Cell::new(egui::vec2(360., 800.));
|
||||
let mut frame = |events| {
|
||||
ctx.run(
|
||||
RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size.get())),
|
||||
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![])
|
||||
};
|
||||
click("lab");
|
||||
size.set(egui::vec2(800., 360.));
|
||||
let live = click(&format!("{} VIP", egui_phosphor::regular::NETWORK));
|
||||
for label in ["Overview", "Configuration", "web.lab", "node:8080"] {
|
||||
let p = position(&live, label);
|
||||
assert!(
|
||||
(0.0..800.0).contains(&p.x),
|
||||
"{label} is outside the landscape view"
|
||||
);
|
||||
}
|
||||
let editor = click("Configuration");
|
||||
position(&editor, "Name");
|
||||
ctx.memory_mut(|m| m.request_focus(name_field));
|
||||
frame(vec![Event::Text("-draft".into())]);
|
||||
size.set(egui::vec2(360., 800.));
|
||||
let editor_portrait = frame(vec![]);
|
||||
position(&editor_portrait, "Unsaved changes");
|
||||
assert!(editor_portrait.shapes.iter().any(|s| matches!(&s.shape,
|
||||
Shape::Text(t) if t.galley.text().contains("-draft"))));
|
||||
for label in [
|
||||
"Active TCP port checks",
|
||||
"Checks and flow expiry",
|
||||
"+ Backend",
|
||||
"+ Listener",
|
||||
] {
|
||||
position(&editor_portrait, label);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Translate Android fingers into egui touch events and one primary pointer.
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TouchInput {
|
||||
primary: Option<i32>,
|
||||
clear_after_release: bool,
|
||||
}
|
||||
|
||||
impl TouchInput {
|
||||
pub(crate) fn push(&mut self, events: &mut Vec<Event>, phase: TouchPhase, id: i32, pos: Pos2) {
|
||||
events.push(Event::Touch {
|
||||
device_id: TouchDeviceId(0),
|
||||
id: TouchId(id as u64),
|
||||
phase,
|
||||
pos,
|
||||
force: None,
|
||||
});
|
||||
if phase == TouchPhase::Start && self.primary.is_none() {
|
||||
self.primary = Some(id);
|
||||
self.clear_after_release = false;
|
||||
}
|
||||
if self.primary != Some(id) {
|
||||
return;
|
||||
}
|
||||
if phase != TouchPhase::Cancel {
|
||||
events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
if phase != TouchPhase::Move {
|
||||
events.push(Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed: phase == TouchPhase::Start,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
}
|
||||
match phase {
|
||||
TouchPhase::End => {
|
||||
self.primary = None;
|
||||
self.clear_after_release = true;
|
||||
}
|
||||
TouchPhase::Cancel => {
|
||||
self.primary = None;
|
||||
events.push(Event::PointerGone);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn take_frame(&mut self, events: &mut Vec<Event>) -> Vec<Event> {
|
||||
let frame = std::mem::take(events);
|
||||
// ScrollArea reads the release velocity in this frame. PointerGone clears
|
||||
// egui's position history, so clear the touch hover in the following frame.
|
||||
if std::mem::take(&mut self.clear_after_release) {
|
||||
events.push(Event::PointerGone);
|
||||
}
|
||||
frame
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::{CentralPanel, Context, RawInput, Rect, ScrollArea, pos2, vec2};
|
||||
|
||||
#[test]
|
||||
fn a_flick_coasts_and_slows_while_a_cancelled_drag_stops() {
|
||||
for end in [TouchPhase::End, TouchPhase::Cancel] {
|
||||
let ctx = Context::default();
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
let mut input = TouchInput::default();
|
||||
let mut events = Vec::new();
|
||||
let mut frame_no = 0;
|
||||
let mut frame = |touch| {
|
||||
if let Some((phase, y)) = touch {
|
||||
input.push(&mut events, phase, 0, pos2(80., y));
|
||||
}
|
||||
frame_no += 1;
|
||||
let mut offset = 0.;
|
||||
let _ = ctx.run(
|
||||
RawInput {
|
||||
time: Some(f64::from(frame_no) / 60.),
|
||||
events: input.take_frame(&mut events),
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(320., 320.))),
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
CentralPanel::default().show(ctx, |ui| {
|
||||
offset = ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
for i in 0..60 {
|
||||
ui.add_sized(
|
||||
[270., 40.],
|
||||
egui::Button::new(format!("Peer {i}")),
|
||||
);
|
||||
}
|
||||
})
|
||||
.state
|
||||
.offset
|
||||
.y;
|
||||
});
|
||||
},
|
||||
);
|
||||
offset
|
||||
};
|
||||
// The first layout measures the content. The next registers its drag area.
|
||||
frame(None);
|
||||
frame(None);
|
||||
frame(Some((TouchPhase::Start, 220.)));
|
||||
for y in [208., 190., 168., 146.] {
|
||||
frame(Some((TouchPhase::Move, y)));
|
||||
}
|
||||
let released = frame(Some((end, 126.)));
|
||||
let first = frame(None);
|
||||
let second = frame(None);
|
||||
assert!(released > 0., "{end:?} should follow a drag");
|
||||
if end == TouchPhase::End {
|
||||
assert!(
|
||||
second > first && first > released,
|
||||
"the scroll should coast after release"
|
||||
);
|
||||
assert!(
|
||||
second - first < first - released,
|
||||
"the fling should decelerate"
|
||||
);
|
||||
} else {
|
||||
assert_eq!((released, first), (first, second));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_primary_touch_supersedes_a_release_in_the_same_frame() {
|
||||
let mut input = TouchInput::default();
|
||||
let mut events = Vec::new();
|
||||
for (phase, id) in [
|
||||
(TouchPhase::Start, 1),
|
||||
(TouchPhase::End, 1),
|
||||
(TouchPhase::Start, 2),
|
||||
] {
|
||||
input.push(&mut events, phase, id, Pos2::ZERO);
|
||||
}
|
||||
let frame = input.take_frame(&mut events);
|
||||
assert!(matches!(
|
||||
frame.last(),
|
||||
Some(Event::PointerButton { pressed: true, .. })
|
||||
));
|
||||
assert!(events.is_empty());
|
||||
input.push(&mut events, TouchPhase::End, 2, Pos2::ZERO);
|
||||
let release = input.take_frame(&mut events);
|
||||
assert!(matches!(
|
||||
release.last(),
|
||||
Some(Event::PointerButton { pressed: false, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
input.take_frame(&mut events).as_slice(),
|
||||
[Event::PointerGone]
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! 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, Mutex as StdMutex},
|
||||
};
|
||||
use tokio::{
|
||||
io::unix::AsyncFd,
|
||||
sync::{Mutex, watch},
|
||||
};
|
||||
use tsunagi::{
|
||||
BoxFuture,
|
||||
overlay::{
|
||||
OverlayError, TunDevice, TunFactory, TunRequest,
|
||||
hostrules::{
|
||||
BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan,
|
||||
ExitHostReport, ExitHostRules, RuleOutcome,
|
||||
},
|
||||
source::{SourceFlows, SourceMode},
|
||||
},
|
||||
};
|
||||
|
||||
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,
|
||||
packets: StdMutex<Option<PacketState>>,
|
||||
}
|
||||
struct PacketState {
|
||||
flows: SourceFlows,
|
||||
// At most one reassembled IPv4 datagram's worth of remaining fragments.
|
||||
pending: std::vec::IntoIter<Bytes>,
|
||||
}
|
||||
impl Attachment {
|
||||
fn packets(&self) -> std::sync::MutexGuard<'_, Option<PacketState>> {
|
||||
self.packets.lock().unwrap_or_else(|err| err.into_inner())
|
||||
}
|
||||
}
|
||||
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 device = 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((file, dns))
|
||||
};
|
||||
// Only retire the old descriptor once establishing its replacement succeeds.
|
||||
let previous = self
|
||||
.0
|
||||
.current
|
||||
.borrow()
|
||||
.clone()
|
||||
.and_then(|fd| fd.packets().take());
|
||||
let fd = device.map(|(file, dns)| {
|
||||
let aliases = next.addresses_in_order();
|
||||
let exit = match (next.full_tunnel, next.exit) {
|
||||
(true, Some(std::net::IpAddr::V4(source))) => Some(source),
|
||||
_ => None,
|
||||
};
|
||||
let flows = if let Some(mut previous) = previous {
|
||||
previous.flows.reconfigure(&aliases, exit, next.mtu);
|
||||
previous.flows
|
||||
} else {
|
||||
SourceFlows::new(&aliases, exit, next.mtu, SourceMode::Primary)
|
||||
};
|
||||
Arc::new(Attachment {
|
||||
device: file,
|
||||
addresses: next.addresses.iter().map(|a| a.addr).collect(),
|
||||
dns,
|
||||
packets: StdMutex::new(Some(PacketState {
|
||||
flows,
|
||||
pending: Vec::new().into_iter(),
|
||||
})),
|
||||
})
|
||||
});
|
||||
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::new();
|
||||
loop {
|
||||
let fd = rx.borrow_and_update().clone();
|
||||
if let Some(fd) = fd {
|
||||
if let Some(packet) = fd.packets().as_mut().and_then(|p| p.pending.next()) {
|
||||
return Some(packet);
|
||||
}
|
||||
buffer.resize(self.mtu as usize + 1, 0);
|
||||
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);
|
||||
if let Some(state) = fd.packets().as_mut() {
|
||||
let frames = state.flows.outbound(std::mem::take(&mut buffer).into());
|
||||
state.pending = frames.into_iter();
|
||||
if let Some(packet) = state.pending.next() {
|
||||
return Some(packet);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// 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 packets = fd
|
||||
.packets()
|
||||
.as_mut()
|
||||
.ok_or_else(|| OverlayError::Unavailable("VPN was reconfigured".into()))?
|
||||
.flows
|
||||
.inbound(packet);
|
||||
for packet in packets {
|
||||
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,573 @@
|
||||
//! 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,
|
||||
Monitor,
|
||||
Join,
|
||||
Devices(String),
|
||||
Vips(String),
|
||||
Exits,
|
||||
Leave(String),
|
||||
}
|
||||
impl Page {
|
||||
fn network(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Devices(id) | Self::Vips(id) | Self::Leave(id) => Some(id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn title(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Home => "tsunagi",
|
||||
Self::About => "About",
|
||||
Self::Monitor => "Traffic monitor",
|
||||
Self::Join => "Join a network",
|
||||
Self::Devices(_) => "Devices",
|
||||
Self::Vips(_) => "VIP",
|
||||
Self::Exits => "Exit nodes",
|
||||
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,
|
||||
monitor: Option<crate::monitor::Monitor>,
|
||||
cache_dir: Option<std::path::PathBuf>,
|
||||
forms: UiState,
|
||||
traffic: Traffic,
|
||||
snapshot: Snapshot,
|
||||
pending: Option<Pending>,
|
||||
error: Option<String>,
|
||||
clipboard: Option<Zeroizing<String>>,
|
||||
landscape: bool,
|
||||
pick_exit: bool,
|
||||
before_picker: Option<Page>,
|
||||
}
|
||||
|
||||
/// Keep reads at tray density. Extra hit area is reserved for the navigation bar.
|
||||
pub fn configure(ctx: &Context) {
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
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 {
|
||||
/// Private directory available to a window's temporary SQLite database.
|
||||
pub fn set_cache_dir(&mut self, path: std::path::PathBuf) {
|
||||
self.cache_dir = Some(path);
|
||||
}
|
||||
/// Release the agent subscription immediately when the activity goes into the background.
|
||||
pub fn pause_monitor(&mut self) {
|
||||
if let Some(m) = &mut self.monitor {
|
||||
m.pause();
|
||||
}
|
||||
}
|
||||
/// Poll the service only while a traffic screen is visible.
|
||||
pub fn poll_monitor(&mut self, open: impl FnOnce() -> Result<Response, String>) {
|
||||
if let Some(m) = &mut self.monitor {
|
||||
m.poll(open);
|
||||
}
|
||||
}
|
||||
fn home(&mut self) {
|
||||
self.monitor = None;
|
||||
if let Some(previous) = self.before_picker.take() {
|
||||
self.forms.exit_confirm = None;
|
||||
self.page = previous;
|
||||
return;
|
||||
}
|
||||
if let Page::Vips(id) = &self.page {
|
||||
self.forms.vip_windows.remove(id);
|
||||
}
|
||||
self.forms.join = Default::default();
|
||||
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 && self.landscape && self.forms.close_selection() {
|
||||
return None;
|
||||
} 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);
|
||||
}
|
||||
|
||||
/// The first tile tap opens the chooser once the agent is ready.
|
||||
pub fn request_exit_picker(&mut self) {
|
||||
self.pick_exit = true;
|
||||
}
|
||||
|
||||
fn open_exit_picker(&mut self) {
|
||||
if self.page != Page::Exits {
|
||||
self.before_picker = Some(std::mem::replace(&mut self.page, Page::Exits));
|
||||
self.forms.exit_confirm = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// This control lives outside both portrait and landscape scroll areas.
|
||||
fn exit_button(&mut self, ctx: &Context, ready: bool) {
|
||||
let clicked = egui::Area::new("home exit button".into())
|
||||
.anchor(egui::Align2::RIGHT_BOTTOM, [-16., -16.])
|
||||
.order(egui::Order::Middle)
|
||||
.movable(false)
|
||||
.show(ctx, |ui| {
|
||||
let (rect, response) = ui.allocate_exact_size(
|
||||
egui::vec2(60., 60.),
|
||||
if ready {
|
||||
egui::Sense::click()
|
||||
} else {
|
||||
egui::Sense::hover()
|
||||
},
|
||||
);
|
||||
let (mut fill, mut ink) = devices::exit_action_colors(ui.visuals().dark_mode);
|
||||
if !ready {
|
||||
fill = ui.visuals().widgets.inactive.bg_fill;
|
||||
ink = ui.visuals().weak_text_color();
|
||||
}
|
||||
ui.painter().circle_filled(rect.center(), 30., fill);
|
||||
if ready && (response.hovered() || response.has_focus()) {
|
||||
ui.painter().circle_stroke(rect.center(), 27., (1_f32, ink));
|
||||
}
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon::SIGN_OUT,
|
||||
egui::FontId::proportional(29.),
|
||||
ink,
|
||||
);
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(
|
||||
egui::WidgetType::Button,
|
||||
ready,
|
||||
"Choose an exit node",
|
||||
)
|
||||
});
|
||||
tsunagi_ui::widgets::hint(response, "Choose an exit node").clicked()
|
||||
})
|
||||
.inner;
|
||||
if ready && clicked {
|
||||
self.open_exit_picker();
|
||||
}
|
||||
}
|
||||
|
||||
fn landscape_home(
|
||||
&mut self,
|
||||
ui: &mut egui::Ui,
|
||||
actions: &Actions,
|
||||
report: &tsunagi::ipc::StatusReport,
|
||||
) {
|
||||
let width = (ui.available_width() / 3.)
|
||||
.clamp(146., 300.)
|
||||
.min(ui.available_width() * 0.45);
|
||||
egui::SidePanel::left("network selector")
|
||||
.resizable(false)
|
||||
.exact_width(width)
|
||||
.show_inside(ui, |ui| {
|
||||
if ui.button("Join or create a network").clicked() {
|
||||
self.page = Page::Join;
|
||||
}
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("network list")
|
||||
.show(ui, |ui| {
|
||||
for network in &report.networks {
|
||||
home::draw_network_selector(
|
||||
ui,
|
||||
network,
|
||||
report,
|
||||
&mut self.forms,
|
||||
&self.traffic,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
egui::CentralPanel::default().show_inside(ui, |ui| {
|
||||
let selected = report
|
||||
.networks
|
||||
.iter()
|
||||
.find(|n| self.forms.selected_network.as_deref() == Some(&n.network_id));
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt(("network settings", selected.map(|n| &n.network_id)))
|
||||
.show(ui, |ui| {
|
||||
if let Some(n) = selected {
|
||||
ui.heading(&n.name);
|
||||
ui.push_id(&n.network_id, |ui| {
|
||||
home::draw_network_details(
|
||||
ui,
|
||||
actions,
|
||||
&mut self.forms,
|
||||
&self.traffic,
|
||||
n,
|
||||
report,
|
||||
false,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
ui.heading("This device");
|
||||
ui.label("Tsunagi Agent is running");
|
||||
home::draw_header(ui, actions, &mut self.forms, report);
|
||||
}
|
||||
ui.add_space(80.);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// 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("Tsunagi Agent 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();
|
||||
self.landscape = tsunagi_ui::widgets::landscape(ctx);
|
||||
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();
|
||||
}
|
||||
if self
|
||||
.forms
|
||||
.selected_network
|
||||
.as_ref()
|
||||
.is_some_and(|id| !report.networks.iter().any(|n| &n.network_id == id))
|
||||
{
|
||||
self.forms.close_selection();
|
||||
}
|
||||
if self.pick_exit && self.pending.is_none() {
|
||||
self.pick_exit = false;
|
||||
self.open_exit_picker();
|
||||
}
|
||||
Some(report)
|
||||
} else {
|
||||
if self.page.network().is_some()
|
||||
|| matches!(self.page, Page::Join | Page::Monitor | Page::Exits)
|
||||
{
|
||||
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
|
||||
&& tsunagi_ui::widgets::icon_button(ui, icon::ARROW_LEFT, "Back").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 tsunagi_ui::widgets::icon_button(ui, icon::INFO, "About Tsunagi")
|
||||
.clicked()
|
||||
{
|
||||
self.page = Page::About;
|
||||
}
|
||||
if report.is_some() {
|
||||
if tsunagi_ui::widgets::icon_button(ui, icon::PULSE, "Traffic monitor")
|
||||
.clicked()
|
||||
{
|
||||
self.page = Page::Monitor;
|
||||
}
|
||||
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 Tsunagi Agent").clicked()
|
||||
{
|
||||
self.home();
|
||||
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));
|
||||
if self.page != Page::Monitor {
|
||||
self.monitor = None;
|
||||
}
|
||||
match (&self.page, selected) {
|
||||
(Page::Monitor, _) => {
|
||||
let m = self
|
||||
.monitor
|
||||
.get_or_insert_with(|| crate::monitor::Monitor::new(self.cache_dir.clone()));
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
m.view
|
||||
.show(ui, report.map(|r| r.as_ref()), self.snapshot.generation)
|
||||
});
|
||||
}
|
||||
(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| {
|
||||
if let Some(report) = report && self.page == Page::Home && self.landscape {
|
||||
self.landscape_home(ui, &actions, report);
|
||||
return;
|
||||
}
|
||||
egui::ScrollArea::vertical().id_salt(self.page.title()).auto_shrink([false, false]).show(ui, |ui| {
|
||||
let Some(report) = report else {
|
||||
match state {
|
||||
State::Starting => {ui.spinner(); ui.label("Starting Tsunagi Agent…");}
|
||||
_ => {
|
||||
if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("Tsunagi Agent is stopped");}
|
||||
if ui.button("Start Tsunagi Agent").clicked() {self.error = None; 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 {
|
||||
home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false);
|
||||
}
|
||||
ui.add_space(80.);
|
||||
}
|
||||
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::Exits => {
|
||||
if let Some(choice) = devices::choose_exit_with_tests(ui, &report.networks, &report.endpoint_id, &actions) {
|
||||
self.forms.exit_confirm = Some(choice);
|
||||
}
|
||||
if report.networks.is_empty() && ui.button("Join or create a network").clicked() {
|
||||
self.before_picker = None;
|
||||
self.page = Page::Join;
|
||||
}
|
||||
}
|
||||
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();}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(report) = report
|
||||
&& self.page == Page::Home
|
||||
{
|
||||
for n in &report.networks {
|
||||
if self.forms.open_devices.remove(&n.network_id) {
|
||||
self.page = Page::Devices(n.network_id.clone());
|
||||
break;
|
||||
}
|
||||
if self.forms.vip_windows.contains_key(&n.network_id) {
|
||||
self.page = Page::Vips(n.network_id.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.page == Page::Home && self.forms.exit_confirm.is_none() {
|
||||
self.exit_button(ctx, report.is_some() && !actions.busy());
|
||||
}
|
||||
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.12"
|
||||
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,950 @@
|
||||
//! 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 confirm_delivery(&self) {
|
||||
self.raw.confirm_delivery();
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
[package]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.12"
|
||||
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]
|
||||
tsunagi-speedtest = { path = "../tsunagi-speedtest", version = "0.1.0" }
|
||||
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"
|
||||
# IPv4 packet and checksum codecs shared by the Android VPN and Wintun.
|
||||
smoltcp = { version = "0.12", default-features = false, features = ["std", "proto-ipv4"] }
|
||||
# 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(any(windows, target_os = "macos"))'.dependencies]
|
||||
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Networking_WinSock",
|
||||
"Win32_Security",
|
||||
"Win32_Security_Authorization",
|
||||
"Win32_Foundation",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
# 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
|
||||
@@ -9,7 +9,7 @@ use std::time::Duration;
|
||||
|
||||
use iroh::EndpointId;
|
||||
|
||||
use crate::identity::NetworkId;
|
||||
use crate::identity::{NetworkId, NetworkName};
|
||||
use crate::net::TransportKind;
|
||||
use crate::proto::ControlMessage;
|
||||
use crate::proto::handshake::Role;
|
||||
@@ -48,8 +48,12 @@ pub enum Event {
|
||||
PeerDisconnected {
|
||||
/// The network the session belonged to.
|
||||
network: NetworkId,
|
||||
/// Its locally configured name.
|
||||
network_name: NetworkName,
|
||||
/// The peer.
|
||||
peer: EndpointId,
|
||||
/// Last known name of the authenticated peer, when available.
|
||||
hostname: Option<String>,
|
||||
/// Why the session ended. Free of secrets.
|
||||
reason: String,
|
||||
},
|
||||
@@ -129,6 +133,19 @@ pub enum Event {
|
||||
/// Why it is not up.
|
||||
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.
|
||||
PluginError {
|
||||
/// 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
@@ -0,0 +1,133 @@
|
||||
//! The elected opener grants one bounded reverse dial over authenticated control.
|
||||
use super::{ControlMessage, EndpointId, LinkOutcome, PluginCapability, Runtime};
|
||||
use crate::dataplane::transport::{DataCarrier, PacketLink, TransportPayload};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub(super) const PROTOCOL: &str = "link-reverse";
|
||||
|
||||
pub(super) fn capability() -> PluginCapability {
|
||||
PluginCapability {
|
||||
protocol: PROTOCOL.into(),
|
||||
version: 1,
|
||||
enabled: true,
|
||||
data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
fn mutual_carrier(&self, peer: EndpointId, name: &str) -> Option<&dyn DataCarrier> {
|
||||
let caps = &self.sessions.get(&peer)?.capabilities;
|
||||
self.params
|
||||
.carriers
|
||||
.iter()
|
||||
.find(|c| {
|
||||
c.protocol_id() == name
|
||||
&& caps.iter().any(|cap| {
|
||||
cap.enabled && cap.protocol == name && cap.version == c.protocol_version()
|
||||
})
|
||||
})
|
||||
.map(|c| c.as_ref())
|
||||
}
|
||||
|
||||
pub(super) fn can_reverse(&self, peer: EndpointId, protocol: &str) -> bool {
|
||||
self.mutual_carrier(peer, protocol)
|
||||
.is_some_and(|c| c.supports_reverse_dial())
|
||||
&& self.sessions.get(&peer).is_some_and(|s| {
|
||||
s.capabilities
|
||||
.iter()
|
||||
.any(|c| c.enabled && c.protocol == PROTOCOL && c.version == 1)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn send_reverse(
|
||||
&mut self,
|
||||
peer: EndpointId,
|
||||
protocol: &str,
|
||||
token: u64,
|
||||
request: bool,
|
||||
) -> bool {
|
||||
let Ok(bytes) = postcard::to_stdvec(&(request, token, protocol)) else {
|
||||
return false;
|
||||
};
|
||||
self.send_to(
|
||||
peer,
|
||||
ControlMessage::Transport {
|
||||
protocol: PROTOCOL.into(),
|
||||
payload: TransportPayload::new(bytes),
|
||||
},
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
pub(super) fn ask_for_reverse(&mut self, attempt: &LinkOutcome) -> bool {
|
||||
let peer = attempt.peer;
|
||||
let protocol = &attempt.protocol;
|
||||
let generation = attempt.generation;
|
||||
if self.local_id >= peer
|
||||
|| !self.can_reverse(peer, protocol)
|
||||
|| !self.send_reverse(peer, protocol, generation, true)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let key = (peer, protocol.clone());
|
||||
self.reverse_dials.insert(key.clone(), generation);
|
||||
let tx = self.link_results_tx.clone();
|
||||
let protocol = protocol.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(12)).await;
|
||||
let _ = tx
|
||||
.send(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol,
|
||||
result: Err("reverse TCP dial timed out".into()),
|
||||
})
|
||||
.await;
|
||||
});
|
||||
self.link_tasks.insert(key, task.abort_handle());
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn receive_reverse(&mut self, peer: EndpointId, payload: &[u8]) {
|
||||
let Ok((request, generation, protocol)) =
|
||||
postcard::from_bytes::<(bool, u64, &str)>(payload)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if protocol.len() > crate::dataplane::MAX_PROTOCOL_ID_LEN
|
||||
|| !self.can_reverse(peer, protocol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let key = (peer, protocol.to_owned());
|
||||
if request && peer < self.local_id {
|
||||
if self.opening.contains(&key) || self.links.get(&key).is_some_and(|l| !l.is_closed()) {
|
||||
return;
|
||||
}
|
||||
if self.no_direct_data(peer)
|
||||
|| self
|
||||
.protocol_dial_states
|
||||
.get(&key)
|
||||
.is_some_and(|s| s.cooldown_until > Instant::now())
|
||||
{
|
||||
self.send_reverse(peer, protocol, generation, false);
|
||||
return;
|
||||
}
|
||||
self.reverse_dials.insert(key, generation);
|
||||
self.start_link_attempt(peer, protocol.to_owned(), false);
|
||||
} else if !request
|
||||
&& self.local_id < peer
|
||||
&& self.reverse_dials.get(&key) == Some(&generation)
|
||||
{
|
||||
if let Some(task) = self.link_tasks.remove(&key) {
|
||||
task.abort();
|
||||
}
|
||||
self.handle_link_result(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol: protocol.into(),
|
||||
result: Err("neither TCP dial direction succeeded".into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Compare one alternative per peer while normal traffic stays on the incumbent.
|
||||
//! The elected dialler chooses for both directions. Each decision names the
|
||||
//! exact two health profiles, so delayed messages cannot retire a reopened link.
|
||||
use super::{ControlMessage, EndpointId, Event, PacketLink, PluginCapability, Runtime};
|
||||
use crate::dataplane::transport::{LinkQuality, TransportPayload};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub(super) const PROTOCOL: &str = "link-choice";
|
||||
const RETRY: Duration = Duration::from_secs(3);
|
||||
const NEXT_TRIAL: Duration = Duration::from_secs(120);
|
||||
const MIN_WINDOW: Duration = Duration::from_secs(6);
|
||||
// Allow a full rolling health window to replace probes sent before the
|
||||
// responder installed its profile. Persistent loss still disqualifies a trial.
|
||||
const MAX_WINDOW: Duration = Duration::from_secs(30);
|
||||
|
||||
pub(super) fn capability() -> PluginCapability {
|
||||
PluginCapability {
|
||||
protocol: PROTOCOL.into(),
|
||||
version: 1,
|
||||
enabled: true,
|
||||
data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn supports_choice(caps: &[PluginCapability]) -> bool {
|
||||
caps.iter()
|
||||
.any(|c| c.enabled && c.protocol == PROTOCOL && c.version == 1)
|
||||
}
|
||||
|
||||
/// None keeps measuring on the alternative while user traffic stays on the incumbent.
|
||||
fn promotion_decision(age: Duration, measured: Option<(LinkQuality, LinkQuality)>) -> Option<bool> {
|
||||
if age < MIN_WINDOW {
|
||||
return None;
|
||||
}
|
||||
let Some((current, alternative)) = measured.filter(|(current, alternative)| {
|
||||
current.samples >= 5 && alternative.samples >= 5 && alternative.losses == 0
|
||||
}) else {
|
||||
return (age >= MAX_WINDOW).then_some(false);
|
||||
};
|
||||
let gain = current.rtt.saturating_sub(alternative.rtt);
|
||||
Some(gain >= (current.rtt / 5).max(Duration::from_millis(5)))
|
||||
}
|
||||
|
||||
/// Fixed-size identifiers from the two privately negotiated health profiles.
|
||||
/// The responder echoes this value after accepting a decision.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
struct Choice {
|
||||
keep: [u8; 16],
|
||||
retire: [u8; 16],
|
||||
}
|
||||
|
||||
struct Trial {
|
||||
protocol: String,
|
||||
started: Instant,
|
||||
decision: Option<Choice>,
|
||||
retry_at: Instant,
|
||||
}
|
||||
|
||||
pub(super) struct Schedule {
|
||||
next: Instant,
|
||||
cursor: usize,
|
||||
trial: Option<Trial>,
|
||||
}
|
||||
|
||||
impl Schedule {
|
||||
pub(super) fn is_trial(&self, protocol: &str) -> bool {
|
||||
self.trial
|
||||
.as_ref()
|
||||
.is_some_and(|trial| trial.protocol == protocol)
|
||||
}
|
||||
|
||||
/// The responder can close the losing link before its acknowledgement
|
||||
/// arrives. Only an exact generation match makes this a planned closure.
|
||||
pub(super) fn retiring(&self, profile: Option<[u8; 16]>) -> bool {
|
||||
self.trial
|
||||
.as_ref()
|
||||
.and_then(|trial| trial.decision)
|
||||
.is_some_and(|choice| Some(choice.retire) == profile)
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
pub(super) fn link_installed(&mut self, peer: EndpointId) {
|
||||
if self.local_id.as_bytes() >= peer.as_bytes() || self.params.carriers.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
let jitter = (peer.as_bytes()[0] ^ self.network_id.as_bytes()[0]) % 6;
|
||||
let schedule = self.comparisons.entry(peer).or_insert(Schedule {
|
||||
next: now + Duration::from_secs(12 + u64::from(jitter)),
|
||||
cursor: 0,
|
||||
trial: None,
|
||||
});
|
||||
if let Some(trial) = &mut schedule.trial {
|
||||
// Any replacement invalidates an outstanding decision naming the
|
||||
// previous pair of profiles. Compare both current links afresh.
|
||||
trial.decision = None;
|
||||
trial.started = now;
|
||||
trial.retry_at = now;
|
||||
}
|
||||
}
|
||||
|
||||
/// At most two alternatives per network are opened or measured at once.
|
||||
/// Waiting for a peer to acknowledge a decision uses no measurement slot. Old peers
|
||||
/// keep the original single-carrier behaviour without a wire upgrade.
|
||||
pub(super) fn next_comparison(
|
||||
&mut self,
|
||||
served: &[(String, u16)],
|
||||
now: Instant,
|
||||
) -> Option<(EndpointId, String)> {
|
||||
if !supports_choice(&self.local_capabilities)
|
||||
|| self
|
||||
.comparisons
|
||||
.values()
|
||||
.filter_map(|s| s.trial.as_ref())
|
||||
.filter(|trial| trial.decision.is_none())
|
||||
.count()
|
||||
>= 2
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (peer, index) =
|
||||
self.comparisons
|
||||
.iter()
|
||||
.filter_map(|(peer, schedule)| {
|
||||
if schedule.next > now
|
||||
|| schedule.trial.is_some()
|
||||
|| self.no_direct_data(*peer)
|
||||
|| self.opening.iter().any(|(id, _)| id == peer)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let session = self.sessions.get(peer)?;
|
||||
if !supports_choice(&session.capabilities)
|
||||
|| self.hub.direct_kinds(*peer).len() != 1
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let index = (0..served.len())
|
||||
.map(|n| (n + schedule.cursor) % served.len())
|
||||
.find(|i| {
|
||||
let (name, version) = &served[*i];
|
||||
let key = (*peer, name.clone());
|
||||
!self.links.contains_key(&key)
|
||||
&& self
|
||||
.protocol_dial_states
|
||||
.get(&key)
|
||||
.is_none_or(|s| s.cooldown_until <= now)
|
||||
&& session.capabilities.iter().any(|c| {
|
||||
c.enabled && &c.protocol == name && &c.version == version
|
||||
})
|
||||
})?;
|
||||
Some((schedule.next, *peer, index))
|
||||
})
|
||||
.min()
|
||||
.map(|(_, peer, index)| (peer, index))?;
|
||||
let schedule = self.comparisons.get_mut(&peer)?;
|
||||
let protocol = served[index].0.clone();
|
||||
schedule.cursor = index + 1;
|
||||
schedule.trial = Some(Trial {
|
||||
protocol: protocol.clone(),
|
||||
started: now,
|
||||
decision: None,
|
||||
retry_at: now,
|
||||
});
|
||||
Some((peer, protocol))
|
||||
}
|
||||
|
||||
pub(super) fn finish_comparison(&mut self, peer: EndpointId) {
|
||||
if let Some(schedule) = self.comparisons.get_mut(&peer) {
|
||||
schedule.trial = None;
|
||||
schedule.next = Instant::now() + NEXT_TRIAL;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn review_comparisons(&mut self) {
|
||||
let peers: Vec<_> = self
|
||||
.comparisons
|
||||
.iter()
|
||||
.filter(|(_, s)| s.trial.is_some())
|
||||
.map(|(peer, _)| *peer)
|
||||
.collect();
|
||||
for peer in peers {
|
||||
self.review_trial(peer);
|
||||
}
|
||||
}
|
||||
|
||||
fn review_trial(&mut self, peer: EndpointId) {
|
||||
let Some(trial) = self.comparisons.get(&peer).and_then(|s| s.trial.as_ref()) else {
|
||||
return;
|
||||
};
|
||||
let key = (peer, trial.protocol.clone());
|
||||
if self.opening.contains(&key) {
|
||||
return;
|
||||
}
|
||||
let kinds = self.hub.direct_kinds(peer);
|
||||
if kinds.len() < 2 || !self.links.contains_key(&key) {
|
||||
self.finish_comparison(peer);
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if now < trial.retry_at {
|
||||
return;
|
||||
}
|
||||
let choice = if let Some(choice) = trial.decision {
|
||||
choice
|
||||
} else {
|
||||
let Some(other) = kinds.iter().find(|kind| **kind != trial.protocol) else {
|
||||
return;
|
||||
};
|
||||
let Some(current) = self.links.get(&(peer, other.clone())) else {
|
||||
return;
|
||||
};
|
||||
let Some(candidate) = self.links.get(&key) else {
|
||||
return;
|
||||
};
|
||||
let age = now.duration_since(trial.started);
|
||||
let measured = current.quality().zip(candidate.quality());
|
||||
let Some(promote) = promotion_decision(age, measured) else {
|
||||
return;
|
||||
};
|
||||
tracing::debug!(peer = %peer.fmt_short(), incumbent = %other, candidate = %trial.protocol, ?measured, promote, "compared data carriers");
|
||||
let (winner, loser) = if promote {
|
||||
(candidate, current)
|
||||
} else {
|
||||
(current, candidate)
|
||||
};
|
||||
let (Some(keep), Some(retire)) = (winner.profile_id(), loser.profile_id()) else {
|
||||
return;
|
||||
};
|
||||
self.hub
|
||||
.prefer_direct(peer, if promote { &trial.protocol } else { other });
|
||||
Choice { keep, retire }
|
||||
};
|
||||
if let Some(trial) = self
|
||||
.comparisons
|
||||
.get_mut(&peer)
|
||||
.and_then(|s| s.trial.as_mut())
|
||||
{
|
||||
trial.decision = Some(choice);
|
||||
trial.retry_at = now + RETRY;
|
||||
}
|
||||
self.send_choice(peer, choice);
|
||||
}
|
||||
|
||||
fn send_choice(&mut self, peer: EndpointId, choice: Choice) {
|
||||
if let Ok(bytes) = postcard::to_stdvec(&choice) {
|
||||
let _ = self.send_to(
|
||||
peer,
|
||||
ControlMessage::Transport {
|
||||
protocol: PROTOCOL.into(),
|
||||
payload: TransportPayload::new(bytes),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn receive_choice(&mut self, peer: EndpointId, payload: &[u8]) {
|
||||
if payload.len() != 32 {
|
||||
return;
|
||||
}
|
||||
let Ok(choice) = postcard::from_bytes::<Choice>(payload) else {
|
||||
return;
|
||||
};
|
||||
if choice.keep == choice.retire
|
||||
|| !supports_choice(&self.local_capabilities)
|
||||
|| !self
|
||||
.sessions
|
||||
.get(&peer)
|
||||
.is_some_and(|s| supports_choice(&s.capabilities))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let dialler = self.local_id.as_bytes() < peer.as_bytes();
|
||||
if dialler
|
||||
&& self
|
||||
.comparisons
|
||||
.get(&peer)
|
||||
.and_then(|s| s.trial.as_ref())
|
||||
.and_then(|t| t.decision)
|
||||
!= Some(choice)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let find = |profile| {
|
||||
self.links
|
||||
.iter()
|
||||
.find(|((id, _), link)| {
|
||||
*id == peer && !link.is_closed() && link.profile_id() == Some(profile)
|
||||
})
|
||||
.map(|((_, kind), _)| kind.clone())
|
||||
};
|
||||
let Some(winner) = find(choice.keep) else {
|
||||
return;
|
||||
};
|
||||
let loser = find(choice.retire);
|
||||
self.hub.prefer_direct(peer, &winner);
|
||||
if let Some(kind) = loser {
|
||||
self.hub.clear_direct(peer, &kind);
|
||||
if let Some(link) = self.links.remove(&(peer, kind.clone())) {
|
||||
link.close();
|
||||
self.emit(Event::DataLinkDown {
|
||||
network: self.network_id,
|
||||
peer,
|
||||
protocol: kind,
|
||||
reason: format!("carrier comparison kept {winner}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
if dialler {
|
||||
self.finish_comparison(peer);
|
||||
} else {
|
||||
self.send_choice(peer, choice);
|
||||
}
|
||||
self.announce_reach(false);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn measurement(ms: u64, samples: usize, losses: usize) -> LinkQuality {
|
||||
LinkQuality {
|
||||
rtt: Duration::from_millis(ms),
|
||||
samples,
|
||||
losses,
|
||||
observed_at: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loss_during_profile_installation_can_age_out_before_deciding() {
|
||||
let observed =
|
||||
|samples, losses| Some((measurement(200, 20, 0), measurement(30, samples, losses)));
|
||||
assert_eq!(promotion_decision(MIN_WINDOW, observed(5, 1)), None);
|
||||
assert_eq!(
|
||||
promotion_decision(Duration::from_secs(24), observed(20, 0)),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(promotion_decision(MAX_WINDOW, observed(18, 2)), Some(false));
|
||||
assert_eq!(promotion_decision(MAX_WINDOW, observed(4, 0)), Some(false));
|
||||
assert_eq!(promotion_decision(MIN_WINDOW / 2, observed(5, 0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_only_a_sampled_reliable_and_materially_faster_path() {
|
||||
let better = |current: &LinkQuality, candidate: &LinkQuality| {
|
||||
promotion_decision(MAX_WINDOW, Some((*current, *candidate))) == Some(true)
|
||||
};
|
||||
let current = measurement(350, 20, 1);
|
||||
assert!(better(¤t, &measurement(60, 6, 0)));
|
||||
assert!(!better(¤t, &measurement(60, 1, 0)));
|
||||
assert!(!better(¤t, &measurement(60, 6, 2)));
|
||||
assert!(!better(&measurement(61, 20, 0), &measurement(59, 10, 0)));
|
||||
assert!(!better(&measurement(10, 20, 0), &measurement(7, 10, 0)));
|
||||
assert!(!better(&measurement(8, 2, 0), &measurement(1, 6, 0)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Each ordered stream keeps a cursor into the latest signed state. A slow or
|
||||
//! reconnecting peer can catch up without a per-peer backlog of signed frames.
|
||||
use super::{ControlMessage, EndpointId, MAX_RETIREMENT_LEN, Runtime};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
|
||||
/// The stable identity of a signed object, including tombstones.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum SyncKey {
|
||||
Claim(EndpointId),
|
||||
Retirement(EndpointId),
|
||||
Vip(String),
|
||||
}
|
||||
|
||||
/// One entry per stored object, regardless of its edit count or the number of
|
||||
/// peers. Revisions are local scheduling information, never persisted or sent.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Changes {
|
||||
latest: u64,
|
||||
revisions: BTreeMap<SyncKey, u64>,
|
||||
order: BTreeMap<u64, SyncKey>,
|
||||
}
|
||||
|
||||
impl Changes {
|
||||
fn note(&mut self, key: SyncKey) {
|
||||
self.latest += 1;
|
||||
if let Some(previous) = self.revisions.insert(key.clone(), self.latest) {
|
||||
self.order.remove(&previous);
|
||||
}
|
||||
self.order.insert(self.latest, key);
|
||||
}
|
||||
|
||||
fn after(&self, cursor: u64) -> impl Iterator<Item = (u64, &SyncKey)> {
|
||||
self.order
|
||||
.range((Excluded(cursor), Unbounded))
|
||||
.map(|(&revision, key)| (revision, key))
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
pub(super) fn index_stored_state(&mut self) {
|
||||
for record in self.state.records() {
|
||||
if let Ok(author) = record.author_id() {
|
||||
self.changes.note(SyncKey::Claim(author));
|
||||
}
|
||||
}
|
||||
for marker in self.state.retirements() {
|
||||
if let Ok(target) = marker.target.author_id() {
|
||||
self.changes.note(SyncKey::Retirement(target));
|
||||
}
|
||||
}
|
||||
for id in self.params.vips.ids() {
|
||||
self.changes.note(SyncKey::Vip(id));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn share_changes(&mut self, keys: impl IntoIterator<Item = SyncKey>) -> usize {
|
||||
for key in keys {
|
||||
self.changes.note(key);
|
||||
}
|
||||
self.params.roster_changed.send_replace(());
|
||||
self.flush_updates();
|
||||
self.sessions
|
||||
.values()
|
||||
.filter(|session| session.state_sent == self.changes.latest)
|
||||
.count()
|
||||
}
|
||||
|
||||
pub(super) fn flush_updates(&mut self) {
|
||||
let peers: Vec<_> = self
|
||||
.sessions
|
||||
.values()
|
||||
.filter(|s| s.state_sent < self.changes.latest)
|
||||
.map(|s| s.peer)
|
||||
.collect();
|
||||
for peer in peers {
|
||||
self.flush_peer(peer);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn flush_peer(&mut self, peer: EndpointId) {
|
||||
// A retirement contains a signed claim plus a second signature, so its
|
||||
// size bound also covers a claim. VIPs are validated as complete frames.
|
||||
let limits = &self.params.limits;
|
||||
let batch = (limits.max_frame_len.saturating_sub(128) / MAX_RETIREMENT_LEN)
|
||||
.max(1)
|
||||
.min(limits.max_state_records.max(1));
|
||||
while let Some(session) = self.sessions.get(&peer) {
|
||||
if session.outbound.capacity() == 0 {
|
||||
break;
|
||||
}
|
||||
let cursor = session.state_sent;
|
||||
let Some((mut through, first)) = self.changes.after(cursor).next() else {
|
||||
break;
|
||||
};
|
||||
let message = {
|
||||
let pending = self.changes.after(cursor).take(batch);
|
||||
match first {
|
||||
SyncKey::Claim(_) => ControlMessage::State {
|
||||
records: pending
|
||||
.map_while(|(revision, key)| {
|
||||
let SyncKey::Claim(id) = key else { return None };
|
||||
through = revision;
|
||||
self.state.get(id).cloned()
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
SyncKey::Retirement(_) => ControlMessage::Retirements {
|
||||
markers: pending
|
||||
.map_while(|(revision, key)| {
|
||||
let SyncKey::Retirement(id) = key else {
|
||||
return None;
|
||||
};
|
||||
through = revision;
|
||||
self.state.retirement_of(id).cloned()
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
SyncKey::Vip(id) => ControlMessage::Vips {
|
||||
entries: self.params.vips.entries(id),
|
||||
},
|
||||
}
|
||||
};
|
||||
if self.send_to(peer, message).is_err() {
|
||||
break;
|
||||
}
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
session.state_sent = through;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn slow_and_returning_sessions_each_get_the_latest_revision() {
|
||||
let mut index = Changes::default();
|
||||
let first = SyncKey::Vip("first".into());
|
||||
let second = SyncKey::Vip("second".into());
|
||||
index.note(first.clone());
|
||||
let sent = index.latest;
|
||||
index.note(second.clone());
|
||||
index.note(first.clone());
|
||||
for cursor in [0, sent] {
|
||||
let pending: Vec<_> = index.after(cursor).map(|(_, key)| key.clone()).collect();
|
||||
assert_eq!(pending, [second.clone(), first.clone()]);
|
||||
}
|
||||
assert_eq!(index.after(index.latest).count(), 0);
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use iroh::EndpointId;
|
||||
use iroh::endpoint::{Connection, RecvStream, SendStream};
|
||||
use iroh::endpoint::{Connection, ConnectionError, RecvStream, SendStream};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
@@ -60,6 +60,22 @@ pub(crate) enum SessionEvent {
|
||||
},
|
||||
}
|
||||
|
||||
/// The transport category and code are useful in logs. Remote close text is
|
||||
/// arbitrary peer-supplied data and may contain secrets or control characters.
|
||||
pub(super) fn describe_quic_close(cause: ConnectionError) -> String {
|
||||
match cause {
|
||||
ConnectionError::ApplicationClosed(close) => {
|
||||
format!("QUIC closed by peer, application code {}", close.error_code)
|
||||
}
|
||||
ConnectionError::ConnectionClosed(close) => {
|
||||
format!("QUIC closed by peer, transport code {}", close.error_code)
|
||||
}
|
||||
ConnectionError::TransportError(error) => format!("QUIC transport error {}", error.code),
|
||||
ConnectionError::LocallyClosed => "QUIC closed locally".to_owned(),
|
||||
other => format!("QUIC: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A live session, as held by the network runtime.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Session {
|
||||
@@ -68,22 +84,35 @@ pub(crate) struct Session {
|
||||
pub(crate) role: Role,
|
||||
pub(crate) established: Instant,
|
||||
pub(crate) conn: Connection,
|
||||
/// Already encoded frame payloads, so the runtime can account for the exact
|
||||
/// number of control bytes it queues.
|
||||
pub(crate) outbound: mpsc::Sender<Vec<u8>>,
|
||||
/// Last signed-state revision queued on this ordered stream.
|
||||
pub(super) state_sent: u64,
|
||||
/// Prefix of the current introduction list already queued on this stream.
|
||||
pub(super) introductions_sent: usize,
|
||||
pub(super) reach_sent: Option<Instant>,
|
||||
/// Already encoded frames, accounted for when queued.
|
||||
pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>,
|
||||
pub(crate) hostname: Option<String>,
|
||||
pub(crate) agent_version: Option<String>,
|
||||
/// Selection reported by this peer, or unknown for a pre-extension session.
|
||||
pub(super) uses_our_exit: Option<bool>,
|
||||
/// Last selection successfully queued to this recipient on this session.
|
||||
pub(super) notified_exit_use: Option<bool>,
|
||||
pub(crate) capabilities: Vec<PluginCapability>,
|
||||
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_received: u64,
|
||||
pub(crate) bytes_sent: u64,
|
||||
pub(crate) bytes_received: u64,
|
||||
reader: JoinHandle<()>,
|
||||
writer: JoinHandle<()>,
|
||||
path_monitor: JoinHandle<()>,
|
||||
shutdown: Shutdown,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Signals both tasks to stop and waits for them, with a bounded grace
|
||||
/// Signals all tasks to stop and waits for them, with a bounded grace
|
||||
/// period.
|
||||
///
|
||||
/// A peer that stops reading must not be able to hold up shutdown, so the
|
||||
@@ -93,6 +122,7 @@ impl Session {
|
||||
conn,
|
||||
reader,
|
||||
writer,
|
||||
path_monitor,
|
||||
shutdown,
|
||||
..
|
||||
} = self;
|
||||
@@ -102,23 +132,27 @@ impl Session {
|
||||
|
||||
let reader_abort = reader.abort_handle();
|
||||
let writer_abort = writer.abort_handle();
|
||||
let path_abort = path_monitor.abort_handle();
|
||||
let joined = tokio::time::timeout(STOP_GRACE, async move {
|
||||
let _ = reader.await;
|
||||
let _ = writer.await;
|
||||
let _ = path_monitor.await;
|
||||
})
|
||||
.await;
|
||||
if joined.is_err() {
|
||||
tracing::debug!("session tasks did not wind down in time; aborting them");
|
||||
reader_abort.abort();
|
||||
writer_abort.abort();
|
||||
path_abort.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// Aborts both tasks without waiting. Used on replacement.
|
||||
/// Aborts all tasks without waiting. Used on replacement.
|
||||
pub(crate) fn abort(&self) {
|
||||
self.shutdown.trigger();
|
||||
self.reader.abort();
|
||||
self.writer.abort();
|
||||
self.path_monitor.abort();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +188,52 @@ pub(crate) fn spawn(
|
||||
parent_shutdown.clone(),
|
||||
));
|
||||
|
||||
let path_conn = conn.clone();
|
||||
let path_shutdown = shutdown.clone();
|
||||
let path_parent = parent_shutdown.clone();
|
||||
let path_monitor = tokio::spawn(async move {
|
||||
use tokio_stream::StreamExt;
|
||||
let mut events = path_conn.path_events();
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = path_shutdown.wait() => break,
|
||||
_ = path_parent.wait() => break,
|
||||
ev = events.next() => {
|
||||
match ev {
|
||||
Some(iroh::endpoint::PathEvent::Selected { remote_addr, local_addr, .. }) => {
|
||||
tracing::debug!(
|
||||
peer = %peer.fmt_short(),
|
||||
remote = %remote_addr,
|
||||
local = ?local_addr,
|
||||
"Connection path selected (direct / relay / hole punch switch)"
|
||||
);
|
||||
}
|
||||
Some(iroh::endpoint::PathEvent::Opened { remote_addr, .. }) => {
|
||||
tracing::debug!(
|
||||
peer = %peer.fmt_short(),
|
||||
remote = %remote_addr,
|
||||
"Network path opened to peer"
|
||||
);
|
||||
}
|
||||
Some(iroh::endpoint::PathEvent::Closed { remote_addr, .. }) => {
|
||||
tracing::debug!(
|
||||
peer = %peer.fmt_short(),
|
||||
remote = %remote_addr,
|
||||
"Network path closed for peer"
|
||||
);
|
||||
}
|
||||
Some(iroh::endpoint::PathEvent::Lagged { missed, .. }) => {
|
||||
tracing::trace!(peer = %peer.fmt_short(), missed, "Path events lagged");
|
||||
}
|
||||
Some(_) => {}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let reader = tokio::spawn(reader_task(
|
||||
id,
|
||||
network_id,
|
||||
@@ -172,21 +252,30 @@ pub(crate) fn spawn(
|
||||
established: Instant::now(),
|
||||
conn,
|
||||
outbound: outbound_tx,
|
||||
state_sent: 0,
|
||||
introductions_sent: 0,
|
||||
reach_sent: None,
|
||||
hostname: None,
|
||||
agent_version: None,
|
||||
uses_our_exit: None,
|
||||
notified_exit_use: None,
|
||||
capabilities: Vec::new(),
|
||||
broadcast: false,
|
||||
exit_node: false,
|
||||
messages_sent: 0,
|
||||
messages_received: 0,
|
||||
bytes_sent: 0,
|
||||
bytes_received: 0,
|
||||
reader,
|
||||
writer,
|
||||
path_monitor,
|
||||
shutdown,
|
||||
}
|
||||
}
|
||||
|
||||
async fn writer_task(
|
||||
mut send: SendStream,
|
||||
mut outbound: mpsc::Receiver<Vec<u8>>,
|
||||
mut outbound: mpsc::Receiver<zeroize::Zeroizing<Vec<u8>>>,
|
||||
limits: Arc<Limits>,
|
||||
shutdown: Shutdown,
|
||||
parent: Shutdown,
|
||||
@@ -273,6 +362,7 @@ async fn reader_task(
|
||||
}
|
||||
};
|
||||
|
||||
let payload = zeroize::Zeroizing::new(payload);
|
||||
let bytes = payload.len();
|
||||
let envelope: Envelope = match decode(&payload) {
|
||||
Ok(envelope) => envelope,
|
||||
@@ -51,3 +51,25 @@ impl Shutdown {
|
||||
// The sender is gone, which for our purposes means "stop".
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn waiting_resolves_once_triggered_and_stays_resolved() {
|
||||
let shutdown = Shutdown::new();
|
||||
assert!(!shutdown.is_triggered());
|
||||
let waiter = shutdown.clone();
|
||||
let waiting = tokio::spawn(async move { waiter.wait().await });
|
||||
shutdown.trigger();
|
||||
waiting.await.unwrap();
|
||||
assert!(shutdown.is_triggered());
|
||||
// Triggering twice is not an error, and a token cloned afterwards
|
||||
// sees the trigger that already happened.
|
||||
shutdown.trigger();
|
||||
shutdown.clone().wait().await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,620 @@
|
||||
//! Local ownership of one bounded throughput diagnostic. Control carries
|
||||
//! negotiation and receiver feedback. Every data packet uses the current cipher and carrier.
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, Weak};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use bytes::Bytes;
|
||||
use iroh::EndpointId;
|
||||
use tsunagi_speedtest as wire;
|
||||
|
||||
use super::{Agent, DataPath, Inner, PeerStatus};
|
||||
use crate::dataplane::PluginCapability;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::NetworkId;
|
||||
use crate::ipc::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
|
||||
use crate::overlay::router::DiagnosticPeer;
|
||||
use crate::proto::message::{ControlMessage, TransportPayload};
|
||||
|
||||
type Key = (NetworkId, EndpointId);
|
||||
|
||||
/// A batch can spend at most this many IPv4 bytes in *each* direction.
|
||||
/// Every remaining peer gets an equal reservation even when earlier probes are lost.
|
||||
const BATCH_BYTES: u32 = 128 * 1024 * 1024;
|
||||
const METERED_BATCH_BYTES: u32 = 16 * 1024 * 1024;
|
||||
|
||||
pub(super) fn capability() -> PluginCapability {
|
||||
PluginCapability {
|
||||
protocol: wire::PROTOCOL.into(),
|
||||
version: wire::VERSION,
|
||||
enabled: true,
|
||||
data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn supported(caps: &[PluginCapability]) -> bool {
|
||||
caps.iter()
|
||||
.any(|c| c.enabled && c.protocol == wire::PROTOCOL && c.version == wire::VERSION)
|
||||
}
|
||||
|
||||
fn envelope(message: &wire::Control) -> Option<ControlMessage> {
|
||||
Some(ControlMessage::Transport {
|
||||
protocol: wire::PROTOCOL.into(),
|
||||
payload: TransportPayload::new(message.encode().ok()?),
|
||||
})
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
}
|
||||
|
||||
struct Channel {
|
||||
key: Key,
|
||||
id: u64,
|
||||
limit: u32,
|
||||
addresses: DiagnosticPeer,
|
||||
handle: wire::Handle,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
generation: u64,
|
||||
network: NetworkId,
|
||||
batch: Option<SpeedBatchReport>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Jobs {
|
||||
job: Option<Job>,
|
||||
history: BTreeMap<Key, SpeedPeerReport>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SpeedTests {
|
||||
// Admission, completion and cancellation serialize here. Decrypted packets
|
||||
// only read the active channel and its receiver counter.
|
||||
jobs: Mutex<Jobs>,
|
||||
active: ArcSwapOption<Channel>,
|
||||
metered: AtomicBool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for SpeedTests {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SpeedTests").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl SpeedTests {
|
||||
fn lock(&self) -> MutexGuard<'_, Jobs> {
|
||||
self.jobs.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn clear_channel(&self, key: Key, id: u64) {
|
||||
// Called with the jobs lock held so an old task cannot clear its successor.
|
||||
if self
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.key == key && c.id == id)
|
||||
{
|
||||
self.active.store(None);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn report(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peers: &[PeerStatus],
|
||||
enabled: bool,
|
||||
) -> SpeedReport {
|
||||
let jobs = self.lock();
|
||||
SpeedReport {
|
||||
batch: jobs
|
||||
.job
|
||||
.as_ref()
|
||||
.filter(|j| j.network == network)
|
||||
.and_then(|j| j.batch),
|
||||
peers: jobs
|
||||
.history
|
||||
.iter()
|
||||
.filter(|((net, _), _)| *net == network)
|
||||
.map(|((_, peer), report)| (peer.to_string(), report.clone()))
|
||||
.collect(),
|
||||
capable: peers
|
||||
.iter()
|
||||
.filter(|p| enabled && p.has_confirmed_data_path() && supported(&p.capabilities))
|
||||
.map(|p| p.endpoint_id.to_string())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn disconnected(&self, network: NetworkId, peer: EndpointId) {
|
||||
if let Some(c) = self
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.key == (network, peer))
|
||||
{
|
||||
c.handle.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_locked(&self, jobs: &mut Jobs, network: NetworkId) {
|
||||
if let Some(c) = self.active.load().as_ref().filter(|c| c.key.0 == network) {
|
||||
c.handle.cancel();
|
||||
}
|
||||
if jobs.job.as_ref().is_some_and(|job| job.network == network) {
|
||||
jobs.job = None;
|
||||
for ((net, _), report) in &mut jobs.history {
|
||||
if *net == network
|
||||
&& matches!(
|
||||
report.phase,
|
||||
SpeedPhase::Queued
|
||||
| SpeedPhase::Preparing
|
||||
| SpeedPhase::Download
|
||||
| SpeedPhase::Upload
|
||||
)
|
||||
{
|
||||
match report.phase {
|
||||
SpeedPhase::Download => report.down = None,
|
||||
SpeedPhase::Upload => report.up = None,
|
||||
_ => {}
|
||||
}
|
||||
report.phase = SpeedPhase::Cancelled;
|
||||
report.measured_at_unix_secs = now();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn remove_network(&self, network: NetworkId) {
|
||||
let mut jobs = self.lock();
|
||||
self.cancel_locked(&mut jobs, network);
|
||||
jobs.history.retain(|(net, _), _| *net != network);
|
||||
}
|
||||
|
||||
pub(super) fn shutdown(&self) {
|
||||
let mut jobs = self.lock();
|
||||
jobs.job = None;
|
||||
if let Some(channel) = self.active.swap(None) {
|
||||
channel.handle.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognized probe frames never go to a host socket. Admission is stricter
|
||||
/// than exit traffic: both addresses must be the current signed overlay pair.
|
||||
pub(super) fn receive_packet(
|
||||
inner: &Inner,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
packet: &[u8],
|
||||
) -> bool {
|
||||
if !wire::is_test_packet(packet) {
|
||||
return false;
|
||||
}
|
||||
if let Some(channel) = inner.speed.active.load().as_ref()
|
||||
&& channel.key == (network, peer)
|
||||
&& let Some(data) = wire::decode_packet(packet)
|
||||
&& data.id == channel.id
|
||||
&& (data.destination, data.source) == (channel.addresses.local, channel.addresses.remote)
|
||||
&& channel.addresses.is_current(&inner.routes)
|
||||
{
|
||||
inner
|
||||
.routes
|
||||
.traffic
|
||||
.packet(network, peer, crate::traffic::Direction::Rx, packet, || {
|
||||
crate::traffic::Role::SpeedTest
|
||||
})
|
||||
.record();
|
||||
channel.handle.data(data);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn config(
|
||||
inner: &Inner,
|
||||
key: Key,
|
||||
id: u64,
|
||||
bytes: u32,
|
||||
rtt: Duration,
|
||||
) -> Option<(wire::Config, DiagnosticPeer)> {
|
||||
let addresses = inner.routes.diagnostic_peer(key.0, key.1)?;
|
||||
let ceiling = if inner.speed.metered.load(Ordering::Relaxed) {
|
||||
wire::METERED_BYTES
|
||||
} else {
|
||||
wire::NORMAL_BYTES
|
||||
};
|
||||
let cfg = wire::Config {
|
||||
id,
|
||||
local: addresses.local,
|
||||
remote: addresses.remote,
|
||||
mtu: u16::try_from(inner.config.interface_mtu).unwrap_or(u16::MAX),
|
||||
byte_limit: bytes.min(ceiling),
|
||||
rtt,
|
||||
};
|
||||
Some((cfg, addresses))
|
||||
}
|
||||
|
||||
pub(super) fn receive_control(
|
||||
inner: &Arc<Inner>,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
message: wire::Control,
|
||||
rtt: impl FnOnce() -> Option<Duration>,
|
||||
) -> Option<ControlMessage> {
|
||||
let key = (network, peer);
|
||||
let id = message.id();
|
||||
if let wire::Control::Start(request) = message {
|
||||
let jobs = inner.speed.lock();
|
||||
if inner.shutdown.is_triggered()
|
||||
|| jobs.job.is_some()
|
||||
|| inner.speed.active.load().is_some()
|
||||
{
|
||||
return envelope(&wire::Control::Busy { id });
|
||||
}
|
||||
let Some((cfg, addresses)) =
|
||||
rtt().and_then(|rtt| config(inner, key, id, request.byte_limit, rtt))
|
||||
else {
|
||||
return envelope(&wire::Control::Cancel { id });
|
||||
};
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::respond(cfg, request);
|
||||
inner.speed.active.store(Some(Arc::new(Channel {
|
||||
key,
|
||||
id,
|
||||
limit,
|
||||
addresses,
|
||||
handle,
|
||||
})));
|
||||
drop(jobs);
|
||||
let io = TestIo::new(inner, key, None);
|
||||
tokio::spawn(async move {
|
||||
let owner = io.inner.clone();
|
||||
session.run(io).await;
|
||||
if let Some(inner) = owner.upgrade() {
|
||||
let _guard = inner.speed.lock();
|
||||
inner.speed.clear_channel(key, id);
|
||||
}
|
||||
});
|
||||
} else if let Some(c) = inner
|
||||
.speed
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.key == key && c.id == id)
|
||||
{
|
||||
c.handle.control(message);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
struct TestIo {
|
||||
inner: Weak<Inner>,
|
||||
key: Key,
|
||||
generation: Option<u64>,
|
||||
started: Instant,
|
||||
}
|
||||
|
||||
impl TestIo {
|
||||
fn new(inner: &Arc<Inner>, key: Key, generation: Option<u64>) -> Self {
|
||||
Self {
|
||||
inner: Arc::downgrade(inner),
|
||||
key,
|
||||
generation,
|
||||
started: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl wire::Io for TestIo {
|
||||
async fn control(&self, message: wire::Control) -> bool {
|
||||
let (Some(inner), Some(message)) = (self.inner.upgrade(), envelope(&message)) else {
|
||||
return false;
|
||||
};
|
||||
Agent { inner }
|
||||
.send(self.key.0, self.key.1, message)
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
self.inner.upgrade().is_some_and(|inner| {
|
||||
let observation = inner.routes.traffic.packet(
|
||||
self.key.0,
|
||||
self.key.1,
|
||||
crate::traffic::Direction::Tx,
|
||||
&packet,
|
||||
|| crate::traffic::Role::SpeedTest,
|
||||
);
|
||||
let sent = inner
|
||||
.config
|
||||
.tunnel
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.carry(self.key.0, self.key.1, packet));
|
||||
if sent {
|
||||
observation.record();
|
||||
}
|
||||
sent
|
||||
})
|
||||
}
|
||||
|
||||
fn progress(&self, update: wire::Progress) {
|
||||
if !matches!(
|
||||
update.state,
|
||||
wire::State::Starting | wire::State::Download | wire::State::Upload
|
||||
) {
|
||||
return; // Publish terminal results together with releasing the slot.
|
||||
}
|
||||
if let Some(generation) = self.generation
|
||||
&& let Some(inner) = self.inner.upgrade()
|
||||
{
|
||||
let mut jobs = inner.speed.lock();
|
||||
if jobs
|
||||
.job
|
||||
.as_ref()
|
||||
.is_some_and(|j| j.generation == generation)
|
||||
&& let Some(report) = jobs.history.get_mut(&self.key)
|
||||
{
|
||||
update_report(report, update, self.started);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_report(report: &mut SpeedPeerReport, progress: wire::Progress, started: Instant) {
|
||||
let live = matches!(progress.state, wire::State::Download | wire::State::Upload);
|
||||
let rate = |reading: wire::Reading| {
|
||||
reading
|
||||
.bps
|
||||
.filter(|_| match reading.quality {
|
||||
wire::Quality::Measured | wire::Quality::AtLeast => true,
|
||||
wire::Quality::Measuring => live,
|
||||
wire::Quality::Insufficient => false,
|
||||
})
|
||||
.map(|bps| SpeedRate {
|
||||
bps,
|
||||
lower_bound: reading.quality == wire::Quality::AtLeast,
|
||||
})
|
||||
};
|
||||
report.down = rate(progress.down);
|
||||
report.up = rate(progress.up);
|
||||
report.bytes = u64::from(progress.down.bytes) + u64::from(progress.up.bytes);
|
||||
report.elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
report.measured_at_unix_secs = now();
|
||||
report.phase = match progress.state {
|
||||
wire::State::Starting => SpeedPhase::Preparing,
|
||||
wire::State::Download => SpeedPhase::Download,
|
||||
wire::State::Upload => SpeedPhase::Upload,
|
||||
wire::State::Complete if report.down.is_some() || report.up.is_some() => SpeedPhase::Done,
|
||||
wire::State::Complete => SpeedPhase::Failed("Insufficient data for a reliable rate".into()),
|
||||
wire::State::Busy => SpeedPhase::Failed("Peer is already running a speed test".into()),
|
||||
wire::State::TimedOut => {
|
||||
SpeedPhase::Failed("Peer did not finish the speed test in time".into())
|
||||
}
|
||||
wire::State::Cancelled => SpeedPhase::Cancelled,
|
||||
wire::State::Failed => {
|
||||
SpeedPhase::Failed("The data path could not complete the speed test".into())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn describe_path(peer: &PeerStatus) -> Option<String> {
|
||||
match &peer.data_path {
|
||||
DataPath::None => None,
|
||||
DataPath::Direct { transport } => Some(match &peer.data_transport_detail {
|
||||
Some(detail) => format!("{transport} · {detail}"),
|
||||
None => transport.clone(),
|
||||
}),
|
||||
DataPath::Relayed { hops, via } => Some(format!("{hops} hops via {}", via.fmt_short())),
|
||||
}
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
/// Runs one peer diagnostic, or sequentially tests the capable exit nodes in the network.
|
||||
pub async fn start_speed_test(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: Option<EndpointId>,
|
||||
metered: bool,
|
||||
) -> Result<()> {
|
||||
let status = self.network_status(network).await?;
|
||||
let targets: Vec<_> = status
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
peer.map_or(p.exit_node, |selected| p.endpoint_id == selected)
|
||||
&& status.speed.capable.contains(&p.endpoint_id.to_string())
|
||||
})
|
||||
.map(|p| p.endpoint_id)
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return Err(Error::SpeedTest(
|
||||
if let Some(target) = peer {
|
||||
if status
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.endpoint_id == target && supported(&p.capabilities))
|
||||
{
|
||||
"No confirmed data path to this peer"
|
||||
} else {
|
||||
"Peer is offline or does not support this speed-test version"
|
||||
}
|
||||
} else {
|
||||
"No compatible exit nodes with a confirmed data path in this network"
|
||||
}
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let cap = self.inner.limits.max_speed_results;
|
||||
if targets.len() > cap {
|
||||
return Err(Error::SpeedTest("Too many peers for one test batch".into()));
|
||||
}
|
||||
let generation = rand::random();
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
if self.inner.shutdown.is_triggered() {
|
||||
return Err(Error::Stopped);
|
||||
}
|
||||
if jobs.job.is_some() || self.inner.speed.active.load().is_some() {
|
||||
return Err(Error::SpeedTest(
|
||||
"Another speed test is already running".into(),
|
||||
));
|
||||
}
|
||||
// Make room before inserting the queue, preserving results of other networks when possible.
|
||||
for target in &targets {
|
||||
jobs.history.remove(&(network, *target));
|
||||
}
|
||||
while jobs.history.len() + targets.len() > cap {
|
||||
let Some(oldest) = jobs
|
||||
.history
|
||||
.iter()
|
||||
.min_by_key(|(_, r)| r.measured_at_unix_secs)
|
||||
.map(|(k, _)| *k)
|
||||
else {
|
||||
break;
|
||||
};
|
||||
jobs.history.remove(&oldest);
|
||||
}
|
||||
let count = targets.len() as u32;
|
||||
jobs.job = Some(Job {
|
||||
generation,
|
||||
network,
|
||||
batch: peer.is_none().then_some(SpeedBatchReport {
|
||||
done: 0,
|
||||
total: count,
|
||||
}),
|
||||
});
|
||||
for target in &targets {
|
||||
jobs.history.insert(
|
||||
(network, *target),
|
||||
SpeedPeerReport {
|
||||
measured_at_unix_secs: now(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let owner = Arc::downgrade(&self.inner);
|
||||
let metered = metered || self.inner.speed.metered.load(Ordering::Relaxed);
|
||||
let per_peer = if metered {
|
||||
wire::METERED_BYTES
|
||||
} else {
|
||||
wire::NORMAL_BYTES
|
||||
};
|
||||
let limit = if peer.is_none() {
|
||||
per_peer.min(
|
||||
if metered {
|
||||
METERED_BATCH_BYTES
|
||||
} else {
|
||||
BATCH_BYTES
|
||||
} / count,
|
||||
)
|
||||
} else {
|
||||
per_peer
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
for (index, target) in targets.into_iter().enumerate() {
|
||||
let key = (network, target);
|
||||
let Some(inner) = owner.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let result = run_outgoing(&inner, key, generation, limit, peer.is_none()).await;
|
||||
let mut jobs = inner.speed.lock();
|
||||
if let Some((id, _, _)) = &result {
|
||||
inner.speed.clear_channel(key, *id);
|
||||
}
|
||||
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
|
||||
return;
|
||||
}
|
||||
if let Some(report) = jobs.history.get_mut(&key) {
|
||||
match result {
|
||||
Some((_, update, started)) => update_report(report, update, started),
|
||||
None => {
|
||||
report.phase = SpeedPhase::Failed(
|
||||
"Peer no longer has a confirmed data path or is no longer eligible"
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if index + 1 == count as usize {
|
||||
jobs.job = None;
|
||||
} else if let Some(batch) = jobs.job.as_mut().and_then(|j| j.batch.as_mut()) {
|
||||
batch.done += 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cancels the current test and any queued peers in this network.
|
||||
pub fn stop_speed_test(&self, network: NetworkId) {
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
self.inner.speed.cancel_locked(&mut jobs, network);
|
||||
}
|
||||
|
||||
/// Applies the host's actual metered-link policy to incoming and outgoing measurements.
|
||||
pub fn set_speed_test_metered(&self, metered: bool) {
|
||||
if self.inner.speed.metered.swap(metered, Ordering::Relaxed) || !metered {
|
||||
return;
|
||||
}
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
if let Some(network) = jobs.job.as_ref().map(|j| j.network) {
|
||||
self.inner.speed.cancel_locked(&mut jobs, network);
|
||||
} else if let Some(c) = self
|
||||
.inner
|
||||
.speed
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.limit > wire::METERED_BYTES)
|
||||
{
|
||||
c.handle.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_outgoing(
|
||||
inner: &Arc<Inner>,
|
||||
key: Key,
|
||||
generation: u64,
|
||||
limit: u32,
|
||||
exits_only: bool,
|
||||
) -> Option<(u64, wire::Progress, Instant)> {
|
||||
let agent = Agent {
|
||||
inner: Arc::clone(inner),
|
||||
};
|
||||
let status = agent.network_status(key.0).await.ok()?;
|
||||
let peer = status.peers.iter().find(|p| {
|
||||
p.endpoint_id == key.1
|
||||
&& (!exits_only || p.exit_node)
|
||||
&& status.speed.capable.contains(&p.endpoint_id.to_string())
|
||||
})?;
|
||||
let id = rand::random();
|
||||
let (cfg, addresses) = config(inner, key, id, limit, peer.data_rtt?)?;
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::initiate(cfg);
|
||||
let io = TestIo::new(inner, key, Some(generation));
|
||||
{
|
||||
let mut jobs = inner.speed.lock();
|
||||
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
|
||||
return None;
|
||||
}
|
||||
let report = jobs.history.get_mut(&key)?;
|
||||
report.phase = SpeedPhase::Preparing;
|
||||
report.path = describe_path(peer);
|
||||
inner.speed.active.store(Some(Arc::new(Channel {
|
||||
key,
|
||||
id,
|
||||
limit,
|
||||
addresses,
|
||||
handle,
|
||||
})));
|
||||
}
|
||||
let started = io.started;
|
||||
let update = session.run(io).await;
|
||||
Some((id, update, started))
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Status snapshots.
|
||||
//!
|
||||
//! Metrics are reported at the level they actually belong to. Values that
|
||||
//! genuinely cannot be attributed to a single network — everything the iroh
|
||||
//! endpoint aggregates, for instance — stay at the endpoint level rather than
|
||||
//! being split between networks with invented precision.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use iroh::{EndpointAddr, EndpointId};
|
||||
|
||||
use crate::dataplane::PluginCapability;
|
||||
use crate::discovery::CandidateSource;
|
||||
use crate::identity::{NetworkDescriptor, NetworkId, NetworkName};
|
||||
use crate::net::{ConnectionCounters, PathAddr, PathInfo, TransportKind};
|
||||
use crate::proto::handshake::Role;
|
||||
use crate::storage::CacheOutcome;
|
||||
|
||||
/// Informational data-channel diagnostics shared by the status UI and runtime.
|
||||
pub const DATA_CONNECTING: &str = "establishing external data transport";
|
||||
/// Data transport was disabled by local policy.
|
||||
pub const DATA_DISABLED: &str = "data transports disabled locally";
|
||||
|
||||
/// Whether a configured network is running locally.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NetworkState {
|
||||
/// Configured and running.
|
||||
Active,
|
||||
/// Configured but not running.
|
||||
Inactive,
|
||||
}
|
||||
|
||||
/// An unverified candidate as seen by a network runtime.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CandidateStatus {
|
||||
/// Candidate endpoint id.
|
||||
pub endpoint_id: EndpointId,
|
||||
/// Where it came from.
|
||||
pub source: CandidateSource,
|
||||
/// Consecutive failed dial attempts since the last success.
|
||||
pub consecutive_failures: u32,
|
||||
}
|
||||
|
||||
/// The overlay interface, as the agent sees it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OverlayStatus {
|
||||
/// The interface name the operating system gave.
|
||||
pub interface: String,
|
||||
/// Whether that interface exists on the host.
|
||||
///
|
||||
/// `false` with an in-memory device: the name is real to the agent and
|
||||
/// to nothing else. Reported, because everything that would configure
|
||||
/// the operating system for this interface must not when it is this.
|
||||
pub on_host: bool,
|
||||
/// Its MTU.
|
||||
pub mtu: u32,
|
||||
/// The addresses it should be carrying.
|
||||
pub addresses: Vec<crate::overlay::Cidr>,
|
||||
/// Last error applying addresses or subnet routes on the shared interface.
|
||||
pub address_error: Option<String>,
|
||||
/// What has happened on it.
|
||||
pub counters: crate::overlay::Counters,
|
||||
/// The route and firewall allowance installed for LAN broadcast, when
|
||||
/// some network has broadcast on and the interface is on the host.
|
||||
/// `None` is "none installed", not "unknown".
|
||||
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.
|
||||
///
|
||||
/// This is the durable roster: it comes from signed records, so a member that
|
||||
/// went away last month is still here. That is what makes it possible to say
|
||||
/// "this peer is offline" rather than only "nobody is connected".
|
||||
///
|
||||
/// It is not a complete membership list, and cannot be. A member is in signed
|
||||
/// state once it has claimed something — an address, a name, or both — so a
|
||||
/// member that has joined but never published is visible only while it is
|
||||
/// connected.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MemberStatus {
|
||||
/// Current signed claim version, used to bind cleanup confirmation.
|
||||
pub record_version: u64,
|
||||
/// The member's device identity.
|
||||
pub endpoint_id: EndpointId,
|
||||
/// The IPv4 overlay address it claimed and signed for.
|
||||
pub overlay_address_v4: Option<std::net::Ipv4Addr>,
|
||||
/// The name it claimed, when it holds that name uncontested.
|
||||
///
|
||||
/// 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.
|
||||
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.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PeerStatus {
|
||||
/// The connected member has selected this gateway, or recently sent exit traffic on a legacy session.
|
||||
pub uses_our_exit: bool,
|
||||
/// This authenticated peer accepts network broadcasts.
|
||||
pub broadcast: bool,
|
||||
/// This authenticated peer offers itself as an exit node.
|
||||
pub exit_node: bool,
|
||||
/// Authenticated endpoint id.
|
||||
pub endpoint_id: EndpointId,
|
||||
/// Which side this agent played in the handshake.
|
||||
pub role: Role,
|
||||
/// Hostname the peer announced, if it has announced one yet.
|
||||
///
|
||||
/// A mutable binding, not an identity.
|
||||
pub hostname: Option<String>,
|
||||
/// Software version in the peer's latest authenticated announcement.
|
||||
pub agent_version: Option<String>,
|
||||
/// Protocols agreed with this peer: both sides have them at the same
|
||||
/// version.
|
||||
///
|
||||
/// Empty means no data plane with that peer, which leaves the control
|
||||
/// plane working — messages and state still flow.
|
||||
pub protocols: Vec<String>,
|
||||
/// Capabilities the peer announced. Payloads stay opaque.
|
||||
pub capabilities: Vec<PluginCapability>,
|
||||
/// Why no data route is available, when known.
|
||||
pub data_error: Option<String>,
|
||||
/// How long the session has been up.
|
||||
pub connected_for: Duration,
|
||||
/// Verified paths of the underlying connection.
|
||||
pub paths: Vec<PathInfo>,
|
||||
/// How the connection currently reaches the peer.
|
||||
pub transport: TransportKind,
|
||||
/// RTT of the selected path, when iroh reported one.
|
||||
pub rtt: Option<Duration>,
|
||||
/// Round trip to this peer over encrypted overlay data, including relay hops.
|
||||
/// Carrier-only agents report their selected physical link's round trip.
|
||||
pub data_rtt: Option<Duration>,
|
||||
/// The selected direct data carrier's own description of its underlying path.
|
||||
pub data_transport_detail: Option<String>,
|
||||
/// Per-connection counters.
|
||||
pub connection: ConnectionCounters,
|
||||
/// Control messages sent on this session.
|
||||
pub control_messages_sent: u64,
|
||||
/// Control messages received on this session.
|
||||
pub control_messages_received: u64,
|
||||
/// Control payload bytes queued for this session.
|
||||
pub control_bytes_sent: u64,
|
||||
/// Control payload bytes read from this session.
|
||||
pub control_bytes_received: u64,
|
||||
/// How packets reach this peer right now.
|
||||
pub data_path: DataPath,
|
||||
}
|
||||
|
||||
impl PeerStatus {
|
||||
/// A usable route with a successful data round trip to this peer.
|
||||
pub fn has_confirmed_data_path(&self) -> bool {
|
||||
!matches!(self.data_path, DataPath::None)
|
||||
&& self.data_rtt.is_some()
|
||||
&& self.data_error.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Counters scoped to one logical network.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct NetworkMetrics {
|
||||
/// Outbound dial attempts started.
|
||||
pub dial_attempts: u64,
|
||||
/// Outbound dials that failed before or during the handshake.
|
||||
pub dial_failures: u64,
|
||||
/// Handshakes rejected, in either direction.
|
||||
pub handshake_failures: u64,
|
||||
/// Sessions that reached the authenticated state.
|
||||
pub sessions_established: u64,
|
||||
/// Sessions that ended.
|
||||
pub disconnects: u64,
|
||||
/// Control messages sent in this network.
|
||||
pub control_messages_sent: u64,
|
||||
/// Control messages received in this network.
|
||||
pub control_messages_received: u64,
|
||||
/// Control bytes sent in this network, payload only.
|
||||
pub control_bytes_sent: u64,
|
||||
/// Control bytes received in this network, payload only.
|
||||
pub control_bytes_received: u64,
|
||||
/// Messages or sessions rejected for protocol violations.
|
||||
pub protocol_violations: u64,
|
||||
/// Errors reported by IP plugins. Never fatal.
|
||||
pub plugin_errors: u64,
|
||||
/// Data plane links that were established.
|
||||
pub data_links_established: u64,
|
||||
/// Attempts to open a data plane link that failed.
|
||||
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.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NetworkStatus {
|
||||
/// Available mesh throughput tests, with local progress and results.
|
||||
pub speed: crate::ipc::SpeedReport,
|
||||
/// 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.
|
||||
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,
|
||||
/// IP byte totals since this exit route was selected.
|
||||
pub exit_traffic: Option<crate::overlay::exit::ExitTraffic>,
|
||||
/// What the host rules for the exit settings are doing.
|
||||
pub exit_rules: crate::overlay::ExitRulesReport,
|
||||
/// Immutable deterministic description of the network space.
|
||||
pub descriptor: NetworkDescriptor,
|
||||
/// Network name, for convenience.
|
||||
pub name: NetworkName,
|
||||
/// Public network identifier.
|
||||
pub network_id: NetworkId,
|
||||
/// Whether the network is running locally.
|
||||
pub state: NetworkState,
|
||||
/// Authenticated sessions.
|
||||
pub peers: Vec<PeerStatus>,
|
||||
/// Unverified candidates currently known. Not peers.
|
||||
pub candidates: Vec<CandidateStatus>,
|
||||
/// Members the signed state knows about, whether connected or not.
|
||||
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.
|
||||
pub range: Option<crate::state::Ipv4Range>,
|
||||
/// The first overlapping active range; `range_conflicts` identifies all blockers.
|
||||
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.
|
||||
pub metrics: NetworkMetrics,
|
||||
/// What has gone through a peer in the middle, in both directions.
|
||||
pub relay: crate::dataplane::relay::RelayCounters,
|
||||
}
|
||||
|
||||
impl NetworkStatus {
|
||||
/// Endpoint ids of peers with an authenticated session.
|
||||
pub fn connected_peers(&self) -> Vec<EndpointId> {
|
||||
self.peers.iter().map(|peer| peer.endpoint_id).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Status of the whole agent.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AgentStatus {
|
||||
/// This device's persistent endpoint id.
|
||||
pub endpoint_id: EndpointId,
|
||||
/// Hostname announced to peers.
|
||||
pub hostname: String,
|
||||
/// Sockets actually bound.
|
||||
pub bound_sockets: Vec<std::net::SocketAddr>,
|
||||
/// Addresses iroh believes this endpoint has. Observed, not verified.
|
||||
pub observed_addrs: Vec<PathAddr>,
|
||||
/// The dialable address of this endpoint, as iroh currently reports it.
|
||||
pub endpoint_addr: EndpointAddr,
|
||||
/// What happened to the disposable cache at startup.
|
||||
pub cache_outcome: CacheOutcome,
|
||||
/// Whether the cache is currently usable.
|
||||
pub cache_healthy: bool,
|
||||
/// Per-network status, including configured but inactive networks.
|
||||
pub networks: Vec<NetworkStatus>,
|
||||
}
|
||||
|
||||
impl AgentStatus {
|
||||
/// Looks up one network's status.
|
||||
pub fn network(&self, network_id: &NetworkId) -> Option<&NetworkStatus> {
|
||||
self.networks
|
||||
.iter()
|
||||
.find(|status| &status.network_id == network_id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
//! Library configuration.
|
||||
//!
|
||||
//! Everything the agent needs is passed in explicitly. The library reads no
|
||||
//! environment variables, installs no global state and picks no default
|
||||
//! directories behind the caller's back — [`StoragePaths::user_default`] exists
|
||||
//! but must be called on purpose.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::dataplane::SharedPlugin;
|
||||
use crate::discovery::{MainlineDiscovery, NetworkDiscovery};
|
||||
use crate::error::Result;
|
||||
|
||||
/// Qualifier/organisation/application triple used for platform directories.
|
||||
///
|
||||
/// Unused on macOS, where the default paths are fixed system locations rather
|
||||
/// than per-user directories derived from this.
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))]
|
||||
const APP_NAME: &str = "tsunagi";
|
||||
|
||||
/// Maximum length of the optional software release label in a peer announcement.
|
||||
pub const MAX_AGENT_VERSION_LEN: usize = 64;
|
||||
|
||||
/// Rendezvous slots per network; this bounds a discovery sample, not membership.
|
||||
pub const DHT_SLOTS: u8 = 16;
|
||||
/// BEP44 permits 1000 bencoded bytes; a 996-byte string has a four-byte prefix.
|
||||
pub const DHT_MAX_VALUE: usize = 996;
|
||||
/// Maximum direct addresses in one rendezvous record.
|
||||
pub const DHT_MAX_ADDRS: usize = 8;
|
||||
/// Maximum relay URL bytes in a rendezvous record.
|
||||
pub const DHT_MAX_RELAY_LEN: usize = 512;
|
||||
/// Application freshness, independent of storage nodes' own expiration.
|
||||
pub const DHT_RECORD_TTL: Duration = Duration::from_secs(900);
|
||||
/// Clock skew tolerated when reading a recently published record.
|
||||
pub const DHT_CLOCK_SKEW: Duration = Duration::from_secs(120);
|
||||
|
||||
/// Maximum reassembled data-transport payload, independent of the path MTU.
|
||||
pub const MAX_DATA_DATAGRAM: usize = 64 * 1024;
|
||||
/// Maximum incomplete datagrams held by one authenticated data link.
|
||||
pub const MAX_DATA_ASSEMBLIES: usize = 64;
|
||||
/// Maximum allocated payload bytes for incomplete datagrams on one data link.
|
||||
pub const MAX_DATA_REASSEMBLY_BYTES: usize = 256 * 1024;
|
||||
/// Maximum fragments of one logical datagram, including after a path MTU change.
|
||||
pub const MAX_DATA_FRAGMENTS: usize = 128;
|
||||
/// Time allowed to assemble a datagram; loss never stalls later datagrams.
|
||||
pub const DATA_REASSEMBLY_TTL: Duration = Duration::from_secs(5);
|
||||
/// Completed or discarded packet IDs retained to ignore late duplicate fragments.
|
||||
pub const DATA_RECENT_IDS: usize = 128;
|
||||
|
||||
/// Simultaneous TCP, UDP and ICMP work on a userspace exit.
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
pub(crate) const EXIT_FORWARD_FLOWS: usize = 256;
|
||||
/// Bounded packet queue shared by userspace exit clients.
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
pub(crate) const EXIT_FORWARD_QUEUE: usize = 64;
|
||||
/// Concurrent fragmented datagrams accepted by a userspace exit.
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
pub(crate) const EXIT_FORWARD_FRAGMENTS: usize = 32;
|
||||
|
||||
/// Where the two stores live.
|
||||
///
|
||||
/// The mandatory state and the disposable cache are separate both logically and
|
||||
/// physically, so that the cache can be deleted at any time without touching
|
||||
/// identity or network configuration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StoragePaths {
|
||||
/// Directory holding `state.sqlite` and the ownership lock.
|
||||
pub state_dir: PathBuf,
|
||||
/// Directory holding `cache.sqlite`.
|
||||
pub cache_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl StoragePaths {
|
||||
/// Uses explicit directories. Tests always use temporary directories.
|
||||
pub fn new(state_dir: impl Into<PathBuf>, cache_dir: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
state_dir: state_dir.into(),
|
||||
cache_dir: cache_dir.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts both stores under one root, in `state/` and `cache/` subdirectories.
|
||||
pub fn under(root: impl AsRef<Path>) -> Self {
|
||||
let root = root.as_ref();
|
||||
Self {
|
||||
state_dir: root.join("state"),
|
||||
cache_dir: root.join("cache"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The default platform directories.
|
||||
///
|
||||
/// Per user on Linux and Windows. On macOS the agent runs as a root
|
||||
/// LaunchDaemon (creating a utun interface needs root, and `$HOME` under
|
||||
/// `sudo` points at the wrong place), so the stores live in the system
|
||||
/// locations instead — `/var/db/tsunagi` for the mandatory state and a
|
||||
/// disposable cache beside it. A caller that wants somewhere else passes
|
||||
/// explicit paths to [`StoragePaths::new`] or [`StoragePaths::under`].
|
||||
pub fn user_default() -> Result<Self> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
Ok(Self {
|
||||
state_dir: PathBuf::from("/var/db/tsunagi"),
|
||||
cache_dir: PathBuf::from("/var/db/tsunagi/cache"),
|
||||
})
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let dirs = directories::ProjectDirs::from("", "", APP_NAME).ok_or_else(|| {
|
||||
crate::error::Error::Storage(
|
||||
"no valid home directory for platform config paths".into(),
|
||||
)
|
||||
})?;
|
||||
Ok(Self {
|
||||
state_dir: dirs.data_dir().to_path_buf(),
|
||||
cache_dir: dirs.cache_dir().to_path_buf(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Path of the mandatory state database.
|
||||
pub fn state_db(&self) -> PathBuf {
|
||||
self.state_dir.join("state.sqlite")
|
||||
}
|
||||
|
||||
/// Path of the disposable cache database.
|
||||
pub fn cache_db(&self) -> PathBuf {
|
||||
self.cache_dir.join("cache.sqlite")
|
||||
}
|
||||
|
||||
/// Path of the ownership lock file.
|
||||
pub fn lock_file(&self) -> PathBuf {
|
||||
self.state_dir.join("state.lock")
|
||||
}
|
||||
}
|
||||
|
||||
/// How the iroh endpoint is allowed to reach the outside world.
|
||||
///
|
||||
/// The default is [`TransportPolicy::LocalOnly`] so that a plain
|
||||
/// `AgentConfig::new(...)` never reaches the internet by accident. Callers that
|
||||
/// want public connectivity must opt in.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum TransportPolicy {
|
||||
/// No relays, no address lookup service, no port mapping.
|
||||
///
|
||||
/// Suitable for tests and for fully local deployments.
|
||||
#[default]
|
||||
LocalOnly,
|
||||
/// Public address lookup, but no relays.
|
||||
///
|
||||
/// Enables iroh's DNS/pkarr address lookup against the public service run
|
||||
/// by Number 0 (the company behind iroh) at `dns.iroh.link`. This endpoint
|
||||
/// publishes a signed record of its own addresses there, so peers can dial
|
||||
/// it by endpoint id alone.
|
||||
DirectOnly,
|
||||
/// iroh's standard behaviour: public address lookup plus public relays.
|
||||
///
|
||||
/// Maps to iroh's own `presets::N0`. As well as the address lookup above,
|
||||
/// it uses Number 0's public relay servers as a fallback when a direct
|
||||
/// path cannot be hole punched. They are fine for development and carry no
|
||||
/// availability guarantee.
|
||||
N0Defaults,
|
||||
}
|
||||
|
||||
/// Bounds applied to everything that comes off the network.
|
||||
///
|
||||
/// Each of these is enforced before memory is allocated for the corresponding
|
||||
/// object where that is possible (notably [`Limits::max_frame_len`]).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
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.
|
||||
pub max_frame_len: usize,
|
||||
/// Largest accepted hostname, in bytes.
|
||||
pub max_hostname_len: usize,
|
||||
/// Largest number of plugin capabilities in one announcement.
|
||||
pub max_capabilities: usize,
|
||||
/// Largest opaque plugin payload, in bytes.
|
||||
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.
|
||||
pub max_echo_payload_len: usize,
|
||||
/// Largest accepted free-text reason string, in bytes.
|
||||
pub max_reason_len: usize,
|
||||
/// Largest number of signed records accepted in one snapshot.
|
||||
pub max_state_records: usize,
|
||||
/// Maximum durable retirement markers retained per network.
|
||||
pub max_retirements: usize,
|
||||
/// Deadline for the whole handshake.
|
||||
pub handshake_timeout: Duration,
|
||||
/// Deadline for one outbound dial attempt.
|
||||
pub dial_timeout: Duration,
|
||||
/// Deadline for writing one control frame.
|
||||
///
|
||||
/// Liveness of an established session is delegated to QUIC: iroh configures
|
||||
/// keep-alives and an idle timeout, so a dead peer surfaces as a read error
|
||||
/// rather than needing a protocol-level heartbeat here.
|
||||
pub write_timeout: Duration,
|
||||
/// Maximum simultaneous outbound dials per network.
|
||||
pub max_concurrent_dials: usize,
|
||||
/// Maximum unverified discovery candidates retained per network.
|
||||
pub max_discovery_candidates: usize,
|
||||
/// Maximum simultaneous authenticated sessions per network.
|
||||
pub max_sessions_per_network: usize,
|
||||
/// Maximum per-peer speed results or queued tests retained by the agent.
|
||||
pub max_speed_results: usize,
|
||||
/// Maximum simultaneous inbound connections being handshaken.
|
||||
pub max_inbound_handshakes: usize,
|
||||
/// Capacity of a session's outbound queue, providing backpressure.
|
||||
pub session_send_queue: usize,
|
||||
/// Capacity of the event broadcast channel.
|
||||
pub event_buffer: usize,
|
||||
/// Maximum address hints kept per peer in the cache.
|
||||
pub max_hints_per_peer: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> 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_hostname_len: 255,
|
||||
max_capabilities: 16,
|
||||
max_transport_payload_len: 4096,
|
||||
max_capability_data_len: 4 * 1024,
|
||||
max_echo_payload_len: 4 * 1024,
|
||||
max_reason_len: 256,
|
||||
max_state_records: crate::state::MAX_RECORDS_PER_MESSAGE,
|
||||
max_retirements: 1024,
|
||||
handshake_timeout: Duration::from_secs(10),
|
||||
dial_timeout: Duration::from_secs(10),
|
||||
write_timeout: Duration::from_secs(30),
|
||||
max_concurrent_dials: 8,
|
||||
max_discovery_candidates: 16,
|
||||
max_sessions_per_network: 64,
|
||||
max_speed_results: 256,
|
||||
max_inbound_handshakes: 32,
|
||||
session_send_queue: 64,
|
||||
event_buffer: 512,
|
||||
max_hints_per_peer: 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded exponential backoff with jitter for reconnect attempts.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ReconnectPolicy {
|
||||
/// Delay before the first retry.
|
||||
pub initial_delay: Duration,
|
||||
/// Upper bound on the delay.
|
||||
pub max_delay: Duration,
|
||||
/// Multiplier applied after each failed attempt.
|
||||
pub factor: f64,
|
||||
/// Fraction of the delay applied as random jitter, in `0.0..=1.0`.
|
||||
pub jitter: f64,
|
||||
/// Give up on a peer after this many consecutive failures until it is seen
|
||||
/// again by discovery. `None` means never give up while the network is up.
|
||||
pub max_consecutive_failures: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for ReconnectPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
initial_delay: Duration::from_millis(250),
|
||||
max_delay: Duration::from_secs(30),
|
||||
factor: 2.0,
|
||||
jitter: 0.3,
|
||||
max_consecutive_failures: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ReconnectPolicy {
|
||||
/// Delay to wait before retry number `attempt` (1-based), with jitter.
|
||||
pub(crate) fn delay_for(&self, attempt: u32) -> Duration {
|
||||
let exp = self.factor.powi(attempt.saturating_sub(1).min(32) as i32);
|
||||
let base = self.initial_delay.as_secs_f64() * exp;
|
||||
let capped = base.min(self.max_delay.as_secs_f64());
|
||||
let jitter = self.jitter.clamp(0.0, 1.0);
|
||||
let factor = 1.0 - jitter + jitter * 2.0 * rand::random::<f64>();
|
||||
Duration::from_secs_f64((capped * factor).max(0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Scheduling of candidate lookup and independent self-publication.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DiscoveryPolicy {
|
||||
/// Mean interval between successful self-publications (20% jitter).
|
||||
pub publish_interval: Duration,
|
||||
/// Initial delay between unsuccessful bootstrap lookups.
|
||||
pub lookup_interval: Duration,
|
||||
/// Maximum delay between bootstrap lookups.
|
||||
pub max_lookup_interval: Duration,
|
||||
/// Continuous isolation before a previously connected network searches again.
|
||||
pub reconnect_delay: Duration,
|
||||
/// Deadline for one backend operation.
|
||||
pub request_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Default for DiscoveryPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
publish_interval: Duration::from_secs(300),
|
||||
lookup_interval: Duration::from_secs(5),
|
||||
max_lookup_interval: Duration::from_secs(30),
|
||||
reconnect_delay: Duration::from_secs(60),
|
||||
request_timeout: Duration::from_secs(60),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything needed to start an [`crate::Agent`].
|
||||
#[derive(Clone)]
|
||||
pub struct AgentConfig {
|
||||
/// Where the mandatory state and the disposable cache live.
|
||||
pub paths: StoragePaths,
|
||||
/// Explicit local bind addresses. Empty means iroh's defaults.
|
||||
///
|
||||
/// Tests bind to `127.0.0.1:0` so each agent gets a dynamic port.
|
||||
pub bind_addrs: Vec<SocketAddr>,
|
||||
/// How much external connectivity machinery the endpoint may use.
|
||||
pub transport: TransportPolicy,
|
||||
/// Real QUIC transport settings for constrained-path integration tests.
|
||||
#[cfg(feature = "testing")]
|
||||
pub test_quic_transport: Option<iroh::endpoint::QuicTransportConfig>,
|
||||
/// Peers with no direct data path, for tests. See
|
||||
/// [`AgentConfig::with_unreachable_data_peers`].
|
||||
#[cfg(feature = "testing")]
|
||||
pub unreachable_data_peers: Arc<std::sync::Mutex<std::collections::HashSet<iroh::EndpointId>>>,
|
||||
/// Hostname announced to peers. `None` keeps whatever the state store holds,
|
||||
/// falling back to the OS hostname and finally to a short endpoint id.
|
||||
pub hostname: Option<String>,
|
||||
/// Additional discovery backend, composed with Mainline when it is enabled.
|
||||
pub discovery: Option<Arc<dyn NetworkDiscovery>>,
|
||||
/// Optional Mainline client, shared by this agent's networks. The CLI enables
|
||||
/// it by default except in local-only mode; library callers opt in explicitly.
|
||||
pub dht: Option<MainlineDiscovery>,
|
||||
/// Lookup, publication and recovery scheduling.
|
||||
pub discovery_policy: DiscoveryPolicy,
|
||||
/// How often each active network maintains known peers and observes address changes.
|
||||
pub discovery_interval: Duration,
|
||||
/// Bounds applied to network input.
|
||||
pub limits: Limits,
|
||||
/// Reconnect backoff policy.
|
||||
pub reconnect: ReconnectPolicy,
|
||||
/// External data carriers whose capabilities are announced and dispatched.
|
||||
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.
|
||||
pub custom_transports:
|
||||
std::collections::HashMap<String, Arc<dyn crate::dataplane::PacketTransport>>,
|
||||
/// Where the overlay interface comes from, when the agent should have one.
|
||||
///
|
||||
/// One agent, one interface: it belongs here rather than to a protocol,
|
||||
/// because every protocol carries traffic for the same addresses on it.
|
||||
/// `None` means no interface — the protocols still run and their packets
|
||||
/// are discarded.
|
||||
pub tun_factory: Option<Arc<dyn crate::overlay::TunFactory>>,
|
||||
/// The name to ask the operating system for.
|
||||
pub interface_name: String,
|
||||
/// The interface MTU.
|
||||
pub interface_mtu: u32,
|
||||
/// 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
|
||||
/// participant keeps the same one across restarts. A network that has
|
||||
/// already settled on another range wins: a joining agent adopts what it
|
||||
/// finds rather than imposing this.
|
||||
pub overlay_ipv4_range: Option<crate::state::Ipv4Range>,
|
||||
}
|
||||
|
||||
impl AgentConfig {
|
||||
/// Creates a configuration with local-only transport and default limits.
|
||||
pub fn new(paths: StoragePaths) -> Self {
|
||||
Self {
|
||||
paths,
|
||||
bind_addrs: Vec::new(),
|
||||
transport: TransportPolicy::default(),
|
||||
#[cfg(feature = "testing")]
|
||||
test_quic_transport: None,
|
||||
#[cfg(feature = "testing")]
|
||||
unreachable_data_peers: Arc::new(std::sync::Mutex::new(
|
||||
std::collections::HashSet::new(),
|
||||
)),
|
||||
hostname: None,
|
||||
discovery: None,
|
||||
dht: None,
|
||||
discovery_policy: DiscoveryPolicy::default(),
|
||||
discovery_interval: Duration::from_secs(5),
|
||||
limits: Limits::default(),
|
||||
reconnect: ReconnectPolicy::default(),
|
||||
carriers: Vec::new(),
|
||||
tunnel: None,
|
||||
default_protocols: None,
|
||||
custom_transports: std::collections::HashMap::new(),
|
||||
tun_factory: None,
|
||||
interface_name: "tsun0".to_string(),
|
||||
interface_mtu: 1280,
|
||||
overlay_ipv4_auto: true,
|
||||
overlay_ipv4_range: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Binds to loopback with a dynamic port. Used by the test suite.
|
||||
pub fn with_loopback_bind(mut self) -> Self {
|
||||
self.bind_addrs = vec![
|
||||
SocketAddr::from(([127, 0, 0, 1], 0)),
|
||||
SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], 0)),
|
||||
];
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets an explicit list of bind addresses.
|
||||
pub fn with_bind_addrs(mut self, addrs: impl IntoIterator<Item = SocketAddr>) -> Self {
|
||||
self.bind_addrs = addrs.into_iter().collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// Peers this agent will not open or accept a **direct** data link with.
|
||||
///
|
||||
/// Test-only, and behind the `testing` feature so a release build has
|
||||
/// no such switch. The one arrangement that cannot be made on a single
|
||||
/// host is two agents that both reach a third and not each other,
|
||||
/// which is exactly the case a relay exists for.
|
||||
#[cfg(feature = "testing")]
|
||||
pub fn with_unreachable_data_peers(
|
||||
mut self,
|
||||
peers: Arc<std::sync::Mutex<std::collections::HashSet<iroh::EndpointId>>>,
|
||||
) -> Self {
|
||||
self.unreachable_data_peers = peers;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the transport policy.
|
||||
pub fn with_transport(mut self, transport: TransportPolicy) -> Self {
|
||||
self.transport = transport;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the discovery backend.
|
||||
pub fn with_discovery(mut self, discovery: Arc<dyn NetworkDiscovery>) -> Self {
|
||||
self.discovery = Some(discovery);
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds Mainline discovery alongside the configured candidate backend.
|
||||
pub fn with_dht(mut self, dht: MainlineDiscovery) -> Self {
|
||||
self.dht = Some(dht);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets lookup, publication and isolation recovery timing.
|
||||
pub fn with_discovery_policy(mut self, policy: DiscoveryPolicy) -> Self {
|
||||
self.discovery_policy = policy;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the known-peer maintenance and endpoint-address observation interval.
|
||||
pub fn with_discovery_interval(mut self, interval: Duration) -> Self {
|
||||
self.discovery_interval = interval;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the announced hostname.
|
||||
pub fn with_hostname(mut self, hostname: impl Into<String>) -> Self {
|
||||
self.hostname = Some(hostname.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
self.overlay_ipv4_auto = false;
|
||||
self.overlay_ipv4_range = range;
|
||||
self
|
||||
}
|
||||
|
||||
/// Registers an external data carrier.
|
||||
pub fn with_carrier(mut self, plugin: crate::dataplane::transport::SharedCarrier) -> Self {
|
||||
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
|
||||
}
|
||||
|
||||
/// Registers a custom packet transport for a specific protocol.
|
||||
pub fn with_custom_transport(
|
||||
mut self,
|
||||
protocol: impl Into<String>,
|
||||
transport: Arc<dyn crate::dataplane::PacketTransport>,
|
||||
) -> Self {
|
||||
self.custom_transports.insert(protocol.into(), transport);
|
||||
self
|
||||
}
|
||||
|
||||
/// Gives the agent an overlay interface, from this factory.
|
||||
pub fn with_interface(
|
||||
mut self,
|
||||
factory: Arc<dyn crate::overlay::TunFactory>,
|
||||
name: impl Into<String>,
|
||||
mtu: u32,
|
||||
) -> Self {
|
||||
self.tun_factory = Some(factory);
|
||||
self.interface_name = name.into();
|
||||
self.interface_mtu = mtu;
|
||||
self
|
||||
}
|
||||
|
||||
/// Replaces the limits.
|
||||
pub fn with_limits(mut self, limits: Limits) -> Self {
|
||||
self.limits = limits;
|
||||
self
|
||||
}
|
||||
|
||||
/// Replaces the reconnect policy.
|
||||
pub fn with_reconnect(mut self, reconnect: ReconnectPolicy) -> Self {
|
||||
self.reconnect = reconnect;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AgentConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AgentConfig")
|
||||
.field("paths", &self.paths)
|
||||
.field("bind_addrs", &self.bind_addrs)
|
||||
.field("transport", &self.transport)
|
||||
.field("hostname", &self.hostname)
|
||||
.field("discovery", &self.discovery.as_ref().map(|d| d.name()))
|
||||
.field("dht", &self.dht.is_some())
|
||||
.field("discovery_policy", &self.discovery_policy)
|
||||
.field("discovery_interval", &self.discovery_interval)
|
||||
.field("limits", &self.limits)
|
||||
.field("reconnect", &self.reconnect)
|
||||
.field(
|
||||
"carriers",
|
||||
&self
|
||||
.carriers
|
||||
.iter()
|
||||
.map(|p| p.protocol_id().to_string())
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
/// Maximum number of transport links a routed datagram may traverse.
|
||||
pub const ROUTING_HOP_LIMIT: u8 = 16;
|
||||
|
||||
/// Maximum distinct flows per local reader between polls (fits one IPC frame).
|
||||
pub(crate) const MAX_INTERVAL_FLOWS: usize = 2048;
|
||||
/// Independent local monitor windows per agent.
|
||||
pub(crate) const MAX_TRAFFIC_READERS: usize = 4;
|
||||
@@ -0,0 +1,528 @@
|
||||
//! Boundaries between the agent, one IP encryption tunnel, and external carriers.
|
||||
//!
|
||||
//! The core moves bounded opaque capabilities without parsing cipher payloads.
|
||||
//! 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.
|
||||
//!
|
||||
//! [`transport::DataCarrier`] owns external capability negotiation and lifecycle.
|
||||
//! It sees reachability but never plaintext overlay packets. A relay forwards
|
||||
//! the encrypted inner bytes without entering an IP plugin or the TUN.
|
||||
//! Data-plane failure never stops control sessions or discovery.
|
||||
|
||||
pub use crate::vip::router::is_path_probe;
|
||||
|
||||
pub mod relay;
|
||||
pub mod routing;
|
||||
pub mod transport;
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use iroh::EndpointId;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::BoxFuture;
|
||||
use crate::identity::NetworkId;
|
||||
|
||||
pub use transport::{
|
||||
MultiPacketTransport, PacketLink, PacketTransport, SharedLink, TransportError,
|
||||
};
|
||||
|
||||
/// Maximum length of a plugin protocol identifier.
|
||||
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.
|
||||
///
|
||||
/// `data` is opaque to the core. Nothing in it may be interpreted as a shell
|
||||
/// command, a filesystem path or an OS setting by the core; a plugin that
|
||||
/// chooses to do so must validate it itself.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PluginCapability {
|
||||
/// Protocol identifier, e.g. `wg-quic`. Bounded by [`MAX_PROTOCOL_ID_LEN`].
|
||||
pub protocol: String,
|
||||
/// Version of the plugin's announcement format.
|
||||
pub version: u16,
|
||||
/// Whether the peer currently has this plugin enabled.
|
||||
pub enabled: bool,
|
||||
/// Opaque, bounded, plugin-defined payload.
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Where a protocol hands the packets it has decrypted.
|
||||
///
|
||||
/// A protocol proves *who* sent a packet; it does not know what that member
|
||||
/// is entitled to say, because entitlement is an address claim the system
|
||||
/// level holds. So a decrypted packet goes here rather than straight to an
|
||||
/// interface, and is checked on the way.
|
||||
pub trait PacketSink: Send + Sync + 'static {
|
||||
/// Hands over one packet, attributed to the peer whose tunnel decrypted
|
||||
/// it.
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
packet: bytes::Bytes,
|
||||
) -> BoxFuture<'a, ()>;
|
||||
}
|
||||
|
||||
/// A sink that drops everything, for a protocol running without an interface.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct DiscardPackets;
|
||||
|
||||
impl PacketSink for DiscardPackets {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
_network: NetworkId,
|
||||
_peer: EndpointId,
|
||||
_packet: bytes::Bytes,
|
||||
) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {})
|
||||
}
|
||||
}
|
||||
|
||||
/// One setting a protocol accepts.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ProtocolOption {
|
||||
/// The key, as written in `key=value`.
|
||||
pub key: &'static str,
|
||||
/// A word for the value, for the help line: `BYTES`, `NAME`.
|
||||
pub value: &'static str,
|
||||
/// What it does.
|
||||
pub help: &'static str,
|
||||
/// What happens when it is not given.
|
||||
pub default: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Errors a plugin may return. They are recorded, never fatal for the agent.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum PluginError {
|
||||
/// The plugin is not currently able to produce or apply configuration.
|
||||
#[error("plugin unavailable: {0}")]
|
||||
Unavailable(String),
|
||||
/// A peer announcement was not acceptable to the plugin.
|
||||
#[error("rejected peer announcement: {0}")]
|
||||
Rejected(String),
|
||||
/// Anything else.
|
||||
#[error("plugin error: {0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// A request a plugin makes of the agent that owns it.
|
||||
#[derive(Debug)]
|
||||
pub enum PluginRequest {
|
||||
/// Re-send this agent's announcement to every peer of a network.
|
||||
Reannounce(NetworkId),
|
||||
/// Surface a plugin error on the agent's event stream.
|
||||
Error {
|
||||
/// Network the error is scoped to.
|
||||
network: NetworkId,
|
||||
/// Plugin protocol id.
|
||||
protocol: String,
|
||||
/// Human readable reason, free of secrets.
|
||||
reason: String,
|
||||
},
|
||||
/// A plugin reported that a data link or tunnel for a peer failed.
|
||||
ProtocolFailure {
|
||||
/// Network the failure occurred in.
|
||||
network: NetworkId,
|
||||
/// Peer whose protocol failed.
|
||||
peer: EndpointId,
|
||||
/// Protocol that failed.
|
||||
protocol: String,
|
||||
/// Human readable reason.
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// The agent-side handle a plugin is given when it is attached.
|
||||
///
|
||||
/// It is deliberately tiny: a plugin may ask for its announcement to be resent
|
||||
/// and may report an error. It cannot reach into agent state, cannot send
|
||||
/// arbitrary control messages and knows nothing about sessions.
|
||||
///
|
||||
/// All calls are non-blocking. If the agent is gone or its queue is full the
|
||||
/// request is dropped rather than stalling the plugin.
|
||||
#[derive(Clone)]
|
||||
pub struct PluginContext {
|
||||
sender: Option<mpsc::Sender<PluginRequest>>,
|
||||
local: Option<EndpointId>,
|
||||
/// Where decrypted packets go. Absent when nothing is carrying traffic,
|
||||
/// in which case a protocol still runs and its packets are discarded.
|
||||
sink: Option<Arc<dyn PacketSink>>,
|
||||
routes: Weak<crate::overlay::RoutingTable>,
|
||||
}
|
||||
|
||||
impl PluginContext {
|
||||
pub(crate) fn new(
|
||||
sender: mpsc::Sender<PluginRequest>,
|
||||
local: EndpointId,
|
||||
sink: Option<Arc<dyn PacketSink>>,
|
||||
routes: &Arc<crate::overlay::RoutingTable>,
|
||||
) -> Self {
|
||||
Self {
|
||||
sender: Some(sender),
|
||||
local: Some(local),
|
||||
sink,
|
||||
routes: Arc::downgrade(routes),
|
||||
}
|
||||
}
|
||||
|
||||
/// The peer whose tunnel should stay ready for traffic even while idle.
|
||||
/// Only the locally selected internet exit in its own network qualifies.
|
||||
pub fn warm_peer(&self, network: NetworkId) -> Option<EndpointId> {
|
||||
let (selected, peer) = self.routes.upgrade()?.exit_via()?;
|
||||
(selected == network).then_some(peer)
|
||||
}
|
||||
|
||||
/// Where to hand a decrypted packet.
|
||||
///
|
||||
/// Always answers: with no interface to write to, the packets are
|
||||
/// discarded, which is what `--no-tun` means and is not an error.
|
||||
pub fn packet_sink(&self) -> Arc<dyn PacketSink> {
|
||||
match &self.sink {
|
||||
Some(sink) => Arc::clone(sink),
|
||||
None => Arc::new(DiscardPackets),
|
||||
}
|
||||
}
|
||||
|
||||
/// A context that discards everything, for plugins used outside an agent.
|
||||
pub fn detached() -> Self {
|
||||
Self {
|
||||
sender: None,
|
||||
local: None,
|
||||
sink: None,
|
||||
routes: Weak::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A context configured with a custom packet sink.
|
||||
pub fn with_sink(sink: Arc<dyn PacketSink>) -> Self {
|
||||
Self {
|
||||
sink: Some(sink),
|
||||
..Self::detached()
|
||||
}
|
||||
}
|
||||
|
||||
/// A context configured with a channel for plugin requests and custom sink, for tests.
|
||||
#[cfg(feature = "testing")]
|
||||
pub fn for_test(
|
||||
sender: mpsc::Sender<PluginRequest>,
|
||||
local: EndpointId,
|
||||
sink: Option<Arc<dyn PacketSink>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
sender: Some(sender),
|
||||
local: Some(local),
|
||||
sink,
|
||||
..Self::detached()
|
||||
}
|
||||
}
|
||||
|
||||
/// This agent's own endpoint id, when the context is attached.
|
||||
///
|
||||
/// A plugin needs it to find itself in the agreed allocation.
|
||||
pub fn local_endpoint_id(&self) -> Option<EndpointId> {
|
||||
self.local
|
||||
}
|
||||
|
||||
fn send(&self, request: PluginRequest) {
|
||||
let Some(sender) = &self.sender else {
|
||||
return;
|
||||
};
|
||||
if let Err(err) = sender.try_send(request) {
|
||||
tracing::debug!(%err, "dropping plugin request");
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the agent to resend this agent's announcement in `network`.
|
||||
///
|
||||
/// A plugin calls this when its own capability changed — it finished
|
||||
/// starting up, its keys or reachability changed — so that peers learn the
|
||||
/// new value without waiting for a reconnect.
|
||||
pub fn request_reannounce(&self, network: NetworkId) {
|
||||
self.send(PluginRequest::Reannounce(network));
|
||||
}
|
||||
|
||||
/// Reports a plugin error on the agent's event stream.
|
||||
///
|
||||
/// Plugin work happens in the plugin's own tasks, so errors cannot always
|
||||
/// be returned from a trait call. They are never fatal for the agent.
|
||||
pub fn report_error(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
protocol: impl Into<String>,
|
||||
reason: impl Into<String>,
|
||||
) {
|
||||
self.send(PluginRequest::Error {
|
||||
network,
|
||||
protocol: protocol.into(),
|
||||
reason: reason.into(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Reports that data plane connectivity or a tunnel for a peer has failed.
|
||||
pub fn report_peer_protocol_failure(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: impl Into<String>,
|
||||
reason: impl Into<String>,
|
||||
) {
|
||||
self.send(PluginRequest::ProtocolFailure {
|
||||
network,
|
||||
peer,
|
||||
protocol: protocol.into(),
|
||||
reason: reason.into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PluginContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PluginContext")
|
||||
.field("attached", &self.sender.is_some())
|
||||
.field("local", &self.local.map(|id| id.fmt_short().to_string()))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The contract an IP plugin implements.
|
||||
///
|
||||
/// Implementations must be cheap and non-blocking: the agent calls them from
|
||||
/// its runtime tasks. Anything slow belongs in the plugin's own tasks.
|
||||
pub trait IpPlugin: Send + Sync + std::fmt::Debug + 'static {
|
||||
/// Stable protocol identifier, e.g. `wg-quic`.
|
||||
///
|
||||
/// Must be non-empty and at most [`MAX_PROTOCOL_ID_LEN`] bytes.
|
||||
fn protocol_id(&self) -> &str;
|
||||
|
||||
/// The wire version of this protocol.
|
||||
///
|
||||
/// Two peers carry traffic for each other only when they have the same
|
||||
/// protocol at the same version. There is no negotiating a middle
|
||||
/// ground: a protocol either speaks the same words at both ends or it
|
||||
/// does not, and pretending otherwise produces a link that fails later
|
||||
/// and less clearly.
|
||||
///
|
||||
/// **Not the software version.** A plugin crate has its own version and
|
||||
/// it is nobody else's business: two peers on different builds work
|
||||
/// together for as long as the wire between them has not changed. This
|
||||
/// number moves only when the bytes do, so it must never be derived from
|
||||
/// `CARGO_PKG_VERSION` or anything else that moves with a release.
|
||||
fn protocol_version(&self) -> u16;
|
||||
|
||||
/// The settings this protocol accepts, and what they mean.
|
||||
///
|
||||
/// Declared rather than documented elsewhere, so the agent can list them
|
||||
/// without knowing anything about the protocol.
|
||||
fn options(&self) -> &'static [ProtocolOption] {
|
||||
&[]
|
||||
}
|
||||
|
||||
/// Called once, when the agent starts, before any network is activated.
|
||||
///
|
||||
/// The plugin keeps the context to ask for re-announcements and to report
|
||||
/// errors that happen in its own tasks.
|
||||
fn attach(&self, context: PluginContext) {
|
||||
let _ = context;
|
||||
}
|
||||
|
||||
/// Produces this agent's announcement for a given network.
|
||||
///
|
||||
/// Returning `Ok(None)` means "nothing to announce right now", which is
|
||||
/// different from an error.
|
||||
fn local_capability(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
) -> std::result::Result<Option<PluginCapability>, PluginError>;
|
||||
|
||||
/// Called when a network is activated locally, before any peer appears.
|
||||
///
|
||||
/// A plugin uses it to get its per-network state ready, so that the first
|
||||
/// announcement already carries its capability.
|
||||
fn on_network_activated(&self, network: NetworkId) {
|
||||
let _ = network;
|
||||
}
|
||||
|
||||
/// Called when a peer announces a capability for this plugin's protocol.
|
||||
///
|
||||
/// The core has already bounded the payload size but has not interpreted it.
|
||||
fn on_peer_capability(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
capability: &PluginCapability,
|
||||
) -> std::result::Result<(), PluginError>;
|
||||
|
||||
/// The overlay addresses the network has agreed on.
|
||||
///
|
||||
/// Allocated rather than derived, and backed by the signed records in
|
||||
/// [`crate::state`], so a participant keeps its address across restarts
|
||||
/// and long absences. Called whenever the agreed picture changes.
|
||||
fn on_address_allocation(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
range: crate::state::Ipv4Range,
|
||||
allocations: &[(EndpointId, std::net::Ipv4Addr)],
|
||||
) {
|
||||
let _ = (network, range, allocations);
|
||||
}
|
||||
|
||||
/// Carries one packet to a peer, encrypting it however this protocol
|
||||
/// does.
|
||||
///
|
||||
/// `false` when it cannot right now — no link, no tunnel, not this
|
||||
/// protocol's peer — which the caller reports rather than treats as an
|
||||
/// error. The packet came off the one interface the agent owns, and
|
||||
/// which protocol takes it is settled by asking.
|
||||
///
|
||||
/// The default carries nothing, which is right for a plugin that only
|
||||
/// announces something.
|
||||
fn carry(&self, _network: NetworkId, _peer: EndpointId, _packet: bytes::Bytes) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// A data plane link to a peer is available for this plugin's protocol.
|
||||
///
|
||||
/// The plugin moves its packets over this link and never learns how the
|
||||
/// link is carried. A new link for a peer replaces any previous one.
|
||||
fn on_peer_link(&self, network: NetworkId, peer: EndpointId, link: SharedLink) {
|
||||
let _ = (network, peer, link);
|
||||
}
|
||||
|
||||
/// Called when a peer's session in a network goes away.
|
||||
///
|
||||
/// Any link handed to the plugin for that peer must be dropped here.
|
||||
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId);
|
||||
|
||||
/// Called when a network is deactivated locally.
|
||||
///
|
||||
/// This is a local deactivation, not a signed revocation of membership.
|
||||
/// The plugin is expected to remove whatever it created for that network.
|
||||
fn on_network_deactivated(&self, network: NetworkId);
|
||||
|
||||
/// Called when this agent has left a network for good.
|
||||
///
|
||||
/// Deactivation is temporary and keeps everything ready for next time;
|
||||
/// this is the other one. Whatever the plugin holds *durably* for that
|
||||
/// network — a key of its own, a file, a record — goes now, because the
|
||||
/// agent is no longer a member and keeping it is keeping a secret for a
|
||||
/// network it cannot rejoin without being told the secret again.
|
||||
///
|
||||
/// Always preceded by [`IpPlugin::on_network_deactivated`], so this is
|
||||
/// only about what outlives a session. Defaulted to nothing, for a
|
||||
/// plugin that stores nothing.
|
||||
fn on_network_forgotten(&self, _network: NetworkId) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async {})
|
||||
}
|
||||
|
||||
/// Called once when the agent shuts down.
|
||||
///
|
||||
/// The plugin removes the system objects it created and stops its tasks.
|
||||
/// It must be bounded: the agent awaits it during shutdown.
|
||||
fn shutdown<'a>(&'a self) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async {})
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared handle to a plugin.
|
||||
pub type SharedPlugin = Arc<dyn IpPlugin>;
|
||||
|
||||
/// A plugin used in tests and examples.
|
||||
///
|
||||
/// It announces an explicitly test-only protocol id, so nothing in this crate
|
||||
/// ever advertises WireGuard as an available transport before it exists.
|
||||
#[derive(Debug)]
|
||||
pub struct TestCapabilityPlugin {
|
||||
protocol: String,
|
||||
payload: Vec<u8>,
|
||||
seen: std::sync::Mutex<Vec<(NetworkId, EndpointId, PluginCapability)>>,
|
||||
}
|
||||
|
||||
impl TestCapabilityPlugin {
|
||||
/// Creates a plugin announcing `protocol` with a fixed opaque payload.
|
||||
pub fn new(protocol: impl Into<String>, payload: impl Into<Vec<u8>>) -> Self {
|
||||
Self {
|
||||
protocol: protocol.into(),
|
||||
payload: payload.into(),
|
||||
seen: std::sync::Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns everything this plugin was handed so far.
|
||||
pub fn observed(&self) -> Vec<(NetworkId, EndpointId, PluginCapability)> {
|
||||
match self.seen.lock() {
|
||||
Ok(guard) => guard.clone(),
|
||||
Err(poisoned) => poisoned.into_inner().clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IpPlugin for TestCapabilityPlugin {
|
||||
fn protocol_id(&self) -> &str {
|
||||
&self.protocol
|
||||
}
|
||||
|
||||
fn protocol_version(&self) -> u16 {
|
||||
1
|
||||
}
|
||||
|
||||
fn local_capability(
|
||||
&self,
|
||||
_network: NetworkId,
|
||||
) -> std::result::Result<Option<PluginCapability>, PluginError> {
|
||||
Ok(Some(PluginCapability {
|
||||
protocol: self.protocol.clone(),
|
||||
version: 1,
|
||||
enabled: true,
|
||||
data: self.payload.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn on_peer_capability(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
capability: &PluginCapability,
|
||||
) -> std::result::Result<(), PluginError> {
|
||||
let mut guard = match self.seen.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
guard.push((network, peer, capability.clone()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_peer_gone(&self, _network: NetworkId, _peer: EndpointId) {}
|
||||
|
||||
fn on_network_deactivated(&self, _network: NetworkId) {}
|
||||
}
|
||||
@@ -0,0 +1,696 @@
|
||||
//! Userspace forwarding. Topology updates publish immutable tables; the packet
|
||||
//! path takes no routing mutex, walks no graph and never inspects plugin bytes.
|
||||
//! Each transport reader forwards transit immediately, independently of the
|
||||
//! destination protocol's receive task. Only local delivery enters its inbox.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use bytes::Bytes;
|
||||
use iroh::EndpointId;
|
||||
use tokio::sync::{Notify, mpsc, watch};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use super::routing::{FlowId, PeerId, RoutingTable, envelope, mix64};
|
||||
use super::transport::{PacketLink, SharedLink, TransportError};
|
||||
use crate::BoxFuture;
|
||||
use crate::config::{MAX_DATA_DATAGRAM, ROUTING_HOP_LIMIT};
|
||||
use crate::identity::NetworkId;
|
||||
|
||||
/// Fixed routing header, subtracted from the logical transport MTU.
|
||||
pub const RELAY_OVERHEAD: usize = envelope::HEADER;
|
||||
const INBOX: usize = 256;
|
||||
|
||||
/// Forwarding counters, shared by all protocols of one network.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct RelayCounters {
|
||||
/// Datagrams originated here and sent through another member.
|
||||
pub sent_via: u64,
|
||||
/// Transit datagrams handed to the next transport link.
|
||||
pub forwarded: u64,
|
||||
/// Local datagrams received through another member.
|
||||
pub received_via: u64,
|
||||
/// Missing or failed next hop.
|
||||
pub dropped_no_link: u64,
|
||||
/// Malformed envelope or unknown member.
|
||||
pub dropped_unknown: u64,
|
||||
/// Exhausted hop limit, including loops during topology convergence.
|
||||
pub dropped_hop_limit: u64,
|
||||
/// Full local protocol inbox. Transit does not use this queue.
|
||||
pub dropped_congested: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Tally {
|
||||
sent_via: AtomicU64,
|
||||
forwarded: AtomicU64,
|
||||
received_via: AtomicU64,
|
||||
dropped_no_link: AtomicU64,
|
||||
dropped_unknown: AtomicU64,
|
||||
dropped_hop_limit: AtomicU64,
|
||||
dropped_congested: AtomicU64,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
fn snapshot(&self) -> RelayCounters {
|
||||
RelayCounters {
|
||||
sent_via: self.sent_via.load(Ordering::Relaxed),
|
||||
forwarded: self.forwarded.load(Ordering::Relaxed),
|
||||
received_via: self.received_via.load(Ordering::Relaxed),
|
||||
dropped_no_link: self.dropped_no_link.load(Ordering::Relaxed),
|
||||
dropped_unknown: self.dropped_unknown.load(Ordering::Relaxed),
|
||||
dropped_hop_limit: self.dropped_hop_limit.load(Ordering::Relaxed),
|
||||
dropped_congested: self.dropped_congested.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
struct NextHop {
|
||||
peer: PeerId,
|
||||
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)]
|
||||
struct ForwardRoute {
|
||||
hops: u8,
|
||||
next: Box<[NextHop]>,
|
||||
}
|
||||
|
||||
impl ForwardRoute {
|
||||
fn select(&self, source: &PeerId, flow: FlowId) -> Option<&NextHop> {
|
||||
if self.next.len() == 1 {
|
||||
return self.next.first().filter(|hop| hop.usable());
|
||||
}
|
||||
let seed = u64::from_le_bytes(source[..8].try_into().ok()?);
|
||||
let start = mix64(flow ^ seed) as usize % self.next.len();
|
||||
// Stable fallback if a link closed just before its table was replaced.
|
||||
(0..self.next.len())
|
||||
.map(|i| &self.next[(start + i) % self.next.len()])
|
||||
.find(|hop| hop.usable())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ForwardingTable {
|
||||
routes: HashMap<PeerId, ForwardRoute>,
|
||||
/// Local delivery, by who sent it and which end-to-end protocol it is.
|
||||
inboxes: HashMap<(PeerId, u64), mpsc::Sender<Bytes>>,
|
||||
members: HashSet<PeerId>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Plane {
|
||||
network: NetworkId,
|
||||
traffic: Arc<crate::traffic::TrafficMonitor>,
|
||||
local: PeerId,
|
||||
table: ArcSwap<ForwardingTable>,
|
||||
tally: Arc<Tally>,
|
||||
}
|
||||
|
||||
impl Plane {
|
||||
/// Synchronous hot path: one snapshot, bounded header decode, table lookup,
|
||||
/// and transport send. An exclusively owned buffer is modified in place.
|
||||
fn receive(&self, incoming: PeerId, frame: Bytes) {
|
||||
let Some(header) = envelope::decode(&frame) else {
|
||||
self.tally.dropped_unknown.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
};
|
||||
let table = self.table.load();
|
||||
if !table.members.contains(&header.source) || header.source == self.local {
|
||||
self.tally.dropped_unknown.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
if header.destination == self.local {
|
||||
let Some(inbox) = table.inboxes.get(&(header.source, header.protocol)) else {
|
||||
self.tally.dropped_unknown.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
};
|
||||
if inbox.try_send(frame.slice(RELAY_OVERHEAD..)).is_err() {
|
||||
self.tally.dropped_congested.fetch_add(1, Ordering::Relaxed);
|
||||
} else if incoming != header.source {
|
||||
self.tally.received_via.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if header.remaining <= 1 {
|
||||
self.tally.dropped_hop_limit.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let hop = table
|
||||
.routes
|
||||
.get(&header.destination)
|
||||
.and_then(|route| route.select(&header.source, header.flow));
|
||||
let Some(hop) = hop else {
|
||||
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
};
|
||||
let len = frame.len();
|
||||
if hop.send(envelope::decrement(frame)).is_ok() {
|
||||
self.traffic.relay(
|
||||
self.network,
|
||||
header.source,
|
||||
header.destination,
|
||||
header.protocol,
|
||||
len,
|
||||
);
|
||||
self.tally.forwarded.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One physical link to a neighbour, of whatever kind of transport.
|
||||
#[derive(Debug)]
|
||||
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>,
|
||||
/// Transport kinds, best first. A neighbour with several links is
|
||||
/// reached over the first of these it has.
|
||||
priority: Vec<String>,
|
||||
preferred: HashMap<PeerId, String>,
|
||||
graph: HashMap<PeerId, Vec<PeerId>>,
|
||||
members: HashSet<PeerId>,
|
||||
raw: HashMap<PeerId, Vec<RawLink>>,
|
||||
links: HashMap<(PeerId, String), 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();
|
||||
let preferred = self.preferred.get(peer);
|
||||
links.sort_by_key(|raw| {
|
||||
(
|
||||
preferred != Some(&raw.kind),
|
||||
self.rank(&raw.kind),
|
||||
&raw.kind,
|
||||
)
|
||||
});
|
||||
links
|
||||
}
|
||||
|
||||
fn publish(&self) {
|
||||
let mut graph = self.graph.clone();
|
||||
let mut neighbours: Vec<PeerId> = self
|
||||
.raw
|
||||
.iter()
|
||||
.filter(|(_, links)| links.iter().any(|raw| !raw.link.is_closed()))
|
||||
.map(|(peer, _)| *peer)
|
||||
.collect();
|
||||
neighbours.sort_unstable();
|
||||
graph.insert(self.plane.local, neighbours);
|
||||
let routing = RoutingTable::build(self.plane.local, &graph, ROUTING_HOP_LIMIT);
|
||||
let routes = routing
|
||||
.iter()
|
||||
.filter_map(|(peer, route)| {
|
||||
let next: Box<[_]> = route
|
||||
.next_hops
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let links: Box<[_]> = self
|
||||
.ordered(id)
|
||||
.into_iter()
|
||||
.map(|raw| raw.link.clone())
|
||||
.collect();
|
||||
(!links.is_empty()).then_some(NextHop { peer: *id, links })
|
||||
})
|
||||
.collect();
|
||||
(!next.is_empty()).then_some((
|
||||
*peer,
|
||||
ForwardRoute {
|
||||
hops: route.hops,
|
||||
next,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let mut members = self.members.clone();
|
||||
members.extend(self.raw.keys().copied());
|
||||
self.plane.table.store(Arc::new(ForwardingTable {
|
||||
routes,
|
||||
members,
|
||||
inboxes: self
|
||||
.links
|
||||
.iter()
|
||||
.map(|((peer, _), link)| ((*peer, link.tag), link.inbox_tx.clone()))
|
||||
.collect(),
|
||||
}));
|
||||
}
|
||||
|
||||
fn stop_readers(&mut self) {
|
||||
for raw in self.raw.values().flatten() {
|
||||
raw.reader.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for State {
|
||||
fn drop(&mut self) {
|
||||
self.stop_readers();
|
||||
for link in self.links.values() {
|
||||
link.close();
|
||||
}
|
||||
self.plane.table.store(Arc::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
pub struct RelayHub {
|
||||
network: NetworkId,
|
||||
state: Mutex<State>,
|
||||
tally: Arc<Tally>,
|
||||
changed: Arc<Notify>,
|
||||
}
|
||||
|
||||
impl RelayHub {
|
||||
/// Creates the router at this network's local endpoint.
|
||||
pub fn new(network: NetworkId, local: EndpointId) -> Arc<Self> {
|
||||
Self::with_monitor(network, local, Arc::default())
|
||||
}
|
||||
|
||||
pub(crate) fn with_monitor(
|
||||
network: NetworkId,
|
||||
local: EndpointId,
|
||||
traffic: Arc<crate::traffic::TrafficMonitor>,
|
||||
) -> Arc<Self> {
|
||||
let tally = Arc::new(Tally::default());
|
||||
Arc::new(Self {
|
||||
network,
|
||||
state: Mutex::new(State {
|
||||
plane: Arc::new(Plane {
|
||||
network,
|
||||
traffic,
|
||||
local: *local.as_bytes(),
|
||||
table: ArcSwap::from_pointee(ForwardingTable::default()),
|
||||
tally: tally.clone(),
|
||||
}),
|
||||
priority: Vec::new(),
|
||||
preferred: HashMap::new(),
|
||||
graph: HashMap::new(),
|
||||
members: HashSet::new(),
|
||||
raw: HashMap::new(),
|
||||
links: HashMap::new(),
|
||||
}),
|
||||
tally,
|
||||
changed: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn state(&self) -> std::sync::MutexGuard<'_, State> {
|
||||
self.state.lock().unwrap_or_else(|error| error.into_inner())
|
||||
}
|
||||
|
||||
/// Sets which kinds of transport are preferred, best first, when a
|
||||
/// neighbour can be reached over more than one.
|
||||
pub fn set_priority(&self, kinds: Vec<String>) {
|
||||
let mut state = self.state();
|
||||
if state.priority != kinds {
|
||||
state.priority = kinds;
|
||||
state.publish();
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects an already open carrier for this neighbour. The existing
|
||||
/// immutable forwarding snapshot handles packet delivery and fallback.
|
||||
pub(crate) fn prefer_direct(&self, peer: EndpointId, kind: &str) {
|
||||
let mut state = self.state();
|
||||
let id = peer.as_bytes();
|
||||
if state.preferred.get(id).map(String::as_str) != Some(kind)
|
||||
&& state.raw.get(id).is_some_and(|links| {
|
||||
links
|
||||
.iter()
|
||||
.any(|raw| raw.kind == kind && !raw.link.is_closed())
|
||||
})
|
||||
{
|
||||
state.preferred.insert(*id, kind.to_owned());
|
||||
state.publish();
|
||||
}
|
||||
}
|
||||
|
||||
/// Wakes the control loop promptly when a transport reader ends.
|
||||
pub async fn changed(&self) {
|
||||
self.changed.notified().await;
|
||||
}
|
||||
|
||||
/// Current counters.
|
||||
pub fn counters(&self) -> RelayCounters {
|
||||
self.tally.snapshot()
|
||||
}
|
||||
|
||||
/// Publishes authenticated topology. Refreshing identical state is cheap.
|
||||
///
|
||||
/// Every row of `graph` is one member's own account of who it has a link
|
||||
/// to; what kind of link it is does not matter here.
|
||||
pub fn set_topology(&self, graph: HashMap<PeerId, Vec<PeerId>>, members: HashSet<PeerId>) {
|
||||
let mut state = self.state();
|
||||
if state.graph != graph || state.members != members {
|
||||
state.graph = graph;
|
||||
state.members = members;
|
||||
state.publish();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the current table has a path to this destination.
|
||||
pub fn reachable(&self, peer: EndpointId) -> bool {
|
||||
self.state()
|
||||
.plane
|
||||
.table
|
||||
.load()
|
||||
.routes
|
||||
.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,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let mut state = self.state();
|
||||
let key = (*peer.as_bytes(), protocol.to_owned());
|
||||
if let Some(link) = state.links.get(&key) {
|
||||
return link.clone();
|
||||
}
|
||||
let (inbox_tx, inbox_rx) = mpsc::channel(INBOX);
|
||||
let (closed, _) = watch::channel(false);
|
||||
let link = Arc::new(PeerLink {
|
||||
network: self.network,
|
||||
peer,
|
||||
tag: envelope::protocol_tag(protocol),
|
||||
plane: state.plane.clone(),
|
||||
inbox_tx,
|
||||
inbox_rx: tokio::sync::Mutex::new(inbox_rx),
|
||||
closed,
|
||||
});
|
||||
state.links.insert(key, link.clone());
|
||||
state.publish();
|
||||
link
|
||||
}
|
||||
|
||||
/// Whether the protocol already owns its end-to-end channel to a peer.
|
||||
pub fn has_link(&self, peer: EndpointId, protocol: &str) -> bool {
|
||||
self.state()
|
||||
.links
|
||||
.contains_key(&(*peer.as_bytes(), protocol.to_owned()))
|
||||
}
|
||||
|
||||
/// Installs a raw transport link and starts its independent ingress reader.
|
||||
///
|
||||
/// 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 {
|
||||
return;
|
||||
}
|
||||
let mut state = self.state();
|
||||
let id = *peer.as_bytes();
|
||||
let plane = state.plane.clone();
|
||||
let changed = self.changed.clone();
|
||||
let reader_link = raw.clone();
|
||||
let reader = tokio::spawn(async move {
|
||||
let mut batch = 0;
|
||||
while let Some(frame) = reader_link.recv().await {
|
||||
plane.receive(id, frame);
|
||||
batch += 1;
|
||||
if batch == 64 {
|
||||
tokio::task::yield_now().await;
|
||||
batch = 0;
|
||||
}
|
||||
}
|
||||
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 one physical link without tearing down end-to-end protocol state.
|
||||
pub fn clear_direct(&self, peer: EndpointId, kind: &str) {
|
||||
let mut state = self.state();
|
||||
if state.preferred.get(peer.as_bytes()).map(String::as_str) == Some(kind) {
|
||||
state.preferred.remove(peer.as_bytes());
|
||||
}
|
||||
let mut changed = false;
|
||||
if let Some(links) = state.raw.get_mut(peer.as_bytes()) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// Retires data channels without removing an authenticated peer's topology.
|
||||
pub fn clear_peer_links(&self, peer: EndpointId) {
|
||||
let mut state = self.state();
|
||||
state.preferred.remove(peer.as_bytes());
|
||||
if let Some(links) = state.raw.remove(peer.as_bytes()) {
|
||||
for raw in links {
|
||||
raw.link.close();
|
||||
raw.reader.abort();
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
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.graph.remove(peer.as_bytes());
|
||||
for neighbors in state.graph.values_mut() {
|
||||
neighbors.retain(|id| id != peer.as_bytes());
|
||||
}
|
||||
state.publish();
|
||||
}
|
||||
|
||||
/// Stops every reader and releases all transport handles.
|
||||
pub fn close(&self) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
/// A protocol's end-to-end channel, independent of its current next hop.
|
||||
#[derive(Debug)]
|
||||
pub struct PeerLink {
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
tag: u64,
|
||||
plane: Arc<Plane>,
|
||||
inbox_tx: mpsc::Sender<Bytes>,
|
||||
inbox_rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||
closed: watch::Sender<bool>,
|
||||
}
|
||||
|
||||
impl PeerLink {
|
||||
fn close(&self) {
|
||||
self.closed.send_replace(true);
|
||||
}
|
||||
}
|
||||
|
||||
impl PacketLink for PeerLink {
|
||||
fn network(&self) -> NetworkId {
|
||||
self.network
|
||||
}
|
||||
fn peer(&self) -> EndpointId {
|
||||
self.peer
|
||||
}
|
||||
fn max_datagram_size(&self) -> usize {
|
||||
MAX_DATA_DATAGRAM - RELAY_OVERHEAD
|
||||
}
|
||||
fn send(&self, payload: Bytes) -> Result<(), TransportError> {
|
||||
self.send_flow(payload, 0)
|
||||
}
|
||||
fn send_flow(&self, payload: Bytes, flow: FlowId) -> Result<(), TransportError> {
|
||||
if self.is_closed() {
|
||||
return Err(TransportError::Closed);
|
||||
}
|
||||
if payload.len() > self.max_datagram_size() {
|
||||
return Err(TransportError::TooLarge {
|
||||
size: payload.len(),
|
||||
limit: self.max_datagram_size(),
|
||||
});
|
||||
}
|
||||
let table = self.plane.table.load();
|
||||
let route = table
|
||||
.routes
|
||||
.get(self.peer.as_bytes())
|
||||
.ok_or(TransportError::Closed)?;
|
||||
let hop = route
|
||||
.select(&self.plane.local, flow)
|
||||
.ok_or(TransportError::Closed)?;
|
||||
hop.send(envelope::encode(
|
||||
self.plane.local,
|
||||
*self.peer.as_bytes(),
|
||||
flow,
|
||||
self.tag,
|
||||
&payload,
|
||||
))?;
|
||||
if route.hops > 1 {
|
||||
self.plane.tally.sent_via.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
|
||||
Box::pin(async move {
|
||||
let mut closed = self.closed.subscribe();
|
||||
if *closed.borrow_and_update() {
|
||||
return None;
|
||||
}
|
||||
let mut inbox = self.inbox_rx.lock().await;
|
||||
tokio::select! { biased; _ = closed.changed() => None, frame = inbox.recv() => frame }
|
||||
})
|
||||
}
|
||||
fn closed(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
let mut closed = self.closed.subscribe();
|
||||
if !*closed.borrow_and_update() {
|
||||
let _ = closed.changed().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
fn is_closed(&self) -> bool {
|
||||
*self.closed.borrow()
|
||||
}
|
||||
fn path_description(&self) -> String {
|
||||
let table = self.plane.table.load();
|
||||
match table.routes.get(self.peer.as_bytes()) {
|
||||
Some(route) if route.hops == 1 => route.next[0]
|
||||
.first_open()
|
||||
.map_or_else(|| "unreachable".into(), |link| link.path_description()),
|
||||
Some(route) => format!(
|
||||
"relay {} hops via {} ({} equal paths)",
|
||||
route.hops,
|
||||
hex::encode(route.next[0].peer),
|
||||
route.next.len()
|
||||
),
|
||||
None => "unreachable".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "relay_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,461 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use crate::identity::{NetworkKeys, NetworkName, NetworkSecret};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
fn network() -> NetworkId {
|
||||
NetworkKeys::derive(
|
||||
&NetworkName::new("routing-tests").unwrap(),
|
||||
&NetworkSecret::from_bytes([3; 32]).unwrap(),
|
||||
)
|
||||
.network_id()
|
||||
}
|
||||
fn peer(seed: u8) -> EndpointId {
|
||||
iroh::SecretKey::from_bytes(&[seed; 32]).public()
|
||||
}
|
||||
fn id(seed: u8) -> PeerId {
|
||||
*peer(seed).as_bytes()
|
||||
}
|
||||
fn tag() -> u64 {
|
||||
envelope::protocol_tag("ip")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn measuring_an_alternative_preserves_the_active_link_until_promotion() {
|
||||
let hub = RelayHub::new(network(), peer(1));
|
||||
hub.set_priority(vec!["first".into(), "second".into()]);
|
||||
let first = Wire::new(2, true);
|
||||
let second = Wire::new(2, true);
|
||||
hub.set_direct(peer(2), "second", second.clone());
|
||||
hub.prefer_direct(peer(2), "second");
|
||||
hub.set_direct(peer(2), "first", first.clone());
|
||||
let logical = hub.link(peer(2), "ip");
|
||||
logical.send(Bytes::from_static(b"while testing")).unwrap();
|
||||
assert_eq!(second.take().len(), 1);
|
||||
assert!(first.take().is_empty());
|
||||
hub.prefer_direct(peer(2), "first");
|
||||
logical
|
||||
.send(Bytes::from_static(b"after switching"))
|
||||
.unwrap();
|
||||
assert_eq!(first.take().len(), 1);
|
||||
first.dead.store(true, Ordering::Relaxed);
|
||||
logical.send(Bytes::from_static(b"fallback")).unwrap();
|
||||
assert_eq!(second.take().len(), 1);
|
||||
hub.clear_direct(peer(2), "first");
|
||||
hub.set_direct(peer(2), "first", Wire::new(2, true));
|
||||
assert!(Arc::ptr_eq(&logical, &hub.link(peer(2), "ip")));
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Wire {
|
||||
peer: EndpointId,
|
||||
sent: Mutex<Vec<Bytes>>,
|
||||
feed: mpsc::Sender<Bytes>,
|
||||
inbound: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||
dead: AtomicBool,
|
||||
count: AtomicU64,
|
||||
record: bool,
|
||||
}
|
||||
impl Wire {
|
||||
fn new(seed: u8, record: bool) -> Arc<Self> {
|
||||
let (feed, inbound) = mpsc::channel(32);
|
||||
Arc::new(Self {
|
||||
peer: peer(seed),
|
||||
sent: Mutex::default(),
|
||||
feed,
|
||||
inbound: tokio::sync::Mutex::new(inbound),
|
||||
dead: AtomicBool::new(false),
|
||||
count: AtomicU64::new(0),
|
||||
record,
|
||||
})
|
||||
}
|
||||
fn take(&self) -> Vec<Bytes> {
|
||||
std::mem::take(&mut self.sent.lock().unwrap())
|
||||
}
|
||||
}
|
||||
impl PacketLink for Wire {
|
||||
fn network(&self) -> NetworkId {
|
||||
network()
|
||||
}
|
||||
fn peer(&self) -> EndpointId {
|
||||
self.peer
|
||||
}
|
||||
fn max_datagram_size(&self) -> usize {
|
||||
MAX_DATA_DATAGRAM
|
||||
}
|
||||
fn send(&self, frame: Bytes) -> Result<(), TransportError> {
|
||||
if self.is_closed() {
|
||||
return Err(TransportError::Closed);
|
||||
}
|
||||
self.count.fetch_add(1, Ordering::Relaxed);
|
||||
if self.record {
|
||||
self.sent.lock().unwrap().push(frame);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
|
||||
Box::pin(async move { self.inbound.lock().await.recv().await })
|
||||
}
|
||||
fn closed(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(std::future::pending())
|
||||
}
|
||||
fn is_closed(&self) -> bool {
|
||||
self.dead.load(Ordering::Relaxed)
|
||||
}
|
||||
fn path_description(&self) -> String {
|
||||
"test-direct".into()
|
||||
}
|
||||
}
|
||||
|
||||
fn topology(hub: &RelayHub, edges: &[(u8, &[u8])], members: &[u8]) {
|
||||
hub.set_topology(
|
||||
edges
|
||||
.iter()
|
||||
.map(|(a, bs)| (id(*a), bs.iter().map(|b| id(*b)).collect()))
|
||||
.collect(),
|
||||
members.iter().map(|p| id(*p)).collect(),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ecmp_is_per_flow_direct_wins_and_existing_tunnel_survives_changes() {
|
||||
let hub = RelayHub::new(network(), peer(1));
|
||||
let b = Wire::new(2, true);
|
||||
let c = Wire::new(3, true);
|
||||
hub.set_direct(peer(2), "ip", b.clone());
|
||||
hub.set_direct(peer(3), "ip", c.clone());
|
||||
topology(&hub, &[(2, &[4]), (3, &[4])], &[1, 2, 3, 4]);
|
||||
let link = hub.link(peer(4), "ip");
|
||||
let mut chosen = HashMap::new();
|
||||
for _ in 0..8 {
|
||||
for flow in 0..100 {
|
||||
link.send_flow(Bytes::from_static(b"ciphertext"), flow)
|
||||
.unwrap();
|
||||
}
|
||||
for (hop, wire) in [(2, &b), (3, &c)] {
|
||||
for frame in wire.take() {
|
||||
let header = envelope::decode(&frame).unwrap();
|
||||
assert_eq!(header.source, id(1));
|
||||
assert_eq!(header.destination, id(4));
|
||||
if let Some(old) = chosen.insert(header.flow, hop) {
|
||||
assert_eq!(old, hop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
chosen.values().copied().collect::<HashSet<_>>(),
|
||||
HashSet::from([2, 3])
|
||||
);
|
||||
let direct = Wire::new(4, true);
|
||||
hub.set_direct(peer(4), "ip", direct.clone());
|
||||
link.send_flow(Bytes::from_static(b"direct"), 8).unwrap();
|
||||
assert_eq!(direct.take().len(), 1);
|
||||
assert!(b.take().is_empty() && c.take().is_empty());
|
||||
hub.clear_direct(peer(4), "ip");
|
||||
b.dead.store(true, Ordering::Relaxed);
|
||||
for flow in 0..100 {
|
||||
link.send_flow(Bytes::from_static(b"fallback"), flow)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(c.take().len(), 100);
|
||||
hub.clear_direct(peer(2), "ip");
|
||||
topology(&hub, &[(3, &[])], &[1, 2, 3, 4]);
|
||||
assert!(link.send(Bytes::new()).is_err());
|
||||
assert!(!link.is_closed());
|
||||
assert!(Arc::ptr_eq(&link, &hub.link(peer(4), "ip")));
|
||||
hub.remove_peer(peer(4));
|
||||
assert!(link.is_closed());
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), link.closed())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(link.recv().await.is_none());
|
||||
hub.close();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protocols() {
|
||||
use crate::traffic::{Flow, Role, TrafficMonitor};
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let window = monitor.subscribe().unwrap();
|
||||
let hub = RelayHub::with_monitor(network(), peer(2), monitor);
|
||||
let a = Wire::new(1, true);
|
||||
let c = Wire::new(3, true);
|
||||
hub.set_direct(peer(1), "ip", a.clone());
|
||||
hub.set_direct(peer(3), "ip", c.clone());
|
||||
topology(&hub, &[(3, &[4])], &[1, 2, 3, 4]);
|
||||
let frame = envelope::encode(id(1), id(4), 91, tag(), b"end-to-end encrypted");
|
||||
let pointer = frame.as_ptr();
|
||||
a.feed.send(frame).await.unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), async {
|
||||
while hub.counters().forwarded == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let sent = c.take();
|
||||
assert_eq!(sent[0].as_ptr(), pointer);
|
||||
assert_eq!(
|
||||
envelope::decode(&sent[0]).unwrap().remaining,
|
||||
ROUTING_HOP_LIMIT - 1
|
||||
);
|
||||
assert_eq!(&sent[0][RELAY_OVERHEAD..], b"end-to-end encrypted");
|
||||
assert_eq!(hub.counters().forwarded, 1);
|
||||
let observed = window.snapshot();
|
||||
assert_eq!(observed.flows.len(), 1);
|
||||
let row = &observed.flows[0];
|
||||
assert_eq!(row.key.role, Role::Relay);
|
||||
assert_eq!(row.key.peer, id(1).min(id(4)));
|
||||
assert_eq!(
|
||||
row.key.flow,
|
||||
Flow::Relay {
|
||||
other: id(1).max(id(4)),
|
||||
wire_protocol: tag()
|
||||
}
|
||||
);
|
||||
assert_eq!(row.tx_bytes + row.rx_bytes, sent[0].len() as u64);
|
||||
assert_eq!(row.tx_packets + row.rx_packets, 1);
|
||||
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]
|
||||
async fn local_delivery_is_bounded_and_malformed_or_unknown_sources_are_dropped() {
|
||||
let hub = RelayHub::new(network(), peer(2));
|
||||
let a = Wire::new(1, true);
|
||||
hub.set_direct(peer(1), "ip", a);
|
||||
let link = hub.link(peer(1), "ip");
|
||||
let plane = link.plane.clone();
|
||||
for _ in 0..INBOX + 1 {
|
||||
plane.receive(id(1), envelope::encode(id(1), id(2), 0, tag(), b"ip"));
|
||||
}
|
||||
assert_eq!(hub.counters().dropped_congested, 1);
|
||||
for _ in 0..INBOX {
|
||||
assert_eq!(link.recv().await.unwrap(), Bytes::from_static(b"ip"));
|
||||
}
|
||||
plane.receive(id(1), Bytes::from_static(b"broken"));
|
||||
plane.receive(
|
||||
id(1),
|
||||
envelope::encode(id(9), id(2), 0, tag(), b"unknown member"),
|
||||
);
|
||||
assert_eq!(hub.counters().dropped_unknown, 2);
|
||||
plane.receive(
|
||||
id(1),
|
||||
envelope::encode(id(1), id(9), 0, tag(), b"unknown destination"),
|
||||
);
|
||||
assert_eq!(hub.counters().dropped_no_link, 1);
|
||||
hub.close();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inconsistent_tables_cannot_loop_beyond_the_hop_limit() {
|
||||
let a = RelayHub::new(network(), peer(1));
|
||||
let b = RelayHub::new(network(), peer(2));
|
||||
let ab = Wire::new(2, true);
|
||||
let ba = Wire::new(1, true);
|
||||
a.set_direct(peer(2), "ip", ab.clone());
|
||||
b.set_direct(peer(1), "ip", ba.clone());
|
||||
// Deliberately inconsistent snapshots while updates are in flight.
|
||||
topology(&a, &[(2, &[4])], &[1, 2, 3, 4]);
|
||||
topology(&b, &[(1, &[4])], &[1, 2, 3, 4]);
|
||||
let ap = a.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, tag(), b"transit");
|
||||
for turn in 0..ROUTING_HOP_LIMIT {
|
||||
let (plane, incoming, wire) = if turn % 2 == 0 {
|
||||
(&ap, id(2), &ab)
|
||||
} else {
|
||||
(&bp, id(1), &ba)
|
||||
};
|
||||
plane.receive(incoming, frame);
|
||||
let sent = wire.take();
|
||||
if turn == ROUTING_HOP_LIMIT - 1 {
|
||||
assert!(sent.is_empty());
|
||||
break;
|
||||
}
|
||||
assert_eq!(sent.len(), 1);
|
||||
frame = sent.into_iter().next().unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
a.counters().forwarded + b.counters().forwarded,
|
||||
u64::from(ROUTING_HOP_LIMIT - 1)
|
||||
);
|
||||
assert_eq!(
|
||||
a.counters().dropped_hop_limit + b.counters().dropped_hop_limit,
|
||||
1
|
||||
);
|
||||
a.close();
|
||||
b.close();
|
||||
}
|
||||
|
||||
/// Measures the actual synchronous transit routine, including header checks,
|
||||
/// snapshot lookup, ECMP, in-place TTL update and mock transport submission.
|
||||
/// Packet construction, encryption and socket I/O are outside this measurement.
|
||||
#[tokio::test]
|
||||
#[ignore = "manual release-mode forwarding microbenchmark"]
|
||||
async fn forwarding_benchmark() {
|
||||
let hub = RelayHub::new(network(), peer(2));
|
||||
let wire = Wire::new(3, false);
|
||||
hub.set_direct(peer(3), "ip", wire.clone());
|
||||
let alternate = Wire::new(5, false);
|
||||
hub.set_direct(peer(5), "ip", alternate.clone());
|
||||
topology(&hub, &[(3, &[4]), (5, &[4])], &[1, 2, 3, 4, 5]);
|
||||
let plane = hub.link(peer(4), "ip").plane.clone();
|
||||
let source = id(1);
|
||||
let destination = id(4);
|
||||
let incoming = id(1);
|
||||
for size in [64, 1280] {
|
||||
let mut elapsed = std::time::Duration::ZERO;
|
||||
const COUNT: usize = 10000;
|
||||
const BATCHES: usize = 100;
|
||||
for _ in 0..BATCHES {
|
||||
let frames: Vec<_> = (0..COUNT)
|
||||
.map(|flow| {
|
||||
envelope::encode(source, destination, flow as u64, tag(), &vec![42; size])
|
||||
})
|
||||
.collect();
|
||||
let start = std::time::Instant::now();
|
||||
for frame in frames {
|
||||
plane.receive(incoming, std::hint::black_box(frame));
|
||||
}
|
||||
elapsed += start.elapsed();
|
||||
}
|
||||
let count = (COUNT * BATCHES) as f64;
|
||||
println!(
|
||||
"transit {size} B: {:.1} ns/packet, {:.2} Mpps (1M packets, two equal paths)",
|
||||
elapsed.as_nanos() as f64 / count,
|
||||
count / elapsed.as_secs_f64() / 1e6
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
wire.count.load(Ordering::Relaxed) + alternate.count.load(Ordering::Relaxed),
|
||||
2000000
|
||||
);
|
||||
hub.close();
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Fixed header. Transit changes one byte in an owned receive buffer.
|
||||
use super::{FlowId, PeerId};
|
||||
use crate::config::{MAX_DATA_DATAGRAM, ROUTING_HOP_LIMIT};
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
|
||||
pub(crate) const HEADER: usize = 2 + 32 + 32 + 8 + 8;
|
||||
const VERSION: u8 = 2;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Header {
|
||||
pub source: PeerId,
|
||||
pub destination: PeerId,
|
||||
pub remaining: u8,
|
||||
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> {
|
||||
if bytes.len() < HEADER
|
||||
|| bytes.len() > MAX_DATA_DATAGRAM
|
||||
|| bytes[0] != VERSION
|
||||
|| bytes[1] == 0
|
||||
|| bytes[1] > ROUTING_HOP_LIMIT
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(Header {
|
||||
source: bytes[2..34].try_into().ok()?,
|
||||
destination: bytes[34..66].try_into().ok()?,
|
||||
remaining: bytes[1],
|
||||
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,
|
||||
protocol: u64,
|
||||
payload: &[u8],
|
||||
) -> Bytes {
|
||||
let mut bytes = BytesMut::with_capacity(HEADER + payload.len());
|
||||
bytes.put_u8(VERSION);
|
||||
bytes.put_u8(ROUTING_HOP_LIMIT);
|
||||
bytes.extend_from_slice(&source);
|
||||
bytes.extend_from_slice(&destination);
|
||||
bytes.put_u64(flow);
|
||||
bytes.put_u64(protocol);
|
||||
bytes.extend_from_slice(payload);
|
||||
bytes.freeze()
|
||||
}
|
||||
|
||||
pub(crate) fn decrement(bytes: Bytes) -> Bytes {
|
||||
let mut bytes = match bytes.try_into_mut() {
|
||||
Ok(bytes) => bytes,
|
||||
Err(bytes) => BytesMut::from(bytes.as_ref()),
|
||||
};
|
||||
// Called only after decode and after excluding remaining <= 1.
|
||||
bytes[1] -= 1;
|
||||
bytes.freeze()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn transit_reuses_the_buffer_and_rejects_invalid_headers() {
|
||||
let frame = encode([1; 32], [2; 32], 17, protocol_tag("wg"), &[42; 1280]);
|
||||
let address = frame.as_ptr();
|
||||
let frame = decrement(frame);
|
||||
assert_eq!(
|
||||
frame.as_ptr(),
|
||||
address,
|
||||
"no payload copy for an owned buffer"
|
||||
);
|
||||
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]);
|
||||
for length in 0..HEADER {
|
||||
assert!(decode(&frame[..length]).is_none());
|
||||
}
|
||||
for ttl in [0, ROUTING_HOP_LIMIT + 1] {
|
||||
let mut bad = frame.to_vec();
|
||||
bad[1] = ttl;
|
||||
assert!(decode(&bad).is_none());
|
||||
}
|
||||
let mut bad = frame.to_vec();
|
||||
bad[0] = 99;
|
||||
assert!(decode(&bad).is_none());
|
||||
assert!(decode(&vec![1; MAX_DATA_DATAGRAM + 1]).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Optional IP flow classifier for IP plugins, called before encryption.
|
||||
//! The router itself treats this identifier and the payload as opaque.
|
||||
|
||||
use super::FlowId;
|
||||
|
||||
fn hash(parts: &[&[u8]]) -> FlowId {
|
||||
let mut value = 0xcbf29ce484222325u64;
|
||||
for part in parts {
|
||||
for byte in *part {
|
||||
value = (value ^ u64::from(*byte)).wrapping_mul(0x100000001b3);
|
||||
}
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
/// Stable directional IP flow hash, independent of TCP sequence numbers,
|
||||
/// checksums and packet contents. Fragmented traffic uses addresses/protocol
|
||||
/// instead of ports: even non-initial fragments and subsequent fragmented
|
||||
/// datagrams stay together. This deliberately coalesces fragmented flows.
|
||||
/// Malformed packets get a coarse hash; parsing is bounded and never allocates.
|
||||
pub fn ip_flow(packet: &[u8]) -> FlowId {
|
||||
match packet.first().map(|b| b >> 4) {
|
||||
Some(4) if packet.len() >= 20 => {
|
||||
let addresses = &packet[12..20];
|
||||
let protocol = &packet[9..10];
|
||||
let offset = usize::from(packet[0] & 15) * 4;
|
||||
if u16::from_be_bytes([packet[6], packet[7]]) & 0x3fff != 0 {
|
||||
return hash(&[addresses, protocol]);
|
||||
}
|
||||
if offset >= 20
|
||||
&& matches!(packet[9], 6 | 17)
|
||||
&& let Some(ports) = packet.get(offset..offset + 4)
|
||||
{
|
||||
return hash(&[addresses, protocol, ports]);
|
||||
}
|
||||
hash(&[addresses, protocol])
|
||||
}
|
||||
Some(6) if packet.len() >= 40 => {
|
||||
let addresses = &packet[8..40];
|
||||
let mut protocol = packet[6];
|
||||
let mut offset = 40;
|
||||
for _ in 0..8 {
|
||||
match protocol {
|
||||
44 => {
|
||||
if let Some(fragment) = packet.get(offset..offset + 8) {
|
||||
return hash(&[addresses, &fragment[..1]]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
0 | 43 | 60 | 51 => {
|
||||
let Some(header) = packet.get(offset..offset + 2) else {
|
||||
break;
|
||||
};
|
||||
let size = if protocol == 51 {
|
||||
(usize::from(header[1]) + 2) * 4
|
||||
} else {
|
||||
(usize::from(header[1]) + 1) * 8
|
||||
};
|
||||
protocol = header[0];
|
||||
offset += size;
|
||||
}
|
||||
6 | 17 => {
|
||||
if let Some(ports) = packet.get(offset..offset + 4) {
|
||||
return hash(&[addresses, &[protocol], ports]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
hash(&[addresses, &[protocol]])
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tcp_flow_ignores_packet_contents_but_distinguishes_ports() {
|
||||
let mut packet = [0u8; 80];
|
||||
packet[0] = 0x45;
|
||||
packet[9] = 6;
|
||||
packet[12..24].copy_from_slice(&[10, 0, 0, 1, 10, 0, 0, 2, 0, 22, 1, 2]);
|
||||
let flow = ip_flow(&packet);
|
||||
packet[4] = 123; // IP id changes for each unfragmented packet.
|
||||
packet[24..].fill(47);
|
||||
assert_eq!(flow, ip_flow(&packet));
|
||||
packet[23] = 3;
|
||||
assert_ne!(flow, ip_flow(&packet));
|
||||
packet[6] = 0x20;
|
||||
let fragment_flow = ip_flow(&packet);
|
||||
packet[6] = 0;
|
||||
packet[7] = 1;
|
||||
packet[20..].fill(99);
|
||||
assert_eq!(fragment_flow, ip_flow(&packet));
|
||||
packet[4] = 97;
|
||||
assert_eq!(fragment_flow, ip_flow(&packet));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv6_extensions_and_fragments_are_bounded_and_stable() {
|
||||
let mut packet = [0u8; 80];
|
||||
packet[0] = 0x60;
|
||||
packet[6] = 0;
|
||||
packet[40] = 17;
|
||||
packet[48..52].copy_from_slice(&[1, 2, 3, 4]);
|
||||
let flow = ip_flow(&packet);
|
||||
packet[52..].fill(5);
|
||||
assert_eq!(flow, ip_flow(&packet));
|
||||
packet[50] = 9;
|
||||
assert_ne!(flow, ip_flow(&packet));
|
||||
packet[6] = 44;
|
||||
packet[40] = 6;
|
||||
let flow = ip_flow(&packet);
|
||||
packet[42] = 32;
|
||||
packet[48..].fill(3);
|
||||
assert_eq!(flow, ip_flow(&packet));
|
||||
for len in 0..packet.len() {
|
||||
let _ = ip_flow(&packet[..len]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Transport-independent routing over opaque identities. Tables are built on
|
||||
//! topology changes, never on the packet path. No WireGuard or iroh APIs here.
|
||||
pub(crate) mod envelope;
|
||||
pub mod flow;
|
||||
|
||||
use std::collections::{BTreeSet, HashMap, VecDeque};
|
||||
|
||||
/// Opaque authenticated identity; the transport adapter validates its keys.
|
||||
pub type PeerId = [u8; 32];
|
||||
/// Stable flow identifier, carried unchanged between transit routers.
|
||||
pub type FlowId = u64;
|
||||
|
||||
/// A shortest route with all equal-cost first hops in stable order.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Route {
|
||||
/// Number of transport links to the destination.
|
||||
pub hops: u8,
|
||||
/// Equal-cost first hops. Direct destinations have one entry.
|
||||
pub next_hops: Box<[PeerId]>,
|
||||
}
|
||||
|
||||
/// Immutable shortest-path table, replaced when connectivity changes.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct RoutingTable {
|
||||
routes: HashMap<PeerId, Route>,
|
||||
}
|
||||
|
||||
impl RoutingTable {
|
||||
/// Computes shortest directed paths bounded by `hop_limit`.
|
||||
/// The caller supplies only authenticated, fresh, compatible edges.
|
||||
pub fn build(local: PeerId, graph: &HashMap<PeerId, Vec<PeerId>>, hop_limit: u8) -> Self {
|
||||
let mut distances = HashMap::from([(local, 0u8)]);
|
||||
let mut first_hops: HashMap<PeerId, BTreeSet<PeerId>> = HashMap::new();
|
||||
let mut pending = VecDeque::from([local]);
|
||||
while let Some(node) = pending.pop_front() {
|
||||
let distance = distances[&node];
|
||||
if distance >= hop_limit {
|
||||
continue;
|
||||
}
|
||||
let inherited = first_hops.get(&node).cloned().unwrap_or_default();
|
||||
for &next in graph.get(&node).into_iter().flatten() {
|
||||
let next_distance = distance + 1;
|
||||
match distances.get(&next) {
|
||||
Some(&known) if known < next_distance => continue,
|
||||
None => {
|
||||
distances.insert(next, next_distance);
|
||||
pending.push_back(next);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let hops = first_hops.entry(next).or_default();
|
||||
if node == local {
|
||||
hops.insert(next);
|
||||
} else {
|
||||
hops.extend(inherited.iter().copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
Self {
|
||||
routes: first_hops
|
||||
.into_iter()
|
||||
.map(|(peer, hops)| {
|
||||
(
|
||||
peer,
|
||||
Route {
|
||||
hops: distances[&peer],
|
||||
next_hops: hops.into_iter().collect(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
/// Precomputed route to a destination.
|
||||
pub fn get(&self, destination: &PeerId) -> Option<&Route> {
|
||||
self.routes.get(destination)
|
||||
}
|
||||
/// All reachable destinations, excluding ourselves.
|
||||
pub fn iter(&self) -> impl Iterator<Item = (&PeerId, &Route)> {
|
||||
self.routes.iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable ECMP mixing, without random state or hashing the payload per hop.
|
||||
pub(crate) fn mix64(mut value: u64) -> u64 {
|
||||
value ^= value >> 30;
|
||||
value = value.wrapping_mul(0xbf58476d1ce4e5b9);
|
||||
value ^= value >> 27;
|
||||
value = value.wrapping_mul(0x94d049bb133111eb);
|
||||
value ^ (value >> 31)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
fn p(n: u8) -> PeerId {
|
||||
[n; 32]
|
||||
}
|
||||
#[test]
|
||||
fn shortest_paths_keep_equal_cost_hops_and_prefer_direct_links() {
|
||||
let mut graph = HashMap::from([
|
||||
(p(1), vec![p(3), p(2)]),
|
||||
(p(2), vec![p(4)]),
|
||||
(p(3), vec![p(4)]),
|
||||
(p(4), vec![p(5)]),
|
||||
(p(5), vec![p(1)]),
|
||||
]);
|
||||
let routes = RoutingTable::build(p(1), &graph, 16);
|
||||
assert_eq!(routes.get(&p(5)).unwrap().hops, 3);
|
||||
assert_eq!(&*routes.get(&p(5)).unwrap().next_hops, &[p(2), p(3)]);
|
||||
assert!(routes.get(&p(1)).is_none());
|
||||
assert!(routes.get(&p(9)).is_none());
|
||||
graph.get_mut(&p(1)).unwrap().push(p(5));
|
||||
assert_eq!(
|
||||
RoutingTable::build(p(1), &graph, 16).get(&p(5)).unwrap(),
|
||||
&Route {
|
||||
hops: 1,
|
||||
next_hops: Box::new([p(5)])
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn topology_removal_and_hop_budget_remove_impossible_routes() {
|
||||
let mut graph = HashMap::from([(p(1), vec![p(2)]), (p(2), vec![p(3)]), (p(3), vec![p(4)])]);
|
||||
assert!(RoutingTable::build(p(1), &graph, 2).get(&p(4)).is_none());
|
||||
assert!(RoutingTable::build(p(1), &graph, 3).get(&p(4)).is_some());
|
||||
graph.remove(&p(2));
|
||||
assert!(RoutingTable::build(p(1), &graph, 16).get(&p(4)).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! 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;
|
||||
/// Whether the peer may dial back after an unsuccessful elected dial.
|
||||
fn supports_reverse_dial(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// 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>;
|
||||
/// Adds IP hints from verified direct control paths. Their UDP ports do not
|
||||
/// identify a TCP listener. Carriers authenticate their own data path.
|
||||
fn on_peer_capability_at(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
capability: &PluginCapability,
|
||||
_ips: &[std::net::IpAddr],
|
||||
) -> Result<(), PluginError> {
|
||||
self.on_peer_capability(network, peer, capability)
|
||||
}
|
||||
/// 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>;
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Bounded fragmentation of opaque transport payloads, below peer relaying.
|
||||
//!
|
||||
//! Data ALPN v3: u64 packet ID, u32 total length, u32 byte offset (big endian),
|
||||
//! followed by payload. Each QUIC connection owns its IDs and reassembly state.
|
||||
//! There is no retransmission: one missing fragment loses one datagram only.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::config::{
|
||||
DATA_REASSEMBLY_TTL, DATA_RECENT_IDS, MAX_DATA_ASSEMBLIES, MAX_DATA_DATAGRAM,
|
||||
MAX_DATA_FRAGMENTS, MAX_DATA_REASSEMBLY_BYTES,
|
||||
};
|
||||
|
||||
pub(super) const HEADER: usize = 16;
|
||||
|
||||
pub(super) fn encode(id: u64, total: usize, offset: usize, payload: &[u8]) -> Bytes {
|
||||
let mut frame = BytesMut::with_capacity(HEADER + payload.len());
|
||||
frame.put_u64(id);
|
||||
frame.put_u32(total as u32);
|
||||
frame.put_u32(offset as u32);
|
||||
frame.extend_from_slice(payload);
|
||||
frame.freeze()
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Assembly {
|
||||
started: Instant,
|
||||
bytes: Vec<u8>,
|
||||
ranges: Vec<(usize, usize)>,
|
||||
received: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct Reassembler {
|
||||
packets: HashMap<u64, Assembly>,
|
||||
buffered: usize,
|
||||
recent: VecDeque<u64>,
|
||||
}
|
||||
|
||||
impl Reassembler {
|
||||
fn remember(&mut self, id: u64) {
|
||||
if self.recent.len() == DATA_RECENT_IDS {
|
||||
self.recent.pop_front();
|
||||
}
|
||||
self.recent.push_back(id);
|
||||
}
|
||||
|
||||
fn remove(&mut self, id: u64) -> Option<Assembly> {
|
||||
let packet = self.packets.remove(&id)?;
|
||||
self.buffered -= packet.bytes.len();
|
||||
self.remember(id);
|
||||
Some(packet)
|
||||
}
|
||||
|
||||
pub(super) fn expire(&mut self, now: Instant) {
|
||||
let expired: Vec<_> = self
|
||||
.packets
|
||||
.iter()
|
||||
.filter(|(_, p)| now.duration_since(p.started) >= DATA_REASSEMBLY_TTL)
|
||||
.map(|(id, _)| *id)
|
||||
.collect();
|
||||
for id in expired {
|
||||
self.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn push(&mut self, frame: Bytes, now: Instant) -> Option<Bytes> {
|
||||
self.expire(now);
|
||||
let id = u64::from_be_bytes(frame.get(..8)?.try_into().ok()?);
|
||||
let total = u32::from_be_bytes(frame.get(8..12)?.try_into().ok()?) as usize;
|
||||
let offset = u32::from_be_bytes(frame.get(12..HEADER)?.try_into().ok()?) as usize;
|
||||
let payload = frame.get(HEADER..)?;
|
||||
let end = offset.checked_add(payload.len())?;
|
||||
if total > MAX_DATA_DATAGRAM
|
||||
|| end > total
|
||||
|| (payload.is_empty() && total != 0)
|
||||
|| self.recent.contains(&id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if !self.packets.contains_key(&id) {
|
||||
if offset == 0 && end == total {
|
||||
self.remember(id);
|
||||
return Some(frame.slice(HEADER..));
|
||||
}
|
||||
// The length is validated before allocating. Drop the oldest
|
||||
// incomplete packet when the per-link byte or entry budget is full.
|
||||
while self.packets.len() >= MAX_DATA_ASSEMBLIES
|
||||
|| self.buffered + total > MAX_DATA_REASSEMBLY_BYTES
|
||||
{
|
||||
let oldest = self
|
||||
.packets
|
||||
.iter()
|
||||
.min_by_key(|(_, p)| p.started)
|
||||
.map(|(id, _)| *id)?;
|
||||
self.remove(oldest);
|
||||
}
|
||||
self.packets.insert(
|
||||
id,
|
||||
Assembly {
|
||||
started: now,
|
||||
bytes: vec![0; total],
|
||||
ranges: Vec::new(),
|
||||
received: 0,
|
||||
},
|
||||
);
|
||||
self.buffered += total;
|
||||
}
|
||||
let packet = self.packets.get_mut(&id)?;
|
||||
if packet.bytes.len() != total {
|
||||
self.remove(id);
|
||||
return None;
|
||||
}
|
||||
for &(start, stop) in &packet.ranges {
|
||||
if start == offset && stop == end && packet.bytes[offset..end] == *payload {
|
||||
return None; // a duplicate does not reset the expiry time
|
||||
}
|
||||
if offset < stop && end > start {
|
||||
self.remove(id); // conflicting or overlapping fragments
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if packet.ranges.len() == MAX_DATA_FRAGMENTS {
|
||||
self.remove(id);
|
||||
return None;
|
||||
}
|
||||
packet.bytes[offset..end].copy_from_slice(payload);
|
||||
packet.ranges.push((offset, end));
|
||||
packet.received += payload.len();
|
||||
if packet.received == total {
|
||||
return self.remove(id).map(|p| Bytes::from(p.bytes));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reordered_duplicates_and_changing_fragment_sizes_reassemble_once() {
|
||||
let mut rx = Reassembler::default();
|
||||
let now = Instant::now();
|
||||
let packet: Vec<u8> = (0..9000).map(|i| (i % 251) as u8).collect();
|
||||
let mut parts = Vec::new();
|
||||
let mut offset = 0;
|
||||
for size in [1100, 700, 1100, 1100, 700, 1100, 1100, 1100, 1000] {
|
||||
parts.push(encode(
|
||||
7,
|
||||
packet.len(),
|
||||
offset,
|
||||
&packet[offset..offset + size],
|
||||
));
|
||||
offset += size;
|
||||
}
|
||||
assert_eq!(offset, packet.len());
|
||||
for part in parts[1..].iter().rev() {
|
||||
assert!(rx.push(part.clone(), now).is_none());
|
||||
assert!(rx.push(part.clone(), now).is_none());
|
||||
}
|
||||
assert_eq!(rx.push(parts[0].clone(), now).unwrap().as_ref(), packet);
|
||||
assert!(rx.push(parts[0].clone(), now).is_none());
|
||||
assert_eq!(rx.buffered, 0);
|
||||
assert!(rx.packets.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_fragment_never_blocks_the_next_packet_and_expires() {
|
||||
let mut rx = Reassembler::default();
|
||||
let now = Instant::now();
|
||||
assert!(rx.push(encode(1, 1280, 0, &[1; 800]), now).is_none());
|
||||
assert_eq!(
|
||||
rx.push(encode(2, 4, 0, b"next"), now).unwrap(),
|
||||
&b"next"[..]
|
||||
);
|
||||
rx.expire(now + DATA_REASSEMBLY_TTL);
|
||||
assert!(rx.packets.is_empty());
|
||||
assert_eq!(rx.buffered, 0);
|
||||
assert!(
|
||||
rx.push(encode(1, 1280, 800, &[1; 480]), now + DATA_REASSEMBLY_TTL)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_conflicting_and_oversized_fragments_are_bounded() {
|
||||
let now = Instant::now();
|
||||
let mut rx = Reassembler::default();
|
||||
for len in 0..HEADER {
|
||||
assert!(rx.push(Bytes::from(vec![0xff; len]), now).is_none());
|
||||
}
|
||||
assert!(
|
||||
rx.push(encode(1, MAX_DATA_DATAGRAM + 1, 0, b"x"), now)
|
||||
.is_none()
|
||||
);
|
||||
assert!(rx.push(encode(2, 100, 100, b"x"), now).is_none());
|
||||
assert!(rx.push(encode(3, 100, 0, b""), now).is_none());
|
||||
assert_eq!(rx.buffered, 0);
|
||||
for (id, bad) in [
|
||||
(4, encode(4, 100, 0, b"different")),
|
||||
(5, encode(5, 100, 3, b"overlap")),
|
||||
(6, encode(6, 101, 9, b"changed total")),
|
||||
] {
|
||||
assert!(rx.push(encode(id, 100, 0, b"123456789"), now).is_none());
|
||||
assert!(rx.push(bad, now).is_none());
|
||||
assert_eq!(rx.buffered, 0);
|
||||
}
|
||||
for id in 100..400 {
|
||||
assert!(
|
||||
rx.push(encode(id, MAX_DATA_DATAGRAM, 0, b"x"), now)
|
||||
.is_none()
|
||||
);
|
||||
assert!(rx.buffered <= MAX_DATA_REASSEMBLY_BYTES);
|
||||
assert!(rx.packets.len() <= MAX_DATA_ASSEMBLIES);
|
||||
assert!(rx.recent.len() <= DATA_RECENT_IDS);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excessive_fragment_counts_are_discarded() {
|
||||
let mut rx = Reassembler::default();
|
||||
let now = Instant::now();
|
||||
for offset in 0..=MAX_DATA_FRAGMENTS {
|
||||
assert!(rx.push(encode(1, 1000, offset, b"x"), now).is_none());
|
||||
}
|
||||
assert!(rx.packets.is_empty());
|
||||
assert_eq!(rx.buffered, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
//! 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::{LinkQuality, 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, usize)>,
|
||||
recent: VecDeque<Option<Duration>>,
|
||||
last_reply: Option<Instant>,
|
||||
}
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const WINDOW: usize = 20;
|
||||
impl Samples {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
pending: VecDeque::new(),
|
||||
recent: VecDeque::new(),
|
||||
last_reply: None,
|
||||
}
|
||||
}
|
||||
fn sent(&mut self, seq: u64, now: Instant, size: usize) {
|
||||
self.pending.push_back((seq, now, size));
|
||||
}
|
||||
fn record(&mut self, rtt: Option<Duration>) {
|
||||
if self.recent.len() == WINDOW {
|
||||
self.recent.pop_front();
|
||||
}
|
||||
self.recent.push_back(rtt);
|
||||
}
|
||||
fn acknowledge(&mut self, seq: u64, now: Instant, size: usize) -> bool {
|
||||
if let Some(i) = self
|
||||
.pending
|
||||
.iter()
|
||||
.position(|(n, _, expected)| *n == seq && *expected == size)
|
||||
&& let Some((_, sent, _)) = self.pending.remove(i)
|
||||
{
|
||||
let rtt = now.saturating_duration_since(sent);
|
||||
let success = rtt < PROBE_TIMEOUT;
|
||||
self.record(success.then_some(rtt));
|
||||
if success {
|
||||
self.last_reply = Some(now);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
false
|
||||
}
|
||||
fn expire(&mut self, now: Instant) {
|
||||
while self
|
||||
.pending
|
||||
.front()
|
||||
.is_some_and(|(_, at, _)| now.duration_since(*at) >= PROBE_TIMEOUT)
|
||||
{
|
||||
self.pending.pop_front();
|
||||
self.record(None);
|
||||
}
|
||||
}
|
||||
fn degraded(&self) -> bool {
|
||||
self.recent.len() >= 15
|
||||
&& self.recent.iter().filter(|rtt| rtt.is_none()).count() * 100
|
||||
>= self.recent.len() * 60
|
||||
}
|
||||
fn quality(&self) -> Option<LinkQuality> {
|
||||
let observed_at = self.last_reply?;
|
||||
let mut delays = [Duration::ZERO; WINDOW];
|
||||
let mut samples = 0;
|
||||
for rtt in self.recent.iter().flatten() {
|
||||
delays[samples] = *rtt;
|
||||
samples += 1;
|
||||
}
|
||||
if samples == 0 {
|
||||
return None;
|
||||
}
|
||||
delays[..samples].sort_unstable();
|
||||
let rtt = (delays[(samples - 1) / 2] + delays[samples / 2]) / 2;
|
||||
Some(LinkQuality {
|
||||
rtt,
|
||||
samples,
|
||||
losses: self.recent.len() - samples,
|
||||
observed_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// 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>>,
|
||||
quality: Mutex<Option<([u8; 16], LinkQuality)>>,
|
||||
}
|
||||
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),
|
||||
quality: 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);
|
||||
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
|
||||
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,packet.len());
|
||||
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 && marker == Some(settings.marker) {
|
||||
if samples.acknowledge(seq, Instant::now(), packet.len()) {
|
||||
raw.confirm_delivery();
|
||||
}
|
||||
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
|
||||
}
|
||||
}
|
||||
} 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);
|
||||
}
|
||||
pub(crate) fn profile_id(&self) -> Option<[u8; 16]> {
|
||||
lock(&self.settings)
|
||||
.as_ref()
|
||||
.map(|settings| settings.marker)
|
||||
}
|
||||
}
|
||||
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 quality(&self) -> Option<LinkQuality> {
|
||||
if self.is_closed() {
|
||||
return None;
|
||||
}
|
||||
let current = self.profile_id()?;
|
||||
lock(&self.quality)
|
||||
.filter(|(profile, quality)| *profile == current && quality.is_fresh(Instant::now()))
|
||||
.map(|(_, quality)| quality)
|
||||
}
|
||||
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 an_authenticated_short_reply_does_not_prove_full_size_delivery() {
|
||||
let start = Instant::now();
|
||||
let mut samples = Samples::new();
|
||||
samples.sent(7, start, 1000);
|
||||
assert!(!samples.acknowledge(7, start, 57));
|
||||
assert!(samples.quality().is_none());
|
||||
assert!(samples.acknowledge(7, start, 1000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quality_uses_matched_fresh_replies_and_keeps_losses_in_the_window() {
|
||||
let mut samples = Samples::new();
|
||||
let start = Instant::now();
|
||||
assert!(samples.quality().is_none());
|
||||
for (seq, delay) in [(1, 10), (2, 30), (3, 250)] {
|
||||
samples.sent(seq, start, 1000);
|
||||
samples.acknowledge(seq, start + Duration::from_millis(delay), 1000);
|
||||
}
|
||||
assert!(!samples.acknowledge(1, start + Duration::from_secs(1), 1000));
|
||||
samples.sent(4, start, 1000);
|
||||
samples.expire(start + Duration::from_secs(3));
|
||||
assert!(!samples.acknowledge(4, start + Duration::from_secs(4), 1000));
|
||||
let measured = samples.quality().unwrap();
|
||||
assert_eq!(measured.rtt, Duration::from_millis(30));
|
||||
assert_eq!((measured.samples, measured.losses), (3, 1));
|
||||
assert!(measured.is_fresh(start + Duration::from_secs(4)));
|
||||
assert!(!measured.is_fresh(start + Duration::from_secs(6)));
|
||||
|
||||
for seq in 5..25 {
|
||||
let sent = start + Duration::from_secs(seq);
|
||||
samples.sent(seq, sent, 1000);
|
||||
samples.acknowledge(seq, sent + Duration::from_millis(80), 1000);
|
||||
}
|
||||
let recovered = samples.quality().unwrap();
|
||||
assert_eq!(recovered.rtt, Duration::from_millis(80));
|
||||
assert_eq!((recovered.samples, recovered.losses), (20, 0));
|
||||
}
|
||||
|
||||
#[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, 1000);
|
||||
if seq % 5 == 0 {
|
||||
samples.acknowledge(seq, now, 1000);
|
||||
}
|
||||
}
|
||||
assert!(!samples.degraded());
|
||||
samples.expire(now + Duration::from_secs(4));
|
||||
assert!(samples.degraded());
|
||||
for seq in 20..40 {
|
||||
samples.sent(seq, now, 1000);
|
||||
samples.acknowledge(seq, now, 1000);
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
+146
-17
@@ -20,13 +20,14 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh::EndpointId;
|
||||
use iroh::endpoint::{Connection, RecvStream, SendStream};
|
||||
|
||||
use crate::BoxFuture;
|
||||
use crate::config::Limits;
|
||||
use crate::config::{DATA_REASSEMBLY_TTL, Limits, MAX_DATA_DATAGRAM, MAX_DATA_FRAGMENTS};
|
||||
use crate::error::ProtocolError;
|
||||
use crate::identity::{NetworkId, NetworkKeys};
|
||||
use crate::net::EndpointAdapter;
|
||||
@@ -36,8 +37,52 @@ use crate::proto::message::{
|
||||
};
|
||||
use crate::proto::{read_frame, write_frame};
|
||||
|
||||
use super::fragments::{self, Reassembler};
|
||||
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.
|
||||
///
|
||||
/// Implemented by the agent, which is the only thing that knows which networks
|
||||
@@ -61,6 +106,8 @@ pub struct IrohLink {
|
||||
peer: EndpointId,
|
||||
conn: Connection,
|
||||
max_datagram: usize,
|
||||
next_packet: AtomicU64,
|
||||
reassembly: tokio::sync::Mutex<Reassembler>,
|
||||
// Kept alive so the peer sees the channel as open; the connection closes
|
||||
// when the link is dropped.
|
||||
_send: tokio::sync::Mutex<SendStream>,
|
||||
@@ -76,14 +123,16 @@ impl IrohLink {
|
||||
send: SendStream,
|
||||
recv: RecvStream,
|
||||
) -> Self {
|
||||
let local_limit = conn.max_datagram_size().unwrap_or(0);
|
||||
// Both ends must agree, so the smaller limit wins.
|
||||
let max_datagram = local_limit.min(peer_limit);
|
||||
// The negotiated limit is for reassembled payloads, never a snapshot
|
||||
// of the initial path (which may still be a relay or another VPN).
|
||||
let max_datagram = MAX_DATA_DATAGRAM.min(peer_limit);
|
||||
Self {
|
||||
network,
|
||||
peer,
|
||||
conn,
|
||||
max_datagram,
|
||||
next_packet: AtomicU64::new(0),
|
||||
reassembly: tokio::sync::Mutex::new(Reassembler::default()),
|
||||
_send: tokio::sync::Mutex::new(send),
|
||||
_recv: tokio::sync::Mutex::new(recv),
|
||||
}
|
||||
@@ -91,6 +140,9 @@ impl IrohLink {
|
||||
}
|
||||
|
||||
impl PacketLink for IrohLink {
|
||||
fn close(&self) {
|
||||
self.conn.close(0u32.into(), b"data link retired");
|
||||
}
|
||||
fn network(&self) -> NetworkId {
|
||||
self.network
|
||||
}
|
||||
@@ -110,17 +162,65 @@ impl PacketLink for IrohLink {
|
||||
limit: self.max_datagram,
|
||||
});
|
||||
}
|
||||
self.conn.send_datagram(payload).map_err(|err| {
|
||||
use iroh::endpoint::SendDatagramError;
|
||||
match err {
|
||||
SendDatagramError::ConnectionLost(_) => TransportError::Closed,
|
||||
other => TransportError::Other(other.to_string()),
|
||||
let id = self.next_packet.fetch_add(1, Ordering::Relaxed);
|
||||
let mut offset: usize = 0;
|
||||
let mut attempts = 0;
|
||||
// Re-read the current path's capacity for every fragment. A migration
|
||||
// can shrink it even between two send_datagram calls.
|
||||
for _ in 0..MAX_DATA_FRAGMENTS {
|
||||
loop {
|
||||
let capacity = self
|
||||
.conn
|
||||
.max_datagram_size()
|
||||
.unwrap_or(0)
|
||||
.checked_sub(fragments::HEADER)
|
||||
.filter(|n| *n > 0)
|
||||
.ok_or_else(|| {
|
||||
TransportError::Other("QUIC path cannot carry data fragments".into())
|
||||
})?;
|
||||
let end = offset.saturating_add(capacity).min(payload.len());
|
||||
let frame = fragments::encode(id, payload.len(), offset, &payload[offset..end]);
|
||||
match self.conn.send_datagram(frame) {
|
||||
Ok(()) => {
|
||||
offset = end;
|
||||
break;
|
||||
}
|
||||
Err(iroh::endpoint::SendDatagramError::TooLarge) if attempts < 3 => {
|
||||
attempts += 1;
|
||||
}
|
||||
Err(iroh::endpoint::SendDatagramError::ConnectionLost(_)) => {
|
||||
return Err(TransportError::Closed);
|
||||
}
|
||||
Err(err) => return Err(TransportError::Other(err.to_string())),
|
||||
}
|
||||
}
|
||||
})
|
||||
if offset == payload.len() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(TransportError::Other(
|
||||
"QUIC path needs too many fragments".into(),
|
||||
))
|
||||
}
|
||||
|
||||
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
|
||||
Box::pin(async move { self.conn.read_datagram().await.ok() })
|
||||
Box::pin(async move {
|
||||
let mut reassembly = self.reassembly.lock().await;
|
||||
loop {
|
||||
match tokio::time::timeout(DATA_REASSEMBLY_TTL, self.conn.read_datagram()).await {
|
||||
Ok(Ok(frame)) => {
|
||||
if let Some(packet) = reassembly.push(frame, tokio::time::Instant::now()) {
|
||||
return Some(packet);
|
||||
}
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
*reassembly = Reassembler::default();
|
||||
return None;
|
||||
}
|
||||
Err(_) => reassembly.expire(tokio::time::Instant::now()),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn closed(&self) -> BoxFuture<'_, ()> {
|
||||
@@ -133,12 +233,16 @@ impl PacketLink for IrohLink {
|
||||
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 {
|
||||
// Report what iroh actually knows, never a guess.
|
||||
let snapshot = crate::net::snapshot_connection(&self.conn);
|
||||
match snapshot.paths.iter().find(|path| path.is_selected) {
|
||||
Some(path) => format!("{:?} via {:?}", snapshot.transport, path.remote),
|
||||
None => format!("{:?}, no selected path yet", snapshot.transport),
|
||||
Some(path) => format!("{} via {}", snapshot.transport, path.remote),
|
||||
None => format!("{}, no selected path yet", snapshot.transport),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,11 +311,16 @@ impl IrohTransport {
|
||||
));
|
||||
}
|
||||
|
||||
let serves = self.lookup.serves(outcome.network_id, &open.protocol).await;
|
||||
let max_datagram = conn.max_datagram_size().unwrap_or(0);
|
||||
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() {
|
||||
return Err(TransportError::Other(
|
||||
"data channel has no datagram support".into(),
|
||||
));
|
||||
}
|
||||
let ack = DataOpenAck {
|
||||
accepted: serves,
|
||||
max_datagram: max_datagram as u32,
|
||||
max_datagram: MAX_DATA_DATAGRAM as u32,
|
||||
};
|
||||
write_frame(
|
||||
&mut send,
|
||||
@@ -226,7 +335,14 @@ impl IrohTransport {
|
||||
return Err(TransportError::Declined(open.protocol));
|
||||
}
|
||||
|
||||
let link = IrohLink::new(outcome.network_id, peer, conn, usize::MAX, send, recv);
|
||||
let link = IrohLink::new(
|
||||
outcome.network_id,
|
||||
peer,
|
||||
conn,
|
||||
open.max_datagram as usize,
|
||||
send,
|
||||
recv,
|
||||
);
|
||||
Ok(InboundLink {
|
||||
network: outcome.network_id,
|
||||
peer,
|
||||
@@ -257,6 +373,12 @@ impl PacketTransport for IrohTransport {
|
||||
"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
|
||||
.lookup
|
||||
.snapshot()
|
||||
@@ -289,6 +411,7 @@ impl PacketTransport for IrohTransport {
|
||||
|
||||
let open = DataOpen {
|
||||
protocol: protocol.to_string(),
|
||||
max_datagram: MAX_DATA_DATAGRAM as u32,
|
||||
};
|
||||
write_frame(
|
||||
&mut send,
|
||||
@@ -310,6 +433,12 @@ impl PacketTransport for IrohTransport {
|
||||
return Err(TransportError::Declined(protocol.to_string()));
|
||||
}
|
||||
|
||||
if ack.max_datagram == 0 || conn.max_datagram_size().is_none() {
|
||||
return Err(TransportError::Other(
|
||||
"data channel has no datagram support".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let link = IrohLink::new(network, peer, conn, ack.max_datagram as usize, send, recv);
|
||||
Ok(Arc::new(link) as SharedLink)
|
||||
})
|
||||
@@ -0,0 +1,349 @@
|
||||
//! The data plane transport boundary.
|
||||
//!
|
||||
//! This is the seam that keeps the control protocol and the data plane
|
||||
//! independent. An [`IpPlugin`] never learns how its packets are moved: it is
|
||||
//! handed a [`PacketLink`] to a peer and writes datagrams into it. Whether
|
||||
//! that link runs over iroh today, a raw UDP socket, or something else
|
||||
//! entirely tomorrow is the transport's business alone.
|
||||
//!
|
||||
//! [`IpPlugin`]: crate::dataplane::IpPlugin
|
||||
//!
|
||||
//! # Why the transport may use iroh
|
||||
//!
|
||||
//! The separation between control and data is **logical**, not a ban on
|
||||
//! sharing technology. Refusing to use iroh for data would throw away exactly
|
||||
//! what iroh is good at — hole punching a direct path between two peers behind
|
||||
//! NAT, with a relay as fallback — and force the data plane to reimplement it.
|
||||
//! So the default transport is [`iroh_link::IrohTransport`], which gives every
|
||||
//! plugin that connectivity for free.
|
||||
//!
|
||||
//! What the separation does buy is that the control protocol in
|
||||
//! [`crate::proto`] knows nothing about packets, and this module knows nothing
|
||||
//! about WireGuard. Either side can be replaced on its own.
|
||||
//!
|
||||
//! # Semantics
|
||||
//!
|
||||
//! A link is an **unreliable, unordered datagram** channel, because that is
|
||||
//! what a tunnelled UDP protocol needs: no retransmission, no head-of-line
|
||||
//! blocking, loss is normal rather than an error. It is authenticated and
|
||||
//! encrypted by the transport, and scoped to exactly one network, one peer and
|
||||
//! one plugin protocol.
|
||||
|
||||
mod fragments;
|
||||
pub(crate) mod health;
|
||||
pub mod iroh_link;
|
||||
|
||||
pub mod carrier;
|
||||
pub use carrier::{DataCarrier, SharedCarrier};
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh::EndpointId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::BoxFuture;
|
||||
use crate::identity::NetworkId;
|
||||
|
||||
/// Why a data plane link failed.
|
||||
///
|
||||
/// None of these ever stop the control plane.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum TransportError {
|
||||
/// The peer is not reachable for the data plane right now.
|
||||
#[error("peer is unreachable: {0}")]
|
||||
Unreachable(String),
|
||||
/// The peer declined to open a channel for this protocol.
|
||||
#[error("peer declined a data channel for protocol `{0}`")]
|
||||
Declined(String),
|
||||
/// The link is closed.
|
||||
#[error("data link is closed")]
|
||||
Closed,
|
||||
/// A datagram was larger than the link can carry.
|
||||
#[error("datagram of {size} bytes exceeds the {limit} byte link limit")]
|
||||
TooLarge {
|
||||
/// Size that was attempted.
|
||||
size: usize,
|
||||
/// Largest datagram this link accepts.
|
||||
limit: usize,
|
||||
},
|
||||
/// Anything else.
|
||||
#[error("data transport error: {0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// Recent observations from authenticated round trips over a physical data link.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct LinkQuality {
|
||||
/// Median round-trip time of successful probes in the window.
|
||||
pub rtt: Duration,
|
||||
/// Successful probes in the window.
|
||||
pub samples: usize,
|
||||
/// Timed-out probes in the same window.
|
||||
pub losses: usize,
|
||||
/// Receipt time of the latest successful probe.
|
||||
pub observed_at: Instant,
|
||||
}
|
||||
|
||||
impl LinkQuality {
|
||||
pub(crate) fn is_fresh(&self, now: Instant) -> bool {
|
||||
now.saturating_duration_since(self.observed_at) <= Duration::from_secs(5)
|
||||
}
|
||||
}
|
||||
|
||||
/// An authenticated datagram channel to one peer, for one plugin protocol.
|
||||
///
|
||||
/// Dropping the link closes it.
|
||||
pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
|
||||
/// The network this link belongs to.
|
||||
fn network(&self) -> NetworkId;
|
||||
|
||||
/// The authenticated peer on the other end.
|
||||
fn peer(&self) -> EndpointId;
|
||||
|
||||
/// The largest datagram this link can carry, in bytes.
|
||||
///
|
||||
/// This is the logical payload limit. A transport can fragment underneath
|
||||
/// it so path MTU changes do not force a plugin to resize the host interface.
|
||||
fn max_datagram_size(&self) -> usize;
|
||||
|
||||
/// Sends one datagram.
|
||||
///
|
||||
/// Delivery is not guaranteed. Returning `Ok` means the datagram was
|
||||
/// handed to the transport, nothing more.
|
||||
fn send(&self, payload: Bytes) -> Result<(), TransportError>;
|
||||
|
||||
/// Sends a datagram with an opaque stable flow identifier. Plugins derive
|
||||
/// this before encryption; transports that do not route can ignore it.
|
||||
fn send_flow(
|
||||
&self,
|
||||
payload: Bytes,
|
||||
_flow: super::routing::FlowId,
|
||||
) -> Result<(), TransportError> {
|
||||
self.send(payload)
|
||||
}
|
||||
|
||||
/// Receives the next datagram, or `None` once the link is finished.
|
||||
fn recv(&self) -> BoxFuture<'_, Option<Bytes>>;
|
||||
|
||||
/// Resolves once the link is closed, for whatever reason.
|
||||
fn closed(&self) -> BoxFuture<'_, ()>;
|
||||
|
||||
/// Whether the link is already closed.
|
||||
///
|
||||
/// Lets the owner notice a dead link and ask for a new one without
|
||||
/// keeping a task parked on [`PacketLink::closed`].
|
||||
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
|
||||
}
|
||||
|
||||
/// Fresh measurements from this physical link's own authenticated probes.
|
||||
fn quality(&self) -> Option<LinkQuality> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The link monitor received a timely, authenticated answer to a data probe
|
||||
/// on this very link. A carrier can use it in place of its own idle probe.
|
||||
fn confirm_delivery(&self) {}
|
||||
|
||||
/// A short description of the path in use, for diagnostics.
|
||||
///
|
||||
/// Reports what the transport actually knows. It must not invent a value.
|
||||
fn path_description(&self) -> String;
|
||||
}
|
||||
|
||||
/// A shared handle to a link.
|
||||
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.
|
||||
#[derive(Debug)]
|
||||
pub struct InboundLink {
|
||||
/// The network it belongs to.
|
||||
pub network: NetworkId,
|
||||
/// The peer that opened it.
|
||||
pub peer: EndpointId,
|
||||
/// The plugin protocol it carries.
|
||||
pub protocol: String,
|
||||
/// The link itself.
|
||||
pub link: SharedLink,
|
||||
}
|
||||
|
||||
/// Opens and accepts data plane links.
|
||||
///
|
||||
/// The agent owns one of these and hands links to plugins; plugins never call
|
||||
/// it directly.
|
||||
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.
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// Lets the agent recover the concrete transport to drive its accept side.
|
||||
///
|
||||
/// Accepting is inherently transport-specific — it starts from whatever
|
||||
/// the transport's own listener produced — so it is not part of this
|
||||
/// trait's uniform interface.
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
|
||||
/// Opens a link to `peer` in `network` for `protocol`.
|
||||
fn open<'a>(
|
||||
&'a self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: &'a str,
|
||||
) -> BoxFuture<'a, Result<SharedLink, TransportError>>;
|
||||
}
|
||||
|
||||
/// A composite packet transport that dispatches requests by protocol id.
|
||||
#[derive(Debug)]
|
||||
pub struct MultiPacketTransport {
|
||||
default: Arc<dyn PacketTransport>,
|
||||
by_protocol: std::collections::HashMap<String, Arc<dyn PacketTransport>>,
|
||||
}
|
||||
|
||||
impl MultiPacketTransport {
|
||||
/// Creates a new composite transport with a default fallback transport.
|
||||
pub fn new(
|
||||
default: Arc<dyn PacketTransport>,
|
||||
by_protocol: std::collections::HashMap<String, Arc<dyn PacketTransport>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
default,
|
||||
by_protocol,
|
||||
}
|
||||
}
|
||||
|
||||
/// Access the default underlying transport.
|
||||
pub fn default_transport(&self) -> &Arc<dyn PacketTransport> {
|
||||
&self.default
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
"multi"
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn open<'a>(
|
||||
&'a self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: &'a str,
|
||||
) -> BoxFuture<'a, Result<SharedLink, TransportError>> {
|
||||
if let Some(transport) = self.by_protocol.get(protocol) {
|
||||
transport.open(network, peer, protocol)
|
||||
} else {
|
||||
self.default.open(network, peer, protocol)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,7 @@
|
||||
//!
|
||||
//! * *Finding members of a network* — [`NetworkDiscovery::resolve`], keyed by
|
||||
//! the secret-derived [`DiscoveryKey`]. That is what lives here, and today
|
||||
//! it is [`StaticBootstrap`] plus a test backend; a DHT backend is future
|
||||
//! work.
|
||||
//! it includes [`StaticBootstrap`], [`MainlineDiscovery`] and a test backend.
|
||||
//! * *Resolving the address of one iroh endpoint* — **iroh's job, not ours**.
|
||||
//! With [`crate::config::TransportPolicy::N0Defaults`] or `DirectOnly`, iroh
|
||||
//! publishes and resolves endpoint addresses through Number 0's public
|
||||
@@ -23,14 +22,18 @@
|
||||
//! No empty result ever proves a network is empty. It only means "nobody found
|
||||
//! yet".
|
||||
//!
|
||||
//! Mainline DHT discovery is future work and is not implemented here.
|
||||
//! Mainline rendezvous is opt-in for library callers; the command line enables it.
|
||||
|
||||
mod mainline;
|
||||
pub(crate) mod worker;
|
||||
pub use mainline::MainlineDiscovery;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use iroh::{EndpointAddr, EndpointId};
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::DiscoveryKey;
|
||||
|
||||
pub use crate::BoxFuture;
|
||||
@@ -44,6 +47,18 @@ pub enum CandidateSource {
|
||||
Discovery,
|
||||
/// An address hint restored from the disposable cache.
|
||||
Cache,
|
||||
/// An author of a signed record: somebody who belongs to this network,
|
||||
/// learned from state that reached us through anybody.
|
||||
///
|
||||
/// It carries no address of its own — the endpoint's own discovery has
|
||||
/// to resolve it — but knowing that a member exists is what turns a
|
||||
/// star around whoever was named on the command line into a mesh.
|
||||
Member,
|
||||
/// Passed on by a member we are talking to.
|
||||
///
|
||||
/// A candidate like any other: an introduction is not a vouching, and
|
||||
/// membership is still decided by the handshake.
|
||||
Introduced,
|
||||
}
|
||||
|
||||
/// An unverified candidate peer.
|
||||
@@ -91,6 +106,23 @@ pub trait NetworkDiscovery: Send + Sync + std::fmt::Debug + 'static {
|
||||
|
||||
/// Returns the candidates currently known for `key`.
|
||||
fn resolve<'a>(&'a self, key: DiscoveryKey) -> BoxFuture<'a, Result<Vec<Candidate>>>;
|
||||
|
||||
/// Delivers candidates as they arrive. The default adapts a batch backend;
|
||||
/// remote backends can override this so the first dial need not wait for all lookups.
|
||||
fn resolve_into<'a>(
|
||||
&'a self,
|
||||
key: DiscoveryKey,
|
||||
candidates: tokio::sync::mpsc::Sender<Candidate>,
|
||||
) -> BoxFuture<'a, Result<()>> {
|
||||
Box::pin(async move {
|
||||
for candidate in self.resolve(key).await? {
|
||||
if candidates.send(candidate).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A statically configured list of bootstrap candidates.
|
||||
@@ -261,13 +293,25 @@ impl NetworkDiscovery for CompositeDiscovery {
|
||||
|
||||
fn publish<'a>(&'a self, key: DiscoveryKey, addr: EndpointAddr) -> BoxFuture<'a, Result<()>> {
|
||||
Box::pin(async move {
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
for backend in &self.backends {
|
||||
// One failing backend must not stop the others.
|
||||
if let Err(err) = backend.publish(key, addr.clone()).await {
|
||||
tracing::debug!(backend = backend.name(), %err, "publish failed");
|
||||
let backend = backend.clone();
|
||||
let addr = addr.clone();
|
||||
tasks.spawn(async move { backend.publish(key, addr).await });
|
||||
}
|
||||
let mut failed = false;
|
||||
while let Some(result) = tasks.join_next().await {
|
||||
if !matches!(result, Ok(Ok(()))) {
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
if failed {
|
||||
Err(Error::Discovery(
|
||||
"a discovery publication failed; will retry".into(),
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -277,11 +321,12 @@ impl NetworkDiscovery for CompositeDiscovery {
|
||||
endpoint: EndpointId,
|
||||
) -> BoxFuture<'a, Result<()>> {
|
||||
Box::pin(async move {
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
for backend in &self.backends {
|
||||
if let Err(err) = backend.unpublish(key, endpoint).await {
|
||||
tracing::debug!(backend = backend.name(), %err, "unpublish failed");
|
||||
}
|
||||
let backend = backend.clone();
|
||||
tasks.spawn(async move { backend.unpublish(key, endpoint).await });
|
||||
}
|
||||
while tasks.join_next().await.is_some() {}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -300,4 +345,25 @@ impl NetworkDiscovery for CompositeDiscovery {
|
||||
Ok(out)
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_into<'a>(
|
||||
&'a self,
|
||||
key: DiscoveryKey,
|
||||
candidates: tokio::sync::mpsc::Sender<Candidate>,
|
||||
) -> BoxFuture<'a, Result<()>> {
|
||||
Box::pin(async move {
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
for backend in &self.backends {
|
||||
let backend = backend.clone();
|
||||
let candidates = candidates.clone();
|
||||
tasks.spawn(async move {
|
||||
if let Err(err) = backend.resolve_into(key, candidates).await {
|
||||
tracing::debug!(backend = backend.name(), %err, "resolve failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
while tasks.join_next().await.is_some() {}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
//! Mainline BEP44 rendezvous. Slots are a changing sample, not a membership list.
|
||||
|
||||
use ::mainline::{Dht, MutableItem, SigningKey, async_dht::AsyncDht};
|
||||
use futures_lite::StreamExt;
|
||||
use iroh::{EndpointAddr, EndpointId};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::sync::{Mutex as AsyncMutex, mpsc};
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::timeout;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{BoxFuture, Candidate, CandidateSource, NetworkDiscovery};
|
||||
use crate::config::{
|
||||
DHT_CLOCK_SKEW, DHT_MAX_ADDRS, DHT_MAX_RELAY_LEN, DHT_MAX_VALUE, DHT_RECORD_TTL, DHT_SLOTS,
|
||||
};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::{DiscoveryKey, NetworkKeys};
|
||||
|
||||
const QUERY_TIMEOUT: Duration = Duration::from_secs(8);
|
||||
const MAGIC: &[u8; 5] = b"TSND\x01";
|
||||
|
||||
/// One lazily started Mainline client, shared by all networks on one agent.
|
||||
/// No socket is opened until an active network publishes or looks up candidates.
|
||||
/// Agent shutdown closes this client and all its clones; a new agent needs a new client.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MainlineDiscovery {
|
||||
client: Arc<AsyncMutex<ClientState>>,
|
||||
allow_loopback: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
enum ClientState {
|
||||
#[default]
|
||||
Pending,
|
||||
Ready(AsyncDht),
|
||||
Stopped,
|
||||
}
|
||||
|
||||
impl MainlineDiscovery {
|
||||
/// Uses a caller-supplied Mainline node instead of public bootstrap defaults.
|
||||
pub fn from_dht(dht: Dht) -> Self {
|
||||
Self {
|
||||
client: Arc::new(AsyncMutex::new(ClientState::Ready(dht.as_async()))),
|
||||
allow_loopback: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a loopback-only client for a local Mainline Testnet.
|
||||
#[cfg(feature = "testing")]
|
||||
pub fn local_testnet(bootstrap: &[String]) -> Result<Self> {
|
||||
// Reject anything that could resolve or send outside loopback.
|
||||
if bootstrap.is_empty()
|
||||
|| bootstrap.iter().any(|s| {
|
||||
s.parse::<SocketAddr>()
|
||||
.map_or(true, |a| !a.ip().is_loopback())
|
||||
})
|
||||
{
|
||||
return Err(Error::Discovery(
|
||||
"test bootstrap must contain loopback sockets".into(),
|
||||
));
|
||||
}
|
||||
let dht = Dht::builder()
|
||||
.bootstrap(bootstrap)
|
||||
.bind_address(Ipv4Addr::LOCALHOST)
|
||||
.port(0)
|
||||
.request_timeout(Duration::from_millis(200))
|
||||
.build()
|
||||
.map_err(|_| Error::Discovery("cannot bind local DHT".into()))?;
|
||||
Ok(Self {
|
||||
allow_loopback: true,
|
||||
..Self::from_dht(dht)
|
||||
})
|
||||
}
|
||||
|
||||
/// Binds this client's rendezvous backend to one network's independent keys.
|
||||
pub fn for_network(&self, keys: &NetworkKeys) -> Arc<dyn NetworkDiscovery> {
|
||||
Arc::new(NetworkDht {
|
||||
client: self.clone(),
|
||||
key: keys.discovery_key(),
|
||||
seed: Zeroizing::new(*keys.dht_write_key()),
|
||||
observed: Mutex::new(VecDeque::new()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn client(&self) -> Result<AsyncDht> {
|
||||
let mut client = self.client.lock().await;
|
||||
match &*client {
|
||||
ClientState::Ready(dht) => return Ok(dht.clone()),
|
||||
ClientState::Stopped => return Err(Error::Discovery("DHT client is stopped".into())),
|
||||
ClientState::Pending => {}
|
||||
}
|
||||
// Construction may resolve bootstrap hostnames. Keep it off Tokio's
|
||||
// executor; a construction failure is retried on the next operation.
|
||||
let dht = tokio::task::spawn_blocking(|| Dht::builder().port(0).build())
|
||||
.await
|
||||
.map_err(|_| Error::Discovery("DHT startup task failed".into()))?
|
||||
.map(Dht::as_async)
|
||||
.map_err(|_| Error::Discovery("cannot start DHT client".into()))?;
|
||||
*client = ClientState::Ready(dht.clone());
|
||||
Ok(dht)
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
*self.client.lock().await = ClientState::Stopped;
|
||||
}
|
||||
}
|
||||
|
||||
struct NetworkDht {
|
||||
client: MainlineDiscovery,
|
||||
key: DiscoveryKey,
|
||||
seed: Zeroizing<[u8; 32]>,
|
||||
// Records encountered while publishing. Only an explicit lookup consumes
|
||||
// these hints: publication never causes dials on a connected network.
|
||||
observed: Mutex<VecDeque<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NetworkDht {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("NetworkDht(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
fn salt(slot: u8) -> Vec<u8> {
|
||||
let mut salt = b"tsunagi-rendezvous-v1".to_vec();
|
||||
salt.push(slot);
|
||||
salt
|
||||
}
|
||||
|
||||
fn slots_for(id: EndpointId) -> [u8; 2] {
|
||||
let hash = Sha256::digest(id.as_bytes());
|
||||
let first = hash[0] % DHT_SLOTS;
|
||||
[first, (first + 1 + hash[1] % (DHT_SLOTS - 1)) % DHT_SLOTS]
|
||||
}
|
||||
|
||||
fn now() -> Result<u64> {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.map_err(|_| Error::Discovery("system clock predates Unix epoch".into()))
|
||||
}
|
||||
|
||||
impl NetworkDht {
|
||||
async fn publish_slot(&self, dht: &AsyncDht, slot: u8, value: &[u8]) -> Result<()> {
|
||||
let salt = salt(slot);
|
||||
let signer = SigningKey::from_bytes(&self.seed);
|
||||
let public = signer.verifying_key().to_bytes();
|
||||
for attempt in 0..3 {
|
||||
let recent = timeout(
|
||||
QUERY_TIMEOUT,
|
||||
dht.get_mutable_most_recent(&public, Some(&salt)),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::Discovery("DHT read timed out".into()))?;
|
||||
if let Some(item) = &recent
|
||||
&& item.value().len() <= DHT_MAX_VALUE
|
||||
&& let Ok(mut observed) = self.observed.lock()
|
||||
{
|
||||
if observed.len() == DHT_SLOTS as usize {
|
||||
observed.pop_front();
|
||||
}
|
||||
observed.push_back(item.value().to_vec());
|
||||
}
|
||||
let seq = recent
|
||||
.as_ref()
|
||||
.map_or(0, MutableItem::seq)
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| Error::Discovery("DHT sequence exhausted".into()))?;
|
||||
let item = MutableItem::new(signer.clone(), value, seq, Some(&salt));
|
||||
match timeout(
|
||||
QUERY_TIMEOUT,
|
||||
dht.put_mutable(item, recent.as_ref().map(MutableItem::seq)),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(outcome)) if outcome.stored_at > 0 => return Ok(()),
|
||||
_ if attempt < 2 => {
|
||||
// CAS is per storage node, not a global lock. Read again on
|
||||
// conflicts; another writer's entry is an acceptable sample.
|
||||
tokio::time::sleep(Duration::from_millis(rand::random_range(30..150))).await;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
Err(Error::Discovery(
|
||||
"DHT publication was not acknowledged".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkDiscovery for NetworkDht {
|
||||
fn name(&self) -> &str {
|
||||
"mainline"
|
||||
}
|
||||
|
||||
fn publish<'a>(&'a self, key: DiscoveryKey, addr: EndpointAddr) -> BoxFuture<'a, Result<()>> {
|
||||
Box::pin(async move {
|
||||
if key != self.key {
|
||||
return Err(Error::Discovery("wrong rendezvous network".into()));
|
||||
}
|
||||
let value = encode_record(&addr, now()?, self.client.allow_loopback)?;
|
||||
let dht = self.client.client().await?;
|
||||
let [first, second] = slots_for(addr.id);
|
||||
let (a, b) = tokio::join!(
|
||||
self.publish_slot(&dht, first, &value),
|
||||
self.publish_slot(&dht, second, &value)
|
||||
);
|
||||
a.and(b)
|
||||
})
|
||||
}
|
||||
|
||||
fn unpublish<'a>(&'a self, _: DiscoveryKey, _: EndpointId) -> BoxFuture<'a, Result<()>> {
|
||||
// Stopping publication lets freshness expire. Deleting a shared slot
|
||||
// could erase a different writer, and BEP44 has no delete operation.
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn resolve<'a>(&'a self, key: DiscoveryKey) -> BoxFuture<'a, Result<Vec<Candidate>>> {
|
||||
Box::pin(async move {
|
||||
let (tx, mut rx) = mpsc::channel(DHT_SLOTS as usize);
|
||||
let collect = async move {
|
||||
let mut found = Vec::new();
|
||||
while let Some(candidate) = rx.recv().await {
|
||||
found.push(candidate);
|
||||
}
|
||||
found
|
||||
};
|
||||
let (result, found) = tokio::join!(self.resolve_into(key, tx), collect);
|
||||
result?;
|
||||
Ok(found)
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_into<'a>(
|
||||
&'a self,
|
||||
key: DiscoveryKey,
|
||||
candidates: mpsc::Sender<Candidate>,
|
||||
) -> BoxFuture<'a, Result<()>> {
|
||||
Box::pin(async move {
|
||||
if key != self.key {
|
||||
return Err(Error::Discovery("wrong rendezvous network".into()));
|
||||
}
|
||||
let dht = self.client.client().await?;
|
||||
let public = SigningKey::from_bytes(&self.seed)
|
||||
.verifying_key()
|
||||
.to_bytes();
|
||||
let observed = self
|
||||
.observed
|
||||
.lock()
|
||||
.map(|mut values| std::mem::take(&mut *values))
|
||||
.unwrap_or_default();
|
||||
let mut seen = HashSet::new();
|
||||
for value in observed {
|
||||
if let Some(addr) = decode_record(&value, now()?, self.client.allow_loopback)
|
||||
&& seen.insert(addr.id)
|
||||
&& candidates
|
||||
.send(Candidate::new(addr, CandidateSource::Discovery))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let mut slots: Vec<_> = (0..DHT_SLOTS).collect();
|
||||
for i in (1..slots.len()).rev() {
|
||||
slots.swap(i, rand::random_range(0..=i));
|
||||
}
|
||||
let mut queries = JoinSet::new();
|
||||
loop {
|
||||
if seen.len() >= DHT_SLOTS as usize {
|
||||
break;
|
||||
}
|
||||
while queries.len() < 4 {
|
||||
let Some(slot) = slots.pop() else {
|
||||
break;
|
||||
};
|
||||
let dht = dht.clone();
|
||||
let allow_loopback = self.client.allow_loopback;
|
||||
queries.spawn(async move {
|
||||
timeout(QUERY_TIMEOUT, async move {
|
||||
let salt = salt(slot);
|
||||
let target = MutableItem::target_from_key(&public, Some(&salt));
|
||||
let mut items = dht.get_mutable(&public, Some(&salt), None);
|
||||
while let Some(item) = items.next().await {
|
||||
// Mainline verifies the signature; also bind the
|
||||
// returned item to the key and slot we requested.
|
||||
if item.key() != &public || item.target() != &target {
|
||||
continue;
|
||||
}
|
||||
if let Some(addr) =
|
||||
decode_record(item.value(), now().ok()?, allow_loopback)
|
||||
{
|
||||
return Some(addr);
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
});
|
||||
}
|
||||
let Some(result) = queries.join_next().await else {
|
||||
break;
|
||||
};
|
||||
if let Ok(Some(addr)) = result
|
||||
&& seen.insert(addr.id)
|
||||
&& candidates
|
||||
.send(Candidate::new(addr, CandidateSource::Discovery))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn usable(addr: &SocketAddr, allow_loopback: bool) -> bool {
|
||||
addr.port() != 0
|
||||
&& !addr.ip().is_unspecified()
|
||||
&& !addr.ip().is_multicast()
|
||||
&& (allow_loopback || !addr.ip().is_loopback())
|
||||
&& match addr.ip() {
|
||||
IpAddr::V4(ip) => !ip.is_broadcast() && !ip.is_link_local(),
|
||||
IpAddr::V6(ip) => !ip.is_unicast_link_local(),
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_record(addr: &EndpointAddr, timestamp: u64, allow_loopback: bool) -> Result<Vec<u8>> {
|
||||
let ips: Vec<_> = addr
|
||||
.ip_addrs()
|
||||
.filter(|ip| usable(ip, allow_loopback))
|
||||
.take(DHT_MAX_ADDRS)
|
||||
.collect();
|
||||
let relay = addr
|
||||
.relay_urls()
|
||||
.next()
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default();
|
||||
if relay.len() > DHT_MAX_RELAY_LEN || (ips.is_empty() && relay.is_empty()) {
|
||||
return Err(Error::Discovery("no encodable endpoint address yet".into()));
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(DHT_MAX_VALUE);
|
||||
bytes.extend_from_slice(MAGIC);
|
||||
bytes.extend_from_slice(×tamp.to_be_bytes());
|
||||
bytes.extend_from_slice(addr.id.as_bytes());
|
||||
bytes.extend_from_slice(&(relay.len() as u16).to_be_bytes());
|
||||
bytes.extend_from_slice(relay.as_bytes());
|
||||
bytes.push(ips.len() as u8);
|
||||
for ip in ips {
|
||||
match ip.ip() {
|
||||
IpAddr::V4(v) => {
|
||||
bytes.push(4);
|
||||
bytes.extend_from_slice(&v.octets());
|
||||
}
|
||||
IpAddr::V6(v) => {
|
||||
bytes.push(6);
|
||||
bytes.extend_from_slice(&v.octets());
|
||||
}
|
||||
}
|
||||
bytes.extend_from_slice(&ip.port().to_be_bytes());
|
||||
}
|
||||
if bytes.len() > DHT_MAX_VALUE {
|
||||
return Err(Error::Discovery("DHT record too large".into()));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn take<'a>(input: &mut &'a [u8], n: usize) -> Option<&'a [u8]> {
|
||||
let (head, rest) = input.split_at_checked(n)?;
|
||||
*input = rest;
|
||||
Some(head)
|
||||
}
|
||||
|
||||
fn decode_record(mut bytes: &[u8], now: u64, allow_loopback: bool) -> Option<EndpointAddr> {
|
||||
if bytes.len() > DHT_MAX_VALUE || take(&mut bytes, MAGIC.len())? != MAGIC {
|
||||
return None;
|
||||
}
|
||||
let timestamp = u64::from_be_bytes(take(&mut bytes, 8)?.try_into().ok()?);
|
||||
if timestamp > now.saturating_add(DHT_CLOCK_SKEW.as_secs())
|
||||
|| now.saturating_sub(timestamp) >= DHT_RECORD_TTL.as_secs()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let id = EndpointId::from_bytes(take(&mut bytes, 32)?.try_into().ok()?).ok()?;
|
||||
let mut addr = EndpointAddr::new(id);
|
||||
let len = u16::from_be_bytes(take(&mut bytes, 2)?.try_into().ok()?) as usize;
|
||||
if len > DHT_MAX_RELAY_LEN {
|
||||
return None;
|
||||
}
|
||||
let relay = std::str::from_utf8(take(&mut bytes, len)?).ok()?;
|
||||
if !relay.is_empty() {
|
||||
addr = addr.with_relay_url(relay.parse().ok()?);
|
||||
}
|
||||
let count = *take(&mut bytes, 1)?.first()? as usize;
|
||||
if count > DHT_MAX_ADDRS {
|
||||
return None;
|
||||
}
|
||||
for _ in 0..count {
|
||||
let ip = match *take(&mut bytes, 1)?.first()? {
|
||||
4 => IpAddr::V4(Ipv4Addr::from(
|
||||
<[u8; 4]>::try_from(take(&mut bytes, 4)?).ok()?,
|
||||
)),
|
||||
6 => IpAddr::V6(Ipv6Addr::from(
|
||||
<[u8; 16]>::try_from(take(&mut bytes, 16)?).ok()?,
|
||||
)),
|
||||
_ => return None,
|
||||
};
|
||||
let port = u16::from_be_bytes(take(&mut bytes, 2)?.try_into().ok()?);
|
||||
let socket = SocketAddr::new(ip, port);
|
||||
if usable(&socket, allow_loopback) {
|
||||
addr = addr.with_ip_addr(socket);
|
||||
}
|
||||
}
|
||||
(bytes.is_empty() && !addr.addrs.is_empty()).then_some(addr)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use crate::testing::network;
|
||||
|
||||
fn address() -> EndpointAddr {
|
||||
EndpointAddr::new(iroh::SecretKey::generate().public())
|
||||
.with_ip_addr("127.0.0.1:12345".parse().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_reject_expiration_future_dates_truncation_and_oversize() {
|
||||
let addr = address();
|
||||
let bytes = encode_record(&addr, 1_000, true).unwrap();
|
||||
assert_eq!(decode_record(&bytes, 1_100, true).unwrap(), addr);
|
||||
assert!(decode_record(&bytes, 1_901, true).is_none());
|
||||
assert!(decode_record(&bytes, 100, true).is_none());
|
||||
for n in 0..bytes.len() {
|
||||
assert!(decode_record(&bytes[..n], 1_100, true).is_none());
|
||||
}
|
||||
assert!(decode_record(&vec![0; DHT_MAX_VALUE + 1], 1_100, true).is_none());
|
||||
assert!(encode_record(&addr, 1_000, false).is_err());
|
||||
assert!(decode_record(&bytes, 1_100, false).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stopped_custom_client_never_falls_back_to_public_bootstrap() {
|
||||
let net = mainline::Testnet::builder(3).build().unwrap();
|
||||
let client = MainlineDiscovery::local_testnet(&net.bootstrap).unwrap();
|
||||
let (name, secret) = network("mainline-shutdown");
|
||||
let keys = NetworkKeys::derive(&name, &secret);
|
||||
let backend = client.for_network(&keys);
|
||||
client.shutdown().await;
|
||||
assert!(backend.resolve(keys.discovery_key()).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_writers_share_slots_and_other_secrets_find_nothing() {
|
||||
let net = mainline::Testnet::builder(5).build().unwrap();
|
||||
let client_a = MainlineDiscovery::local_testnet(&net.bootstrap).unwrap();
|
||||
let client_b = MainlineDiscovery::local_testnet(&net.bootstrap).unwrap();
|
||||
let (name, secret) = network("mainline-slots");
|
||||
let keys = NetworkKeys::derive(&name, &secret);
|
||||
let a = client_a.for_network(&keys);
|
||||
let b = client_b.for_network(&keys);
|
||||
let first = address();
|
||||
let second = loop {
|
||||
let next = address();
|
||||
if slots_for(next.id) == slots_for(first.id) {
|
||||
break next;
|
||||
}
|
||||
};
|
||||
let key = keys.discovery_key();
|
||||
let (ra, rb) = tokio::join!(
|
||||
a.publish(key, first.clone()),
|
||||
b.publish(key, second.clone())
|
||||
);
|
||||
assert!(ra.is_ok() || rb.is_ok());
|
||||
let (found_a, found_b) = tokio::join!(a.resolve(key), b.resolve(key));
|
||||
let found_a = found_a.unwrap();
|
||||
let found_b = found_b.unwrap();
|
||||
assert!(
|
||||
found_a.iter().any(|c| c.addr == second) || found_b.iter().any(|c| c.addr == first),
|
||||
"at least one writer must discover the other despite colliding in both slots"
|
||||
);
|
||||
assert!(
|
||||
found_a
|
||||
.iter()
|
||||
.chain(&found_b)
|
||||
.all(|c| c.addr == first || c.addr == second)
|
||||
);
|
||||
let other = NetworkKeys::derive(&name, &crate::identity::NetworkSecret::generate());
|
||||
assert!(
|
||||
client_a
|
||||
.for_network(&other)
|
||||
.resolve(other.discovery_key())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
// Restarting the publisher must read seq from DHT instead of starting at 1.
|
||||
let restarted = client_a.for_network(&keys);
|
||||
restarted.publish(key, first.clone()).await.unwrap();
|
||||
assert!(
|
||||
b.resolve(key)
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|c| c.addr == first)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Per-network discovery tasks. Dropping the owner cancels all backend futures.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::{Instant, timeout};
|
||||
|
||||
use super::{Candidate, NetworkDiscovery};
|
||||
use crate::config::DiscoveryPolicy;
|
||||
use crate::identity::DiscoveryKey;
|
||||
use crate::net::EndpointAdapter;
|
||||
|
||||
pub(crate) struct DiscoveryWorker {
|
||||
connected: watch::Sender<Connectivity>,
|
||||
tasks: JoinSet<()>,
|
||||
backend: Arc<dyn NetworkDiscovery>,
|
||||
key: DiscoveryKey,
|
||||
endpoint: iroh::EndpointId,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Connectivity {
|
||||
Initial,
|
||||
Connected,
|
||||
Isolated(Instant),
|
||||
}
|
||||
|
||||
impl DiscoveryWorker {
|
||||
pub(crate) fn spawn(
|
||||
backend: Arc<dyn NetworkDiscovery>,
|
||||
key: DiscoveryKey,
|
||||
adapter: EndpointAdapter,
|
||||
policy: DiscoveryPolicy,
|
||||
address_check: Duration,
|
||||
candidates: mpsc::Sender<Candidate>,
|
||||
) -> Self {
|
||||
let (connected, receiver) = watch::channel(Connectivity::Initial);
|
||||
let mut tasks = JoinSet::new();
|
||||
tasks.spawn(publish_loop(
|
||||
backend.clone(),
|
||||
key,
|
||||
adapter.clone(),
|
||||
policy.clone(),
|
||||
address_check,
|
||||
));
|
||||
tasks.spawn(lookup_loop(
|
||||
backend.clone(),
|
||||
key,
|
||||
policy,
|
||||
receiver,
|
||||
candidates,
|
||||
));
|
||||
Self {
|
||||
connected,
|
||||
tasks,
|
||||
backend,
|
||||
key,
|
||||
endpoint: adapter.endpoint_id(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_connected(&self, connected: bool) {
|
||||
self.connected.send_if_modified(|current| {
|
||||
if matches!(*current, Connectivity::Connected) == connected {
|
||||
return false;
|
||||
}
|
||||
*current = if connected {
|
||||
Connectivity::Connected
|
||||
} else {
|
||||
Connectivity::Isolated(Instant::now())
|
||||
};
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(mut self) {
|
||||
self.tasks.abort_all();
|
||||
while self.tasks.join_next().await.is_some() {}
|
||||
// BEP44 has no deletion. Memory/static backends can withdraw promptly;
|
||||
// an unresponsive backend must not extend agent shutdown.
|
||||
let _ = timeout(
|
||||
Duration::from_millis(250),
|
||||
self.backend.unpublish(self.key, self.endpoint),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
fn jitter(delay: Duration) -> Duration {
|
||||
delay
|
||||
.mul_f64(0.8 + 0.4 * rand::random::<f64>())
|
||||
.max(Duration::from_millis(10))
|
||||
}
|
||||
|
||||
async fn publish_loop(
|
||||
backend: Arc<dyn NetworkDiscovery>,
|
||||
key: DiscoveryKey,
|
||||
adapter: EndpointAdapter,
|
||||
policy: DiscoveryPolicy,
|
||||
address_check: Duration,
|
||||
) {
|
||||
let mut previous = None;
|
||||
let mut due = Instant::now();
|
||||
let mut ticker = tokio::time::interval(address_check.max(Duration::from_millis(10)));
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
let mut addr = adapter.addr();
|
||||
addr.addrs.extend(adapter.loopback_addr().addrs);
|
||||
if previous.as_ref() != Some(&addr) {
|
||||
previous = Some(addr.clone());
|
||||
due = Instant::now();
|
||||
}
|
||||
if Instant::now() < due {
|
||||
continue;
|
||||
}
|
||||
let result = timeout(policy.request_timeout, backend.publish(key, addr.clone())).await;
|
||||
match result {
|
||||
Ok(Ok(())) => {
|
||||
due = Instant::now() + jitter(policy.publish_interval);
|
||||
}
|
||||
result => {
|
||||
tracing::debug!(?result, "discovery publication failed; will retry");
|
||||
due = Instant::now() + jitter(policy.lookup_interval);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn lookup_loop(
|
||||
backend: Arc<dyn NetworkDiscovery>,
|
||||
key: DiscoveryKey,
|
||||
policy: DiscoveryPolicy,
|
||||
mut connected: watch::Receiver<Connectivity>,
|
||||
candidates: mpsc::Sender<Candidate>,
|
||||
) {
|
||||
let mut last_isolation = None;
|
||||
let mut due = Instant::now();
|
||||
let mut delay = policy.lookup_interval;
|
||||
loop {
|
||||
let state = *connected.borrow_and_update();
|
||||
if matches!(state, Connectivity::Connected) {
|
||||
if connected.changed().await.is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Connectivity::Isolated(since) = state
|
||||
&& last_isolation != Some(since)
|
||||
{
|
||||
// Preserve the transition time even if a rapid reconnect/disconnect
|
||||
// overwrote a watch value before this task had a chance to run.
|
||||
due = since + policy.reconnect_delay;
|
||||
delay = policy.lookup_interval;
|
||||
last_isolation = Some(since);
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
changed = connected.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
continue;
|
||||
}
|
||||
_ = tokio::time::sleep_until(due) => {}
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
changed = connected.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
continue;
|
||||
}
|
||||
result = timeout(policy.request_timeout, backend.resolve_into(key, candidates.clone())) => {
|
||||
if !matches!(result, Ok(Ok(()))) {
|
||||
tracing::debug!(?result, "discovery lookup failed; will retry");
|
||||
}
|
||||
}
|
||||
}
|
||||
due = Instant::now() + jitter(delay);
|
||||
delay = delay.saturating_mul(2).min(policy.max_lookup_interval);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use crate::Result;
|
||||
use crate::discovery::BoxFuture;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Reads(AtomicUsize);
|
||||
impl NetworkDiscovery for Reads {
|
||||
fn name(&self) -> &str {
|
||||
"reads"
|
||||
}
|
||||
fn publish<'a>(
|
||||
&'a self,
|
||||
_: DiscoveryKey,
|
||||
_: iroh::EndpointAddr,
|
||||
) -> BoxFuture<'a, Result<()>> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
fn unpublish<'a>(
|
||||
&'a self,
|
||||
_: DiscoveryKey,
|
||||
_: iroh::EndpointId,
|
||||
) -> BoxFuture<'a, Result<()>> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
fn resolve<'a>(&'a self, _: DiscoveryKey) -> BoxFuture<'a, Result<Vec<Candidate>>> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Box::pin(async { Ok(Vec::new()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn recovery_requires_a_full_minute_and_reconnection_restarts_that_minute() {
|
||||
let reads = Arc::new(Reads::default());
|
||||
let (tx, rx) = watch::channel(Connectivity::Connected);
|
||||
let (candidates, _receiver) = mpsc::channel(16);
|
||||
let mut tasks = JoinSet::new();
|
||||
tasks.spawn(lookup_loop(
|
||||
reads.clone(),
|
||||
DiscoveryKey::from_bytes([0; 32]),
|
||||
DiscoveryPolicy::default(),
|
||||
rx,
|
||||
candidates,
|
||||
));
|
||||
tokio::task::yield_now().await;
|
||||
tx.send(Connectivity::Isolated(Instant::now())).unwrap();
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(Duration::from_secs(59)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(reads.0.load(Ordering::SeqCst), 0);
|
||||
tx.send(Connectivity::Connected).unwrap();
|
||||
tx.send(Connectivity::Isolated(Instant::now())).unwrap();
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(Duration::from_secs(59)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(reads.0.load(Ordering::SeqCst), 0);
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(reads.0.load(Ordering::SeqCst), 1);
|
||||
tx.send(Connectivity::Connected).unwrap();
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(Duration::from_secs(600)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(reads.0.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//! A DNS view of the overlay.
|
||||
//!
|
||||
//! The names and addresses of a network, served to the host that runs the
|
||||
//! agent, so members can be reached by name. Answered from signed state, so a
|
||||
//! member that is switched off still resolves.
|
||||
//!
|
||||
//! Three parts, kept apart on purpose:
|
||||
//!
|
||||
//! * [`zone`] decides what the answer is. Pure, and knows nothing about
|
||||
//! packets or sockets.
|
||||
//! * [`server`] puts that on the wire.
|
||||
//! * `publish` tells the operating system where to send its questions,
|
||||
//! which is the only part that differs between platforms.
|
||||
|
||||
pub mod publish;
|
||||
pub mod server;
|
||||
pub mod zone;
|
||||
|
||||
pub use publish::{DnsPublisher, PublishError, Published};
|
||||
|
||||
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||
|
||||
/// Where the server listens, one list per address family.
|
||||
///
|
||||
/// Loopback, and only loopback. The zones are a view *for the host running
|
||||
/// the agent*: it is that host's resolver that is pointed at them. Binding
|
||||
/// an overlay address instead would put them in front of the whole mesh —
|
||||
/// and an agent in several networks would then answer one network's
|
||||
/// questions about another's names, which is precisely what separate
|
||||
/// networks are for.
|
||||
///
|
||||
/// Both families, and independently: a question arrives over whichever one
|
||||
/// the resolver happens to use, and on a host with one of them switched off
|
||||
/// the other must still answer. So neither list failing says anything about
|
||||
/// the other, and a listener is opened from each.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ListenPlan {
|
||||
/// IPv4 candidates, best first.
|
||||
pub v4: Vec<SocketAddr>,
|
||||
/// IPv6 candidates, best first.
|
||||
pub v6: Vec<SocketAddr>,
|
||||
}
|
||||
|
||||
impl ListenPlan {
|
||||
/// The two lists, so a caller can bind one listener from each.
|
||||
pub fn families(&self) -> [&[SocketAddr]; 2] {
|
||||
[&self.v4, &self.v6]
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the listen plan for one port.
|
||||
pub fn listen_plan(port: u16) -> ListenPlan {
|
||||
ListenPlan {
|
||||
v4: vec![SocketAddr::from((Ipv4Addr::LOCALHOST, port))],
|
||||
v6: vec![SocketAddr::from((Ipv6Addr::LOCALHOST, port))],
|
||||
}
|
||||
}
|
||||
|
||||
pub use server::{DnsServer, SharedZone};
|
||||
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)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn both_families_are_planned_for_and_neither_is_reachable_off_this_host() {
|
||||
let plan = listen_plan(5354);
|
||||
assert_eq!(
|
||||
plan.v4,
|
||||
vec!["127.0.0.1:5354".parse::<SocketAddr>().unwrap()]
|
||||
);
|
||||
assert_eq!(plan.v6, vec!["[::1]:5354".parse::<SocketAddr>().unwrap()]);
|
||||
assert_eq!(plan.families().len(), 2);
|
||||
// Nothing here is reachable from another member: the zones are a
|
||||
// view for this host, and an agent in two networks must not answer
|
||||
// one network's questions about the other's names.
|
||||
for address in plan.families().concat() {
|
||||
assert!(address.ip().is_loopback(), "{address} is not loopback");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! Telling the macOS resolver to send some questions here, through
|
||||
//! `/etc/resolver`.
|
||||
//!
|
||||
//! macOS reads one file per domain out of `/etc/resolver`: a file named after
|
||||
//! a domain, containing the `nameserver` and `port` to send that domain's
|
||||
//! questions to, makes the system resolver a *scoped* resolver for exactly
|
||||
//! that suffix and nothing else (see `resolver(5)`). That is the same contract
|
||||
//! the systemd-resolved and NRPT publishers arrange on the other platforms:
|
||||
//! route these suffixes to this server, and claim nothing else.
|
||||
//!
|
||||
//! # Why a port, and so no privileged socket
|
||||
//!
|
||||
//! A resolver file carries a `port`, so the server does not have to sit on 53
|
||||
//! and the agent needs nothing like `CAP_NET_BIND_SERVICE`. It can serve on a
|
||||
//! high port and still be reached for its suffixes.
|
||||
//!
|
||||
//! # Tagged, reversible, and never clobbering
|
||||
//!
|
||||
//! Every file this publisher writes begins with a marker line, so it only ever
|
||||
//! replaces or removes files it wrote itself: a pre-existing `/etc/resolver`
|
||||
//! entry a user set up by hand is left untouched. The files are removed when
|
||||
//! the resolver is turned off and on shutdown; a crash leaves them behind, and
|
||||
//! the next apply for the same domains overwrites them.
|
||||
//!
|
||||
//! # Privilege
|
||||
//!
|
||||
//! Writing under `/etc/resolver` needs root. A permission error is reported as
|
||||
//! a refusal — the kind of failure a person has to act on — rather than a
|
||||
//! transient one, so the agent does not retry it at the ordinary pace.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::net::IpAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::BoxFuture;
|
||||
|
||||
use super::{DnsPublisher, PublishError, Published};
|
||||
|
||||
/// The directory macOS reads scoped resolvers from.
|
||||
const RESOLVER_DIR: &str = "/etc/resolver";
|
||||
|
||||
/// The first line of every file this publisher writes, so it recognises its
|
||||
/// own and never touches a file a user created.
|
||||
const MARKER: &str = "# managed by tsunagi — do not edit";
|
||||
|
||||
/// Writes and removes `/etc/resolver` files for the overlay zones.
|
||||
#[derive(Debug)]
|
||||
pub struct ResolverDirPublisher {
|
||||
/// The resolver directory. A field rather than a constant so the tests can
|
||||
/// point it at a temporary directory and never touch the real one.
|
||||
dir: PathBuf,
|
||||
/// The domain files written by the last apply, so a later apply can remove
|
||||
/// the ones no longer wanted and `revert` can remove them all.
|
||||
written: Mutex<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
impl Default for ResolverDirPublisher {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ResolverDirPublisher {
|
||||
/// A publisher writing to the real `/etc/resolver`.
|
||||
pub fn new() -> Self {
|
||||
Self::in_dir(RESOLVER_DIR)
|
||||
}
|
||||
|
||||
/// A publisher writing to a specific directory. For the tests.
|
||||
fn in_dir(dir: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
dir: dir.into(),
|
||||
written: Mutex::new(BTreeSet::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_inner(&self, published: &Published) -> Result<(), PublishError> {
|
||||
let desired = desired_files(published)?;
|
||||
|
||||
// The directory may not exist yet; creating it needs root.
|
||||
std::fs::create_dir_all(&self.dir).map_err(|err| classify(&self.dir, err))?;
|
||||
|
||||
// Remove the files from a previous apply that are no longer wanted.
|
||||
let previous = lock(&self.written).clone();
|
||||
for name in previous.difference(&keys(&desired)) {
|
||||
remove_if_ours(&self.dir.join(name));
|
||||
}
|
||||
|
||||
for (name, body) in &desired {
|
||||
let path = self.dir.join(name);
|
||||
// Only ever overwrite a file that is already ours, or a name that
|
||||
// is free. A resolver a user set up by hand is left in place and
|
||||
// reported, never clobbered.
|
||||
if path.exists() && !is_ours(&path) {
|
||||
return Err(PublishError::Failed(format!(
|
||||
"{} already exists and was not created by tsunagi; \
|
||||
remove it or rename the network to publish its resolver",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|err| classify(&path, err))?;
|
||||
}
|
||||
|
||||
*lock(&self.written) = keys(&desired);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn revert_inner(&self) {
|
||||
let written = std::mem::take(&mut *lock(&self.written));
|
||||
for name in &written {
|
||||
remove_if_ours(&self.dir.join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DnsPublisher for ResolverDirPublisher {
|
||||
fn name(&self) -> &str {
|
||||
"resolver-dir"
|
||||
}
|
||||
|
||||
fn apply<'a>(&'a self, published: &'a Published) -> BoxFuture<'a, Result<(), PublishError>> {
|
||||
// A handful of small file writes, short enough to run in place rather
|
||||
// than hop to the blocking pool.
|
||||
Box::pin(async move { self.apply_inner(published) })
|
||||
}
|
||||
|
||||
fn revert(&self) -> BoxFuture<'_, Result<(), PublishError>> {
|
||||
Box::pin(async move {
|
||||
self.revert_inner();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The resolver files a publication implies: a map of file name to contents.
|
||||
fn desired_files(published: &Published) -> Result<Vec<(String, String)>, PublishError> {
|
||||
if published.servers.is_empty() {
|
||||
return Err(PublishError::Failed(
|
||||
"no server address to point the resolver at".to_string(),
|
||||
));
|
||||
}
|
||||
let body = file_contents(published);
|
||||
let mut files = Vec::new();
|
||||
for domain in &published.domains {
|
||||
let name = resolver_file_name(domain)?;
|
||||
files.push((name, body.clone()));
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
/// The contents of one resolver file: the marker, every server, one port.
|
||||
fn file_contents(published: &Published) -> String {
|
||||
let mut out = String::from(MARKER);
|
||||
out.push('\n');
|
||||
for server in &published.servers {
|
||||
let ip = match server.ip() {
|
||||
IpAddr::V4(v4) => v4.to_string(),
|
||||
IpAddr::V6(v6) => v6.to_string(),
|
||||
};
|
||||
out.push_str("nameserver ");
|
||||
out.push_str(&ip);
|
||||
out.push('\n');
|
||||
}
|
||||
// One port for the file; every server listens on the same one. The `port`
|
||||
// directive is what lets the server stay off 53.
|
||||
if let Some(first) = published.servers.first() {
|
||||
out.push_str("port ");
|
||||
out.push_str(&first.port().to_string());
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The file name for a domain, rejecting anything that is not a plain label
|
||||
/// path component: a resolver file name must never escape the directory.
|
||||
fn resolver_file_name(domain: &str) -> Result<String, PublishError> {
|
||||
let trimmed = domain.trim_end_matches('.');
|
||||
if trimmed.is_empty()
|
||||
|| trimmed.contains('/')
|
||||
|| trimmed.contains('\\')
|
||||
|| trimmed.contains(std::path::MAIN_SEPARATOR)
|
||||
|| trimmed == "."
|
||||
|| trimmed == ".."
|
||||
|| trimmed.starts_with('.')
|
||||
{
|
||||
return Err(PublishError::Failed(format!(
|
||||
"cannot make a resolver file name for the domain {domain:?}"
|
||||
)));
|
||||
}
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
/// Whether a file is one this publisher wrote, by its marker first line.
|
||||
fn is_ours(path: &Path) -> bool {
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => text.lines().next() == Some(MARKER),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes a file, but only if it is one of ours. Best effort.
|
||||
fn remove_if_ours(path: &Path) {
|
||||
if is_ours(path)
|
||||
&& let Err(err) = std::fs::remove_file(path)
|
||||
&& err.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::debug!(path = %path.display(), %err, "cannot remove the resolver file");
|
||||
}
|
||||
}
|
||||
|
||||
/// The set of file names in a desired-files list.
|
||||
fn keys(files: &[(String, String)]) -> BTreeSet<String> {
|
||||
files.iter().map(|(name, _)| name.clone()).collect()
|
||||
}
|
||||
|
||||
/// Turns a filesystem error into the right kind of publish error: a permission
|
||||
/// problem is a refusal a person must act on, anything else is a plain failure.
|
||||
fn classify(path: &Path, err: std::io::Error) -> PublishError {
|
||||
if err.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
PublishError::Refused(format!(
|
||||
"writing {} needs root; start the agent with `sudo` or as a root LaunchDaemon",
|
||||
path.display()
|
||||
))
|
||||
} else {
|
||||
PublishError::Failed(format!("cannot write {}: {err}", path.display()))
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
match mutex.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn published(domains: &[&str]) -> Published {
|
||||
Published {
|
||||
interface: "utun5".into(),
|
||||
servers: vec![
|
||||
"10.13.37.1:5353".parse::<SocketAddr>().unwrap(),
|
||||
"[fd00::1]:5353".parse::<SocketAddr>().unwrap(),
|
||||
],
|
||||
domains: domains.iter().map(|d| d.to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_lists_every_server_and_one_port_under_the_marker() {
|
||||
let body = file_contents(&published(&["mynet."]));
|
||||
let mut lines = body.lines();
|
||||
assert_eq!(lines.next(), Some(MARKER));
|
||||
assert_eq!(lines.next(), Some("nameserver 10.13.37.1"));
|
||||
assert_eq!(lines.next(), Some("nameserver fd00::1"));
|
||||
assert_eq!(lines.next(), Some("port 5353"));
|
||||
assert_eq!(lines.next(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_domain_becomes_a_plain_file_name_without_its_trailing_dot() {
|
||||
assert_eq!(resolver_file_name("mynet.").unwrap(), "mynet");
|
||||
assert_eq!(resolver_file_name("my.net").unwrap(), "my.net");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_domain_that_would_escape_the_directory_is_refused() {
|
||||
assert!(resolver_file_name("../etc/passwd").is_err());
|
||||
assert!(resolver_file_name("a/b").is_err());
|
||||
assert!(resolver_file_name("").is_err());
|
||||
assert!(resolver_file_name(".").is_err());
|
||||
assert!(resolver_file_name(".hidden").is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apply_writes_a_file_per_domain_and_revert_removes_them() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let publisher = ResolverDirPublisher::in_dir(dir.path());
|
||||
|
||||
publisher
|
||||
.apply(&published(&["mynet.", "other."]))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(dir.path().join("mynet").is_file());
|
||||
assert!(dir.path().join("other").is_file());
|
||||
|
||||
publisher.revert().await.unwrap();
|
||||
assert!(!dir.path().join("mynet").exists());
|
||||
assert!(!dir.path().join("other").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn re_applying_removes_a_domain_that_is_no_longer_wanted() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let publisher = ResolverDirPublisher::in_dir(dir.path());
|
||||
|
||||
publisher.apply(&published(&["a.", "b."])).await.unwrap();
|
||||
publisher.apply(&published(&["a."])).await.unwrap();
|
||||
|
||||
assert!(dir.path().join("a").is_file());
|
||||
assert!(
|
||||
!dir.path().join("b").exists(),
|
||||
"the dropped domain's file is removed"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_file_a_user_created_is_never_clobbered_or_removed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let foreign = dir.path().join("mynet");
|
||||
std::fs::write(&foreign, "nameserver 9.9.9.9\n").unwrap();
|
||||
|
||||
let publisher = ResolverDirPublisher::in_dir(dir.path());
|
||||
let err = publisher.apply(&published(&["mynet."])).await.unwrap_err();
|
||||
assert!(matches!(err, PublishError::Failed(_)), "{err:?}");
|
||||
// Untouched.
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&foreign).unwrap(),
|
||||
"nameserver 9.9.9.9\n"
|
||||
);
|
||||
|
||||
// And revert leaves a foreign file alone even if it is in our set.
|
||||
publisher.revert().await.unwrap();
|
||||
assert!(foreign.is_file());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! A pretend resolver, so the wiring is tested without touching this host's.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::BoxFuture;
|
||||
|
||||
use super::{DnsPublisher, PublishError, Published};
|
||||
|
||||
/// Records what it was asked to do, and can be told to refuse.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MockPublisher {
|
||||
applied: Arc<Mutex<Option<Published>>>,
|
||||
failure: Option<PublishError>,
|
||||
}
|
||||
|
||||
impl MockPublisher {
|
||||
/// A publisher that accepts everything.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// A publisher that refuses everything, with this reason.
|
||||
pub fn failing(error: PublishError) -> Self {
|
||||
Self {
|
||||
applied: Arc::new(Mutex::new(None)),
|
||||
failure: Some(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// What is currently applied, if anything.
|
||||
pub fn applied(&self) -> Option<Published> {
|
||||
match self.applied.lock() {
|
||||
Ok(guard) => guard.clone(),
|
||||
Err(poisoned) => poisoned.into_inner().clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DnsPublisher for MockPublisher {
|
||||
fn name(&self) -> &str {
|
||||
"mock"
|
||||
}
|
||||
|
||||
fn apply<'a>(&'a self, published: &'a Published) -> BoxFuture<'a, Result<(), PublishError>> {
|
||||
Box::pin(async move {
|
||||
if let Some(failure) = &self.failure {
|
||||
return Err(failure.clone());
|
||||
}
|
||||
match self.applied.lock() {
|
||||
Ok(mut guard) => *guard = Some(published.clone()),
|
||||
Err(poisoned) => *poisoned.into_inner() = Some(published.clone()),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn revert(&self) -> BoxFuture<'_, Result<(), PublishError>> {
|
||||
Box::pin(async move {
|
||||
match self.applied.lock() {
|
||||
Ok(mut guard) => *guard = None,
|
||||
Err(poisoned) => *poisoned.into_inner() = None,
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
|
||||
fn published() -> Published {
|
||||
Published {
|
||||
interface: "tsundemo".into(),
|
||||
servers: vec![
|
||||
"10.13.37.69:5354".parse().unwrap(),
|
||||
"[::1]:5354".parse().unwrap(),
|
||||
],
|
||||
domains: vec!["lab".into()],
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn applying_and_reverting_are_both_recorded() {
|
||||
let publisher = MockPublisher::new();
|
||||
assert!(publisher.applied().is_none());
|
||||
|
||||
publisher.apply(&published()).await.unwrap();
|
||||
assert_eq!(publisher.applied(), Some(published()));
|
||||
|
||||
publisher.revert().await.unwrap();
|
||||
assert!(publisher.applied().is_none());
|
||||
// Reverting twice is not an error: shutdown must not fail here.
|
||||
publisher.revert().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refusal_leaves_nothing_applied() {
|
||||
let publisher = MockPublisher::failing(PublishError::Refused("polkit said no".into()));
|
||||
assert!(publisher.apply(&published()).await.is_err());
|
||||
assert!(publisher.applied().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Telling the operating system where to send its questions.
|
||||
//!
|
||||
//! The server answers whether or not this works. That is the whole reason it
|
||||
//! is a separate thing: if the resolver cannot be configured — no
|
||||
//! systemd-resolved, an unwilling polkit, a platform nobody has written this
|
||||
//! for — the port is still up and the user can point something at it by
|
||||
//! hand. A failure here is a degraded overlay, not a broken one.
|
||||
//!
|
||||
//! Only the *mechanics* differ between systems. What has to be arranged is
|
||||
//! the same everywhere: send questions for these suffixes to this address,
|
||||
//! through this interface, and do not make it the resolver for anything
|
||||
//! else. That is [`Published`]; the rest is behind [`DnsPublisher`].
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use crate::BoxFuture;
|
||||
|
||||
mod mock;
|
||||
pub use mock::MockPublisher;
|
||||
|
||||
#[cfg(all(feature = "dns-publish", target_os = "linux"))]
|
||||
mod resolved;
|
||||
#[cfg(all(feature = "dns-publish", target_os = "linux"))]
|
||||
pub use resolved::ResolvedPublisher;
|
||||
|
||||
#[cfg(all(feature = "dns-publish", target_os = "windows"))]
|
||||
mod windows;
|
||||
#[cfg(all(feature = "dns-publish", target_os = "windows"))]
|
||||
pub use windows::NrptPublisher;
|
||||
|
||||
#[cfg(all(feature = "dns-publish", target_os = "macos"))]
|
||||
mod macos;
|
||||
#[cfg(all(feature = "dns-publish", target_os = "macos"))]
|
||||
pub use macos::ResolverDirPublisher;
|
||||
|
||||
mod unsupported;
|
||||
pub use unsupported::UnsupportedPublisher;
|
||||
|
||||
/// What the operating system is asked to do.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Published {
|
||||
/// The interface questions should be sent through.
|
||||
///
|
||||
/// The server listens on an overlay address, which is only reachable
|
||||
/// over the overlay interface, so the two travel together. It must be an
|
||||
/// interface this agent created: configuring one it did not is
|
||||
/// configuring somebody else's.
|
||||
pub interface: String,
|
||||
/// Every address the server is listening on, best first.
|
||||
///
|
||||
/// One per address family, so a resolver reaches it over whichever it
|
||||
/// uses. All of them are published together and none is preferred by
|
||||
/// this: which one a resolver picks is its business.
|
||||
pub servers: Vec<SocketAddr>,
|
||||
/// The suffixes that belong to this server.
|
||||
///
|
||||
/// Routing suffixes only: they say *which questions* come here, never
|
||||
/// that this is the resolver for anything else.
|
||||
pub domains: Vec<String>,
|
||||
}
|
||||
|
||||
/// Why the resolver could not be told.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum PublishError {
|
||||
/// There is nothing here that can be configured this way.
|
||||
#[error("{0}")]
|
||||
Unavailable(String),
|
||||
/// Something is there, and it declined.
|
||||
///
|
||||
/// Separate from a plain failure because the answer is different: this
|
||||
/// one is about who the agent is running as, not about whether the thing
|
||||
/// works.
|
||||
#[error("{0}")]
|
||||
Refused(String),
|
||||
/// It was there, it accepted the request, and it went wrong anyway.
|
||||
#[error("{0}")]
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl PublishError {
|
||||
/// Whether waiting will fix it.
|
||||
///
|
||||
/// A refusal will not change on its own — somebody has to grant
|
||||
/// permission — so retrying it at the pace of everything else is just
|
||||
/// noise. Anything else might be a service still starting.
|
||||
pub fn needs_a_human(&self) -> bool {
|
||||
matches!(self, PublishError::Refused(_))
|
||||
}
|
||||
|
||||
/// One line for a status table.
|
||||
pub fn remedy(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
PublishError::Refused(_) => Some(
|
||||
"grant this user the `org.freedesktop.resolve1.set-*` actions in \
|
||||
/etc/polkit-1/rules.d, or run the agent as a system service",
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The polkit rule that lets this user configure the resolver.
|
||||
///
|
||||
/// Printed in full rather than described, because the point of this feature
|
||||
/// is that the user has as little to do as possible, and "write a polkit
|
||||
/// rule" is a great deal more work than pasting one.
|
||||
///
|
||||
/// It grants exactly the four actions this agent calls and nothing else.
|
||||
/// polkit decides by user id — a capability does not help here — so there is
|
||||
/// no way to do this from inside the process.
|
||||
pub fn polkit_recipe(user: &str) -> String {
|
||||
format!(
|
||||
"sudo tee /etc/polkit-1/rules.d/50-tsunagi-resolved.rules > /dev/null <<'RULE'\n\
|
||||
polkit.addRule(function(action, subject) {{\n\
|
||||
\x20 var allowed = [\n\
|
||||
\x20 \"org.freedesktop.resolve1.set-dns-servers\",\n\
|
||||
\x20 \"org.freedesktop.resolve1.set-domains\",\n\
|
||||
\x20 \"org.freedesktop.resolve1.set-default-route\",\n\
|
||||
\x20 \"org.freedesktop.resolve1.revert\"\n\
|
||||
\x20 ];\n\
|
||||
\x20 if (allowed.indexOf(action.id) >= 0 && subject.user == \"{user}\") {{\n\
|
||||
\x20 return polkit.Result.YES;\n\
|
||||
\x20 }}\n\
|
||||
}});\n\
|
||||
RULE"
|
||||
)
|
||||
}
|
||||
|
||||
/// Arranges for the operating system to ask this server.
|
||||
pub trait DnsPublisher: Send + Sync + std::fmt::Debug + 'static {
|
||||
/// A short name used in diagnostics.
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// Applies the setting, replacing whatever this publisher set before.
|
||||
fn apply<'a>(&'a self, published: &'a Published) -> BoxFuture<'a, Result<(), PublishError>>;
|
||||
|
||||
/// Undoes it.
|
||||
///
|
||||
/// Reverting something that was never applied succeeds: this runs on the
|
||||
/// shutdown path, where the setting being gone is the point.
|
||||
fn revert(&self) -> BoxFuture<'_, Result<(), PublishError>>;
|
||||
}
|
||||
|
||||
/// The kernel's index for an interface.
|
||||
///
|
||||
/// From sysfs, which needs no privileges and no netlink round trip.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn interface_index(name: &str) -> Option<u32> {
|
||||
std::fs::read_to_string(format!("/sys/class/net/{name}/ifindex"))
|
||||
.ok()?
|
||||
.trim()
|
||||
.parse()
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// The kernel's index for an interface.
|
||||
///
|
||||
/// Only the systemd-resolved publisher needs one, so off Linux there is
|
||||
/// nothing to look up and this is always `None`.
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn interface_index(_name: &str) -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_refusal_suggests_what_to_do_about_it() {
|
||||
// The other two are conditions of the host, not of the user.
|
||||
assert!(PublishError::Refused("no".into()).remedy().is_some());
|
||||
assert!(PublishError::Unavailable("none".into()).remedy().is_none());
|
||||
assert!(PublishError::Failed("bang".into()).remedy().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_refusal_waits_for_a_person() {
|
||||
// The rest may come right on their own, so they are worth retrying
|
||||
// at the ordinary pace; a refusal is not.
|
||||
assert!(PublishError::Refused("no".into()).needs_a_human());
|
||||
assert!(!PublishError::Unavailable("none".into()).needs_a_human());
|
||||
assert!(!PublishError::Failed("bang".into()).needs_a_human());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_polkit_recipe_grants_what_is_called_and_no_more() {
|
||||
let recipe = polkit_recipe("ab");
|
||||
for action in [
|
||||
"set-dns-servers",
|
||||
"set-domains",
|
||||
"set-default-route",
|
||||
"revert",
|
||||
] {
|
||||
assert!(recipe.contains(action), "{action} missing from:\n{recipe}");
|
||||
}
|
||||
// Nothing beyond what the agent calls: a rule that granted the lot
|
||||
// would be handing out more than this feature needs.
|
||||
for other in ["set-dnssec", "set-mdns", "register-service", "set-llmnr"] {
|
||||
assert!(!recipe.contains(other), "{other} should not be granted");
|
||||
}
|
||||
assert!(recipe.contains("subject.user == \"ab\""));
|
||||
// ES5: the rules engine is duktape and has no `startsWith`.
|
||||
assert!(!recipe.contains("startsWith"));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn an_interface_index_is_read_from_the_running_kernel() {
|
||||
assert_eq!(interface_index("lo"), Some(1));
|
||||
assert_eq!(interface_index("tsunagi-no-such-interface"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! Telling systemd-resolved to send some questions here.
|
||||
//!
|
||||
//! Three calls on `org.freedesktop.resolve1.Manager`, all scoped to the
|
||||
//! overlay interface:
|
||||
//!
|
||||
//! * `SetLinkDNSEx` — where to send them. The `Ex` form carries a **port**,
|
||||
//! which is why this server does not have to sit on 53 and the agent needs
|
||||
//! no `CAP_NET_BIND_SERVICE`. Systems before systemd 247 have only
|
||||
//! `SetLinkDNS`, which has no port; there the fallback only works if the
|
||||
//! server did get port 53, and it says so rather than appearing to work.
|
||||
//! * `SetLinkDomains` with `routing_only` set — a *routing* suffix, the
|
||||
//! `~domain` form. It says which questions come here and claims nothing
|
||||
//! else.
|
||||
//! * `SetLinkDefaultRoute(false)` — so this never becomes the resolver for
|
||||
//! anything outside those suffixes. Without it resolved may fall back to
|
||||
//! this link for ordinary names, and this server refuses those.
|
||||
//!
|
||||
//! # It cleans up by itself
|
||||
//!
|
||||
//! resolved keys all of this to the interface, and drops it when the
|
||||
//! interface goes. The overlay interface belongs to a file descriptor the
|
||||
//! agent holds, so it goes when the agent does — however the agent goes. The
|
||||
//! explicit `RevertLink` on shutdown only makes that immediate.
|
||||
//!
|
||||
//! # Privilege
|
||||
//!
|
||||
//! resolved asks polkit, and polkit decides by user id, not by capability.
|
||||
//! So `CAP_NET_ADMIN` does not help here: an ordinary user is prompted or
|
||||
//! refused, while a system service running as root is not. That refusal is
|
||||
//! reported as its own kind of error, because the answer to it is different
|
||||
//! from the answer to "resolved is not installed".
|
||||
|
||||
use std::net::IpAddr;
|
||||
|
||||
use crate::BoxFuture;
|
||||
|
||||
use super::{DnsPublisher, PublishError, Published, interface_index};
|
||||
|
||||
/// `AF_INET`, as resolved wants it.
|
||||
const AF_INET: i32 = 2;
|
||||
/// `AF_INET6`.
|
||||
const AF_INET6: i32 = 10;
|
||||
|
||||
#[zbus::proxy(
|
||||
interface = "org.freedesktop.resolve1.Manager",
|
||||
default_service = "org.freedesktop.resolve1",
|
||||
default_path = "/org/freedesktop/resolve1"
|
||||
)]
|
||||
trait Resolved {
|
||||
/// Servers for a link, with a port and a name. systemd 247 and later.
|
||||
#[zbus(name = "SetLinkDNSEx")]
|
||||
fn set_link_dns_ex(
|
||||
&self,
|
||||
ifindex: i32,
|
||||
addresses: &[(i32, Vec<u8>, u16, String)],
|
||||
) -> zbus::Result<()>;
|
||||
|
||||
/// Servers for a link, without a port. Always port 53.
|
||||
#[zbus(name = "SetLinkDNS")]
|
||||
fn set_link_dns(&self, ifindex: i32, addresses: &[(i32, Vec<u8>)]) -> zbus::Result<()>;
|
||||
|
||||
/// Suffixes for a link. The flag makes one routing-only.
|
||||
#[zbus(name = "SetLinkDomains")]
|
||||
fn set_link_domains(&self, ifindex: i32, domains: &[(String, bool)]) -> zbus::Result<()>;
|
||||
|
||||
/// Whether this link may answer for names outside its suffixes.
|
||||
#[zbus(name = "SetLinkDefaultRoute")]
|
||||
fn set_link_default_route(&self, ifindex: i32, enable: bool) -> zbus::Result<()>;
|
||||
|
||||
/// Forgets everything set for a link.
|
||||
#[zbus(name = "RevertLink")]
|
||||
fn revert_link(&self, ifindex: i32) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
/// Configures systemd-resolved over D-Bus.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ResolvedPublisher {
|
||||
/// The link last configured, so shutdown knows what to undo.
|
||||
applied: std::sync::Mutex<Option<u32>>,
|
||||
}
|
||||
|
||||
impl ResolvedPublisher {
|
||||
/// Creates the publisher. Nothing is contacted until [`Self::apply`].
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn proxy() -> Result<ResolvedProxy<'static>, PublishError> {
|
||||
let connection = zbus::Connection::system().await.map_err(|err| {
|
||||
PublishError::Unavailable(format!("no system D-Bus to talk to resolved on: {err}"))
|
||||
})?;
|
||||
ResolvedProxy::new(&connection).await.map_err(|err| {
|
||||
PublishError::Unavailable(format!("systemd-resolved is not answering: {err}"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns a D-Bus failure into the kind of failure it actually is.
|
||||
fn classify(err: zbus::Error, what: &str) -> PublishError {
|
||||
let name = match &err {
|
||||
zbus::Error::MethodError(name, _, _) => name.as_str().to_string(),
|
||||
_ => String::new(),
|
||||
};
|
||||
match name.as_str() {
|
||||
"org.freedesktop.DBus.Error.InteractiveAuthorizationRequired"
|
||||
| "org.freedesktop.DBus.Error.AccessDenied" => {
|
||||
PublishError::Refused(format!("systemd-resolved refused {what}: {err}"))
|
||||
}
|
||||
"org.freedesktop.DBus.Error.UnknownMethod"
|
||||
| "org.freedesktop.DBus.Error.ServiceUnknown" => {
|
||||
PublishError::Unavailable(format!("systemd-resolved cannot do {what}: {err}"))
|
||||
}
|
||||
_ => PublishError::Failed(format!("systemd-resolved failed {what}: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The address in the shape resolved wants: a family and raw octets.
|
||||
fn wire_address(address: IpAddr) -> (i32, Vec<u8>) {
|
||||
match address {
|
||||
IpAddr::V4(address) => (AF_INET, address.octets().to_vec()),
|
||||
IpAddr::V6(address) => (AF_INET6, address.octets().to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
impl DnsPublisher for ResolvedPublisher {
|
||||
fn name(&self) -> &str {
|
||||
"systemd-resolved"
|
||||
}
|
||||
|
||||
fn apply<'a>(&'a self, published: &'a Published) -> BoxFuture<'a, Result<(), PublishError>> {
|
||||
Box::pin(async move {
|
||||
let ifindex = interface_index(&published.interface).ok_or_else(|| {
|
||||
PublishError::Unavailable(format!(
|
||||
"interface `{}` is not on this host, so there is no link to configure",
|
||||
published.interface
|
||||
))
|
||||
})?;
|
||||
if published.servers.is_empty() {
|
||||
return Err(PublishError::Unavailable(
|
||||
"there is no listening address to send questions to".to_string(),
|
||||
));
|
||||
}
|
||||
let proxy = Self::proxy().await?;
|
||||
let index = ifindex as i32;
|
||||
// Every family in one call, because this replaces the link's
|
||||
// whole list: sending them one at a time would leave only the
|
||||
// last. A resolver then picks whichever it can reach.
|
||||
let servers: Vec<(i32, Vec<u8>, u16, String)> = published
|
||||
.servers
|
||||
.iter()
|
||||
.map(|server| {
|
||||
let (family, octets) = wire_address(server.ip());
|
||||
(family, octets, server.port(), String::new())
|
||||
})
|
||||
.collect();
|
||||
|
||||
match proxy.set_link_dns_ex(index, &servers).await {
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
let classified = classify(err, "setting the link's DNS servers");
|
||||
// Older systemd has no `Ex` form, and the plain one is
|
||||
// always port 53. Falling back to it when the server is
|
||||
// somewhere else would point resolved at nothing.
|
||||
if !matches!(classified, PublishError::Unavailable(_)) {
|
||||
return Err(classified);
|
||||
}
|
||||
if let Some(elsewhere) =
|
||||
published.servers.iter().find(|server| server.port() != 53)
|
||||
{
|
||||
return Err(PublishError::Unavailable(format!(
|
||||
"this systemd-resolved cannot be given a port, and the server is on \
|
||||
{}. Run the server on port 53, or point your resolver at \
|
||||
{elsewhere} yourself.",
|
||||
elsewhere.port()
|
||||
)));
|
||||
}
|
||||
let plain: Vec<(i32, Vec<u8>)> = servers
|
||||
.into_iter()
|
||||
.map(|(family, octets, _, _)| (family, octets))
|
||||
.collect();
|
||||
proxy
|
||||
.set_link_dns(index, &plain)
|
||||
.await
|
||||
.map_err(|err| classify(err, "setting the link's DNS servers"))?;
|
||||
}
|
||||
}
|
||||
|
||||
let domains: Vec<(String, bool)> = published
|
||||
.domains
|
||||
.iter()
|
||||
.map(|domain| (domain.clone(), true))
|
||||
.collect();
|
||||
proxy
|
||||
.set_link_domains(index, &domains)
|
||||
.await
|
||||
.map_err(|err| classify(err, "setting the link's search domains"))?;
|
||||
|
||||
// Last, and deliberately: until this is off, resolved may send
|
||||
// ordinary names here, and this server refuses them.
|
||||
proxy
|
||||
.set_link_default_route(index, false)
|
||||
.await
|
||||
.map_err(|err| classify(err, "clearing the link's default route"))?;
|
||||
|
||||
match self.applied.lock() {
|
||||
Ok(mut guard) => *guard = Some(ifindex),
|
||||
Err(poisoned) => *poisoned.into_inner() = Some(ifindex),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn revert(&self) -> BoxFuture<'_, Result<(), PublishError>> {
|
||||
Box::pin(async move {
|
||||
let applied = match self.applied.lock() {
|
||||
Ok(mut guard) => guard.take(),
|
||||
Err(poisoned) => poisoned.into_inner().take(),
|
||||
};
|
||||
let Some(ifindex) = applied else {
|
||||
return Ok(());
|
||||
};
|
||||
let proxy = Self::proxy().await?;
|
||||
match proxy.revert_link(ifindex as i32).await {
|
||||
Ok(()) => Ok(()),
|
||||
// The link going away takes the setting with it, so this is
|
||||
// the outcome asked for rather than a failure.
|
||||
Err(zbus::Error::MethodError(name, _, _))
|
||||
if name.as_str().contains("NoSuchLink") =>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(classify(err, "reverting the link")),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
|
||||
#[test]
|
||||
fn an_address_is_encoded_the_way_resolved_expects() {
|
||||
assert_eq!(
|
||||
wire_address(IpAddr::V4(Ipv4Addr::new(10, 13, 37, 69))),
|
||||
(AF_INET, vec![10, 13, 37, 69])
|
||||
);
|
||||
let (family, octets) = wire_address("fd55::1".parse().unwrap());
|
||||
assert_eq!(family, AF_INET6);
|
||||
assert_eq!(octets.len(), 16);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_interface_that_is_not_here_is_unavailable_not_a_failure() {
|
||||
// Nothing is contacted: there is no link to configure, and saying so
|
||||
// is the honest answer without bothering the bus.
|
||||
let publisher = ResolvedPublisher::new();
|
||||
let published = Published {
|
||||
interface: "tsunagi-no-such-interface".into(),
|
||||
servers: vec![SocketAddr::from(([10, 13, 37, 69], 5354))],
|
||||
domains: vec!["lab".into()],
|
||||
};
|
||||
let err = publisher.apply(&published).await.unwrap_err();
|
||||
assert!(matches!(err, PublishError::Unavailable(_)), "{err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reverting_without_having_applied_does_nothing_and_succeeds() {
|
||||
// The shutdown path must not fail because there was nothing to undo.
|
||||
ResolvedPublisher::new().revert().await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! The publisher for systems nobody has written one for.
|
||||
//!
|
||||
//! macOS needs `SystemConfiguration` and Windows the IP Helper API, and
|
||||
//! neither is written. Saying so is more use than appearing to work: the
|
||||
//! server is already answering, so all that is missing is the last step, and
|
||||
//! the user can take it by hand once they know that is what is needed.
|
||||
|
||||
use crate::BoxFuture;
|
||||
|
||||
use super::{DnsPublisher, PublishError, Published};
|
||||
|
||||
/// Refuses to configure anything, with an explanation.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UnsupportedPublisher {
|
||||
platform: &'static str,
|
||||
}
|
||||
|
||||
impl Default for UnsupportedPublisher {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl UnsupportedPublisher {
|
||||
/// A publisher naming the platform it stands in for.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
platform: std::env::consts::OS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DnsPublisher for UnsupportedPublisher {
|
||||
fn name(&self) -> &str {
|
||||
"unsupported"
|
||||
}
|
||||
|
||||
fn apply<'a>(&'a self, _published: &'a Published) -> BoxFuture<'a, Result<(), PublishError>> {
|
||||
Box::pin(async move {
|
||||
Err(PublishError::Unavailable(format!(
|
||||
"configuring the system resolver is not implemented on {} yet",
|
||||
self.platform
|
||||
)))
|
||||
})
|
||||
}
|
||||
|
||||
fn revert(&self) -> BoxFuture<'_, Result<(), PublishError>> {
|
||||
// Nothing was set, so there is nothing to undo and no reason to fail
|
||||
// a shutdown over it.
|
||||
Box::pin(async move { Ok(()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_names_the_platform_and_still_reverts_quietly() {
|
||||
let publisher = UnsupportedPublisher::new();
|
||||
let published = Published {
|
||||
interface: "tsundemo".into(),
|
||||
servers: vec!["10.0.0.1:5354".parse().unwrap()],
|
||||
domains: vec!["lab".into()],
|
||||
};
|
||||
let err = publisher.apply(&published).await.unwrap_err();
|
||||
assert!(matches!(err, PublishError::Unavailable(_)));
|
||||
assert!(err.to_string().contains(std::env::consts::OS));
|
||||
publisher.revert().await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
//! Telling the Windows DNS client to send some questions here, through the
|
||||
//! Name Resolution Policy Table.
|
||||
//!
|
||||
//! The NRPT is how Windows does split DNS: a rule says "names under this
|
||||
//! suffix are resolved by these servers", and names outside every rule are
|
||||
//! resolved the ordinary way. That is exactly the contract of [`Published`] —
|
||||
//! route these suffixes here and claim nothing else — so one NRPT rule per
|
||||
//! suffix is the whole of it. The rules are keyed by namespace, not by
|
||||
//! interface, so the interface name in [`Published`] is not needed here.
|
||||
//!
|
||||
//! # Why PowerShell
|
||||
//!
|
||||
//! The NRPT lives in the registry, but a rule only takes effect once the DNS
|
||||
//! client is told to reload its policy, and that notification is an RPC with
|
||||
//! no safe wrapper this crate may call — it forbids `unsafe`. The
|
||||
//! `DnsClient` PowerShell module does the write *and* the reload, so it is
|
||||
//! used by absolute path from `%SystemRoot%`. Every value passed to it is one
|
||||
//! this agent produced: the suffixes are validated zone names (letters,
|
||||
//! digits, `-`, `_`, `.` only) and the servers are addresses it is listening
|
||||
//! on. They are still single-quoted and escaped when built into the script,
|
||||
//! so nothing could be read as PowerShell rather than as data.
|
||||
//!
|
||||
//! # The port
|
||||
//!
|
||||
//! The Windows DNS client always asks on port 53; it cannot be told another.
|
||||
//! So a server on a different port cannot be reached this way, and rather than
|
||||
//! configure a rule that points at nothing, this says so — the same honest
|
||||
//! failure the systemd-resolved path gives for an old resolver with no port.
|
||||
//!
|
||||
//! # Privilege
|
||||
//!
|
||||
//! Writing an NRPT rule needs an elevated process. An ordinary user is
|
||||
//! refused, which is reported as its own kind of error because the answer to
|
||||
//! it — run elevated, or as a service — differs from "this is not Windows".
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::BoxFuture;
|
||||
|
||||
use super::{DnsPublisher, PublishError, Published};
|
||||
|
||||
/// The port the Windows DNS client is fixed to.
|
||||
const DNS_PORT: u16 = 53;
|
||||
|
||||
/// Configures the Name Resolution Policy Table through PowerShell.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct NrptPublisher {
|
||||
/// The namespaces last configured, so shutdown knows what to undo.
|
||||
applied: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl NrptPublisher {
|
||||
/// Creates the publisher. Nothing is contacted until [`Self::apply`].
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A suffix as the NRPT wants it: a leading dot means "this and everything
|
||||
/// under it".
|
||||
fn namespace(domain: &str) -> String {
|
||||
let trimmed = domain.trim_matches('.');
|
||||
format!(".{trimmed}")
|
||||
}
|
||||
|
||||
/// A PowerShell single-quoted literal, with any embedded quote doubled.
|
||||
fn ps_literal(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
/// A PowerShell array literal, `@('a','b')`, or `@()` when empty.
|
||||
fn ps_array(values: &[String]) -> String {
|
||||
let items: Vec<String> = values.iter().map(|value| ps_literal(value)).collect();
|
||||
format!("@({})", items.join(","))
|
||||
}
|
||||
|
||||
/// The script that clears our rules for these namespaces and then adds them.
|
||||
fn apply_script(namespaces: &[String], servers: &[String]) -> String {
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
$ns = {ns}\n\
|
||||
$srv = {srv}\n\
|
||||
foreach ($n in $ns) {{ Get-DnsClientNrptRule | Where-Object {{ $_.Namespace -eq $n }} | \
|
||||
ForEach-Object {{ Remove-DnsClientNrptRule -Name $_.Name -Force }} }}\n\
|
||||
foreach ($n in $ns) {{ Add-DnsClientNrptRule -Namespace $n -NameServers $srv }}\n",
|
||||
ns = ps_array(namespaces),
|
||||
srv = ps_array(servers),
|
||||
)
|
||||
}
|
||||
|
||||
/// The script that clears our rules for these namespaces.
|
||||
fn revert_script(namespaces: &[String]) -> String {
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
$ns = {ns}\n\
|
||||
foreach ($n in $ns) {{ Get-DnsClientNrptRule | Where-Object {{ $_.Namespace -eq $n }} | \
|
||||
ForEach-Object {{ Remove-DnsClientNrptRule -Name $_.Name -Force }} }}\n",
|
||||
ns = ps_array(namespaces),
|
||||
)
|
||||
}
|
||||
|
||||
/// Turns what PowerShell said on failure into the kind of failure it is.
|
||||
fn classify(text: &str) -> PublishError {
|
||||
let lower = text.to_ascii_lowercase();
|
||||
if lower.contains("access is denied")
|
||||
|| lower.contains("requires elevation")
|
||||
|| lower.contains("run as administrator")
|
||||
|| lower.contains("administrator privilege")
|
||||
|| lower.contains("permissiondenied")
|
||||
{
|
||||
PublishError::Refused(format!("the Windows DNS client refused the change: {text}"))
|
||||
} else if lower.contains("is not recognized")
|
||||
|| lower.contains("commandnotfoundexception")
|
||||
|| lower.contains("not recognized as the name of a cmdlet")
|
||||
{
|
||||
PublishError::Unavailable(format!(
|
||||
"the DnsClient PowerShell module is not available: {text}"
|
||||
))
|
||||
} else {
|
||||
PublishError::Failed(format!("the Windows DNS client failed the change: {text}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a PowerShell script from `%SystemRoot%` and maps a failure to a
|
||||
/// [`PublishError`].
|
||||
async fn powershell(script: String) -> Result<(), PublishError> {
|
||||
let program = powershell_path();
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
std::process::Command::new(program)
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-Command",
|
||||
&script,
|
||||
])
|
||||
.output()
|
||||
})
|
||||
.await
|
||||
.map_err(|err| PublishError::Failed(format!("could not run PowerShell: {err}")))?
|
||||
.map_err(|err| PublishError::Unavailable(format!("could not run PowerShell: {err}")))?;
|
||||
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let text = if stderr.trim().is_empty() {
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_string()
|
||||
} else {
|
||||
stderr.trim().to_string()
|
||||
};
|
||||
Err(classify(if text.is_empty() { "no output" } else { &text }))
|
||||
}
|
||||
|
||||
/// The absolute path to Windows PowerShell, so nothing on `PATH` can stand in
|
||||
/// for it.
|
||||
fn powershell_path() -> std::path::PathBuf {
|
||||
let root = std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into());
|
||||
std::path::Path::new(&root)
|
||||
.join("System32")
|
||||
.join("WindowsPowerShell")
|
||||
.join("v1.0")
|
||||
.join("powershell.exe")
|
||||
}
|
||||
|
||||
impl DnsPublisher for NrptPublisher {
|
||||
fn name(&self) -> &str {
|
||||
"windows-nrpt"
|
||||
}
|
||||
|
||||
fn apply<'a>(&'a self, published: &'a Published) -> BoxFuture<'a, Result<(), PublishError>> {
|
||||
Box::pin(async move {
|
||||
if published.domains.is_empty() {
|
||||
return Err(PublishError::Unavailable(
|
||||
"there are no suffixes to route, so there is no rule to write".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
// Windows can only ask on port 53, so a server anywhere else is
|
||||
// unreachable this way. Keep the ones it can use.
|
||||
let servers: BTreeSet<IpAddr> = published
|
||||
.servers
|
||||
.iter()
|
||||
.filter(|server| server.port() == DNS_PORT)
|
||||
.map(|server| server.ip())
|
||||
.collect();
|
||||
if servers.is_empty() {
|
||||
let elsewhere = published
|
||||
.servers
|
||||
.iter()
|
||||
.map(|server| server.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
return Err(PublishError::Unavailable(format!(
|
||||
"the Windows DNS client only asks on port {DNS_PORT}, and the server is on \
|
||||
{elsewhere}. Run the server on port {DNS_PORT}, or point your resolver at it \
|
||||
yourself."
|
||||
)));
|
||||
}
|
||||
|
||||
let namespaces: Vec<String> = published.domains.iter().map(|d| namespace(d)).collect();
|
||||
let servers: Vec<String> = servers.iter().map(|ip| ip.to_string()).collect();
|
||||
|
||||
powershell(apply_script(&namespaces, &servers)).await?;
|
||||
|
||||
match self.applied.lock() {
|
||||
Ok(mut guard) => *guard = namespaces,
|
||||
Err(poisoned) => *poisoned.into_inner() = namespaces,
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn revert(&self) -> BoxFuture<'_, Result<(), PublishError>> {
|
||||
Box::pin(async move {
|
||||
let namespaces = match self.applied.lock() {
|
||||
Ok(mut guard) => std::mem::take(&mut *guard),
|
||||
Err(poisoned) => std::mem::take(&mut *poisoned.into_inner()),
|
||||
};
|
||||
if namespaces.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
powershell(revert_script(&namespaces)).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[test]
|
||||
fn a_suffix_gets_a_leading_dot() {
|
||||
assert_eq!(namespace("lab"), ".lab");
|
||||
assert_eq!(namespace(".lab"), ".lab");
|
||||
assert_eq!(namespace("a.b"), ".a.b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quote_in_a_value_cannot_escape_the_literal() {
|
||||
// Zone names never contain a quote, but the escaping is what makes
|
||||
// that a guarantee rather than a hope.
|
||||
assert_eq!(ps_literal("a'b"), "'a''b'");
|
||||
assert_eq!(ps_array(&["x".into(), "y".into()]), "@('x','y')");
|
||||
assert_eq!(ps_array(&[]), "@()");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_apply_script_removes_before_it_adds() {
|
||||
let script = apply_script(&[".lab".into()], &["10.13.37.69".into()]);
|
||||
let remove = script.find("Remove-DnsClientNrptRule").unwrap();
|
||||
let add = script.find("Add-DnsClientNrptRule").unwrap();
|
||||
assert!(
|
||||
remove < add,
|
||||
"a stale rule must go before the new one:\n{script}"
|
||||
);
|
||||
assert!(script.contains("@('.lab')"));
|
||||
assert!(script.contains("@('10.13.37.69')"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_access_denied_is_a_refusal_a_missing_cmdlet_is_unavailable() {
|
||||
assert!(matches!(
|
||||
classify("Access is denied"),
|
||||
PublishError::Refused(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
classify("The term 'Add-DnsClientNrptRule' is not recognized"),
|
||||
PublishError::Unavailable(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
classify("something else"),
|
||||
PublishError::Failed(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_server_only_on_a_nonstandard_port_is_unavailable_not_a_failure() {
|
||||
// Nothing is run: Windows cannot ask there, and saying so is the
|
||||
// honest answer without touching the DNS client.
|
||||
let publisher = NrptPublisher::new();
|
||||
let published = Published {
|
||||
interface: "tsun0".into(),
|
||||
servers: vec![SocketAddr::from(([10, 13, 37, 69], 5354))],
|
||||
domains: vec!["lab".into()],
|
||||
};
|
||||
let err = publisher.apply(&published).await.unwrap_err();
|
||||
assert!(matches!(err, PublishError::Unavailable(_)), "{err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reverting_without_having_applied_does_nothing_and_succeeds() {
|
||||
NrptPublisher::new().revert().await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
//! Answering DNS questions about the overlay, over UDP and TCP.
|
||||
//!
|
||||
//! Authoritative for one zone and nothing else. There is no recursion, no
|
||||
//! forwarding and no cache: a question this agent cannot answer from the
|
||||
//! signed roster is refused rather than passed anywhere, so pointing a
|
||||
//! resolver at this server can never make it a path to the outside.
|
||||
//!
|
||||
//! The decision of what to answer lives in [`super::zone`]; this module is
|
||||
//! only the wire format and the sockets. [`respond`] sits between them and
|
||||
//! takes bytes to bytes, so everything the server does to a packet is
|
||||
//! testable without opening a socket.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use simple_dns::rdata::{A, PTR, RData, SOA};
|
||||
use simple_dns::{Name, PacketFlag, QCLASS, QTYPE, RCODE, ResourceRecord, TYPE};
|
||||
|
||||
use super::zone::{Answer, Query, Zone, Zones};
|
||||
|
||||
/// How long an answer may be cached.
|
||||
///
|
||||
/// Short, because the roster changes when members come and go and a stale
|
||||
/// answer is worse than another question.
|
||||
pub const TTL: u32 = 30;
|
||||
|
||||
/// The largest question this server will read.
|
||||
///
|
||||
/// A DNS message is 512 bytes without EDNS and 4096 with it; anything past
|
||||
/// that is not a question worth answering.
|
||||
pub const MAX_MESSAGE_LEN: usize = 4096;
|
||||
|
||||
/// The largest answer sent over UDP without the client offering EDNS.
|
||||
const CLASSIC_UDP_LIMIT: usize = 512;
|
||||
|
||||
/// How long a TCP client may take over one question.
|
||||
const TCP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// How many TCP questions may be in flight at once.
|
||||
const MAX_TCP_CONNECTIONS: usize = 32;
|
||||
|
||||
/// The zones the server answers from, swapped as the rosters change.
|
||||
///
|
||||
/// Shared rather than copied into the server so that a roster change — or a
|
||||
/// network joining or leaving — is one write, not a restart: rebinding the
|
||||
/// socket would drop questions in flight for no reason.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct SharedZone(Arc<RwLock<Arc<Zones>>>);
|
||||
|
||||
impl SharedZone {
|
||||
/// Wraps a set of zones.
|
||||
pub fn new(zones: Zones) -> Self {
|
||||
Self(Arc::new(RwLock::new(Arc::new(zones))))
|
||||
}
|
||||
|
||||
/// Wraps a single zone, which is the common case in a test.
|
||||
pub fn one(zone: Zone) -> Self {
|
||||
Self::new(Zones::new([zone]))
|
||||
}
|
||||
|
||||
/// Replaces them.
|
||||
pub fn set(&self, zones: Zones) {
|
||||
match self.0.write() {
|
||||
Ok(mut guard) => *guard = Arc::new(zones),
|
||||
Err(poisoned) => *poisoned.into_inner() = Arc::new(zones),
|
||||
}
|
||||
}
|
||||
|
||||
/// The zones as they are now.
|
||||
pub fn get(&self) -> Arc<Zones> {
|
||||
match self.0.read() {
|
||||
Ok(guard) => Arc::clone(&guard),
|
||||
Err(poisoned) => Arc::clone(&poisoned.into_inner()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the answer to one question.
|
||||
///
|
||||
/// `None` means say nothing at all: the message was not a question this
|
||||
/// server should reply to, and replying anyway would make this a useful
|
||||
/// amplifier for somebody spoofing a source address.
|
||||
pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
||||
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) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut reply = simple_dns::Packet::new_reply(packet.id());
|
||||
// Recursion is not available here and the flag says so honestly; the
|
||||
// desired bit is echoed because a resolver compares it.
|
||||
if packet.has_flags(PacketFlag::RECURSION_DESIRED) {
|
||||
reply.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||
}
|
||||
|
||||
if packet.opcode() != simple_dns::OPCODE::StandardQuery {
|
||||
*reply.rcode_mut() = RCODE::NotImplemented;
|
||||
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||
}
|
||||
|
||||
// Exactly one question. Zero is nothing to answer; more than one has no
|
||||
// agreed meaning and every real server rejects it.
|
||||
let [question] = packet.questions.as_slice() else {
|
||||
*reply.rcode_mut() = RCODE::FormatError;
|
||||
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||
};
|
||||
if !matches!(question.qclass, QCLASS::CLASS(simple_dns::CLASS::IN)) {
|
||||
*reply.rcode_mut() = RCODE::Refused;
|
||||
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||
}
|
||||
|
||||
let qname = question.qname.to_string();
|
||||
// Which zone answers is part of the answer: a denial is bounded by the
|
||||
// SOA of the zone that denied it, and this server may hold several.
|
||||
let (zone, answer) = match zones.lookup(&qname, query_kind(question.qtype)) {
|
||||
Some(answered) => answered,
|
||||
None => {
|
||||
reply.questions.push(question.clone());
|
||||
*reply.rcode_mut() = RCODE::Refused;
|
||||
return reply
|
||||
.build_bytes_vec_compressed()
|
||||
.ok()
|
||||
.map(Resolution::Outside);
|
||||
}
|
||||
};
|
||||
reply.questions.push(question.clone());
|
||||
|
||||
let name = Name::new(&qname).ok()?;
|
||||
match answer {
|
||||
Answer::NotOurs => *reply.rcode_mut() = RCODE::Refused,
|
||||
Answer::Addresses(addresses) => {
|
||||
reply.set_flags(PacketFlag::AUTHORITATIVE_ANSWER);
|
||||
for address in addresses {
|
||||
reply.answers.push(ResourceRecord::new(
|
||||
name.clone(),
|
||||
simple_dns::CLASS::IN,
|
||||
TTL,
|
||||
RData::A(A::from(address)),
|
||||
));
|
||||
}
|
||||
}
|
||||
Answer::Name(target) => {
|
||||
reply.set_flags(PacketFlag::AUTHORITATIVE_ANSWER);
|
||||
let target = Name::new(&target).ok()?.into_owned();
|
||||
reply.answers.push(ResourceRecord::new(
|
||||
name.clone(),
|
||||
simple_dns::CLASS::IN,
|
||||
TTL,
|
||||
RData::PTR(PTR(target)),
|
||||
));
|
||||
}
|
||||
Answer::Soa => {
|
||||
reply.set_flags(PacketFlag::AUTHORITATIVE_ANSWER);
|
||||
reply.answers.push(soa_record(zone)?);
|
||||
}
|
||||
Answer::NoData => {
|
||||
reply.set_flags(PacketFlag::AUTHORITATIVE_ANSWER);
|
||||
// The authority section carries the SOA so a resolver knows how
|
||||
// long it may remember that there is nothing here.
|
||||
reply.name_servers.push(soa_record(zone)?);
|
||||
}
|
||||
Answer::NoSuchName => {
|
||||
reply.set_flags(PacketFlag::AUTHORITATIVE_ANSWER);
|
||||
*reply.rcode_mut() = RCODE::NameError;
|
||||
reply.name_servers.push(soa_record(zone)?);
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
fn soa_record(zone: &Zone) -> Option<ResourceRecord<'static>> {
|
||||
let origin = Name::new(zone.origin().as_str()).ok()?.into_owned();
|
||||
Some(ResourceRecord::new(
|
||||
origin.clone(),
|
||||
simple_dns::CLASS::IN,
|
||||
TTL,
|
||||
RData::SOA(SOA {
|
||||
mname: origin.clone(),
|
||||
// There is no mailbox behind this zone and inventing one would
|
||||
// be a fiction; the origin itself is the honest answer.
|
||||
rname: origin,
|
||||
serial: zone.serial(),
|
||||
refresh: TTL as i32,
|
||||
retry: TTL as i32,
|
||||
expire: 86_400,
|
||||
minimum: TTL,
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
fn query_kind(qtype: QTYPE) -> Query {
|
||||
match qtype {
|
||||
QTYPE::TYPE(TYPE::A) => Query::A,
|
||||
QTYPE::TYPE(TYPE::PTR) => Query::Ptr,
|
||||
QTYPE::TYPE(TYPE::SOA) => Query::Soa,
|
||||
QTYPE::TYPE(TYPE::NS) => Query::Ns,
|
||||
// ANY is answered as an address question rather than by dumping the
|
||||
// zone: an ANY that returns everything is an amplification gift.
|
||||
QTYPE::ANY => Query::A,
|
||||
_ => Query::Other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the client offered EDNS, and so how large an answer it will take.
|
||||
fn udp_limit(query: &[u8]) -> usize {
|
||||
parse_message(query)
|
||||
.and_then(|packet| packet.opt().map(|opt| opt.udp_packet_size as usize))
|
||||
.unwrap_or(CLASSIC_UDP_LIMIT as u16 as usize)
|
||||
.clamp(CLASSIC_UDP_LIMIT, MAX_MESSAGE_LEN)
|
||||
}
|
||||
|
||||
/// Cuts an answer down to what the client said it would take.
|
||||
///
|
||||
/// 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
|
||||
/// look like packet loss.
|
||||
pub fn truncate_for_udp(query: &[u8], reply: Vec<u8>, payload_limit: usize) -> Vec<u8> {
|
||||
let limit = udp_limit(query).min(payload_limit);
|
||||
if reply.len() <= limit {
|
||||
return reply;
|
||||
}
|
||||
let Some(mut short) = parse_message(&reply) else {
|
||||
return reply;
|
||||
};
|
||||
short.set_flags(PacketFlag::TRUNCATION);
|
||||
short.answers.clear();
|
||||
short.name_servers.clear();
|
||||
short.additional_records.clear();
|
||||
*short.opt_mut() = None;
|
||||
short.build_bytes_vec().unwrap_or(reply)
|
||||
}
|
||||
|
||||
/// A running DNS server.
|
||||
#[derive(Debug)]
|
||||
pub struct DnsServer {
|
||||
local_addr: SocketAddr,
|
||||
tasks: Vec<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl DnsServer {
|
||||
/// Binds and starts answering.
|
||||
///
|
||||
/// Both transports on the same address and port, as a resolver expects:
|
||||
/// it falls back to TCP when an answer does not fit, and a server that
|
||||
/// only listened on UDP would leave it with nowhere to go.
|
||||
pub async fn bind(addr: SocketAddr, zone: SharedZone) -> std::io::Result<Self> {
|
||||
let udp = tokio::net::UdpSocket::bind(addr).await?;
|
||||
let local_addr = udp.local_addr()?;
|
||||
let tcp = tokio::net::TcpListener::bind(local_addr).await?;
|
||||
|
||||
let udp_zone = zone.clone();
|
||||
let udp_task = tokio::spawn(async move {
|
||||
let mut buffer = vec![0u8; MAX_MESSAGE_LEN];
|
||||
loop {
|
||||
let (read, from) = match udp.recv_from(&mut buffer).await {
|
||||
Ok(pair) => pair,
|
||||
Err(err) => {
|
||||
tracing::debug!(%err, "dns udp receive failed");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let query = &buffer[..read];
|
||||
let Some(reply) = respond(&udp_zone.get(), query) else {
|
||||
continue;
|
||||
};
|
||||
let reply = truncate_for_udp(query, reply, MAX_MESSAGE_LEN);
|
||||
if let Err(err) = udp.send_to(&reply, from).await {
|
||||
tracing::debug!(%err, "dns udp reply failed");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let tcp_zone = zone.clone();
|
||||
let tcp_task = tokio::spawn(async move {
|
||||
let permits = Arc::new(tokio::sync::Semaphore::new(MAX_TCP_CONNECTIONS));
|
||||
loop {
|
||||
let (stream, _) = match tcp.accept().await {
|
||||
Ok(pair) => pair,
|
||||
Err(err) => {
|
||||
tracing::debug!(%err, "dns tcp accept failed");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Ok(permit) = Arc::clone(&permits).acquire_owned().await else {
|
||||
return;
|
||||
};
|
||||
let zone = tcp_zone.clone();
|
||||
tokio::spawn(async move {
|
||||
let _permit = permit;
|
||||
// Bounded, so a client that connects and says nothing
|
||||
// cannot hold a slot open.
|
||||
let _ = tokio::time::timeout(TCP_TIMEOUT, serve_tcp(stream, zone)).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
local_addr,
|
||||
tasks: vec![udp_task, tcp_task],
|
||||
})
|
||||
}
|
||||
|
||||
/// The address it is answering on.
|
||||
pub fn local_addr(&self) -> SocketAddr {
|
||||
self.local_addr
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DnsServer {
|
||||
fn drop(&mut self) {
|
||||
for task in &self.tasks {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_tcp(mut stream: tokio::net::TcpStream, zone: SharedZone) -> std::io::Result<()> {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
loop {
|
||||
let mut header = [0u8; 2];
|
||||
if stream.read_exact(&mut header).await.is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
// Checked before the buffer is allocated, as everywhere else that
|
||||
// reads a length off a wire.
|
||||
let len = u16::from_be_bytes(header) as usize;
|
||||
if len == 0 || len > MAX_MESSAGE_LEN {
|
||||
return Ok(());
|
||||
}
|
||||
let mut query = vec![0u8; len];
|
||||
stream.read_exact(&mut query).await?;
|
||||
|
||||
let Some(reply) = respond(&zone.get(), &query) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Ok(len) = u16::try_from(reply.len()) else {
|
||||
return Ok(());
|
||||
};
|
||||
stream.write_all(&len.to_be_bytes()).await?;
|
||||
stream.write_all(&reply).await?;
|
||||
stream.flush().await?;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
use crate::dns::zone::ZoneName;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
fn zone() -> Zones {
|
||||
Zones::new([one_zone()])
|
||||
}
|
||||
|
||||
fn one_zone() -> Zone {
|
||||
Zone::new(
|
||||
ZoneName::new("lab").unwrap(),
|
||||
[
|
||||
("music".to_string(), Ipv4Addr::new(10, 13, 37, 237)),
|
||||
("ai".to_string(), Ipv4Addr::new(10, 13, 37, 69)),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn ask(name: &str, qtype: TYPE) -> Vec<u8> {
|
||||
let mut packet = simple_dns::Packet::new_query(0x1234);
|
||||
packet.questions.push(simple_dns::Question::new(
|
||||
Name::new(name).unwrap(),
|
||||
qtype.into(),
|
||||
QCLASS::CLASS(simple_dns::CLASS::IN),
|
||||
false,
|
||||
));
|
||||
packet.build_bytes_vec().unwrap()
|
||||
}
|
||||
|
||||
/// The bytes of a reply. Parsed by each caller, because a parsed packet
|
||||
/// borrows from them.
|
||||
fn answer(query: &[u8]) -> Vec<u8> {
|
||||
respond(&zone(), query).expect("a reply")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_is_answered_authoritatively() {
|
||||
let bytes = answer(&ask("music.lab", TYPE::A));
|
||||
let reply = simple_dns::Packet::parse(&bytes).unwrap();
|
||||
assert_eq!(reply.rcode(), RCODE::NoError);
|
||||
assert!(reply.has_flags(PacketFlag::RESPONSE));
|
||||
assert!(reply.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
|
||||
assert!(!reply.has_flags(PacketFlag::RECURSION_AVAILABLE));
|
||||
assert_eq!(reply.answers.len(), 1);
|
||||
assert_eq!(reply.questions.len(), 1, "the question is echoed");
|
||||
match &reply.answers[0].rdata {
|
||||
RData::A(a) => assert_eq!(Ipv4Addr::from(a.address), Ipv4Addr::new(10, 13, 37, 237)),
|
||||
other => panic!("expected an A record, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_name_is_denied_with_a_soa_to_cache_the_denial() {
|
||||
let bytes = answer(&ask("nobody.lab", TYPE::A));
|
||||
let reply = simple_dns::Packet::parse(&bytes).unwrap();
|
||||
assert_eq!(reply.rcode(), RCODE::NameError);
|
||||
assert!(reply.answers.is_empty());
|
||||
assert_eq!(
|
||||
reply.name_servers.len(),
|
||||
1,
|
||||
"a SOA bounds the negative cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_exists_without_that_record_is_not_denied() {
|
||||
// NODATA, not NXDOMAIN: denying the name would stop a resolver
|
||||
// asking for the A record it could have had.
|
||||
let bytes = answer(&ask("music.lab", TYPE::AAAA));
|
||||
let reply = simple_dns::Packet::parse(&bytes).unwrap();
|
||||
assert_eq!(reply.rcode(), RCODE::NoError);
|
||||
assert!(reply.answers.is_empty());
|
||||
assert_eq!(reply.name_servers.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anything_outside_the_zone_is_refused_and_never_forwarded() {
|
||||
for name in ["example.com", "evillab", "google.com"] {
|
||||
let bytes = answer(&ask(name, TYPE::A));
|
||||
let reply = simple_dns::Packet::parse(&bytes).unwrap();
|
||||
assert_eq!(reply.rcode(), RCODE::Refused, "{name}");
|
||||
assert!(reply.answers.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_is_answered_backwards() {
|
||||
let bytes = answer(&ask("237.37.13.10.in-addr.arpa", TYPE::PTR));
|
||||
let reply = simple_dns::Packet::parse(&bytes).unwrap();
|
||||
assert_eq!(reply.rcode(), RCODE::NoError);
|
||||
match &reply.answers[0].rdata {
|
||||
RData::PTR(ptr) => assert_eq!(ptr.0.to_string(), "music.lab"),
|
||||
other => panic!("expected a PTR record, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reply_is_never_sent_to_something_that_was_not_a_question() {
|
||||
// Answering a response would make this a reflector for anyone who
|
||||
// can spoof a source address.
|
||||
let mut packet = simple_dns::Packet::new_reply(1);
|
||||
packet.set_flags(PacketFlag::RESPONSE);
|
||||
assert!(respond(&zone(), &packet.build_bytes_vec().unwrap()).is_none());
|
||||
assert!(respond(&zone(), b"").is_none());
|
||||
assert!(respond(&zone(), b"not a dns packet at all").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_question_with_no_question_in_it_is_a_format_error() {
|
||||
let packet = simple_dns::Packet::new_query(7);
|
||||
let bytes = respond(&zone(), &packet.build_bytes_vec().unwrap()).unwrap();
|
||||
let reply = simple_dns::Packet::parse(&bytes).unwrap();
|
||||
assert_eq!(reply.rcode(), RCODE::FormatError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_other_than_internet_is_refused() {
|
||||
let mut packet = simple_dns::Packet::new_query(9);
|
||||
packet.questions.push(simple_dns::Question::new(
|
||||
Name::new("music.lab").unwrap(),
|
||||
TYPE::A.into(),
|
||||
QCLASS::CLASS(simple_dns::CLASS::CH),
|
||||
false,
|
||||
));
|
||||
let bytes = respond(&zone(), &packet.build_bytes_vec().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
simple_dns::Packet::parse(&bytes).unwrap().rcode(),
|
||||
RCODE::Refused
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_too_large_for_udp_is_truncated_rather_than_dropped() {
|
||||
// A resolver that gets a truncated reply asks again over TCP; one
|
||||
// that gets nothing back just waits.
|
||||
let many: Vec<(String, Ipv4Addr)> = (0..200)
|
||||
.map(|i| ("host".to_string(), Ipv4Addr::new(10, 13, 37, i as u8)))
|
||||
.collect();
|
||||
let wide = Zones::new([Zone::new(ZoneName::new("lab").unwrap(), many)]);
|
||||
let query = ask("host.lab", TYPE::A);
|
||||
let full = respond(&wide, &query).unwrap();
|
||||
assert!(
|
||||
full.len() > CLASSIC_UDP_LIMIT,
|
||||
"the test needs a big answer"
|
||||
);
|
||||
|
||||
let short = truncate_for_udp(&query, full, MAX_MESSAGE_LEN);
|
||||
assert!(short.len() <= CLASSIC_UDP_LIMIT);
|
||||
let parsed = simple_dns::Packet::parse(&short).unwrap();
|
||||
assert!(parsed.has_flags(PacketFlag::TRUNCATION));
|
||||
assert_eq!(parsed.questions.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_server_answers_over_udp_and_tcp_on_one_address() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
let shared = SharedZone::new(zone());
|
||||
let server = DnsServer::bind("127.0.0.1:0".parse().unwrap(), shared.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let addr = server.local_addr();
|
||||
|
||||
let client = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
client
|
||||
.send_to(&ask("music.lab", TYPE::A), addr)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut buffer = vec![0u8; MAX_MESSAGE_LEN];
|
||||
let read = client.recv(&mut buffer).await.unwrap();
|
||||
let reply = simple_dns::Packet::parse(&buffer[..read]).unwrap();
|
||||
assert_eq!(reply.answers.len(), 1);
|
||||
|
||||
let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
|
||||
let query = ask("ai.lab", TYPE::A);
|
||||
stream
|
||||
.write_all(&(query.len() as u16).to_be_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
stream.write_all(&query).await.unwrap();
|
||||
let mut header = [0u8; 2];
|
||||
stream.read_exact(&mut header).await.unwrap();
|
||||
let mut body = vec![0u8; u16::from_be_bytes(header) as usize];
|
||||
stream.read_exact(&mut body).await.unwrap();
|
||||
let reply = simple_dns::Packet::parse(&body).unwrap();
|
||||
assert_eq!(reply.answers.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_same_zone_is_answered_over_ipv6_as_over_ipv4() {
|
||||
// A question arrives over whichever family the resolver chooses, so
|
||||
// a listener is opened from each list in the plan and both have to
|
||||
// answer the same thing. Answering one family only leaves the other
|
||||
// timing out, which looks like a broken overlay.
|
||||
let shared = SharedZone::new(zone());
|
||||
let plan = crate::dns::listen_plan(0);
|
||||
let mut answered = 0;
|
||||
|
||||
for family in plan.families() {
|
||||
let candidate = family[0];
|
||||
let server = match DnsServer::bind(candidate, shared.clone()).await {
|
||||
Ok(server) => server,
|
||||
// A host with IPv6 switched off in the kernel cannot bind
|
||||
// `::1`, and the agent copes with that by design; so does
|
||||
// this. The other family still has to work.
|
||||
Err(err) if candidate.is_ipv6() => {
|
||||
eprintln!("no IPv6 loopback on this host ({err}); skipping that family");
|
||||
continue;
|
||||
}
|
||||
Err(err) => panic!("cannot listen on {candidate}: {err}"),
|
||||
};
|
||||
let addr = server.local_addr();
|
||||
assert_eq!(addr.is_ipv6(), candidate.is_ipv6());
|
||||
|
||||
let client = tokio::net::UdpSocket::bind(if addr.is_ipv6() {
|
||||
"[::1]:0"
|
||||
} else {
|
||||
"127.0.0.1:0"
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
client
|
||||
.send_to(&ask("music.lab", TYPE::A), addr)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut buffer = vec![0u8; MAX_MESSAGE_LEN];
|
||||
let read = client.recv(&mut buffer).await.unwrap();
|
||||
let reply = simple_dns::Packet::parse(&buffer[..read]).unwrap();
|
||||
assert_eq!(reply.rcode(), RCODE::NoError, "over {addr}");
|
||||
match &reply.answers[0].rdata {
|
||||
// The same IPv4 answer either way: the family a question
|
||||
// travelled over says nothing about what the answer is.
|
||||
RData::A(a) => {
|
||||
assert_eq!(Ipv4Addr::from(a.address), Ipv4Addr::new(10, 13, 37, 237))
|
||||
}
|
||||
other => panic!("expected an A record over {addr}, got {other:?}"),
|
||||
}
|
||||
answered += 1;
|
||||
}
|
||||
|
||||
assert!(answered > 0, "at least one family must have answered");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replacing_the_zone_changes_what_the_running_server_answers() {
|
||||
let shared = SharedZone::one(Zone::new(ZoneName::new("lab").unwrap(), []));
|
||||
let server = DnsServer::bind("127.0.0.1:0".parse().unwrap(), shared.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let addr = server.local_addr();
|
||||
let client = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let mut buffer = vec![0u8; MAX_MESSAGE_LEN];
|
||||
|
||||
client
|
||||
.send_to(&ask("music.lab", TYPE::A), addr)
|
||||
.await
|
||||
.unwrap();
|
||||
let read = client.recv(&mut buffer).await.unwrap();
|
||||
assert_eq!(
|
||||
simple_dns::Packet::parse(&buffer[..read]).unwrap().rcode(),
|
||||
RCODE::NameError
|
||||
);
|
||||
|
||||
// A member joins: no rebind, no dropped socket.
|
||||
shared.set(zone());
|
||||
client
|
||||
.send_to(&ask("music.lab", TYPE::A), addr)
|
||||
.await
|
||||
.unwrap();
|
||||
let read = client.recv(&mut buffer).await.unwrap();
|
||||
let reply = simple_dns::Packet::parse(&buffer[..read]).unwrap();
|
||||
assert_eq!(reply.rcode(), RCODE::NoError);
|
||||
assert_eq!(reply.answers.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,767 @@
|
||||
//! What the overlay answers to, as a DNS zone.
|
||||
//!
|
||||
//! Nothing here touches a socket or the operating system, and it does not
|
||||
//! depend on a DNS wire library either: it takes a roster and a question and
|
||||
//! says what the answer is. That is what makes the interesting parts — which
|
||||
//! names exist, what "does not exist" means as against "exists with nothing
|
||||
//! of that type", and what is outside the zone entirely — testable on their
|
||||
//! own.
|
||||
//!
|
||||
//! # Where the names come from
|
||||
//!
|
||||
//! From signed state, which is why a member that is switched off still
|
||||
//! resolves. Its claim outlived the session, so the name and the address are
|
||||
//! both still there to answer with. Nothing is invented for a member that
|
||||
//! claimed neither.
|
||||
//!
|
||||
//! Only IPv4 is served. The IPv6 overlay address is derived from a
|
||||
//! WireGuard key that travels in live announcements and is not in signed
|
||||
//! state, so it cannot be answered for a member that is away — and answering
|
||||
//! for some members and not others depending on whether they happen to be
|
||||
//! online is worse than not answering at all.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
/// Longest a DNS name may be, in the presentation form used here.
|
||||
const MAX_NAME_LEN: usize = 253;
|
||||
/// Longest one label may be.
|
||||
const MAX_LABEL_LEN: usize = 63;
|
||||
|
||||
/// Why a zone name cannot be used.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ZoneError {
|
||||
/// The name was empty, or became empty once normalised.
|
||||
#[error("a zone name must have at least one label")]
|
||||
Empty,
|
||||
/// One label was unusable.
|
||||
#[error("`{label}` is not a usable DNS label: {reason}")]
|
||||
Label {
|
||||
/// The offending label.
|
||||
label: String,
|
||||
/// What is wrong with it.
|
||||
reason: &'static str,
|
||||
},
|
||||
/// The whole name is too long.
|
||||
#[error("a zone name must be at most {MAX_NAME_LEN} characters")]
|
||||
TooLong,
|
||||
}
|
||||
|
||||
/// A validated, canonical zone name.
|
||||
///
|
||||
/// Held without a trailing dot and lower-cased, so comparison is a plain
|
||||
/// string comparison rather than a special case at every use.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct ZoneName(String);
|
||||
|
||||
impl ZoneName {
|
||||
/// Validates and normalises a zone name.
|
||||
pub fn new(raw: &str) -> Result<Self, ZoneError> {
|
||||
let trimmed = raw.trim().trim_end_matches('.').to_ascii_lowercase();
|
||||
if trimmed.is_empty() {
|
||||
return Err(ZoneError::Empty);
|
||||
}
|
||||
if trimmed.len() > MAX_NAME_LEN {
|
||||
return Err(ZoneError::TooLong);
|
||||
}
|
||||
for label in trimmed.split('.') {
|
||||
let reason = if label.is_empty() {
|
||||
Some("it is empty")
|
||||
} else if label.len() > MAX_LABEL_LEN {
|
||||
Some("it is longer than 63 characters")
|
||||
} else if !label
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
{
|
||||
Some("only letters, digits, `-` and `_` are allowed")
|
||||
} else if label.starts_with('-') || label.ends_with('-') {
|
||||
Some("a label may not start or end with `-`")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(reason) = reason {
|
||||
return Err(ZoneError::Label {
|
||||
label: label.to_string(),
|
||||
reason,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Self(trimmed))
|
||||
}
|
||||
|
||||
/// The name, without a trailing dot.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// The last label, which is what would collide with a real top-level
|
||||
/// domain.
|
||||
pub fn top_label(&self) -> &str {
|
||||
self.0.rsplit('.').next().unwrap_or(&self.0)
|
||||
}
|
||||
|
||||
/// What is worrying about this zone name, if anything.
|
||||
///
|
||||
/// A warning and never a refusal: the name is the user's to choose, and
|
||||
/// a private zone that shadows a public one is a decision, not a
|
||||
/// mistake. Saying nothing would let it be an accident.
|
||||
pub fn collision(&self) -> Option<String> {
|
||||
let top = self.top_label();
|
||||
// Reserved for exactly this use and never delegated, so nothing to
|
||||
// say. See RFC 6761 and RFC 8375.
|
||||
const RESERVED: &[&str] = &[
|
||||
"internal",
|
||||
"home",
|
||||
"test",
|
||||
"example",
|
||||
"invalid",
|
||||
"localhost",
|
||||
];
|
||||
if RESERVED.contains(&top) {
|
||||
return None;
|
||||
}
|
||||
if top == "local" {
|
||||
return Some(
|
||||
"`.local` belongs to multicast DNS: on a host running Avahi or \
|
||||
systemd-resolved's mDNS, names under it are resolved by that and \
|
||||
not by this agent"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
// A real top-level domain is the whole of it. A name that is not
|
||||
// delegated today might be one day — and saying so fires on every
|
||||
// private name anybody ever picks, which is a warning about
|
||||
// nothing that teaches people to ignore warnings.
|
||||
tld::exist_case_insensitive(top).then(|| {
|
||||
format!(
|
||||
"`.{top}` is a real top-level domain, so every public name under it \
|
||||
becomes unreachable from this host while the overlay is up"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `name` is this zone or sits under it.
|
||||
///
|
||||
/// Compared label-wise, so `evilzone` does not count as being under
|
||||
/// `zone`.
|
||||
pub fn covers(&self, name: &str) -> bool {
|
||||
let name = name.trim_end_matches('.').to_ascii_lowercase();
|
||||
name == self.0
|
||||
|| name
|
||||
.strip_suffix(&self.0)
|
||||
.is_some_and(|rest| rest.ends_with('.'))
|
||||
}
|
||||
|
||||
/// The part of `name` below this zone, if it is under it.
|
||||
fn relative(&self, name: &str) -> Option<String> {
|
||||
let name = name.trim_end_matches('.').to_ascii_lowercase();
|
||||
if name == self.0 {
|
||||
return Some(String::new());
|
||||
}
|
||||
let rest = name.strip_suffix(&self.0)?;
|
||||
let rest = rest.strip_suffix('.')?;
|
||||
(!rest.is_empty()).then(|| rest.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The kinds of question this zone knows how to answer.
|
||||
///
|
||||
/// Its own enum rather than the wire library's, so the decision of what to
|
||||
/// answer does not depend on how a packet is encoded.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Query {
|
||||
/// An IPv4 address.
|
||||
A,
|
||||
/// A name for an address.
|
||||
Ptr,
|
||||
/// The zone's start of authority.
|
||||
Soa,
|
||||
/// The zone's name servers.
|
||||
Ns,
|
||||
/// Anything else, including AAAA.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What the zone has to say.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Answer {
|
||||
/// Addresses for the name asked about.
|
||||
Addresses(Vec<Ipv4Addr>),
|
||||
/// A name for the address asked about.
|
||||
Name(String),
|
||||
/// The zone's start of authority.
|
||||
Soa,
|
||||
/// The name exists here but has nothing of the type asked for.
|
||||
///
|
||||
/// Distinct from [`Answer::NoSuchName`] because the two are different
|
||||
/// answers on the wire: this one is a success with no records, and a
|
||||
/// resolver must not take it as proof the name is absent. Getting them
|
||||
/// the wrong way round teaches a resolver to cache the wrong thing.
|
||||
NoData,
|
||||
/// No such name in this zone.
|
||||
NoSuchName,
|
||||
/// Not a name this zone is responsible for.
|
||||
NotOurs,
|
||||
}
|
||||
|
||||
/// The names and addresses of one network, ready to answer questions.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Zone {
|
||||
origin: ZoneName,
|
||||
reverse_range: Option<crate::state::Ipv4Range>,
|
||||
/// Name relative to the origin, to the addresses it answers to.
|
||||
hosts: BTreeMap<String, Vec<Ipv4Addr>>,
|
||||
/// Address to the name that holds it.
|
||||
names: BTreeMap<Ipv4Addr, String>,
|
||||
/// Changes whenever the contents do.
|
||||
serial: u32,
|
||||
}
|
||||
|
||||
impl Zone {
|
||||
/// Builds a zone from the members that have both a name and an address.
|
||||
///
|
||||
/// A member with one but not the other contributes nothing: a name with
|
||||
/// no address cannot be answered, and an address with no name has nothing
|
||||
/// to be asked about.
|
||||
pub fn new(origin: ZoneName, members: impl IntoIterator<Item = (String, Ipv4Addr)>) -> Self {
|
||||
let mut hosts: BTreeMap<String, Vec<Ipv4Addr>> = BTreeMap::new();
|
||||
let mut names: BTreeMap<Ipv4Addr, String> = BTreeMap::new();
|
||||
for (hostname, address) in members {
|
||||
let hostname = hostname.trim_matches('.').to_ascii_lowercase();
|
||||
if hostname.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let addresses = hosts.entry(hostname.clone()).or_default();
|
||||
if !addresses.contains(&address) {
|
||||
addresses.push(address);
|
||||
}
|
||||
// First name wins, and the map is ordered, so the reverse answer
|
||||
// is the same on every replica rather than depending on the order
|
||||
// records happened to arrive in.
|
||||
names.entry(address).or_insert(hostname);
|
||||
}
|
||||
for addresses in hosts.values_mut() {
|
||||
addresses.sort();
|
||||
}
|
||||
|
||||
let serial = content_serial(&hosts);
|
||||
Self {
|
||||
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,
|
||||
names,
|
||||
serial,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn with_reverse_range(mut self, range: Option<crate::state::Ipv4Range>) -> Self {
|
||||
self.reverse_range = range;
|
||||
self
|
||||
}
|
||||
|
||||
/// The zone's origin.
|
||||
pub fn origin(&self) -> &ZoneName {
|
||||
&self.origin
|
||||
}
|
||||
|
||||
/// A number that changes whenever the contents do.
|
||||
pub fn serial(&self) -> u32 {
|
||||
self.serial
|
||||
}
|
||||
|
||||
/// How many names it answers for.
|
||||
pub fn len(&self) -> usize {
|
||||
self.hosts.len()
|
||||
}
|
||||
|
||||
/// Whether it answers for nothing.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.hosts.is_empty()
|
||||
}
|
||||
|
||||
/// Every name it answers for, with its addresses.
|
||||
pub fn entries(&self) -> impl Iterator<Item = (&str, &[Ipv4Addr])> {
|
||||
self.hosts
|
||||
.iter()
|
||||
.map(|(name, addresses)| (name.as_str(), addresses.as_slice()))
|
||||
}
|
||||
|
||||
/// The reverse zones this zone is authoritative for.
|
||||
///
|
||||
/// Only when the range lands on an octet boundary. Claiming a reverse
|
||||
/// zone larger than the range would shadow reverse lookups for addresses
|
||||
/// that are nothing to do with us, which is worse than not answering.
|
||||
pub fn reverse_origin(base: Ipv4Addr, prefix_len: u8) -> Option<String> {
|
||||
let octets = base.octets();
|
||||
match prefix_len {
|
||||
8 => Some(format!("{}.in-addr.arpa", octets[0])),
|
||||
16 => Some(format!("{}.{}.in-addr.arpa", octets[1], octets[0])),
|
||||
24 => Some(format!(
|
||||
"{}.{}.{}.in-addr.arpa",
|
||||
octets[2], octets[1], octets[0]
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers one question.
|
||||
pub fn lookup(&self, qname: &str, query: Query) -> Answer {
|
||||
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) {
|
||||
Some(name) if query == Query::Ptr => {
|
||||
Answer::Name(format!("{name}.{}", self.origin.as_str()))
|
||||
}
|
||||
Some(_) => Answer::NoData,
|
||||
None => Answer::NoSuchName,
|
||||
};
|
||||
}
|
||||
|
||||
let Some(relative) = self.origin.relative(qname) else {
|
||||
return Answer::NotOurs;
|
||||
};
|
||||
|
||||
// The apex: the zone itself exists whether or not anybody is in it.
|
||||
if relative.is_empty() {
|
||||
return match query {
|
||||
Query::Soa => Answer::Soa,
|
||||
Query::Ns => Answer::NoData,
|
||||
_ => Answer::NoData,
|
||||
};
|
||||
}
|
||||
|
||||
match self.hosts.get(&relative) {
|
||||
Some(addresses) if query == Query::A => Answer::Addresses(addresses.clone()),
|
||||
// The name is here, it just has no AAAA and never will while
|
||||
// only IPv4 is served. Saying "no such name" instead would tell
|
||||
// a resolver to stop asking for the A record too.
|
||||
Some(_) => Answer::NoData,
|
||||
None => Answer::NoSuchName,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every zone one agent serves.
|
||||
///
|
||||
/// One agent has one identity and as many networks as it likes, and each of
|
||||
/// them is a zone of its own named after the network. They are served
|
||||
/// together because they arrive at the same socket: a question is not
|
||||
/// labelled with the network it belongs to, only with a name, and the
|
||||
/// suffix is what decides. Nothing is shared between them — a member of one
|
||||
/// network is not a name in another.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Zones {
|
||||
zones: Vec<Zone>,
|
||||
}
|
||||
|
||||
impl Zones {
|
||||
/// Collects zones, dropping any that repeats an origin already taken.
|
||||
///
|
||||
/// Two networks can be given the same name, and then only one of them
|
||||
/// can own the suffix. First wins, deterministically, rather than one
|
||||
/// shadowing the other depending on the order they happened to start.
|
||||
pub fn new(zones: impl IntoIterator<Item = Zone>) -> Self {
|
||||
let mut taken: Vec<Zone> = Vec::new();
|
||||
for zone in zones {
|
||||
if taken.iter().any(|other| other.origin() == zone.origin()) {
|
||||
continue;
|
||||
}
|
||||
taken.push(zone);
|
||||
}
|
||||
Self { zones: taken }
|
||||
}
|
||||
|
||||
/// The zones, in the order they will be consulted.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Zone> {
|
||||
self.zones.iter()
|
||||
}
|
||||
|
||||
/// How many zones are served.
|
||||
pub fn len(&self) -> usize {
|
||||
self.zones.len()
|
||||
}
|
||||
|
||||
/// Whether nothing is served.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.zones.is_empty()
|
||||
}
|
||||
|
||||
/// How many names are answered for, across every zone.
|
||||
pub fn names(&self) -> usize {
|
||||
self.zones.iter().map(Zone::len).sum()
|
||||
}
|
||||
|
||||
/// Answers one question, and says which zone answered it.
|
||||
///
|
||||
/// The answer has to travel with its zone because the SOA that bounds a
|
||||
/// denial belongs to the zone that denied it, and serving several means
|
||||
/// that is no longer a foregone conclusion.
|
||||
///
|
||||
/// A reverse question carries no suffix to match on, so every zone is
|
||||
/// asked and the one that holds the address answers; if none does, the
|
||||
/// denial comes from whichever is authoritative for that reverse zone,
|
||||
/// and from nowhere at all when none is.
|
||||
pub fn lookup(&self, qname: &str, query: Query) -> Option<(&Zone, Answer)> {
|
||||
let mut denial: Option<(&Zone, Answer)> = None;
|
||||
for zone in &self.zones {
|
||||
match zone.lookup(qname, query) {
|
||||
// Not this zone's question. Another may still own it.
|
||||
Answer::NotOurs => continue,
|
||||
// A zone that owns the suffix but not the name can still be
|
||||
// overruled by one that has an answer: only reverse
|
||||
// questions reach more than one zone, and there the zone
|
||||
// holding the address is the one that knows.
|
||||
answer @ (Answer::NoSuchName | Answer::NoData) => {
|
||||
denial.get_or_insert((zone, answer));
|
||||
}
|
||||
answer => return Some((zone, answer)),
|
||||
}
|
||||
}
|
||||
denial
|
||||
}
|
||||
}
|
||||
|
||||
/// The address a reverse name asks about, if it is one.
|
||||
fn reverse_address(qname: &str) -> Option<Ipv4Addr> {
|
||||
let name = qname.trim_end_matches('.').to_ascii_lowercase();
|
||||
let rest = name.strip_suffix(".in-addr.arpa")?;
|
||||
let mut octets = [0u8; 4];
|
||||
let mut seen = 0;
|
||||
for (index, part) in rest.split('.').enumerate() {
|
||||
if index >= 4 {
|
||||
return None;
|
||||
}
|
||||
octets[3 - index] = part.parse().ok()?;
|
||||
seen += 1;
|
||||
}
|
||||
(seen == 4).then(|| Ipv4Addr::from(octets))
|
||||
}
|
||||
|
||||
/// A serial that changes with the contents and not otherwise.
|
||||
///
|
||||
/// Derived rather than counted, so two agents holding the same roster agree,
|
||||
/// and a restart does not go backwards.
|
||||
fn content_serial(hosts: &BTreeMap<String, Vec<Ipv4Addr>>) -> u32 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
for (name, addresses) in hosts {
|
||||
name.hash(&mut hasher);
|
||||
for address in addresses {
|
||||
address.octets().hash(&mut hasher);
|
||||
}
|
||||
}
|
||||
// Never zero: a zero serial is legal but reads like "unset" in a log.
|
||||
(hasher.finish() as u32).max(1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
|
||||
fn zone() -> Zone {
|
||||
Zone::new(
|
||||
ZoneName::new("lab").unwrap(),
|
||||
[
|
||||
("music".to_string(), Ipv4Addr::new(10, 13, 37, 237)),
|
||||
("ai".to_string(), Ipv4Addr::new(10, 13, 37, 69)),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_name_is_normalised_and_checked() {
|
||||
assert_eq!(ZoneName::new("LAB.").unwrap().as_str(), "lab");
|
||||
assert_eq!(
|
||||
ZoneName::new(" lab.internal ").unwrap().as_str(),
|
||||
"lab.internal"
|
||||
);
|
||||
assert_eq!(
|
||||
ZoneName::new("lab.internal").unwrap().top_label(),
|
||||
"internal"
|
||||
);
|
||||
|
||||
assert_eq!(ZoneName::new("").unwrap_err(), ZoneError::Empty);
|
||||
assert_eq!(ZoneName::new(".").unwrap_err(), ZoneError::Empty);
|
||||
assert!(matches!(
|
||||
ZoneName::new("a..b").unwrap_err(),
|
||||
ZoneError::Label { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
ZoneName::new("-lab").unwrap_err(),
|
||||
ZoneError::Label { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
ZoneName::new("la b").unwrap_err(),
|
||||
ZoneError::Label { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
ZoneName::new(&"x".repeat(64)).unwrap_err(),
|
||||
ZoneError::Label { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_name_that_shadows_a_public_one_is_flagged_but_allowed() {
|
||||
// Flagged, never refused: shadowing is the user's decision to make.
|
||||
let ru = ZoneName::new("ru").unwrap();
|
||||
let warning = ru.collision().expect("a real TLD is worth mentioning");
|
||||
assert!(warning.contains("real top-level domain"), "{warning}");
|
||||
|
||||
assert!(ZoneName::new("com").unwrap().collision().is_some());
|
||||
assert!(ZoneName::new("lab.com").unwrap().collision().is_some());
|
||||
|
||||
// Reserved for private use, so nothing to say.
|
||||
for quiet in ["internal", "lab.internal", "home", "test", "invalid"] {
|
||||
assert_eq!(ZoneName::new(quiet).unwrap().collision(), None, "{quiet}");
|
||||
}
|
||||
|
||||
// `.local` is not a delegated TLD, but it is not free either.
|
||||
let local = ZoneName::new("local").unwrap().collision().unwrap();
|
||||
assert!(local.contains("multicast DNS"), "{local}");
|
||||
|
||||
// A name that collides with nothing is said nothing about. It
|
||||
// might be delegated one day, and warning about that fires on
|
||||
// every private name anybody picks — a warning about nothing,
|
||||
// which is how people learn to ignore warnings.
|
||||
for quiet in ["lab", "a.lab", "pidar", "twar", "kitchen-table"] {
|
||||
assert_eq!(ZoneName::new(quiet).unwrap().collision(), None, "{quiet}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_neighbouring_name_is_not_inside_the_zone() {
|
||||
// `evillab` ends with `lab`, and a suffix comparison that forgot the
|
||||
// label boundary would hand it to us.
|
||||
let origin = ZoneName::new("lab").unwrap();
|
||||
assert!(origin.covers("lab"));
|
||||
assert!(origin.covers("music.lab."));
|
||||
assert!(origin.covers("a.b.lab"));
|
||||
assert!(!origin.covers("evillab"));
|
||||
assert!(!origin.covers("lab.example.com"));
|
||||
assert!(!origin.covers("example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_resolves_by_name() {
|
||||
let zone = zone();
|
||||
assert_eq!(
|
||||
zone.lookup("music.lab", Query::A),
|
||||
Answer::Addresses(vec![Ipv4Addr::new(10, 13, 37, 237)])
|
||||
);
|
||||
// Case and a trailing dot are the same question.
|
||||
assert_eq!(
|
||||
zone.lookup("MUSIC.LAB.", Query::A),
|
||||
Answer::Addresses(vec![Ipv4Addr::new(10, 13, 37, 237)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_with_no_record_of_that_type_is_not_a_missing_name() {
|
||||
// AAAA for a member that exists must be NODATA, not NXDOMAIN: an
|
||||
// NXDOMAIN would tell the resolver the name is absent and stop it
|
||||
// asking for the A record.
|
||||
let zone = zone();
|
||||
assert_eq!(zone.lookup("music.lab", Query::Other), Answer::NoData);
|
||||
assert_eq!(zone.lookup("nobody.lab", Query::A), Answer::NoSuchName);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn questions_outside_the_zone_are_refused_rather_than_denied() {
|
||||
// Denying them would be a lie: this server knows nothing about them.
|
||||
let zone = zone();
|
||||
assert_eq!(zone.lookup("example.com", Query::A), Answer::NotOurs);
|
||||
assert_eq!(zone.lookup("evillab", Query::A), Answer::NotOurs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_apex_exists_even_with_nobody_in_the_network() {
|
||||
let empty = Zone::new(ZoneName::new("lab").unwrap(), []);
|
||||
assert!(empty.is_empty());
|
||||
assert_eq!(empty.lookup("lab", Query::Soa), Answer::Soa);
|
||||
assert_eq!(empty.lookup("lab", Query::A), Answer::NoData);
|
||||
assert_eq!(empty.lookup("music.lab", Query::A), Answer::NoSuchName);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_resolves_back_to_its_name() {
|
||||
let zone = zone();
|
||||
assert_eq!(
|
||||
zone.lookup("237.37.13.10.in-addr.arpa", Query::Ptr),
|
||||
Answer::Name("music.lab".into())
|
||||
);
|
||||
assert_eq!(
|
||||
zone.lookup("9.37.13.10.in-addr.arpa", Query::Ptr),
|
||||
Answer::NoSuchName
|
||||
);
|
||||
// A reverse name asked for the wrong type is still a name we know.
|
||||
assert_eq!(
|
||||
zone.lookup("237.37.13.10.in-addr.arpa", Query::A),
|
||||
Answer::NoData
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reverse_zone_is_claimed_only_when_it_is_exactly_ours() {
|
||||
// Claiming a reverse zone wider than the range would shadow lookups
|
||||
// for addresses that have nothing to do with this network.
|
||||
assert_eq!(
|
||||
Zone::reverse_origin(Ipv4Addr::new(10, 13, 37, 0), 24).as_deref(),
|
||||
Some("37.13.10.in-addr.arpa")
|
||||
);
|
||||
assert_eq!(
|
||||
Zone::reverse_origin(Ipv4Addr::new(10, 13, 0, 0), 16).as_deref(),
|
||||
Some("13.10.in-addr.arpa")
|
||||
);
|
||||
assert_eq!(Zone::reverse_origin(Ipv4Addr::new(10, 13, 37, 0), 25), None);
|
||||
assert_eq!(Zone::reverse_origin(Ipv4Addr::new(100, 64, 0, 0), 10), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_with_nothing_to_say_are_left_out() {
|
||||
let zone = Zone::new(
|
||||
ZoneName::new("lab").unwrap(),
|
||||
[(String::new(), Ipv4Addr::new(10, 0, 0, 1))],
|
||||
);
|
||||
assert!(zone.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_members_sharing_a_name_both_answer_and_the_order_is_stable() {
|
||||
// The state layer resolves name ownership; if two records still
|
||||
// reach here, answering with both beats picking one at random.
|
||||
let build = |flip: bool| {
|
||||
let members = if flip {
|
||||
vec![
|
||||
("music".to_string(), Ipv4Addr::new(10, 0, 0, 2)),
|
||||
("music".to_string(), Ipv4Addr::new(10, 0, 0, 1)),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
("music".to_string(), Ipv4Addr::new(10, 0, 0, 1)),
|
||||
("music".to_string(), Ipv4Addr::new(10, 0, 0, 2)),
|
||||
]
|
||||
};
|
||||
Zone::new(ZoneName::new("lab").unwrap(), members)
|
||||
};
|
||||
assert_eq!(
|
||||
build(false).lookup("music.lab", Query::A),
|
||||
build(true).lookup("music.lab", Query::A)
|
||||
);
|
||||
assert_eq!(build(false).serial(), build(true).serial());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_serial_follows_the_contents() {
|
||||
let a = zone();
|
||||
let b = zone();
|
||||
assert_eq!(a.serial(), b.serial(), "the same roster, the same serial");
|
||||
|
||||
let changed = Zone::new(
|
||||
ZoneName::new("lab").unwrap(),
|
||||
[("music".to_string(), Ipv4Addr::new(10, 13, 37, 238))],
|
||||
);
|
||||
assert_ne!(a.serial(), changed.serial());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_network_answers_only_for_its_own_zone() {
|
||||
// One agent, several networks, one socket. A question carries a
|
||||
// name and not the network it belongs to, so the suffix is what
|
||||
// decides — and a member of one network is not a name in another.
|
||||
let zones = Zones::new([
|
||||
Zone::new(
|
||||
ZoneName::new("lab").unwrap(),
|
||||
[("music".to_string(), Ipv4Addr::new(10, 13, 37, 2))],
|
||||
),
|
||||
Zone::new(
|
||||
ZoneName::new("home").unwrap(),
|
||||
[("music".to_string(), Ipv4Addr::new(10, 20, 0, 2))],
|
||||
),
|
||||
]);
|
||||
assert_eq!(zones.len(), 2);
|
||||
assert_eq!(zones.names(), 2);
|
||||
|
||||
let (zone, answer) = zones.lookup("music.lab", Query::A).unwrap();
|
||||
assert_eq!(zone.origin().as_str(), "lab");
|
||||
assert_eq!(
|
||||
answer,
|
||||
Answer::Addresses(vec![Ipv4Addr::new(10, 13, 37, 2)])
|
||||
);
|
||||
|
||||
let (zone, answer) = zones.lookup("music.home", Query::A).unwrap();
|
||||
assert_eq!(zone.origin().as_str(), "home");
|
||||
assert_eq!(answer, Answer::Addresses(vec![Ipv4Addr::new(10, 20, 0, 2)]));
|
||||
|
||||
// A name under neither is nobody's business here.
|
||||
assert!(zones.lookup("music.example.com", Query::A).is_none());
|
||||
assert!(Zones::default().lookup("music.lab", Query::A).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_denial_comes_from_the_zone_that_owns_the_name() {
|
||||
// The SOA that bounds a negative answer belongs to the zone that
|
||||
// denied it; with several served that is no longer a given.
|
||||
let zones = Zones::new([
|
||||
Zone::new(ZoneName::new("lab").unwrap(), []),
|
||||
Zone::new(
|
||||
ZoneName::new("home").unwrap(),
|
||||
[("music".to_string(), Ipv4Addr::new(10, 20, 0, 2))],
|
||||
),
|
||||
]);
|
||||
let (zone, answer) = zones.lookup("nobody.lab", Query::A).unwrap();
|
||||
assert_eq!(zone.origin().as_str(), "lab");
|
||||
assert_eq!(answer, Answer::NoSuchName);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reverse_question_is_answered_by_whichever_zone_holds_the_address() {
|
||||
// It carries no suffix to match on, so every zone is asked.
|
||||
let zones = Zones::new([
|
||||
Zone::new(
|
||||
ZoneName::new("lab").unwrap(),
|
||||
[("music".to_string(), Ipv4Addr::new(10, 13, 37, 2))],
|
||||
),
|
||||
Zone::new(
|
||||
ZoneName::new("home").unwrap(),
|
||||
[("kitchen".to_string(), Ipv4Addr::new(10, 20, 0, 2))],
|
||||
),
|
||||
]);
|
||||
let (_, answer) = zones.lookup("2.0.20.10.in-addr.arpa", Query::Ptr).unwrap();
|
||||
assert_eq!(answer, Answer::Name("kitchen.home".to_string()));
|
||||
let (_, answer) = zones.lookup("2.37.13.10.in-addr.arpa", Query::Ptr).unwrap();
|
||||
assert_eq!(answer, Answer::Name("music.lab".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_networks_of_one_name_do_not_shadow_each_other_at_random() {
|
||||
// Exactly the two-`LAB` case. Only one can own the suffix; which
|
||||
// one must not depend on the order they happened to start in.
|
||||
let first = Zone::new(
|
||||
ZoneName::new("lab").unwrap(),
|
||||
[("music".to_string(), Ipv4Addr::new(10, 13, 37, 2))],
|
||||
);
|
||||
let second = Zone::new(
|
||||
ZoneName::new("lab").unwrap(),
|
||||
[("music".to_string(), Ipv4Addr::new(10, 99, 0, 2))],
|
||||
);
|
||||
let zones = Zones::new([first, second]);
|
||||
assert_eq!(zones.len(), 1, "one suffix, one zone");
|
||||
let (_, answer) = zones.lookup("music.lab", Query::A).unwrap();
|
||||
assert_eq!(
|
||||
answer,
|
||||
Answer::Addresses(vec![Ipv4Addr::new(10, 13, 37, 2)])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,18 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// The local traffic monitor could not start or poll its subscription.
|
||||
#[error("{0}")]
|
||||
TrafficMonitor(String),
|
||||
/// A requested mesh throughput test cannot run.
|
||||
#[error("{0}")]
|
||||
SpeedTest(String),
|
||||
/// 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.
|
||||
#[error("invalid network name: {0}")]
|
||||
InvalidNetworkName(&'static str),
|
||||
@@ -97,6 +109,19 @@ pub enum Error {
|
||||
#[error("network {0} is not configured")]
|
||||
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.
|
||||
#[error("no authenticated session with peer {peer} in network {network}")]
|
||||
NoSuchPeer {
|
||||
@@ -110,6 +135,23 @@ pub enum Error {
|
||||
#[error("agent is stopped")]
|
||||
Stopped,
|
||||
|
||||
/// Something that had to answer in bounded time did not.
|
||||
///
|
||||
/// Reported instead of waited out: an agent that has wedged must not
|
||||
/// leave a command hanging with nothing on screen and no way out.
|
||||
#[error("{what} did not answer in time")]
|
||||
Timeout {
|
||||
/// What was asked, phrased so the message stands on its own.
|
||||
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.
|
||||
#[error("discovery error: {0}")]
|
||||
Discovery(String),
|
||||
@@ -49,15 +49,28 @@ impl DeviceIdentity {
|
||||
self.secret.public()
|
||||
}
|
||||
|
||||
/// The raw secret key bytes, for persistence only.
|
||||
pub(crate) fn secret_bytes(&self) -> [u8; 32] {
|
||||
/// The raw secret key bytes, for persistence and transport certificate generation.
|
||||
pub fn secret_bytes(&self) -> [u8; 32] {
|
||||
self.secret.to_bytes()
|
||||
}
|
||||
|
||||
/// Signs a message with the device's persistent secret key.
|
||||
pub fn sign(&self, message: &[u8]) -> iroh::Signature {
|
||||
self.secret.sign(message)
|
||||
}
|
||||
|
||||
/// A clone of the iroh secret key, for endpoint construction only.
|
||||
pub(crate) fn secret_key(&self) -> SecretKey {
|
||||
self.secret.clone()
|
||||
}
|
||||
|
||||
/// A clone of the key used to sign this device's own state records.
|
||||
///
|
||||
/// The same persistent identity the control plane authenticates, so a
|
||||
/// record signed today is still attributable after any absence.
|
||||
pub(crate) fn signing_key(&self) -> SecretKey {
|
||||
self.secret.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DeviceIdentity {
|
||||
@@ -340,6 +340,8 @@ pub struct NetworkKeys {
|
||||
network_id: NetworkId,
|
||||
discovery_key: DiscoveryKey,
|
||||
auth_key: Zeroizing<[u8; 32]>,
|
||||
// Separate from the semi-public DiscoveryKey. Existing derivations stay frozen.
|
||||
dht_write_key: Zeroizing<[u8; 32]>,
|
||||
name: NetworkName,
|
||||
}
|
||||
|
||||
@@ -373,6 +375,7 @@ impl NetworkKeys {
|
||||
network_id: NetworkId(expand("network-id")),
|
||||
discovery_key: DiscoveryKey(expand("discovery-key")),
|
||||
auth_key: Zeroizing::new(expand("handshake-auth")),
|
||||
dht_write_key: Zeroizing::new(expand("mainline-rendezvous-write-v1")),
|
||||
name: name.clone(),
|
||||
}
|
||||
}
|
||||
@@ -405,6 +408,11 @@ impl NetworkKeys {
|
||||
pub(crate) fn auth_key(&self) -> &[u8; 32] {
|
||||
&self.auth_key
|
||||
}
|
||||
|
||||
/// Secret signing material for network rendezvous; never exported or logged.
|
||||
pub(crate) fn dht_write_key(&self) -> &[u8; 32] {
|
||||
&self.dht_write_key
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NetworkKeys {
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Exit offers may need the local user's approval. The dialog belongs to the
|
||||
//! initiating client, outside the daemon's IPC deadline and network actors.
|
||||
use super::{EXCHANGE_TIMEOUT, Error, Path, Request, Response, Result, exchange};
|
||||
use crate::state::Ipv4Range;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Result of applying the local exit settings on the host.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ExitOfferOutcome {
|
||||
/// Current setting after applying the requested change.
|
||||
Set(bool),
|
||||
/// macOS denied the host operation for this local overlay range.
|
||||
NeedsAuthorization {
|
||||
/// Locally selected overlay range.
|
||||
range: Ipv4Range,
|
||||
/// Owner of the running agent.
|
||||
agent_uid: u32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Offers the running agent as an exit in one network, or withdraws it.
|
||||
pub async fn set_exit_offer(
|
||||
path: impl AsRef<Path>,
|
||||
network_id: &str,
|
||||
enabled: bool,
|
||||
) -> Result<bool> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let authorize = |path: &Path, range, uid| {
|
||||
use std::os::unix::fs::{FileTypeExt, MetadataExt};
|
||||
let socket = std::fs::symlink_metadata(path).map_err(|e| e.to_string())?;
|
||||
if !socket.file_type().is_socket() || uid == 0 || socket.uid() != uid {
|
||||
return Err("The local control socket does not belong to the account requesting exit authorization".into());
|
||||
}
|
||||
crate::overlay::hostrules::authorize_macos_exit(range, uid)
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let authorize =
|
||||
|_: &Path, _, _| Err("macOS exit authorization is unavailable on this platform".into());
|
||||
apply(path.as_ref(), network_id, enabled, authorize).await
|
||||
}
|
||||
|
||||
async fn apply(
|
||||
path: &Path,
|
||||
id: &str,
|
||||
enabled: bool,
|
||||
authorize: impl FnOnce(&Path, Ipv4Range, u32) -> std::result::Result<(), String> + Send + 'static,
|
||||
) -> Result<bool> {
|
||||
let request = |choice| Request::SetExitOffer {
|
||||
network_id: id.to_owned(),
|
||||
enabled: choice,
|
||||
};
|
||||
let decode = |answer| match answer {
|
||||
Response::ExitOffer(outcome) => Ok(outcome),
|
||||
Response::Error(message) => Err(Error::Storage(message)),
|
||||
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
|
||||
};
|
||||
let result = decode(exchange(path, &request(Some(enabled)), EXCHANGE_TIMEOUT).await?)?;
|
||||
match result {
|
||||
ExitOfferOutcome::Set(on) => Ok(on),
|
||||
ExitOfferOutcome::NeedsAuthorization { range, agent_uid } if enabled => {
|
||||
let path_owned = path.to_owned();
|
||||
tokio::task::spawn_blocking(move || authorize(&path_owned, range, agent_uid))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
Error::Storage(format!("could not finish macOS authorization: {err}"))
|
||||
})?
|
||||
.map_err(Error::Storage)?;
|
||||
// Reconcile the current settings. A different client may have withdrawn
|
||||
// its offer while the system was waiting for the user to respond.
|
||||
match decode(exchange(path, &request(None), EXCHANGE_TIMEOUT).await?)? {
|
||||
ExitOfferOutcome::Set(on) => Ok(on),
|
||||
ExitOfferOutcome::NeedsAuthorization { .. } => Err(Error::Storage(
|
||||
"macOS still denies the exit settings after authorization".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
ExitOfferOutcome::NeedsAuthorization { .. } => Err(Error::Storage(
|
||||
"unexpected authorization request while withdrawing an exit".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use crate::ipc::{ControlSocket, ControlSocketAccess, ReportSource, StatusReport};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
struct Source {
|
||||
calls: Mutex<Vec<Option<bool>>>,
|
||||
answers: Mutex<VecDeque<ExitOfferOutcome>>,
|
||||
}
|
||||
|
||||
impl ReportSource for Source {
|
||||
fn report(&self) -> crate::BoxFuture<'_, StatusReport> {
|
||||
Box::pin(async { StatusReport::default() })
|
||||
}
|
||||
|
||||
fn set_exit_offer(
|
||||
&self,
|
||||
id: String,
|
||||
change: Option<bool>,
|
||||
) -> crate::BoxFuture<'_, std::result::Result<ExitOfferOutcome, String>> {
|
||||
assert_eq!(id, "lab");
|
||||
self.calls.lock().unwrap().push(change);
|
||||
let answer = self
|
||||
.answers
|
||||
.lock()
|
||||
.unwrap()
|
||||
.pop_front()
|
||||
.ok_or("unexpected reapply".to_owned());
|
||||
Box::pin(async move { answer })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prompt_only_on_denial_and_retry_the_current_plan_once() {
|
||||
let subnet: Ipv4Range = "10.2.3.0/24".parse().unwrap();
|
||||
let need = ExitOfferOutcome::NeedsAuthorization {
|
||||
range: subnet,
|
||||
agent_uid: 501,
|
||||
};
|
||||
let on = ExitOfferOutcome::Set(true);
|
||||
let off = ExitOfferOutcome::Set(false);
|
||||
for (answers, enabled, grant, prompts, result) in [
|
||||
(vec![on], true, true, 0, Some(true)),
|
||||
(vec![off], false, true, 0, Some(false)),
|
||||
(vec![need, on], true, true, 1, Some(true)),
|
||||
(vec![need, off], true, true, 1, Some(false)),
|
||||
(vec![need, need], true, true, 1, None),
|
||||
(vec![need], true, false, 1, None),
|
||||
(vec![need], false, true, 0, None),
|
||||
] {
|
||||
let requests = answers.len();
|
||||
let source = Arc::new(Source {
|
||||
calls: Default::default(),
|
||||
answers: Mutex::new(answers.into()),
|
||||
});
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("agent.sock");
|
||||
let server = ControlSocket::bind(&path, source.clone(), ControlSocketAccess::Private)
|
||||
.await
|
||||
.unwrap();
|
||||
let approvals = Arc::new(AtomicUsize::new(0));
|
||||
let seen = approvals.clone();
|
||||
let actual = apply(&path, "lab", enabled, move |_, range, uid| {
|
||||
seen.fetch_add(1, Ordering::Relaxed);
|
||||
assert_eq!((range, uid), (subnet, 501));
|
||||
if grant {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("cancelled".into())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert_eq!(actual.ok(), result);
|
||||
assert_eq!(approvals.load(Ordering::Relaxed), prompts);
|
||||
let expected = if requests == 1 {
|
||||
vec![Some(enabled)]
|
||||
} else {
|
||||
vec![Some(enabled), None]
|
||||
};
|
||||
assert_eq!(*source.calls.lock().unwrap(), expected);
|
||||
server.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,72 @@
|
||||
//! Local presentation of receiver-measured peer throughput.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Tests last requested on this device, scoped to one network.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedReport {
|
||||
/// Progress of the current sequential exit-node test.
|
||||
pub batch: Option<SpeedBatchReport>,
|
||||
/// Per-peer progress or the last local result, keyed by endpoint ID.
|
||||
pub peers: BTreeMap<String, SpeedPeerReport>,
|
||||
/// Compatible peers with a confirmed encrypted data path for a test.
|
||||
pub capable: Vec<String>,
|
||||
}
|
||||
|
||||
/// Progress of an exit-node batch.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedBatchReport {
|
||||
/// Number of peers that have finished, including failures.
|
||||
pub done: u32,
|
||||
/// Number selected when the batch started.
|
||||
pub total: u32,
|
||||
}
|
||||
|
||||
/// A receiver-confirmed rate in decimal bits per second.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedRate {
|
||||
/// Measured bits per second.
|
||||
pub bps: u64,
|
||||
/// The test reached its budget before establishing a throughput ceiling.
|
||||
pub lower_bound: bool,
|
||||
}
|
||||
|
||||
/// Locally observed phase of one diagnostic.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum SpeedPhase {
|
||||
/// Waiting behind another exit in the same batch.
|
||||
#[default]
|
||||
Queued,
|
||||
/// Negotiating over the authenticated control session.
|
||||
Preparing,
|
||||
/// Receiving test data.
|
||||
Download,
|
||||
/// Sending test data.
|
||||
Upload,
|
||||
/// Measurement is complete.
|
||||
Done,
|
||||
/// The test could not produce a result, with an explanation for the user.
|
||||
Failed(String),
|
||||
/// The test was stopped.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// A single live or completed diagnostic on this device.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedPeerReport {
|
||||
/// Current or terminal phase.
|
||||
pub phase: SpeedPhase,
|
||||
/// Download rate from the remote peer.
|
||||
pub down: Option<SpeedRate>,
|
||||
/// Upload rate to the remote peer.
|
||||
pub up: Option<SpeedRate>,
|
||||
/// Time since the individual test began.
|
||||
pub elapsed_ms: u32,
|
||||
/// Unique payload bytes received across both directions.
|
||||
pub bytes: u64,
|
||||
/// Wall-clock time of the most recent update, for display only.
|
||||
pub measured_at_unix_secs: u64,
|
||||
/// Data path at the start of the measurement, when known.
|
||||
pub path: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! A dedicated local connection is the lifetime of one traffic window.
|
||||
use super::{
|
||||
EXCHANGE_TIMEOUT, Error, Path, Request, Response, Result, read_message, transport,
|
||||
write_message,
|
||||
};
|
||||
use crate::traffic::{TrafficSnapshot, TrafficSubscription};
|
||||
use std::{future::Future, time::Duration};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
#[cfg(unix)]
|
||||
type Socket = tokio::net::UnixStream;
|
||||
#[cfg(windows)]
|
||||
type Socket = tokio::net::windows::named_pipe::NamedPipeClient;
|
||||
|
||||
async fn bounded<T>(duration: Duration, f: impl Future<Output = Result<T>>) -> Result<T> {
|
||||
tokio::time::timeout(duration, f)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout {
|
||||
what: "local traffic monitor".into(),
|
||||
})?
|
||||
}
|
||||
|
||||
/// A local monitor stream. Dropping it releases the agent's interval buffer.
|
||||
pub struct TrafficStream(Socket);
|
||||
impl TrafficStream {
|
||||
/// Starts observing now, independently of any other open window.
|
||||
pub async fn open(path: &Path) -> Result<Self> {
|
||||
bounded(EXCHANGE_TIMEOUT, async {
|
||||
let mut socket = transport::connect(path).await?;
|
||||
write_message(&mut socket, &Request::WatchTraffic).await?;
|
||||
match read_message(&mut socket).await? {
|
||||
Response::TrafficReady => Ok(Self(socket)),
|
||||
Response::Error(reason) => Err(Error::TrafficMonitor(reason)),
|
||||
_ => Err(Error::TrafficMonitor(
|
||||
"Unexpected answer opening traffic monitor".into(),
|
||||
)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Drains only this reader's interval.
|
||||
pub async fn snapshot(&mut self) -> Result<TrafficSnapshot> {
|
||||
bounded(EXCHANGE_TIMEOUT, async {
|
||||
write_message(&mut self.0, &0u8).await?;
|
||||
read_message(&mut self.0).await
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn serve<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
mut socket: S,
|
||||
sub: TrafficSubscription,
|
||||
) -> Result<()> {
|
||||
bounded(
|
||||
EXCHANGE_TIMEOUT,
|
||||
write_message(&mut socket, &Response::TrafficReady),
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
// A wedged or suspended client cannot keep the collector running indefinitely.
|
||||
let token: u8 = bounded(Duration::from_secs(15), read_message(&mut socket)).await?;
|
||||
if token != 0 {
|
||||
return Err(Error::TrafficMonitor("Invalid monitor poll".into()));
|
||||
}
|
||||
bounded(
|
||||
EXCHANGE_TIMEOUT,
|
||||
write_message(&mut socket, &sub.snapshot()),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 449 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user