Compare commits
19
Commits
No files matched your search
@@ -127,7 +127,7 @@ jobs:
|
||||
# (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 libxdo-dev
|
||||
libgtk-3-dev libayatana-appindicator3-dev
|
||||
cargo build --release --locked \
|
||||
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
|
||||
else
|
||||
@@ -237,7 +237,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#v}"
|
||||
pkgver="${version//-/_}"
|
||||
pkgver="${version//-/}"
|
||||
bash dist/arch/build-pkg.sh \
|
||||
"target/${{ matrix.target }}/release/tsng" \
|
||||
"${{ matrix.pkg_arch }}" \
|
||||
@@ -252,7 +252,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#v}"
|
||||
pkgver="${version//-/_}"
|
||||
pkgver="${version//-/}"
|
||||
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
|
||||
bash dist/deb/build-deb.sh \
|
||||
"target/${{ matrix.target }}/release/tsng" \
|
||||
|
||||
@@ -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")
|
||||
@@ -1,9 +1,7 @@
|
||||
name: Release
|
||||
|
||||
# GitHub version of the release pipeline. The build half mirrors the Gitea one
|
||||
# in .gitea/workflows/release.yml (static musl Linux via cargo-zigbuild, native
|
||||
# macOS and Windows); only the publish half differs: it uses the current
|
||||
# artifact actions (Node 24) and fills the release with `gh`.
|
||||
# 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
|
||||
@@ -30,7 +28,7 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
- os: ubuntu-26.04
|
||||
target: x86_64-unknown-linux-musl
|
||||
asset: tsunagi-linux-x86_64
|
||||
archive: tar.gz
|
||||
@@ -129,7 +127,7 @@ jobs:
|
||||
# (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 libxdo-dev
|
||||
libgtk-3-dev libayatana-appindicator3-dev
|
||||
cargo build --release --locked \
|
||||
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
|
||||
else
|
||||
@@ -239,7 +237,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#v}"
|
||||
pkgver="${version//-/_}"
|
||||
pkgver="${version//-/}"
|
||||
bash dist/arch/build-pkg.sh \
|
||||
"target/${{ matrix.target }}/release/tsng" \
|
||||
"${{ matrix.pkg_arch }}" \
|
||||
@@ -254,7 +252,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#v}"
|
||||
pkgver="${version//-/_}"
|
||||
pkgver="${version//-/}"
|
||||
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
|
||||
bash dist/deb/build-deb.sh \
|
||||
"target/${{ matrix.target }}/release/tsng" \
|
||||
@@ -276,9 +274,77 @@ jobs:
|
||||
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
|
||||
needs: [build, android]
|
||||
if: ${{ github.server_url == 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -303,6 +369,9 @@ jobs:
|
||||
# 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=()
|
||||
@@ -320,3 +389,194 @@ jobs:
|
||||
--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,72 @@
|
||||
name: Native subnet source selection
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
paths:
|
||||
- '.github/workflows/subnet-source.yml'
|
||||
- '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: 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 source selection on a real utun
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --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
|
||||
Generated
+57
-38
@@ -3253,25 +3253,6 @@ dependencies = [
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libxdo"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00333b8756a3d28e78def82067a377de7fa61b24909000aeaa2b446a948d14db"
|
||||
dependencies = [
|
||||
"libxdo-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libxdo-sys"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db23b9e7e2b7831bbd8aac0bbeeeb7b68cbebc162b227e7052e8e55829a09212"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"x11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
@@ -3491,7 +3472,6 @@ dependencies = [
|
||||
"dpi",
|
||||
"gtk",
|
||||
"keyboard-types",
|
||||
"libxdo",
|
||||
"objc2 0.6.4",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
@@ -6316,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -6330,17 +6310,41 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsunagi-awg",
|
||||
"tsunagi-core",
|
||||
"tsunagi-runtime",
|
||||
"tsunagi-tcp-tls",
|
||||
"tsunagi-wg-quic",
|
||||
"tsunagi-wireguard",
|
||||
"windows-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"egui_glow",
|
||||
"iroh",
|
||||
"jni 0.21.1",
|
||||
"jni 0.22.4",
|
||||
"rand 0.10.3",
|
||||
"rustls-platform-verifier",
|
||||
"simple-dns",
|
||||
"smoltcp",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tsunagi-core",
|
||||
"tsunagi-runtime",
|
||||
"tsunagi-ui",
|
||||
"tsunagi-wg-quic",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-awg"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"iroh",
|
||||
@@ -6355,7 +6359,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-core"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -6380,6 +6384,7 @@ dependencies = [
|
||||
"serde",
|
||||
"sha2",
|
||||
"simple-dns",
|
||||
"smoltcp",
|
||||
"subtle",
|
||||
"tempfile",
|
||||
"thiserror 2.0.20",
|
||||
@@ -6395,9 +6400,22 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tsunagi-awg",
|
||||
"tsunagi-core",
|
||||
"tsunagi-tcp-tls",
|
||||
"tsunagi-wg-quic",
|
||||
"tsunagi-wireguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"caps",
|
||||
@@ -6417,7 +6435,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tray"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui-phosphor",
|
||||
@@ -6427,12 +6445,23 @@ dependencies = [
|
||||
"tracing-subscriber",
|
||||
"tray-icon",
|
||||
"tsunagi-core",
|
||||
"tsunagi-ui",
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"tsunagi-core",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wg-quic"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
@@ -6459,7 +6488,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
@@ -7625,16 +7654,6 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x11"
|
||||
version = "2.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x11-dl"
|
||||
version = "2.21.0"
|
||||
|
||||
@@ -55,6 +55,7 @@ with relay fallback), and keep the network state among themselves.
|
||||
- **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).
|
||||
|
||||
## Install
|
||||
|
||||
@@ -63,6 +64,7 @@ Grab a build from the [latest release](https://github.com/house-of-vanity/tsunag
|
||||
| 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` |
|
||||
@@ -112,15 +114,18 @@ explicit Save. [Commands, health, metrics and limits](docs/vip.md).
|
||||
```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 everything through it
|
||||
tsng exit-node laptop # send internet traffic through it
|
||||
tsng exit-node off
|
||||
```
|
||||
|
||||
One exit serves the whole agent. Peers in every active Tsunagi network stay
|
||||
reachable on their own mesh routes.
|
||||
|
||||
The tray does the same with a checkbox. An exit node sees everything you send
|
||||
through it, so use only members you trust.
|
||||
[Details and per-OS notes](docs/exit-node.md).
|
||||
|
||||
The default data transport order is `wg,awg,wg-quic,tcp-tls`. AWG negotiates a
|
||||
The initial data transport order is `wg,awg,wg-quic,tcp-tls` 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).
|
||||
@@ -130,14 +135,19 @@ 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 # prefer AWG, retain QUIC as fallback
|
||||
tsng protocols home awg,wg-quic # enable AWG and QUIC, try AWG first
|
||||
tsng protocols home none # control plane only
|
||||
```
|
||||
|
||||
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, expand **data transports** on a network
|
||||
tile to toggle protocols or change their preference order. Adjacent peers need a common external transport at the same wire version.
|
||||
tile to enable transports and set their initial preference order. 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 the tray show the direct data link's measured RTT separately
|
||||
from the control connection's RTT. A mesh relay's first-hop RTT cannot measure
|
||||
the round trip to the destination.
|
||||
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.
|
||||
@@ -180,7 +190,8 @@ Online nodes and the currently selected exit node cannot be forgotten.
|
||||
² Newer and less battle-tested than on Linux.
|
||||
³ Builds from source, not covered by CI.</sup>
|
||||
|
||||
The Linux CLI is a single static binary: it runs on any distribution.
|
||||
The Linux release CLI is a single static musl binary, independent of the
|
||||
distribution's libc. The tray uses dynamic desktop libraries.
|
||||
|
||||
## NixOS
|
||||
|
||||
@@ -226,6 +237,18 @@ cargo build --release --bin tsng # the agent and CLI
|
||||
cargo build --release --bin tsunagi-tray # the tray (Linux needs GTK 3 and libayatana-appindicator)
|
||||
```
|
||||
|
||||
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):
|
||||
|
||||
```sh
|
||||
rustup target add x86_64-unknown-linux-musl
|
||||
cargo zigbuild --release --locked --target x86_64-unknown-linux-musl --bin tsng
|
||||
```
|
||||
|
||||
The static binary is `target/x86_64-unknown-linux-musl/release/tsng`.
|
||||
|
||||
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).
|
||||
|
||||
@@ -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,61 @@
|
||||
# Android client
|
||||
|
||||
Download `tsunagi-android-<version>-arm64-v8a.apk` from the project's GitHub release and open it on an ARM64 phone running Android 8 or later. If prompted, allow the app that opened the file to install it. Later releases can update the installed app and preserve the mesh identity. A prototype signed with a local debug key requires a fresh install to switch to the release signer. Uninstalling the prototype removes its local identity and saved networks. [GitHub Releases](https://github.com/house-of-vanity/tsunagi/releases)
|
||||
|
||||
## Build from source
|
||||
|
||||
Open this directory in Android Studio. The debug prototype targets ARM64 devices running Android 8 or later with OpenGL ES 3. Install SDK Platform 35 and the NDK with the SDK Manager. Point `ANDROID_HOME` at your SDK and `ANDROID_NDK_HOME` at the installed NDK directory. The Gradle launcher needs a JDK, such as the one bundled with Android Studio.
|
||||
|
||||
From the repository root, with Cargo and cargo-ndk on your PATH:
|
||||
|
||||
```sh
|
||||
rustup target add aarch64-linux-android
|
||||
cargo install cargo-ndk --version 4.1.2 --locked
|
||||
cd android
|
||||
./gradlew :app:assembleDebug
|
||||
adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
```
|
||||
|
||||
Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join with the existing network name and secret. Android keeps the established VPN service bound when the activity closes. **About → Stop VPN** disconnects it. The app-private state directory holds the device identity and its saved networks.
|
||||
|
||||
The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic.
|
||||
|
||||
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.
|
||||
|
||||
Open **Exit node…** on a network tile to compare remote gateways by measured data RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
|
||||
|
||||
## 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.2')
|
||||
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,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,25 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
|
||||
<application android:label="tsunagi" android:icon="@drawable/tsunagi"
|
||||
android:enableOnBackInvokedCallback="false" android:allowBackup="false" android:theme="@android:style/Theme.Material.NoActionBar">
|
||||
<activity android:name=".MainActivity" android:exported="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<service android:name=".MeshVpn" android:permission="android.permission.BIND_VPN_SERVICE"
|
||||
android:foregroundServiceType="systemExempted" android:exported="false">
|
||||
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
|
||||
<meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON" android:value="false" />
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,53 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.WindowInsets
|
||||
import android.widget.FrameLayout
|
||||
|
||||
class MainActivity : Activity() {
|
||||
private var askedForNotifications = false
|
||||
internal fun requestExitNotifications() {
|
||||
if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications &&
|
||||
checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
askedForNotifications = true
|
||||
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 2)
|
||||
}
|
||||
}
|
||||
private lateinit var surface: MeshSurface
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
surface = MeshSurface(this)
|
||||
val root = FrameLayout(this)
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
window.setDecorFitsSystemWindows(false)
|
||||
root.setOnApplyWindowInsetsListener { view, insets ->
|
||||
val area = insets.getInsets(WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout() or WindowInsets.Type.ime())
|
||||
view.setPadding(area.left, area.top, area.right, area.bottom)
|
||||
insets
|
||||
}
|
||||
} else root.fitsSystemWindows = true
|
||||
root.addView(surface)
|
||||
setContentView(root)
|
||||
}
|
||||
internal fun requestVpn() {
|
||||
val consent = VpnService.prepare(this)
|
||||
if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java))
|
||||
else startActivityForResult(consent, 1)
|
||||
}
|
||||
@Deprecated("Platform consent result")
|
||||
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
|
||||
super.onActivityResult(request, result, data)
|
||||
if (request == 1) {
|
||||
if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java))
|
||||
else surface.input(5, "VPN permission was declined")
|
||||
}
|
||||
}
|
||||
@Deprecated("Forward system Back to the current Rust view")
|
||||
override fun onBackPressed() { surface.dispatchBack() }
|
||||
override fun onResume() { super.onResume(); surface.onResume() }
|
||||
override fun onPause() { surface.onPause(); super.onPause() }
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.opengl.GLSurfaceView
|
||||
import android.text.InputType
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.inputmethod.BaseInputConnection
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.InputConnection
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import javax.microedition.khronos.egl.EGLConfig
|
||||
import javax.microedition.khronos.opengles.GL10
|
||||
|
||||
/** Surface, input connection and clipboard bridge for egui. */
|
||||
class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), GLSurfaceView.Renderer {
|
||||
private val density get() = resources.displayMetrics.density
|
||||
private val imm = activity.getSystemService(InputMethodManager::class.java)
|
||||
private var imeMode = 0
|
||||
private var widthPx = 0
|
||||
private var heightPx = 0
|
||||
private val repaint = Runnable { requestRender() }
|
||||
init {
|
||||
setEGLContextClientVersion(3)
|
||||
preserveEGLContextOnPause = true
|
||||
setRenderer(this)
|
||||
renderMode = RENDERMODE_WHEN_DIRTY
|
||||
isFocusableInTouchMode = true
|
||||
requestFocus()
|
||||
}
|
||||
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
|
||||
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
|
||||
override fun onDrawFrame(gl: GL10?) {
|
||||
val delay = Native.draw(this, widthPx, heightPx, density)
|
||||
removeCallbacks(repaint)
|
||||
postDelayed(repaint, delay.coerceAtLeast(16))
|
||||
}
|
||||
override fun onPause() { super.onPause(); removeCallbacks(repaint) }
|
||||
override fun onTouchEvent(e: MotionEvent): Boolean {
|
||||
val phase = when (e.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0
|
||||
MotionEvent.ACTION_MOVE -> 1
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> 2
|
||||
MotionEvent.ACTION_CANCEL -> 3
|
||||
else -> return false
|
||||
}
|
||||
for (i in 0 until e.pointerCount) {
|
||||
if ((phase == 0 || phase == 2) && i != e.actionIndex) continue
|
||||
val id = e.getPointerId(i)
|
||||
val x = e.getX(i) / density
|
||||
val y = e.getY(i) / density
|
||||
queueEvent { Native.touch(phase, id, x, y) }
|
||||
}
|
||||
requestRender()
|
||||
return true
|
||||
}
|
||||
|
||||
fun startVpn() { post { activity.requestVpn() } }
|
||||
fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } }
|
||||
fun requestExitNotifications() { post { activity.requestExitNotifications() } }
|
||||
fun closeScreen() { post { activity.finish() } }
|
||||
fun openUrl(url: String) { post {
|
||||
val uri = android.net.Uri.parse(url)
|
||||
if (uri.scheme == "https") {
|
||||
try { activity.startActivity(Intent(Intent.ACTION_VIEW, uri)) }
|
||||
catch (_: android.content.ActivityNotFoundException) { }
|
||||
}
|
||||
} }
|
||||
fun dispatchBack() { queueEvent { Native.back(this) }; requestRender() }
|
||||
fun copyText(value: String) { post {
|
||||
activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("tsunagi", value))
|
||||
} }
|
||||
fun copySecret(value: String) { post {
|
||||
val clip = ClipData.newPlainText("tsunagi", value)
|
||||
clip.description.extras = android.os.PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) }
|
||||
activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(clip)
|
||||
} }
|
||||
fun pasteSecret() { post {
|
||||
val clip = activity.getSystemService(ClipboardManager::class.java).primaryClip
|
||||
val text = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
|
||||
if (text != null && text.length <= 2048) input(4, text.toString())
|
||||
} }
|
||||
fun keyboard(mode: Int) { post {
|
||||
imeMode = mode
|
||||
if (mode == 0) {
|
||||
imm.hideSoftInputFromWindow(windowToken, 0)
|
||||
imm.restartInput(this)
|
||||
}
|
||||
else {
|
||||
requestFocus()
|
||||
imm.restartInput(this)
|
||||
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
} }
|
||||
fun input(kind: Int, value: String) {
|
||||
queueEvent { Native.input(kind, value) }
|
||||
requestRender()
|
||||
}
|
||||
private fun key(code: Int) { queueEvent { Native.key(code) }; requestRender() }
|
||||
override fun onCheckIsTextEditor(): Boolean = imeMode != 0
|
||||
override fun onCreateInputConnection(info: EditorInfo): InputConnection? {
|
||||
if (imeMode == 0) return null
|
||||
info.inputType = InputType.TYPE_CLASS_TEXT or (if (imeMode == 2) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)
|
||||
info.imeOptions = EditorInfo.IME_ACTION_DONE or EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
|
||||
return object : BaseInputConnection(this, false) {
|
||||
private var composing: String? = null
|
||||
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
if (composing == null) input(1, "")
|
||||
composing = text?.toString().orEmpty()
|
||||
input(2, composing.orEmpty())
|
||||
return true
|
||||
}
|
||||
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
input(if (composing == null) 0 else 3, text?.toString().orEmpty())
|
||||
composing = null
|
||||
return true
|
||||
}
|
||||
override fun finishComposingText(): Boolean {
|
||||
composing?.let { input(3, it) }
|
||||
composing = null
|
||||
return true
|
||||
}
|
||||
override fun deleteSurroundingText(before: Int, after: Int): Boolean {
|
||||
repeat(before.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_DEL) }
|
||||
repeat(after.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_FORWARD_DEL) }
|
||||
return true
|
||||
}
|
||||
override fun sendKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event)
|
||||
override fun performEditorAction(action: Int): Boolean { key(KeyEvent.KEYCODE_ENTER); return true }
|
||||
}
|
||||
}
|
||||
override fun onKeyDown(code: Int, event: KeyEvent): Boolean {
|
||||
when (code) {
|
||||
KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_DEL,
|
||||
KeyEvent.KEYCODE_FORWARD_DEL, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> key(code)
|
||||
else -> {
|
||||
val point = event.unicodeChar
|
||||
if (point <= 0) return super.onKeyDown(code, event)
|
||||
input(0, String(Character.toChars(point)))
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.DnsResolver
|
||||
import android.net.Network
|
||||
import android.net.LinkProperties
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.NetworkRequest
|
||||
import android.net.VpnService
|
||||
import android.os.Handler
|
||||
import android.os.Build
|
||||
import android.os.CancellationSignal
|
||||
import android.os.Looper
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.system.OsConstants
|
||||
import java.util.concurrent.CompletableFuture
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class MeshVpn : VpnService() {
|
||||
companion object {
|
||||
const val STOP_VPN = "cy.hexor.tsunagi.STOP_VPN"
|
||||
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
|
||||
private const val NOTIFICATION_ID = 1
|
||||
private const val EXIT_CHANNEL = "exit-node"
|
||||
}
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val notifications by lazy { getSystemService(NotificationManager::class.java) }
|
||||
@Volatile private var instance = 0L
|
||||
private var closed = false
|
||||
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
|
||||
@Volatile private var upstream: Network? = null
|
||||
private var watching = false
|
||||
private val changes = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) = useUnderlay(network)
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
|
||||
if (network == upstream && !closed) updateAddresses(properties)
|
||||
}
|
||||
override fun onLost(network: Network) {
|
||||
if (network != upstream || closed) return
|
||||
upstream = null
|
||||
// Keep the binding to the lost network until its replacement is ready.
|
||||
// Falling back to the default network here could send iroh into its own TUN.
|
||||
setUnderlyingNetworks(emptyArray())
|
||||
physicalAddresses = ""
|
||||
Native.networkChanged(instance, "")
|
||||
}
|
||||
}
|
||||
|
||||
private var physicalAddresses = ""
|
||||
private fun addresses(properties: LinkProperties?) = properties?.linkAddresses.orEmpty()
|
||||
.mapNotNull { it.address.hostAddress?.substringBefore('%') }.distinct().take(32).joinToString(",")
|
||||
private fun updateAddresses(properties: LinkProperties) {
|
||||
val next = addresses(properties)
|
||||
if (next == physicalAddresses) return
|
||||
physicalAddresses = next
|
||||
Native.networkChanged(instance, next)
|
||||
}
|
||||
|
||||
@Synchronized private fun useUnderlay(network: Network) {
|
||||
if (closed || !connectivity.bindProcessToNetwork(network)) return
|
||||
upstream = network
|
||||
setUnderlyingNetworks(arrayOf(network))
|
||||
physicalAddresses = addresses(connectivity.getLinkProperties(network))
|
||||
if (instance == 0L) {
|
||||
Native.trust(applicationContext)
|
||||
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses)
|
||||
} else Native.networkChanged(instance, physicalAddresses)
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY }
|
||||
DISCONNECT_EXIT -> {
|
||||
val ids = intent.data?.pathSegments.orEmpty()
|
||||
if (watching && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
|
||||
if (!Native.disconnectExit(instance, ids[0], ids[1])) {
|
||||
android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
} else if (!watching) stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
if (watching) {
|
||||
if (Native.failed(instance)) {
|
||||
Native.stop(instance)
|
||||
instance = 0
|
||||
upstream?.let(::useUnderlay)
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
notifications.createNotificationChannel(NotificationChannel("vpn", "VPN", NotificationManager.IMPORTANCE_LOW))
|
||||
notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW))
|
||||
val startup = notification("vpn").setContentTitle("Starting mesh VPN")
|
||||
if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
|
||||
startForeground(NOTIFICATION_ID, startup.build())
|
||||
watching = true
|
||||
connectivity.requestNetwork(NetworkRequest.Builder()
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper()))
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun notification(channel: String): Notification.Builder {
|
||||
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
return Notification.Builder(this, channel).setSmallIcon(R.drawable.tsunagi)
|
||||
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true).setShowWhen(false)
|
||||
.setCategory(Notification.CATEGORY_SERVICE)
|
||||
}
|
||||
|
||||
// Rust publishes a change even when the activity is closed. Android holds its
|
||||
// own service binding for an established TUN, so mesh-only mode can leave
|
||||
// foreground promotion and remove the app's notification.
|
||||
fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String) {
|
||||
main.post {
|
||||
if (closed || session != instance) return@post
|
||||
if (peer.isEmpty()) {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
return@post
|
||||
}
|
||||
val target = android.net.Uri.Builder().scheme("tsunagi").authority("exit")
|
||||
.appendPath(network).appendPath(peer).build()
|
||||
val disconnect = PendingIntent.getService(this, 1,
|
||||
Intent(this, MeshVpn::class.java).setAction(DISCONNECT_EXIT).setData(target).putExtra("instance", session),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val notice = notification(EXIT_CHANNEL).setContentTitle(title).setContentText(text)
|
||||
.addAction(Notification.Action.Builder(null, "Disconnect exit node", disconnect).build())
|
||||
if (Build.VERSION.SDK_INT >= 31) notice.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
|
||||
startForeground(NOTIFICATION_ID, notice.build())
|
||||
}
|
||||
}
|
||||
|
||||
// Called from Rust with the exhaustive local plan; detachFd transfers ownership.
|
||||
@Synchronized fun establishTun(addresses: String, routes: String, dns: String, mtu: Int, fullTunnel: Boolean): Int {
|
||||
if (closed) return -1
|
||||
val builder = Builder().setSession("tsunagi").setMtu(mtu).setBlocking(false)
|
||||
builder.setUnderlyingNetworks(upstream?.let { arrayOf(it) } ?: emptyArray())
|
||||
addresses.split(',').forEach { builder.addAddress(it.substringBefore('/'), it.substringAfter('/').toInt()) }
|
||||
routes.split(',').forEach { builder.addRoute(it.substringBefore('/'), it.substringAfter('/').toInt()) }
|
||||
if (dns.isNotEmpty()) builder.addDnsServer(dns)
|
||||
// Mesh exits currently carry IPv4. Android blocks an unconfigured family
|
||||
// unless explicitly allowed. In split mode ordinary IPv6 should pass.
|
||||
if (!fullTunnel) builder.allowFamily(OsConstants.AF_INET6)
|
||||
return builder.establish()?.detachFd() ?: -1
|
||||
}
|
||||
|
||||
// Called on a bounded Rust blocking worker, never on the UI or TUN reader.
|
||||
@android.annotation.TargetApi(29)
|
||||
fun resolveDns(query: ByteArray): ByteArray? {
|
||||
val network = upstream ?: return null
|
||||
val result = CompletableFuture<ByteArray>()
|
||||
val cancel = CancellationSignal()
|
||||
return try {
|
||||
DnsResolver.getInstance().rawQuery(network, query, DnsResolver.FLAG_EMPTY, { it.run() }, cancel,
|
||||
object : DnsResolver.Callback<ByteArray> {
|
||||
override fun onAnswer(answer: ByteArray, rcode: Int) { result.complete(answer) }
|
||||
override fun onError(error: DnsResolver.DnsException) { result.completeExceptionally(error) }
|
||||
})
|
||||
result.get(4, TimeUnit.SECONDS)
|
||||
} catch (_: Exception) { null } finally { cancel.cancel() }
|
||||
}
|
||||
|
||||
// Android 8 and 9 expose only address lookups through their system resolver.
|
||||
fun resolveAddresses(host: String): String? = try {
|
||||
upstream?.getAllByName(host)?.mapNotNull { it.hostAddress }?.joinToString(",")
|
||||
} catch (_: java.net.UnknownHostException) { null }
|
||||
|
||||
// The endpoint uses the physical network. This one explicitly selected TCP
|
||||
// socket must instead follow the same VPN as applications using the VIP.
|
||||
@Suppress("DEPRECATION")
|
||||
fun bindOverlaySocket(fd: Int, source: String): Boolean {
|
||||
val vpn = connectivity.allNetworks.firstOrNull { network ->
|
||||
connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true &&
|
||||
connectivity.getLinkProperties(network)?.linkAddresses?.any { it.address.hostAddress == source } == true
|
||||
} ?: return false
|
||||
return try {
|
||||
ParcelFileDescriptor.fromFd(fd).use { vpn.bindSocket(it.fileDescriptor) }
|
||||
true
|
||||
} catch (_: java.io.IOException) { false }
|
||||
}
|
||||
|
||||
override fun onRevoke() { shutdown(); stopSelf() }
|
||||
override fun onDestroy() { shutdown(); super.onDestroy() }
|
||||
@Synchronized private fun shutdown() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
if (watching) connectivity.unregisterNetworkCallback(changes)
|
||||
if (instance != 0L) Native.stop(instance)
|
||||
connectivity.bindProcessToNetwork(null)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.content.Context
|
||||
|
||||
/** OS entry points. Network commands and all views live in the Rust library. */
|
||||
internal object Native {
|
||||
init { System.loadLibrary("tsunagi_android") }
|
||||
external fun trust(context: Context)
|
||||
external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String): Long
|
||||
external fun failed(instance: Long): Boolean
|
||||
external fun stop(instance: Long)
|
||||
external fun disconnectExit(instance: Long, network: String, peer: String): Boolean
|
||||
external fun networkChanged(instance: Long, addresses: String)
|
||||
|
||||
external fun surface()
|
||||
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long
|
||||
external fun touch(action: Int, id: Int, x: Float, y: Float)
|
||||
external fun input(kind: Int, value: String)
|
||||
external fun key(key: Int)
|
||||
external fun back(host: MeshSurface)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp" android:height="48dp" android:viewportWidth="128" android:viewportHeight="128">
|
||||
<path android:fillColor="#2f80d8" android:pathData="M64,8a56,56 0,1 1,0 112a56,56 0,1 1,0 -112" />
|
||||
<path android:strokeColor="#ffffff" android:strokeWidth="7" android:pathData="M64,34a30,30 0,1 1,0 60a30,30 0,1 1,0 -60" />
|
||||
<path android:fillColor="#ffffff" android:pathData="M64,55a9,9 0,1 1,0 18a9,9 0,1 1,0 -18" />
|
||||
</vector>
|
||||
@@ -0,0 +1,2 @@
|
||||
android.useAndroidX=true
|
||||
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,3 @@
|
||||
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||
rootProject.name = 'tsunagi-android'
|
||||
include ':app'
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
apk=${1:?expected an APK}
|
||||
version_name=${2:?expected the release version}
|
||||
version_code=${3:?expected the Android version code}
|
||||
build_tools=${4:?expected the Android SDK Build Tools directory}
|
||||
|
||||
badging=$("$build_tools/aapt" dump badging "$apk")
|
||||
package="package: name='cy.hexor.tsunagi' versionCode='$version_code' versionName='$version_name'"
|
||||
if [[ "$badging" != "$package "* ]]; then
|
||||
echo "Expected tsunagi $version_name (version code $version_code) in the APK manifest" >&2
|
||||
exit 1
|
||||
fi
|
||||
if grep -Fxq 'application-debuggable' <<< "$badging"; then
|
||||
echo "The release APK enables Android debugging" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! grep -Fxq "native-code: 'arm64-v8a'" <<< "$badging"; then
|
||||
echo "Expected an arm64-v8a APK" >&2
|
||||
exit 1
|
||||
fi
|
||||
library=$(mktemp)
|
||||
trap 'rm -f "$library"' EXIT
|
||||
unzip -p "$apk" lib/arm64-v8a/libtsunagi_android.so > "$library"
|
||||
if [[ "$(LC_ALL=C file -b "$library")" != *"ARM aarch64"*", stripped"* ]]; then
|
||||
echo "Expected a stripped ARM64 tsunagi native library" >&2
|
||||
exit 1
|
||||
fi
|
||||
"$build_tools/zipalign" -c -P 16 4 "$apk"
|
||||
"$build_tools/apksigner" verify --verbose --print-certs "$apk"
|
||||
@@ -0,0 +1,46 @@
|
||||
[package]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.2"
|
||||
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.2" }
|
||||
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,263 @@
|
||||
//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets.
|
||||
use crate::view::{Phone, SystemAction};
|
||||
use egui::{
|
||||
Event, ImeEvent, Key, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase,
|
||||
};
|
||||
use egui_glow::{Painter, glow};
|
||||
use jni::{
|
||||
JNIEnv,
|
||||
objects::{JObject, JString, JValue},
|
||||
sys::{jfloat, jint, jlong},
|
||||
};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
ffi::{c_char, c_void},
|
||||
sync::Arc,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
#[link(name = "EGL")]
|
||||
unsafe extern "C" {
|
||||
fn eglGetProcAddress(name: *const c_char) -> *const c_void;
|
||||
}
|
||||
|
||||
struct Display {
|
||||
painter: Painter,
|
||||
ctx: egui::Context,
|
||||
ui: Phone,
|
||||
events: Vec<Event>,
|
||||
primary: Option<i32>,
|
||||
start: Instant,
|
||||
ime: i32,
|
||||
exit_active: bool,
|
||||
}
|
||||
thread_local! { static DISPLAY: RefCell<Option<Display>> = const {RefCell::new(None)}; }
|
||||
|
||||
fn with_display<T: Default>(f: impl FnOnce(&mut Display) -> T) -> T {
|
||||
DISPLAY.with_borrow_mut(|d| d.as_mut().map(f).unwrap_or_default())
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) {
|
||||
// SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current.
|
||||
let gl = unsafe {
|
||||
glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr()))
|
||||
};
|
||||
let Ok(painter) = Painter::new(Arc::new(gl), "", None, false) else {
|
||||
let _ = env.throw_new(
|
||||
"java/lang/IllegalStateException",
|
||||
"Could not initialise OpenGL ES",
|
||||
);
|
||||
return;
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
crate::view::configure(&ctx);
|
||||
DISPLAY.with_borrow_mut(|d| {
|
||||
// If Android discarded the old EGL context, its GPU resources are already gone.
|
||||
let ui = d.take().map(|old| old.ui).unwrap_or_default();
|
||||
*d = Some(Display {
|
||||
painter,
|
||||
ctx,
|
||||
ui,
|
||||
events: Vec::new(),
|
||||
primary: None,
|
||||
start: Instant::now(),
|
||||
ime: -1,
|
||||
exit_active: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
host: JObject,
|
||||
w: jint,
|
||||
h: jint,
|
||||
scale: jfloat,
|
||||
) -> jlong {
|
||||
with_display(|d| {
|
||||
let size = egui::vec2(w as f32, h as f32) / scale;
|
||||
let mut input = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
|
||||
events: std::mem::take(&mut d.events),
|
||||
time: Some(d.start.elapsed().as_secs_f64()),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(info) = input.viewports.get_mut(&egui::ViewportId::ROOT) {
|
||||
info.native_pixels_per_point = Some(scale);
|
||||
}
|
||||
let mut action = None;
|
||||
let state = super::status();
|
||||
let exit_active = matches!(&state, crate::service::State::Ready(report, _) if report.networks.iter().any(|n| n.active && n.exit.via.is_some()));
|
||||
if exit_active && !d.exit_active {
|
||||
let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]);
|
||||
}
|
||||
d.exit_active = exit_active;
|
||||
let output = d.ctx.run(input, |ctx| {
|
||||
action = d.ui.draw(ctx, &state, super::send);
|
||||
});
|
||||
if let Some(action) = action {
|
||||
let method = match action {
|
||||
SystemAction::Start => "startVpn",
|
||||
SystemAction::Stop => "stopVpn",
|
||||
SystemAction::PasteSecret => "pasteSecret",
|
||||
SystemAction::Finish => "closeScreen",
|
||||
};
|
||||
let _ = env.call_method(&host, method, "()V", &[]);
|
||||
}
|
||||
if let Some(secret) = d.ui.take_copied_secret()
|
||||
&& let Ok(text) = env.new_string(secret.as_str())
|
||||
{
|
||||
let _ = env.call_method(
|
||||
&host,
|
||||
"copySecret",
|
||||
"(Ljava/lang/String;)V",
|
||||
&[JValue::Object(&text)],
|
||||
);
|
||||
}
|
||||
for command in output.platform_output.commands {
|
||||
let (method, value) = match command {
|
||||
egui::OutputCommand::CopyText(text) => ("copyText", text),
|
||||
egui::OutputCommand::OpenUrl(url) => ("openUrl", url.url),
|
||||
_ => continue,
|
||||
};
|
||||
if let Ok(text) = env.new_string(value) {
|
||||
let _ = env.call_method(
|
||||
&host,
|
||||
method,
|
||||
"(Ljava/lang/String;)V",
|
||||
&[JValue::Object(&text)],
|
||||
);
|
||||
}
|
||||
}
|
||||
let ime = if output.platform_output.ime.is_none() {
|
||||
0
|
||||
} else if d.ui.secret_focused(&d.ctx) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
if ime != d.ime {
|
||||
d.ime = ime;
|
||||
let _ = env.call_method(&host, "keyboard", "(I)V", &[JValue::Int(ime)]);
|
||||
}
|
||||
let ppp = output.pixels_per_point;
|
||||
let primitives = d.ctx.tessellate(output.shapes, ppp);
|
||||
let pixels = [w as u32, h as u32];
|
||||
d.painter.clear(pixels, [0.1, 0.1, 0.1, 1.0]);
|
||||
d.painter
|
||||
.paint_and_update_textures(pixels, ppp, &primitives, &output.textures_delta);
|
||||
output
|
||||
.viewport_output
|
||||
.get(&egui::ViewportId::ROOT)
|
||||
.map_or(1000, |v| {
|
||||
v.repaint_delay.as_millis().clamp(16, 1000) as jlong
|
||||
})
|
||||
})
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_touch(
|
||||
_: JNIEnv,
|
||||
_: JObject,
|
||||
action: jint,
|
||||
id: jint,
|
||||
x: jfloat,
|
||||
y: jfloat,
|
||||
) {
|
||||
with_display(|d| {
|
||||
let pos = egui::pos2(x, y);
|
||||
let phase = match action {
|
||||
0 => TouchPhase::Start,
|
||||
1 => TouchPhase::Move,
|
||||
2 => TouchPhase::End,
|
||||
_ => TouchPhase::Cancel,
|
||||
};
|
||||
d.events.push(Event::Touch {
|
||||
device_id: TouchDeviceId(0),
|
||||
id: TouchId(id as u64),
|
||||
phase,
|
||||
pos,
|
||||
force: None,
|
||||
});
|
||||
if phase == TouchPhase::Start && d.primary.is_none() {
|
||||
d.primary = Some(id);
|
||||
}
|
||||
if d.primary != Some(id) {
|
||||
return;
|
||||
}
|
||||
if phase != TouchPhase::Cancel {
|
||||
d.events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
if phase != TouchPhase::Move {
|
||||
if phase == TouchPhase::Cancel {
|
||||
d.events.push(Event::PointerGone);
|
||||
}
|
||||
d.events.push(Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed: phase == TouchPhase::Start,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
}
|
||||
if matches!(phase, TouchPhase::Cancel | TouchPhase::End) {
|
||||
d.events.push(Event::PointerGone);
|
||||
d.primary = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_input(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
kind: jint,
|
||||
value: JString,
|
||||
) {
|
||||
let Ok(text) = env.get_string(&value) else {
|
||||
return;
|
||||
};
|
||||
let text = String::from(text);
|
||||
with_display(|d| match kind {
|
||||
0 => d.events.push(Event::Text(text)),
|
||||
1 => d.events.push(Event::Ime(ImeEvent::Enabled)),
|
||||
2 => d.events.push(Event::Ime(ImeEvent::Preedit(text))),
|
||||
3 => {
|
||||
d.events.push(Event::Ime(ImeEvent::Commit(text)));
|
||||
d.events.push(Event::Ime(ImeEvent::Disabled));
|
||||
}
|
||||
4 => d.ui.paste_secret(text),
|
||||
5 => d.ui.error(text),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_key(_: JNIEnv, _: JObject, key: jint) {
|
||||
let key = match key {
|
||||
67 => Key::Backspace,
|
||||
112 => Key::Delete,
|
||||
66 => Key::Enter,
|
||||
21 => Key::ArrowLeft,
|
||||
22 => Key::ArrowRight,
|
||||
61 => Key::Tab,
|
||||
_ => return,
|
||||
};
|
||||
with_display(|d| {
|
||||
for pressed in [true, false] {
|
||||
d.events.push(Event::Key {
|
||||
key,
|
||||
physical_key: None,
|
||||
pressed,
|
||||
repeat: false,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_back(mut env: JNIEnv, _: JObject, host: JObject) {
|
||||
with_display(|d| {
|
||||
if d.ui.back() == Some(SystemAction::Finish) {
|
||||
let _ = env.call_method(&host, "closeScreen", "()V", &[]);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Android's physical-network resolver, including its Private DNS policy.
|
||||
use crate::dns::Resolver;
|
||||
use jni::{
|
||||
JNIEnv, JavaVM,
|
||||
objects::{GlobalRef, JByteArray, JString, JValue},
|
||||
};
|
||||
use simple_dns::{CLASS, Packet, PacketFlag, QTYPE, RCODE, ResourceRecord, TYPE, rdata::RData};
|
||||
use std::{net::IpAddr, sync::Arc};
|
||||
|
||||
pub(super) fn resolver(vm: Arc<JavaVM>, service: GlobalRef, sdk: i32) -> Resolver {
|
||||
Resolver::new(move |query| {
|
||||
let mut env = vm.attach_current_thread().ok()?;
|
||||
let response = env.with_local_frame(6, |env| {
|
||||
if sdk < 29 {
|
||||
return legacy(env, &service, query);
|
||||
}
|
||||
let bytes = env.byte_array_from_slice(query)?;
|
||||
let reply = env
|
||||
.call_method(&service, "resolveDns", "([B)[B", &[JValue::Object(&bytes)])?
|
||||
.l()?;
|
||||
if reply.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
let reply = JByteArray::from(reply);
|
||||
if env.get_array_length(&reply)? > i32::from(u16::MAX) {
|
||||
return Ok(None);
|
||||
}
|
||||
env.convert_byte_array(reply).map(Some)
|
||||
});
|
||||
if env.exception_check().unwrap_or(false) {
|
||||
let _ = env.exception_clear();
|
||||
return None;
|
||||
}
|
||||
response.ok().flatten()
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy(
|
||||
env: &mut JNIEnv<'_>,
|
||||
service: &GlobalRef,
|
||||
query: &[u8],
|
||||
) -> jni::errors::Result<Option<Vec<u8>>> {
|
||||
let Some(packet) = Packet::parse(query).ok() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let [question] = packet.questions.as_slice() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut reply = Packet::new_reply(packet.id());
|
||||
reply.questions.push(question.clone());
|
||||
reply.set_flags(PacketFlag::RECURSION_AVAILABLE);
|
||||
if packet.has_flags(PacketFlag::RECURSION_DESIRED) {
|
||||
reply.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||
}
|
||||
if matches!(question.qtype, QTYPE::TYPE(TYPE::A | TYPE::AAAA)) {
|
||||
let name = env.new_string(format!("{}.", question.qname))?;
|
||||
let addresses = env
|
||||
.call_method(
|
||||
service,
|
||||
"resolveAddresses",
|
||||
"(Ljava/lang/String;)Ljava/lang/String;",
|
||||
&[JValue::Object(&name)],
|
||||
)?
|
||||
.l()?;
|
||||
if addresses.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
let addresses: String = env.get_string(&JString::from(addresses))?.into();
|
||||
for address in addresses
|
||||
.split(',')
|
||||
.take(128)
|
||||
.filter_map(|s| s.parse::<IpAddr>().ok())
|
||||
{
|
||||
let data = match (question.qtype, address) {
|
||||
(QTYPE::TYPE(TYPE::A), IpAddr::V4(v4)) => RData::A(v4.into()),
|
||||
(QTYPE::TYPE(TYPE::AAAA), IpAddr::V6(v6)) => RData::AAAA(v6.into()),
|
||||
_ => continue,
|
||||
};
|
||||
reply.answers.push(ResourceRecord::new(
|
||||
question.qname.clone(),
|
||||
CLASS::IN,
|
||||
0,
|
||||
data,
|
||||
));
|
||||
}
|
||||
} else {
|
||||
*reply.rcode_mut() = RCODE::NotImplemented;
|
||||
}
|
||||
Ok(reply.build_bytes_vec_compressed().ok())
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
//! Android process entry points. JNI owns references here, never in the core.
|
||||
#![allow(unsafe_code)]
|
||||
mod display;
|
||||
mod dns;
|
||||
use crate::{
|
||||
plan::VpnPlan,
|
||||
service::{Reply, Request, Response, State},
|
||||
tun::AndroidTun,
|
||||
};
|
||||
use jni::{
|
||||
JNIEnv, JavaVM,
|
||||
objects::{GlobalRef, JObject, JString, JValue},
|
||||
sys::jlong,
|
||||
};
|
||||
use std::{
|
||||
fs::File,
|
||||
io,
|
||||
os::fd::{AsRawFd, FromRawFd, OwnedFd},
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
};
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tsunagi::{Agent, AgentConfig, StoragePaths, TransportPolicy, discovery::MainlineDiscovery};
|
||||
use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin};
|
||||
|
||||
struct Session {
|
||||
id: i64,
|
||||
commands: mpsc::Sender<(Request, Reply)>,
|
||||
state: watch::Receiver<State>,
|
||||
underlay: watch::Sender<Vec<std::net::IpAddr>>,
|
||||
stop: watch::Sender<bool>,
|
||||
}
|
||||
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||
// Stop/start can cross on the Android main thread. The previous agent closes
|
||||
// its fd, endpoint and directory lock before its successor opens that identity.
|
||||
static LIFETIME: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn current() -> std::sync::MutexGuard<'static, Option<Session>> {
|
||||
SESSION.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
fn status() -> State {
|
||||
current()
|
||||
.as_ref()
|
||||
.map(|s| s.state.borrow().clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||
let (reply, result) = oneshot::channel();
|
||||
current()
|
||||
.as_ref()
|
||||
.ok_or("VPN service stopped")?
|
||||
.commands
|
||||
.try_send((Request::Action(cmd), reply))
|
||||
.map_err(|_| "VPN service is busy or stopped".to_owned())?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_trust(
|
||||
mut env: jni_verifier::EnvUnowned,
|
||||
_: jni_verifier::objects::JObject,
|
||||
app: jni_verifier::objects::JObject,
|
||||
) {
|
||||
env.with_env(|env| rustls_platform_verifier::android::init_with_env(env, app))
|
||||
.resolve::<jni_verifier::errors::ThrowRuntimeExAndDefault>();
|
||||
}
|
||||
|
||||
fn establish(vm: &JavaVM, service: &GlobalRef, plan: &VpnPlan) -> io::Result<File> {
|
||||
let mut env = vm.attach_current_thread().map_err(io::Error::other)?;
|
||||
let addresses = plan
|
||||
.addresses_in_order()
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let routes = plan.routes().join(",");
|
||||
let result = env.with_local_frame(6, |env| -> jni::errors::Result<i32> {
|
||||
let addresses = env.new_string(addresses)?;
|
||||
let routes = env.new_string(routes)?;
|
||||
let dns = env.new_string(
|
||||
plan.dns_address()
|
||||
.map(|a| a.to_string())
|
||||
.unwrap_or_default(),
|
||||
)?;
|
||||
env.call_method(
|
||||
service,
|
||||
"establishTun",
|
||||
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)I",
|
||||
&[
|
||||
JValue::Object(&addresses),
|
||||
JValue::Object(&routes),
|
||||
JValue::Object(&dns),
|
||||
JValue::Int(plan.mtu as i32),
|
||||
JValue::Bool(plan.full_tunnel.into()),
|
||||
],
|
||||
)?
|
||||
.i()
|
||||
});
|
||||
if env.exception_check().unwrap_or(false) {
|
||||
let _ = env.exception_clear();
|
||||
return Err(io::Error::other(
|
||||
"Android could not establish the VPN. Check the VPN permission.",
|
||||
));
|
||||
}
|
||||
let fd = result.map_err(io::Error::other)?;
|
||||
if fd < 0 {
|
||||
return Err(io::Error::other("Android revoked the VPN permission"));
|
||||
}
|
||||
// SAFETY: establishTun transferred exclusive ownership with detachFd().
|
||||
Ok(File::from(unsafe { OwnedFd::from_raw_fd(fd) }))
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
service: JObject,
|
||||
app: JObject,
|
||||
state_dir: JString,
|
||||
cache_dir: JString,
|
||||
addresses: JString,
|
||||
) -> jlong {
|
||||
let result = (|| -> Result<i64, Box<dyn std::error::Error>> {
|
||||
// Keep the application (never an activity) alive for DNS throughout the process.
|
||||
static APPLICATION: OnceLock<GlobalRef> = OnceLock::new();
|
||||
let vm = Arc::new(env.get_java_vm()?);
|
||||
let application = env.new_global_ref(app)?;
|
||||
if APPLICATION.set(application.clone()).is_ok() {
|
||||
// SAFETY: the VM and this stored global reference live until process exit.
|
||||
unsafe {
|
||||
iroh::dns::install_android_jni_context(
|
||||
vm.get_java_vm_pointer().cast(),
|
||||
application.as_obj().as_raw().cast(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let service = env.new_global_ref(service)?;
|
||||
let state_dir: String = env.get_string(&state_dir)?.into();
|
||||
let cache_dir: String = env.get_string(&cache_dir)?.into();
|
||||
let paths = StoragePaths::new(PathBuf::from(state_dir), PathBuf::from(cache_dir));
|
||||
let tun_vm = vm.clone();
|
||||
let tun_service = service.clone();
|
||||
let notice_vm = vm.clone();
|
||||
let notice_service = service.clone();
|
||||
let sdk = env
|
||||
.get_static_field("android/os/Build$VERSION", "SDK_INT", "I")?
|
||||
.i()?;
|
||||
let dns = dns::resolver(vm.clone(), service.clone(), sdk);
|
||||
let factory = AndroidTun::new(
|
||||
dns.clone(),
|
||||
move |plan| establish(&tun_vm, &tun_service, plan),
|
||||
move |socket, source| {
|
||||
let mut env = vm.attach_current_thread().map_err(io::Error::other)?;
|
||||
let result = env.with_local_frame(3, |env| -> jni::errors::Result<bool> {
|
||||
let source = env.new_string(source.to_string())?;
|
||||
env.call_method(
|
||||
&service,
|
||||
"bindOverlaySocket",
|
||||
"(ILjava/lang/String;)Z",
|
||||
&[JValue::Int(socket.as_raw_fd()), JValue::Object(&source)],
|
||||
)?
|
||||
.z()
|
||||
});
|
||||
if env.exception_check().unwrap_or(false) {
|
||||
let _ = env.exception_clear();
|
||||
return Err(io::Error::other("VPN socket binding failed"));
|
||||
}
|
||||
if result.map_err(io::Error::other)? {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other("VPN network is unavailable"))
|
||||
}
|
||||
},
|
||||
);
|
||||
let addresses: String = env.get_string(&addresses)?.into();
|
||||
let (underlay, physical) = watch::channel(underlay_ips(&addresses));
|
||||
let (commands, rx) = mpsc::channel(16);
|
||||
let (state, state_rx) = watch::channel(State::Starting);
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
static NEXT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
|
||||
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut slot = current();
|
||||
if let Some(old) = slot.as_ref() {
|
||||
old.stop.send_replace(true);
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name("tsunagi-agent".into())
|
||||
.spawn(move || {
|
||||
let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if *stopped.borrow() {
|
||||
return;
|
||||
}
|
||||
let run = || -> Result<(), Box<dyn std::error::Error>> {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()?;
|
||||
runtime.block_on(async {
|
||||
let wg = WireguardPlugin::open(WireguardConfig::new(
|
||||
paths.state_dir.join("wg-quic"),
|
||||
))
|
||||
.await?;
|
||||
let config = AgentConfig::new(paths)
|
||||
.with_transport(TransportPolicy::N0Defaults)
|
||||
.with_dht(MainlineDiscovery::default())
|
||||
.with_interface(Arc::new(factory), "tsunagi-vpn", DEFAULT_MTU)
|
||||
.with_tunnel(wg.clone());
|
||||
let (config, carriers) = tsunagi_runtime::Carriers::configure(
|
||||
config,
|
||||
&[],
|
||||
Some(physical),
|
||||
|_| Vec::new(),
|
||||
)
|
||||
.await?;
|
||||
let agent = Agent::spawn(config).await?;
|
||||
let _listeners = carriers.listen(&agent);
|
||||
crate::service::serve(agent, wg, dns, rx, &state, stopped, |notice| {
|
||||
update_exit_notification(¬ice_vm, ¬ice_service, id, notice);
|
||||
})
|
||||
.await;
|
||||
Ok(())
|
||||
})
|
||||
};
|
||||
if let Err(e) = run() {
|
||||
state.send_replace(State::Error(e.to_string()));
|
||||
}
|
||||
})?;
|
||||
*slot = Some(Session {
|
||||
id,
|
||||
commands,
|
||||
state: state_rx,
|
||||
underlay,
|
||||
stop,
|
||||
});
|
||||
Ok(id)
|
||||
})();
|
||||
match result {
|
||||
Ok(id) => id,
|
||||
Err(e) => {
|
||||
let _ = env.throw_new("java/lang/IllegalStateException", e.to_string());
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_exit_notification(
|
||||
vm: &JavaVM,
|
||||
service: &GlobalRef,
|
||||
id: i64,
|
||||
notice: Option<&crate::service::ExitNotice>,
|
||||
) {
|
||||
let Ok(mut env) = vm.attach_current_thread() else {
|
||||
return;
|
||||
};
|
||||
let _ = env.with_local_frame(6, |env| -> jni::errors::Result<()> {
|
||||
let network = env.new_string(notice.map_or("", |n| &n.network))?;
|
||||
let peer = env.new_string(notice.map_or("", |n| &n.peer))?;
|
||||
let title = env.new_string(
|
||||
notice
|
||||
.map(|n| format!("Exit node · {}", n.name))
|
||||
.unwrap_or_default(),
|
||||
)?;
|
||||
let text = env.new_string(
|
||||
notice
|
||||
.map(|n| {
|
||||
if n.online {
|
||||
format!("IPv4 internet via {}", n.network_name)
|
||||
} else {
|
||||
format!(
|
||||
"{} · Exit offline. IPv4 internet is blocked.",
|
||||
n.network_name
|
||||
)
|
||||
}
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
)?;
|
||||
env.call_method(
|
||||
service,
|
||||
"updateExitNotification",
|
||||
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
&[
|
||||
JValue::Long(id),
|
||||
JValue::Object(&network),
|
||||
JValue::Object(&peer),
|
||||
JValue::Object(&title),
|
||||
JValue::Object(&text),
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
});
|
||||
if env.exception_check().unwrap_or(false) {
|
||||
let _ = env.exception_clear();
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_disconnectExit(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
id: jlong,
|
||||
network: JString,
|
||||
peer: JString,
|
||||
) -> jni::sys::jboolean {
|
||||
let (Ok(network), Ok(peer)) = (env.get_string(&network), env.get_string(&peer)) else {
|
||||
return false.into();
|
||||
};
|
||||
current()
|
||||
.as_ref()
|
||||
.filter(|s| s.id == id)
|
||||
.is_some_and(|s| {
|
||||
s.commands
|
||||
.try_send((
|
||||
Request::DisconnectExit {
|
||||
network: network.into(),
|
||||
peer: peer.into(),
|
||||
},
|
||||
oneshot::channel().0,
|
||||
))
|
||||
.is_ok()
|
||||
})
|
||||
.into()
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_failed(
|
||||
_: JNIEnv,
|
||||
_: JObject,
|
||||
id: jlong,
|
||||
) -> jni::sys::jboolean {
|
||||
current()
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.id == id && matches!(*s.state.borrow(), State::Error(_)))
|
||||
.into()
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_stop(_: JNIEnv, _: JObject, id: jlong) {
|
||||
let mut slot = current();
|
||||
if slot.as_ref().is_some_and(|s| s.id == id)
|
||||
&& let Some(session) = slot.take()
|
||||
{
|
||||
session.stop.send_replace(true);
|
||||
}
|
||||
}
|
||||
fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
|
||||
addresses
|
||||
.split(',')
|
||||
.take(32)
|
||||
.filter_map(|s| s.parse().ok())
|
||||
.collect()
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_networkChanged(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
id: jlong,
|
||||
addresses: JString,
|
||||
) {
|
||||
let Ok(raw) = env.get_string(&addresses) else {
|
||||
return;
|
||||
};
|
||||
if let Some(s) = current().as_ref().filter(|s| s.id == id) {
|
||||
s.underlay.send_replace(underlay_ips(&String::from(raw)));
|
||||
let _ = s
|
||||
.commands
|
||||
.try_send((Request::NetworkChanged, oneshot::channel().0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Device-local split DNS. Only questions outside the signed mesh zones reach Android's resolver.
|
||||
use simple_dns::{Packet, PacketFlag, RCODE};
|
||||
use std::{net::Ipv4Addr, sync::Arc, time::Duration};
|
||||
use tokio::sync::{Semaphore, watch};
|
||||
use tsunagi::dns::{
|
||||
Zones,
|
||||
server::{MAX_MESSAGE_LEN, Resolution, parse_message, resolve},
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) mod stack;
|
||||
|
||||
type Upstream = dyn Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync;
|
||||
|
||||
/// One view of all joined zones, shared across TUN replacements.
|
||||
#[derive(Clone)]
|
||||
pub struct Resolver {
|
||||
zones: watch::Sender<Option<Arc<Zones>>>,
|
||||
listening: watch::Sender<Option<Ipv4Addr>>,
|
||||
upstream: Arc<Upstream>,
|
||||
pending: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl Resolver {
|
||||
/// The platform callback resolves a wire question on the selected physical network.
|
||||
pub fn new(upstream: impl Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync + 'static) -> Self {
|
||||
Self {
|
||||
zones: watch::channel(None).0,
|
||||
listening: watch::channel(None).0,
|
||||
upstream: Arc::new(upstream),
|
||||
pending: Arc::new(Semaphore::new(16)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Withhold forwarding while configured zones are loading or changing.
|
||||
pub fn replace(&self, zones: Option<Zones>) {
|
||||
self.zones.send_replace(zones.map(Arc::new));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn publish(&self, address: Option<Ipv4Addr>) {
|
||||
self.listening.send_replace(address);
|
||||
}
|
||||
|
||||
pub(crate) fn refresh(&self, networks: &[tsunagi::NetworkStatus]) -> tsunagi::ipc::DnsReport {
|
||||
let view = tsunagi::dns::RosterZones::from_networks(networks);
|
||||
let names = view.zones.names() as u32;
|
||||
self.replace(Some(view.zones));
|
||||
let address = *self.listening.borrow();
|
||||
tsunagi::ipc::DnsReport {
|
||||
listening: address.map(|ip| format!("{ip}:53")).into_iter().collect(),
|
||||
publish_error: (address.is_none() && !view.labels.is_empty())
|
||||
.then(|| "Waiting for a VPN interface with a DNS address.".into()),
|
||||
zones: view.labels,
|
||||
zone_warnings: view.warnings,
|
||||
names,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer a local DNS request. Slow public lookups never block a mesh answer.
|
||||
pub async fn answer(&self, query: &[u8]) -> Option<Vec<u8>> {
|
||||
if query.len() > MAX_MESSAGE_LEN {
|
||||
return None;
|
||||
}
|
||||
let zones = self.zones.borrow().clone();
|
||||
let Some(zones) = zones else {
|
||||
let question = parse_message(query)?;
|
||||
if question.has_flags(PacketFlag::RESPONSE) {
|
||||
return None;
|
||||
}
|
||||
return error_reply(&question, RCODE::ServerFailure);
|
||||
};
|
||||
match resolve(&zones, query)? {
|
||||
Resolution::Local(reply) => Some(reply),
|
||||
Resolution::Outside(_) => {
|
||||
let question = parse_message(query)?;
|
||||
if let Ok(permit) = self.pending.clone().try_acquire_owned() {
|
||||
let upstream = self.upstream.clone();
|
||||
let wire = query.to_vec();
|
||||
let job = tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
upstream(&wire)
|
||||
});
|
||||
if let Ok(Ok(Some(mut wire))) =
|
||||
tokio::time::timeout(Duration::from_secs(5), job).await
|
||||
&& wire.len() <= usize::from(u16::MAX)
|
||||
&& parse_message(&wire).is_some_and(|p| {
|
||||
let [received] = p.questions.as_slice() else {
|
||||
return false;
|
||||
};
|
||||
let sent = &question.questions[0]; // Resolution::Outside has exactly one IN question.
|
||||
p.has_flags(PacketFlag::RESPONSE)
|
||||
&& received.qtype == sent.qtype
|
||||
&& received.qclass == sent.qclass
|
||||
&& received
|
||||
.qname
|
||||
.to_string()
|
||||
.eq_ignore_ascii_case(&sent.qname.to_string())
|
||||
})
|
||||
{
|
||||
// Android's upstream transaction may have used its own ID.
|
||||
wire[..2].copy_from_slice(&question.id().to_be_bytes());
|
||||
return Some(wire);
|
||||
}
|
||||
}
|
||||
error_reply(&question, RCODE::ServerFailure)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn error_reply(query: &Packet<'_>, code: RCODE) -> Option<Vec<u8>> {
|
||||
let mut answer = Packet::new_reply(query.id());
|
||||
answer.questions.clone_from(&query.questions);
|
||||
if query.has_flags(PacketFlag::RECURSION_DESIRED) {
|
||||
answer.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||
}
|
||||
answer.set_flags(PacketFlag::RECURSION_AVAILABLE);
|
||||
*answer.rcode_mut() = code;
|
||||
answer.build_bytes_vec_compressed().ok()
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! A DNS-only endpoint on the application side of one Android TUN descriptor.
|
||||
//! The kernel reserves port 53. smoltcp terminates UDP and TCP without root.
|
||||
use super::Resolver;
|
||||
use smoltcp::{
|
||||
iface::{Config, Interface, SocketHandle, SocketSet},
|
||||
phy::{self, Device, DeviceCapabilities, Medium},
|
||||
socket::{tcp, udp},
|
||||
time::Instant as NetTime,
|
||||
wire::{HardwareAddress, IpAddress, IpCidr, IpEndpoint},
|
||||
};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
fs::File,
|
||||
io::Write,
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::{
|
||||
io::{Interest, unix::AsyncFd},
|
||||
sync::mpsc,
|
||||
task::{JoinHandle, JoinSet},
|
||||
};
|
||||
use tsunagi::dns::server::{MAX_MESSAGE_LEN, truncate_for_udp};
|
||||
|
||||
const PORT: u16 = 53;
|
||||
const QUEUE: usize = 32;
|
||||
const TCP_CLIENTS: usize = 8;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub(crate) struct DnsPort {
|
||||
address: Ipv4Addr,
|
||||
input: mpsc::Sender<Vec<u8>>,
|
||||
worker: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl DnsPort {
|
||||
pub(crate) fn start(
|
||||
address: Ipv4Addr,
|
||||
mtu: usize,
|
||||
resolver: Resolver,
|
||||
fd: Arc<AsyncFd<File>>,
|
||||
) -> Self {
|
||||
let (input, packets) = mpsc::channel(QUEUE);
|
||||
let worker = tokio::spawn(run(address, mtu, resolver, packets, fd));
|
||||
Self {
|
||||
address,
|
||||
input,
|
||||
worker,
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume only packets sent to our private endpoint by a local VPN address.
|
||||
pub(crate) fn intercept(&self, bytes: &[u8], local: &[IpAddr]) -> bool {
|
||||
let Ok(packet) = smoltcp::wire::Ipv4Packet::new_checked(bytes) else {
|
||||
return false;
|
||||
};
|
||||
if packet.version() != 4 || packet.dst_addr() != self.address {
|
||||
return false;
|
||||
}
|
||||
if local.contains(&IpAddr::V4(packet.src_addr())) {
|
||||
let _ = self.input.try_send(bytes.to_vec());
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DnsPort {
|
||||
fn drop(&mut self) {
|
||||
self.worker.abort();
|
||||
}
|
||||
}
|
||||
|
||||
struct Wire {
|
||||
mtu: usize,
|
||||
input: Option<Vec<u8>>,
|
||||
output: VecDeque<Vec<u8>>,
|
||||
}
|
||||
struct Rx(Vec<u8>);
|
||||
impl phy::RxToken for Rx {
|
||||
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
|
||||
f(&self.0)
|
||||
}
|
||||
}
|
||||
struct Tx<'a>(&'a mut VecDeque<Vec<u8>>);
|
||||
impl phy::TxToken for Tx<'_> {
|
||||
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
|
||||
let mut packet = vec![0; len];
|
||||
let result = f(&mut packet);
|
||||
self.0.push_back(packet);
|
||||
result
|
||||
}
|
||||
}
|
||||
impl Device for Wire {
|
||||
type RxToken<'a> = Rx;
|
||||
type TxToken<'a> = Tx<'a>;
|
||||
fn receive(&mut self, _: NetTime) -> Option<(Rx, Tx<'_>)> {
|
||||
self.input
|
||||
.take()
|
||||
.map(|packet| (Rx(packet), Tx(&mut self.output)))
|
||||
}
|
||||
fn transmit(&mut self, _: NetTime) -> Option<Tx<'_>> {
|
||||
(self.output.len() < QUEUE).then_some(Tx(&mut self.output))
|
||||
}
|
||||
fn capabilities(&self) -> DeviceCapabilities {
|
||||
let mut caps = DeviceCapabilities::default();
|
||||
caps.medium = Medium::Ip;
|
||||
caps.max_transmission_unit = self.mtu;
|
||||
caps
|
||||
}
|
||||
}
|
||||
|
||||
struct TcpSlot {
|
||||
handle: SocketHandle,
|
||||
pending: Option<u64>,
|
||||
}
|
||||
enum Client {
|
||||
Udp(IpEndpoint),
|
||||
Tcp { slot: usize, request: u64 },
|
||||
}
|
||||
type Jobs = JoinSet<(Client, Option<Vec<u8>>)>;
|
||||
|
||||
struct Stack {
|
||||
iface: Interface,
|
||||
wire: Wire,
|
||||
sockets: SocketSet<'static>,
|
||||
udp: SocketHandle,
|
||||
tcp: Vec<TcpSlot>,
|
||||
next_request: u64,
|
||||
}
|
||||
|
||||
impl Stack {
|
||||
fn new(address: Ipv4Addr, mtu: usize) -> Self {
|
||||
let mut wire = Wire {
|
||||
mtu,
|
||||
input: None,
|
||||
output: VecDeque::new(),
|
||||
};
|
||||
let mut config = Config::new(HardwareAddress::Ip);
|
||||
config.random_seed = rand::random();
|
||||
let mut iface = Interface::new(config, &mut wire, NetTime::from_millis(0));
|
||||
// This is a point-to-point IP device. Its only neighbour is Android, whatever
|
||||
// the OS chose as the source address among the attached networks.
|
||||
iface.update_ip_addrs(|addrs| {
|
||||
let _ = addrs.push(IpCidr::new(IpAddress::Ipv4(address), 0));
|
||||
});
|
||||
let mut sockets = SocketSet::new(Vec::new());
|
||||
let datagrams = || {
|
||||
udp::PacketBuffer::new(
|
||||
vec![udp::PacketMetadata::EMPTY; QUEUE],
|
||||
vec![0; QUEUE * mtu],
|
||||
)
|
||||
};
|
||||
let mut socket = udp::Socket::new(datagrams(), datagrams());
|
||||
let _ = socket.bind(PORT);
|
||||
let udp = sockets.add(socket);
|
||||
let tcp = (0..TCP_CLIENTS)
|
||||
.map(|_| {
|
||||
let mut socket = tcp::Socket::new(
|
||||
tcp::SocketBuffer::new(vec![0; MAX_MESSAGE_LEN + 2]),
|
||||
tcp::SocketBuffer::new(vec![0; usize::from(u16::MAX) + 2]),
|
||||
);
|
||||
socket.set_timeout(Some(smoltcp::time::Duration::from_secs(10)));
|
||||
let _ = socket.listen(PORT);
|
||||
TcpSlot {
|
||||
handle: sockets.add(socket),
|
||||
pending: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
iface,
|
||||
wire,
|
||||
sockets,
|
||||
udp,
|
||||
tcp,
|
||||
next_request: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self, now: NetTime) {
|
||||
self.iface.poll(now, &mut self.wire, &mut self.sockets);
|
||||
}
|
||||
|
||||
fn dispatch(&mut self, resolver: &Resolver, jobs: &mut Jobs) {
|
||||
let udp = self.sockets.get_mut::<udp::Socket>(self.udp);
|
||||
while let Ok((wire, metadata)) = udp.recv() {
|
||||
if jobs.len() >= QUEUE || wire.len() > MAX_MESSAGE_LEN {
|
||||
continue;
|
||||
}
|
||||
let resolver = resolver.clone();
|
||||
let query = wire.to_vec();
|
||||
let limit = self.wire.mtu.saturating_sub(28);
|
||||
jobs.spawn(async move {
|
||||
let reply = resolver
|
||||
.answer(&query)
|
||||
.await
|
||||
.map(|reply| truncate_for_udp(&query, reply, limit));
|
||||
(Client::Udp(metadata.endpoint), reply)
|
||||
});
|
||||
}
|
||||
for (index, slot) in self.tcp.iter_mut().enumerate() {
|
||||
let tcp = self.sockets.get_mut::<tcp::Socket>(slot.handle);
|
||||
if !tcp.is_open() {
|
||||
slot.pending = None;
|
||||
let _ = tcp.listen(PORT);
|
||||
}
|
||||
if slot.pending.is_some() || tcp.send_queue() != 0 {
|
||||
continue;
|
||||
}
|
||||
if tcp.state() == tcp::State::CloseWait && tcp.recv_queue() < 2 {
|
||||
tcp.close();
|
||||
continue;
|
||||
}
|
||||
let mut header = [0; 2];
|
||||
if tcp.peek_slice(&mut header) != Ok(2) {
|
||||
continue;
|
||||
}
|
||||
let len = usize::from(u16::from_be_bytes(header));
|
||||
if !(12..=MAX_MESSAGE_LEN).contains(&len) {
|
||||
tcp.abort();
|
||||
continue;
|
||||
}
|
||||
if tcp.recv_queue() < len + 2 || jobs.len() >= QUEUE {
|
||||
continue;
|
||||
}
|
||||
let mut query = vec![0; len];
|
||||
if tcp.recv_slice(&mut header) != Ok(2) || tcp.recv_slice(&mut query) != Ok(len) {
|
||||
tcp.abort();
|
||||
continue;
|
||||
}
|
||||
self.next_request = self.next_request.wrapping_add(1);
|
||||
let request = self.next_request;
|
||||
slot.pending = Some(request);
|
||||
let resolver = resolver.clone();
|
||||
jobs.spawn(async move {
|
||||
(
|
||||
Client::Tcp {
|
||||
slot: index,
|
||||
request,
|
||||
},
|
||||
resolver.answer(&query).await,
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn deliver(&mut self, client: Client, reply: Option<Vec<u8>>) {
|
||||
match client {
|
||||
Client::Udp(peer) => {
|
||||
if let Some(reply) = reply {
|
||||
let _ = self
|
||||
.sockets
|
||||
.get_mut::<udp::Socket>(self.udp)
|
||||
.send_slice(&reply, peer);
|
||||
}
|
||||
}
|
||||
Client::Tcp { slot, request } => {
|
||||
let slot = &mut self.tcp[slot];
|
||||
if slot.pending != Some(request) {
|
||||
return;
|
||||
}
|
||||
slot.pending = None;
|
||||
let tcp = self.sockets.get_mut::<tcp::Socket>(slot.handle);
|
||||
if let Some(reply) = reply
|
||||
&& let Ok(len) = u16::try_from(reply.len())
|
||||
&& tcp.send_slice(&len.to_be_bytes()) == Ok(2)
|
||||
&& tcp.send_slice(&reply) == Ok(reply.len())
|
||||
{
|
||||
return;
|
||||
}
|
||||
tcp.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(
|
||||
address: Ipv4Addr,
|
||||
mtu: usize,
|
||||
resolver: Resolver,
|
||||
mut input: mpsc::Receiver<Vec<u8>>,
|
||||
fd: Arc<AsyncFd<File>>,
|
||||
) {
|
||||
let mut stack = Stack::new(address, mtu);
|
||||
let mut jobs = Jobs::new();
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
|
||||
stack.poll(now);
|
||||
stack.dispatch(&resolver, &mut jobs);
|
||||
stack.poll(now);
|
||||
while let Some(packet) = stack.wire.output.pop_front() {
|
||||
if !matches!(fd.async_io(Interest::WRITABLE, |mut file| file.write(&packet)).await, Ok(n) if n == packet.len())
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
let delay = stack
|
||||
.iface
|
||||
.poll_delay(now, &stack.sockets)
|
||||
.map(Duration::from);
|
||||
tokio::select! {
|
||||
packet = input.recv() => match packet { Some(packet) => stack.wire.input = Some(packet), None => return },
|
||||
Some(Ok((client, reply))) = jobs.join_next(), if !jobs.is_empty() => stack.deliver(client, reply),
|
||||
_ = async { if let Some(delay) = delay { tokio::time::sleep(delay).await } else { std::future::pending().await } } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, TYPE};
|
||||
use std::os::{fd::OwnedFd, unix::net::UnixDatagram};
|
||||
use tsunagi::dns::{Zone, ZoneName, Zones};
|
||||
|
||||
#[tokio::test]
|
||||
async fn android_tun_dns_truncates_udp_and_returns_the_complete_answer_over_tcp() {
|
||||
let address = Ipv4Addr::new(192, 0, 2, 53);
|
||||
let phone = Ipv4Addr::new(10, 10, 0, 1);
|
||||
let (fd, os) = UnixDatagram::pair().unwrap();
|
||||
fd.set_nonblocking(true).unwrap();
|
||||
os.set_nonblocking(true).unwrap();
|
||||
let fd = AsyncFd::new(File::from(OwnedFd::from(fd))).unwrap();
|
||||
let os = tokio::net::UnixDatagram::from_std(os).unwrap();
|
||||
let resolver = Resolver::new(|_| panic!("a mesh name went upstream"));
|
||||
resolver.replace(Some(Zones::new([Zone::new(
|
||||
ZoneName::new("tsng").unwrap(),
|
||||
(1..=90).map(|host| ("api".into(), Ipv4Addr::new(10, 1, 2, host))),
|
||||
)])));
|
||||
let port = DnsPort::start(address, 1280, resolver, Arc::new(fd));
|
||||
let mut wire = Wire {
|
||||
mtu: 1280,
|
||||
input: None,
|
||||
output: VecDeque::new(),
|
||||
};
|
||||
let mut iface = Interface::new(
|
||||
Config::new(HardwareAddress::Ip),
|
||||
&mut wire,
|
||||
NetTime::from_millis(0),
|
||||
);
|
||||
iface.update_ip_addrs(|a| a.push(IpCidr::new(IpAddress::Ipv4(phone), 0)).unwrap());
|
||||
let mut sockets = SocketSet::new(Vec::new());
|
||||
let buf = || udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY; 4], vec![0; 4096]);
|
||||
let mut datagram = udp::Socket::new(buf(), buf());
|
||||
datagram.bind(41000).unwrap();
|
||||
let mut packet = Packet::new_query(42);
|
||||
packet.questions.push(Question::new(
|
||||
Name::new("api.tsng").unwrap(),
|
||||
TYPE::A.into(),
|
||||
CLASS::IN.into(),
|
||||
false,
|
||||
));
|
||||
let query = packet.build_bytes_vec().unwrap();
|
||||
datagram.send_slice(&query, (address, PORT)).unwrap();
|
||||
let udp = sockets.add(datagram);
|
||||
let tcp = sockets.add(tcp::Socket::new(
|
||||
tcp::SocketBuffer::new(vec![0; 8192]),
|
||||
tcp::SocketBuffer::new(vec![0; 512]),
|
||||
));
|
||||
let mut sent = false;
|
||||
let mut received = Vec::new();
|
||||
let mut buf = [0; 1500];
|
||||
let start = Instant::now();
|
||||
tokio::time::timeout(Duration::from_secs(4), async {
|
||||
loop {
|
||||
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
|
||||
iface.poll(now, &mut wire, &mut sockets);
|
||||
if let Ok((reply, from)) = sockets.get_mut::<udp::Socket>(udp).recv() {
|
||||
assert_eq!(from.endpoint, (address, PORT).into());
|
||||
let reply = Packet::parse(reply).unwrap();
|
||||
assert_eq!(reply.id(), 42);
|
||||
assert!(reply.has_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER));
|
||||
sockets
|
||||
.get_mut::<tcp::Socket>(tcp)
|
||||
.connect(iface.context(), (address, PORT), 41001)
|
||||
.unwrap();
|
||||
}
|
||||
let stream = sockets.get_mut::<tcp::Socket>(tcp);
|
||||
if stream.can_send() && !sent {
|
||||
let mut frame = (query.len() as u16).to_be_bytes().to_vec();
|
||||
frame.extend_from_slice(&query);
|
||||
assert_eq!(stream.send_slice(&frame).unwrap(), frame.len());
|
||||
sent = true;
|
||||
}
|
||||
while stream.can_recv() {
|
||||
let n = stream.recv_slice(&mut buf).unwrap();
|
||||
received.extend_from_slice(&buf[..n]);
|
||||
}
|
||||
if let Some(prefix) = received.first_chunk::<2>()
|
||||
&& received.len() == 2 + usize::from(u16::from_be_bytes(*prefix))
|
||||
{
|
||||
break;
|
||||
}
|
||||
iface.poll(now, &mut wire, &mut sockets);
|
||||
for outgoing in wire.output.drain(..) {
|
||||
assert!(port.intercept(&outgoing, &[phone.into()]));
|
||||
}
|
||||
let delay = iface
|
||||
.poll_delay(now, &sockets)
|
||||
.map(Duration::from)
|
||||
.unwrap_or(Duration::from_secs(4));
|
||||
tokio::select! {
|
||||
n = os.recv(&mut buf) => wire.input = Some(buf[..n.unwrap()].to_vec()),
|
||||
_ = tokio::time::sleep(delay) => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("DNS over the Android packet device must complete");
|
||||
let reply = Packet::parse(&received[2..]).unwrap();
|
||||
assert_eq!(reply.id(), 42);
|
||||
assert!(!reply.has_flags(PacketFlag::TRUNCATION));
|
||||
assert_eq!(reply.answers.len(), 90);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! The Android application. Mesh state belongs to one service-owned Rust agent.
|
||||
|
||||
pub mod dns;
|
||||
pub mod plan;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
mod android;
|
||||
pub mod service;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(unix)]
|
||||
pub mod tun;
|
||||
pub mod view;
|
||||
@@ -0,0 +1,85 @@
|
||||
//! All addresses and routes installed in the one Android VPN.
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
use tsunagi::overlay::Cidr;
|
||||
|
||||
/// An exhaustive VpnService configuration, derived from local core policy.
|
||||
#[derive(Clone, Default, Debug, PartialEq, Eq)]
|
||||
pub struct VpnPlan {
|
||||
/// One address in each active, non-overlapping network.
|
||||
pub addresses: Vec<Cidr>,
|
||||
/// Payload MTU for every attached network.
|
||||
pub mtu: u32,
|
||||
/// Capture IPv4 traffic outside the mesh.
|
||||
pub full_tunnel: bool,
|
||||
/// Preferred IPv4 source for the default route.
|
||||
pub exit: Option<IpAddr>,
|
||||
/// Capture the limited broadcast when requested by the core.
|
||||
pub broadcast: bool,
|
||||
}
|
||||
|
||||
impl VpnPlan {
|
||||
/// Device-local DNS endpoint. Never take an address from a joined mesh.
|
||||
pub fn dns_address(&self) -> Option<Ipv4Addr> {
|
||||
if self.addresses.is_empty() {
|
||||
return None;
|
||||
}
|
||||
[
|
||||
Ipv4Addr::new(192, 0, 2, 53),
|
||||
Ipv4Addr::new(198, 51, 100, 53),
|
||||
Ipv4Addr::new(203, 0, 113, 53),
|
||||
]
|
||||
.into_iter()
|
||||
.find(|candidate| {
|
||||
!self.addresses.iter().any(|cidr| {
|
||||
let IpAddr::V4(base) = cidr.addr else {
|
||||
return false;
|
||||
};
|
||||
tsunagi::state::Ipv4Range {
|
||||
base,
|
||||
prefix_len: cidr.prefix_len,
|
||||
}
|
||||
.contains(*candidate)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Android uses the first address as primary for unscoped IPv4 traffic.
|
||||
pub fn addresses_in_order(&self) -> Vec<Cidr> {
|
||||
let mut ordered = self.addresses.clone();
|
||||
ordered.sort_by_key(|cidr| (Some(cidr.addr) != self.exit, *cidr));
|
||||
ordered
|
||||
}
|
||||
|
||||
/// Explicitly route the entire agreed subnet, including its virtual services.
|
||||
pub fn routes(&self) -> Vec<String> {
|
||||
let mut routes: Vec<_> = self
|
||||
.addresses
|
||||
.iter()
|
||||
.map(|cidr| {
|
||||
let p = cidr.prefix_len;
|
||||
let base = match cidr.addr {
|
||||
IpAddr::V4(a) => IpAddr::V4(Ipv4Addr::from(
|
||||
u32::from(a) & u32::MAX.checked_shl(u32::from(32 - p)).unwrap_or(0),
|
||||
)),
|
||||
IpAddr::V6(a) => IpAddr::V6(Ipv6Addr::from(
|
||||
u128::from(a) & u128::MAX.checked_shl(u32::from(128 - p)).unwrap_or(0),
|
||||
)),
|
||||
};
|
||||
format!("{base}/{p}")
|
||||
})
|
||||
.collect();
|
||||
if let Some(dns) = self.dns_address() {
|
||||
routes.push(format!("{dns}/32"));
|
||||
}
|
||||
if self.full_tunnel {
|
||||
routes.push("0.0.0.0/0".into());
|
||||
}
|
||||
if self.broadcast {
|
||||
routes.push("255.255.255.255/32".into());
|
||||
}
|
||||
routes.sort();
|
||||
routes.dedup();
|
||||
routes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Actions and status for the service-owned Rust agent.
|
||||
use std::{sync::Arc, time::Instant};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tsunagi::{
|
||||
Agent, NetworkName, NetworkSecret,
|
||||
ipc::{PrivilegeReport, ProtocolReport, StatusReport},
|
||||
vip::VipStatus,
|
||||
};
|
||||
use tsunagi_ui::client::Command;
|
||||
use tsunagi_wg_quic::WireguardPlugin;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// A platform notification or user gesture.
|
||||
pub enum Request {
|
||||
/// A command from the same form used by the tray.
|
||||
Action(Command),
|
||||
/// The physical network changed.
|
||||
NetworkChanged,
|
||||
/// Disable only the exit identified by the notification the user tapped.
|
||||
DisconnectExit {
|
||||
/// Network id captured in the immutable action.
|
||||
network: String,
|
||||
/// Endpoint id captured at the same time.
|
||||
peer: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// A configured default route stays visible if its remote peer goes offline.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ExitNotice {
|
||||
/// Active network identity for the notification action.
|
||||
pub network: String,
|
||||
/// Selected remote device identity.
|
||||
pub peer: String,
|
||||
/// Human-readable mesh name.
|
||||
pub network_name: String,
|
||||
/// Same name shown in the exit chooser.
|
||||
pub name: String,
|
||||
/// Whether the peer still offers its exit.
|
||||
pub online: bool,
|
||||
}
|
||||
|
||||
/// Only an active network with a selected remote exit needs an ongoing notice.
|
||||
pub fn exit_notice(report: &StatusReport) -> Option<ExitNotice> {
|
||||
report.networks.iter().filter(|n| n.active).find_map(|n| {
|
||||
let peer = n.exit.via.as_ref()?;
|
||||
Some(ExitNotice {
|
||||
network: n.network_id.clone(),
|
||||
peer: peer.clone(),
|
||||
network_name: n.name.clone(),
|
||||
name: tsunagi_ui::devices::name_of(n, peer),
|
||||
online: n.exit.via_online,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Actions are serialized in the service command loop. An old PendingIntent cannot
|
||||
/// clear a replacement exit selected in this or another network.
|
||||
pub async fn disconnect_exit(
|
||||
agent: &Agent,
|
||||
network: &str,
|
||||
peer: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let network = network.parse()?;
|
||||
let peer = peer.parse()?;
|
||||
if agent.is_active(network).await && agent.network_status(network).await?.exit_via == Some(peer)
|
||||
{
|
||||
agent.set_exit_via(network, None).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Private reply delivered only to the UI that requested the action.
|
||||
pub enum Outcome {
|
||||
/// The agent has applied the action.
|
||||
Applied,
|
||||
/// Revisions returned by a successful signed write.
|
||||
Saved(Vec<VipStatus>),
|
||||
/// A user-requested, single-use clipboard export.
|
||||
Clipboard(Zeroizing<String>),
|
||||
}
|
||||
|
||||
/// Delivery channel for a request.
|
||||
pub type Reply = tokio::sync::oneshot::Sender<Result<Outcome, String>>;
|
||||
/// Pending acknowledgement of a UI action.
|
||||
pub type Response = tokio::sync::oneshot::Receiver<Result<Outcome, String>>;
|
||||
|
||||
/// Execute exactly the selection and revision supplied by the form.
|
||||
pub async fn apply(
|
||||
command: Command,
|
||||
agent: &Agent,
|
||||
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
|
||||
match command {
|
||||
Command::Join { name, secret } => {
|
||||
agent
|
||||
.join_network(&NetworkName::new(name)?, &NetworkSecret::decode(&secret)?)
|
||||
.await?;
|
||||
}
|
||||
Command::SetActive { network_id, active } => {
|
||||
let id = network_id.parse()?;
|
||||
if active {
|
||||
agent.switch_network(id).await?;
|
||||
} else {
|
||||
agent.pause_network(id).await?;
|
||||
}
|
||||
}
|
||||
Command::Leave { network_id } => {
|
||||
agent.leave_network(network_id.parse()?).await?;
|
||||
}
|
||||
Command::SetBroadcast {
|
||||
network_id,
|
||||
enabled,
|
||||
} => agent.set_broadcast(network_id.parse()?, enabled).await?,
|
||||
Command::SetProtocols {
|
||||
network_id,
|
||||
protocols,
|
||||
} => agent.set_protocols(network_id.parse()?, protocols).await?,
|
||||
Command::SetHostname(hostname) => {
|
||||
agent.set_hostname(&hostname).await?;
|
||||
}
|
||||
Command::ForgetNode {
|
||||
network_id,
|
||||
peer,
|
||||
expected_version,
|
||||
} => {
|
||||
agent
|
||||
.forget_node(network_id.parse()?, peer.parse()?, expected_version)
|
||||
.await?;
|
||||
}
|
||||
Command::SetExitNode { network_id, peer } => {
|
||||
agent
|
||||
.set_exit_via(network_id.parse()?, peer.map(|p| p.parse()).transpose()?)
|
||||
.await?
|
||||
}
|
||||
Command::SetExitOffer { .. } => {
|
||||
return Err("This phone can only use a remote exit node.".into());
|
||||
}
|
||||
Command::SaveVip {
|
||||
network_id,
|
||||
config,
|
||||
expected,
|
||||
delete,
|
||||
..
|
||||
} => {
|
||||
return Ok(Outcome::Saved(
|
||||
agent
|
||||
.save_vip(network_id.parse()?, config, expected, delete)
|
||||
.await?,
|
||||
));
|
||||
}
|
||||
Command::CopySecret { network_id } => {
|
||||
return Ok(Outcome::Clipboard(
|
||||
agent.network_secret(network_id.parse()?).await?.encode(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(Outcome::Applied)
|
||||
}
|
||||
|
||||
/// State visible to an activity which may be recreated while the service runs.
|
||||
#[derive(Clone, Default)]
|
||||
pub enum State {
|
||||
/// The user can start the VPN.
|
||||
#[default]
|
||||
Off,
|
||||
/// Opening the endpoint or waiting for connectivity.
|
||||
Starting,
|
||||
/// The last complete snapshot and its monotonic observation time.
|
||||
Ready(Arc<StatusReport>, Instant),
|
||||
/// Actionable startup or status error.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
/// Build the same network and counter reports used by the desktop client.
|
||||
pub async fn report(
|
||||
agent: &Agent,
|
||||
wg: Option<&WireguardPlugin>,
|
||||
dns: &crate::dns::Resolver,
|
||||
) -> tsunagi::Result<StatusReport> {
|
||||
let status = agent.status().await?;
|
||||
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.refresh(&status.networks)),
|
||||
endpoint_id: status.endpoint_id.to_string(),
|
||||
hostname: status.hostname,
|
||||
bound_sockets: status
|
||||
.bound_sockets
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect(),
|
||||
cache_healthy: status.cache_healthy,
|
||||
available_protocols: tsunagi_runtime::PROTOCOLS
|
||||
.iter()
|
||||
.map(|spec| ProtocolReport {
|
||||
name: spec.name.into(),
|
||||
summary: spec.summary.into(),
|
||||
})
|
||||
.collect(),
|
||||
protocols: tsunagi_runtime::PROTOCOLS
|
||||
.iter()
|
||||
.map(|spec| format!("{} v{}", spec.name, spec.version))
|
||||
.collect(),
|
||||
privilege: PrivilegeReport::Available,
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Drive the agent until Android stops this service instance.
|
||||
pub async fn serve(
|
||||
agent: Agent,
|
||||
wg: Arc<WireguardPlugin>,
|
||||
dns: crate::dns::Resolver,
|
||||
mut commands: mpsc::Receiver<(Request, Reply)>,
|
||||
state: &watch::Sender<State>,
|
||||
mut stop: watch::Receiver<bool>,
|
||||
mut publish_exit: impl FnMut(Option<&ExitNotice>),
|
||||
) {
|
||||
let mut poll = tokio::time::interval(std::time::Duration::from_secs(2));
|
||||
poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut published_exit = None;
|
||||
loop {
|
||||
let reply = tokio::select! {
|
||||
biased;
|
||||
_ = stop.wait_for(|stopped| *stopped) => break,
|
||||
command = commands.recv() => {
|
||||
let Some((request, reply)) = command else { break };
|
||||
let result = match request {
|
||||
Request::Action(cmd) => {
|
||||
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||
dns.replace(None);
|
||||
}
|
||||
apply(cmd, &agent).await.map_err(|e| e.to_string())
|
||||
}
|
||||
Request::NetworkChanged => {
|
||||
agent.endpoint().network_change().await;
|
||||
agent.recheck().await;
|
||||
Ok(Outcome::Applied)
|
||||
}
|
||||
Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await
|
||||
.map(|()| Outcome::Applied).map_err(|e| e.to_string()),
|
||||
};
|
||||
Some((reply, result))
|
||||
}
|
||||
_ = poll.tick() => None,
|
||||
};
|
||||
state.send_replace(match report(&agent, Some(&wg), &dns).await {
|
||||
Ok(report) => {
|
||||
let notice = exit_notice(&report);
|
||||
if published_exit.as_ref() != Some(¬ice) {
|
||||
publish_exit(notice.as_ref());
|
||||
published_exit = Some(notice);
|
||||
}
|
||||
State::Ready(Arc::new(report), Instant::now())
|
||||
}
|
||||
Err(error) => State::Error(error.to_string()),
|
||||
});
|
||||
if let Some((reply, outcome)) = reply {
|
||||
let _ = reply.send(outcome);
|
||||
}
|
||||
}
|
||||
agent.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,651 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::plan::VpnPlan;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use tsunagi::overlay::Cidr;
|
||||
|
||||
fn addr(octet: u8) -> Cidr {
|
||||
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, octet, 42, 19)), 24).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() {
|
||||
use crate::service::{disconnect_exit, exit_notice, report};
|
||||
use tsunagi::{
|
||||
discovery::SharedMemoryDiscovery,
|
||||
testing::{TestAgent, network, wait_until},
|
||||
};
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let phone = TestAgent::spawn(&discovery).await.unwrap();
|
||||
let rules = std::sync::Arc::new(tsunagi::overlay::MockHostRules::new());
|
||||
let tuns = tsunagi::overlay::MemoryTunFactory::new().with_host_rules(rules);
|
||||
let exit = TestAgent::spawn_with(
|
||||
|cfg| cfg.with_interface(std::sync::Arc::new(tuns), "gateway", 1280),
|
||||
&discovery,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (name, secret) = network("travel");
|
||||
let id = phone.agent.join_network(&name, &secret).await.unwrap();
|
||||
exit.agent.set_hostname("gateway").await.unwrap();
|
||||
exit.agent.join_network(&name, &secret).await.unwrap();
|
||||
exit.agent.set_exit_offer(id, true).await.unwrap();
|
||||
let peer = exit.agent.endpoint_id();
|
||||
wait_until("authenticated exit offer", || async {
|
||||
phone
|
||||
.agent
|
||||
.network_status(id)
|
||||
.await
|
||||
.ok()?
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.endpoint_id == peer && p.exit_node)
|
||||
.then_some(())
|
||||
})
|
||||
.await;
|
||||
let dns = crate::dns::Resolver::new(|_| None);
|
||||
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||
phone.agent.set_exit_via(id, Some(peer)).await.unwrap();
|
||||
let notice = exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).unwrap();
|
||||
assert_eq!(notice.name, "gateway");
|
||||
assert_eq!(notice.network_name, "travel");
|
||||
assert!(notice.online);
|
||||
disconnect_exit(
|
||||
&phone.agent,
|
||||
&id.to_string(),
|
||||
&phone.agent.endpoint_id().to_string(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
phone.agent.network_status(id).await.unwrap().exit_via,
|
||||
Some(peer)
|
||||
);
|
||||
exit.stop().await;
|
||||
wait_until(
|
||||
"offline exit remains selected in the notification",
|
||||
|| async {
|
||||
let report = report(&phone.agent, None, &dns).await.ok()?;
|
||||
exit_notice(&report).filter(|n| !n.online)
|
||||
},
|
||||
)
|
||||
.await;
|
||||
disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||
assert!(phone.agent.is_active(id).await);
|
||||
phone.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn vpn_dns_answers_hosts_and_vips_in_each_zone_and_only_forwards_external_names() {
|
||||
use crate::dns::Resolver;
|
||||
use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, RCODE, TYPE, rdata::RData};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use tsunagi::dns::{Zone, ZoneName, Zones};
|
||||
|
||||
fn query(name: &str, kind: TYPE) -> Vec<u8> {
|
||||
let mut packet = Packet::new_query(119);
|
||||
packet.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||
packet.questions.push(Question::new(
|
||||
Name::new(name).unwrap(),
|
||||
kind.into(),
|
||||
CLASS::IN.into(),
|
||||
false,
|
||||
));
|
||||
packet.build_bytes_vec().unwrap()
|
||||
}
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let forwarded = calls.clone();
|
||||
let resolver = Resolver::new(move |wire| {
|
||||
forwarded.fetch_add(1, Ordering::Relaxed);
|
||||
let query = Packet::parse(wire).unwrap();
|
||||
let mut answer = Packet::new_reply(999);
|
||||
answer.questions = query.questions;
|
||||
answer.build_bytes_vec().ok()
|
||||
});
|
||||
let private = query("k8s.tsng", TYPE::A);
|
||||
let answer = resolver.answer(&private).await.unwrap();
|
||||
assert_eq!(
|
||||
Packet::parse(&answer).unwrap().rcode(),
|
||||
RCODE::ServerFailure
|
||||
);
|
||||
let lab = |name, members| Zone::new(ZoneName::new(name).unwrap(), members);
|
||||
resolver.replace(Some(Zones::new([
|
||||
lab(
|
||||
"tsng",
|
||||
vec![
|
||||
("ai".into(), [10, 1, 1, 100].into()),
|
||||
("k8s".into(), [10, 1, 1, 106].into()),
|
||||
],
|
||||
),
|
||||
lab("lab", vec![("ai".into(), [10, 2, 1, 100].into())]),
|
||||
])));
|
||||
for (name, ip) in [
|
||||
("AI.TSNG", [10, 1, 1, 100]),
|
||||
("k8s.tsng", [10, 1, 1, 106]),
|
||||
("ai.lab", [10, 2, 1, 100]),
|
||||
] {
|
||||
let reply = resolver.answer(&query(name, TYPE::A)).await.unwrap();
|
||||
let packet = Packet::parse(&reply).unwrap();
|
||||
assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
|
||||
assert!(
|
||||
matches!(&packet.answers[0].rdata, RData::A(a) if Ipv4Addr::from(a.address) == Ipv4Addr::from(ip))
|
||||
);
|
||||
}
|
||||
for (name, kind, code) in [
|
||||
("missing.tsng", TYPE::A, RCODE::NameError),
|
||||
("k8s.tsng", TYPE::AAAA, RCODE::NoError),
|
||||
] {
|
||||
let reply = resolver.answer(&query(name, kind)).await.unwrap();
|
||||
let packet = Packet::parse(&reply).unwrap();
|
||||
assert_eq!(packet.rcode(), code);
|
||||
assert!(packet.answers.is_empty());
|
||||
assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
|
||||
}
|
||||
assert!(resolver.answer(b"invalid").await.is_none());
|
||||
assert_eq!(calls.load(Ordering::Relaxed), 0);
|
||||
let reply = resolver
|
||||
.answer(&query("example.org", TYPE::HTTPS))
|
||||
.await
|
||||
.unwrap();
|
||||
let packet = Packet::parse(&reply).unwrap();
|
||||
assert_eq!(packet.id(), 119);
|
||||
assert_eq!(packet.questions[0].qtype, TYPE::HTTPS.into());
|
||||
assert_eq!(calls.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_dns_address_is_routed_and_cannot_claim_an_overlay_ip() {
|
||||
let mut plan = VpnPlan {
|
||||
addresses: vec![addr(1)],
|
||||
..Default::default()
|
||||
};
|
||||
let dns = plan.dns_address().unwrap();
|
||||
assert!(plan.routes().contains(&format!("{dns}/32")));
|
||||
plan.addresses.push(Cidr::new(dns.into(), 24).unwrap());
|
||||
let other = plan.dns_address().unwrap();
|
||||
assert_ne!(other, dns);
|
||||
assert!(plan.routes().contains(&format!("{other}/32")));
|
||||
plan.addresses.clear();
|
||||
assert!(plan.dns_address().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn service_dns_tracks_signed_hostnames_vip_deletion_and_reverse_ranges() {
|
||||
use tsunagi::{
|
||||
Agent,
|
||||
dns::{Answer, Query, RosterZones},
|
||||
testing,
|
||||
vip::VipConfig,
|
||||
};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let agent = Agent::spawn(testing::local_config(dir.path()))
|
||||
.await
|
||||
.unwrap();
|
||||
let (network, secret) = testing::network("tsng");
|
||||
let id = agent.join_network(&network, &secret).await.unwrap();
|
||||
agent.set_hostname("worker").await.unwrap();
|
||||
let vip = agent
|
||||
.save_vip(id, VipConfig::new("k8s"), None, false)
|
||||
.await
|
||||
.unwrap()
|
||||
.remove(0);
|
||||
let status = agent.status().await.unwrap();
|
||||
let roster = RosterZones::from_networks(&status.networks);
|
||||
let worker = status.networks[0]
|
||||
.members
|
||||
.iter()
|
||||
.find(|m| m.hostname.as_deref() == Some("worker"))
|
||||
.unwrap()
|
||||
.overlay_address_v4
|
||||
.unwrap();
|
||||
for (name, ip) in [("worker.tsng", worker), ("k8s.tsng", vip.address.unwrap())] {
|
||||
assert_eq!(
|
||||
roster.zones.lookup(name, Query::A).unwrap().1,
|
||||
Answer::Addresses(vec![ip])
|
||||
);
|
||||
let [a, b, c, d] = ip.octets();
|
||||
assert_eq!(
|
||||
roster
|
||||
.zones
|
||||
.lookup(&format!("{d}.{c}.{b}.{a}.in-addr.arpa"), Query::Ptr)
|
||||
.unwrap()
|
||||
.1,
|
||||
Answer::Name(name.into())
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
roster
|
||||
.zones
|
||||
.lookup("8.8.8.8.in-addr.arpa", Query::Ptr)
|
||||
.is_none()
|
||||
);
|
||||
agent
|
||||
.save_vip(id, vip.config, Some(vip.revision), true)
|
||||
.await
|
||||
.unwrap();
|
||||
let zones = RosterZones::from_networks(&agent.status().await.unwrap().networks).zones;
|
||||
assert_eq!(
|
||||
zones.lookup("k8s.tsng", Query::A).unwrap().1,
|
||||
Answer::NoSuchName
|
||||
);
|
||||
agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_exit_keeps_every_mesh_route_and_prefers_the_selected_source() {
|
||||
let first = addr(2);
|
||||
let second = addr(5);
|
||||
let mut plan = VpnPlan {
|
||||
addresses: vec![first, second],
|
||||
mtu: 1280,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
plan.routes(),
|
||||
["10.2.42.0/24", "10.5.42.0/24", "192.0.2.53/32"]
|
||||
);
|
||||
assert_eq!(plan.addresses_in_order(), [first, second]);
|
||||
plan.full_tunnel = true;
|
||||
plan.exit = Some(second.addr);
|
||||
assert_eq!(plan.addresses_in_order(), [second, first]);
|
||||
assert!(plan.routes().contains(&"0.0.0.0/0".into()));
|
||||
assert!(plan.routes().contains(&"10.2.42.0/24".into()));
|
||||
plan.full_tunnel = false;
|
||||
plan.exit = None;
|
||||
plan.addresses.remove(0);
|
||||
assert_eq!(plan.routes(), ["10.5.42.0/24", "192.0.2.53/32"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broadcast_route_is_only_present_when_requested() {
|
||||
let mut plan = VpnPlan {
|
||||
addresses: vec![addr(1)],
|
||||
mtu: 1280,
|
||||
..Default::default()
|
||||
};
|
||||
plan.broadcast = true;
|
||||
assert!(plan.routes().contains(&"255.255.255.255/32".into()));
|
||||
plan.broadcast = false;
|
||||
assert_eq!(plan.routes(), ["10.1.42.0/24", "192.0.2.53/32"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preference() {
|
||||
use tsunagi::{Agent, testing};
|
||||
use tsunagi_runtime::{Carriers, PROTOCOLS};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let names = ["wg", "awg", "wg-quic", "tcp-tls"];
|
||||
let (network, secret) = testing::network("carriers");
|
||||
for restart in [false, true] {
|
||||
let config = testing::local_config(dir.path());
|
||||
let (config, carriers) = Carriers::configure(config, &[], None, |spec| {
|
||||
if spec.name == "tcp-tls" {
|
||||
vec![("port".into(), "0".into())]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
config
|
||||
.carriers
|
||||
.iter()
|
||||
.map(|c| c.protocol_id())
|
||||
.collect::<Vec<_>>(),
|
||||
names
|
||||
);
|
||||
assert!(
|
||||
config
|
||||
.carriers
|
||||
.iter()
|
||||
.zip(PROTOCOLS)
|
||||
.all(|(c, spec)| c.protocol_version() == spec.version)
|
||||
);
|
||||
let agent = Agent::spawn(config).await.unwrap();
|
||||
let _listeners = carriers.listen(&agent);
|
||||
let id = agent.join_network(&network, &secret).await.unwrap();
|
||||
let saved = agent.network_status(id).await.unwrap().protocols;
|
||||
if restart {
|
||||
assert_eq!(saved, ["tcp-tls", "wg"]);
|
||||
} else {
|
||||
assert_eq!(saved, names);
|
||||
agent
|
||||
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
|
||||
.await
|
||||
.unwrap();
|
||||
let (other, secret) = testing::network("other");
|
||||
let second = agent.join_network(&other, &secret).await.unwrap();
|
||||
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
|
||||
}
|
||||
agent.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn commands_scope_vip_edits_and_leaving_to_the_selected_network() {
|
||||
use crate::service::apply;
|
||||
use tsunagi::vip::VipConfig;
|
||||
use tsunagi::{Agent, NetworkName, NetworkSecret, testing};
|
||||
use tsunagi_ui::client::Command;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let agent = Agent::spawn(testing::local_config(dir.path()))
|
||||
.await
|
||||
.unwrap();
|
||||
let name = NetworkName::new("shared-name").unwrap();
|
||||
let one = NetworkSecret::generate();
|
||||
let two = NetworkSecret::generate();
|
||||
for secret in [&one, &two] {
|
||||
apply(
|
||||
Command::Join {
|
||||
name: name.to_string(),
|
||||
secret: secret.encode(),
|
||||
},
|
||||
&agent,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let first = tsunagi::identity::NetworkKeys::derive(&name, &one)
|
||||
.network_id()
|
||||
.to_string();
|
||||
let second = tsunagi::identity::NetworkKeys::derive(&name, &two).network_id();
|
||||
let config = VipConfig::new("web");
|
||||
let save = |expected, delete| Command::SaveVip {
|
||||
token: "draft".into(),
|
||||
network_id: first.clone(),
|
||||
config: config.clone(),
|
||||
expected,
|
||||
delete,
|
||||
};
|
||||
apply(save(None, false), &agent).await.unwrap();
|
||||
assert!(
|
||||
apply(save(Some("stale".into()), true), &agent)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
agent
|
||||
.network_status(first.parse().unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.vips
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
assert!(agent.network_status(second).await.unwrap().vips.is_empty());
|
||||
assert!(
|
||||
apply(
|
||||
Command::SetExitNode {
|
||||
network_id: second.to_string(),
|
||||
peer: Some(agent.endpoint_id().to_string())
|
||||
},
|
||||
&agent
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
apply(
|
||||
Command::SetExitOffer {
|
||||
network_id: second.to_string(),
|
||||
enabled: true
|
||||
},
|
||||
&agent
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
apply(Command::Leave { network_id: first }, &agent)
|
||||
.await
|
||||
.unwrap();
|
||||
let saved = agent.list_networks().await.unwrap();
|
||||
assert_eq!(saved.len(), 1);
|
||||
assert_eq!(saved[0].network_id, second);
|
||||
agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn tun_reader_survives_address_changes_failed_establish_and_last_network_leaving() {
|
||||
use std::io;
|
||||
use std::os::{fd::OwnedFd, unix::net::UnixDatagram};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tsunagi::overlay::{TunFactory, TunRequest};
|
||||
let sockets = Arc::new(Mutex::new(Vec::new()));
|
||||
let peers = sockets.clone();
|
||||
let factory = crate::tun::AndroidTun::new(
|
||||
crate::dns::Resolver::new(|_| None),
|
||||
move |plan| {
|
||||
if plan.addresses.contains(&addr(9)) {
|
||||
return Err(io::Error::other("permission revoked"));
|
||||
}
|
||||
let (dev, os) = UnixDatagram::pair()?;
|
||||
dev.set_nonblocking(true)?;
|
||||
peers.lock().unwrap().push(os);
|
||||
Ok(OwnedFd::from(dev).into())
|
||||
},
|
||||
|_, _| Ok(()),
|
||||
);
|
||||
let mut req = TunRequest::bare("tsun0", 1280);
|
||||
let dev = factory.create(req.clone()).await.unwrap();
|
||||
let reader = tokio::spawn({
|
||||
let dev = dev.clone();
|
||||
async move { dev.recv().await.unwrap() }
|
||||
});
|
||||
req.addresses = vec![addr(2)];
|
||||
factory.reconfigure(req.clone()).await.unwrap();
|
||||
assert_eq!(factory.assigned_addresses(), [addr(2).addr]);
|
||||
req.addresses.push(addr(9));
|
||||
assert!(factory.reconfigure(req.clone()).await.is_err());
|
||||
assert_eq!(factory.assigned_addresses(), [addr(2).addr]);
|
||||
sockets
|
||||
.lock()
|
||||
.unwrap()
|
||||
.last()
|
||||
.unwrap()
|
||||
.send(b"first")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
&tokio::time::timeout(std::time::Duration::from_secs(2), reader)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()[..],
|
||||
b"first"
|
||||
);
|
||||
req.addresses.clear();
|
||||
factory.reconfigure(req.clone()).await.unwrap();
|
||||
assert!(
|
||||
dev.send(bytes::Bytes::from_static(b"offline"))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(factory.assigned_addresses().is_empty());
|
||||
req.addresses = vec![addr(5)];
|
||||
factory.reconfigure(req).await.unwrap();
|
||||
sockets
|
||||
.lock()
|
||||
.unwrap()
|
||||
.last()
|
||||
.unwrap()
|
||||
.send(b"second")
|
||||
.unwrap();
|
||||
assert_eq!(&dev.recv().await.unwrap()[..], b"second");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() {
|
||||
use crate::{
|
||||
service::{State, report},
|
||||
view::{Phone, configure},
|
||||
};
|
||||
use egui::epaint::Shape;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let agent = tsunagi::Agent::spawn(tsunagi::testing::local_config(dir.path()))
|
||||
.await
|
||||
.unwrap();
|
||||
let (name, secret) = tsunagi::testing::network("layout");
|
||||
agent.join_network(&name, &secret).await.unwrap();
|
||||
let mut sample = report(&agent, None, &crate::dns::Resolver::new(|_| None))
|
||||
.await
|
||||
.unwrap();
|
||||
sample.networks[0].overlay = Some(tsunagi::ipc::OverlayReport {
|
||||
address: Some("10.1.2.3".into()),
|
||||
..Default::default()
|
||||
});
|
||||
let state = State::Ready(Arc::new(sample), Instant::now());
|
||||
let ctx = egui::Context::default();
|
||||
configure(&ctx);
|
||||
let mut phone = Phone::default();
|
||||
let frame = ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(360., 720.),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
phone.draw(ctx, &state, |_| {
|
||||
panic!("drawing the overview issued a command")
|
||||
});
|
||||
},
|
||||
);
|
||||
let y = |label: &str| {
|
||||
frame
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|shape| match &shape.shape {
|
||||
Shape::Text(text) if text.galley.text() == label => Some(text.pos.y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing label {label}"))
|
||||
};
|
||||
assert!((0.0..=26.0).contains(&(y("host") - y("device"))));
|
||||
assert!((0.0..=26.0).contains(&(y("range") - y("id"))));
|
||||
assert!((0.0..=26.0).contains(&(y("peers") - y("addr"))));
|
||||
agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
|
||||
use crate::service::State;
|
||||
use crate::view::{Phone, configure};
|
||||
use egui::{Event, PointerButton, Pos2, RawInput, Rect, Shape};
|
||||
use std::{sync::Arc, time::Instant};
|
||||
use tsunagi::{
|
||||
ipc::{NetworkReport, StatusReport},
|
||||
vip::{
|
||||
Backend, BackendStatus, Counters, Listener, ListenerStatus, Protocol, VipConfig,
|
||||
VipStatus,
|
||||
},
|
||||
};
|
||||
let backend = Backend {
|
||||
peer: "node".into(),
|
||||
port: 8080,
|
||||
};
|
||||
let mut config = VipConfig::new("web");
|
||||
let mut listener = Listener::new(Protocol::Tcp, 80);
|
||||
listener.backends.push(backend.clone());
|
||||
config.listeners.push(listener);
|
||||
let network = NetworkReport {
|
||||
active: true,
|
||||
name: "lab".into(),
|
||||
network_id: "network".into(),
|
||||
vips: vec![VipStatus {
|
||||
config,
|
||||
address: None,
|
||||
revision: "r1".into(),
|
||||
error: None,
|
||||
listeners: vec![ListenerStatus {
|
||||
protocol: Protocol::Tcp,
|
||||
port: 80,
|
||||
selected: Some(backend.clone()),
|
||||
counters: Counters::default(),
|
||||
backends: vec![BackendStatus {
|
||||
backend,
|
||||
state: "ready".into(),
|
||||
rtt_us: Some(1000),
|
||||
measurement_age_ms: Some(1),
|
||||
active_flows: 1,
|
||||
counters: Counters::default(),
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let state = State::Ready(
|
||||
Arc::new(StatusReport {
|
||||
networks: vec![network],
|
||||
..Default::default()
|
||||
}),
|
||||
Instant::now(),
|
||||
);
|
||||
let ctx = egui::Context::default();
|
||||
configure(&ctx);
|
||||
let mut phone = Phone::default();
|
||||
let mut frame = |events| {
|
||||
ctx.run(
|
||||
RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(360., 800.))),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
phone.draw(ctx, &state, |_| panic!("navigation wrote to the network"));
|
||||
},
|
||||
)
|
||||
};
|
||||
let position = |output: &egui::FullOutput, label: &str| {
|
||||
output
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
Shape::Text(t) if t.galley.text() == label => {
|
||||
Some(t.pos + t.galley.rect.center().to_vec2())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing {label}"))
|
||||
};
|
||||
let mut click = |label: &str| {
|
||||
frame(vec![]);
|
||||
let p = position(&frame(vec![]), label);
|
||||
for pressed in [true, false] {
|
||||
frame(vec![
|
||||
Event::PointerMoved(p),
|
||||
Event::PointerButton {
|
||||
pos: p,
|
||||
button: PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
frame(vec![])
|
||||
};
|
||||
let live = click("VIP");
|
||||
for label in ["Overview", "Configuration", "Next new flow", "node:8080"] {
|
||||
let p = position(&live, label);
|
||||
assert!(
|
||||
(0.0..360.0).contains(&p.x),
|
||||
"{label} is outside the portrait view"
|
||||
);
|
||||
}
|
||||
let editor = click("Configuration");
|
||||
for label in [
|
||||
"Active TCP port checks",
|
||||
"Checks and flow expiry",
|
||||
"+ Backend",
|
||||
"+ Listener",
|
||||
] {
|
||||
position(&editor, label);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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,361 @@
|
||||
//! Android supplies navigation and the VPN lifecycle to the shared egui forms.
|
||||
use crate::service::{Outcome, Response, State};
|
||||
use egui::{Color32, Context};
|
||||
use egui_phosphor::regular as icon;
|
||||
use std::cell::RefCell;
|
||||
use tsunagi_ui::{
|
||||
about,
|
||||
client::{Client, Command, Snapshot, VipSaveResult},
|
||||
devices,
|
||||
home::{self, UiState},
|
||||
stats::{Traffic, Unit},
|
||||
vip,
|
||||
};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
const BAD: Color32 = Color32::from_rgb(0xd0, 0x4a, 0x3c);
|
||||
|
||||
#[derive(Default, PartialEq, Eq)]
|
||||
enum Page {
|
||||
#[default]
|
||||
Home,
|
||||
About,
|
||||
Join,
|
||||
Devices(String),
|
||||
Vips(String),
|
||||
Exit(String),
|
||||
Leave(String),
|
||||
}
|
||||
impl Page {
|
||||
fn network(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Devices(id) | Self::Vips(id) | Self::Exit(id) | Self::Leave(id) => Some(id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn title(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Home => "tsunagi",
|
||||
Self::About => "About",
|
||||
Self::Join => "Join a network",
|
||||
Self::Devices(_) => "Devices",
|
||||
Self::Vips(_) => "VIP",
|
||||
Self::Exit(_) => "Exit node",
|
||||
Self::Leave(_) => "Leave network",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Operations that require the Android activity.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SystemAction {
|
||||
/// Request VPN consent and start the foreground service.
|
||||
Start,
|
||||
/// Stop the service while preserving this identity and its networks.
|
||||
Stop,
|
||||
/// Read the clipboard after a user gesture.
|
||||
PasteSecret,
|
||||
/// Return to the previous Android activity.
|
||||
Finish,
|
||||
}
|
||||
|
||||
struct Actions {
|
||||
command: RefCell<Option<Command>>,
|
||||
busy: bool,
|
||||
}
|
||||
impl Client for Actions {
|
||||
fn send(&self, cmd: Command) {
|
||||
if !self.busy() {
|
||||
self.command.replace(Some(cmd));
|
||||
}
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
self.busy || self.command.borrow().is_some()
|
||||
}
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
result: Response,
|
||||
vip: Option<String>,
|
||||
go_home: bool,
|
||||
}
|
||||
|
||||
/// Presentation state of the single Android viewport.
|
||||
#[derive(Default)]
|
||||
pub struct Phone {
|
||||
page: Page,
|
||||
forms: UiState,
|
||||
traffic: Traffic,
|
||||
snapshot: Snapshot,
|
||||
pending: Option<Pending>,
|
||||
error: Option<String>,
|
||||
clipboard: Option<Zeroizing<String>>,
|
||||
}
|
||||
|
||||
/// Keep reads at tray density. Extra hit area is reserved for the navigation bar.
|
||||
pub fn configure(ctx: &Context) {
|
||||
ctx.set_fonts(tsunagi_ui::app_fonts());
|
||||
ctx.style_mut(|style| {
|
||||
style.spacing.interact_size.y = 19.0;
|
||||
style.spacing.button_padding = egui::vec2(6.0, 3.0);
|
||||
style.spacing.item_spacing = egui::vec2(6.0, 3.0);
|
||||
});
|
||||
}
|
||||
|
||||
impl Phone {
|
||||
fn home(&mut self) {
|
||||
if let Page::Vips(id) = &self.page {
|
||||
self.forms.vip_windows.remove(id);
|
||||
}
|
||||
self.forms.join.name.clear();
|
||||
self.forms.join.secret.zeroize();
|
||||
self.forms.exit_confirm = None;
|
||||
self.forms.forget_confirm = None;
|
||||
self.page = Page::Home;
|
||||
}
|
||||
|
||||
/// System Back and toolbar Back use the same draft and confirmation state.
|
||||
pub fn back(&mut self) -> Option<SystemAction> {
|
||||
if self.pending.is_some() {
|
||||
return None;
|
||||
}
|
||||
if self.forms.exit_confirm.take().is_some() || self.forms.forget_confirm.take().is_some() {
|
||||
return None;
|
||||
}
|
||||
if let Page::Vips(id) = &self.page
|
||||
&& let Some(editor) = self.forms.vip_windows.get_mut(id)
|
||||
&& editor.dirty()
|
||||
{
|
||||
editor.request_close();
|
||||
} else if self.page == Page::Home {
|
||||
return Some(SystemAction::Finish);
|
||||
} else {
|
||||
self.home();
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Accept a user-initiated paste into the join form.
|
||||
pub fn paste_secret(&mut self, value: String) {
|
||||
if self.page == Page::Join {
|
||||
self.forms.join.secret.zeroize();
|
||||
self.forms.join.secret = Zeroizing::new(value);
|
||||
}
|
||||
}
|
||||
/// Request password input with IME suggestions disabled.
|
||||
pub fn secret_focused(&self, ctx: &Context) -> bool {
|
||||
ctx.memory(|m| m.has_focus("join-secret".into()))
|
||||
}
|
||||
/// Present an error from an Android operation.
|
||||
pub fn error(&mut self, message: String) {
|
||||
self.error = Some(message);
|
||||
}
|
||||
|
||||
/// Take a secret once for the platform’s sensitive clipboard.
|
||||
pub fn take_copied_secret(&mut self) -> Option<Zeroizing<String>> {
|
||||
self.clipboard.take()
|
||||
}
|
||||
|
||||
fn acknowledge(&mut self) {
|
||||
let Some(pending) = &mut self.pending else {
|
||||
return;
|
||||
};
|
||||
let outcome = match pending.result.try_recv() {
|
||||
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return,
|
||||
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
|
||||
Err("VPN service stopped".to_owned())
|
||||
}
|
||||
Ok(v) => v,
|
||||
};
|
||||
if let Some(token) = pending.vip.take() {
|
||||
let result = outcome.and_then(|r| match r {
|
||||
Outcome::Saved(vips) => Ok(vips),
|
||||
_ => Err("Missing VIP save acknowledgement".into()),
|
||||
});
|
||||
self.snapshot.vip_result = Some(VipSaveResult { token, result });
|
||||
} else {
|
||||
match outcome {
|
||||
Ok(Outcome::Clipboard(text)) => self.clipboard = Some(text),
|
||||
Ok(_) if pending.go_home => self.home(),
|
||||
Ok(_) => {}
|
||||
Err(e) => self.error = Some(e),
|
||||
}
|
||||
}
|
||||
self.pending = None;
|
||||
}
|
||||
|
||||
/// Render a tray view in this viewport and send gestures to the service.
|
||||
pub fn draw(
|
||||
&mut self,
|
||||
ctx: &Context,
|
||||
state: &State,
|
||||
mut submit: impl FnMut(Command) -> Result<Response, String>,
|
||||
) -> Option<SystemAction> {
|
||||
self.acknowledge();
|
||||
let report = if let State::Ready(report, at) = state {
|
||||
if self.snapshot.at != Some(*at) {
|
||||
self.snapshot.generation = self.snapshot.generation.wrapping_add(1);
|
||||
self.snapshot.at = Some(*at);
|
||||
self.snapshot.status = Some(Ok(report.clone()));
|
||||
self.traffic.observe(report, *at);
|
||||
}
|
||||
if self
|
||||
.page
|
||||
.network()
|
||||
.is_some_and(|id| !report.networks.iter().any(|n| n.network_id == id))
|
||||
{
|
||||
self.home();
|
||||
}
|
||||
Some(report)
|
||||
} else {
|
||||
if self.page.network().is_some() || self.page == Page::Join {
|
||||
self.home();
|
||||
}
|
||||
self.snapshot = Snapshot::default();
|
||||
self.traffic = Traffic::default();
|
||||
None
|
||||
};
|
||||
let actions = Actions {
|
||||
command: RefCell::default(),
|
||||
busy: self.pending.is_some(),
|
||||
};
|
||||
let mut system = None;
|
||||
egui::TopBottomPanel::top("navigation").show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().interact_size.y = 32.0;
|
||||
if self.page != Page::Home && ui.button(icon::ARROW_LEFT).clicked() {
|
||||
system = self.back();
|
||||
}
|
||||
ui.heading(self.page.title());
|
||||
if self.page == Page::Home {
|
||||
ui.weak(env!("CARGO_PKG_VERSION"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(icon::INFO).clicked() {
|
||||
self.page = Page::About;
|
||||
}
|
||||
if report.is_some() {
|
||||
ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes");
|
||||
ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts");
|
||||
}
|
||||
});
|
||||
} else if self.page == Page::About
|
||||
&& !matches!(state, State::Off)
|
||||
&& ui.button("Stop VPN").clicked()
|
||||
{
|
||||
system = Some(SystemAction::Stop);
|
||||
}
|
||||
});
|
||||
if let Some(error) = &self.error {
|
||||
ui.colored_label(BAD, error);
|
||||
}
|
||||
});
|
||||
let selected = self
|
||||
.page
|
||||
.network()
|
||||
.and_then(|id| report?.networks.iter().find(|n| n.network_id == id));
|
||||
match (&self.page, selected) {
|
||||
(Page::About, _) => about::show(ctx, None, &self.snapshot),
|
||||
(Page::Vips(id), Some(network)) => {
|
||||
let editor = self.forms.vip_windows.entry(id.clone()).or_default();
|
||||
if vip::show(ctx, &actions, editor, network, &self.snapshot) {
|
||||
self.home();
|
||||
}
|
||||
}
|
||||
(Page::Devices(_), Some(network)) => {
|
||||
if let Some(report) = report {
|
||||
devices::show(
|
||||
ctx,
|
||||
&actions,
|
||||
&mut self.forms.unit,
|
||||
(&mut self.forms.exit_confirm, &mut self.forms.forget_confirm),
|
||||
network,
|
||||
&report.endpoint_id,
|
||||
&self.traffic,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
let Some(report) = report else {
|
||||
match state {
|
||||
State::Starting => {ui.spinner(); ui.label("Starting VPN…");}
|
||||
_ => {
|
||||
if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("VPN is stopped");}
|
||||
if ui.button("Start VPN").clicked() {system = Some(SystemAction::Start);}
|
||||
}
|
||||
}
|
||||
return;
|
||||
};
|
||||
match &self.page {
|
||||
Page::Home => {
|
||||
home::draw_header(ui, &actions, &mut self.forms, report);
|
||||
ui.separator();
|
||||
if ui.button("Join or create a network").clicked() {self.page = Page::Join;}
|
||||
for n in &report.networks {
|
||||
if home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false) {self.page = Page::Exit(n.network_id.clone());}
|
||||
if self.forms.open_devices.remove(&n.network_id) {self.page = Page::Devices(n.network_id.clone());}
|
||||
if self.forms.vip_windows.contains_key(&n.network_id) {self.page = Page::Vips(n.network_id.clone());}
|
||||
}
|
||||
}
|
||||
Page::Join => {
|
||||
home::draw_join(ui, &actions, &mut self.forms.join);
|
||||
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
|
||||
}
|
||||
Page::Exit(_) => {
|
||||
if let Some(n) = selected && let Some(choice) = devices::choose_exit(ui, n, &report.endpoint_id) {
|
||||
self.forms.exit_confirm = Some(choice);
|
||||
}
|
||||
}
|
||||
Page::Leave(id) => {
|
||||
if let Some(n) = selected {
|
||||
ui.label(format!("Leave {} on this phone? You will need its secret to join again.", n.name));
|
||||
if ui.button("Leave network").clicked() {actions.send(Command::Leave {network_id: id.clone()});}
|
||||
if ui.button("Cancel").clicked() {self.home();}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
});
|
||||
devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None);
|
||||
}
|
||||
}
|
||||
if let Some(command) = actions.command.into_inner() {
|
||||
self.error = None;
|
||||
if let Command::Leave { network_id } = &command
|
||||
&& !matches!(self.page, Page::Leave(_))
|
||||
{
|
||||
self.page = Page::Leave(network_id.clone());
|
||||
} else {
|
||||
let token = match &command {
|
||||
Command::SaveVip { token, .. } => Some(token.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let go_home = matches!(
|
||||
command,
|
||||
Command::Join { .. } | Command::Leave { .. } | Command::SetExitNode { .. }
|
||||
);
|
||||
match submit(command) {
|
||||
Ok(result) => {
|
||||
self.pending = Some(Pending {
|
||||
result,
|
||||
vip: token,
|
||||
go_home,
|
||||
})
|
||||
}
|
||||
Err(error) => {
|
||||
if let Some(token) = token {
|
||||
self.snapshot.vip_result = Some(VipSaveResult {
|
||||
token,
|
||||
result: Err(error),
|
||||
});
|
||||
} else {
|
||||
self.error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
system
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-awg"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-core"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
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"]
|
||||
@@ -59,6 +59,8 @@ rand = "0.10"
|
||||
# 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.
|
||||
|
||||
@@ -104,7 +104,7 @@ struct Inner {
|
||||
networks: RwLock<HashMap<NetworkId, NetworkHandle>>,
|
||||
shutdown: Shutdown,
|
||||
/// Serialises start, stop, switching and conflict cleanup, including teardown.
|
||||
lifecycle: Mutex<()>,
|
||||
lifecycle: Arc<Mutex<()>>,
|
||||
range_changed: watch::Sender<()>,
|
||||
range_task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
accept_task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
@@ -135,7 +135,9 @@ impl Inner {
|
||||
.await
|
||||
{
|
||||
Ok(interface) => {
|
||||
self.adapter.exclude_interface(interface.name());
|
||||
if interface.on_host() {
|
||||
self.adapter.exclude_interface(interface.name());
|
||||
}
|
||||
for carrier in &self.config.carriers {
|
||||
carrier.on_interface_ready(interface.name());
|
||||
}
|
||||
@@ -448,7 +450,7 @@ impl Agent {
|
||||
events,
|
||||
networks: RwLock::new(HashMap::new()),
|
||||
shutdown: Shutdown::new(),
|
||||
lifecycle: Mutex::new(()),
|
||||
lifecycle: Arc::new(Mutex::new(())),
|
||||
range_changed,
|
||||
range_task: std::sync::Mutex::new(None),
|
||||
accept_task: std::sync::Mutex::new(None),
|
||||
@@ -643,6 +645,7 @@ impl Agent {
|
||||
on_host: interface.on_host(),
|
||||
mtu: interface.mtu(),
|
||||
addresses: interface.wanted_addresses(),
|
||||
address_error: interface.address_error(),
|
||||
counters: interface.counters(),
|
||||
broadcast_rules: interface.broadcast_rules(),
|
||||
})
|
||||
@@ -794,47 +797,27 @@ impl Agent {
|
||||
/// choice in the others. The member has to be connected and offering
|
||||
/// to be an exit node. Remembered across restarts.
|
||||
pub async fn set_exit_via(&self, network_id: NetworkId, via: Option<EndpointId>) -> Result<()> {
|
||||
let active = self.is_active(network_id).await;
|
||||
if via.is_some() && !active {
|
||||
return Err(Error::NetworkNotActive(network_id));
|
||||
}
|
||||
if active {
|
||||
let (reply, receive) = oneshot::channel();
|
||||
self.command(network_id, NetCommand::SetExitVia { via, reply })
|
||||
.await?;
|
||||
receive
|
||||
.await
|
||||
.map_err(|_| Error::Stopped)?
|
||||
.map_err(|reason| Error::Rejected { reason })?;
|
||||
}
|
||||
self.inner
|
||||
.storage
|
||||
.set_exit_via(network_id, via.map(|peer| *peer.as_bytes()))
|
||||
.await?;
|
||||
if via.is_some() {
|
||||
// One default route: whatever the other networks were doing, they
|
||||
// are not any more.
|
||||
let others: Vec<NetworkId> = self
|
||||
.inner
|
||||
.networks
|
||||
.read()
|
||||
.await
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|other| *other != network_id)
|
||||
.collect();
|
||||
for other in others {
|
||||
let (reply, receive) = oneshot::channel();
|
||||
if self
|
||||
.command(other, NetCommand::SetExitVia { via: None, reply })
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
let _ = receive.await;
|
||||
}
|
||||
let lifecycle = self.inner.lifecycle.clone().lock_owned().await;
|
||||
if !self.is_active(network_id).await {
|
||||
if via.is_some() {
|
||||
return Err(Error::NetworkNotActive(network_id));
|
||||
}
|
||||
return self.inner.storage.set_exit_via(network_id, None).await;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
// The actor owns the guard through validation, persistence and routing,
|
||||
// even if the requesting IPC client disconnects halfway through.
|
||||
let (reply, receive) = oneshot::channel();
|
||||
self.command(
|
||||
network_id,
|
||||
NetCommand::SetExitVia {
|
||||
via,
|
||||
lifecycle,
|
||||
reply,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
receive.await.map_err(|_| Error::Stopped)?
|
||||
}
|
||||
|
||||
/// Changes a network's local broadcast policy now and after restart.
|
||||
@@ -958,6 +941,13 @@ impl Agent {
|
||||
)?;
|
||||
}
|
||||
let range = self.desired_range(network_id).await?;
|
||||
let exit = crate::overlay::ExitPolicy {
|
||||
offer: stored.as_ref().is_some_and(|s| s.exit_node),
|
||||
via: stored
|
||||
.as_ref()
|
||||
.and_then(|s| s.exit_via)
|
||||
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok()),
|
||||
};
|
||||
if let Some(range) = range {
|
||||
let conflicts = self.inner.routes.overlapping_networks(network_id, range);
|
||||
if !conflicts.is_empty() {
|
||||
@@ -967,19 +957,20 @@ impl Agent {
|
||||
conflicts: conflicts.into_iter().map(|(id, _)| id).collect(),
|
||||
});
|
||||
}
|
||||
self.inner
|
||||
.routes
|
||||
.set_network(
|
||||
network_id,
|
||||
crate::overlay::NetworkRoutes {
|
||||
range: Some(range),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.map_err(|err| Error::Rejected {
|
||||
reason: err.to_string(),
|
||||
})?;
|
||||
}
|
||||
self.inner
|
||||
.routes
|
||||
.set_network(
|
||||
network_id,
|
||||
crate::overlay::NetworkRoutes {
|
||||
range,
|
||||
exit,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.map_err(|err| Error::Rejected {
|
||||
reason: err.to_string(),
|
||||
})?;
|
||||
let mut backends = Vec::new();
|
||||
if let Some(discovery) = &self.inner.config.discovery {
|
||||
backends.push(discovery.clone());
|
||||
@@ -1003,17 +994,10 @@ impl Agent {
|
||||
if !plugins.is_empty() {
|
||||
self.inner.ensure_interface().await;
|
||||
}
|
||||
let exit_offer = stored.as_ref().is_some_and(|stored| stored.exit_node);
|
||||
let exit_via = stored
|
||||
.as_ref()
|
||||
.and_then(|stored| stored.exit_via)
|
||||
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok());
|
||||
let handle = network::spawn(RuntimeParams {
|
||||
vips,
|
||||
retirements,
|
||||
broadcast,
|
||||
exit_offer,
|
||||
exit_via,
|
||||
keys,
|
||||
adapter: self.inner.adapter.clone(),
|
||||
storage: self.inner.storage.clone(),
|
||||
@@ -1179,6 +1163,19 @@ impl Agent {
|
||||
self.inner.networks.read().await.contains_key(&network_id)
|
||||
}
|
||||
|
||||
/// Retrieve the locally stored secret for an explicit user export.
|
||||
/// Status and ordinary network listings never include it.
|
||||
pub async fn network_secret(&self, network_id: NetworkId) -> Result<NetworkSecret> {
|
||||
self.inner
|
||||
.storage
|
||||
.list_networks()
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|network| network.network_id == network_id)
|
||||
.map(|network| network.secret)
|
||||
.ok_or(Error::NetworkUnknown(network_id))
|
||||
}
|
||||
|
||||
/// Lists configured networks and whether each is running.
|
||||
pub async fn list_networks(&self) -> Result<Vec<ConfiguredNetwork>> {
|
||||
let active: Vec<NetworkId> = self.inner.networks.read().await.keys().copied().collect();
|
||||
|
||||
@@ -39,6 +39,8 @@ use super::status::{
|
||||
NetworkStatus, PeerStatus,
|
||||
};
|
||||
|
||||
mod selection;
|
||||
|
||||
/// An inbound connection that already passed the handshake.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct InboundSession {
|
||||
@@ -94,7 +96,8 @@ pub(crate) enum NetCommand {
|
||||
/// Send this device's internet traffic through a member, or stop.
|
||||
SetExitVia {
|
||||
via: Option<EndpointId>,
|
||||
reply: oneshot::Sender<std::result::Result<(), String>>,
|
||||
lifecycle: tokio::sync::OwnedMutexGuard<()>,
|
||||
reply: oneshot::Sender<Result<()>>,
|
||||
},
|
||||
/// Resend this agent's announcement to every peer of this network.
|
||||
Reannounce,
|
||||
@@ -175,10 +178,6 @@ pub(crate) struct RuntimeParams {
|
||||
pub(crate) vips: crate::vip::VipSet,
|
||||
pub(crate) retirements: Vec<SignedRetirement>,
|
||||
pub(crate) broadcast: bool,
|
||||
/// This agent offers itself as an exit node here.
|
||||
pub(crate) exit_offer: bool,
|
||||
/// The member this device's internet traffic goes through.
|
||||
pub(crate) exit_via: Option<EndpointId>,
|
||||
pub(crate) keys: NetworkKeys,
|
||||
pub(crate) adapter: EndpointAdapter,
|
||||
pub(crate) storage: Storage,
|
||||
@@ -327,6 +326,7 @@ struct Runtime {
|
||||
/// peer, which outlives any particular path.
|
||||
links: HashMap<(EndpointId, String), Arc<HealthLink>>,
|
||||
pending_health: HashMap<(EndpointId, String), HealthSettings>,
|
||||
comparisons: HashMap<EndpointId, selection::Schedule>,
|
||||
last_failed_protocol: HashMap<EndpointId, String>,
|
||||
/// Every data link of this network, and what is reached through what.
|
||||
hub: Arc<crate::dataplane::relay::RelayHub>,
|
||||
@@ -450,6 +450,7 @@ impl Runtime {
|
||||
dial_results_rx,
|
||||
links: HashMap::new(),
|
||||
pending_health: HashMap::new(),
|
||||
comparisons: HashMap::new(),
|
||||
last_failed_protocol: HashMap::new(),
|
||||
hub,
|
||||
reachable: HashMap::new(),
|
||||
@@ -685,25 +686,24 @@ impl Runtime {
|
||||
let _ = reply.send(());
|
||||
}
|
||||
NetCommand::SetExitOffer { enabled, reply } => {
|
||||
self.params.exit_offer = enabled;
|
||||
self.params
|
||||
.routes
|
||||
.update_exit(self.network_id, |exit| exit.offer = enabled);
|
||||
self.apply_exit().await;
|
||||
self.reannounce();
|
||||
let _ = reply.send(());
|
||||
}
|
||||
NetCommand::SetExitVia { via, reply } => {
|
||||
let outcome = match via {
|
||||
Some(peer) if !self.exit_node_online(peer) => Err(
|
||||
"that member is not connected or does not offer to be an exit node"
|
||||
.to_string(),
|
||||
),
|
||||
_ => Ok(()),
|
||||
};
|
||||
if outcome.is_ok() {
|
||||
self.params.exit_via = via;
|
||||
self.exit_via_was_online = via.is_some();
|
||||
NetCommand::SetExitVia {
|
||||
via,
|
||||
lifecycle,
|
||||
reply,
|
||||
} => {
|
||||
let result = self.select_exit(via).await;
|
||||
drop(lifecycle);
|
||||
if result.is_ok() {
|
||||
self.apply_exit().await;
|
||||
}
|
||||
let _ = reply.send(outcome);
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
NetCommand::Recheck => self.discovery_round().await,
|
||||
NetCommand::Reannounce => {
|
||||
@@ -903,7 +903,12 @@ impl Runtime {
|
||||
/// the relays in use. Only hosts that cannot exempt the agent from an
|
||||
/// exit node's default route read it.
|
||||
async fn refresh_underlay(&self) {
|
||||
let Some(interface) = self.params.interface.clone() else {
|
||||
let Some(interface) = self
|
||||
.params
|
||||
.interface
|
||||
.as_ref()
|
||||
.filter(|i| i.needs_underlay_targets())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut addresses = Vec::new();
|
||||
@@ -1304,7 +1309,7 @@ impl Runtime {
|
||||
"the node is online; only offline history can be forgotten".into(),
|
||||
));
|
||||
}
|
||||
if self.params.exit_via == Some(peer) {
|
||||
if self.exit_policy().via == Some(peer) {
|
||||
return Err(Error::ForgetNode(
|
||||
"stop using this exit node before forgetting it".into(),
|
||||
));
|
||||
@@ -1766,20 +1771,36 @@ impl Runtime {
|
||||
}
|
||||
|
||||
fn exit_policy(&self) -> crate::overlay::ExitPolicy {
|
||||
crate::overlay::ExitPolicy {
|
||||
offer: self.params.exit_offer,
|
||||
via: self.params.exit_via,
|
||||
self.params
|
||||
.routes
|
||||
.exit_settings(self.network_id)
|
||||
.map(|(policy, _)| policy)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn select_exit(&mut self, via: Option<EndpointId>) -> Result<()> {
|
||||
if via.is_some_and(|peer| !self.exit_node_online(peer)) {
|
||||
return Err(Error::Rejected {
|
||||
reason: "that member is not connected or does not offer to be an exit node".into(),
|
||||
});
|
||||
}
|
||||
self.params
|
||||
.storage
|
||||
.set_exit_via(self.network_id, via.map(|peer| *peer.as_bytes()))
|
||||
.await?;
|
||||
self.params
|
||||
.routes
|
||||
.update_exit(self.network_id, |exit| exit.via = via);
|
||||
self.exit_via_was_online = via.is_some();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether this agent offers to be an exit node and can really be one.
|
||||
fn exit_ready(&self) -> bool {
|
||||
self.params.exit_offer
|
||||
&& self
|
||||
.params
|
||||
.interface
|
||||
.as_ref()
|
||||
.is_some_and(|interface| interface.exit_offer_ready(self.network_id))
|
||||
self.params
|
||||
.interface
|
||||
.as_ref()
|
||||
.is_some_and(|interface| interface.exit_offer_ready(self.network_id))
|
||||
}
|
||||
|
||||
/// Whether a member is connected and says it is an exit node.
|
||||
@@ -1789,15 +1810,12 @@ impl Runtime {
|
||||
.is_some_and(|session| session.exit_node)
|
||||
}
|
||||
|
||||
/// Puts the exit settings into the routing table and the host rules.
|
||||
/// Reconciles the host rules with the shared routing table.
|
||||
///
|
||||
/// The routes and the rules stay as they are when the exit node in use
|
||||
/// goes away: dropping them would send the traffic out the old way, in
|
||||
/// the clear, without anyone having asked.
|
||||
async fn apply_exit(&mut self) {
|
||||
self.params
|
||||
.routes
|
||||
.set_exit(self.network_id, self.exit_policy());
|
||||
if let Some(interface) = self.params.interface.clone() {
|
||||
interface.sync_exit_rules().await;
|
||||
}
|
||||
@@ -1810,7 +1828,7 @@ impl Runtime {
|
||||
|
||||
/// Says so, once, when the exit node in use is lost or comes back.
|
||||
fn watch_exit_via(&mut self) {
|
||||
let Some(via) = self.params.exit_via else {
|
||||
let Some(via) = self.exit_policy().via else {
|
||||
return;
|
||||
};
|
||||
let online = self.exit_node_online(via);
|
||||
@@ -1861,7 +1879,7 @@ impl Runtime {
|
||||
// a packet for ourselves does not go over a tunnel.
|
||||
let local = self.state.address_of(&self.local_id);
|
||||
let routes = crate::overlay::NetworkRoutes {
|
||||
exit: self.exit_policy(),
|
||||
exit: Default::default(),
|
||||
broadcast: self.broadcast_policy(),
|
||||
range: Some(range),
|
||||
local,
|
||||
@@ -1874,7 +1892,7 @@ impl Runtime {
|
||||
if self
|
||||
.params
|
||||
.routes
|
||||
.set_network(self.network_id, routes)
|
||||
.update_allocations(self.network_id, routes)
|
||||
.is_err()
|
||||
{
|
||||
self.range_blocked
|
||||
@@ -2024,24 +2042,29 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
for (peer, protocol) in dead {
|
||||
let reason = self
|
||||
.links
|
||||
.remove(&(peer, protocol.clone()))
|
||||
.map(|link| {
|
||||
let reason = link
|
||||
.failure_reason()
|
||||
.unwrap_or_else(|| "link closed".into());
|
||||
link.close();
|
||||
reason
|
||||
})
|
||||
.unwrap_or_else(|| "link closed".into());
|
||||
let Some(link) = self.links.remove(&(peer, protocol.clone())) else {
|
||||
continue;
|
||||
};
|
||||
let planned = self
|
||||
.comparisons
|
||||
.get(&peer)
|
||||
.is_some_and(|s| s.retiring(link.profile_id()));
|
||||
let reason = if planned {
|
||||
"retired after carrier comparison".into()
|
||||
} else {
|
||||
let reason = link
|
||||
.failure_reason()
|
||||
.unwrap_or_else(|| "link closed".into());
|
||||
self.data_errors
|
||||
.insert(peer, format!("{protocol}: {reason}"));
|
||||
self.record_protocol_failure(peer, &protocol);
|
||||
reason
|
||||
};
|
||||
link.close();
|
||||
// Only the direct path is gone. Whether the peer is still
|
||||
// reachable through somebody is decided below; the protocol's
|
||||
// link stays either way.
|
||||
self.hub.clear_direct(peer, &protocol);
|
||||
self.data_errors
|
||||
.insert(peer, format!("{protocol}: {reason}"));
|
||||
self.record_protocol_failure(peer, &protocol);
|
||||
self.emit(Event::DataLinkDown {
|
||||
network: self.network_id,
|
||||
peer,
|
||||
@@ -2050,17 +2073,23 @@ impl Runtime {
|
||||
});
|
||||
}
|
||||
|
||||
// Choose the highest priority mutually supported protocol for each peer.
|
||||
// If a direct data link is already open or opening, do not dial another.
|
||||
// If a protocol recently failed, fall back to other mutually supported
|
||||
// protocols according to backoff cooldown.
|
||||
// Foreground recovery always precedes optional comparisons.
|
||||
self.review_comparisons();
|
||||
let now = std::time::Instant::now();
|
||||
let mut wanted: Vec<(EndpointId, String)> = Vec::new();
|
||||
let mut interrupted = Vec::new();
|
||||
for session in self.sessions.values() {
|
||||
let peer = session.peer;
|
||||
if self.links.keys().any(|(p, _)| *p == peer)
|
||||
|| self.opening.iter().any(|(p, _)| *p == peer)
|
||||
{
|
||||
if self.links.keys().any(|(p, _)| *p == peer) {
|
||||
continue;
|
||||
}
|
||||
let opening = self.opening.iter().find(|(id, _)| *id == peer);
|
||||
if opening.is_some_and(|(_, protocol)| {
|
||||
!self
|
||||
.comparisons
|
||||
.get(&peer)
|
||||
.is_some_and(|s| s.is_trial(protocol))
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
if self.no_direct_data(peer) {
|
||||
@@ -2087,27 +2116,41 @@ impl Runtime {
|
||||
continue;
|
||||
}
|
||||
|
||||
let start = next_protocol_index(
|
||||
&supported,
|
||||
self.last_failed_protocol.get(&peer).map(String::as_str),
|
||||
);
|
||||
let last_failed = self.last_failed_protocol.get(&peer);
|
||||
let start = next_protocol_index(&supported, last_failed.map(String::as_str));
|
||||
let chosen = supported
|
||||
.iter()
|
||||
.cycle()
|
||||
.skip(start)
|
||||
.take(supported.len())
|
||||
.find(
|
||||
|proto| match self.protocol_dial_states.get(&(peer, (*proto).clone())) {
|
||||
Some(state) => state.cooldown_until <= now,
|
||||
None => true,
|
||||
},
|
||||
);
|
||||
.find(|proto| {
|
||||
opening.is_none_or(|(_, kind)| kind != *proto && last_failed != Some(*proto))
|
||||
&& self
|
||||
.protocol_dial_states
|
||||
.get(&(peer, (*proto).clone()))
|
||||
.is_none_or(|state| state.cooldown_until <= now)
|
||||
});
|
||||
|
||||
if let Some(proto) = chosen {
|
||||
wanted.push((peer, proto.clone()));
|
||||
if let Some(key) = opening {
|
||||
interrupted.push(key.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A trial can still recover a two-carrier peer. Cancel it only for a
|
||||
// third eligible carrier, preserving the failure order and cooldowns.
|
||||
for key in interrupted {
|
||||
self.opening.remove(&key);
|
||||
self.link_attempts.remove(&key);
|
||||
if let Some(task) = self.link_tasks.remove(&key) {
|
||||
task.abort();
|
||||
}
|
||||
self.finish_comparison(key.0);
|
||||
}
|
||||
let trial = self.next_comparison(&served, now);
|
||||
wanted.extend(trial.iter().cloned());
|
||||
for (peer, protocol) in wanted {
|
||||
let key = (peer, protocol.clone());
|
||||
if self.links.contains_key(&key) || self.opening.contains(&key) {
|
||||
@@ -2119,6 +2162,7 @@ impl Runtime {
|
||||
let transport = Arc::clone(&transport);
|
||||
let network = self.network_id;
|
||||
let shutdown = self.shutdown.clone();
|
||||
let background = trial.as_ref() == Some(&key);
|
||||
self.next_link_attempt = self.next_link_attempt.wrapping_add(1);
|
||||
let generation = self.next_link_attempt;
|
||||
self.link_attempts.insert(key.clone(), generation);
|
||||
@@ -2126,8 +2170,16 @@ impl Runtime {
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => Err("network deactivated".to_string()),
|
||||
result = transport.open(network, peer, &protocol) => {
|
||||
result.map_err(|err| err.to_string())
|
||||
result = async {
|
||||
let dial = transport.open(network, peer, &protocol);
|
||||
if background {
|
||||
tokio::time::timeout(Duration::from_secs(30), dial).await
|
||||
.map_err(|_| "carrier comparison timed out".to_owned())?
|
||||
} else {
|
||||
dial.await
|
||||
}.map_err(|err| err.to_string())
|
||||
} => {
|
||||
result
|
||||
}
|
||||
};
|
||||
let _ = results
|
||||
@@ -2475,6 +2527,10 @@ impl Runtime {
|
||||
self.pending_health.remove(&key)
|
||||
};
|
||||
let link = HealthLink::new(link, self.local_id, settings);
|
||||
if let Some(primary) = self.hub.direct_kinds(peer).first() {
|
||||
self.hub.prefer_direct(peer, primary);
|
||||
}
|
||||
self.link_installed(peer);
|
||||
let path = link.path_description();
|
||||
let max_datagram = link.max_datagram_size();
|
||||
if let Some(old) = self.links.insert(key, Arc::clone(&link)) {
|
||||
@@ -2512,6 +2568,7 @@ impl Runtime {
|
||||
|
||||
/// Retire only the data plane; authenticated membership and topology remain.
|
||||
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
|
||||
self.comparisons.remove(&peer);
|
||||
self.data_errors.remove(&peer);
|
||||
self.link_attempts.retain(|(id, _), _| *id != peer);
|
||||
self.opening.retain(|(id, _)| *id != peer);
|
||||
@@ -2604,6 +2661,9 @@ impl Runtime {
|
||||
|
||||
let snapshot = snapshot_connection(&conn);
|
||||
self.sessions.insert(peer, session);
|
||||
// An exit may be selected as soon as the peer advertises it, before
|
||||
// the next discovery tick. Keep this transport on its physical path.
|
||||
self.refresh_underlay().await;
|
||||
if let Some(worker) = &self.discovery_worker {
|
||||
worker.set_connected(true);
|
||||
}
|
||||
@@ -2661,6 +2721,9 @@ impl Runtime {
|
||||
reason,
|
||||
});
|
||||
}
|
||||
if self.params.carriers.len() > 1 {
|
||||
capabilities.push(selection::capability());
|
||||
}
|
||||
capabilities.truncate(self.params.limits.max_capabilities);
|
||||
self.local_capabilities = capabilities
|
||||
.iter()
|
||||
@@ -2802,6 +2865,10 @@ impl Runtime {
|
||||
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
|
||||
match &message {
|
||||
ControlMessage::Transport { protocol, payload } => {
|
||||
if protocol == selection::PROTOCOL {
|
||||
self.receive_choice(peer, payload.as_bytes());
|
||||
return;
|
||||
}
|
||||
if protocol == "link-health" {
|
||||
// Only the elected initiator supplies a profile, for an enabled,
|
||||
// mutually supported physical protocol in this authenticated session.
|
||||
@@ -3079,6 +3146,7 @@ impl Runtime {
|
||||
.iter()
|
||||
.filter(|cap| {
|
||||
cap.enabled
|
||||
&& cap.protocol != selection::PROTOCOL
|
||||
&& self
|
||||
.params
|
||||
.tunnel
|
||||
@@ -3106,7 +3174,17 @@ impl Runtime {
|
||||
.values()
|
||||
.map(|session| {
|
||||
let snapshot = snapshot_connection(&session.conn);
|
||||
let selected = self
|
||||
.hub
|
||||
.direct_kinds(session.peer)
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|kind| self.links.get(&(session.peer, kind)));
|
||||
PeerStatus {
|
||||
data_rtt: selected
|
||||
.and_then(|link| link.quality())
|
||||
.map(|quality| quality.rtt),
|
||||
data_transport_detail: selected.map(|link| link.path_description()),
|
||||
broadcast: session.broadcast,
|
||||
exit_node: session.exit_node,
|
||||
endpoint_id: session.peer,
|
||||
@@ -3185,6 +3263,7 @@ impl Runtime {
|
||||
members.sort_by(|a, b| a.endpoint_id.as_bytes().cmp(b.endpoint_id.as_bytes()));
|
||||
members.dedup_by(|a, b| a.endpoint_id == b.endpoint_id);
|
||||
|
||||
let exit = self.exit_policy();
|
||||
NetworkStatus {
|
||||
vips: self.params.routes.vips.statuses(self.network_id),
|
||||
protocols: self
|
||||
@@ -3195,12 +3274,9 @@ impl Runtime {
|
||||
.collect(),
|
||||
auto_start: true,
|
||||
broadcast: self.params.broadcast,
|
||||
exit_offer: self.params.exit_offer,
|
||||
exit_via: self.params.exit_via,
|
||||
exit_via_online: self
|
||||
.params
|
||||
.exit_via
|
||||
.is_some_and(|via| self.exit_node_online(via)),
|
||||
exit_offer: exit.offer,
|
||||
exit_via: exit.via,
|
||||
exit_via_online: exit.via.is_some_and(|via| self.exit_node_online(via)),
|
||||
exit_rules: self
|
||||
.params
|
||||
.interface
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,8 @@ pub struct OverlayStatus {
|
||||
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
|
||||
@@ -168,6 +170,10 @@ pub struct PeerStatus {
|
||||
pub transport: TransportKind,
|
||||
/// RTT of the selected path, when iroh reported one.
|
||||
pub rtt: Option<Duration>,
|
||||
/// Recent RTT of the selected direct data link, measured by authenticated probes.
|
||||
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.
|
||||
|
||||
@@ -208,6 +208,7 @@ struct State {
|
||||
/// 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>>,
|
||||
@@ -229,7 +230,14 @@ impl State {
|
||||
.get(peer)
|
||||
.map(|links| links.iter().collect())
|
||||
.unwrap_or_default();
|
||||
links.sort_by_key(|raw| (self.rank(&raw.kind), raw.kind.clone()));
|
||||
let preferred = self.preferred.get(peer);
|
||||
links.sort_by_key(|raw| {
|
||||
(
|
||||
preferred != Some(&raw.kind),
|
||||
self.rank(&raw.kind),
|
||||
&raw.kind,
|
||||
)
|
||||
});
|
||||
links
|
||||
}
|
||||
|
||||
@@ -326,6 +334,7 @@ impl RelayHub {
|
||||
tally: tally.clone(),
|
||||
}),
|
||||
priority: Vec::new(),
|
||||
preferred: HashMap::new(),
|
||||
graph: HashMap::new(),
|
||||
members: HashSet::new(),
|
||||
raw: HashMap::new(),
|
||||
@@ -350,6 +359,23 @@ impl RelayHub {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
@@ -477,6 +503,9 @@ impl RelayHub {
|
||||
/// 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) {
|
||||
@@ -495,6 +524,7 @@ impl RelayHub {
|
||||
/// 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();
|
||||
|
||||
@@ -20,6 +20,32 @@ 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,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Authenticated probes of the actual data link, independent of control RTT.
|
||||
//! Keys are negotiated privately for each physical link. No fixed wire magic.
|
||||
use super::{PacketLink, SharedLink, TransportError};
|
||||
use super::{LinkQuality, PacketLink, SharedLink, TransportError};
|
||||
use crate::{BoxFuture, NetworkId};
|
||||
use bytes::Bytes;
|
||||
use hmac::{Hmac, KeyInit, Mac};
|
||||
@@ -32,40 +32,74 @@ impl std::fmt::Debug for Settings {
|
||||
}
|
||||
struct Samples {
|
||||
pending: VecDeque<(u64, Instant)>,
|
||||
recent: VecDeque<bool>,
|
||||
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) {
|
||||
self.pending.push_back((seq, now));
|
||||
}
|
||||
fn acknowledge(&mut self, seq: u64) {
|
||||
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq) {
|
||||
self.pending.remove(i);
|
||||
self.recent.push_back(true);
|
||||
fn 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) {
|
||||
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq)
|
||||
&& 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn expire(&mut self, now: Instant) {
|
||||
while self
|
||||
.pending
|
||||
.front()
|
||||
.is_some_and(|(_, at)| now.duration_since(*at) >= Duration::from_secs(3))
|
||||
.is_some_and(|(_, at)| now.duration_since(*at) >= PROBE_TIMEOUT)
|
||||
{
|
||||
self.pending.pop_front();
|
||||
self.recent.push_back(false);
|
||||
}
|
||||
while self.recent.len() > 20 {
|
||||
self.recent.pop_front();
|
||||
self.record(None);
|
||||
}
|
||||
}
|
||||
fn degraded(&self) -> bool {
|
||||
self.recent.len() >= 15
|
||||
&& self.recent.iter().filter(|ok| !**ok).count() * 100 >= self.recent.len() * 60
|
||||
&& 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.
|
||||
@@ -75,6 +109,7 @@ pub(crate) struct HealthLink {
|
||||
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 {
|
||||
@@ -99,6 +134,7 @@ impl HealthLink {
|
||||
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();
|
||||
@@ -117,6 +153,7 @@ impl HealthLink {
|
||||
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;
|
||||
}
|
||||
@@ -132,7 +169,10 @@ impl HealthLink {
|
||||
if let Some(settings)=settings && packet.starts_with(&settings.marker) {
|
||||
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
|
||||
if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));}
|
||||
else if kind==2 {samples.acknowledge(seq);}
|
||||
else if kind==2 && marker == Some(settings.marker) {
|
||||
samples.acknowledge(seq, Instant::now());
|
||||
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
|
||||
}
|
||||
}
|
||||
} else {let _=tx.try_send(packet);}
|
||||
}
|
||||
@@ -149,6 +189,11 @@ impl HealthLink {
|
||||
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)];
|
||||
@@ -236,6 +281,15 @@ impl PacketLink for HealthLink {
|
||||
.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()
|
||||
}
|
||||
@@ -251,6 +305,35 @@ impl Drop for HealthLink {
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
#[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);
|
||||
samples.acknowledge(seq, start + Duration::from_millis(delay));
|
||||
}
|
||||
samples.acknowledge(1, start + Duration::from_secs(1));
|
||||
samples.sent(4, start);
|
||||
samples.expire(start + Duration::from_secs(3));
|
||||
samples.acknowledge(4, start + Duration::from_secs(4));
|
||||
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);
|
||||
samples.acknowledge(seq, sent + Duration::from_millis(80));
|
||||
}
|
||||
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();
|
||||
@@ -258,7 +341,7 @@ mod tests {
|
||||
for seq in 0..20 {
|
||||
samples.sent(seq, now);
|
||||
if seq % 5 == 0 {
|
||||
samples.acknowledge(seq);
|
||||
samples.acknowledge(seq, now);
|
||||
}
|
||||
}
|
||||
assert!(!samples.degraded());
|
||||
@@ -266,7 +349,7 @@ mod tests {
|
||||
assert!(samples.degraded());
|
||||
for seq in 20..40 {
|
||||
samples.sent(seq, now);
|
||||
samples.acknowledge(seq);
|
||||
samples.acknowledge(seq, now);
|
||||
}
|
||||
samples.expire(now + Duration::from_secs(4));
|
||||
assert!(!samples.degraded());
|
||||
|
||||
@@ -37,6 +37,7 @@ pub mod carrier;
|
||||
pub use carrier::{DataCarrier, SharedCarrier};
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh::EndpointId;
|
||||
@@ -73,6 +74,25 @@ pub enum TransportError {
|
||||
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.
|
||||
@@ -125,6 +145,11 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
|
||||
None
|
||||
}
|
||||
|
||||
/// Fresh measurements from this physical link's own authenticated probes.
|
||||
fn quality(&self) -> Option<LinkQuality> {
|
||||
None
|
||||
}
|
||||
|
||||
/// A short description of the path in use, for diagnostics.
|
||||
///
|
||||
/// Reports what the transport actually knows. It must not invent a value.
|
||||
|
||||
@@ -59,6 +59,56 @@ pub fn listen_plan(port: u16) -> ListenPlan {
|
||||
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)]
|
||||
|
||||
@@ -81,7 +81,22 @@ impl SharedZone {
|
||||
/// 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>> {
|
||||
let packet = simple_dns::Packet::parse(query).ok()?;
|
||||
match resolve(zones, query)? {
|
||||
Resolution::Local(reply) | Resolution::Outside(reply) => Some(reply),
|
||||
}
|
||||
}
|
||||
|
||||
/// An authoritative decision for a host resolver that also handles external domains.
|
||||
pub enum Resolution {
|
||||
/// Answer locally, including authoritative denials and protocol errors.
|
||||
Local(Vec<u8>),
|
||||
/// A well-formed question outside all mesh zones, with the authoritative server's REFUSED reply.
|
||||
Outside(Vec<u8>),
|
||||
}
|
||||
|
||||
/// Distinguish an external question from an unknown name inside a mesh zone.
|
||||
pub fn resolve(zones: &Zones, query: &[u8]) -> Option<Resolution> {
|
||||
let packet = parse_message(query)?;
|
||||
if packet.has_flags(PacketFlag::RESPONSE) {
|
||||
return None;
|
||||
}
|
||||
@@ -95,18 +110,18 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
||||
|
||||
if packet.opcode() != simple_dns::OPCODE::StandardQuery {
|
||||
*reply.rcode_mut() = RCODE::NotImplemented;
|
||||
return reply.build_bytes_vec().ok();
|
||||
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||
}
|
||||
|
||||
// Exactly one question. Zero is nothing to answer; more than one has no
|
||||
// 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();
|
||||
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();
|
||||
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||
}
|
||||
|
||||
let qname = question.qname.to_string();
|
||||
@@ -117,7 +132,10 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
||||
None => {
|
||||
reply.questions.push(question.clone());
|
||||
*reply.rcode_mut() = RCODE::Refused;
|
||||
return reply.build_bytes_vec_compressed().ok();
|
||||
return reply
|
||||
.build_bytes_vec_compressed()
|
||||
.ok()
|
||||
.map(Resolution::Outside);
|
||||
}
|
||||
};
|
||||
reply.questions.push(question.clone());
|
||||
@@ -163,7 +181,22 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
||||
}
|
||||
}
|
||||
|
||||
reply.build_bytes_vec_compressed().ok()
|
||||
reply
|
||||
.build_bytes_vec_compressed()
|
||||
.ok()
|
||||
.map(Resolution::Local)
|
||||
}
|
||||
|
||||
/// Parse a DNS message only after bounding its section allocations against the bytes received.
|
||||
pub fn parse_message(wire: &[u8]) -> Option<simple_dns::Packet<'_>> {
|
||||
let header = wire.get(..12)?;
|
||||
let counts = |at: usize| usize::from(u16::from_be_bytes([header[at], header[at + 1]]));
|
||||
// Even a root question needs five bytes. An empty root resource record needs eleven.
|
||||
let minimum = 12 + counts(4) * 5 + (counts(6) + counts(8) + counts(10)) * 11;
|
||||
if wire.len() < minimum || wire.len() > usize::from(u16::MAX) {
|
||||
return None;
|
||||
}
|
||||
simple_dns::Packet::parse(wire).ok()
|
||||
}
|
||||
|
||||
/// The zone's start of authority.
|
||||
@@ -202,8 +235,7 @@ fn query_kind(qtype: QTYPE) -> Query {
|
||||
|
||||
/// Whether the client offered EDNS, and so how large an answer it will take.
|
||||
fn udp_limit(query: &[u8]) -> usize {
|
||||
simple_dns::Packet::parse(query)
|
||||
.ok()
|
||||
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)
|
||||
@@ -214,20 +246,19 @@ fn udp_limit(query: &[u8]) -> usize {
|
||||
/// 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.
|
||||
fn truncate_for_udp(query: &[u8], reply: Vec<u8>) -> Vec<u8> {
|
||||
let limit = udp_limit(query);
|
||||
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 Ok(parsed) = simple_dns::Packet::parse(&reply) else {
|
||||
let Some(mut short) = parse_message(&reply) else {
|
||||
return reply;
|
||||
};
|
||||
let mut short = simple_dns::Packet::new_reply(parsed.id());
|
||||
short.set_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER);
|
||||
*short.rcode_mut() = parsed.rcode();
|
||||
for question in &parsed.questions {
|
||||
short.questions.push(question.clone());
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -264,7 +295,7 @@ impl DnsServer {
|
||||
let Some(reply) = respond(&udp_zone.get(), query) else {
|
||||
continue;
|
||||
};
|
||||
let reply = truncate_for_udp(query, reply);
|
||||
let reply = truncate_for_udp(query, reply, MAX_MESSAGE_LEN);
|
||||
if let Err(err) = udp.send_to(&reply, from).await {
|
||||
tracing::debug!(%err, "dns udp reply failed");
|
||||
}
|
||||
@@ -494,7 +525,7 @@ mod tests {
|
||||
"the test needs a big answer"
|
||||
);
|
||||
|
||||
let short = truncate_for_udp(&query, full);
|
||||
let short = truncate_for_udp(&query, full, MAX_MESSAGE_LEN);
|
||||
assert!(short.len() <= CLASSIC_UDP_LIMIT);
|
||||
let parsed = simple_dns::Packet::parse(&short).unwrap();
|
||||
assert!(parsed.has_flags(PacketFlag::TRUNCATION));
|
||||
|
||||
@@ -208,6 +208,7 @@ pub enum Answer {
|
||||
#[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.
|
||||
@@ -246,12 +247,23 @@ impl Zone {
|
||||
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
|
||||
@@ -300,6 +312,12 @@ impl Zone {
|
||||
/// 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()))
|
||||
|
||||
@@ -614,6 +614,8 @@ pub struct LeftReport {
|
||||
/// Everything the agent is doing, in one snapshot.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct StatusReport {
|
||||
/// Last error applying the shared overlay interface's host addresses and routes.
|
||||
pub overlay_config_error: Option<String>,
|
||||
/// Data-plane protocols this agent can enable at runtime.
|
||||
pub available_protocols: Vec<ProtocolReport>,
|
||||
/// This device's persistent endpoint id.
|
||||
@@ -837,8 +839,12 @@ pub struct PeerReport {
|
||||
/// How the connection reaches the peer: `direct`, `relay` or `unknown`,
|
||||
/// as the transport reports it.
|
||||
pub transport: String,
|
||||
/// Round-trip time in milliseconds, when a path is selected.
|
||||
/// Round-trip time of the control connection in milliseconds.
|
||||
pub rtt_ms: Option<u64>,
|
||||
/// Fresh median RTT of the selected direct data link, in milliseconds.
|
||||
pub data_rtt_ms: Option<u64>,
|
||||
/// Underlying path reported by the selected direct data carrier.
|
||||
pub data_transport_detail: Option<String>,
|
||||
/// The peer offers itself as an exit node in this network.
|
||||
pub exit_node: bool,
|
||||
/// How packets reach it.
|
||||
@@ -1135,7 +1141,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
///
|
||||
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
||||
/// changes shape.
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 23]);
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 24]);
|
||||
|
||||
/// Reads one request off an accepted stream, answers it, writes the response.
|
||||
///
|
||||
|
||||
@@ -364,7 +364,9 @@ mod tests {
|
||||
});
|
||||
|
||||
assert!(!is_serving(&path).await, "nothing serves the pipe yet");
|
||||
let control = ControlSocket::bind(&path, source).await.unwrap();
|
||||
let control = ControlSocket::bind(&path, source, ControlSocketAccess::Private)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(is_serving(&path).await, "the agent serves it now");
|
||||
|
||||
let answer = exchange(&path, &Request::Status, EXCHANGE_TIMEOUT)
|
||||
@@ -439,10 +441,10 @@ mod tests {
|
||||
Box::pin(async { StatusReport::default() })
|
||||
});
|
||||
|
||||
let first = ControlSocket::bind(&path, Arc::clone(&source))
|
||||
let first = ControlSocket::bind(&path, Arc::clone(&source), ControlSocketAccess::Private)
|
||||
.await
|
||||
.unwrap();
|
||||
let second = ControlSocket::bind(&path, source).await;
|
||||
let second = ControlSocket::bind(&path, source, ControlSocketAccess::Private).await;
|
||||
assert!(
|
||||
matches!(second, Err(Error::StateLocked { .. })),
|
||||
"{second:?}"
|
||||
|
||||
+117
-11
@@ -222,16 +222,13 @@ fn local_addr_string(addr: &iroh::endpoint::LocalTransportAddr) -> Option<String
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EndpointAdapter {
|
||||
endpoint: Endpoint,
|
||||
owned_interface: Arc<std::sync::RwLock<String>>,
|
||||
owned_interface: Arc<std::sync::OnceLock<String>>,
|
||||
}
|
||||
|
||||
impl EndpointAdapter {
|
||||
/// Excludes the real name after interface creation (macOS assigns utunN).
|
||||
pub(crate) fn exclude_interface(&self, name: &str) {
|
||||
*self
|
||||
.owned_interface
|
||||
.write()
|
||||
.unwrap_or_else(|p| p.into_inner()) = name.to_lowercase();
|
||||
let _ = self.owned_interface.set(name.to_owned());
|
||||
}
|
||||
|
||||
/// Binds an endpoint according to `config`, reusing the persistent device key.
|
||||
@@ -250,16 +247,44 @@ impl EndpointAdapter {
|
||||
TransportPolicy::N0Defaults => builder.preset(presets::N0),
|
||||
};
|
||||
|
||||
let owned_interface =
|
||||
Arc::new(std::sync::RwLock::new(config.interface_name.to_lowercase()));
|
||||
let owned_interface = Arc::new(std::sync::OnceLock::<String>::new());
|
||||
{
|
||||
let monitor_interface = Arc::clone(&owned_interface);
|
||||
#[cfg(windows)]
|
||||
let adapter_id = std::sync::OnceLock::<String>::new();
|
||||
builder = builder.network_change_filter(move |previous, current| {
|
||||
let Some(name) = monitor_interface.get() else {
|
||||
return true;
|
||||
};
|
||||
// Wintun gives us its friendly name. netwatch keys Windows
|
||||
// interfaces by GUID. Enumeration can lag adapter creation,
|
||||
// so cache a successful lookup and retry a miss on later events.
|
||||
#[cfg(windows)]
|
||||
let Some(name) = adapter_id.get().or_else(|| {
|
||||
let id = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.find(|iface| {
|
||||
iface
|
||||
.friendly_name
|
||||
.as_deref()
|
||||
.is_some_and(|alias| alias.eq_ignore_ascii_case(name))
|
||||
})?
|
||||
.name;
|
||||
Some(adapter_id.get_or_init(|| id))
|
||||
}) else {
|
||||
return true;
|
||||
};
|
||||
!only_owned_interface_changed(previous, current, name)
|
||||
});
|
||||
let interface_filter = Arc::clone(&owned_interface);
|
||||
let requested = config.interface_name.clone();
|
||||
let factory = config.tun_factory.clone();
|
||||
let filter = iroh::address_lookup::AddrFilter::new(move |addrs| {
|
||||
let owned_interface = interface_filter
|
||||
.read()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.clone();
|
||||
let owned_interface = interface_filter.get().unwrap_or(&requested).to_lowercase();
|
||||
let mut overlay_ips = std::collections::HashSet::new();
|
||||
if let Some(factory) = &factory {
|
||||
overlay_ips.extend(factory.assigned_addresses());
|
||||
}
|
||||
for iface in netdev::get_interfaces() {
|
||||
let name = iface.name.to_lowercase();
|
||||
let friendly = iface
|
||||
@@ -489,3 +514,84 @@ impl EndpointAdapter {
|
||||
self.endpoint.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// netwatch treats every new unicast prefix as a link change. A second overlay
|
||||
/// prefix on the same TUN cannot affect the paths carrying those tunnels.
|
||||
pub(crate) fn only_owned_interface_changed(
|
||||
previous: &netwatch::netmon::State,
|
||||
current: &netwatch::netmon::State,
|
||||
name: &str,
|
||||
) -> bool {
|
||||
if previous.default_route_interface != current.default_route_interface
|
||||
|| current.default_route_interface.as_deref() == Some(name)
|
||||
|| previous.last_unsuspend != current.last_unsuspend
|
||||
|| previous.is_expensive != current.is_expensive
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Interface equality in netwatch covers identity and flags. Compare
|
||||
// addresses separately, including family, prefix and IPv6 address flags.
|
||||
let same_interface = |a: &netwatch::interfaces::Interface,
|
||||
b: &netwatch::interfaces::Interface| {
|
||||
a == b && a.addrs().eq(b.addrs())
|
||||
};
|
||||
let old_tun = previous.interfaces.get(name);
|
||||
let new_tun = current.interfaces.get(name);
|
||||
match (old_tun, new_tun) {
|
||||
(None, None) => return false,
|
||||
(Some(a), Some(b)) if same_interface(a, b) => return false,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// have_v4, have_v6 and local_addresses are derived from these interfaces
|
||||
// and can all change when only the TUN changes.
|
||||
let old_count = previous.interfaces.len() - usize::from(old_tun.is_some());
|
||||
let new_count = current.interfaces.len() - usize::from(new_tun.is_some());
|
||||
old_count == new_count
|
||||
&& previous.interfaces.iter().all(|(iface, old)| {
|
||||
iface == name
|
||||
|| current
|
||||
.interfaces
|
||||
.get(iface)
|
||||
.is_some_and(|new| same_interface(old, new))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use netwatch::netmon::State;
|
||||
|
||||
#[test]
|
||||
fn tun_address_changes_leave_existing_underlay_connections_alone() {
|
||||
let before = State::fake();
|
||||
let mut after = before.clone();
|
||||
// netwatch keys interfaces by their OS name. Its fixture provides a
|
||||
// unicast address, precisely the kind of change it classifies as major.
|
||||
let tun = State::fake().interfaces.remove("wifi0").unwrap();
|
||||
let address = tun.addrs().next().unwrap().addr();
|
||||
after.interfaces.insert("utun7".into(), tun);
|
||||
after.local_addresses.regular.push(address);
|
||||
assert!(after.is_major_change(&before));
|
||||
assert!(only_owned_interface_changed(&before, &after, "utun7"));
|
||||
assert!(only_owned_interface_changed(&after, &before, "utun7"));
|
||||
assert!(!only_owned_interface_changed(&before, &after, "utun6"));
|
||||
|
||||
// An update to the real underlay can arrive in the same notification.
|
||||
let mut lost_wifi = after.clone();
|
||||
lost_wifi.interfaces.remove("wifi0");
|
||||
assert!(!only_owned_interface_changed(&before, &lost_wifi, "utun7"));
|
||||
let mut changed_route = after.clone();
|
||||
changed_route.default_route_interface = Some("utun7".to_owned());
|
||||
assert!(!only_owned_interface_changed(
|
||||
&before,
|
||||
&changed_route,
|
||||
"utun7"
|
||||
));
|
||||
let mut resumed = after;
|
||||
resumed.last_unsuspend = Some(std::time::Instant::now().into());
|
||||
assert!(!only_owned_interface_changed(&before, &resumed, "utun7"));
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,8 @@ pub struct ExitHostPlan {
|
||||
pub offer: Vec<Ipv4Range>,
|
||||
/// Whether this device sends its internet traffic through a member.
|
||||
pub client: bool,
|
||||
/// Local address in the selected exit network, for hosts that choose a primary address.
|
||||
pub client_source: Option<std::net::Ipv4Addr>,
|
||||
/// The range of every network on the interface. Only the using side
|
||||
/// reads it, to keep this agent's own traffic *to* the overlay inside it
|
||||
/// where the host has no per-user routing (macOS).
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
//! Policy routing, with no `/1` routes and nothing in the main table:
|
||||
//!
|
||||
//! ```text
|
||||
//! table 0x7473: default dev <if>
|
||||
//! table 0x7473: default dev <if> src <selected overlay address>
|
||||
//! 5205: from all fwmark 0x40000000/0x40000000 lookup main
|
||||
//! 5206: from all uidrange <euid>-<euid> lookup main
|
||||
//! 5290: from all lookup main suppress_prefixlength 0
|
||||
@@ -45,6 +45,7 @@
|
||||
|
||||
use crate::BoxFuture;
|
||||
use crate::state::Ipv4Range;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use super::RuleOutcome;
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules, exit_tag, exit_tag_prefix};
|
||||
@@ -441,7 +442,7 @@ impl LinuxHostRules {
|
||||
.map_err(|err| format!("the task failed: {err}"))
|
||||
}
|
||||
|
||||
async fn apply_client(&self, interface: &str) -> RuleOutcome {
|
||||
async fn apply_client(&self, interface: &str, source: Option<Ipv4Addr>) -> RuleOutcome {
|
||||
let xdg = std::env::var("XDG_RUNTIME_DIR").ok();
|
||||
if let Some(reason) = client_refusal(xdg.as_deref()) {
|
||||
// Whatever an earlier run left must not stay in force.
|
||||
@@ -461,7 +462,15 @@ impl LinuxHostRules {
|
||||
.as_ref()
|
||||
.is_some_and(|(name, _, routed)| name == interface && *routed);
|
||||
if installed {
|
||||
// A failed socket refresh must never remove an active exit route.
|
||||
// A different network can now supply the exit on this same TUN.
|
||||
// Preserve the policy rules and underlay protection during the switch.
|
||||
let route = self.route.clone();
|
||||
let name = interface.to_string();
|
||||
match Self::blocking(move || route.update_exit_source(&name, source)).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(err)) => return RuleOutcome::Failed(err.to_string()),
|
||||
Err(reason) => return RuleOutcome::Failed(reason),
|
||||
}
|
||||
return self
|
||||
.refresh_sockets(interface)
|
||||
.await
|
||||
@@ -492,7 +501,8 @@ impl LinuxHostRules {
|
||||
}
|
||||
let route = self.route.clone();
|
||||
let name = interface.to_string();
|
||||
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid)).await {
|
||||
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid, source)).await
|
||||
{
|
||||
Ok(Ok(())) => RuleOutcome::Applied,
|
||||
Ok(Err(err)) => RuleOutcome::Failed(err.to_string()),
|
||||
Err(reason) => RuleOutcome::Failed(reason),
|
||||
@@ -616,7 +626,7 @@ impl ExitHostRules for LinuxHostRules {
|
||||
forwarding_state(read_sysctl, &interface)
|
||||
};
|
||||
let client = if plan.client {
|
||||
Some(self.apply_client(&interface).await)
|
||||
Some(self.apply_client(&interface, plan.client_source).await)
|
||||
} else {
|
||||
if let Err(reason) = self.clear_client(&interface).await {
|
||||
tracing::warn!(%reason, "cannot remove exit-client rules");
|
||||
|
||||
@@ -217,7 +217,9 @@ fn client() {
|
||||
ip(&["-6", "route", "add", "throw", prefix, "table", "52"]);
|
||||
}
|
||||
let mut passive = spawn_listener("listener");
|
||||
route.set_exit_client("tsun0", 990).unwrap();
|
||||
route
|
||||
.set_exit_client("tsun0", 990, Some("10.99.0.1".parse().unwrap()))
|
||||
.unwrap();
|
||||
// uid bypass alone cannot protect reverse lookups, reproducing the bug.
|
||||
run_probes("blocked");
|
||||
install(&run_firewall, "tsun0", 990, true).unwrap();
|
||||
@@ -248,6 +250,25 @@ for family,source,target in [(socket.AF_INET,'198.51.100.2','192.0.2.1'),(socket
|
||||
install(&run_firewall, "tsun0", 990, true).unwrap();
|
||||
run_probes("pass");
|
||||
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("dev tsun0"));
|
||||
// Check our own default table without the foreign VPN's higher-priority default.
|
||||
ip(&["-4", "rule", "del", "priority", "5270"]);
|
||||
for (destination, source) in [
|
||||
("10.13.37.2", "10.13.37.1"),
|
||||
("10.99.0.2", "10.99.0.1"),
|
||||
("198.51.100.2", "10.99.0.1"),
|
||||
] {
|
||||
let result = ip(&["-4", "route", "get", destination, "uid", "991"]);
|
||||
assert!(
|
||||
result.contains("dev tsun0") && result.contains(&format!("src {source}")),
|
||||
"{result}"
|
||||
);
|
||||
}
|
||||
route
|
||||
.update_exit_source("tsun0", Some("10.13.37.1".parse().unwrap()))
|
||||
.unwrap();
|
||||
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("src 10.13.37.1"));
|
||||
assert!(ip(&["-4", "route", "get", "10.99.0.2", "uid", "991"]).contains("src 10.99.0.1"));
|
||||
ip(&["-4", "rule", "add", "priority", "5270", "table", "52"]);
|
||||
let blocked = Command::new("ip")
|
||||
.args(["-6", "route", "get", "2001:db8:2::2", "uid", "991"])
|
||||
.output()
|
||||
@@ -384,6 +405,15 @@ fn strict_firewall_preserves_underlay_and_application_exit_routing() {
|
||||
"tsun0",
|
||||
]);
|
||||
ip(&["-n", &client_name, "link", "set", "tsun0", "up"]);
|
||||
ip(&[
|
||||
"-n",
|
||||
&client_name,
|
||||
"addr",
|
||||
"add",
|
||||
"10.99.0.1/24",
|
||||
"dev",
|
||||
"tsun0",
|
||||
]);
|
||||
let echo_code = r#"import socket,selectors,sys
|
||||
selector=selectors.DefaultSelector()
|
||||
for family in [socket.AF_INET,socket.AF_INET6]:
|
||||
|
||||
@@ -29,8 +29,8 @@
|
||||
//! Linux scheme does not carry over. Instead:
|
||||
//!
|
||||
//! ```text
|
||||
//! route add -net 0.0.0.0/1 -interface <if>
|
||||
//! route add -net 128.0.0.0/1 -interface <if>
|
||||
//! route add -net 0.0.0.0/1 -interface <if> -ifa <selected overlay address>
|
||||
//! route add -net 128.0.0.0/1 -interface <if> -ifa <selected overlay address>
|
||||
//! pass out quick on <if> route-to (<egress> <gateway>) inet proto { tcp udp }
|
||||
//! from any to ! <overlay ranges> user <agent uid>
|
||||
//! nat on <egress> inet from (<if>) to any -> (<egress>)
|
||||
@@ -104,6 +104,7 @@ pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran
|
||||
|
||||
let mut command = Command::new(tool.path());
|
||||
command
|
||||
.env("LC_ALL", "C")
|
||||
.args(args)
|
||||
.stdin(if stdin.is_some() {
|
||||
Stdio::piped()
|
||||
@@ -206,8 +207,8 @@ fn run_ok(
|
||||
Ran::Exited {
|
||||
success: true,
|
||||
stdout,
|
||||
..
|
||||
} => Ok(stdout),
|
||||
stderr,
|
||||
} if tool != Tool::Route || stderr.is_empty() => Ok(stdout),
|
||||
Ran::Exited { stderr, stdout, .. } => Err(format!(
|
||||
"{} {} failed: {}",
|
||||
tool.path(),
|
||||
@@ -380,8 +381,17 @@ const HALVES: [&str; 2] = ["0.0.0.0/1", "128.0.0.0/1"];
|
||||
/// The IPv6 halves, made unreachable.
|
||||
const HALVES_V6: [&str; 2] = ["::/1", "8000::/1"];
|
||||
|
||||
fn route_add_args(half: &str, interface: &str) -> Vec<String> {
|
||||
owned(&["-q", "-n", "add", "-net", half, "-interface", interface])
|
||||
fn route_set_args(
|
||||
action: &str,
|
||||
half: &str,
|
||||
interface: &str,
|
||||
source: Option<Ipv4Addr>,
|
||||
) -> Vec<String> {
|
||||
let mut args = owned(&["-q", "-n", action, "-net", half, "-interface", interface]);
|
||||
if let Some(source) = source {
|
||||
args.extend(["-ifa".into(), source.to_string()]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
fn route_del_args(half: &str, interface: &str) -> Vec<String> {
|
||||
@@ -407,12 +417,57 @@ fn clear_routes(run: Run<'_>, interface: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_routes(run: Run<'_>, interface: &str) -> Result<(), String> {
|
||||
clear_routes(run, interface);
|
||||
/// Installs a split default, or changes its source in place when the route
|
||||
/// already belongs to this utun. Returns whether this call added it.
|
||||
fn set_half(
|
||||
run: Run<'_>,
|
||||
half: &str,
|
||||
interface: &str,
|
||||
source: Option<Ipv4Addr>,
|
||||
) -> Result<bool, String> {
|
||||
match run_ok(
|
||||
run,
|
||||
Tool::Route,
|
||||
&route_set_args("add", half, interface, source),
|
||||
None,
|
||||
) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(why) if why.contains("File exists") => {
|
||||
let lookup = run_ok(run, Tool::Route, &owned(&["-n", "get", "-net", half]), None)
|
||||
.map_err(|inspect| format!("{why}; {inspect}"))?;
|
||||
let field = |key: &str| {
|
||||
lookup
|
||||
.lines()
|
||||
.filter_map(|line| line.trim().split_once(':'))
|
||||
.find_map(|(name, value)| (name == key).then(|| value.trim()))
|
||||
};
|
||||
if field("mask") != Some("128.0.0.0") || field("interface") != Some(interface) {
|
||||
return Err(why);
|
||||
}
|
||||
run_ok(
|
||||
run,
|
||||
Tool::Route,
|
||||
&route_set_args("change", half, interface, source),
|
||||
None,
|
||||
)?;
|
||||
Ok(false)
|
||||
}
|
||||
Err(why) => Err(why),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_routes(run: Run<'_>, interface: &str, source: Option<Ipv4Addr>) -> Result<(), String> {
|
||||
let mut added = Vec::new();
|
||||
for half in HALVES {
|
||||
if let Err(why) = run_ok(run, Tool::Route, &route_add_args(half, interface), None) {
|
||||
clear_routes(run, interface);
|
||||
return Err(why);
|
||||
match set_half(run, half, interface, source) {
|
||||
Ok(true) => added.push(half),
|
||||
Ok(false) => {}
|
||||
Err(why) => {
|
||||
for half in added {
|
||||
let _ = run(Tool::Route, &route_del_args(half, interface), None);
|
||||
}
|
||||
return Err(why);
|
||||
}
|
||||
}
|
||||
}
|
||||
for half in HALVES_V6 {
|
||||
@@ -490,7 +545,7 @@ fn apply_rules(
|
||||
// The routes come after the rules that keep the agent's own traffic off
|
||||
// them: the other order would loop for as long as it takes.
|
||||
if plan.client {
|
||||
set_routes(run, interface)?;
|
||||
set_routes(run, interface, plan.client_source)?;
|
||||
} else {
|
||||
clear_routes(run, interface);
|
||||
}
|
||||
@@ -545,6 +600,7 @@ destination: default\n\
|
||||
pf_missing: bool,
|
||||
pf_load_fails: bool,
|
||||
route_add_fails: bool,
|
||||
half_interface: Option<&'static str>,
|
||||
pf_enable_output: &'static str,
|
||||
}
|
||||
|
||||
@@ -558,6 +614,7 @@ destination: default\n\
|
||||
pf_missing: false,
|
||||
pf_load_fails: false,
|
||||
route_add_fails: false,
|
||||
half_interface: None,
|
||||
pf_enable_output: "pf enabled\nToken : 4242\n",
|
||||
}
|
||||
}
|
||||
@@ -581,14 +638,29 @@ destination: default\n\
|
||||
match tool {
|
||||
Tool::Id => ok("0\n", ""),
|
||||
Tool::Sysctl => ok(self.forwarding, ""),
|
||||
Tool::Route
|
||||
if args.iter().any(|arg| arg == "get")
|
||||
&& args.iter().any(|arg| arg == "-net") =>
|
||||
{
|
||||
match self.half_interface {
|
||||
Some(name) => ok(&format!("mask: 128.0.0.0\ninterface: {name}\n"), ""),
|
||||
None => fail("not in table"),
|
||||
}
|
||||
}
|
||||
Tool::Route if args.first().map(String::as_str) == Some("-n") => {
|
||||
match &self.default_route {
|
||||
Some(text) => ok(text, ""),
|
||||
None => fail("route: writing to routing socket: not in table"),
|
||||
}
|
||||
}
|
||||
Tool::Route if args.contains(&"add".to_string()) && self.route_add_fails => {
|
||||
fail("route: writing to routing socket: File exists")
|
||||
Tool::Route
|
||||
if args.contains(&"add".to_string())
|
||||
&& ((self.route_add_fails && args.iter().any(|a| a == HALVES[1]))
|
||||
|| (self.half_interface.is_some()
|
||||
&& HALVES.iter().any(|half| args.iter().any(|a| a == half)))) =>
|
||||
{
|
||||
// Darwin route can return success after a routing-socket write failed.
|
||||
ok("", "route: writing to routing socket: File exists")
|
||||
}
|
||||
Tool::Route => ok("", ""),
|
||||
Tool::Pfctl if self.pf_missing => Ran::Missing,
|
||||
@@ -718,7 +790,7 @@ destination: default\n\
|
||||
#[test]
|
||||
fn the_overlay_default_routes_are_halves_and_ipv6_is_rejected() {
|
||||
assert_eq!(
|
||||
route_add_args("0.0.0.0/1", "utun5").join(" "),
|
||||
route_set_args("add", "0.0.0.0/1", "utun5", None).join(" "),
|
||||
"-q -n add -net 0.0.0.0/1 -interface utun5"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -805,6 +877,55 @@ destination: default\n\
|
||||
assert!(fake.position("-n get default").unwrap() < add);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_exit_halves_use_the_selected_networks_address_on_a_shared_utun() {
|
||||
let fake = Fake::new();
|
||||
let token = Mutex::new(None);
|
||||
let mut selected = plan(false, true);
|
||||
selected.overlay.push("10.99.0.0/24".parse().unwrap());
|
||||
for source in ["10.99.0.17", "10.13.37.34"] {
|
||||
selected.client_source = Some(source.parse().unwrap());
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &selected);
|
||||
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||
for half in HALVES {
|
||||
assert!(
|
||||
fake.position(&format!("add -net {half} -interface utun5 -ifa {source}"))
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_active_exit_keeps_both_halves_routed_through_its_utun() {
|
||||
let mut selected = plan(false, true);
|
||||
selected.client_source = Some("10.99.0.17".parse().unwrap());
|
||||
let mut fake = Fake::new();
|
||||
fake.half_interface = Some("utun5");
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &Mutex::new(None), &selected);
|
||||
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||
for half in HALVES {
|
||||
assert!(
|
||||
fake.position(&format!(
|
||||
"change -net {half} -interface utun5 -ifa 10.99.0.17"
|
||||
))
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
assert_eq!(fake.count(" delete "), 0);
|
||||
|
||||
let mut foreign = Fake::new();
|
||||
foreign.half_interface = Some("utun9");
|
||||
let report = apply_plan(
|
||||
&|t, a, s| foreign.run(t, a, s),
|
||||
&Mutex::new(None),
|
||||
&selected,
|
||||
);
|
||||
assert!(matches!(report.client, Some(RuleOutcome::Failed(_))));
|
||||
assert_eq!(foreign.count(" change "), 0);
|
||||
assert_eq!(foreign.count(" delete "), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_routes_are_added_when_the_rules_did_not_load() {
|
||||
let mut fake = Fake::new();
|
||||
|
||||
@@ -141,13 +141,18 @@ fn bypass_script(index: u32, gateway: Ipv4Addr, addresses: &[Ipv4Addr]) -> Strin
|
||||
.collect();
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
$keep = @(@({}) | ForEach-Object {{ \"$_/32\" }})\n\
|
||||
foreach ($p in $keep) {{\n\
|
||||
if (-not (Get-NetRoute -DestinationPrefix $p -InterfaceIndex {index} -NextHop '{gateway}' \
|
||||
-PolicyStore ActiveStore -ErrorAction SilentlyContinue)) {{\n\
|
||||
New-NetRoute -DestinationPrefix $p -InterfaceIndex {index} -NextHop '{gateway}' \
|
||||
-RouteMetric {BYPASS_METRIC} -PolicyStore ActiveStore | Out-Null\n\
|
||||
}}\n\
|
||||
}}\n\
|
||||
Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore -ErrorAction SilentlyContinue | \
|
||||
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32') }} | \
|
||||
Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
|
||||
foreach ($ip in @({})) {{\n\
|
||||
New-NetRoute -DestinationPrefix \"$ip/32\" -InterfaceIndex {index} -NextHop '{gateway}' \
|
||||
-RouteMetric {BYPASS_METRIC} -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Out-Null\n\
|
||||
}}\n",
|
||||
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32') -and \
|
||||
($keep -notcontains $_.DestinationPrefix -or $_.InterfaceIndex -ne {index} -or $_.NextHop -ne '{gateway}') }} | \
|
||||
Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n",
|
||||
list.join(", ")
|
||||
)
|
||||
}
|
||||
@@ -159,14 +164,14 @@ fn halves_script(interface: &str) -> String {
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
$alias = {alias}\n\
|
||||
foreach ($p in '0.0.0.0/1', '128.0.0.0/1') {{\n\
|
||||
Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -PolicyStore ActiveStore \
|
||||
-ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
|
||||
if (Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '0.0.0.0' \
|
||||
-PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ continue }}\n\
|
||||
New-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '0.0.0.0' \
|
||||
-RouteMetric 1 -PolicyStore ActiveStore | Out-Null\n\
|
||||
}}\n\
|
||||
foreach ($p in '::/1', '8000::/1') {{\n\
|
||||
Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -PolicyStore ActiveStore \
|
||||
-ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
|
||||
if (Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '::' \
|
||||
-PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ continue }}\n\
|
||||
New-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '::' \
|
||||
-RouteMetric 1 -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Out-Null\n\
|
||||
}}\n"
|
||||
@@ -197,13 +202,21 @@ fn bypass_addresses(
|
||||
resolve: Resolve<'_>,
|
||||
addresses: &[Ipv4Addr],
|
||||
hosts: &[String],
|
||||
overlay: &[Ipv4Range],
|
||||
) -> Vec<Ipv4Addr> {
|
||||
let mut all: std::collections::BTreeSet<Ipv4Addr> = addresses.iter().copied().collect();
|
||||
for host in hosts {
|
||||
all.extend(resolve(host));
|
||||
}
|
||||
all.into_iter()
|
||||
.filter(|a| !a.is_loopback() && !a.is_unspecified() && !a.is_multicast())
|
||||
.filter(|a| {
|
||||
!a.is_loopback()
|
||||
&& !a.is_unspecified()
|
||||
&& !a.is_multicast()
|
||||
&& !a.is_link_local()
|
||||
&& !a.is_broadcast()
|
||||
&& !overlay.iter().any(|range| range.contains(*a))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -216,7 +229,7 @@ fn apply_client(
|
||||
let gateway = run(&gateway_script(interface))?;
|
||||
let (index, hop) = parse_gateway(&gateway)
|
||||
.ok_or_else(|| format!("cannot read the default gateway from `{}`", gateway.trim()))?;
|
||||
let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts);
|
||||
let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay);
|
||||
run(&bypass_script(index, hop, &addresses))?;
|
||||
if let Err(why) = run(&halves_script(interface)) {
|
||||
// Do not leave a half-installed set: bypass routes alone are harmless
|
||||
@@ -407,6 +420,7 @@ mod tests {
|
||||
overlay: vec![range()],
|
||||
bypass: vec![Ipv4Addr::new(138, 201, 61, 182)],
|
||||
bypass_hosts: vec!["relay.example".into()],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,8 +450,10 @@ mod tests {
|
||||
assert!(script.contains("-InterfaceIndex 12 -NextHop '192.168.1.1'"));
|
||||
assert!(script.contains("-RouteMetric 7373"));
|
||||
assert!(script.contains("-PolicyStore ActiveStore"));
|
||||
// Stale marked routes go first, and only /32 ones with our metric.
|
||||
assert!(script.find("Remove-NetRoute").unwrap() < script.find("New-NetRoute").unwrap());
|
||||
// Install missing routes before pruning stale entries. Existing paths
|
||||
// continue carrying the tunnel throughout another network's update.
|
||||
assert!(script.find("New-NetRoute").unwrap() < script.find("Remove-NetRoute").unwrap());
|
||||
assert!(script.contains("$keep -notcontains $_.DestinationPrefix"));
|
||||
assert!(script.contains("RouteMetric -eq 7373"));
|
||||
assert!(script.contains("EndsWith('/32')"));
|
||||
}
|
||||
@@ -445,6 +461,10 @@ mod tests {
|
||||
#[test]
|
||||
fn the_halves_go_through_the_overlay_and_ipv6_is_blackholed() {
|
||||
let script = halves_script("tsun0");
|
||||
assert!(
|
||||
!script.contains("Remove-NetRoute"),
|
||||
"reapplying must keep existing split defaults: {script}"
|
||||
);
|
||||
assert!(script.contains("'0.0.0.0/1', '128.0.0.0/1'"));
|
||||
assert!(script.contains("-InterfaceAlias $alias -NextHop '0.0.0.0'"));
|
||||
assert!(script.contains("'::/1', '8000::/1'"));
|
||||
@@ -472,6 +492,7 @@ mod tests {
|
||||
Ipv4Addr::UNSPECIFIED,
|
||||
],
|
||||
&["relay.example".into(), "gone.example".into()],
|
||||
&[],
|
||||
);
|
||||
assert_eq!(
|
||||
all,
|
||||
@@ -504,12 +525,36 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_dns_cannot_install_a_host_route_over_either_overlay() {
|
||||
let mut plan = client_plan();
|
||||
plan.overlay.push("10.99.0.0/24".parse().unwrap());
|
||||
let resolve = |_: &str| {
|
||||
["10.13.37.4", "10.99.0.6", "9.9.9.9"]
|
||||
.map(|ip| ip.parse().unwrap())
|
||||
.to_vec()
|
||||
};
|
||||
let calls = RefCell::new(Vec::new());
|
||||
let run = |script: &str| {
|
||||
calls.borrow_mut().push(script.to_string());
|
||||
Ok("12 192.168.1.1".to_string())
|
||||
};
|
||||
apply_client(&run, &resolve, &plan).unwrap();
|
||||
let calls = calls.borrow();
|
||||
let bypass = calls
|
||||
.iter()
|
||||
.find(|c| c.contains("-RouteMetric 7373"))
|
||||
.unwrap();
|
||||
assert!(bypass.contains("'9.9.9.9'") && bypass.contains("'138.201.61.182'"));
|
||||
assert!(!bypass.contains("'10.13.37.4'") && !bypass.contains("'10.99.0.6'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_goes_through_the_overlay_when_the_bypass_cannot_be_written() {
|
||||
let run = |script: &str| -> Result<String, String> {
|
||||
if script.contains("Select-Object -First 1") {
|
||||
Ok("12 192.168.1.1".to_string())
|
||||
} else if script.contains("-RouteMetric 7373") && script.contains("foreach ($ip") {
|
||||
} else if script.contains("-RouteMetric 7373") && script.contains("New-NetRoute") {
|
||||
Err("Access is denied".to_string())
|
||||
} else {
|
||||
assert!(!script.contains("-NextHop '0.0.0.0'"), "{script}");
|
||||
|
||||
@@ -35,7 +35,7 @@ use super::hostrules::{
|
||||
RuleOutcome, offer_detail,
|
||||
};
|
||||
use super::packet::IpHeader;
|
||||
use super::router::{Route, RoutingTable};
|
||||
use super::router::{PacketSource, Route, RoutingTable};
|
||||
use super::tun::{TunDevice, TunFactory, TunRequest};
|
||||
use super::{Cidr, OverlayError};
|
||||
|
||||
@@ -153,9 +153,7 @@ pub struct Interface {
|
||||
routes: Arc<RoutingTable>,
|
||||
carrier: Arc<dyn PacketCarrier>,
|
||||
tally: Arc<Tally>,
|
||||
/// What was last applied to the host, so an unchanged table is not
|
||||
/// re-applied on every pass.
|
||||
applied: std::sync::Mutex<Vec<Cidr>>,
|
||||
addresses: std::sync::Mutex<AddressState>,
|
||||
task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
vip_task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
sync_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
@@ -171,6 +169,13 @@ pub struct Interface {
|
||||
underlay: std::sync::Mutex<std::collections::HashMap<NetworkId, Underlay>>,
|
||||
}
|
||||
|
||||
/// Addresses and subnet routes are applied together. A partial change
|
||||
/// invalidates the cached plan until the whole interface reconciles again.
|
||||
struct AddressState {
|
||||
applied: Option<Vec<Cidr>>,
|
||||
last_error: Option<String>,
|
||||
}
|
||||
|
||||
/// Underlay destinations one network's runtime currently depends on.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
struct Underlay {
|
||||
@@ -231,6 +236,7 @@ impl Interface {
|
||||
let tally = Arc::new(Tally::default());
|
||||
|
||||
let vip_task = {
|
||||
let factory = Arc::clone(&factory);
|
||||
let routes = Arc::clone(&routes);
|
||||
let carrier = Arc::clone(&carrier);
|
||||
tokio::spawn(async move {
|
||||
@@ -242,7 +248,10 @@ impl Interface {
|
||||
_=interval.tick()=>{
|
||||
let (probes,jobs)=routes.vips.tick(routes.vips.check_capacity().saturating_sub(checks.len()));
|
||||
for (route,packet) in probes {carrier.carry(route,packet);}
|
||||
for job in jobs {checks.spawn(job.run());}
|
||||
for job in jobs {
|
||||
let factory = Arc::clone(&factory);
|
||||
checks.spawn(job.run(move |socket, source| factory.bind_overlay_socket(socket, source)));
|
||||
}
|
||||
},
|
||||
Some(result)=checks.join_next(),if !checks.is_empty()=>{
|
||||
if let Ok((job,ok))=result {routes.vips.checked(job,ok);}
|
||||
@@ -332,7 +341,10 @@ impl Interface {
|
||||
routes,
|
||||
carrier,
|
||||
tally,
|
||||
applied: std::sync::Mutex::new(Vec::new()),
|
||||
addresses: std::sync::Mutex::new(AddressState {
|
||||
applied: Some(Vec::new()),
|
||||
last_error: None,
|
||||
}),
|
||||
task: std::sync::Mutex::new(Some(task)),
|
||||
vip_task: std::sync::Mutex::new(Some(vip_task)),
|
||||
sync_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
@@ -415,7 +427,10 @@ impl Interface {
|
||||
.collect();
|
||||
ranges.sort_by_key(|range| (range.base, range.prefix_len));
|
||||
ranges.dedup();
|
||||
let client = self.routes.exit_via().is_some();
|
||||
let (client, client_source) = self.routes.exit_client();
|
||||
#[cfg(windows)]
|
||||
self.device
|
||||
.set_exit_source(&self.wanted_addresses(), client_source);
|
||||
let overlay = self.routes.overlay_ranges();
|
||||
let (bypass, bypass_hosts) = if client && exit.needs_bypass() {
|
||||
self.underlay_targets(&overlay)
|
||||
@@ -426,6 +441,7 @@ impl Interface {
|
||||
interface: self.name.clone(),
|
||||
offer: ranges,
|
||||
client,
|
||||
client_source,
|
||||
overlay,
|
||||
bypass,
|
||||
bypass_hosts,
|
||||
@@ -508,6 +524,14 @@ impl Interface {
|
||||
state.report = Some(report);
|
||||
}
|
||||
|
||||
/// Whether the host routes its own transport by destination.
|
||||
pub(crate) fn needs_underlay_targets(&self) -> bool {
|
||||
self.host_rules
|
||||
.as_ref()
|
||||
.and_then(|rules| rules.exit_rules())
|
||||
.is_some_and(|exit| exit.needs_bypass())
|
||||
}
|
||||
|
||||
/// Tells the interface where a network's runtime reaches peers and
|
||||
/// relays outside the overlay. When the host needs those kept out of the
|
||||
/// exit node's default route and the set changed, the rules follow.
|
||||
@@ -532,13 +556,7 @@ impl Interface {
|
||||
map.insert(network, new.clone()) != Some(new)
|
||||
}
|
||||
};
|
||||
let needed = changed
|
||||
&& self.routes.exit_via().is_some()
|
||||
&& self
|
||||
.host_rules
|
||||
.as_ref()
|
||||
.and_then(|rules| rules.exit_rules())
|
||||
.is_some_and(|exit| exit.needs_bypass());
|
||||
let needed = changed && self.routes.exit_via().is_some() && self.needs_underlay_targets();
|
||||
if needed {
|
||||
self.sync_exit_rules().await;
|
||||
}
|
||||
@@ -695,13 +713,13 @@ impl Interface {
|
||||
let _guard = self.sync_lock.lock().await;
|
||||
let wanted = self.wanted_addresses();
|
||||
{
|
||||
let applied = match self.applied.lock() {
|
||||
Ok(guard) => guard.clone(),
|
||||
Err(poisoned) => poisoned.into_inner().clone(),
|
||||
};
|
||||
if applied == wanted {
|
||||
let mut addresses = self.addresses.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if addresses.applied.as_ref() == Some(&wanted) {
|
||||
return Ok(());
|
||||
}
|
||||
// A failed or cancelled reconfiguration can leave some aliases or
|
||||
// routes installed. Even a return to the previous plan must retry.
|
||||
addresses.applied = None;
|
||||
}
|
||||
|
||||
// Every address this agent holds, in every network it is in. The
|
||||
@@ -712,12 +730,25 @@ impl Interface {
|
||||
addresses: wanted.clone(),
|
||||
mtu: self.mtu,
|
||||
};
|
||||
self.factory.reconfigure(request).await?;
|
||||
match self.applied.lock() {
|
||||
Ok(mut guard) => *guard = wanted,
|
||||
Err(poisoned) => *poisoned.into_inner() = wanted,
|
||||
let result = self.factory.reconfigure(request).await;
|
||||
let mut addresses = self.addresses.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match &result {
|
||||
Ok(()) => {
|
||||
addresses.applied = Some(wanted);
|
||||
addresses.last_error = None;
|
||||
}
|
||||
Err(err) => addresses.last_error = Some(format!("{}: {err}", self.name)),
|
||||
}
|
||||
Ok(())
|
||||
result
|
||||
}
|
||||
|
||||
/// Last error applying the shared interface's addresses and subnet routes.
|
||||
pub fn address_error(&self) -> Option<String> {
|
||||
self.addresses
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.last_error
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The interface name the operating system gave.
|
||||
@@ -805,12 +836,19 @@ impl Interface {
|
||||
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(Rejected::WrongFamily);
|
||||
};
|
||||
if !self.routes.may_send_from(network, peer, source) {
|
||||
let Some(origin) = self.routes.packet_source(network, peer, source) else {
|
||||
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(Rejected::WrongSource);
|
||||
}
|
||||
let broadcast = match header.destination() {
|
||||
IpAddr::V4(destination) if self.routes.is_broadcast(destination) => {
|
||||
};
|
||||
let broadcast = match (origin, header.destination()) {
|
||||
(PacketSource::ExitReply { local: Some(local) }, IpAddr::V4(destination))
|
||||
if destination == local =>
|
||||
{
|
||||
false
|
||||
}
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.is_broadcast(destination) =>
|
||||
{
|
||||
if !super::broadcast::valid_udp(&packet)
|
||||
|| !self.routes.accepts_broadcast(network, peer, destination)
|
||||
{
|
||||
@@ -819,12 +857,10 @@ impl Interface {
|
||||
}
|
||||
true
|
||||
}
|
||||
IpAddr::V4(destination) if self.routes.is_local_destination(network, destination) => {
|
||||
false
|
||||
}
|
||||
// This agent is an exit node of this network: a member's packet
|
||||
// for the internet goes to the host, which masquerades it.
|
||||
IpAddr::V4(destination) if self.routes.accepts_exit_traffic(network, destination) => {
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.is_local_destination(network, destination)
|
||||
|| self.routes.accepts_exit_traffic(network, destination) =>
|
||||
{
|
||||
false
|
||||
}
|
||||
_ => {
|
||||
@@ -1239,6 +1275,83 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_a_network_after_partial_provisioning_removes_its_alias() {
|
||||
#[derive(Debug, Default)]
|
||||
struct PartialFactory {
|
||||
devices: MemoryTunFactory,
|
||||
addresses: std::sync::Mutex<Vec<Cidr>>,
|
||||
}
|
||||
|
||||
impl TunFactory for PartialFactory {
|
||||
fn name(&self) -> &str {
|
||||
"partial"
|
||||
}
|
||||
|
||||
fn on_host(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn create<'a>(
|
||||
&'a self,
|
||||
request: TunRequest,
|
||||
) -> crate::BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
|
||||
self.devices.create(request)
|
||||
}
|
||||
|
||||
fn reconfigure<'a>(
|
||||
&'a self,
|
||||
request: TunRequest,
|
||||
) -> crate::BoxFuture<'a, Result<(), OverlayError>> {
|
||||
Box::pin(async move {
|
||||
let mut host = self.addresses.lock().unwrap();
|
||||
*host = request.addresses;
|
||||
if !host.is_empty() {
|
||||
return Err(OverlayError::Unavailable("subnet route failed".into()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let routes = Arc::new(RoutingTable::new());
|
||||
let network = network("partial");
|
||||
routes
|
||||
.set_network(
|
||||
network,
|
||||
NetworkRoutes {
|
||||
local: Some(addr(1)),
|
||||
range: Some("10.13.37.0/24".parse().unwrap()),
|
||||
..NetworkRoutes::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let factory = Arc::new(PartialFactory::default());
|
||||
let interface = Interface::start(
|
||||
factory.clone(),
|
||||
"tsunpartial",
|
||||
1280,
|
||||
routes.clone(),
|
||||
Arc::new(Recorder::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(interface.address_error().is_none());
|
||||
assert!(interface.sync_addresses().await.is_err());
|
||||
assert!(
|
||||
interface
|
||||
.address_error()
|
||||
.unwrap()
|
||||
.contains("subnet route failed")
|
||||
);
|
||||
assert_eq!(factory.addresses.lock().unwrap().len(), 1);
|
||||
routes.remove_network(network);
|
||||
interface.sync_addresses().await.unwrap();
|
||||
assert!(interface.address_error().is_none());
|
||||
assert!(factory.addresses.lock().unwrap().is_empty());
|
||||
interface.remove().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_wanted_addresses_follow_the_table() {
|
||||
let (interface, _device, routes, _carrier, id) = interface(false).await;
|
||||
@@ -1472,6 +1585,47 @@ mod tests {
|
||||
assert_eq!(interface.counters().received, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_exit_reply_must_terminate_locally_even_while_this_agent_offers_forwarding() {
|
||||
use super::super::broadcast::BroadcastPolicy;
|
||||
let (interface, device, routes, _, id) = interface(false).await;
|
||||
routes.set_exit(
|
||||
id,
|
||||
ExitPolicy {
|
||||
offer: true,
|
||||
via: Some(peer(2)),
|
||||
},
|
||||
);
|
||||
routes.set_broadcast(
|
||||
id,
|
||||
BroadcastPolicy {
|
||||
enabled: true,
|
||||
peers: [peer(2)].into_iter().collect(),
|
||||
},
|
||||
);
|
||||
|
||||
let udp = [0, 1, 0, 2, 0, 8, 0, 0];
|
||||
for destination in [Ipv4Addr::new(1, 1, 1, 1), Ipv4Addr::BROADCAST] {
|
||||
assert_eq!(
|
||||
interface
|
||||
.deliver(id, peer(2), ipv4(INTERNET, destination, &udp))
|
||||
.await,
|
||||
Err(Rejected::WrongDestination)
|
||||
);
|
||||
}
|
||||
assert_eq!(interface.counters().received, 0);
|
||||
|
||||
// The same peer can still return internet traffic to us, and can
|
||||
// originate its own ordinary packets under the network's offer.
|
||||
for packet in [ipv4(INTERNET, addr(1), &udp), ipv4(addr(2), INTERNET, &udp)] {
|
||||
interface
|
||||
.deliver(id, peer(2), packet.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(device.pop_to_os().await.unwrap(), packet);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_exit_node_hands_a_members_internet_packet_to_the_host_only_while_offering() {
|
||||
let (interface, device, routes, _carrier, id) = interface(false).await;
|
||||
@@ -1572,6 +1726,19 @@ mod tests {
|
||||
vec![Ipv4Addr::new(5, 6, 7, 8)]
|
||||
);
|
||||
|
||||
let second = network("second underlay");
|
||||
let second_path = Ipv4Addr::new(203, 0, 113, 10);
|
||||
interface.set_underlay(second, [second_path], []).await;
|
||||
assert_eq!(
|
||||
rules.exit().installed().unwrap().bypass,
|
||||
[Ipv4Addr::new(5, 6, 7, 8), second_path]
|
||||
);
|
||||
interface.set_underlay(second, [], []).await;
|
||||
assert_eq!(
|
||||
rules.exit().installed().unwrap().bypass,
|
||||
[Ipv4Addr::new(5, 6, 7, 8)]
|
||||
);
|
||||
|
||||
// Not using an exit node: nothing to keep direct.
|
||||
routes.set_exit(id, Default::default());
|
||||
interface.sync_exit_rules().await;
|
||||
|
||||
@@ -46,6 +46,7 @@ pub mod interface;
|
||||
pub mod packet;
|
||||
pub mod provision;
|
||||
pub mod router;
|
||||
pub mod source;
|
||||
pub mod tun;
|
||||
|
||||
pub use config::{Cidr, DEFAULT_INTERFACE_PREFIX, MAX_INTERFACE_NAME_LEN, interface_name};
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||
|
||||
pub use crate::vip::packet::{Reassembly as Ipv4Reassembly, fragments as fragment_ipv4};
|
||||
|
||||
/// The addresses of an IP packet, as far as routing cares.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum IpHeader {
|
||||
|
||||
@@ -76,7 +76,9 @@ enum Command {
|
||||
DelBroadcastRoute(String, Reply<()>),
|
||||
/// Send the host's default traffic through this interface, except what
|
||||
/// this user id sends.
|
||||
SetExitClient(String, u32, Reply<()>),
|
||||
SetExitClient(String, u32, Option<Ipv4Addr>, Reply<()>),
|
||||
/// Replace only the default route on an already protected interface.
|
||||
UpdateExitSource(String, Option<Ipv4Addr>, Reply<()>),
|
||||
/// Take those routing rules away again.
|
||||
ClearExitClient(Reply<()>),
|
||||
/// Stop the thread.
|
||||
@@ -213,10 +215,25 @@ impl RouteHandle {
|
||||
|
||||
/// Sends the host's default traffic through `interface`, except what the
|
||||
/// user id `uid` sends. Replaces what an earlier call set up.
|
||||
pub(crate) fn set_exit_client(&self, interface: &str, uid: u32) -> Result<(), OverlayError> {
|
||||
pub(crate) fn set_exit_client(
|
||||
&self,
|
||||
interface: &str,
|
||||
uid: u32,
|
||||
source: Option<Ipv4Addr>,
|
||||
) -> Result<(), OverlayError> {
|
||||
let interface = interface.to_string();
|
||||
call_thread(&self.commands, |reply| {
|
||||
Command::SetExitClient(interface, uid, reply)
|
||||
Command::SetExitClient(interface, uid, source, reply)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn update_exit_source(
|
||||
&self,
|
||||
interface: &str,
|
||||
source: Option<Ipv4Addr>,
|
||||
) -> Result<(), OverlayError> {
|
||||
call_thread(&self.commands, |reply| {
|
||||
Command::UpdateExitSource(interface.to_string(), source, reply)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -346,7 +363,8 @@ fn netlink_thread(requests: mpsc::Receiver<Command>) {
|
||||
| Command::Configure(_, reply)
|
||||
| Command::SetBroadcastRoute(_, _, reply)
|
||||
| Command::DelBroadcastRoute(_, reply)
|
||||
| Command::SetExitClient(_, _, reply) => {
|
||||
| Command::SetExitClient(_, _, _, reply)
|
||||
| Command::UpdateExitSource(_, _, reply) => {
|
||||
let _ = reply.send(Err(OverlayError::Unavailable(message)));
|
||||
}
|
||||
Command::ClearExitClient(reply) => {
|
||||
@@ -398,9 +416,19 @@ fn netlink_thread(requests: mpsc::Receiver<Command>) {
|
||||
});
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
Command::SetExitClient(name, uid, reply) => {
|
||||
Command::SetExitClient(name, uid, source, reply) => {
|
||||
let result = NetAdmin::acquire().and_then(|guard| {
|
||||
let result = runtime.block_on(set_exit_client(&name, uid));
|
||||
let result = runtime.block_on(set_exit_client(&name, uid, source));
|
||||
drop(guard);
|
||||
result
|
||||
});
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
Command::UpdateExitSource(name, source, reply) => {
|
||||
let result = NetAdmin::acquire().and_then(|guard| {
|
||||
let result = runtime.block_on(with_netlink(|handle| async move {
|
||||
replace_exit_default(&handle, &name, source).await
|
||||
}));
|
||||
drop(guard);
|
||||
result
|
||||
});
|
||||
@@ -704,13 +732,19 @@ fn is_exit_rule(rule: &RuleMessage) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn exit_default_route(index: Option<u32>) -> rtnetlink::packet_route::route::RouteMessage {
|
||||
fn exit_default_route(
|
||||
index: Option<u32>,
|
||||
source: Option<Ipv4Addr>,
|
||||
) -> rtnetlink::packet_route::route::RouteMessage {
|
||||
let mut builder = RouteMessageBuilder::<Ipv4Addr>::new()
|
||||
.destination_prefix(Ipv4Addr::UNSPECIFIED, 0)
|
||||
.table_id(EXIT_TABLE);
|
||||
if let Some(index) = index {
|
||||
builder = builder.output_interface(index).scope(RouteScope::Link);
|
||||
}
|
||||
if let Some(source) = source {
|
||||
builder = builder.pref_source(source);
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
@@ -772,7 +806,12 @@ async fn remove_exit_rules(
|
||||
|
||||
async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayError> {
|
||||
remove_exit_rules(handle, IpVersion::V4).await?;
|
||||
match handle.route().del(exit_default_route(None)).execute().await {
|
||||
match handle
|
||||
.route()
|
||||
.del(exit_default_route(None, None))
|
||||
.execute()
|
||||
.await
|
||||
{
|
||||
Ok(()) => {}
|
||||
// "No such process": no such route, which is the goal.
|
||||
Err(err) if err.to_string().contains("No such") => {}
|
||||
@@ -797,10 +836,32 @@ async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayErr
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the default route atomically when the selected overlay address changes.
|
||||
async fn replace_exit_default(
|
||||
handle: &rtnetlink::Handle,
|
||||
name: &str,
|
||||
source: Option<Ipv4Addr>,
|
||||
) -> Result<(), OverlayError> {
|
||||
let index = link_index(handle, name).await.ok_or_else(|| {
|
||||
OverlayError::Unavailable(format!(
|
||||
"interface `{name}` disappeared before the exit node route could be added"
|
||||
))
|
||||
})?;
|
||||
handle
|
||||
.route()
|
||||
.add(exit_default_route(Some(index), source))
|
||||
.replace()
|
||||
.execute()
|
||||
.await
|
||||
.map_err(|err| {
|
||||
OverlayError::Unavailable(format!("cannot set the exit node default route: {err}"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets up the using side of an exit node.
|
||||
///
|
||||
/// ```text
|
||||
/// ip route replace default dev <if> table 0x7473
|
||||
/// ip route replace default dev <if> src <selected overlay address> table 0x7473
|
||||
/// ip rule add priority 5205 fwmark 0x40000000/0x40000000 lookup main
|
||||
/// ip rule add priority 5206 uidrange <uid>-<uid> lookup main
|
||||
/// ip rule add priority 5290 lookup main suppress_prefixlength 0
|
||||
@@ -813,24 +874,17 @@ async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayErr
|
||||
/// What an earlier call left is removed first, so repeating it is safe, and
|
||||
/// the rules go in last, so a failure part way never leaves a rule that
|
||||
/// sends traffic to a table with no route in it.
|
||||
async fn set_exit_client(name: &str, uid: u32) -> Result<(), OverlayError> {
|
||||
async fn set_exit_client(
|
||||
name: &str,
|
||||
uid: u32,
|
||||
source: Option<Ipv4Addr>,
|
||||
) -> Result<(), OverlayError> {
|
||||
with_netlink(|handle| async move {
|
||||
let index = link_index(&handle, name).await.ok_or_else(|| {
|
||||
OverlayError::Unavailable(format!(
|
||||
"interface `{name}` disappeared before the exit node routes could be added"
|
||||
))
|
||||
})?;
|
||||
remove_exit_client(&handle).await?;
|
||||
let fail = |what: &str, err: rtnetlink::Error| {
|
||||
OverlayError::Unavailable(format!("cannot add the exit node {what}: {err}"))
|
||||
};
|
||||
handle
|
||||
.route()
|
||||
.add(exit_default_route(Some(index)))
|
||||
.replace()
|
||||
.execute()
|
||||
.await
|
||||
.map_err(|err| fail("default route", err))?;
|
||||
replace_exit_default(&handle, name, source).await?;
|
||||
|
||||
add_mark_bypass(&handle, false).await?;
|
||||
|
||||
@@ -1190,13 +1244,17 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_default_route_of_the_exit_table_names_the_table_and_the_interface() {
|
||||
let route = exit_default_route(Some(7));
|
||||
let source = Ipv4Addr::new(10, 99, 0, 1);
|
||||
let route = exit_default_route(Some(7), Some(source));
|
||||
assert_eq!(route.header.destination_prefix_length, 0);
|
||||
let debug = format!("{route:?}");
|
||||
assert!(debug.contains(&format!("Table({EXIT_TABLE})")), "{debug}");
|
||||
assert!(debug.contains("Oif(7)"), "{debug}");
|
||||
assert!(route.attributes.contains(
|
||||
&rtnetlink::packet_route::route::RouteAttribute::PrefSource(source.into())
|
||||
));
|
||||
// Deleting names no interface, so it matches whatever it was added on.
|
||||
assert!(!format!("{:?}", exit_default_route(None)).contains("Oif"));
|
||||
assert!(!format!("{:?}", exit_default_route(None, None)).contains("Oif"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -39,7 +39,8 @@
|
||||
//! `getifaddrs`. An interface is matched by its real `utunN` name, which only
|
||||
//! matters on reconfiguration: the first create always makes a fresh device.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
use netdev::ipnet::IpNet;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::BoxFuture;
|
||||
@@ -115,7 +116,7 @@ impl InterfaceProvisioner for UtunProvisioner {
|
||||
if self.is_ours(&plan.name) {
|
||||
let current = observe(&plan.name).await;
|
||||
let changes = plan_changes(¤t, plan, true)?;
|
||||
configure(&plan.name, &changes).await?;
|
||||
configure(&plan.name, &changes, &plan.addresses).await?;
|
||||
return Ok(Provisioned {
|
||||
changes,
|
||||
device: None,
|
||||
@@ -136,7 +137,7 @@ impl InterfaceProvisioner for UtunProvisioner {
|
||||
// A failure here leaves an interface that exists but cannot carry
|
||||
// traffic. Drop the device so the utun closes, and report, rather
|
||||
// than leave a trap behind.
|
||||
if let Err(err) = configure(&real, &changes).await {
|
||||
if let Err(err) = configure(&real, &changes, &plan.addresses).await {
|
||||
drop(device);
|
||||
return Err(err);
|
||||
}
|
||||
@@ -225,28 +226,25 @@ async fn observe(name: &str) -> InterfaceState {
|
||||
}
|
||||
|
||||
/// Applies MTU, link state, addresses and the on-link routes they imply.
|
||||
async fn configure(name: &str, changes: &super::Changes) -> Result<(), OverlayError> {
|
||||
async fn configure(
|
||||
name: &str,
|
||||
changes: &super::Changes,
|
||||
wanted: &[Cidr],
|
||||
) -> Result<(), OverlayError> {
|
||||
if let Some(mtu) = changes.set_mtu {
|
||||
set_mtu(name, mtu).await?;
|
||||
}
|
||||
for cidr in &changes.remove {
|
||||
// Best effort: an address that is already gone is the outcome wanted.
|
||||
if let Err(err) = address_del(name, *cidr).await {
|
||||
tracing::debug!(interface = %name, %cidr, %err, "could not remove address");
|
||||
}
|
||||
if let Err(err) = route_del(name, *cidr).await {
|
||||
tracing::debug!(interface = %name, %cidr, %err, "could not remove route");
|
||||
let network = subnet(*cidr)?;
|
||||
if !is_host_route(*cidr)
|
||||
&& matches!(subnet_route(network).await?, SubnetRoute::Present { interface, .. } if interface == name)
|
||||
{
|
||||
run("/sbin/route", route_args("delete", name, network)).await?;
|
||||
}
|
||||
address_del(name, *cidr).await?;
|
||||
}
|
||||
for cidr in &changes.add {
|
||||
address_add(name, *cidr).await?;
|
||||
// The subnet route makes the whole overlay range reach the interface;
|
||||
// a point-to-point utun does not install one from the address alone. A
|
||||
// host address (/32 or /128) needs none. Best effort: a route that is
|
||||
// already there is the outcome wanted.
|
||||
if let Err(err) = route_add(name, *cidr).await {
|
||||
tracing::debug!(interface = %name, %cidr, %err, "could not add route");
|
||||
}
|
||||
}
|
||||
if changes.bring_up {
|
||||
// Best effort: a utun with a descriptor open is up already, and a
|
||||
@@ -255,31 +253,22 @@ async fn configure(name: &str, changes: &super::Changes) -> Result<(), OverlayEr
|
||||
tracing::debug!(interface = %name, %err, "could not enable the interface");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The network address of a CIDR, with the host bits cleared.
|
||||
fn network_of(cidr: Cidr) -> IpAddr {
|
||||
match cidr.addr {
|
||||
IpAddr::V4(addr) => {
|
||||
let bits = u32::from(addr);
|
||||
let mask = if cidr.prefix_len == 0 {
|
||||
0
|
||||
} else {
|
||||
u32::MAX << (32 - u32::from(cidr.prefix_len))
|
||||
};
|
||||
IpAddr::V4(Ipv4Addr::from(bits & mask))
|
||||
}
|
||||
IpAddr::V6(addr) => {
|
||||
let bits = u128::from(addr);
|
||||
let mask = if cidr.prefix_len == 0 {
|
||||
0
|
||||
} else {
|
||||
u128::MAX << (128 - u32::from(cidr.prefix_len))
|
||||
};
|
||||
IpAddr::V6(Ipv6Addr::from(bits & mask))
|
||||
// An alias may already be present after a partial reconcile, or its old
|
||||
// subnet route may still select the first alias on this utun.
|
||||
let mut result = Ok(());
|
||||
for &cidr in wanted {
|
||||
if !is_host_route(cidr) {
|
||||
// Finish the other networks even when one subnet conflicts.
|
||||
let update = ensure_subnet_route(name, subnet(cidr)?).await;
|
||||
result = result.and(update);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn subnet(cidr: Cidr) -> Result<IpNet, OverlayError> {
|
||||
IpNet::new(cidr.addr, cidr.prefix_len)
|
||||
.map_err(|err| OverlayError::Unavailable(format!("invalid overlay prefix {cidr}: {err}")))
|
||||
}
|
||||
|
||||
/// Whether a CIDR is a single host address, which needs no subnet route.
|
||||
@@ -326,40 +315,26 @@ fn address_del_args(name: &str, cidr: Cidr) -> Vec<String> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The `route` arguments that point a CIDR's subnet at the interface.
|
||||
fn route_add_args(name: &str, cidr: Cidr) -> Vec<String> {
|
||||
let family = match cidr.addr {
|
||||
fn route_args(command: &str, name: &str, subnet: IpNet) -> Vec<String> {
|
||||
let family = match subnet.addr() {
|
||||
IpAddr::V4(_) => "-inet",
|
||||
IpAddr::V6(_) => "-inet6",
|
||||
};
|
||||
vec![
|
||||
"-q".into(),
|
||||
let mut args = vec![
|
||||
if command == "get" { "-v" } else { "-q" }.into(),
|
||||
"-n".into(),
|
||||
"add".into(),
|
||||
command.into(),
|
||||
family.into(),
|
||||
"-net".into(),
|
||||
format!("{}/{}", network_of(cidr), cidr.prefix_len),
|
||||
"-interface".into(),
|
||||
name.into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The `route` arguments that remove that subnet route.
|
||||
fn route_del_args(name: &str, cidr: Cidr) -> Vec<String> {
|
||||
let family = match cidr.addr {
|
||||
IpAddr::V4(_) => "-inet",
|
||||
IpAddr::V6(_) => "-inet6",
|
||||
};
|
||||
vec![
|
||||
"-q".into(),
|
||||
"-n".into(),
|
||||
"delete".into(),
|
||||
family.into(),
|
||||
"-net".into(),
|
||||
format!("{}/{}", network_of(cidr), cidr.prefix_len),
|
||||
"-interface".into(),
|
||||
name.into(),
|
||||
]
|
||||
subnet.trunc().to_string(),
|
||||
];
|
||||
if command != "get" {
|
||||
args.extend(["-interface".into(), name.into()]);
|
||||
}
|
||||
if matches!(command, "add" | "change") {
|
||||
args.extend(["-ifa".into(), subnet.addr().to_string()]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
async fn address_add(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
|
||||
@@ -370,18 +345,92 @@ async fn address_del(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
|
||||
ifconfig(address_del_args(name, cidr)).await
|
||||
}
|
||||
|
||||
async fn route_add(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
|
||||
if is_host_route(cidr) {
|
||||
return Ok(());
|
||||
}
|
||||
route(route_add_args(name, cidr)).await
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
enum SubnetRoute {
|
||||
Absent,
|
||||
Present { interface: String, source: IpAddr },
|
||||
}
|
||||
|
||||
async fn route_del(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
|
||||
if is_host_route(cidr) {
|
||||
return Ok(());
|
||||
impl SubnetRoute {
|
||||
fn action(&self, name: &str, subnet: IpNet) -> Result<Option<&'static str>, OverlayError> {
|
||||
match self {
|
||||
Self::Absent => Ok(Some("add")),
|
||||
Self::Present { interface, .. } if interface != name => {
|
||||
Err(OverlayError::Unavailable(format!(
|
||||
"route for {}/{} belongs to {interface}; cannot install it on {name}",
|
||||
subnet.network(),
|
||||
subnet.prefix_len()
|
||||
)))
|
||||
}
|
||||
Self::Present { source, .. } if *source == subnet.addr() => Ok(None),
|
||||
Self::Present { .. } => Ok(Some("change")),
|
||||
}
|
||||
}
|
||||
route(route_del_args(name, cidr)).await
|
||||
}
|
||||
|
||||
// A verbose RTM_GET prints two sockaddr lists (request and reply). In the
|
||||
// kernel's reply IFA follows the variable-width link address of the interface.
|
||||
fn parse_subnet_route(output: &str, subnet: IpNet) -> Result<SubnetRoute, OverlayError> {
|
||||
let invalid =
|
||||
|| OverlayError::Unavailable(format!("could not read the kernel route for {subnet}"));
|
||||
let field = |key: &str| {
|
||||
output
|
||||
.lines()
|
||||
.find_map(|line| line.trim().strip_prefix(key).map(str::trim))
|
||||
};
|
||||
let destination = field("destination:").ok_or_else(invalid)?;
|
||||
let matches = |text: &str, expected: IpAddr| {
|
||||
text.parse::<IpAddr>() == Ok(expected) || (text == "default" && expected.is_unspecified())
|
||||
};
|
||||
if !matches(destination, subnet.network())
|
||||
|| !field("mask:").is_some_and(|mask| matches(mask, subnet.netmask()))
|
||||
{
|
||||
return Ok(SubnetRoute::Absent);
|
||||
}
|
||||
let interface = field("interface:").ok_or_else(invalid)?;
|
||||
let (_, reply) = output.rsplit_once("sockaddrs:").ok_or_else(invalid)?;
|
||||
let (fields, addresses) = reply.trim().split_once('\n').ok_or_else(invalid)?;
|
||||
let after = fields
|
||||
.trim()
|
||||
.trim_matches(['<', '>'])
|
||||
.split(',')
|
||||
.rev()
|
||||
.position(|field| field == "IFA")
|
||||
.ok_or_else(invalid)?;
|
||||
let source = addresses
|
||||
.split_whitespace()
|
||||
.rev()
|
||||
.nth(after)
|
||||
.and_then(|ip| ip.parse().ok())
|
||||
.ok_or_else(invalid)?;
|
||||
Ok(SubnetRoute::Present {
|
||||
interface: interface.into(),
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
async fn subnet_route(subnet: IpNet) -> Result<SubnetRoute, OverlayError> {
|
||||
match run("/sbin/route", route_args("get", "", subnet)).await {
|
||||
Ok(output) => parse_subnet_route(&output, subnet),
|
||||
Err(OverlayError::Unavailable(message)) if message.ends_with("not in table") => {
|
||||
Ok(SubnetRoute::Absent)
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_subnet_route(name: &str, subnet: IpNet) -> Result<(), OverlayError> {
|
||||
if let Some(command) = subnet_route(subnet).await?.action(name, subnet)? {
|
||||
run("/sbin/route", route_args(command, name, subnet)).await?;
|
||||
let observed = subnet_route(subnet).await?;
|
||||
if observed.action(name, subnet)?.is_some() {
|
||||
return Err(OverlayError::Unavailable(format!(
|
||||
"route for {subnet} on {name} did not select source {} (observed {observed:?})",
|
||||
subnet.addr()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_mtu(name: &str, mtu: u32) -> Result<(), OverlayError> {
|
||||
@@ -394,27 +443,26 @@ async fn set_up(name: &str) -> Result<(), OverlayError> {
|
||||
|
||||
/// Runs `/sbin/ifconfig`, turning a non-zero exit into an error with its text.
|
||||
async fn ifconfig(args: Vec<String>) -> Result<(), OverlayError> {
|
||||
run("/sbin/ifconfig", args).await
|
||||
}
|
||||
|
||||
/// Runs `/sbin/route`, turning a non-zero exit into an error with its text.
|
||||
async fn route(args: Vec<String>) -> Result<(), OverlayError> {
|
||||
run("/sbin/route", args).await
|
||||
run("/sbin/ifconfig", args).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Runs a system tool by absolute path, so nothing on `PATH` can stand in for
|
||||
/// it, and turns a non-zero exit into an error carrying what it said.
|
||||
async fn run(program: &'static str, args: Vec<String>) -> Result<(), OverlayError> {
|
||||
async fn run(program: &'static str, args: Vec<String>) -> Result<String, OverlayError> {
|
||||
let display = format!("{program} {}", args.join(" "));
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
std::process::Command::new(program).args(&args).output()
|
||||
std::process::Command::new(program)
|
||||
.env("LC_ALL", "C")
|
||||
.args(&args)
|
||||
.output()
|
||||
})
|
||||
.await
|
||||
.map_err(|err| OverlayError::Other(format!("could not run {display}: {err}")))?
|
||||
.map_err(|err| OverlayError::Unavailable(format!("could not run {display}: {err}")))?;
|
||||
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
// Darwin route can exit successfully after a routing-socket write failed.
|
||||
if output.status.success() && (program != "/sbin/route" || output.stderr.is_empty()) {
|
||||
return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
|
||||
}
|
||||
let message = {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
@@ -439,6 +487,7 @@ mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||
|
||||
fn v4(last: u8, prefix: u8) -> Cidr {
|
||||
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, 13, 37, last)), prefix).unwrap()
|
||||
@@ -476,8 +525,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subnet_route_points_the_masked_network_at_the_interface() {
|
||||
let args = route_add_args("utun5", v4(69, 24));
|
||||
fn a_subnet_route_names_its_own_overlay_source() {
|
||||
let args = route_args("add", "utun5", subnet(v4(69, 24)).unwrap());
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
@@ -488,11 +537,93 @@ mod tests {
|
||||
"-net",
|
||||
"10.13.37.0/24",
|
||||
"-interface",
|
||||
"utun5"
|
||||
"utun5",
|
||||
"-ifa",
|
||||
"10.13.37.69"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_source_is_repaired_only_on_the_owned_interface() {
|
||||
let cidr = subnet(v4(69, 24)).unwrap();
|
||||
let observed = "destination: 10.13.37.0\n mask: 255.255.255.0\n interface: utun5\n\
|
||||
sockaddrs: <DST,GATEWAY,NETMASK,IFP,IFA>\n 10.13.37.0 index: 20 255.255.255.0 index: 20 utun5 10.99.0.2\n";
|
||||
let route = parse_subnet_route(observed, cidr).unwrap();
|
||||
assert_eq!(route.action("utun5", cidr).unwrap(), Some("change"));
|
||||
assert!(route.action("utun9", cidr).is_err());
|
||||
let corrected = observed.replace("10.99.0.2", "10.13.37.69");
|
||||
assert_eq!(
|
||||
parse_subnet_route(&corrected, cidr)
|
||||
.unwrap()
|
||||
.action("utun5", cidr)
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
assert!(parse_subnet_route(&observed.replace(",IFA>", ">"), cidr).is_err());
|
||||
assert!(parse_subnet_route("", cidr).is_err());
|
||||
let broader = observed.replace("255.255.255.0", "255.255.0.0");
|
||||
assert_eq!(
|
||||
parse_subnet_route(&broader, cidr).unwrap(),
|
||||
SubnetRoute::Absent
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires root and creates a temporary macOS utun with two subnet routes"]
|
||||
async fn unbound_sockets_choose_each_networks_source_on_one_real_utun() {
|
||||
let provisioner = UtunProvisioner::new().unwrap();
|
||||
let first = Cidr::new("198.18.251.1".parse().unwrap(), 30).unwrap();
|
||||
let second = Cidr::new("198.19.251.1".parse().unwrap(), 30).unwrap();
|
||||
let created = provisioner
|
||||
.reconcile(&InterfacePlan::new("tsuntest", 1280, vec![first]))
|
||||
.await
|
||||
.unwrap();
|
||||
let device = created.device.unwrap();
|
||||
let plan = InterfacePlan::new(device.name(), 1280, vec![first, second]);
|
||||
let before = netwatch::netmon::State::new().await;
|
||||
provisioner.reconcile(&plan).await.unwrap();
|
||||
let after = netwatch::netmon::State::new().await;
|
||||
assert!(crate::net::only_owned_interface_changed(
|
||||
&before,
|
||||
&after,
|
||||
device.name()
|
||||
));
|
||||
for (peer, expected) in [("198.18.251.2", first), ("198.19.251.2", second)] {
|
||||
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
|
||||
socket
|
||||
.connect((peer.parse::<Ipv4Addr>().unwrap(), 9))
|
||||
.unwrap();
|
||||
assert_eq!(socket.local_addr().unwrap().ip(), expected.addr);
|
||||
}
|
||||
// Simulate a route left by an earlier release, with both aliases still present.
|
||||
let second_subnet = subnet(second).unwrap();
|
||||
let mut stale = route_args("change", device.name(), second_subnet);
|
||||
*stale.last_mut().unwrap() = first.addr.to_string();
|
||||
run("/sbin/route", stale).await.unwrap();
|
||||
assert_eq!(
|
||||
subnet_route(second_subnet)
|
||||
.await
|
||||
.unwrap()
|
||||
.action(device.name(), second_subnet)
|
||||
.unwrap(),
|
||||
Some("change")
|
||||
);
|
||||
provisioner.reconcile(&plan).await.unwrap();
|
||||
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
|
||||
socket.connect(("198.19.251.2", 9)).unwrap();
|
||||
assert_eq!(socket.local_addr().unwrap().ip(), second.addr);
|
||||
provisioner
|
||||
.reconcile(&InterfacePlan::new(device.name(), 1280, vec![first]))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
subnet_route(second_subnet).await.unwrap(),
|
||||
SubnetRoute::Absent
|
||||
);
|
||||
provisioner.remove(device.name()).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_address_installs_no_subnet_route() {
|
||||
assert!(is_host_route(v4(69, 32)));
|
||||
@@ -501,22 +632,6 @@ mod tests {
|
||||
assert!(!is_host_route(v6(1, 64)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_network_address_clears_the_host_bits() {
|
||||
assert_eq!(
|
||||
network_of(v4(69, 24)),
|
||||
IpAddr::V4(Ipv4Addr::new(10, 13, 37, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
network_of(Cidr::new(IpAddr::V4(Ipv4Addr::new(10, 13, 37, 69)), 16).unwrap()),
|
||||
IpAddr::V4(Ipv4Addr::new(10, 13, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
network_of(v6(0x1234, 64)),
|
||||
IpAddr::V6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_local_addresses_are_not_ours_to_manage() {
|
||||
assert!(is_link_local(IpAddr::V6(Ipv6Addr::new(
|
||||
|
||||
@@ -131,10 +131,14 @@ impl InterfaceProvisioner for WintunProvisioner {
|
||||
};
|
||||
|
||||
for cidr in flush.iter().chain(changes.remove.iter()) {
|
||||
// Best effort: an address that is already gone is the outcome
|
||||
// wanted, and refusing to start over one is not worth it.
|
||||
if let Err(err) = address_del(&plan.name, *cidr).await {
|
||||
tracing::debug!(interface = %plan.name, %cidr, %err, "could not remove address");
|
||||
if let Err(err) = address_del(&plan.name, *cidr).await
|
||||
&& observe(&plan.name)
|
||||
.await
|
||||
.addresses
|
||||
.iter()
|
||||
.any(|a| a.addr == cidr.addr)
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,11 +266,12 @@ async fn configure(plan: &InterfacePlan, changes: &super::Changes) -> Result<(),
|
||||
set_mtu(&plan.name, mtu).await?;
|
||||
}
|
||||
for cidr in &changes.add {
|
||||
if let Err(err) = address_add(&plan.name, *cidr).await {
|
||||
let err_str = err.to_string();
|
||||
if !err_str.contains("already exists") && !err_str.contains("0x80071392") {
|
||||
return Err(err);
|
||||
}
|
||||
// An already-installed alias is idempotent, including on localized
|
||||
// Windows. A duplicate on a different adapter cannot satisfy the plan.
|
||||
if let Err(err) = address_add(&plan.name, *cidr).await
|
||||
&& !observe(&plan.name).await.addresses.contains(cidr)
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
if changes.bring_up {
|
||||
@@ -300,6 +305,7 @@ fn address_add_args(name: &str, cidr: Cidr) -> Vec<String> {
|
||||
format!("address={addr}"),
|
||||
format!("mask={}", ipv4_mask(cidr.prefix_len)),
|
||||
"store=active".into(),
|
||||
"skipassource=false".into(),
|
||||
],
|
||||
IpAddr::V6(addr) => vec![
|
||||
"interface".into(),
|
||||
@@ -466,6 +472,70 @@ mod tests {
|
||||
assert!(args.contains(&"name=tsun0".to_string()));
|
||||
assert!(args.contains(&"address=10.13.37.69".to_string()));
|
||||
assert!(args.contains(&"mask=255.255.255.0".to_string()));
|
||||
assert!(args.contains(&"skipassource=false".to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires an elevated Windows host with Wintun"]
|
||||
async fn two_windows_subnets_choose_their_own_source_and_survive_removal() {
|
||||
let addresses = [
|
||||
(
|
||||
Ipv4Addr::new(198, 18, 251, 1),
|
||||
Ipv4Addr::new(198, 18, 251, 2),
|
||||
),
|
||||
(
|
||||
Ipv4Addr::new(198, 19, 251, 1),
|
||||
Ipv4Addr::new(198, 19, 251, 2),
|
||||
),
|
||||
];
|
||||
for iface in netdev::get_interfaces() {
|
||||
for prefix in iface.ipv4 {
|
||||
assert!(
|
||||
addresses.iter().all(|(ip, destination)| {
|
||||
!prefix.contains(ip) && !prefix.contains(destination)
|
||||
}),
|
||||
"test subnets already in use"
|
||||
);
|
||||
}
|
||||
}
|
||||
let adapter = format!("tsun-test-{:08x}", rand::random::<u32>());
|
||||
let provisioner = WintunProvisioner::new().unwrap();
|
||||
let cidrs: Vec<_> = addresses
|
||||
.iter()
|
||||
.map(|(ip, _)| Cidr::new((*ip).into(), 30).unwrap())
|
||||
.collect();
|
||||
let mut device = None;
|
||||
for wanted in [&cidrs[..1], &cidrs[..], &cidrs[1..], &cidrs[..]] {
|
||||
let plan = InterfacePlan::new(&adapter, 1280, wanted.to_vec());
|
||||
let result = provisioner.reconcile(&plan).await.unwrap();
|
||||
if let Some(created) = result.device {
|
||||
assert!(device.replace(created).is_none());
|
||||
}
|
||||
// Allow the Windows address to finish duplicate address detection.
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
let ready = addresses
|
||||
.iter()
|
||||
.filter(|(ip, _)| wanted.iter().any(|c| c.addr == IpAddr::V4(*ip)))
|
||||
.all(|(ip, destination)| {
|
||||
std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
|
||||
.and_then(|socket| {
|
||||
socket.connect((*destination, 9))?;
|
||||
socket.local_addr()
|
||||
})
|
||||
.is_ok_and(|source| source.ip() == IpAddr::V4(*ip))
|
||||
});
|
||||
if ready {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("Windows selected the wrong source");
|
||||
assert_eq!(observe(&adapter).await.addresses, plan.addresses);
|
||||
}
|
||||
provisioner.remove(&adapter).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -40,6 +40,12 @@ pub struct Route {
|
||||
pub peer: EndpointId,
|
||||
}
|
||||
|
||||
/// An internet source is valid only for a reply to our address in the exit's network.
|
||||
pub(super) enum PacketSource {
|
||||
Member,
|
||||
ExitReply { local: Option<Ipv4Addr> },
|
||||
}
|
||||
|
||||
/// A network's exit-node settings, as far as packets are concerned.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct ExitPolicy {
|
||||
@@ -120,7 +126,29 @@ impl RoutingTable {
|
||||
/// interface an address can belong to only one network, and guessing
|
||||
/// which would send somebody's traffic to a stranger.
|
||||
pub fn set_network(&self, network: NetworkId, routes: NetworkRoutes) -> Result<(), RouteError> {
|
||||
self.replace_network(&mut self.write(), network, routes)
|
||||
}
|
||||
|
||||
/// A fresh allocation snapshot cannot change the operator's exit settings.
|
||||
pub(crate) fn update_allocations(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
mut routes: NetworkRoutes,
|
||||
) -> Result<(), RouteError> {
|
||||
let mut networks = self.write();
|
||||
routes.exit = networks
|
||||
.get(&network)
|
||||
.map(|current| current.exit)
|
||||
.unwrap_or_default();
|
||||
self.replace_network(&mut networks, network, routes)
|
||||
}
|
||||
|
||||
fn replace_network(
|
||||
&self,
|
||||
networks: &mut HashMap<NetworkId, NetworkRoutes>,
|
||||
network: NetworkId,
|
||||
routes: NetworkRoutes,
|
||||
) -> Result<(), RouteError> {
|
||||
if let Some(range) = routes.range {
|
||||
for (other, existing) in networks.iter() {
|
||||
if *other == network {
|
||||
@@ -139,9 +167,12 @@ impl RoutingTable {
|
||||
}
|
||||
}
|
||||
}
|
||||
if routes.exit.via.is_some() {
|
||||
clear_other_exits(networks, network);
|
||||
}
|
||||
networks.insert(network, routes);
|
||||
self.broadcast
|
||||
.store(Arc::new(BroadcastTable::build(&networks)));
|
||||
.store(Arc::new(BroadcastTable::build(networks)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -172,8 +203,16 @@ impl RoutingTable {
|
||||
/// A network that has no entry yet (its range is not agreed) takes them
|
||||
/// from [`NetworkRoutes::exit`] when it is added.
|
||||
pub fn set_exit(&self, network: NetworkId, policy: ExitPolicy) {
|
||||
if let Some(routes) = self.write().get_mut(&network) {
|
||||
routes.exit = policy;
|
||||
self.update_exit(network, |current| *current = policy);
|
||||
}
|
||||
|
||||
pub(crate) fn update_exit(&self, network: NetworkId, update: impl FnOnce(&mut ExitPolicy)) {
|
||||
let mut networks = self.write();
|
||||
if let Some(routes) = networks.get_mut(&network) {
|
||||
update(&mut routes.exit);
|
||||
if routes.exit.via.is_some() {
|
||||
clear_other_exits(&mut networks, network);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,20 +280,30 @@ impl RoutingTable {
|
||||
/// internet carries the internet's addresses, so from *that* peer any
|
||||
/// source outside the overlay ranges is accepted.
|
||||
pub fn may_send_from(&self, network: NetworkId, peer: EndpointId, source: Ipv4Addr) -> bool {
|
||||
self.packet_source(network, peer, source).is_some()
|
||||
}
|
||||
|
||||
pub(super) fn packet_source(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
source: Ipv4Addr,
|
||||
) -> Option<PacketSource> {
|
||||
let networks = self.read();
|
||||
let Some(routes) = networks.get(&network) else {
|
||||
return false;
|
||||
};
|
||||
let routes = networks.get(&network)?;
|
||||
if routes
|
||||
.peers
|
||||
.iter()
|
||||
.any(|(address, holder)| *address == source && *holder == peer)
|
||||
{
|
||||
return true;
|
||||
return Some(PacketSource::Member);
|
||||
}
|
||||
routes.exit.via == Some(peer)
|
||||
(exit_via(&networks) == Some((network, peer))
|
||||
&& is_internet_destination(source)
|
||||
&& !in_any_range(&networks, source)
|
||||
&& !in_any_range(&networks, source))
|
||||
.then_some(PacketSource::ExitReply {
|
||||
local: routes.local,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether this agent, as an exit node of `network`, takes a member's
|
||||
@@ -275,12 +324,20 @@ impl RoutingTable {
|
||||
|
||||
/// The network and member this device sends its internet traffic through.
|
||||
///
|
||||
/// One default route, so one answer; if several networks claim one (they
|
||||
/// should not) the lowest network id decides, so two runs agree.
|
||||
/// Choosing another exit replaces the previous one under the table's write lock.
|
||||
pub fn exit_via(&self) -> Option<(NetworkId, EndpointId)> {
|
||||
exit_via(&self.read())
|
||||
}
|
||||
|
||||
/// Whether a default route is selected and the local source valid in that network.
|
||||
pub(crate) fn exit_client(&self) -> (bool, Option<Ipv4Addr>) {
|
||||
let networks = self.read();
|
||||
match exit_via(&networks) {
|
||||
Some((id, _)) => (true, networks.get(&id).and_then(|routes| routes.local)),
|
||||
None => (false, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Networks that offer this agent as an exit node, with the range each
|
||||
/// agreed. A network that has not agreed one yet has nothing to
|
||||
/// masquerade and is left out.
|
||||
@@ -414,12 +471,19 @@ fn in_any_range(networks: &HashMap<NetworkId, NetworkRoutes>, address: Ipv4Addr)
|
||||
.any(|routes| routes.range.is_some_and(|range| range.contains(address)))
|
||||
}
|
||||
|
||||
/// The exit node in use, if any, from the lowest network that names one.
|
||||
fn clear_other_exits(networks: &mut HashMap<NetworkId, NetworkRoutes>, selected: NetworkId) {
|
||||
for (id, routes) in networks {
|
||||
if *id != selected {
|
||||
routes.exit.via = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the selected network can have an exit peer.
|
||||
fn exit_via(networks: &HashMap<NetworkId, NetworkRoutes>) -> Option<(NetworkId, EndpointId)> {
|
||||
networks
|
||||
.iter()
|
||||
.filter_map(|(network, routes)| Some((*network, routes.exit.via?)))
|
||||
.min_by_key(|(network, _)| *network)
|
||||
.find_map(|(network, routes)| Some((*network, routes.exit.via?)))
|
||||
}
|
||||
|
||||
/// Whether two ranges share any address.
|
||||
@@ -736,6 +800,46 @@ mod tests {
|
||||
|
||||
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
|
||||
|
||||
#[test]
|
||||
fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() {
|
||||
let table = RoutingTable::new();
|
||||
let (a, b) = (network("first"), network("second"));
|
||||
let first = with_exit(true, Some(peer(2)));
|
||||
let second = NetworkRoutes {
|
||||
range: Some("10.99.0.0/24".parse().unwrap()),
|
||||
local: Some(Ipv4Addr::new(10, 99, 0, 1)),
|
||||
..Default::default()
|
||||
};
|
||||
table.set_network(a, first.clone()).unwrap();
|
||||
table.set_network(b, second.clone()).unwrap();
|
||||
table.set_exit(
|
||||
b,
|
||||
ExitPolicy {
|
||||
offer: false,
|
||||
via: Some(peer(3)),
|
||||
},
|
||||
);
|
||||
|
||||
table.update_allocations(a, first).unwrap();
|
||||
table.update_allocations(b, second).unwrap();
|
||||
assert_eq!(
|
||||
table.exit_client(),
|
||||
(true, Some(Ipv4Addr::new(10, 99, 0, 1)))
|
||||
);
|
||||
assert_eq!(table.exit_via(), Some((b, peer(3))));
|
||||
assert_eq!(
|
||||
table.exit_settings(a).unwrap().0,
|
||||
ExitPolicy {
|
||||
offer: true,
|
||||
via: None
|
||||
}
|
||||
);
|
||||
table.remove_network(a);
|
||||
assert_eq!(table.exit_via(), Some((b, peer(3))));
|
||||
table.remove_network(b);
|
||||
assert_eq!(table.exit_via(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_an_exit_node_the_internet_has_nowhere_to_go() {
|
||||
let table = RoutingTable::new();
|
||||
@@ -810,7 +914,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_exit_choices_resolve_to_the_lowest_network_id() {
|
||||
fn competing_exit_choices_use_the_same_peer_for_requests_and_replies() {
|
||||
let table = RoutingTable::new();
|
||||
let (a, b) = (network("one"), network("two"));
|
||||
table
|
||||
@@ -829,9 +933,10 @@ mod tests {
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let (chosen, _) = table.exit_via().unwrap();
|
||||
assert_eq!(chosen, a.min(b));
|
||||
assert_eq!(table.route(INTERNET).unwrap().network, a.min(b));
|
||||
assert_eq!(table.exit_via(), Some((b, peer(9))));
|
||||
assert_eq!(table.route(INTERNET).unwrap().network, b);
|
||||
assert!(table.may_send_from(b, peer(9), INTERNET));
|
||||
assert!(!table.may_send_from(a, peer(2), INTERNET));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,787 @@
|
||||
//! Translate host-selected IPv4 aliases at the local packet interface.
|
||||
use super::Cidr;
|
||||
use super::packet::{Ipv4Reassembly, fragment_ipv4};
|
||||
use bytes::Bytes;
|
||||
use smoltcp::wire::{Ipv4Cidr, Ipv4Packet};
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
mod icmp;
|
||||
|
||||
#[cfg(any(all(windows, feature = "tun-device"), test))]
|
||||
pub(crate) mod windows;
|
||||
|
||||
// No mappings are persisted, and a new flow cannot evict a live socket.
|
||||
const MAX_FLOWS: usize = 4096;
|
||||
const MAX_FRAGMENTED: usize = 16;
|
||||
const UDP_IDLE: Duration = Duration::from_secs(120);
|
||||
const TCP_IDLE: Duration = Duration::from_secs(2 * 60 * 60);
|
||||
const ECHO_IDLE: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
struct WireFlow {
|
||||
local: Ipv4Addr,
|
||||
remote: Ipv4Addr,
|
||||
protocol: u8,
|
||||
local_port: u16,
|
||||
remote_port: u16,
|
||||
}
|
||||
|
||||
impl WireFlow {
|
||||
// ICMP errors quote as few as eight transport bytes; the caller validates
|
||||
// the outer packet separately. Echo requests in opposite directions can
|
||||
// have the same identifier without sharing a flow.
|
||||
fn parse(packet: &[u8], outbound: bool) -> Option<Self> {
|
||||
let h = usize::from(*packet.first()? & 15) * 4;
|
||||
if packet[0] >> 4 != 4
|
||||
|| h < 20
|
||||
|| packet.len() < h + 8
|
||||
|| u16::from_be_bytes([packet[6], packet[7]]) & 0x1fff != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let src = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[12..16]).ok()?);
|
||||
let dst = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[16..20]).ok()?);
|
||||
let (local, remote) = if outbound { (src, dst) } else { (dst, src) };
|
||||
let protocol = packet[9];
|
||||
let data = &packet[h..];
|
||||
let (local_port, remote_port) = match protocol {
|
||||
6 | 17 => {
|
||||
let src = u16::from_be_bytes([data[0], data[1]]);
|
||||
let dst = u16::from_be_bytes([data[2], data[3]]);
|
||||
if outbound { (src, dst) } else { (dst, src) }
|
||||
}
|
||||
1 if matches!(data[0], 0 | 8) && data[1] == 0 => {
|
||||
let id = u16::from_be_bytes([data[4], data[5]]);
|
||||
(id, u16::from(outbound != (data[0] == 8)))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(Self {
|
||||
local,
|
||||
remote,
|
||||
protocol,
|
||||
local_port,
|
||||
remote_port,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Binding {
|
||||
host: Ipv4Addr,
|
||||
// A response from an unbound UDP listener can leave Android with the
|
||||
// primary address even though its request targeted a different alias.
|
||||
remote_initiated: bool,
|
||||
expires: Instant,
|
||||
}
|
||||
|
||||
/// How the host chooses a source at the TUN boundary.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SourceMode {
|
||||
/// Android can choose the primary VPN address even for another mesh.
|
||||
Primary,
|
||||
/// Windows chooses the matching subnet for mesh traffic, but may select
|
||||
/// any local alias for a default route.
|
||||
ExitOnly,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Domains {
|
||||
aliases: Vec<Ipv4Cidr>,
|
||||
exit: Option<Ipv4Addr>,
|
||||
mode: SourceMode,
|
||||
}
|
||||
|
||||
impl Domains {
|
||||
fn new(addresses: &[Cidr], exit: Option<Ipv4Addr>, mode: SourceMode) -> Self {
|
||||
let aliases = addresses
|
||||
.iter()
|
||||
.filter_map(|cidr| match cidr.addr {
|
||||
IpAddr::V4(addr) if cidr.prefix_len <= 32 => {
|
||||
Some(Ipv4Cidr::new(addr, cidr.prefix_len))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
aliases,
|
||||
exit,
|
||||
mode,
|
||||
}
|
||||
}
|
||||
|
||||
fn primary(&self) -> Option<Ipv4Addr> {
|
||||
match self.mode {
|
||||
SourceMode::Primary => self.aliases.first().map(Ipv4Cidr::address),
|
||||
SourceMode::ExitOnly => None,
|
||||
}
|
||||
}
|
||||
fn has(&self, addr: Ipv4Addr) -> bool {
|
||||
self.aliases.iter().any(|alias| alias.address() == addr)
|
||||
}
|
||||
fn owner(&self, remote: Ipv4Addr) -> Option<Ipv4Addr> {
|
||||
if remote.is_broadcast()
|
||||
|| remote.is_multicast()
|
||||
|| remote.is_unspecified()
|
||||
|| remote.is_loopback()
|
||||
|| self.has(remote)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if let Some(prefix) = self.aliases.iter().find(|p| p.contains_addr(&remote)) {
|
||||
return (self.mode == SourceMode::Primary && prefix.broadcast() != Some(remote))
|
||||
.then(|| prefix.address());
|
||||
}
|
||||
self.exit
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded flow bindings restore replies to the socket that opened each flow.
|
||||
pub struct SourceFlows {
|
||||
domains: Domains,
|
||||
mtu: u32,
|
||||
flows: HashMap<Ipv4Addr, HashMap<WireFlow, Binding>>,
|
||||
primary_has_translations: bool,
|
||||
last_sweep: Instant,
|
||||
outgoing_parts: HashMap<Ipv4Addr, Ipv4Reassembly>,
|
||||
incoming_parts: HashMap<Ipv4Addr, Ipv4Reassembly>,
|
||||
}
|
||||
|
||||
impl SourceFlows {
|
||||
/// Addresses are in the same order as on the device, primary first where applicable.
|
||||
pub fn new(addresses: &[Cidr], exit: Option<Ipv4Addr>, mtu: u32, mode: SourceMode) -> Self {
|
||||
Self {
|
||||
domains: Domains::new(addresses, exit, mode),
|
||||
mtu,
|
||||
flows: HashMap::new(),
|
||||
primary_has_translations: false,
|
||||
last_sweep: Instant::now(),
|
||||
outgoing_parts: HashMap::new(),
|
||||
incoming_parts: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep live bindings whose host and wire addresses still belong to the same domains.
|
||||
pub fn reconfigure(&mut self, addresses: &[Cidr], exit: Option<Ipv4Addr>, mtu: u32) {
|
||||
self.domains = Domains::new(addresses, exit, self.domains.mode);
|
||||
self.mtu = mtu;
|
||||
self.flows.retain(|_, table| {
|
||||
table.retain(|wire, entry| {
|
||||
self.domains.has(entry.host) && self.domains.owner(wire.remote) == Some(wire.local)
|
||||
});
|
||||
!table.is_empty()
|
||||
});
|
||||
self.refresh_primary();
|
||||
// Outstanding fragments belong to the previous VPN attachment.
|
||||
self.outgoing_parts.clear();
|
||||
self.incoming_parts.clear();
|
||||
}
|
||||
|
||||
fn refresh_primary(&mut self) {
|
||||
if let Some(primary) = self.domains.primary() {
|
||||
self.primary_has_translations = self
|
||||
.flows
|
||||
.get(&primary)
|
||||
.is_some_and(|table| table.values().any(|entry| entry.host != primary));
|
||||
if !self.primary_has_translations {
|
||||
self.flows.remove(&primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Packets read from the host.
|
||||
pub fn outbound(&mut self, packet: Bytes) -> Vec<Bytes> {
|
||||
self.process(packet, true)
|
||||
}
|
||||
|
||||
/// Packets admitted by the mesh and destined for the host.
|
||||
pub fn inbound(&mut self, packet: Bytes) -> Vec<Bytes> {
|
||||
self.process(packet, false)
|
||||
}
|
||||
|
||||
fn process(&mut self, packet: Bytes, outbound: bool) -> Vec<Bytes> {
|
||||
if self.domains.aliases.len() < 2 || packet.first().is_none_or(|byte| byte >> 4 != 4) {
|
||||
return vec![packet];
|
||||
}
|
||||
let Ok(ip) = Ipv4Packet::new_checked(&packet[..]) else {
|
||||
return vec![];
|
||||
};
|
||||
let h = usize::from(ip.header_len());
|
||||
if h < 20 || usize::from(ip.total_len()) != packet.len() {
|
||||
return vec![];
|
||||
}
|
||||
let (local, remote) = if outbound {
|
||||
(ip.src_addr(), ip.dst_addr())
|
||||
} else {
|
||||
(ip.dst_addr(), ip.src_addr())
|
||||
};
|
||||
// ICMP errors can come from a router other than the original peer.
|
||||
let is_icmp = packet[9] == 1;
|
||||
let owner = self.domains.owner(remote);
|
||||
let fragmented = ip.more_frags() || ip.frag_offset() != 0;
|
||||
if self.domains.mode == SourceMode::ExitOnly {
|
||||
// A mesh router can report PMTU for an internet flow whose source
|
||||
// we translated. All other native mesh and forwarded packets pass
|
||||
// directly, including fragments and packets headed to the gateway.
|
||||
let exit_error = !outbound
|
||||
&& Some(local) == self.domains.exit
|
||||
&& is_icmp
|
||||
&& (fragmented || matches!(packet.get(h), Some(3 | 11 | 12)));
|
||||
if !self.domains.has(local) || (owner.is_none() && !exit_error) {
|
||||
return vec![packet];
|
||||
}
|
||||
}
|
||||
if !ip.verify_checksum() {
|
||||
return vec![];
|
||||
}
|
||||
let primary = self.domains.primary();
|
||||
// The kernel already uses the primary address for its own subnet. A
|
||||
// primary change can leave earlier translated sockets draining there.
|
||||
if Some(local) == primary
|
||||
&& (!outbound || owner == primary)
|
||||
&& !self.primary_has_translations
|
||||
{
|
||||
return vec![packet];
|
||||
}
|
||||
if owner.is_none() && !(is_icmp && self.domains.has(local)) {
|
||||
return vec![packet];
|
||||
}
|
||||
if !self.domains.has(local) {
|
||||
// Never translate addresses outside the local host's assignments.
|
||||
return if outbound { vec![] } else { vec![packet] };
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
if now.duration_since(self.last_sweep) >= Duration::from_secs(5) {
|
||||
self.flows.retain(|_, table| {
|
||||
table.retain(|_, entry| now < entry.expires);
|
||||
!table.is_empty()
|
||||
});
|
||||
self.refresh_primary();
|
||||
self.last_sweep = now;
|
||||
}
|
||||
let packet = if fragmented {
|
||||
let parts = if outbound {
|
||||
&mut self.outgoing_parts
|
||||
} else {
|
||||
&mut self.incoming_parts
|
||||
};
|
||||
let key = if outbound {
|
||||
owner.unwrap_or(local)
|
||||
} else {
|
||||
local
|
||||
};
|
||||
let Some(packet) = parts
|
||||
.entry(key)
|
||||
.or_default()
|
||||
.accept(packet, MAX_FRAGMENTED, None)
|
||||
else {
|
||||
return vec![];
|
||||
};
|
||||
packet
|
||||
} else {
|
||||
packet
|
||||
};
|
||||
let h = usize::from(packet[0] & 15) * 4;
|
||||
let output = if is_icmp
|
||||
&& packet
|
||||
.get(h)
|
||||
.is_some_and(|kind| matches!(kind, 3 | 11 | 12))
|
||||
{
|
||||
icmp::rewrite_error(packet, h, !outbound, |quote, quote_outbound| {
|
||||
let binding = WireFlow::parse(quote, quote_outbound)
|
||||
.and_then(|flow| self.domains.owner(flow.remote).map(|alias| (flow, alias)));
|
||||
let Some((flow, alias)) = binding else {
|
||||
// The quote passed validation but never required exit translation,
|
||||
// for example a native socket talking to a peer inside the mesh.
|
||||
return (self.domains.mode == SourceMode::ExitOnly).then_some((local, local));
|
||||
};
|
||||
let wire = WireFlow {
|
||||
local: alias,
|
||||
..flow
|
||||
};
|
||||
let entry = self
|
||||
.flows
|
||||
.get(&wire.local)
|
||||
.and_then(|table| table.get(&wire))
|
||||
.filter(|entry| now < entry.expires);
|
||||
let Some(entry) = entry else {
|
||||
return (wire.local == flow.local
|
||||
&& (Some(wire.local) == primary
|
||||
|| self.domains.mode == SourceMode::ExitOnly))
|
||||
.then_some((wire.local, wire.local));
|
||||
};
|
||||
if quote_outbound {
|
||||
(flow.local == wire.local).then_some((wire.local, entry.host))
|
||||
} else {
|
||||
(flow.local == entry.host).then_some((entry.host, wire.local))
|
||||
}
|
||||
})
|
||||
} else {
|
||||
self.translate(packet, h, local, remote, outbound, now)
|
||||
};
|
||||
match output {
|
||||
Some(packet) if fragmented => fragment_ipv4(packet, self.mtu),
|
||||
Some(packet) => vec![packet],
|
||||
None => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn translate(
|
||||
&mut self,
|
||||
packet: Bytes,
|
||||
h: usize,
|
||||
local: Ipv4Addr,
|
||||
remote: Ipv4Addr,
|
||||
outbound: bool,
|
||||
now: Instant,
|
||||
) -> Option<Bytes> {
|
||||
let Some(alias) = self.domains.owner(remote) else {
|
||||
return Some(packet);
|
||||
};
|
||||
// VIP/exit replies and any other special delivery already admitted by
|
||||
// core may have a source outside the addressed subnet.
|
||||
if !outbound && local != alias {
|
||||
return Some(packet);
|
||||
}
|
||||
let Some(flow) = WireFlow::parse(&packet, outbound) else {
|
||||
return (local == alias).then_some(packet);
|
||||
};
|
||||
let data = &packet[h..];
|
||||
let idle = match flow.protocol {
|
||||
6 => {
|
||||
let n = usize::from(*data.get(12)? >> 4) * 4;
|
||||
if n < 20 || n > data.len() {
|
||||
return None;
|
||||
}
|
||||
if data[13] & 5 != 0 {
|
||||
UDP_IDLE
|
||||
} else {
|
||||
TCP_IDLE
|
||||
}
|
||||
}
|
||||
17 => {
|
||||
if usize::from(u16::from_be_bytes([data[4], data[5]])) != data.len() {
|
||||
return None;
|
||||
}
|
||||
UDP_IDLE
|
||||
}
|
||||
_ => ECHO_IDLE,
|
||||
};
|
||||
let wire = WireFlow {
|
||||
local: alias,
|
||||
..flow
|
||||
};
|
||||
let table = self.flows.entry(alias).or_default();
|
||||
if table.get(&wire).is_some_and(|entry| entry.expires <= now) {
|
||||
table.remove(&wire);
|
||||
}
|
||||
if !table.contains_key(&wire) {
|
||||
if Some(alias) == self.domains.primary() && local == alias {
|
||||
return Some(packet);
|
||||
}
|
||||
if table.len() >= MAX_FLOWS {
|
||||
return None;
|
||||
}
|
||||
if outbound
|
||||
&& local != alias
|
||||
&& (self
|
||||
.domains
|
||||
.primary()
|
||||
.is_some_and(|primary| primary != local)
|
||||
|| flow.protocol == 6 && data[13] & 0x12 != 2)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let entry = table.entry(wire).or_insert(Binding {
|
||||
host: local,
|
||||
remote_initiated: !outbound,
|
||||
expires: now + idle,
|
||||
});
|
||||
let target = if outbound {
|
||||
if local != entry.host {
|
||||
let wildcard_reply = entry.remote_initiated
|
||||
&& entry.host == alias
|
||||
&& flow.protocol == 17
|
||||
&& self.domains.primary() == Some(local);
|
||||
if !wildcard_reply {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
alias
|
||||
} else {
|
||||
if entry.host != alias && flow.protocol == 6 && data[13] & 0x12 == 2 {
|
||||
return None;
|
||||
}
|
||||
entry.host
|
||||
};
|
||||
entry.expires = now + idle;
|
||||
if target == local {
|
||||
return Some(packet);
|
||||
}
|
||||
let mut out = packet.to_vec();
|
||||
let address = if outbound { 12 } else { 16 };
|
||||
out[address..address + 4].copy_from_slice(&target.octets());
|
||||
let check = u16::from_be_bytes([out[10], out[11]]);
|
||||
out[10..12].copy_from_slice(&update_checksum(check, local, target).to_be_bytes());
|
||||
if matches!(flow.protocol, 6 | 17) {
|
||||
let off = h + if flow.protocol == 6 { 16 } else { 6 };
|
||||
let check = u16::from_be_bytes([out[off], out[off + 1]]);
|
||||
if flow.protocol == 6 || check != 0 {
|
||||
let new = update_checksum(check, local, target);
|
||||
let new = if new == 0 && flow.protocol == 17 {
|
||||
u16::MAX
|
||||
} else {
|
||||
new
|
||||
};
|
||||
out[off..off + 2].copy_from_slice(&new.to_be_bytes());
|
||||
}
|
||||
}
|
||||
Some(out.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// RFC 1624 one's-complement adjustment for replacing an IPv4 address.
|
||||
fn update_checksum(checksum: u16, old: Ipv4Addr, new: Ipv4Addr) -> u16 {
|
||||
let mut sum = u32::from(!checksum);
|
||||
for (old, new) in old
|
||||
.octets()
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(new.octets().as_chunks::<2>().0)
|
||||
{
|
||||
sum += u32::from(!u16::from_be_bytes(*old)) + u32::from(u16::from_be_bytes(*new));
|
||||
}
|
||||
while sum >> 16 != 0 {
|
||||
sum = (sum & 0xffff) + (sum >> 16);
|
||||
}
|
||||
!(sum as u16)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
|
||||
const FIRST: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1);
|
||||
const SECOND: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1);
|
||||
const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 8);
|
||||
|
||||
fn aliases() -> Vec<Cidr> {
|
||||
vec![
|
||||
Cidr::new(FIRST.into(), 24).unwrap(),
|
||||
Cidr::new(SECOND.into(), 24).unwrap(),
|
||||
]
|
||||
}
|
||||
|
||||
fn udp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, payload: &[u8]) -> Bytes {
|
||||
use smoltcp::wire::{IpAddress, Ipv4Packet, UdpPacket};
|
||||
let mut bytes = vec![0; 28 + payload.len()];
|
||||
bytes[0] = 0x45;
|
||||
let size = bytes.len() as u16;
|
||||
bytes[2..4].copy_from_slice(&size.to_be_bytes());
|
||||
bytes[8] = 64;
|
||||
bytes[9] = 17;
|
||||
bytes[12..16].copy_from_slice(&src.octets());
|
||||
bytes[16..20].copy_from_slice(&dst.octets());
|
||||
Ipv4Packet::new_unchecked(&mut bytes[..]).fill_checksum();
|
||||
let mut udp = UdpPacket::new_unchecked(&mut bytes[20..]);
|
||||
udp.set_src_port(sport);
|
||||
udp.set_dst_port(dport);
|
||||
udp.set_len(size - 20);
|
||||
udp.payload_mut().copy_from_slice(payload);
|
||||
udp.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst));
|
||||
bytes.into()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connected_udp_keeps_its_kernel_address_while_the_peer_sees_the_right_alias() {
|
||||
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
|
||||
let request = udp(FIRST, PEER, 4123, 1234, b"request");
|
||||
assert_eq!(
|
||||
flows.outbound(request),
|
||||
vec![udp(SECOND, PEER, 4123, 1234, b"request")]
|
||||
);
|
||||
assert_eq!(
|
||||
flows.inbound(udp(PEER, SECOND, 1234, 4123, b"reply")),
|
||||
vec![udp(PEER, FIRST, 1234, 4123, b"reply")]
|
||||
);
|
||||
assert!(
|
||||
flows
|
||||
.outbound(udp(SECOND, PEER, 4123, 1234, b"bound collision"))
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
flows.inbound(udp(PEER, SECOND, 1234, 4124, b"to a listener")),
|
||||
vec![udp(PEER, SECOND, 1234, 4124, b"to a listener")]
|
||||
);
|
||||
assert_eq!(
|
||||
flows.outbound(udp(FIRST, PEER, 4124, 1234, b"wildcard listener reply")),
|
||||
vec![udp(SECOND, PEER, 4124, 1234, b"wildcard listener reply")]
|
||||
);
|
||||
assert_eq!(
|
||||
flows.inbound(udp(PEER, SECOND, 1234, 4124, b"again")),
|
||||
vec![udp(PEER, SECOND, 1234, 4124, b"again")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_exit_accepts_any_local_alias_and_restores_external_replies() {
|
||||
let mut flows = SourceFlows::new(&aliases(), Some(FIRST), 1280, SourceMode::ExitOnly);
|
||||
let internet = Ipv4Addr::new(203, 0, 113, 2);
|
||||
let request = udp(SECOND, internet, 4123, 443, b"external");
|
||||
assert_eq!(
|
||||
flows.outbound(request),
|
||||
[udp(FIRST, internet, 4123, 443, b"external")]
|
||||
);
|
||||
assert_eq!(
|
||||
flows.inbound(udp(internet, FIRST, 443, 4123, b"reply")),
|
||||
[udp(internet, SECOND, 443, 4123, b"reply")]
|
||||
);
|
||||
// An explicitly bound socket cannot take replies from this flow.
|
||||
assert!(
|
||||
flows
|
||||
.outbound(udp(FIRST, internet, 4123, 443, b"collision"))
|
||||
.is_empty()
|
||||
);
|
||||
// An address in either overlay, including the gateway itself, stays native.
|
||||
let mesh = udp(SECOND, PEER, 4123, 443, b"mesh");
|
||||
assert_eq!(flows.outbound(mesh.clone()), [mesh]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wintun_normalizes_only_external_flows_while_an_exit_is_selected() {
|
||||
use super::windows::ExitSourceTun;
|
||||
use crate::overlay::{MemoryTun, TunDevice};
|
||||
|
||||
let device = MemoryTun::new("test", 1280);
|
||||
let tun = ExitSourceTun::new(device.clone());
|
||||
let internet = Ipv4Addr::new(203, 0, 113, 2);
|
||||
let request = udp(FIRST, internet, 4000, 80, &[1; 1600]);
|
||||
let on_wire = udp(SECOND, internet, 4000, 80, &[1; 1600]);
|
||||
tun.set_exit_source(&aliases(), Some(SECOND));
|
||||
for part in fragment_ipv4(request.clone(), 1280) {
|
||||
device.push_from_os(part);
|
||||
}
|
||||
for expected in fragment_ipv4(on_wire, 1280) {
|
||||
assert_eq!(tun.recv().await, Some(expected));
|
||||
}
|
||||
// Periodic exit rule refreshes must preserve the original socket.
|
||||
tun.set_exit_source(&aliases(), Some(SECOND));
|
||||
tun.send(udp(internet, SECOND, 80, 4000, b"reply"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
device.pop_to_os().await,
|
||||
Some(udp(internet, FIRST, 80, 4000, b"reply"))
|
||||
);
|
||||
let forwarded = udp(PEER, internet, 4000, 80, b"forwarded");
|
||||
device.push_from_os(forwarded.clone());
|
||||
assert_eq!(tun.recv().await, Some(forwarded));
|
||||
|
||||
tun.set_exit_source(&aliases(), None);
|
||||
device.push_from_os(request.clone());
|
||||
assert_eq!(tun.recv().await, Some(request));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proper_bound_flows_and_limited_broadcast_keep_their_identity() {
|
||||
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
|
||||
let native = udp(SECOND, PEER, 3000, 3001, b"bound");
|
||||
assert_eq!(flows.outbound(native.clone()), vec![native]);
|
||||
assert!(
|
||||
flows
|
||||
.outbound(udp(FIRST, PEER, 3000, 3001, b"collision"))
|
||||
.is_empty()
|
||||
);
|
||||
let reply = udp(PEER, SECOND, 3001, 3000, b"native");
|
||||
assert_eq!(flows.inbound(reply.clone()), vec![reply]);
|
||||
let broadcast = udp(FIRST, Ipv4Addr::BROADCAST, 3000, 3001, b"lan");
|
||||
assert_eq!(flows.outbound(broadcast.clone()), vec![broadcast]);
|
||||
assert!(
|
||||
flows
|
||||
.outbound(udp(PEER, PEER, 3100, 3100, b"forged source"))
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
fn packet(src: Ipv4Addr, dst: Ipv4Addr, protocol: u8, data: &[u8]) -> Bytes {
|
||||
let mut out = vec![0; 20 + data.len()];
|
||||
let size = out.len() as u16;
|
||||
out[0] = 0x45;
|
||||
out[2..4].copy_from_slice(&size.to_be_bytes());
|
||||
out[8] = 64;
|
||||
out[9] = protocol;
|
||||
out[12..16].copy_from_slice(&src.octets());
|
||||
out[16..20].copy_from_slice(&dst.octets());
|
||||
out[20..].copy_from_slice(data);
|
||||
Ipv4Packet::new_unchecked(&mut out).fill_checksum();
|
||||
out.into()
|
||||
}
|
||||
|
||||
fn tcp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, flags: u8) -> Bytes {
|
||||
use smoltcp::wire::{IpAddress, TcpPacket};
|
||||
let mut data = [0; 20];
|
||||
data[..2].copy_from_slice(&sport.to_be_bytes());
|
||||
data[2..4].copy_from_slice(&dport.to_be_bytes());
|
||||
data[12] = 0x50;
|
||||
data[13] = flags;
|
||||
TcpPacket::new_unchecked(&mut data[..])
|
||||
.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst));
|
||||
packet(src, dst, 6, &data)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_keeps_direction_and_bindings_survive_unrelated_plans() {
|
||||
let mut aliases = aliases();
|
||||
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
|
||||
assert!(flows.outbound(tcp(FIRST, PEER, 333, 443, 16)).is_empty());
|
||||
assert_eq!(
|
||||
flows.outbound(tcp(FIRST, PEER, 333, 443, 2)),
|
||||
[tcp(SECOND, PEER, 333, 443, 2)]
|
||||
);
|
||||
flows.reconfigure(&aliases, None, 1280);
|
||||
assert_eq!(
|
||||
flows.inbound(tcp(PEER, SECOND, 443, 333, 18)),
|
||||
[tcp(PEER, FIRST, 443, 333, 18)]
|
||||
);
|
||||
// An inbound connection cannot replace a client's active translation.
|
||||
assert!(flows.inbound(tcp(PEER, SECOND, 443, 333, 2)).is_empty());
|
||||
let inbound = tcp(PEER, SECOND, 12345, 80, 2);
|
||||
assert_eq!(flows.inbound(inbound.clone()), [inbound]);
|
||||
let syn_ack = tcp(SECOND, PEER, 80, 12345, 18);
|
||||
assert_eq!(flows.outbound(syn_ack.clone()), [syn_ack]);
|
||||
aliases.remove(0);
|
||||
flows.reconfigure(&aliases, None, 1280);
|
||||
assert!(
|
||||
!flows
|
||||
.flows
|
||||
.values()
|
||||
.any(|table| table.values().any(|e| e.host == FIRST))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_primary_drains_earlier_translations_and_passes_its_own_packets() {
|
||||
let mut aliases = aliases();
|
||||
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
|
||||
assert_eq!(flows.outbound(udp(FIRST, PEER, 2222, 53, b"q")).len(), 1);
|
||||
aliases.swap(0, 1);
|
||||
flows.reconfigure(&aliases, Some(SECOND), 1280);
|
||||
assert_eq!(
|
||||
flows.inbound(udp(PEER, SECOND, 53, 2222, b"a")),
|
||||
[udp(PEER, FIRST, 53, 2222, b"a")]
|
||||
);
|
||||
let bound = udp(SECOND, PEER, 4444, 443, b"native");
|
||||
assert_eq!(flows.outbound(bound.clone()), [bound]);
|
||||
let native_reply = udp(PEER, SECOND, 443, 4444, b"r");
|
||||
assert_eq!(flows.inbound(native_reply.clone()), [native_reply]);
|
||||
assert_eq!(flows.flows[&SECOND].len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untracked_primary_errors_and_point_to_point_destinations_are_preserved() {
|
||||
let mut aliases = aliases();
|
||||
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
|
||||
let router = Ipv4Addr::new(10, 1, 0, 7);
|
||||
let mut unreachable = vec![3, 1, 0, 0, 0, 0, 0, 0];
|
||||
unreachable.extend_from_slice(&udp(FIRST, router, 50_000, 7, b"probe")[..28]);
|
||||
smoltcp::wire::Icmpv4Packet::new_unchecked(&mut unreachable).fill_checksum();
|
||||
let error = packet(router, FIRST, 1, &unreachable);
|
||||
assert_eq!(flows.inbound(error.clone()), [error]);
|
||||
let directed = udp(FIRST, Ipv4Addr::new(10, 2, 0, 255), 5, 6, b"broadcast");
|
||||
assert_eq!(flows.outbound(directed.clone()), [directed]);
|
||||
let point = Ipv4Addr::new(10, 2, 0, 0);
|
||||
aliases[1] = Cidr::new(point.into(), 31).unwrap();
|
||||
flows.reconfigure(&aliases, None, 1280);
|
||||
assert_eq!(
|
||||
flows.outbound(udp(FIRST, SECOND, 5, 6, b"p2p")),
|
||||
[udp(point, SECOND, 5, 6, b"p2p")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn echo_ids_can_match_in_both_directions() {
|
||||
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
|
||||
let message = |src, dst, kind| {
|
||||
use smoltcp::wire::Icmpv4Packet;
|
||||
let mut data = [kind, 0, 0, 0, 0x12, 0x34, 0, 2];
|
||||
Icmpv4Packet::new_unchecked(&mut data[..]).fill_checksum();
|
||||
packet(src, dst, 1, &data)
|
||||
};
|
||||
assert_eq!(
|
||||
flows.outbound(message(FIRST, PEER, 8)),
|
||||
[message(SECOND, PEER, 8)]
|
||||
);
|
||||
assert_eq!(
|
||||
flows.inbound(message(PEER, SECOND, 8)),
|
||||
[message(PEER, SECOND, 8)]
|
||||
);
|
||||
assert_eq!(
|
||||
flows.outbound(message(SECOND, PEER, 0)),
|
||||
[message(SECOND, PEER, 0)]
|
||||
);
|
||||
assert_eq!(
|
||||
flows.inbound(message(PEER, SECOND, 0)),
|
||||
[message(PEER, FIRST, 0)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturated_network_does_not_take_another_networks_capacity() {
|
||||
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
|
||||
for port in 0..MAX_FLOWS {
|
||||
assert_eq!(
|
||||
flows
|
||||
.outbound(udp(FIRST, PEER, port as u16, 53, b"q"))
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
flows
|
||||
.outbound(udp(FIRST, PEER, 60000, 53, b"full"))
|
||||
.is_empty()
|
||||
);
|
||||
let primary_peer = Ipv4Addr::new(10, 1, 0, 20);
|
||||
let own = udp(FIRST, primary_peer, 60000, 53, b"first");
|
||||
assert_eq!(flows.outbound(own.clone()), [own]);
|
||||
for entry in flows.flows.get_mut(&SECOND).unwrap().values_mut() {
|
||||
entry.expires = Instant::now();
|
||||
}
|
||||
flows.last_sweep -= Duration::from_secs(6);
|
||||
assert_eq!(
|
||||
flows.outbound(udp(FIRST, PEER, 60000, 53, b"free")).len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(flows.flows[&SECOND].len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragmented_udp_translates_after_assembly_in_both_directions() {
|
||||
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
|
||||
let mut original = udp(FIRST, PEER, 3333, 4444, &[7; 1900]);
|
||||
let parts = fragment_ipv4(original.clone(), 1280);
|
||||
let mut output = Vec::new();
|
||||
for part in parts.into_iter().rev() {
|
||||
output.extend(flows.outbound(part));
|
||||
}
|
||||
assert_eq!(
|
||||
output,
|
||||
fragment_ipv4(udp(SECOND, PEER, 3333, 4444, &[7; 1900]), 1280)
|
||||
);
|
||||
original = udp(PEER, SECOND, 4444, 3333, &[8; 1900]);
|
||||
let mut output = Vec::new();
|
||||
for part in fragment_ipv4(original, 1280) {
|
||||
output.extend(flows.inbound(part));
|
||||
}
|
||||
assert_eq!(
|
||||
output,
|
||||
fragment_ipv4(udp(PEER, FIRST, 4444, 3333, &[8; 1900]), 1280)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Translate errors on existing flows, including truncated RFC 792 quotations.
|
||||
use super::update_checksum;
|
||||
use bytes::Bytes;
|
||||
use smoltcp::wire::{Icmpv4Packet, IpProtocol, Ipv4Packet};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub(super) fn rewrite_error(
|
||||
packet: Bytes,
|
||||
header_len: usize,
|
||||
inbound: bool,
|
||||
mut lookup: impl FnMut(&[u8], bool) -> Option<(Ipv4Addr, Ipv4Addr)>,
|
||||
) -> Option<Bytes> {
|
||||
let outer = Ipv4Packet::new_checked(&packet[..]).ok()?;
|
||||
if outer.version() != 4
|
||||
|| header_len < 20
|
||||
|| header_len != usize::from(outer.header_len())
|
||||
|| usize::from(outer.total_len()) != packet.len()
|
||||
|| outer.next_header() != IpProtocol::Icmp
|
||||
|| outer.more_frags()
|
||||
|| outer.frag_offset() != 0
|
||||
|| !outer.verify_checksum()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let icmp = outer.payload();
|
||||
if !Icmpv4Packet::new_checked(icmp).ok()?.verify_checksum() || !matches!(icmp[0], 3 | 11 | 12) {
|
||||
return None;
|
||||
}
|
||||
let payload = &icmp[8..];
|
||||
// RFC 4884 records the padded quotation length in words when extensions follow.
|
||||
let quote = match icmp[5] {
|
||||
0 => payload,
|
||||
words => payload.get(..usize::from(words) * 4)?,
|
||||
};
|
||||
quote.get(..20)?;
|
||||
// The original total length may exceed the bytes the router chose to quote.
|
||||
let inner = Ipv4Packet::new_unchecked(quote);
|
||||
let inner_header = usize::from(inner.header_len());
|
||||
let quote_len = quote.len().min(usize::from(inner.total_len()));
|
||||
if inner.version() != 4
|
||||
|| inner_header < 20
|
||||
|| quote_len < inner_header + 8
|
||||
|| inner.frag_offset() != 0
|
||||
|| !inner.verify_checksum()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (outer_local, inner_local) = if inbound {
|
||||
(outer.dst_addr(), inner.src_addr())
|
||||
} else {
|
||||
(outer.src_addr(), inner.dst_addr())
|
||||
};
|
||||
if outer_local != inner_local {
|
||||
return None;
|
||||
}
|
||||
let (old, new) = lookup("e[..quote_len], inbound)?;
|
||||
if old != inner_local {
|
||||
return None;
|
||||
}
|
||||
if old == new {
|
||||
return Some(packet);
|
||||
}
|
||||
let transport = inner.next_header();
|
||||
let mut result = packet.to_vec();
|
||||
let quote_start = header_len + 8;
|
||||
let mut inner = Ipv4Packet::new_unchecked(&mut result[quote_start..quote_start + quote_len]);
|
||||
if inbound {
|
||||
inner.set_src_addr(new);
|
||||
} else {
|
||||
inner.set_dst_addr(new);
|
||||
}
|
||||
inner.fill_checksum();
|
||||
let transport_bytes = &mut inner.into_inner()[inner_header..];
|
||||
// A minimum TCP quote includes ports and sequence number, but not its checksum.
|
||||
let field = match transport {
|
||||
IpProtocol::Tcp => transport_bytes.get_mut(16..18),
|
||||
IpProtocol::Udp => transport_bytes.get_mut(6..8),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(field) = field {
|
||||
let previous = u16::from_be_bytes([field[0], field[1]]);
|
||||
if previous != 0 || transport == IpProtocol::Tcp {
|
||||
let adjusted = update_checksum(previous, old, new);
|
||||
let value = if adjusted == 0 && transport == IpProtocol::Udp {
|
||||
u16::MAX
|
||||
} else {
|
||||
adjusted
|
||||
};
|
||||
field.copy_from_slice(&value.to_be_bytes());
|
||||
}
|
||||
}
|
||||
Icmpv4Packet::new_unchecked(&mut result[header_len..]).fill_checksum();
|
||||
let mut outer = Ipv4Packet::new_unchecked(&mut result);
|
||||
if inbound {
|
||||
outer.set_dst_addr(new);
|
||||
} else {
|
||||
outer.set_src_addr(new);
|
||||
}
|
||||
outer.fill_checksum();
|
||||
Some(result.into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use smoltcp::wire::{TcpPacket, UdpPacket};
|
||||
|
||||
const APP: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1);
|
||||
const WIRE: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1);
|
||||
const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 2);
|
||||
const ROUTER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 3);
|
||||
|
||||
fn ipv4(protocol: u8, src: Ipv4Addr, dst: Ipv4Addr, payload: &[u8]) -> Vec<u8> {
|
||||
let mut p = vec![0; 20 + payload.len()];
|
||||
let total = p.len() as u16;
|
||||
p[0] = 0x45;
|
||||
p[2..4].copy_from_slice(&total.to_be_bytes());
|
||||
p[8] = 64;
|
||||
p[9] = protocol;
|
||||
p[12..16].copy_from_slice(&src.octets());
|
||||
p[16..20].copy_from_slice(&dst.octets());
|
||||
p[20..].copy_from_slice(payload);
|
||||
Ipv4Packet::new_unchecked(&mut p).fill_checksum();
|
||||
p
|
||||
}
|
||||
|
||||
fn error(src: Ipv4Addr, dst: Ipv4Addr, quote: &[u8]) -> Bytes {
|
||||
let mut icmp = vec![3, 4, 0, 0, 0, 0, 5, 0];
|
||||
icmp.extend_from_slice(quote);
|
||||
Icmpv4Packet::new_unchecked(&mut icmp).fill_checksum();
|
||||
ipv4(1, src, dst, &icmp).into()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wintun_keeps_mesh_errors_and_restores_exit_errors_from_a_mesh_router() {
|
||||
use super::super::{SourceFlows, SourceMode};
|
||||
use crate::overlay::Cidr;
|
||||
|
||||
let external = Ipv4Addr::new(203, 0, 113, 200);
|
||||
let mut flows = SourceFlows::new(
|
||||
&[
|
||||
Cidr::new(APP.into(), 24).unwrap(),
|
||||
Cidr::new(WIRE.into(), 24).unwrap(),
|
||||
],
|
||||
Some(WIRE),
|
||||
1280,
|
||||
SourceMode::ExitOnly,
|
||||
);
|
||||
let mut udp = [0; 8];
|
||||
udp[4..6].copy_from_slice(&8u16.to_be_bytes());
|
||||
let mesh_packet = ipv4(17, WIRE, PEER, &udp);
|
||||
let mesh_error = error(ROUTER, WIRE, &mesh_packet);
|
||||
assert_eq!(flows.inbound(mesh_error.clone()), [mesh_error]);
|
||||
|
||||
let original = ipv4(17, APP, external, &udp);
|
||||
let translated = flows.outbound(original.clone().into()).pop().unwrap();
|
||||
assert_eq!(
|
||||
flows.inbound(error(ROUTER, WIRE, &translated)),
|
||||
[error(ROUTER, APP, &original)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbound_pmtu_restores_a_truncated_udp_quote_and_preserves_the_reporting_router() {
|
||||
use super::super::{SourceFlows, SourceMode};
|
||||
use crate::overlay::Cidr;
|
||||
|
||||
let mut flows = SourceFlows::new(
|
||||
&[
|
||||
Cidr::new(APP.into(), 24).unwrap(),
|
||||
Cidr::new(WIRE.into(), 24).unwrap(),
|
||||
],
|
||||
None,
|
||||
1280,
|
||||
SourceMode::Primary,
|
||||
);
|
||||
let mut udp = [0x71; 16];
|
||||
udp[4..6].copy_from_slice(&16u16.to_be_bytes());
|
||||
UdpPacket::new_unchecked(&mut udp[..]).fill_checksum(&APP.into(), &PEER.into());
|
||||
let original = ipv4(17, APP, PEER, &udp);
|
||||
let wire = flows.outbound(original.clone().into()).pop().unwrap();
|
||||
let p = error(ROUTER, WIRE, &wire[..28]);
|
||||
let restored = flows.inbound(p).pop().unwrap();
|
||||
let outer = Ipv4Packet::new_checked(&restored[..]).unwrap();
|
||||
assert!(outer.verify_checksum());
|
||||
assert_eq!(outer.src_addr(), ROUTER);
|
||||
assert_eq!(outer.dst_addr(), APP);
|
||||
assert!(
|
||||
Icmpv4Packet::new_checked(outer.payload())
|
||||
.unwrap()
|
||||
.verify_checksum()
|
||||
);
|
||||
assert_eq!(outer.payload()[6..8], 1280u16.to_be_bytes());
|
||||
assert_eq!(outer.payload()[8..], original[..28]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outbound_error_restores_tcp_quotes_with_or_without_a_transport_checksum() {
|
||||
let mut tcp = [0x41; 48];
|
||||
tcp[12] = 0x50;
|
||||
TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &APP.into());
|
||||
let original = ipv4(6, PEER, APP, &tcp);
|
||||
TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &WIRE.into());
|
||||
let wire = ipv4(6, PEER, WIRE, &tcp);
|
||||
for length in [28, original.len()] {
|
||||
let p = error(APP, PEER, &original[..length]);
|
||||
let rewritten = rewrite_error(p, 20, false, |_, outbound| {
|
||||
assert!(!outbound);
|
||||
Some((APP, WIRE))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(rewritten, error(WIRE, PEER, &wire[..length]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_quotes_unknown_flows_and_unrelated_outer_addresses_are_rejected() {
|
||||
let original = ipv4(17, WIRE, PEER, &[0; 8]);
|
||||
let p = error(ROUTER, WIRE, &original);
|
||||
assert_eq!(
|
||||
rewrite_error(p.clone(), 20, true, |_, _| Some((WIRE, WIRE))),
|
||||
Some(p.clone())
|
||||
);
|
||||
assert!(rewrite_error(p, 20, true, |_, _| None).is_none());
|
||||
for invalid in [
|
||||
error(ROUTER, APP, &original),
|
||||
error(ROUTER, WIRE, &original[..26]),
|
||||
{
|
||||
let mut fragment = original.clone();
|
||||
fragment[7] = 1;
|
||||
Ipv4Packet::new_unchecked(&mut fragment).fill_checksum();
|
||||
error(ROUTER, WIRE, &fragment)
|
||||
},
|
||||
{
|
||||
let mut damaged = error(ROUTER, WIRE, &original).to_vec();
|
||||
damaged[22] ^= 1;
|
||||
damaged.into()
|
||||
},
|
||||
] {
|
||||
assert!(
|
||||
rewrite_error(invalid, 20, true, |_, _| panic!(
|
||||
"invalid quote reached lookup"
|
||||
))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
// IPv4 UDP allows a zero checksum; translation may not enable it.
|
||||
let restored = rewrite_error(error(ROUTER, WIRE, &original), 20, true, |_, _| {
|
||||
Some((WIRE, APP))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(restored[54..56], [0, 0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Wintun default routes cannot specify a preferred IPv4 source address.
|
||||
use super::{Domains, SourceFlows, SourceMode};
|
||||
use crate::BoxFuture;
|
||||
use crate::overlay::{Cidr, OverlayError, TunDevice};
|
||||
use bytes::Bytes;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
pub(crate) struct ExitSourceTun {
|
||||
device: Arc<dyn TunDevice>,
|
||||
state: Mutex<Option<State>>,
|
||||
}
|
||||
|
||||
struct State {
|
||||
flows: SourceFlows,
|
||||
pending: std::vec::IntoIter<Bytes>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ExitSourceTun {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("ExitSourceTun").field(&self.device).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExitSourceTun {
|
||||
pub(crate) fn new(device: Arc<dyn TunDevice>) -> Self {
|
||||
Self {
|
||||
device,
|
||||
state: Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn state(&self) -> MutexGuard<'_, Option<State>> {
|
||||
self.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
impl TunDevice for ExitSourceTun {
|
||||
fn name(&self) -> &str {
|
||||
self.device.name()
|
||||
}
|
||||
|
||||
fn mtu(&self) -> u32 {
|
||||
self.device.mtu()
|
||||
}
|
||||
|
||||
fn set_exit_source(&self, addresses: &[Cidr], source: Option<Ipv4Addr>) {
|
||||
let mut active = self.state();
|
||||
let domains = Domains::new(addresses, source, SourceMode::ExitOnly);
|
||||
if domains.aliases.len() < 2 || !source.is_some_and(|addr| domains.has(addr)) {
|
||||
*active = None;
|
||||
return;
|
||||
}
|
||||
if let Some(state) = active.as_mut() {
|
||||
if state.flows.domains != domains {
|
||||
state.flows.reconfigure(addresses, source, self.mtu());
|
||||
state.pending = Vec::new().into_iter();
|
||||
}
|
||||
} else {
|
||||
*active = Some(State {
|
||||
flows: SourceFlows::new(addresses, source, self.mtu(), SourceMode::ExitOnly),
|
||||
pending: Vec::new().into_iter(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
|
||||
Box::pin(async {
|
||||
if let Some(part) = self.state().as_mut().and_then(|s| s.pending.next()) {
|
||||
return Some(part);
|
||||
}
|
||||
loop {
|
||||
let packet = self.device.recv().await?;
|
||||
let mut active = self.state();
|
||||
let Some(state) = active.as_mut() else {
|
||||
return Some(packet);
|
||||
};
|
||||
state.pending = state.flows.outbound(packet).into_iter();
|
||||
if let Some(part) = state.pending.next() {
|
||||
return Some(part);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send(&self, packet: Bytes) -> BoxFuture<'_, Result<(), OverlayError>> {
|
||||
Box::pin(async move {
|
||||
let parts = self
|
||||
.state()
|
||||
.as_mut()
|
||||
.map(|s| s.flows.inbound(packet.clone()));
|
||||
if let Some(parts) = parts {
|
||||
for part in parts {
|
||||
self.device.send(part).await?;
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
self.device.send(packet).await
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,10 @@ pub trait TunDevice: Send + Sync + std::fmt::Debug + 'static {
|
||||
/// The interface MTU.
|
||||
fn mtu(&self) -> u32;
|
||||
|
||||
/// Supply the local Wintun address and exit selection used for off-mesh flows.
|
||||
#[cfg(any(windows, test))]
|
||||
fn set_exit_source(&self, _addresses: &[super::Cidr], _source: Option<std::net::Ipv4Addr>) {}
|
||||
|
||||
/// The next packet the operating system wants to send, or `None` once the
|
||||
/// device is gone.
|
||||
fn recv(&self) -> BoxFuture<'_, Option<Bytes>>;
|
||||
@@ -90,6 +94,21 @@ pub trait TunFactory: Send + Sync + std::fmt::Debug + 'static {
|
||||
/// land on the second.
|
||||
fn on_host(&self) -> bool;
|
||||
|
||||
/// Bind a socket carrying a VIP health check to this overlay on platforms
|
||||
/// that explicitly route mesh transport sockets outside the VPN.
|
||||
fn bind_overlay_socket(
|
||||
&self,
|
||||
_socket: &tokio::net::TcpSocket,
|
||||
_source: std::net::Ipv4Addr,
|
||||
) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Assigned overlay addresses when the OS chooses a new interface name on reconfiguration.
|
||||
fn assigned_addresses(&self) -> Vec<std::net::IpAddr> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Creates a device.
|
||||
fn create<'a>(
|
||||
&'a self,
|
||||
@@ -229,37 +248,34 @@ impl TunDevice for MemoryTun {
|
||||
/// enough here: the agent chose the address, so anything else holding it is a
|
||||
/// problem in its own right.
|
||||
pub fn address_is_local(address: std::net::IpAddr) -> bool {
|
||||
if std::net::UdpSocket::bind((address, 0)).is_ok() {
|
||||
return true;
|
||||
}
|
||||
let bound = std::net::UdpSocket::bind((address, 0)).is_ok();
|
||||
#[cfg(all(feature = "tun-device", target_os = "windows"))]
|
||||
{
|
||||
if let Ok(interfaces) = std::panic::catch_unwind(netdev::get_interfaces) {
|
||||
for iface in interfaces {
|
||||
if iface.is_up() {
|
||||
match address {
|
||||
std::net::IpAddr::V4(v4) => {
|
||||
if iface.ipv4.iter().any(|ip| ip.addr() == v4) {
|
||||
return true;
|
||||
}
|
||||
if !bound && let Ok(interfaces) = std::panic::catch_unwind(netdev::get_interfaces) {
|
||||
for iface in interfaces {
|
||||
if iface.is_up() {
|
||||
match address {
|
||||
std::net::IpAddr::V4(v4) => {
|
||||
if iface.ipv4.iter().any(|ip| ip.addr() == v4) {
|
||||
return true;
|
||||
}
|
||||
std::net::IpAddr::V6(v6) => {
|
||||
if iface.ipv6.iter().any(|ip| ip.addr() == v6) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
std::net::IpAddr::V6(v6) => {
|
||||
if iface.ipv6.iter().any(|ip| ip.addr() == v6) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
bound
|
||||
}
|
||||
|
||||
/// Creates [`MemoryTun`] devices.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MemoryTunFactory {
|
||||
created: Arc<std::sync::Mutex<Vec<Arc<MemoryTun>>>>,
|
||||
rules: Option<Arc<dyn super::hostrules::BroadcastHostRules>>,
|
||||
}
|
||||
|
||||
impl MemoryTunFactory {
|
||||
@@ -268,6 +284,12 @@ impl MemoryTunFactory {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Simulate host rule outcomes alongside this in-memory interface.
|
||||
pub fn with_host_rules(mut self, rules: Arc<dyn super::hostrules::BroadcastHostRules>) -> Self {
|
||||
self.rules = Some(rules);
|
||||
self
|
||||
}
|
||||
|
||||
/// The device created for an interface name, if any.
|
||||
pub fn device(&self, name: &str) -> Option<Arc<MemoryTun>> {
|
||||
let guard = match self.created.lock() {
|
||||
@@ -291,6 +313,9 @@ impl MemoryTunFactory {
|
||||
}
|
||||
|
||||
impl TunFactory for MemoryTunFactory {
|
||||
fn host_rules(&self) -> Option<Arc<dyn super::hostrules::BroadcastHostRules>> {
|
||||
self.rules.clone()
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
"memory"
|
||||
}
|
||||
@@ -455,12 +480,16 @@ mod system {
|
||||
let name = request.name.clone();
|
||||
|
||||
let (reader, writer) = tokio::io::split(device);
|
||||
Ok(Arc::new(SystemTun {
|
||||
let device: Arc<dyn TunDevice> = Arc::new(SystemTun {
|
||||
name,
|
||||
mtu: request.mtu,
|
||||
reader: Mutex::new(reader),
|
||||
writer: Mutex::new(writer),
|
||||
}) as Arc<dyn TunDevice>)
|
||||
});
|
||||
#[cfg(windows)]
|
||||
let device: Arc<dyn TunDevice> =
|
||||
Arc::new(crate::overlay::source::windows::ExitSourceTun::new(device));
|
||||
Ok(device)
|
||||
}
|
||||
|
||||
fn open_error(name: &str, error: tun::Error) -> OverlayError {
|
||||
|
||||
@@ -273,15 +273,19 @@ struct Datagram {
|
||||
bytes: usize,
|
||||
}
|
||||
type FragmentKey = (Option<[u8; 32]>, Ipv4Addr, Ipv4Addr, u16, u8);
|
||||
/// Bounded IPv4 fragment assembly for a local packet consumer.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Reassembly {
|
||||
pub struct Reassembly {
|
||||
pending: HashMap<FragmentKey, Datagram>,
|
||||
}
|
||||
impl Reassembly {
|
||||
/// Forget incomplete datagrams after their five-second lifetime.
|
||||
pub fn expire(&mut self, now: Instant) {
|
||||
self.pending
|
||||
.retain(|_, d| now.duration_since(d.at) < Duration::from_secs(5));
|
||||
}
|
||||
/// Accept one fragment or complete packet. `max` bounds pending datagrams;
|
||||
/// `scope` separates authenticated senders sharing an address domain.
|
||||
pub fn accept(&mut self, p: Bytes, max: usize, scope: Option<[u8; 32]>) -> Option<Bytes> {
|
||||
let n = header(&p)?;
|
||||
let flags = u16::from_be_bytes([p[6], p[7]]);
|
||||
@@ -363,7 +367,7 @@ impl Reassembly {
|
||||
}
|
||||
|
||||
/// Re-fragments an assembled NAT datagram for the unchanged overlay MTU.
|
||||
pub(crate) fn fragments(packet: Bytes, mtu: u32) -> Vec<Bytes> {
|
||||
pub fn fragments(packet: Bytes, mtu: u32) -> Vec<Bytes> {
|
||||
if packet.len() <= mtu as usize {
|
||||
return vec![packet];
|
||||
}
|
||||
|
||||
@@ -92,18 +92,20 @@ type CheckKey = (NetworkId, EndpointId, Ipv4Addr, Protocol, u16);
|
||||
/// A bounded TCP connect check prepared off the packet path.
|
||||
pub(crate) struct CheckJob {
|
||||
key: CheckKey,
|
||||
source: Ipv4Addr,
|
||||
timeout: Duration,
|
||||
}
|
||||
impl CheckJob {
|
||||
pub async fn run(self) -> (Self, bool) {
|
||||
let ok = matches!(
|
||||
tokio::time::timeout(
|
||||
self.timeout,
|
||||
tokio::net::TcpStream::connect((self.key.2, self.key.4))
|
||||
)
|
||||
.await,
|
||||
Ok(Ok(_))
|
||||
);
|
||||
pub async fn run(
|
||||
self,
|
||||
bind: impl FnOnce(&tokio::net::TcpSocket, Ipv4Addr) -> std::io::Result<()>,
|
||||
) -> (Self, bool) {
|
||||
let connect = async {
|
||||
let socket = tokio::net::TcpSocket::new_v4()?;
|
||||
bind(&socket, self.source)?;
|
||||
socket.connect((self.key.2, self.key.4).into()).await
|
||||
};
|
||||
let ok = matches!(tokio::time::timeout(self.timeout, connect).await, Ok(Ok(_)));
|
||||
(self, ok)
|
||||
}
|
||||
}
|
||||
@@ -396,6 +398,7 @@ impl VipRouter {
|
||||
for (l, b) in listeners {
|
||||
let key = (network, peer, address, l.protocol, b.port);
|
||||
wanted_checks.insert(key);
|
||||
let Some(source) = source else { continue };
|
||||
if l.protocol != Protocol::Tcp || !l.port_check {
|
||||
continue;
|
||||
}
|
||||
@@ -412,6 +415,7 @@ impl VipRouter {
|
||||
{
|
||||
jobs.push(CheckJob {
|
||||
key,
|
||||
source,
|
||||
timeout: Duration::from_millis(u64::from(l.check_timeout_ms)),
|
||||
});
|
||||
}
|
||||
@@ -1078,6 +1082,38 @@ mod tests {
|
||||
};
|
||||
assert_eq!(packet::tuple(&reply), Some(t.reverse()));
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn tcp_check_connects_only_after_the_overlay_socket_is_bound() {
|
||||
use std::io;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let (_, network, local, _, _, _) = fixture(Protocol::Tcp);
|
||||
let server = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.unwrap();
|
||||
let port = server.local_addr().unwrap().port();
|
||||
let job = || CheckJob {
|
||||
key: (network, local, Ipv4Addr::LOCALHOST, Protocol::Tcp, port),
|
||||
source: Ipv4Addr::LOCALHOST,
|
||||
timeout: Duration::from_secs(1),
|
||||
};
|
||||
let called = AtomicUsize::new(0);
|
||||
let (_, ok) = job()
|
||||
.run(|_, source| {
|
||||
assert_eq!(source, Ipv4Addr::LOCALHOST);
|
||||
called.fetch_add(1, Ordering::Relaxed);
|
||||
Err(io::Error::other("VPN replaced"))
|
||||
})
|
||||
.await;
|
||||
assert!(!ok);
|
||||
assert_eq!(called.load(Ordering::Relaxed), 1);
|
||||
let (_, ok) = job()
|
||||
.run(|socket, source| socket.bind((source, 0).into()))
|
||||
.await;
|
||||
assert!(ok);
|
||||
let (_, peer) = server.accept().await.unwrap();
|
||||
assert_eq!(peer.ip(), Ipv4Addr::LOCALHOST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_tcp_port_checks_recover_after_a_real_listener_appears() {
|
||||
let (r, n, local, _, _, _) = fixture(Protocol::Tcp);
|
||||
@@ -1099,7 +1135,7 @@ mod tests {
|
||||
}
|
||||
let (_, jobs) = r.tick(32);
|
||||
for job in jobs {
|
||||
let (job, ok) = job.run().await;
|
||||
let (job, ok) = job.run(|_, _| Ok(())).await;
|
||||
assert!(ok);
|
||||
r.checked(job, ok);
|
||||
}
|
||||
@@ -1112,7 +1148,7 @@ mod tests {
|
||||
}
|
||||
let (_, jobs) = r.tick(32);
|
||||
for job in jobs {
|
||||
let (job, ok) = job.run().await;
|
||||
let (job, ok) = job.run(|_, _| Ok(())).await;
|
||||
assert!(!ok);
|
||||
r.checked(job, ok);
|
||||
}
|
||||
@@ -1127,7 +1163,7 @@ mod tests {
|
||||
}
|
||||
let (_, jobs) = r.tick(32);
|
||||
for job in jobs {
|
||||
let (job, ok) = job.run().await;
|
||||
let (job, ok) = job.run(|_, _| Ok(())).await;
|
||||
r.checked(job, ok);
|
||||
}
|
||||
assert!(r.statuses(n)[0].listeners[0].selected.is_some());
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.2"
|
||||
description = "Built-in mesh transports and status reporting for native tsunagi agents."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.2" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.2" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.2" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.2" }
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Construct the native data transports in one place for both the CLI and Android.
|
||||
//! The embedding application supplies the Tokio runtime, TUN and discovery policy.
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::{sync::watch, task::JoinSet};
|
||||
use tsunagi::{
|
||||
Agent, AgentConfig, TransportPolicy, dataplane::transport::iroh_link::IrohCarrier,
|
||||
iroh_types::EndpointAddr,
|
||||
};
|
||||
use tsunagi_awg::{AWG_PROTOCOL, AWG_WIRE_VERSION, AwgPlugin, AwgTransport};
|
||||
use tsunagi_tcp_tls::{TCP_TLS_PROTOCOL, TcpTlsCarrier, TcpTlsConfig, TcpTlsTransport};
|
||||
use tsunagi_wireguard::WG_PROTOCOL;
|
||||
|
||||
pub mod report;
|
||||
|
||||
/// What a protocol is called, what it speaks, and what it takes.
|
||||
///
|
||||
/// A registry rather than a lookup on the plugins themselves, because
|
||||
/// `tsng protocols` has to answer before anything is constructed, and
|
||||
/// because this is the list `--protocol` resolves against.
|
||||
pub struct ProtocolSpec {
|
||||
/// The name on the wire, which is what peers compare.
|
||||
pub name: &'static str,
|
||||
/// The wire version. Not the software version: two peers on different
|
||||
/// builds carry traffic for each other as long as this matches.
|
||||
pub version: u16,
|
||||
/// One line about what it is.
|
||||
pub summary: &'static str,
|
||||
/// The settings it accepts.
|
||||
pub options: &'static [tsunagi::dataplane::ProtocolOption],
|
||||
}
|
||||
|
||||
const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::ProtocolOption {
|
||||
key: "port",
|
||||
value: "PORT",
|
||||
help: "preferred local UDP port; additional pairs use dynamic ports",
|
||||
default: Some("51820"),
|
||||
}];
|
||||
|
||||
/// Every protocol this build has.
|
||||
pub const PROTOCOLS: &[ProtocolSpec] = &[
|
||||
ProtocolSpec {
|
||||
name: WG_PROTOCOL,
|
||||
version: tsunagi_wireguard::WG_WIRE_VERSION,
|
||||
summary: "Pure WireGuard direct UDP transport",
|
||||
options: WG_OPTIONS,
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: AWG_PROTOCOL,
|
||||
version: AWG_WIRE_VERSION,
|
||||
summary: "Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt",
|
||||
options: AwgPlugin::OPTIONS,
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: "wg-quic",
|
||||
version: 1,
|
||||
summary: "iroh QUIC datagram carrier with NAT traversal and relays",
|
||||
options: &[],
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: TCP_TLS_PROTOCOL,
|
||||
version: tsunagi_tcp_tls::TCP_TLS_VERSION,
|
||||
summary: "TCP TLS 1.3 carrier",
|
||||
options: TcpTlsConfig::OPTIONS,
|
||||
},
|
||||
];
|
||||
|
||||
/// Incoming direct connections to attach after the agent has acquired its identity.
|
||||
pub struct Carriers {
|
||||
udp: [Arc<AwgTransport>; 2],
|
||||
tls: Arc<TcpTlsTransport>,
|
||||
}
|
||||
|
||||
impl Carriers {
|
||||
/// Register the complete catalog. CLI options and phone defaults use the same
|
||||
/// constructors and wire versions. Android supplies the addresses of its selected
|
||||
/// physical network; desktop discovers addresses on its host interfaces.
|
||||
pub async fn configure(
|
||||
mut config: AgentConfig,
|
||||
bootstrap: &[EndpointAddr],
|
||||
underlay: Option<watch::Receiver<Vec<IpAddr>>>,
|
||||
options: impl Fn(&ProtocolSpec) -> Vec<(String, String)>,
|
||||
) -> Result<(AgentConfig, Self), Box<dyn std::error::Error>> {
|
||||
let options_for = |name| {
|
||||
PROTOCOLS
|
||||
.iter()
|
||||
.find(|p| p.name == name)
|
||||
.map(&options)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let wg_opts = options_for(WG_PROTOCOL);
|
||||
let port = wg_opts
|
||||
.iter()
|
||||
.find(|(k, _)| k == "port")
|
||||
.map(|(_, v)| v.parse::<u16>())
|
||||
.transpose()?
|
||||
.unwrap_or(51820);
|
||||
let awg_opts = options_for(AWG_PROTOCOL);
|
||||
const STUN: &str = "stun.l.google.com:19302";
|
||||
let server = awg_opts
|
||||
.iter()
|
||||
.find(|(key, _)| key == "stun")
|
||||
.map_or(STUN, |(_, value)| value.as_str());
|
||||
if server.len() > 255 || (server != "off" && !server.contains(':')) {
|
||||
return Err("awg:stun must be HOST:PORT or off".into());
|
||||
}
|
||||
let public = config.transport != TransportPolicy::LocalOnly;
|
||||
let db = config.paths.state_db();
|
||||
let identity = tokio::task::spawn_blocking(move || {
|
||||
tsunagi::storage::StateStore::open(db)?.load_or_create_device_identity()
|
||||
})
|
||||
.await??;
|
||||
let bind = Ipv4Addr::UNSPECIFIED;
|
||||
let udp = [
|
||||
AwgTransport::wireguard_with_port(
|
||||
identity.endpoint_id(),
|
||||
bind,
|
||||
public.then(|| STUN.into()),
|
||||
port,
|
||||
),
|
||||
AwgTransport::new_with_stun(
|
||||
identity.endpoint_id(),
|
||||
bind,
|
||||
(public && server != "off").then(|| server.into()),
|
||||
),
|
||||
];
|
||||
for transport in &udp {
|
||||
transport.exclude_interface(config.interface_name.clone());
|
||||
if let Some(source) = &underlay {
|
||||
transport.set_underlay(source.clone());
|
||||
}
|
||||
config = config
|
||||
.with_carrier(AwgPlugin::new(transport.clone()))
|
||||
.with_custom_transport(transport.protocol_id(), transport.clone());
|
||||
}
|
||||
let settings =
|
||||
TcpTlsConfig::configure(TcpTlsConfig::new(), &options_for(TCP_TLS_PROTOCOL))?;
|
||||
let tls = Arc::new(
|
||||
TcpTlsTransport::bind(&identity, settings.port, settings.sni)
|
||||
.await
|
||||
.map_err(|error| -> Box<dyn std::error::Error> { error })?,
|
||||
);
|
||||
for address in bootstrap {
|
||||
for ip in address.ip_addrs() {
|
||||
tls.set_peer_addr(address.id, *ip);
|
||||
}
|
||||
}
|
||||
let carrier = TcpTlsCarrier::with_interface(tls.clone(), config.interface_name.clone());
|
||||
if let Some(source) = underlay {
|
||||
carrier.set_underlay(source);
|
||||
}
|
||||
config = config
|
||||
.with_carrier(Arc::new(IrohCarrier))
|
||||
.with_carrier(carrier)
|
||||
.with_custom_transport(TCP_TLS_PROTOCOL, tls.clone());
|
||||
Ok((config, Self { udp, tls }))
|
||||
}
|
||||
|
||||
/// Accept incoming authenticated links until the caller drops the returned task set.
|
||||
#[must_use = "keep the listeners alive for the lifetime of this agent"]
|
||||
pub fn listen(self, agent: &Agent) -> JoinSet<()> {
|
||||
let mut tasks = JoinSet::new();
|
||||
for transport in self.udp {
|
||||
let agent = agent.clone();
|
||||
tasks.spawn(async move {
|
||||
while let Some(inbound) = transport.next_inbound().await {
|
||||
if let Err(error) = agent.install_inbound_link(inbound).await {
|
||||
tracing::debug!(%error, protocol=transport.protocol_id(), "inbound link rejected");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let agent = agent.clone();
|
||||
tasks.spawn(async move {
|
||||
self.tls
|
||||
.accept_loop(move |inbound| {
|
||||
let agent = agent.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = agent.install_inbound_link(inbound).await {
|
||||
tracing::debug!(%error, "inbound tcp-tls link rejected");
|
||||
}
|
||||
});
|
||||
})
|
||||
.await;
|
||||
});
|
||||
tasks
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Combine the core snapshot and live WireGuard observations for local clients.
|
||||
use tsunagi::ipc::{MemberReport, NetworkReport, OverlayPeerReport, OverlayReport, PeerReport};
|
||||
use tsunagi::{AgentStatus, agent::OverlayStatus};
|
||||
use tsunagi_wg_quic::WireguardPlugin;
|
||||
|
||||
/// Build the same per-network view for an in-process client and the CLI's IPC server.
|
||||
pub fn networks(
|
||||
status: &AgentStatus,
|
||||
overlay: Option<&OverlayStatus>,
|
||||
wireguard: Option<&WireguardPlugin>,
|
||||
) -> Vec<NetworkReport> {
|
||||
status
|
||||
.networks
|
||||
.iter()
|
||||
.map(|network| {
|
||||
let wg_view = wireguard.and_then(|plugin| plugin.overview(network.network_id));
|
||||
let wg_overlay_addr = wg_view.as_ref().and_then(|v| v.overlay_address_v4);
|
||||
let wg_prefix_len = wg_view
|
||||
.as_ref()
|
||||
.and_then(|v| v.ipv4_range)
|
||||
.map_or(0, |r| r.prefix_len);
|
||||
let has_any_plugin = wg_view.is_some();
|
||||
|
||||
let overlay = if has_any_plugin && overlay.is_some() {
|
||||
let mut peers: Vec<OverlayPeerReport> = Vec::new();
|
||||
|
||||
if let Some(view) = &wg_view {
|
||||
for peer in &view.peers {
|
||||
let tunnel = peer.tunnel.as_ref();
|
||||
peers.push(OverlayPeerReport {
|
||||
counter_epoch: tunnel.map_or(0, |t| t.stats.counter_epoch),
|
||||
endpoint_id: peer.endpoint_id.to_string(),
|
||||
protocol: String::new(),
|
||||
public_key: peer.public_key.to_string(),
|
||||
address: peer.overlay_address_v4.map(|a| a.to_string()),
|
||||
handshake_secs_ago: tunnel
|
||||
.and_then(|t| t.health.since_handshake.map(|s| s.as_secs())),
|
||||
tx_packets: tunnel.map_or(0, |t| t.stats.tx_packets),
|
||||
rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets),
|
||||
tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes),
|
||||
rx_bytes: tunnel.map_or(0, |t| t.stats.rx_bytes),
|
||||
dropped: tunnel.map_or(0, |t| {
|
||||
t.stats.dropped_wrong_source + t.stats.dropped_oversize
|
||||
}),
|
||||
protocol_errors: tunnel.map_or(0, |t| t.stats.protocol_errors),
|
||||
path: tunnel.map_or_else(|| "no data path".into(), |t| t.path.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let (address, prefix_len) = if wg_overlay_addr.is_some() {
|
||||
(wg_overlay_addr.map(|addr| addr.to_string()), wg_prefix_len)
|
||||
} else {
|
||||
(
|
||||
network
|
||||
.members
|
||||
.iter()
|
||||
.find(|m| m.endpoint_id == status.endpoint_id)
|
||||
.and_then(|m| m.overlay_address_v4)
|
||||
.map(|a| a.to_string()),
|
||||
network.range.map_or(0, |r| r.prefix_len),
|
||||
)
|
||||
};
|
||||
|
||||
Some(OverlayReport {
|
||||
interface: overlay.map_or_else(String::new, |o| o.interface.clone()),
|
||||
on_host: overlay.is_some_and(|o| o.on_host),
|
||||
mtu: overlay.map_or(0, |o| o.mtu),
|
||||
address,
|
||||
prefix_len,
|
||||
peers,
|
||||
unroutable_packets: overlay.map_or(0, |o| o.counters.unroutable),
|
||||
multicast_packets: overlay.map_or(0, |o| o.counters.multicast),
|
||||
unroutable_sample: overlay
|
||||
.and_then(|o| o.counters.unroutable_sample.map(|a| a.to_string())),
|
||||
broadcast_rules: overlay.and_then(|o| o.broadcast_rules.as_ref()).map(
|
||||
|rules| tsunagi::ipc::HostRulesReport {
|
||||
ok: rules.is_ok(),
|
||||
detail: rules.summary(),
|
||||
source: rules.plan.source.to_string(),
|
||||
},
|
||||
),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
NetworkReport {
|
||||
vips: network.vips.clone(),
|
||||
protocols: network.protocols.clone(),
|
||||
auto_start: network.auto_start,
|
||||
exit: exit_report(network),
|
||||
broadcast: network.broadcast,
|
||||
name: network.name.to_string(),
|
||||
network_id: network.network_id.to_string(),
|
||||
active: matches!(network.state, tsunagi::agent::NetworkState::Active),
|
||||
candidates: network.candidates.len() as u32,
|
||||
relay_forwarded: network.relay.forwarded,
|
||||
relay_sent_via: network.relay.sent_via,
|
||||
relay_received_via: network.relay.received_via,
|
||||
peers: network
|
||||
.peers
|
||||
.iter()
|
||||
.map(|peer| PeerReport {
|
||||
data_error: peer.data_error.clone(),
|
||||
endpoint_id: peer.endpoint_id.to_string(),
|
||||
hostname: peer.hostname.clone(),
|
||||
transport: peer.transport.to_string(),
|
||||
rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64),
|
||||
data_rtt_ms: peer.data_rtt.map(|rtt| rtt.as_millis() as u64),
|
||||
data_transport_detail: peer.data_transport_detail.clone(),
|
||||
exit_node: peer.exit_node,
|
||||
path: data_path_report(&peer.data_path),
|
||||
})
|
||||
.collect(),
|
||||
members: network
|
||||
.members
|
||||
.iter()
|
||||
.map(|member| MemberReport {
|
||||
record_version: member.record_version,
|
||||
endpoint_id: member.endpoint_id.to_string(),
|
||||
overlay_address_v4: member.overlay_address_v4.map(|addr| addr.to_string()),
|
||||
// What this agent is currently experiencing trying to
|
||||
// reach it, so a dial-failure count can be attributed
|
||||
// to the member it belongs to instead of floating
|
||||
// free as a network-wide number.
|
||||
failed_dials: network
|
||||
.candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.endpoint_id == member.endpoint_id)
|
||||
.map_or(0, |candidate| candidate.consecutive_failures),
|
||||
hostname: member
|
||||
.last_hostname
|
||||
.clone()
|
||||
.or_else(|| member.hostname.clone()),
|
||||
online: member.online,
|
||||
path: data_path_report(&member.data_path),
|
||||
hostname_conflict: member.hostname_conflict.as_ref().map(conflict_report),
|
||||
})
|
||||
.collect(),
|
||||
range: network.range.map(|range| range.to_string()),
|
||||
range_conflict: network.range_conflict.map(|range| range.to_string()),
|
||||
range_conflicts: network
|
||||
.range_conflicts
|
||||
.iter()
|
||||
.map(|c| tsunagi::ipc::RangeConflictReport {
|
||||
network_id: c.network_id.to_string(),
|
||||
name: c.name.to_string(),
|
||||
range: c.range.to_string(),
|
||||
})
|
||||
.collect(),
|
||||
dial_failures: network.metrics.dial_failures,
|
||||
handshake_failures: network.metrics.handshake_failures,
|
||||
control_messages: (
|
||||
network.metrics.control_messages_sent,
|
||||
network.metrics.control_messages_received,
|
||||
),
|
||||
overlay,
|
||||
hostname_conflict: network.hostname_conflict.as_ref().map(conflict_report),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn data_path_report(path: &tsunagi::agent::DataPath) -> tsunagi::ipc::DataPathReport {
|
||||
match path {
|
||||
tsunagi::agent::DataPath::None => tsunagi::ipc::DataPathReport::None,
|
||||
tsunagi::agent::DataPath::Direct { transport } => tsunagi::ipc::DataPathReport::Direct {
|
||||
transport: transport.clone(),
|
||||
},
|
||||
tsunagi::agent::DataPath::Relayed { hops, via } => tsunagi::ipc::DataPathReport::Relayed {
|
||||
hops: *hops,
|
||||
via: via.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn conflict_report(
|
||||
conflict: &tsunagi::agent::HostnameConflict,
|
||||
) -> tsunagi::ipc::HostnameConflictReport {
|
||||
tsunagi::ipc::HostnameConflictReport {
|
||||
name: conflict.name.clone(),
|
||||
holder: conflict.holder.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One network's exit-node settings, as the control interface reports them.
|
||||
fn exit_report(network: &tsunagi::agent::NetworkStatus) -> tsunagi::ipc::ExitReport {
|
||||
let rules = |report: &Option<tsunagi::overlay::RuleSetReport>| {
|
||||
report.as_ref().map(|report| tsunagi::ipc::RuleSetReport {
|
||||
ok: report.ok,
|
||||
detail: report.detail.clone(),
|
||||
})
|
||||
};
|
||||
tsunagi::ipc::ExitReport {
|
||||
offering: network.exit_offer,
|
||||
offer_rules: rules(&network.exit_rules.offer),
|
||||
forwarding: network.exit_rules.forwarding,
|
||||
via: network.exit_via.map(|peer| peer.to_string()),
|
||||
via_online: network.exit_via_online,
|
||||
client_rules: rules(&network.exit_rules.client),
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -8,7 +8,7 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "0.1.0" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
||||
rustls = "0.23"
|
||||
|
||||
@@ -156,10 +156,7 @@ pub(crate) fn is_candidate_ip(addr: std::net::IpAddr) -> bool {
|
||||
}
|
||||
let segments = v6.segments();
|
||||
// Filter link-local fe80::/10
|
||||
if (segments[0] & 0xffc0) == 0xfe80 {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
(segments[0] & 0xffc0) != 0xfe80
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -238,6 +235,7 @@ impl TcpTlsConfig {
|
||||
pub struct TcpTlsCarrier {
|
||||
transport: Arc<TcpTlsTransport>,
|
||||
excluded_interface: std::sync::Mutex<Option<String>>,
|
||||
underlay: std::sync::OnceLock<tokio::sync::watch::Receiver<Vec<std::net::IpAddr>>>,
|
||||
peers: std::sync::Mutex<
|
||||
std::collections::HashMap<(NetworkId, EndpointId), Vec<std::net::SocketAddr>>,
|
||||
>,
|
||||
@@ -248,6 +246,7 @@ impl TcpTlsCarrier {
|
||||
Arc::new(Self {
|
||||
transport,
|
||||
excluded_interface: std::sync::Mutex::new(None),
|
||||
underlay: Default::default(),
|
||||
peers: Default::default(),
|
||||
})
|
||||
}
|
||||
@@ -256,9 +255,14 @@ impl TcpTlsCarrier {
|
||||
Arc::new(Self {
|
||||
transport,
|
||||
excluded_interface: std::sync::Mutex::new(Some(interface)),
|
||||
underlay: Default::default(),
|
||||
peers: Default::default(),
|
||||
})
|
||||
}
|
||||
/// Use only the addresses assigned to the OS-selected physical network.
|
||||
pub fn set_underlay(&self, source: tokio::sync::watch::Receiver<Vec<std::net::IpAddr>>) {
|
||||
let _ = self.underlay.set(source);
|
||||
}
|
||||
fn update_peer(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
@@ -302,17 +306,23 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
&self,
|
||||
_: NetworkId,
|
||||
) -> Result<Option<tsunagi::dataplane::PluginCapability>, PluginError> {
|
||||
let data = postcard::to_allocvec(&(
|
||||
self.transport.bound_port(),
|
||||
local_ip_candidates_excluding(
|
||||
let ips = match self.underlay.get() {
|
||||
Some(source) => source
|
||||
.borrow()
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|ip| is_candidate_ip(*ip))
|
||||
.collect(),
|
||||
None => local_ip_candidates_excluding(
|
||||
self.excluded_interface
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.as_deref(),
|
||||
)
|
||||
.into_iter()
|
||||
.take(32)
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
};
|
||||
let data = postcard::to_allocvec(&(
|
||||
self.transport.bound_port(),
|
||||
ips.into_iter().take(32).collect::<Vec<_>>(),
|
||||
))
|
||||
.map_err(|_| PluginError::Other("cannot encode TLS addresses".into()))?;
|
||||
Ok(Some(tsunagi::dataplane::PluginCapability {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tray"
|
||||
version = "0.1.0"
|
||||
version = "1.0.2"
|
||||
description = "Tray application to manage a running tsunagi agent."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -12,14 +12,17 @@ name = "tsunagi-tray"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||
# The agent control client and the report types: the GUI is a thin client over
|
||||
# the same local control interface the CLI uses, so it reuses these directly
|
||||
# and never re-implements the protocol.
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "0.1.0" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" }
|
||||
# Native, lightweight GUI — no web engine. eframe re-exports egui.
|
||||
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
|
||||
# Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
|
||||
tray-icon = "0.21"
|
||||
# libxdo only implements predefined Copy/Cut/Paste/SelectAll menu actions,
|
||||
# which this tray does not use. Avoid a distro-specific libxdo SONAME dependency.
|
||||
tray-icon = { version = "0.21", default-features = false }
|
||||
# Background worker that talks to the agent off the UI thread.
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -14,76 +14,21 @@ use std::time::{Duration, Instant};
|
||||
use eframe::egui;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use tsunagi::ipc::{self, StatusReport};
|
||||
use tsunagi::ipc;
|
||||
|
||||
/// How often the worker refreshes status while idle.
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// A request from the UI to the agent.
|
||||
pub(crate) enum Command {
|
||||
SaveVip {
|
||||
token: String,
|
||||
network_id: String,
|
||||
config: tsunagi::vip::VipConfig,
|
||||
expected: Option<String>,
|
||||
delete: bool,
|
||||
},
|
||||
/// Retire the exact offline-node claim selected in the devices window.
|
||||
ForgetNode {
|
||||
network_id: String,
|
||||
peer: String,
|
||||
expected_version: u64,
|
||||
},
|
||||
/// Replace the network's enabled protocols in preference order.
|
||||
SetProtocols {
|
||||
network_id: String,
|
||||
protocols: Vec<String>,
|
||||
},
|
||||
/// Stop serving a network, or start serving it again.
|
||||
SetActive { network_id: String, active: bool },
|
||||
/// Turn local broadcast participation on or off for a network.
|
||||
SetBroadcast { network_id: String, enabled: bool },
|
||||
/// Offer this device as an exit node in a network, or stop.
|
||||
SetExitOffer { network_id: String, enabled: bool },
|
||||
/// Send all this device's internet traffic through a member of a
|
||||
/// network, or (`None`) back the ordinary way.
|
||||
SetExitNode {
|
||||
network_id: String,
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Join a network, or start one already configured.
|
||||
Join { name: String, secret: String },
|
||||
/// Leave a network entirely.
|
||||
Leave { network_id: String },
|
||||
/// Change the hostname this device announces.
|
||||
SetHostname(String),
|
||||
/// Fetch a network's shared secret and place it on the clipboard.
|
||||
CopySecret { network_id: String },
|
||||
}
|
||||
use tsunagi_ui::client::Client;
|
||||
pub(crate) use tsunagi_ui::client::{Command, Snapshot, VipSaveResult};
|
||||
|
||||
/// The latest the worker knows, read by the UI each frame.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct VipSaveResult {
|
||||
pub token: String,
|
||||
pub result: Result<Vec<tsunagi::vip::VipStatus>, String>,
|
||||
}
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct Snapshot {
|
||||
pub vip_result: Option<VipSaveResult>,
|
||||
/// The last status, or the reason it could not be read (agent down, no
|
||||
/// permission on the socket, …).
|
||||
pub status: Option<Result<StatusReport, String>>,
|
||||
/// The outcome of the most recent command, for a transient banner.
|
||||
pub last_action: Option<Result<String, String>>,
|
||||
/// Whether a command is currently being executed.
|
||||
pub busy: bool,
|
||||
/// Bumped each time `status` is refreshed, so the UI can tell new data from
|
||||
/// a repaint of the same data and sample traffic rates only on change.
|
||||
pub generation: u64,
|
||||
/// When this status was read, for computing rates between refreshes.
|
||||
pub at: Option<Instant>,
|
||||
/// The socket the last request went to.
|
||||
pub socket: PathBuf,
|
||||
impl Client for AgentClient {
|
||||
fn send(&self, command: Command) {
|
||||
self.send(command);
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
lock(&self.shared).busy
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle the UI holds: send commands, read the latest snapshot.
|
||||
@@ -97,18 +42,6 @@ pub(crate) struct AgentClient {
|
||||
}
|
||||
|
||||
impl AgentClient {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_client() -> (Self, mpsc::UnboundedReceiver<Command>) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
(
|
||||
Self {
|
||||
tx,
|
||||
shared: Arc::new(Mutex::new(Snapshot::default())),
|
||||
pending_copy: Arc::new(Mutex::new(None)),
|
||||
},
|
||||
rx,
|
||||
)
|
||||
}
|
||||
/// Starts the worker on `runtime`, reporting to `ctx` (for repaints).
|
||||
pub(crate) fn spawn(runtime: &tokio::runtime::Handle, ctx: egui::Context) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
@@ -203,7 +136,7 @@ async fn refresh(shared: &Arc<Mutex<Snapshot>>, ctx: &egui::Context) {
|
||||
.map_err(|err| err.to_string());
|
||||
{
|
||||
let mut guard = lock(shared);
|
||||
guard.status = Some(status);
|
||||
guard.status = Some(status.map(Arc::new));
|
||||
guard.generation = guard.generation.wrapping_add(1);
|
||||
guard.at = Some(Instant::now());
|
||||
guard.socket = socket;
|
||||
|
||||
@@ -15,11 +15,7 @@ use crate::devices;
|
||||
use crate::stats::Traffic;
|
||||
use crate::ui::{self, UiState};
|
||||
|
||||
fn app_fonts() -> egui::FontDefinitions {
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
|
||||
fonts
|
||||
}
|
||||
use tsunagi_ui::app_fonts;
|
||||
|
||||
/// The window's state.
|
||||
pub(crate) struct App {
|
||||
@@ -140,7 +136,7 @@ impl App {
|
||||
egui::ViewportId::from_hash_of("about"),
|
||||
builder,
|
||||
|vctx, _class| {
|
||||
about::show(vctx, &socket, snapshot);
|
||||
about::show(vctx, Some(&socket), snapshot);
|
||||
!vctx.input(|i| i.viewport().close_requested())
|
||||
},
|
||||
);
|
||||
|
||||
@@ -78,7 +78,7 @@ fn colour_of(health: Health) -> [u8; 3] {
|
||||
match health {
|
||||
Health::Disconnected => DARK_RED,
|
||||
Health::Connected => BLUE,
|
||||
Health::RangeConflict => [0xd9, 0x91, 0x20],
|
||||
Health::RangeConflict | Health::InterfaceError => [0xd9, 0x91, 0x20],
|
||||
Health::ExitNode => GREEN,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,19 +9,15 @@
|
||||
// Nothing here is a library.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod about;
|
||||
use tsunagi_ui::about;
|
||||
mod agent;
|
||||
mod app;
|
||||
mod devices;
|
||||
mod exit;
|
||||
mod format;
|
||||
use tsunagi_ui::devices;
|
||||
mod icon;
|
||||
mod stats;
|
||||
mod table;
|
||||
use tsunagi_ui::stats;
|
||||
mod tray;
|
||||
mod ui;
|
||||
mod vip;
|
||||
mod vip_status;
|
||||
use tsunagi_ui::vip;
|
||||
mod watch;
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
@@ -3,67 +3,22 @@
|
||||
//! [`crate::devices`]), opened from each tile.
|
||||
//!
|
||||
//! Pure rendering: state comes from the snapshot and the traffic sampler, a
|
||||
//! change to a switch or button sends a [`Command`] to the worker, and local UI
|
||||
//! change to a switch or button sends a [`tsunagi_ui::client::Command`] to the worker, and local UI
|
||||
//! state (the join form, the unit toggle, which devices windows are open, an
|
||||
//! in-progress hostname edit) lives in [`UiState`].
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
pub(crate) use tsunagi_ui::home::UiState;
|
||||
use tsunagi_ui::home::{draw_header, draw_join, draw_network};
|
||||
|
||||
use eframe::egui;
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||
|
||||
use crate::agent::{AgentClient, Command, Snapshot};
|
||||
use crate::agent::{AgentClient, Snapshot};
|
||||
use crate::devices;
|
||||
use crate::exit;
|
||||
use crate::format;
|
||||
use crate::stats::{Traffic, Unit};
|
||||
|
||||
const OK: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a);
|
||||
const BAD: egui::Color32 = egui::Color32::from_rgb(0xd0, 0x4a, 0x3c);
|
||||
/// A neutral, not-garish red for the Leave button.
|
||||
const LEAVE_RED: egui::Color32 = egui::Color32::from_rgb(0xa8, 0x3a, 0x3a);
|
||||
|
||||
/// Join form fields.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct JoinForm {
|
||||
pub(crate) name: String,
|
||||
pub(crate) secret: String,
|
||||
}
|
||||
|
||||
/// Local UI state kept across frames.
|
||||
pub(crate) struct UiState {
|
||||
pub(crate) join: JoinForm,
|
||||
/// Whether rates and sparklines are shown in packets or bytes.
|
||||
pub(crate) unit: Unit,
|
||||
/// An in-progress hostname edit (`None` when not editing).
|
||||
pub(crate) host_edit: Option<String>,
|
||||
/// Network ids whose devices window is open.
|
||||
pub(crate) open_devices: BTreeSet<String>,
|
||||
pub(crate) vip_windows: std::collections::BTreeMap<String, crate::vip::Window>,
|
||||
/// Whether the About window is open.
|
||||
pub(crate) about_open: bool,
|
||||
/// An exit-node choice waiting for the user to confirm it.
|
||||
pub(crate) exit_confirm: Option<devices::ExitConfirm>,
|
||||
/// A selected offline claim waiting for cleanup confirmation.
|
||||
pub(crate) forget_confirm: Option<devices::ForgetConfirm>,
|
||||
}
|
||||
|
||||
impl Default for UiState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
join: JoinForm::default(),
|
||||
unit: Unit::Packets,
|
||||
host_edit: None,
|
||||
open_devices: BTreeSet::new(),
|
||||
vip_windows: Default::default(),
|
||||
about_open: false,
|
||||
exit_confirm: None,
|
||||
forget_confirm: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the main window.
|
||||
pub(crate) fn draw(
|
||||
@@ -128,7 +83,7 @@ pub(crate) fn draw(
|
||||
ui.weak("No networks yet — join one below.");
|
||||
}
|
||||
for network in &report.networks {
|
||||
draw_network(ui, agent, state, traffic, network, report);
|
||||
draw_network(ui, agent, state, traffic, network, report, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -154,350 +109,3 @@ fn draw_unreachable(ui: &mut egui::Ui, agent: &AgentClient, error: &str) {
|
||||
(its group, mode 0660).",
|
||||
);
|
||||
}
|
||||
|
||||
/// The device header: id (with a copy button) and an editable hostname.
|
||||
fn draw_header(ui: &mut egui::Ui, agent: &AgentClient, state: &mut UiState, report: &StatusReport) {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.weak("device");
|
||||
// Clicking the shortened id copies the full one.
|
||||
format::copy_field(ui, &format::short(&report.endpoint_id), &report.endpoint_id);
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.weak("host");
|
||||
match &mut state.host_edit {
|
||||
None => {
|
||||
ui.label(&report.hostname);
|
||||
if ui
|
||||
.small_button(icon::PENCIL_SIMPLE)
|
||||
.on_hover_text("rename")
|
||||
.clicked()
|
||||
{
|
||||
state.host_edit = Some(report.hostname.clone());
|
||||
}
|
||||
}
|
||||
Some(buffer) => {
|
||||
let response = ui.add(egui::TextEdit::singleline(buffer).desired_width(150.0));
|
||||
let submit = (response.lost_focus()
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Enter)))
|
||||
|| ui.small_button(icon::CHECK).on_hover_text("save").clicked();
|
||||
if submit {
|
||||
agent.send(Command::SetHostname(buffer.trim().to_string()));
|
||||
state.host_edit = None;
|
||||
} else if ui.small_button(icon::X).on_hover_text("cancel").clicked() {
|
||||
state.host_edit = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if !report.cache_healthy {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(0xd9, 0x9a, 0x00),
|
||||
"cache unavailable",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One compact network tile.
|
||||
fn draw_network(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &AgentClient,
|
||||
state: &mut UiState,
|
||||
traffic: &Traffic,
|
||||
network: &NetworkReport,
|
||||
report: &StatusReport,
|
||||
) {
|
||||
ui.add_space(6.0);
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
format::copy_field(ui, network.name.as_str(), &network.name);
|
||||
if ui.button("VIP").clicked(){state.vip_windows.entry(network.network_id.clone()).or_default();}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let leave =
|
||||
egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE))
|
||||
.fill(LEAVE_RED);
|
||||
if ui.add(leave).clicked() {
|
||||
agent.send(Command::Leave {
|
||||
network_id: network.network_id.clone(),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let address = network.overlay.as_ref().and_then(|o| o.address.as_ref());
|
||||
let series = traffic.network(&network.network_id);
|
||||
|
||||
egui::Grid::new(("net", &network.network_id))
|
||||
.num_columns(2)
|
||||
.spacing([10.0, 3.0])
|
||||
.show(ui, |ui| {
|
||||
ui.weak("id");
|
||||
format::copy_field(ui, &format::short(&network.network_id), &network.network_id);
|
||||
ui.end_row();
|
||||
|
||||
if let Some(range) = &network.range {
|
||||
ui.weak("range");
|
||||
format::copy_field(ui, range, range);
|
||||
ui.end_row();
|
||||
}
|
||||
if let Some(address) = address {
|
||||
ui.weak("addr");
|
||||
format::copy_field(ui, address, address);
|
||||
ui.end_row();
|
||||
}
|
||||
ui.weak("peers");
|
||||
ui.label(format!(
|
||||
"{} online · {} known",
|
||||
devices::online_count(network, &report.endpoint_id),
|
||||
devices::known_count(network, &report.endpoint_id)
|
||||
));
|
||||
ui.end_row();
|
||||
});
|
||||
|
||||
draw_protocols(ui, agent, network, &report.available_protocols);
|
||||
|
||||
format::sparkline(ui, series, state.unit, 34.0);
|
||||
|
||||
if !network.range_conflicts.is_empty() {
|
||||
ui.colored_label(BAD, "Stopped: overlapping network ranges");
|
||||
for conflict in &network.range_conflicts {
|
||||
ui.label(format!("{} ({}) uses {}", conflict.name, conflict.network_id, conflict.range));
|
||||
}
|
||||
ui.label("Switching suspends these networks until this network stops, then resumes them automatically.");
|
||||
if network.auto_start { ui.weak("This network will resume automatically when its range is free."); }
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if !network.active && !network.range_conflicts.is_empty() {
|
||||
if ui.button("Switch to this network").clicked() {
|
||||
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: true });
|
||||
}
|
||||
if network.auto_start && ui.button("Keep stopped").clicked() {
|
||||
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: false });
|
||||
}
|
||||
} else {
|
||||
let mut active = network.active;
|
||||
if ui.checkbox(&mut active, "active").changed() {
|
||||
agent.send(Command::SetActive {
|
||||
network_id: network.network_id.clone(),
|
||||
active,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut broadcast = network.broadcast;
|
||||
if ui.checkbox(&mut broadcast, "broadcast").changed() {
|
||||
agent.send(Command::SetBroadcast {
|
||||
network_id: network.network_id.clone(),
|
||||
enabled: broadcast,
|
||||
});
|
||||
}
|
||||
let mut offering = network.exit.offering;
|
||||
if ui
|
||||
.checkbox(&mut offering, "exit node")
|
||||
.on_hover_text(
|
||||
"let other members send all their internet traffic through this \
|
||||
device, which can see it",
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
agent.send(Command::SetExitOffer {
|
||||
network_id: network.network_id.clone(),
|
||||
enabled: offering,
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
// In the bottom left corner while this device sends its traffic through
|
||||
// somebody: green while that works, red while it does not.
|
||||
if let Some(via) = &network.exit.via {
|
||||
let color = if network.exit.via_online {
|
||||
exit::GOOD
|
||||
} else {
|
||||
exit::LOUD
|
||||
};
|
||||
let response = ui
|
||||
.add(
|
||||
egui::Label::new(
|
||||
egui::RichText::new(icon::SIGN_OUT).size(18.0).color(color),
|
||||
)
|
||||
.sense(egui::Sense::click()),
|
||||
)
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text(format!(
|
||||
"exit node: {} — click to stop",
|
||||
exit::name_of(network, via)
|
||||
));
|
||||
if response.clicked() {
|
||||
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
|
||||
}
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Show devices").clicked() {
|
||||
state.open_devices.insert(network.network_id.clone());
|
||||
}
|
||||
if ui
|
||||
.button(format!("{} Copy secret", icon::COPY))
|
||||
.on_hover_text("copy this network's secret to the clipboard")
|
||||
.clicked()
|
||||
{
|
||||
agent.send(Command::CopySecret {
|
||||
network_id: network.network_id.clone(),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
for warning in exit::warnings(network) {
|
||||
draw_exit_warning(ui, &warning);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn draw_protocols(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &AgentClient,
|
||||
network: &NetworkReport,
|
||||
available: &[tsunagi::ipc::ProtocolReport],
|
||||
) {
|
||||
let summary = if network.protocols.is_empty() {
|
||||
"none".into()
|
||||
} else {
|
||||
network.protocols.join(", ")
|
||||
};
|
||||
egui::CollapsingHeader::new(format!("data transports {summary}"))
|
||||
.id_salt(("protocols", &network.network_id))
|
||||
.show(ui, |ui| {
|
||||
ui.weak("Preference order; changes apply immediately and are saved.");
|
||||
let mut selected = network.protocols.clone();
|
||||
let mut changed = false;
|
||||
ui.add_enabled_ui(!agent.snapshot().busy, |ui| {
|
||||
// Enabled items follow the user's preference; unchecked items
|
||||
// follow the agent's catalog. The worker refreshes after edits.
|
||||
let ordered: Vec<_> = network
|
||||
.protocols
|
||||
.iter()
|
||||
.filter_map(|name| available.iter().find(|p| &p.name == name))
|
||||
.chain(
|
||||
available
|
||||
.iter()
|
||||
.filter(|p| !network.protocols.contains(&p.name)),
|
||||
)
|
||||
.collect();
|
||||
for protocol in ordered {
|
||||
ui.horizontal(|ui| {
|
||||
let mut on = selected.contains(&protocol.name);
|
||||
if ui.checkbox(&mut on, &protocol.name).changed() {
|
||||
if on {
|
||||
selected.push(protocol.name.clone());
|
||||
} else {
|
||||
selected.retain(|p| p != &protocol.name);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if let Some(index) = selected.iter().position(|p| p == &protocol.name) {
|
||||
if ui
|
||||
.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP))
|
||||
.on_hover_text("prefer earlier")
|
||||
.clicked()
|
||||
{
|
||||
selected.swap(index, index - 1);
|
||||
changed = true;
|
||||
}
|
||||
if ui
|
||||
.add_enabled(
|
||||
index + 1 < selected.len(),
|
||||
egui::Button::new(icon::ARROW_DOWN),
|
||||
)
|
||||
.on_hover_text("prefer later")
|
||||
.clicked()
|
||||
{
|
||||
selected.swap(index, index + 1);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.indent(("description", &network.network_id, &protocol.name), |ui| {
|
||||
ui.weak(&protocol.summary);
|
||||
});
|
||||
}
|
||||
});
|
||||
if selected.is_empty() {
|
||||
ui.weak("Control only; no IP traffic in this network.");
|
||||
}
|
||||
if changed {
|
||||
agent.send(Command::SetProtocols {
|
||||
network_id: network.network_id.clone(),
|
||||
protocols: selected,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A prominent line about an exit node. One that carries a command copies it
|
||||
/// when clicked.
|
||||
fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) {
|
||||
let text = egui::RichText::new(format!("{} {}", icon::WARNING, warning.text))
|
||||
.color(exit::LOUD)
|
||||
.strong();
|
||||
let label = egui::Label::new(text).wrap();
|
||||
match warning.copy {
|
||||
Some(command) => {
|
||||
let response = ui
|
||||
.add(label.sense(egui::Sense::click()))
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text("click to copy the command");
|
||||
if response.clicked() {
|
||||
ui.ctx().copy_text(command.to_owned());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.add(label);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The join form: aligned name and secret, a generate button, and Join.
|
||||
fn draw_join(ui: &mut egui::Ui, agent: &AgentClient, join: &mut JoinForm) {
|
||||
const INPUT_WIDTH: f32 = 208.0;
|
||||
ui.label("Join or create a network");
|
||||
egui::Grid::new("join")
|
||||
.num_columns(2)
|
||||
.spacing([8.0, 6.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label("name");
|
||||
ui.add(egui::TextEdit::singleline(&mut join.name).desired_width(INPUT_WIDTH));
|
||||
ui.end_row();
|
||||
|
||||
ui.label("secret");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut join.secret)
|
||||
.desired_width(INPUT_WIDTH - 26.0)
|
||||
.password(true),
|
||||
);
|
||||
if ui
|
||||
.button(icon::SHUFFLE)
|
||||
.on_hover_text("Generate a new random secret")
|
||||
.clicked()
|
||||
{
|
||||
join.secret = tsunagi::identity::NetworkSecret::generate()
|
||||
.encode()
|
||||
.as_str()
|
||||
.to_owned();
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
|
||||
let ready = !join.name.trim().is_empty() && !join.secret.trim().is_empty();
|
||||
if ui
|
||||
.add_enabled(ready, egui::Button::new("Join / create"))
|
||||
.clicked()
|
||||
{
|
||||
agent.send(Command::Join {
|
||||
name: join.name.trim().to_string(),
|
||||
secret: join.secret.trim().to_string(),
|
||||
});
|
||||
join.secret.clear();
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ pub(crate) enum Health {
|
||||
Disconnected,
|
||||
/// Connected, nothing out of the ordinary.
|
||||
Connected,
|
||||
/// The shared host interface could not apply its addresses or routes.
|
||||
InterfaceError,
|
||||
/// At least one configured network is blocked by an overlapping active range.
|
||||
RangeConflict,
|
||||
/// This device's traffic leaves through an exit node, and that works.
|
||||
@@ -35,6 +37,9 @@ impl Health {
|
||||
let Some(report) = report else {
|
||||
return Self::Disconnected;
|
||||
};
|
||||
if report.overlay_config_error.is_some() {
|
||||
return Self::InterfaceError;
|
||||
}
|
||||
if report
|
||||
.networks
|
||||
.iter()
|
||||
@@ -65,6 +70,7 @@ impl Health {
|
||||
match self {
|
||||
Self::Disconnected => "tsunagi: not connected",
|
||||
Self::Connected => "tsunagi: connected",
|
||||
Self::InterfaceError => "tsunagi: overlay interface configuration failed",
|
||||
Self::RangeConflict => "tsunagi: network range conflict; open to switch networks",
|
||||
Self::ExitNode => "tsunagi: using an exit node",
|
||||
}
|
||||
@@ -118,6 +124,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_interface_error_is_visible_even_with_connected_peers() {
|
||||
let mut status = report(vec![network(2, ExitReport::default())]);
|
||||
status.overlay_config_error = Some("utun5: could not install subnet route".into());
|
||||
assert_eq!(Health::of(Some(&status)), Health::InterfaceError);
|
||||
status.overlay_config_error = None;
|
||||
assert_eq!(Health::of(Some(&status)), Health::Connected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_networks_are_visible_even_while_other_peers_are_connected() {
|
||||
let mut blocked = NetworkReport {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.2"
|
||||
description = "Shared egui widgets for the tray and Android clients."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
egui = "0.31"
|
||||
egui-phosphor = "0.9"
|
||||
zeroize = "1.9"
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -4,11 +4,9 @@
|
||||
//! half is whatever the agent says about itself, so a client and an agent that
|
||||
//! are not the same build show up as such.
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
use tsunagi::ipc::{PrivilegeReport, StatusReport};
|
||||
|
||||
use crate::agent::Snapshot;
|
||||
use crate::client::Snapshot;
|
||||
use crate::format;
|
||||
|
||||
const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
|
||||
@@ -16,7 +14,7 @@ const AUTHOR: &str = "AB <tsunagi@hexor.cy>";
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Draws the window body into its viewport.
|
||||
pub(crate) fn show(ctx: &egui::Context, socket: &std::path::Path, snapshot: &Snapshot) {
|
||||
pub fn show(ctx: &egui::Context, socket: Option<&std::path::Path>, snapshot: &Snapshot) {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
// Long paths and a taller agent table must scroll rather than be cut.
|
||||
egui::ScrollArea::both()
|
||||
@@ -25,7 +23,7 @@ pub(crate) fn show(ctx: &egui::Context, socket: &std::path::Path, snapshot: &Sna
|
||||
});
|
||||
}
|
||||
|
||||
fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) {
|
||||
fn body(ui: &mut egui::Ui, socket: Option<&std::path::Path>, snapshot: &Snapshot) {
|
||||
{
|
||||
ui.horizontal(|ui| {
|
||||
ui.heading("tsunagi");
|
||||
@@ -61,11 +59,13 @@ fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) {
|
||||
|
||||
ui.add_space(8.0);
|
||||
section(ui, "agent");
|
||||
let socket = socket.display().to_string();
|
||||
let socket = socket.map(|p| p.display().to_string());
|
||||
match &snapshot.status {
|
||||
None => {
|
||||
grid(ui, "about agent", |ui| {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, &socket, &socket));
|
||||
if let Some(socket) = &socket {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
||||
}
|
||||
row(ui, "state", |ui| {
|
||||
ui.label("connecting…");
|
||||
});
|
||||
@@ -73,7 +73,9 @@ fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) {
|
||||
}
|
||||
Some(Err(error)) => {
|
||||
grid(ui, "about agent", |ui| {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, &socket, &socket));
|
||||
if let Some(socket) = &socket {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
||||
}
|
||||
row(ui, "state", |ui| {
|
||||
ui.colored_label(egui::Color32::from_rgb(0xd8, 0x4a, 0x3a), "unreachable");
|
||||
});
|
||||
@@ -82,14 +84,16 @@ fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) {
|
||||
});
|
||||
});
|
||||
}
|
||||
Some(Ok(report)) => agent_table(ui, &socket, report),
|
||||
Some(Ok(report)) => agent_table(ui, socket.as_deref(), report),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn agent_table(ui: &mut egui::Ui, socket: &str, report: &StatusReport) {
|
||||
fn agent_table(ui: &mut egui::Ui, socket: Option<&str>, report: &StatusReport) {
|
||||
grid(ui, "about agent", |ui| {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
||||
if let Some(socket) = socket {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
||||
}
|
||||
row(ui, "state", |ui| {
|
||||
ui.colored_label(egui::Color32::from_rgb(0x3c, 0xb0, 0x4a), "connected");
|
||||
});
|
||||
@@ -134,7 +138,11 @@ fn agent_table(ui: &mut egui::Ui, socket: &str, report: &StatusReport) {
|
||||
ui.weak("unknown");
|
||||
}
|
||||
PrivilegeReport::Available => {
|
||||
ui.label("can be managed (CAP_NET_ADMIN)");
|
||||
ui.label(if socket.is_some() {
|
||||
"can be managed (CAP_NET_ADMIN)"
|
||||
} else {
|
||||
"Android VPN service"
|
||||
});
|
||||
}
|
||||
PrivilegeReport::Missing(_) => {
|
||||
ui.colored_label(egui::Color32::from_rgb(0xd8, 0x9a, 0x2a), "no privileges");
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Commands and observations shared by both graphical clients.
|
||||
use std::{path::PathBuf, time::Instant};
|
||||
use tsunagi::ipc::StatusReport;
|
||||
|
||||
/// A request from the UI to the agent.
|
||||
pub enum Command {
|
||||
/// Commit one complete VIP draft if its revision is current.
|
||||
SaveVip {
|
||||
/// Local acknowledgement token for this Save.
|
||||
token: String,
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Complete edited configuration.
|
||||
config: tsunagi::vip::VipConfig,
|
||||
/// Revision originally opened in the form.
|
||||
expected: Option<String>,
|
||||
/// Retire this revision when saved.
|
||||
delete: bool,
|
||||
},
|
||||
/// Retire the exact offline-node claim selected in the devices window.
|
||||
ForgetNode {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Selected member identity.
|
||||
peer: String,
|
||||
/// Observed claim version.
|
||||
expected_version: u64,
|
||||
},
|
||||
/// Replace the network's enabled protocols in preference order.
|
||||
SetProtocols {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Enabled transports in preference order.
|
||||
protocols: Vec<String>,
|
||||
},
|
||||
/// Stop serving a network, or start serving it again.
|
||||
SetActive {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Whether to run the network.
|
||||
active: bool,
|
||||
},
|
||||
/// Turn local broadcast participation on or off for a network.
|
||||
SetBroadcast {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Requested local setting.
|
||||
enabled: bool,
|
||||
},
|
||||
/// Offer this device as an exit node in a network, or stop.
|
||||
SetExitOffer {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Requested local setting.
|
||||
enabled: bool,
|
||||
},
|
||||
/// Send all this device's internet traffic through a member of a
|
||||
/// network, or (`None`) back the ordinary way.
|
||||
SetExitNode {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Selected member identity.
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Join a network, or start one already configured.
|
||||
Join {
|
||||
/// Network name.
|
||||
name: String,
|
||||
/// Locally supplied join secret.
|
||||
secret: zeroize::Zeroizing<String>,
|
||||
},
|
||||
/// Leave a network entirely.
|
||||
Leave {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
},
|
||||
/// Change the hostname this device announces.
|
||||
SetHostname(String),
|
||||
/// Fetch a network's shared secret and place it on the clipboard.
|
||||
CopySecret {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Response to one revision-checked VIP write.
|
||||
#[derive(Clone)]
|
||||
pub struct VipSaveResult {
|
||||
/// Request being acknowledged.
|
||||
pub token: String,
|
||||
/// Current VIPs or the error for this draft.
|
||||
pub result: Result<Vec<tsunagi::vip::VipStatus>, String>,
|
||||
}
|
||||
/// Current observations and last command outcome from a local agent.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Snapshot {
|
||||
/// Most recent saved draft.
|
||||
pub vip_result: Option<VipSaveResult>,
|
||||
/// The last status, or the reason it could not be read (agent down, no
|
||||
/// permission on the socket, …).
|
||||
pub status: Option<Result<std::sync::Arc<StatusReport>, String>>,
|
||||
/// The outcome of the most recent command, for a transient banner.
|
||||
pub last_action: Option<Result<String, String>>,
|
||||
/// Whether a command is currently being executed.
|
||||
pub busy: bool,
|
||||
/// Bumped each time `status` is refreshed, so the UI can tell new data from
|
||||
/// a repaint of the same data and sample traffic rates only on change.
|
||||
pub generation: u64,
|
||||
/// When this status was read, for computing rates between refreshes.
|
||||
pub at: Option<Instant>,
|
||||
/// The socket the last request went to.
|
||||
pub socket: PathBuf,
|
||||
}
|
||||
|
||||
/// Delivers a user gesture to the owning worker without blocking the UI.
|
||||
pub trait Client {
|
||||
/// Queue an action from a form.
|
||||
fn send(&self, command: Command);
|
||||
/// An earlier action is waiting for an acknowledgement.
|
||||
fn busy(&self) -> bool;
|
||||
}
|
||||
@@ -6,13 +6,16 @@
|
||||
//! the main window.
|
||||
|
||||
use std::collections::HashMap;
|
||||
mod compact;
|
||||
mod exit_picker;
|
||||
pub use crate::exit::name_of;
|
||||
pub use exit_picker::choose_exit;
|
||||
|
||||
use eframe::egui;
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
use tsunagi::ipc::{DataPathReport, NetworkReport, OverlayPeerReport};
|
||||
|
||||
use crate::agent::{AgentClient, Command};
|
||||
use crate::client::{Client, Command};
|
||||
use crate::exit;
|
||||
use crate::format;
|
||||
use crate::stats::{Traffic, Unit};
|
||||
@@ -22,7 +25,7 @@ use crate::stats::{Traffic, Unit};
|
||||
const AMBER: egui::Color32 = egui::Color32::from_rgb(0xd9, 0xa4, 0x2c);
|
||||
|
||||
/// A readable title for a network's window.
|
||||
pub(crate) fn title(network: &NetworkReport) -> String {
|
||||
pub fn title(network: &NetworkReport) -> String {
|
||||
format!("tsunagi · {}", network.name)
|
||||
}
|
||||
|
||||
@@ -49,6 +52,8 @@ struct Device<'a> {
|
||||
data_error: Option<&'a str>,
|
||||
address: Option<String>,
|
||||
control_rtt_ms: Option<u64>,
|
||||
data_rtt_ms: Option<u64>,
|
||||
data_transport_detail: Option<&'a str>,
|
||||
overlay: Option<&'a OverlayPeerReport>,
|
||||
/// It is connected and offers to be an exit node.
|
||||
exit_node: bool,
|
||||
@@ -58,7 +63,7 @@ struct Device<'a> {
|
||||
|
||||
/// An exit-node choice the user has to confirm: all their traffic goes through
|
||||
/// somebody else's device, or stops doing so.
|
||||
pub(crate) struct ExitConfirm {
|
||||
pub struct ExitConfirm {
|
||||
network_id: String,
|
||||
peer_id: String,
|
||||
name: String,
|
||||
@@ -69,7 +74,7 @@ pub(crate) struct ExitConfirm {
|
||||
}
|
||||
|
||||
/// An exact offline claim selected for durable cleanup.
|
||||
pub(crate) struct ForgetConfirm {
|
||||
pub struct ForgetConfirm {
|
||||
network_id: String,
|
||||
peer: String,
|
||||
version: u64,
|
||||
@@ -79,7 +84,7 @@ pub(crate) struct ForgetConfirm {
|
||||
|
||||
impl ExitConfirm {
|
||||
/// A question about stopping the exit node a network's tile shows.
|
||||
pub(crate) fn stop_from_tile(network: &NetworkReport, peer_id: &str) -> Self {
|
||||
pub fn stop_from_tile(network: &NetworkReport, peer_id: &str) -> Self {
|
||||
Self {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: peer_id.to_string(),
|
||||
@@ -126,9 +131,9 @@ fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
|
||||
}
|
||||
|
||||
/// Draws the window body into its viewport.
|
||||
pub(crate) fn show(
|
||||
pub fn show(
|
||||
ctx: &egui::Context,
|
||||
agent: &AgentClient,
|
||||
agent: &dyn Client,
|
||||
unit: &mut Unit,
|
||||
confirmations: (&mut Option<ExitConfirm>, &mut Option<ForgetConfirm>),
|
||||
network: &NetworkReport,
|
||||
@@ -148,6 +153,23 @@ pub(crate) fn show(
|
||||
// A copy of the chosen unit for the read-only rendering below.
|
||||
let unit = *unit;
|
||||
|
||||
if ctx.os() == egui::os::OperatingSystem::Android || ui.available_width() < 620.0 {
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
ui.collapsing("Network details", |ui| summary(ui, network));
|
||||
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0);
|
||||
compact::roster(
|
||||
ui,
|
||||
network,
|
||||
own_id,
|
||||
traffic,
|
||||
unit,
|
||||
(confirm, forget_confirm),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
summary(ui, network);
|
||||
ui.add_space(6.0);
|
||||
|
||||
@@ -185,7 +207,7 @@ pub(crate) fn show(
|
||||
|
||||
fn confirm_forget(
|
||||
ctx: &egui::Context,
|
||||
agent: &AgentClient,
|
||||
agent: &dyn Client,
|
||||
confirm: &mut Option<ForgetConfirm>,
|
||||
network: &str,
|
||||
) {
|
||||
@@ -216,7 +238,7 @@ fn confirm_forget(
|
||||
}
|
||||
ui.label("The network will forget this claim and free its name and IP. A returning device can publish a new claim; this does not ban it.");
|
||||
ui.horizontal(|ui| {
|
||||
accepted = ui.add_enabled(!agent.snapshot().busy, egui::Button::new("Forget")).clicked();
|
||||
accepted = ui.add_enabled(!agent.busy(), egui::Button::new("Forget")).clicked();
|
||||
cancelled = ui.button("Cancel").clicked();
|
||||
});
|
||||
});
|
||||
@@ -237,9 +259,9 @@ fn confirm_forget(
|
||||
///
|
||||
/// `network_id` is the devices window the question is drawn in, or `None` for
|
||||
/// the main window; a question appears in the window it was asked in only.
|
||||
pub(crate) fn confirm_exit(
|
||||
pub fn confirm_exit(
|
||||
ctx: &egui::Context,
|
||||
agent: &AgentClient,
|
||||
agent: &dyn Client,
|
||||
confirm: &mut Option<ExitConfirm>,
|
||||
network_id: Option<&str>,
|
||||
) {
|
||||
@@ -266,14 +288,24 @@ pub(crate) fn confirm_exit(
|
||||
.resizable(false)
|
||||
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
|
||||
.show(ctx, |ui| {
|
||||
ui.set_max_width(380.0);
|
||||
ui.set_max_width((ctx.screen_rect().width() - 40.0).clamp(160.0, 380.0));
|
||||
let phone = ctx.os() == egui::os::OperatingSystem::Android;
|
||||
ui.label(if pending.stop {
|
||||
format!("Stop using {}?", pending.name)
|
||||
} else if phone {
|
||||
format!(
|
||||
"Route this phone’s IPv4 internet traffic through {}?",
|
||||
pending.name
|
||||
)
|
||||
} else {
|
||||
format!("Use {} as exit node?", pending.name)
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if phone {
|
||||
ui.spacing_mut().interact_size = egui::vec2(104., 48.);
|
||||
ui.spacing_mut().button_padding.x = 18.;
|
||||
}
|
||||
if ui
|
||||
.button(if pending.stop { "Stop" } else { "Use" })
|
||||
.clicked()
|
||||
@@ -303,7 +335,12 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) {
|
||||
.spacing([12.0, 3.0])
|
||||
.show(ui, |ui| {
|
||||
ui.weak("id");
|
||||
format::copy_field(ui, &network.network_id, &network.network_id);
|
||||
let id = if ui.ctx().os() == egui::os::OperatingSystem::Android {
|
||||
format::short(&network.network_id)
|
||||
} else {
|
||||
network.network_id.clone()
|
||||
};
|
||||
format::copy_field(ui, &id, &network.network_id);
|
||||
ui.end_row();
|
||||
|
||||
ui.weak("active");
|
||||
@@ -365,12 +402,12 @@ fn known_ids<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<&'a str> {
|
||||
}
|
||||
|
||||
/// How many other devices can be reached now, by any path.
|
||||
pub(crate) fn online_count(network: &NetworkReport, own_id: &str) -> usize {
|
||||
pub fn online_count(network: &NetworkReport, own_id: &str) -> usize {
|
||||
devices(network, own_id).iter().filter(|d| d.online).count()
|
||||
}
|
||||
|
||||
/// How many other devices this network knows of, connected or not.
|
||||
pub(crate) fn known_count(network: &NetworkReport, own_id: &str) -> usize {
|
||||
pub fn known_count(network: &NetworkReport, own_id: &str) -> usize {
|
||||
known_ids(network, own_id).len()
|
||||
}
|
||||
|
||||
@@ -403,14 +440,9 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
|
||||
.map(|id| {
|
||||
let overlay = overlay_peers.iter().find(|p| p.endpoint_id == id);
|
||||
let member = network.members.iter().find(|m| m.endpoint_id == id);
|
||||
let online = member.is_some_and(|m| m.online)
|
||||
|| network.peers.iter().any(|p| p.endpoint_id == id);
|
||||
let path = network
|
||||
.peers
|
||||
.iter()
|
||||
.find(|p| p.endpoint_id == id)
|
||||
.map(|p| &p.path)
|
||||
.or_else(|| member.map(|m| &m.path));
|
||||
let peer = network.peers.iter().find(|p| p.endpoint_id == id);
|
||||
let online = member.is_some_and(|m| m.online) || peer.is_some();
|
||||
let path = peer.map(|p| &p.path).or_else(|| member.map(|m| &m.path));
|
||||
let via_name = match path {
|
||||
Some(DataPathReport::Relayed { via, .. }) => Some(exit::name_of(network, via)),
|
||||
_ => None,
|
||||
@@ -430,25 +462,15 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
|
||||
hostname,
|
||||
copy: hostname.map(|h| format!("{h}.{}", network.name)),
|
||||
id,
|
||||
data_error: network
|
||||
.peers
|
||||
.iter()
|
||||
.find(|p| p.endpoint_id == id)
|
||||
.and_then(|p| p.data_error.as_deref()),
|
||||
data_error: peer.and_then(|p| p.data_error.as_deref()),
|
||||
address: overlay
|
||||
.and_then(|p| p.address.clone())
|
||||
.or_else(|| member.and_then(|m| m.overlay_address_v4.clone())),
|
||||
control_rtt_ms: network
|
||||
.peers
|
||||
.iter()
|
||||
.find(|p| p.endpoint_id == id)
|
||||
.and_then(|p| p.rtt_ms),
|
||||
control_rtt_ms: peer.and_then(|p| p.rtt_ms),
|
||||
data_rtt_ms: peer.and_then(|p| p.data_rtt_ms),
|
||||
data_transport_detail: peer.and_then(|p| p.data_transport_detail.as_deref()),
|
||||
overlay,
|
||||
exit_node: online
|
||||
&& network
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.endpoint_id == id && p.exit_node),
|
||||
exit_node: peer.is_some_and(|p| p.exit_node),
|
||||
in_use: network.exit.via.as_deref() == Some(id),
|
||||
}
|
||||
})
|
||||
@@ -466,7 +488,7 @@ const COLUMN_HEADERS: [&str; 10] = [
|
||||
"device",
|
||||
"exit",
|
||||
"data",
|
||||
"RTT",
|
||||
"RTT data / control",
|
||||
"address",
|
||||
"data path",
|
||||
"pkts",
|
||||
@@ -612,7 +634,7 @@ fn device_table(
|
||||
let (path, _) = data_path_text(device.path, device.via_name.as_deref(), device.online);
|
||||
for (column, text) in [
|
||||
(2, "waiting".to_owned()),
|
||||
(3, rtt_text(device.control_rtt_ms)),
|
||||
(3, rtt_pair(device)),
|
||||
(4, device.address.clone().unwrap_or_default()),
|
||||
(5, path),
|
||||
] {
|
||||
@@ -688,28 +710,14 @@ fn device_table(
|
||||
|column, ui| match column {
|
||||
0 => {
|
||||
name_cell(ui, device);
|
||||
if !device.online
|
||||
&& !device.in_use
|
||||
&& let Some(version) = device.record_version
|
||||
&& ui
|
||||
.add_enabled(network.active, egui::Button::new("Forget"))
|
||||
.on_hover_text("Free this offline device's name and IPv4")
|
||||
.clicked()
|
||||
{
|
||||
*forget_confirm = Some(ForgetConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer: device.id.into(),
|
||||
version,
|
||||
name: device.name(),
|
||||
address: device.address.clone(),
|
||||
});
|
||||
}
|
||||
forget_button(ui, device, network, forget_confirm);
|
||||
}
|
||||
1 => exit_cell(ui, device, network_id, confirm),
|
||||
2 => tunnel_cell(ui, device),
|
||||
3 => {
|
||||
ui.label(rtt_text(device.control_rtt_ms))
|
||||
.on_hover_text("Control-connection round-trip time.");
|
||||
ui.label(rtt_pair(device)).on_hover_text(
|
||||
"Median authenticated direct data-link RTT / selected control-connection RTT. A dash means there is no current measurement.",
|
||||
);
|
||||
}
|
||||
4 => match &device.address {
|
||||
Some(address) => format::copy_field(ui, address, address),
|
||||
@@ -771,11 +779,18 @@ fn device_table(
|
||||
);
|
||||
}
|
||||
|
||||
/// Control RTT is independent of the hidden internal cipher's handshake age.
|
||||
fn rtt_text(rtt: Option<u64>) -> String {
|
||||
rtt.map_or_else(|| "—".into(), |value| format!("{value} ms"))
|
||||
}
|
||||
|
||||
fn rtt_pair(device: &Device<'_>) -> String {
|
||||
format!(
|
||||
"{} / {}",
|
||||
rtt_text(device.data_rtt_ms),
|
||||
rtt_text(device.control_rtt_ms)
|
||||
)
|
||||
}
|
||||
|
||||
fn tunnel_cell(ui: &mut egui::Ui, device: &Device<'_>) {
|
||||
let ready = device.overlay.is_some_and(|peer| peer.is_up())
|
||||
&& !matches!(device.path, None | Some(DataPathReport::None));
|
||||
@@ -835,13 +850,39 @@ fn data_path_cell(ui: &mut egui::Ui, device: &Device<'_>) {
|
||||
)
|
||||
};
|
||||
response.on_hover_text(match device.path {
|
||||
Some(DataPathReport::Direct { .. }) => "Direct transport; no mesh relay.",
|
||||
Some(DataPathReport::Direct { .. }) => device
|
||||
.data_transport_detail
|
||||
.unwrap_or("Direct link to this member."),
|
||||
Some(DataPathReport::Relayed { .. }) => "Traffic forwarded through another device.",
|
||||
_ if device.online => "Control connected; data transport unavailable.",
|
||||
_ => "Unreachable.",
|
||||
});
|
||||
}
|
||||
|
||||
fn forget_button(
|
||||
ui: &mut egui::Ui,
|
||||
device: &Device<'_>,
|
||||
network: &NetworkReport,
|
||||
confirm: &mut Option<ForgetConfirm>,
|
||||
) {
|
||||
if !device.online
|
||||
&& !device.in_use
|
||||
&& let Some(version) = device.record_version
|
||||
&& ui
|
||||
.add_enabled(network.active, egui::Button::new("Forget"))
|
||||
.on_hover_text("Free this offline device's name and IPv4")
|
||||
.clicked()
|
||||
{
|
||||
*confirm = Some(ForgetConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer: device.id.into(),
|
||||
version,
|
||||
name: device.name(),
|
||||
address: device.address.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn yes_no(value: bool) -> &'static str {
|
||||
if value { "yes" } else { "no" }
|
||||
}
|
||||
@@ -862,6 +903,109 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phone_roster_fits_each_width_and_expands_only_the_tapped_member() {
|
||||
struct ReadOnly;
|
||||
impl Client for ReadOnly {
|
||||
fn send(&self, _: Command) {
|
||||
panic!("reading a row issued an action");
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
let mut network = NetworkReport {
|
||||
network_id: "a".repeat(60),
|
||||
name: "lab".into(),
|
||||
..Default::default()
|
||||
};
|
||||
for (i, name) in [
|
||||
"alpha",
|
||||
"bravo",
|
||||
"charlie",
|
||||
"long-hostname-that-cannot-fit-a-phone-row",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let mut m = member(name, i < 2, DataPathReport::None);
|
||||
m.hostname = Some(name.into());
|
||||
m.overlay_address_v4 = Some(format!("192.168.254.{}", 240 + i));
|
||||
network.members.push(m);
|
||||
}
|
||||
for width in [320.0, 360.0, 430.0, 870.0] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
let frame = |events| {
|
||||
ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 720.),
|
||||
)),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
show(
|
||||
ctx,
|
||||
&ReadOnly,
|
||||
&mut Unit::Packets,
|
||||
(&mut None, &mut None),
|
||||
&network,
|
||||
"self",
|
||||
&Traffic::default(),
|
||||
)
|
||||
},
|
||||
)
|
||||
};
|
||||
let positions = |out: &egui::FullOutput, value: &str| -> Vec<egui::Pos2> {
|
||||
out.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == value => {
|
||||
Some(t.pos + t.galley.rect.center().to_vec2())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
frame(vec![]);
|
||||
let out = frame(vec![]);
|
||||
let a = positions(&out, "alpha")[0];
|
||||
let b = positions(&out, "bravo")[0];
|
||||
assert!(
|
||||
(15.0..=29.0).contains(&(b.y - a.y)),
|
||||
"one text line per device at {width}"
|
||||
);
|
||||
for i in 240..244 {
|
||||
let p = positions(&out, &format!("192.168.254.{i}"))[0];
|
||||
assert!(p.x < width - 30.0, "IPv4 outside row at {width}: {p:?}");
|
||||
}
|
||||
assert!(positions(&out, "Endpoint ID").is_empty());
|
||||
let click = |p: egui::Pos2| {
|
||||
for pressed in [true, false] {
|
||||
frame(vec![
|
||||
egui::Event::PointerMoved(p),
|
||||
egui::Event::PointerButton {
|
||||
pos: p,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
frame(vec![])
|
||||
};
|
||||
let expanded = click(a);
|
||||
assert_eq!(positions(&expanded, "Endpoint ID").len(), 1);
|
||||
let switched = click(positions(&expanded, "bravo")[0]);
|
||||
assert_eq!(positions(&switched, "Endpoint ID").len(), 1);
|
||||
let closed = click(positions(&switched, "bravo")[0]);
|
||||
assert!(positions(&closed, "Endpoint ID").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_reached_through_another_is_online_whatever_its_tunnel_says() {
|
||||
// The tray used to call a device online only while its tunnel had
|
||||
@@ -963,6 +1107,8 @@ mod tests {
|
||||
data_error: None,
|
||||
endpoint_id: "peer".into(),
|
||||
rtt_ms: Some(27),
|
||||
data_rtt_ms: Some(203),
|
||||
data_transport_detail: Some("relay via relay.example".into()),
|
||||
..Default::default()
|
||||
}],
|
||||
overlay: Some(OverlayReport {
|
||||
@@ -978,6 +1124,11 @@ mod tests {
|
||||
};
|
||||
let rows = devices(&network, "own");
|
||||
assert_eq!(rtt_text(rows[0].control_rtt_ms), "27 ms");
|
||||
assert_eq!(rtt_text(rows[0].data_rtt_ms), "203 ms");
|
||||
assert_eq!(
|
||||
rows[0].data_transport_detail,
|
||||
Some("relay via relay.example")
|
||||
);
|
||||
assert_eq!(rtt_text(None), "—");
|
||||
}
|
||||
|
||||
@@ -1084,8 +1235,8 @@ mod tests {
|
||||
let mut texts = Vec::new();
|
||||
collect_text(&shapes, &mut texts);
|
||||
for (label, next_column) in [
|
||||
("RTT".to_string(), "address"),
|
||||
(rtt_text(Some(12_345)), "address"),
|
||||
("RTT data / control".to_string(), "address"),
|
||||
(rtt_pair(&rows[0]), "address"),
|
||||
(format!("{packets}/{}", packets + 1), "bytes"),
|
||||
(format!("{}/{}", packets * 2, (packets + 1) * 2), "bytes"),
|
||||
] {
|
||||
@@ -0,0 +1,203 @@
|
||||
//! One line per member and one expanded detail block, with no horizontal scroller.
|
||||
use super::{
|
||||
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text,
|
||||
devices, exit, forget_button, format, icon, rtt_text, tunnel_cell,
|
||||
};
|
||||
|
||||
pub(super) fn roster(
|
||||
ui: &mut egui::Ui,
|
||||
network: &NetworkReport,
|
||||
own_id: &str,
|
||||
traffic: &Traffic,
|
||||
unit: Unit,
|
||||
(exit, forget): (&mut Option<ExitConfirm>, &mut Option<ForgetConfirm>),
|
||||
) {
|
||||
let members = devices(network, own_id);
|
||||
let online = members.iter().filter(|m| m.online).count();
|
||||
ui.strong(format!(
|
||||
"devices ({} online / {} known)",
|
||||
online,
|
||||
members.len()
|
||||
));
|
||||
let id = ui.make_persistent_id(("expanded device", &network.network_id));
|
||||
let mut selected = ui.data(|d| d.get_temp::<String>(id));
|
||||
let width = ui.available_width();
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let measure = |s: &str| {
|
||||
ui.painter()
|
||||
.layout_no_wrap(s.to_owned(), font.clone(), ui.visuals().text_color())
|
||||
.size()
|
||||
.x
|
||||
};
|
||||
let rtt_x = width - (measure("9999 ms") + 18.0).min(width * 0.25);
|
||||
let ip_x = rtt_x - (measure("255.255.255.255") + 14.0).min(width * 0.40);
|
||||
let offsets = [16.0, ip_x, rtt_x];
|
||||
let size = egui::vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 8.0);
|
||||
ui.spacing_mut().item_spacing.y = 1.0;
|
||||
let (header, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "Data RTT"]) {
|
||||
ui.painter().text(
|
||||
header.left_center() + egui::vec2(x, 0.),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
title,
|
||||
font.clone(),
|
||||
ui.visuals().weak_text_color(),
|
||||
);
|
||||
}
|
||||
for (index, member) in members.iter().enumerate() {
|
||||
let (row, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
let response = ui.interact(row, id.with(member.id), egui::Sense::click());
|
||||
if response.clicked() {
|
||||
selected = (selected.as_deref() != Some(member.id)).then(|| member.id.to_owned());
|
||||
}
|
||||
let open = selected.as_deref() == Some(member.id);
|
||||
if open || index % 2 == 0 {
|
||||
ui.painter().rect_filled(
|
||||
row,
|
||||
2.0,
|
||||
if open {
|
||||
ui.visuals().widgets.hovered.weak_bg_fill
|
||||
} else {
|
||||
ui.visuals().faint_bg_color
|
||||
},
|
||||
);
|
||||
}
|
||||
let dot = row.left_center() + egui::vec2(6., 0.);
|
||||
if member.online {
|
||||
ui.painter().circle_filled(dot, 3., exit::GOOD);
|
||||
} else {
|
||||
ui.painter().circle_stroke(
|
||||
dot,
|
||||
3.,
|
||||
egui::Stroke::new(1.0_f32, ui.visuals().weak_text_color()),
|
||||
);
|
||||
}
|
||||
let name = member.name();
|
||||
let rtt = rtt_text(member.data_rtt_ms);
|
||||
let labels = [
|
||||
name.as_str(),
|
||||
member.address.as_deref().unwrap_or("—"),
|
||||
rtt.as_str(),
|
||||
];
|
||||
let color = if member.online {
|
||||
ui.visuals().text_color()
|
||||
} else {
|
||||
ui.visuals().weak_text_color()
|
||||
};
|
||||
for ((x, end), label) in offsets
|
||||
.into_iter()
|
||||
.zip([ip_x, rtt_x, width - 13.0])
|
||||
.zip(labels)
|
||||
{
|
||||
let mut job =
|
||||
egui::text::LayoutJob::simple_singleline(label.into(), font.clone(), color);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.max_width = (end - x - 4.0).max(0.0);
|
||||
job.wrap.break_anywhere = true;
|
||||
let galley = ui.painter().layout_job(job);
|
||||
let origin = row.left_center() + egui::vec2(x, -galley.size().y * 0.5);
|
||||
ui.painter().galley(origin, galley, color);
|
||||
}
|
||||
ui.painter().text(
|
||||
row.right_center(),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
if open {
|
||||
icon::CARET_DOWN
|
||||
} else {
|
||||
icon::CARET_RIGHT
|
||||
},
|
||||
font.clone(),
|
||||
ui.visuals().weak_text_color(),
|
||||
);
|
||||
if open {
|
||||
ui.push_id(member.id, |ui| {
|
||||
details(ui, network, member, traffic, unit, exit, forget)
|
||||
});
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| match selected {
|
||||
Some(member) => d.insert_temp(id, member),
|
||||
None => d.remove::<String>(id),
|
||||
});
|
||||
}
|
||||
|
||||
fn details(
|
||||
ui: &mut egui::Ui,
|
||||
network: &NetworkReport,
|
||||
member: &Device<'_>,
|
||||
traffic: &Traffic,
|
||||
unit: Unit,
|
||||
exit: &mut Option<ExitConfirm>,
|
||||
forget: &mut Option<ForgetConfirm>,
|
||||
) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak(if member.online { "online" } else { "offline" });
|
||||
if let Some(name) = &member.copy {
|
||||
format::copy_field(ui, &member.name(), name);
|
||||
}
|
||||
if let Some(address) = &member.address {
|
||||
format::copy_field(ui, address, address);
|
||||
}
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak("Endpoint ID");
|
||||
format::copy_field(ui, &format::short(member.id), member.id);
|
||||
});
|
||||
let (path, _) = data_path_text(member.path, member.via_name.as_deref(), member.online);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(path);
|
||||
tunnel_cell(ui, member);
|
||||
});
|
||||
if member.online {
|
||||
if let Some(path) = member.data_transport_detail {
|
||||
ui.label(path);
|
||||
}
|
||||
ui.label(format!(
|
||||
"Data RTT {} · Control RTT {}",
|
||||
rtt_text(member.data_rtt_ms),
|
||||
rtt_text(member.control_rtt_ms)
|
||||
));
|
||||
}
|
||||
if let Some(error) = member.data_error {
|
||||
ui.colored_label(AMBER, error);
|
||||
}
|
||||
if let Some((taken, holder)) = &member.name_taken {
|
||||
ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}."));
|
||||
}
|
||||
if let Some(peer) = member.overlay {
|
||||
let series = traffic.peer(&network.network_id, &peer.public_key);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(format!(
|
||||
"TX {} · {} pkts",
|
||||
format::bytes(peer.tx_bytes as f64),
|
||||
peer.tx_packets
|
||||
));
|
||||
ui.label(format!(
|
||||
"RX {} · {} pkts",
|
||||
format::bytes(peer.rx_bytes as f64),
|
||||
peer.rx_packets
|
||||
));
|
||||
ui.weak(format::series_rate(series, unit));
|
||||
});
|
||||
format::sparkline(ui, series, unit, 22.);
|
||||
}
|
||||
if (member.exit_node || member.in_use)
|
||||
&& ui
|
||||
.button(if member.in_use {
|
||||
"Stop using exit node"
|
||||
} else {
|
||||
"Use exit node"
|
||||
})
|
||||
.clicked()
|
||||
{
|
||||
*exit = Some(ExitConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: member.id.into(),
|
||||
name: member.name(),
|
||||
stop: member.in_use,
|
||||
main: false,
|
||||
});
|
||||
}
|
||||
forget_button(ui, member, network, forget);
|
||||
ui.separator();
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! The remote-exit chooser. Each radio row is one touch target, including its telemetry.
|
||||
use super::{ExitConfirm, devices, rtt_text};
|
||||
use crate::exit;
|
||||
use egui::{Align2, FontId, Pos2, Rect, Sense, Ui};
|
||||
use tsunagi::ipc::{DataPathReport, NetworkReport};
|
||||
|
||||
/// Draw the selectable exits for one network and return a choice for confirmation.
|
||||
pub fn choose_exit(ui: &mut Ui, network: &NetworkReport, own: &str) -> Option<ExitConfirm> {
|
||||
ui.heading(&network.name);
|
||||
if let Some(rules) = &network.exit.client_rules
|
||||
&& !rules.ok
|
||||
{
|
||||
ui.colored_label(exit::LOUD, &rules.detail);
|
||||
}
|
||||
let width = ui.available_width();
|
||||
let (header, _) = ui.allocate_exact_size(egui::vec2(width, 22.), Sense::hover());
|
||||
let columns = Columns::new(header);
|
||||
let muted = ui.visuals().weak_text_color();
|
||||
for (x, label) in [
|
||||
(columns.name, "Exit node"),
|
||||
(columns.rtt, "Data RTT"),
|
||||
(columns.path, "Path"),
|
||||
] {
|
||||
ui.painter().text(
|
||||
egui::pos2(x, header.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
label,
|
||||
egui::TextStyle::Small.resolve(ui.style()),
|
||||
muted,
|
||||
);
|
||||
}
|
||||
let current = network.exit.via.as_deref();
|
||||
let mut choice = None;
|
||||
let local = Row {
|
||||
peer: None,
|
||||
name: "No exit node",
|
||||
address: None,
|
||||
rtt: None,
|
||||
path: "Local",
|
||||
transport: None,
|
||||
selected: current.is_none(),
|
||||
};
|
||||
if local.draw(ui, &network.network_id)
|
||||
&& let Some(id) = current
|
||||
{
|
||||
choice = Some(ExitConfirm::stop_from_tile(network, id));
|
||||
}
|
||||
let mut candidates = devices(network, own);
|
||||
candidates.retain(|d| d.exit_node || d.in_use);
|
||||
candidates.sort_by_key(|d| !d.in_use);
|
||||
if let Some(id) = current
|
||||
&& !candidates.iter().any(|d| d.id == id)
|
||||
{
|
||||
Row {
|
||||
peer: Some(id),
|
||||
name: &exit::name_of(network, id),
|
||||
address: None,
|
||||
rtt: None,
|
||||
path: "Offline",
|
||||
transport: None,
|
||||
selected: true,
|
||||
}
|
||||
.draw(ui, &network.network_id);
|
||||
}
|
||||
for candidate in &candidates {
|
||||
let name = candidate.name();
|
||||
let relayed;
|
||||
let (path, transport) = if !candidate.online {
|
||||
("Offline", None)
|
||||
} else if candidate.in_use && !network.exit.via_online || candidate.data_error.is_some() {
|
||||
("Unavailable", None)
|
||||
} else {
|
||||
match candidate.path {
|
||||
Some(DataPathReport::Direct { transport }) => ("Direct", Some(transport.as_str())),
|
||||
Some(DataPathReport::Relayed { hops, .. }) => {
|
||||
relayed = format!("{hops} hops");
|
||||
("Relayed", Some(relayed.as_str()))
|
||||
}
|
||||
_ => ("Connecting", None),
|
||||
}
|
||||
};
|
||||
let row = Row {
|
||||
peer: Some(candidate.id),
|
||||
name: &name,
|
||||
address: candidate.address.as_deref(),
|
||||
rtt: candidate.data_rtt_ms,
|
||||
path,
|
||||
transport,
|
||||
selected: candidate.in_use,
|
||||
};
|
||||
if row.draw(ui, &network.network_id) && !candidate.in_use {
|
||||
choice = Some(ExitConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: candidate.id.into(),
|
||||
name,
|
||||
stop: false,
|
||||
main: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
if !candidates.iter().any(|d| d.exit_node) {
|
||||
ui.weak("No connected peers offer an exit node.");
|
||||
}
|
||||
choice
|
||||
}
|
||||
|
||||
struct Columns {
|
||||
name: f32,
|
||||
rtt: f32,
|
||||
path: f32,
|
||||
}
|
||||
impl Columns {
|
||||
fn new(rect: Rect) -> Self {
|
||||
let path = rect.right() - (rect.width() * 0.24).clamp(66., 110.);
|
||||
Self {
|
||||
name: rect.left() + 31.,
|
||||
rtt: path - 61.,
|
||||
path,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
peer: Option<&'a str>,
|
||||
name: &'a str,
|
||||
address: Option<&'a str>,
|
||||
rtt: Option<u64>,
|
||||
path: &'a str,
|
||||
transport: Option<&'a str>,
|
||||
selected: bool,
|
||||
}
|
||||
impl Row<'_> {
|
||||
fn draw(&self, ui: &mut Ui, network: &str) -> bool {
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let small = egui::TextStyle::Small.resolve(ui.style());
|
||||
let height = (font.size + small.size + 18.).max(52.);
|
||||
let (rect, _) =
|
||||
ui.allocate_exact_size(egui::vec2(ui.available_width(), height), Sense::hover());
|
||||
let id = ui.make_persistent_id(("exit choice", network, self.peer));
|
||||
let response = ui.interact(rect, id, Sense::click());
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::selected(
|
||||
egui::WidgetType::RadioButton,
|
||||
true,
|
||||
self.selected,
|
||||
self.name,
|
||||
)
|
||||
});
|
||||
let visuals = ui.style().interact_selectable(&response, self.selected);
|
||||
let painter = ui.painter();
|
||||
if self.selected || response.hovered() || response.has_focus() {
|
||||
painter.rect_filled(rect, 3., visuals.weak_bg_fill);
|
||||
}
|
||||
painter.hline(
|
||||
rect.x_range(),
|
||||
rect.bottom(),
|
||||
ui.visuals().widgets.noninteractive.bg_stroke,
|
||||
);
|
||||
let dot = rect.left_center() + egui::vec2(15., 0.);
|
||||
painter.circle_stroke(dot, 6., visuals.fg_stroke);
|
||||
if self.selected {
|
||||
painter.circle_filled(dot, 3., visuals.text_color());
|
||||
}
|
||||
let c = Columns::new(rect);
|
||||
let center = rect.center().y;
|
||||
let muted = ui.visuals().weak_text_color();
|
||||
let line = |x: f32, end: f32, y: f32, value: &str, font: &FontId, color| {
|
||||
let mut job =
|
||||
egui::text::LayoutJob::simple_singleline(value.into(), font.clone(), color);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
job.wrap.max_width = (end - x - 5.).max(0.);
|
||||
let text = painter.layout_job(job);
|
||||
painter.galley(Pos2::new(x, y - text.size().y * 0.5), text, color);
|
||||
};
|
||||
let pair = |x, end, label, detail: Option<&str>| {
|
||||
let y = if detail.is_some() {
|
||||
center - small.size * 0.55
|
||||
} else {
|
||||
center
|
||||
};
|
||||
line(x, end, y, label, &font, visuals.text_color());
|
||||
if let Some(detail) = detail {
|
||||
line(x, end, center + font.size * 0.65, detail, &small, muted);
|
||||
}
|
||||
};
|
||||
pair(c.name, c.rtt, self.name, self.address);
|
||||
line(
|
||||
c.rtt,
|
||||
c.path,
|
||||
center,
|
||||
&rtt_text(self.rtt),
|
||||
&font,
|
||||
visuals.text_color(),
|
||||
);
|
||||
pair(c.path, rect.right(), self.path, self.transport);
|
||||
response.clicked()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::choose_exit;
|
||||
use egui::{CentralPanel, Context, Event, PointerButton, Pos2, RawInput, Rect, Shape};
|
||||
use tsunagi::ipc::{DataPathReport, ExitReport, MemberReport, NetworkReport, PeerReport};
|
||||
|
||||
#[test]
|
||||
fn exit_table_fits_phone_widths_and_the_whole_row_selects_the_exact_peer() {
|
||||
let mut network = NetworkReport {
|
||||
name: "lab".into(),
|
||||
network_id: "network-id".into(),
|
||||
exit: ExitReport {
|
||||
via: Some("old-id".into()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
for (id, name, offer) in [
|
||||
("new-id", "west", true),
|
||||
("self", "my-phone", true),
|
||||
("ordinary", "worker", false),
|
||||
] {
|
||||
network.peers.push(PeerReport {
|
||||
endpoint_id: id.into(),
|
||||
hostname: Some(name.into()),
|
||||
data_rtt_ms: Some(37),
|
||||
rtt_ms: Some(142),
|
||||
path: DataPathReport::Direct {
|
||||
transport: "wg".into(),
|
||||
},
|
||||
exit_node: offer,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
network.members.push(MemberReport {
|
||||
endpoint_id: "old-id".into(),
|
||||
hostname: Some("east".into()),
|
||||
..Default::default()
|
||||
});
|
||||
network.members.push(MemberReport {
|
||||
endpoint_id: "new-id".into(),
|
||||
hostname: Some("west".into()),
|
||||
overlay_address_v4: Some("10.9.0.4".into()),
|
||||
..Default::default()
|
||||
});
|
||||
for width in [320., 430.] {
|
||||
let ctx = Context::default();
|
||||
let frame = |events| {
|
||||
let mut chosen = None;
|
||||
let out = ctx.run(
|
||||
RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 640.))),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
CentralPanel::default().show(ctx, |ui| {
|
||||
chosen = choose_exit(ui, &network, "self");
|
||||
});
|
||||
},
|
||||
);
|
||||
(out, chosen)
|
||||
};
|
||||
let (out, initial) = frame(Vec::new());
|
||||
assert!(initial.is_none());
|
||||
let labels: Vec<_> = out
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
Shape::Text(t) => Some((t.galley.text(), t.visual_bounding_rect())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for text in [
|
||||
"No exit node",
|
||||
"east",
|
||||
"west",
|
||||
"10.9.0.4",
|
||||
"37 ms",
|
||||
"Direct",
|
||||
"wg",
|
||||
"Offline",
|
||||
] {
|
||||
assert!(
|
||||
labels.iter().any(|(label, _)| *label == text),
|
||||
"missing {text}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!labels
|
||||
.iter()
|
||||
.any(|(label, _)| matches!(*label, "my-phone" | "worker"))
|
||||
);
|
||||
assert!(
|
||||
labels
|
||||
.iter()
|
||||
.all(|(_, r)| r.left() >= 0. && r.right() <= width + 1.)
|
||||
);
|
||||
let y = |name| {
|
||||
labels
|
||||
.iter()
|
||||
.find(|(label, _)| *label == name)
|
||||
.unwrap()
|
||||
.1
|
||||
.center()
|
||||
.y
|
||||
};
|
||||
assert!(y("west") - y("east") >= 44.);
|
||||
let tap = |name| {
|
||||
let pos = egui::pos2(width - 14., y(name) + 8.0);
|
||||
frame(vec![
|
||||
Event::PointerMoved(pos),
|
||||
Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
]);
|
||||
frame(vec![Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: Default::default(),
|
||||
}])
|
||||
.1
|
||||
};
|
||||
assert!(tap("east").is_none());
|
||||
let select = tap("west").unwrap();
|
||||
assert!(!select.stop);
|
||||
assert_eq!(
|
||||
(select.network_id.as_str(), select.peer_id.as_str()),
|
||||
("network-id", "new-id")
|
||||
);
|
||||
let stop = tap("No exit node").unwrap();
|
||||
assert!(stop.stop);
|
||||
assert_eq!(stop.peer_id, "old-id");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Exit nodes as the windows show them: what to call one, and what is wrong
|
||||
//! with the ones in play.
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
use tsunagi::ipc::NetworkReport;
|
||||
|
||||
use crate::format;
|
||||
@@ -30,7 +28,7 @@ pub(crate) struct Warning {
|
||||
}
|
||||
|
||||
/// What to call a device in a network, even while it is away.
|
||||
pub(crate) fn name_of(network: &NetworkReport, id: &str) -> String {
|
||||
pub fn name_of(network: &NetworkReport, id: &str) -> String {
|
||||
network
|
||||
.peers
|
||||
.iter()
|
||||
@@ -3,8 +3,6 @@
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
use crate::stats::{Series, Unit};
|
||||
|
||||
/// Sparkline accent.
|
||||
@@ -15,7 +13,7 @@ const COPIED_GREEN: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a);
|
||||
const FLASH: Duration = Duration::from_secs(1);
|
||||
|
||||
/// A short, readable prefix of a long identifier (char-safe, no panic).
|
||||
pub(crate) fn short(id: &str) -> String {
|
||||
pub fn short(id: &str) -> String {
|
||||
const KEEP: usize = 12;
|
||||
if id.chars().count() <= KEEP {
|
||||
id.to_string()
|
||||
@@ -25,7 +23,7 @@ pub(crate) fn short(id: &str) -> String {
|
||||
}
|
||||
|
||||
/// A byte count in binary units.
|
||||
pub(crate) fn bytes(n: f64) -> String {
|
||||
pub fn bytes(n: f64) -> String {
|
||||
const UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
|
||||
let mut value = n.max(0.0);
|
||||
let mut unit = 0;
|
||||
@@ -41,7 +39,7 @@ pub(crate) fn bytes(n: f64) -> String {
|
||||
}
|
||||
|
||||
/// A rate in the chosen unit, per second.
|
||||
pub(crate) fn rate(value: f32, unit: Unit) -> String {
|
||||
pub fn rate(value: f32, unit: Unit) -> String {
|
||||
match unit {
|
||||
Unit::Packets => {
|
||||
if value >= 1000.0 {
|
||||
@@ -55,14 +53,14 @@ pub(crate) fn rate(value: f32, unit: Unit) -> String {
|
||||
}
|
||||
|
||||
/// The current rate of a series as a string, or a dash when unsampled.
|
||||
pub(crate) fn series_rate(series: Option<&Series>, unit: Unit) -> String {
|
||||
pub fn series_rate(series: Option<&Series>, unit: Unit) -> String {
|
||||
series.map_or_else(|| "—".to_string(), |s| rate(s.rate(unit), unit))
|
||||
}
|
||||
|
||||
/// A label whose text is `display` and which copies `value` to the clipboard
|
||||
/// when clicked. Feedback is a green flash that fades back over a second — the
|
||||
/// text itself never changes, so a dense table does not reflow on a copy.
|
||||
pub(crate) fn copy_field(ui: &mut egui::Ui, display: &str, value: &str) {
|
||||
pub fn copy_field(ui: &mut egui::Ui, display: &str, value: &str) {
|
||||
let id = ui.make_persistent_id(("copy", value, display));
|
||||
let copied_at: Option<Instant> = ui.memory(|memory| memory.data.get_temp(id));
|
||||
// 1.0 right after the click, fading to 0.0 a second later.
|
||||
@@ -103,7 +101,7 @@ fn lerp_color(a: egui::Color32, b: egui::Color32, t: f32) -> egui::Color32 {
|
||||
/// A fixed-height sparkline of a series' recent rate, with the peak (top-left)
|
||||
/// and current value (bottom-right) overlaid. The space is always reserved —
|
||||
/// even with no data — so the layout never jumps when data arrives.
|
||||
pub(crate) fn sparkline(ui: &mut egui::Ui, series: Option<&Series>, unit: Unit, height: f32) {
|
||||
pub fn sparkline(ui: &mut egui::Ui, series: Option<&Series>, unit: Unit, height: f32) {
|
||||
let width = ui.available_width();
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
let painter = ui.painter_at(rect);
|
||||
@@ -0,0 +1,415 @@
|
||||
//! Shared compact network tiles, device header and join form.
|
||||
use crate::{
|
||||
client::{Client, Command},
|
||||
devices, exit, format,
|
||||
stats::{Traffic, Unit},
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
use std::collections::BTreeSet;
|
||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
const BAD: egui::Color32 = egui::Color32::from_rgb(0xd0, 0x4a, 0x3c);
|
||||
/// A neutral, not-garish red for the Leave button.
|
||||
const LEAVE_RED: egui::Color32 = egui::Color32::from_rgb(0xa8, 0x3a, 0x3a);
|
||||
|
||||
/// Join form fields.
|
||||
#[derive(Default)]
|
||||
pub struct JoinForm {
|
||||
/// Visible network name.
|
||||
pub name: String,
|
||||
/// User-entered network secret.
|
||||
pub secret: Zeroizing<String>,
|
||||
}
|
||||
|
||||
/// Local UI state kept across frames.
|
||||
pub struct UiState {
|
||||
/// Join form draft.
|
||||
pub join: JoinForm,
|
||||
/// Whether rates and sparklines are shown in packets or bytes.
|
||||
pub unit: Unit,
|
||||
/// An in-progress hostname edit (`None` when not editing).
|
||||
pub host_edit: Option<String>,
|
||||
/// Network ids whose devices window is open.
|
||||
pub open_devices: BTreeSet<String>,
|
||||
/// Per-network VIP drafts.
|
||||
pub vip_windows: std::collections::BTreeMap<String, crate::vip::Window>,
|
||||
/// Whether the About window is open.
|
||||
pub about_open: bool,
|
||||
/// An exit-node choice waiting for the user to confirm it.
|
||||
pub exit_confirm: Option<devices::ExitConfirm>,
|
||||
/// A selected offline claim waiting for cleanup confirmation.
|
||||
pub forget_confirm: Option<devices::ForgetConfirm>,
|
||||
}
|
||||
|
||||
impl Default for UiState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
join: JoinForm::default(),
|
||||
unit: Unit::Packets,
|
||||
host_edit: None,
|
||||
open_devices: BTreeSet::new(),
|
||||
vip_windows: Default::default(),
|
||||
about_open: false,
|
||||
exit_confirm: None,
|
||||
forget_confirm: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The device header: id (with a copy button) and an editable hostname.
|
||||
pub fn draw_header(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
state: &mut UiState,
|
||||
report: &StatusReport,
|
||||
) {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.weak("device");
|
||||
// Clicking the shortened id copies the full one.
|
||||
format::copy_field(ui, &format::short(&report.endpoint_id), &report.endpoint_id);
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.weak("host");
|
||||
match &mut state.host_edit {
|
||||
None => {
|
||||
ui.label(&report.hostname);
|
||||
if ui
|
||||
.small_button(icon::PENCIL_SIMPLE)
|
||||
.on_hover_text("rename")
|
||||
.clicked()
|
||||
{
|
||||
state.host_edit = Some(report.hostname.clone());
|
||||
}
|
||||
}
|
||||
Some(buffer) => {
|
||||
let response = ui.add(egui::TextEdit::singleline(buffer).desired_width(150.0));
|
||||
let submit = (response.lost_focus()
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Enter)))
|
||||
|| ui.small_button(icon::CHECK).on_hover_text("save").clicked();
|
||||
if submit {
|
||||
agent.send(Command::SetHostname(buffer.trim().to_string()));
|
||||
state.host_edit = None;
|
||||
} else if ui.small_button(icon::X).on_hover_text("cancel").clicked() {
|
||||
state.host_edit = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if !report.cache_healthy {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(0xd9, 0x9a, 0x00),
|
||||
"cache unavailable",
|
||||
);
|
||||
}
|
||||
if let Some(error) = &report.overlay_config_error {
|
||||
ui.colored_label(BAD, format!("Shared overlay interface {error}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// One compact network tile.
|
||||
pub fn draw_network(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
state: &mut UiState,
|
||||
traffic: &Traffic,
|
||||
network: &NetworkReport,
|
||||
report: &StatusReport,
|
||||
offer_exit: bool,
|
||||
) -> bool {
|
||||
let mut pick_exit = false;
|
||||
ui.add_space(6.0);
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
format::copy_field(ui, network.name.as_str(), &network.name);
|
||||
if ui.button("VIP").clicked(){state.vip_windows.entry(network.network_id.clone()).or_default();}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let leave =
|
||||
egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE))
|
||||
.fill(LEAVE_RED);
|
||||
if ui.add(leave).clicked() {
|
||||
agent.send(Command::Leave {
|
||||
network_id: network.network_id.clone(),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let address = network.overlay.as_ref().and_then(|o| o.address.as_ref());
|
||||
let series = traffic.network(&network.network_id);
|
||||
|
||||
egui::Grid::new(("net", &network.network_id))
|
||||
.num_columns(2)
|
||||
.spacing([10.0, 3.0])
|
||||
.show(ui, |ui| {
|
||||
ui.weak("id");
|
||||
format::copy_field(ui, &format::short(&network.network_id), &network.network_id);
|
||||
ui.end_row();
|
||||
|
||||
if let Some(range) = &network.range {
|
||||
ui.weak("range");
|
||||
format::copy_field(ui, range, range);
|
||||
ui.end_row();
|
||||
}
|
||||
if let Some(address) = address {
|
||||
ui.weak("addr");
|
||||
format::copy_field(ui, address, address);
|
||||
ui.end_row();
|
||||
}
|
||||
ui.weak("peers");
|
||||
ui.label(format!(
|
||||
"{} online · {} known",
|
||||
devices::online_count(network, &report.endpoint_id),
|
||||
devices::known_count(network, &report.endpoint_id)
|
||||
));
|
||||
ui.end_row();
|
||||
});
|
||||
|
||||
draw_protocols(ui, agent, network, &report.available_protocols);
|
||||
|
||||
format::sparkline(ui, series, state.unit, 34.0);
|
||||
|
||||
if !network.range_conflicts.is_empty() {
|
||||
ui.colored_label(BAD, "Stopped: overlapping network ranges");
|
||||
for conflict in &network.range_conflicts {
|
||||
ui.label(format!("{} ({}) uses {}", conflict.name, conflict.network_id, conflict.range));
|
||||
}
|
||||
ui.label("Switching suspends these networks until this network stops, then resumes them automatically.");
|
||||
if network.auto_start { ui.weak("This network will resume automatically when its range is free."); }
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if !network.active && !network.range_conflicts.is_empty() {
|
||||
if ui.button("Switch to this network").clicked() {
|
||||
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: true });
|
||||
}
|
||||
if network.auto_start && ui.button("Keep stopped").clicked() {
|
||||
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: false });
|
||||
}
|
||||
} else {
|
||||
let mut active = network.active;
|
||||
if ui.checkbox(&mut active, "active").changed() {
|
||||
agent.send(Command::SetActive {
|
||||
network_id: network.network_id.clone(),
|
||||
active,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut broadcast = network.broadcast;
|
||||
if ui.checkbox(&mut broadcast, "broadcast").changed() {
|
||||
agent.send(Command::SetBroadcast {
|
||||
network_id: network.network_id.clone(),
|
||||
enabled: broadcast,
|
||||
});
|
||||
}
|
||||
if !offer_exit && ui.button("Exit node…").clicked() { pick_exit = true; }
|
||||
let mut offering = network.exit.offering;
|
||||
if offer_exit && ui
|
||||
.checkbox(&mut offering, "exit node")
|
||||
.on_hover_text(
|
||||
"let other members send all their internet traffic through this \
|
||||
device, which can see it",
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
agent.send(Command::SetExitOffer {
|
||||
network_id: network.network_id.clone(),
|
||||
enabled: offering,
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
// In the bottom left corner while this device sends its traffic through
|
||||
// somebody: green while that works, red while it does not.
|
||||
if let Some(via) = &network.exit.via {
|
||||
let color = if network.exit.via_online {
|
||||
exit::GOOD
|
||||
} else {
|
||||
exit::LOUD
|
||||
};
|
||||
let response = ui
|
||||
.add(
|
||||
egui::Label::new(
|
||||
egui::RichText::new(icon::SIGN_OUT).size(18.0).color(color),
|
||||
)
|
||||
.sense(egui::Sense::click()),
|
||||
)
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text(format!(
|
||||
"exit node: {} — click to stop",
|
||||
exit::name_of(network, via)
|
||||
));
|
||||
if response.clicked() {
|
||||
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
|
||||
}
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Show devices").clicked() {
|
||||
state.open_devices.insert(network.network_id.clone());
|
||||
}
|
||||
if ui
|
||||
.button(format!("{} Copy secret", icon::COPY))
|
||||
.on_hover_text("copy this network's secret to the clipboard")
|
||||
.clicked()
|
||||
{
|
||||
agent.send(Command::CopySecret {
|
||||
network_id: network.network_id.clone(),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
for warning in exit::warnings(network) {
|
||||
draw_exit_warning(ui, &warning);
|
||||
}
|
||||
});
|
||||
pick_exit
|
||||
}
|
||||
|
||||
fn draw_protocols(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
network: &NetworkReport,
|
||||
available: &[tsunagi::ipc::ProtocolReport],
|
||||
) {
|
||||
let summary = if network.protocols.is_empty() {
|
||||
"none".into()
|
||||
} else {
|
||||
network.protocols.join(", ")
|
||||
};
|
||||
egui::CollapsingHeader::new(format!("data transports {summary}"))
|
||||
.id_salt(("protocols", &network.network_id))
|
||||
.show(ui, |ui| {
|
||||
ui.weak("Order sets the first choice. Peers that support link comparison can switch to a faster enabled transport.");
|
||||
let mut selected = network.protocols.clone();
|
||||
let mut changed = false;
|
||||
ui.add_enabled_ui(!agent.busy(), |ui| {
|
||||
// Enabled items follow the user's preference; unchecked items
|
||||
// follow the agent's catalog. The worker refreshes after edits.
|
||||
let ordered: Vec<_> = network
|
||||
.protocols
|
||||
.iter()
|
||||
.filter_map(|name| available.iter().find(|p| &p.name == name))
|
||||
.chain(
|
||||
available
|
||||
.iter()
|
||||
.filter(|p| !network.protocols.contains(&p.name)),
|
||||
)
|
||||
.collect();
|
||||
for protocol in ordered {
|
||||
ui.horizontal(|ui| {
|
||||
let mut on = selected.contains(&protocol.name);
|
||||
if ui.checkbox(&mut on, &protocol.name).changed() {
|
||||
if on {
|
||||
selected.push(protocol.name.clone());
|
||||
} else {
|
||||
selected.retain(|p| p != &protocol.name);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if let Some(index) = selected.iter().position(|p| p == &protocol.name) {
|
||||
if ui
|
||||
.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP))
|
||||
.on_hover_text("prefer earlier")
|
||||
.clicked()
|
||||
{
|
||||
selected.swap(index, index - 1);
|
||||
changed = true;
|
||||
}
|
||||
if ui
|
||||
.add_enabled(
|
||||
index + 1 < selected.len(),
|
||||
egui::Button::new(icon::ARROW_DOWN),
|
||||
)
|
||||
.on_hover_text("prefer later")
|
||||
.clicked()
|
||||
{
|
||||
selected.swap(index, index + 1);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.indent(("description", &network.network_id, &protocol.name), |ui| {
|
||||
ui.weak(&protocol.summary);
|
||||
});
|
||||
}
|
||||
});
|
||||
if selected.is_empty() {
|
||||
ui.weak("Control only; no IP traffic in this network.");
|
||||
}
|
||||
if changed {
|
||||
agent.send(Command::SetProtocols {
|
||||
network_id: network.network_id.clone(),
|
||||
protocols: selected,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A prominent line about an exit node. One that carries a command copies it
|
||||
/// when clicked.
|
||||
fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) {
|
||||
let text = egui::RichText::new(format!("{} {}", icon::WARNING, warning.text))
|
||||
.color(exit::LOUD)
|
||||
.strong();
|
||||
let label = egui::Label::new(text).wrap();
|
||||
match warning.copy {
|
||||
Some(command) => {
|
||||
let response = ui
|
||||
.add(label.sense(egui::Sense::click()))
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text("click to copy the command");
|
||||
if response.clicked() {
|
||||
ui.ctx().copy_text(command.to_owned());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.add(label);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The join form: aligned name and secret, a generate button, and Join.
|
||||
pub fn draw_join(ui: &mut egui::Ui, agent: &dyn Client, join: &mut JoinForm) {
|
||||
const INPUT_WIDTH: f32 = 208.0;
|
||||
ui.label("Join or create a network");
|
||||
egui::Grid::new("join")
|
||||
.num_columns(2)
|
||||
.spacing([8.0, 6.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label("name");
|
||||
ui.add(egui::TextEdit::singleline(&mut join.name).desired_width(INPUT_WIDTH));
|
||||
ui.end_row();
|
||||
|
||||
ui.label("secret");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut *join.secret)
|
||||
.id("join-secret".into())
|
||||
.desired_width(INPUT_WIDTH - 26.0)
|
||||
.password(true),
|
||||
);
|
||||
if ui
|
||||
.button(icon::SHUFFLE)
|
||||
.on_hover_text("Generate a new random secret")
|
||||
.clicked()
|
||||
{
|
||||
join.secret = tsunagi::identity::NetworkSecret::generate().encode();
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
|
||||
let ready = !join.name.trim().is_empty() && !join.secret.trim().is_empty();
|
||||
if ui
|
||||
.add_enabled(ready, egui::Button::new("Join / create"))
|
||||
.clicked()
|
||||
{
|
||||
agent.send(Command::Join {
|
||||
name: join.name.trim().to_string(),
|
||||
secret: Zeroizing::new(join.secret.trim().to_owned()),
|
||||
});
|
||||
join.secret.zeroize();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Shared presentation for the egui clients.
|
||||
pub mod about;
|
||||
pub mod client;
|
||||
pub mod devices;
|
||||
mod exit;
|
||||
pub mod format;
|
||||
pub mod home;
|
||||
pub mod listeners;
|
||||
pub mod stats;
|
||||
mod table;
|
||||
pub mod vip;
|
||||
mod vip_status;
|
||||
|
||||
/// Install the tray's regular Phosphor glyphs alongside egui's standard fonts.
|
||||
pub fn app_fonts() -> egui::FontDefinitions {
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
|
||||
fonts
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Editor for the listener and backend portion of a shared VIP draft.
|
||||
use tsunagi::vip::{Backend, Listener, Protocol, VipConfig};
|
||||
|
||||
/// Edit local draft fields. Callers own validation, signed revision and Save.
|
||||
pub fn edit(ui: &mut egui::Ui, config: &mut VipConfig, members: &[(String, String)]) {
|
||||
let mut remove = None;
|
||||
for (index, listener) in config.listeners.iter_mut().enumerate() {
|
||||
ui.push_id(&listener.id, |ui| {
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
egui::ComboBox::from_id_salt("protocol")
|
||||
.selected_text(listener.protocol.to_string())
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut listener.protocol, Protocol::Tcp, "TCP");
|
||||
ui.selectable_value(&mut listener.protocol, Protocol::Udp, "UDP");
|
||||
});
|
||||
port_field(ui, "Port", &mut listener.port);
|
||||
if ui.button("Remove listener").clicked() {
|
||||
remove = Some(index);
|
||||
}
|
||||
});
|
||||
if listener.protocol == Protocol::Tcp {
|
||||
ui.checkbox(&mut listener.port_check, "Active TCP port checks");
|
||||
} else {
|
||||
ui.weak("UDP health uses path probes and explicit port errors.");
|
||||
}
|
||||
ui.collapsing("Checks and flow expiry", |ui| {
|
||||
egui::Grid::new("settings").show(ui, |ui| {
|
||||
macro_rules! setting {
|
||||
($label:literal, $value:ident, $range:expr) => {
|
||||
ui.label($label);
|
||||
ui.add(egui::DragValue::new(&mut listener.$value).range($range));
|
||||
ui.end_row();
|
||||
};
|
||||
}
|
||||
setting!("Check interval, ms", check_interval_ms, 250..=3_600_000);
|
||||
setting!("Check timeout, ms", check_timeout_ms, 100..=60_000);
|
||||
setting!("Failures before exclusion", failure_threshold, 1..=255);
|
||||
setting!("Successes before recovery", recovery_threshold, 1..=255);
|
||||
setting!("Flow idle timeout, seconds", idle_timeout_secs, 1..=604800);
|
||||
});
|
||||
});
|
||||
let mut remove_backend = None;
|
||||
for (i, backend) in listener.backends.iter_mut().enumerate() {
|
||||
ui.push_id(i, |ui| {
|
||||
let width = ui.available_width().min(240.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let selected = members
|
||||
.iter()
|
||||
.find(|(id, _)| id == &backend.peer)
|
||||
.map(|(_, label)| label.to_owned())
|
||||
.unwrap_or_else(|| crate::format::short(&backend.peer));
|
||||
egui::ComboBox::from_id_salt("node")
|
||||
.width(width)
|
||||
.truncate()
|
||||
.selected_text(selected)
|
||||
.show_ui(ui, |ui| {
|
||||
for (id, label) in members {
|
||||
ui.selectable_value(&mut backend.peer, id.clone(), label);
|
||||
}
|
||||
});
|
||||
port_field(ui, "Target port", &mut backend.port);
|
||||
if ui.button("Remove").clicked() {
|
||||
remove_backend = Some(i);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some(i) = remove_backend {
|
||||
listener.backends.remove(i);
|
||||
}
|
||||
if ui.button("+ Backend").clicked() {
|
||||
listener.backends.push(Backend {
|
||||
peer: members
|
||||
.first()
|
||||
.map(|(id, _)| id.clone())
|
||||
.unwrap_or_default(),
|
||||
port: listener.port,
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
if let Some(i) = remove {
|
||||
config.listeners.remove(i);
|
||||
}
|
||||
if ui.button("+ Listener").clicked() {
|
||||
config.listeners.push(Listener::new(Protocol::Tcp, 443));
|
||||
}
|
||||
}
|
||||
fn port_field(ui: &mut egui::Ui, label: &str, value: &mut u16) {
|
||||
ui.label(label);
|
||||
ui.add(egui::DragValue::new(value).range(1..=65535));
|
||||
}
|
||||
@@ -16,7 +16,7 @@ const HISTORY: usize = 60;
|
||||
|
||||
/// Which quantity a rate or history is of.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Unit {
|
||||
pub enum Unit {
|
||||
/// Packets per second.
|
||||
Packets,
|
||||
/// Bytes per second.
|
||||
@@ -25,7 +25,7 @@ pub(crate) enum Unit {
|
||||
|
||||
/// One series' rolling packet and byte rates.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Series {
|
||||
pub struct Series {
|
||||
last: Option<(Instant, Counters)>,
|
||||
packets_rate: f32,
|
||||
bytes_rate: f32,
|
||||
@@ -35,7 +35,7 @@ pub(crate) struct Series {
|
||||
|
||||
impl Series {
|
||||
/// Samples a single cumulative counter pair (VIP histories own their lifetime).
|
||||
pub(crate) fn sample(&mut self, now: Instant, packets: u64, bytes: u64) {
|
||||
pub fn sample(&mut self, now: Instant, packets: u64, bytes: u64) {
|
||||
self.sample_peer(
|
||||
now,
|
||||
Counters {
|
||||
@@ -83,7 +83,7 @@ impl Series {
|
||||
}
|
||||
|
||||
/// The current rate in the chosen unit.
|
||||
pub(crate) fn rate(&self, unit: Unit) -> f32 {
|
||||
pub fn rate(&self, unit: Unit) -> f32 {
|
||||
match unit {
|
||||
Unit::Packets => self.packets_rate,
|
||||
Unit::Bytes => self.bytes_rate,
|
||||
@@ -91,7 +91,7 @@ impl Series {
|
||||
}
|
||||
|
||||
/// The rolling history in the chosen unit.
|
||||
pub(crate) fn history(&self, unit: Unit) -> &VecDeque<f32> {
|
||||
pub fn history(&self, unit: Unit) -> &VecDeque<f32> {
|
||||
match unit {
|
||||
Unit::Packets => &self.packets_history,
|
||||
Unit::Bytes => &self.bytes_history,
|
||||
@@ -107,12 +107,18 @@ fn push(history: &mut VecDeque<f32>, value: f32) {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Counters {
|
||||
epoch: u64,
|
||||
tx_packets: u64,
|
||||
rx_packets: u64,
|
||||
tx_bytes: u64,
|
||||
rx_bytes: u64,
|
||||
/// Cumulative tunnel counters in one peer epoch.
|
||||
pub struct Counters {
|
||||
/// Counter reset generation.
|
||||
pub epoch: u64,
|
||||
/// Sent packets.
|
||||
pub tx_packets: u64,
|
||||
/// Received packets.
|
||||
pub rx_packets: u64,
|
||||
/// Sent bytes.
|
||||
pub tx_bytes: u64,
|
||||
/// Received bytes.
|
||||
pub rx_bytes: u64,
|
||||
}
|
||||
|
||||
impl From<&OverlayPeerReport> for Counters {
|
||||
@@ -129,32 +135,53 @@ impl From<&OverlayPeerReport> for Counters {
|
||||
|
||||
/// All traffic series, keyed by a stable string.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Traffic {
|
||||
pub struct Traffic {
|
||||
series: HashMap<String, Series>,
|
||||
}
|
||||
|
||||
impl Traffic {
|
||||
/// Folds a fresh snapshot into the rates. Call once per new generation.
|
||||
pub(crate) fn observe(&mut self, report: &StatusReport, now: Instant) {
|
||||
pub fn observe(&mut self, report: &StatusReport, now: Instant) {
|
||||
self.observe_peers(
|
||||
report.networks.iter().filter_map(|network| {
|
||||
Some((
|
||||
network.network_id.as_str(),
|
||||
network
|
||||
.overlay
|
||||
.as_ref()?
|
||||
.peers
|
||||
.iter()
|
||||
.map(|p| (p.public_key.as_str(), Counters::from(p))),
|
||||
))
|
||||
}),
|
||||
now,
|
||||
);
|
||||
}
|
||||
|
||||
/// Sample live per-peer counters from either an in-process agent or IPC.
|
||||
pub fn observe_peers<'a, I>(
|
||||
&mut self,
|
||||
networks: impl IntoIterator<Item = (&'a str, I)>,
|
||||
now: Instant,
|
||||
) where
|
||||
I: IntoIterator<Item = (&'a str, Counters)>,
|
||||
{
|
||||
let mut active = HashSet::new();
|
||||
for network in &report.networks {
|
||||
let Some(overlay) = &network.overlay else {
|
||||
continue;
|
||||
};
|
||||
for (network, peers) in networks {
|
||||
let (mut packets_rate, mut bytes_rate) = (0.0, 0.0);
|
||||
for peer in &overlay.peers {
|
||||
let key = peer_key(&network.network_id, &peer.public_key);
|
||||
for (peer, counters) in peers {
|
||||
let key = peer_key(network, peer);
|
||||
// Duplicate rows are not additional traffic.
|
||||
if !active.insert(key.clone()) {
|
||||
continue;
|
||||
}
|
||||
let series = self.series.entry(key).or_default();
|
||||
series.sample_peer(now, peer.into());
|
||||
series.sample_peer(now, counters);
|
||||
packets_rate += series.rate(Unit::Packets);
|
||||
bytes_rate += series.rate(Unit::Bytes);
|
||||
}
|
||||
// Sum rates, not cumulative counters of a changing set of peers.
|
||||
let key = net_key(&network.network_id);
|
||||
let key = net_key(network);
|
||||
active.insert(key.clone());
|
||||
self.series
|
||||
.entry(key)
|
||||
@@ -165,12 +192,12 @@ impl Traffic {
|
||||
}
|
||||
|
||||
/// The network-total series, if sampled.
|
||||
pub(crate) fn network(&self, network_id: &str) -> Option<&Series> {
|
||||
pub fn network(&self, network_id: &str) -> Option<&Series> {
|
||||
self.series.get(&net_key(network_id))
|
||||
}
|
||||
|
||||
/// One peer's series, if sampled.
|
||||
pub(crate) fn peer(&self, network_id: &str, public_key: &str) -> Option<&Series> {
|
||||
pub fn peer(&self, network_id: &str, public_key: &str) -> Option<&Series> {
|
||||
self.series.get(&peer_key(network_id, public_key))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Fixed row geometry for dense live tables. Children cannot resize a row or
|
||||
//! paint into its neighbours; the enclosing scroll area owns overflow.
|
||||
use eframe::egui;
|
||||
|
||||
pub(crate) const GAP: f32 = 10.0;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! Per-network VIP editor. Drafts never issue commands until Save is pressed.
|
||||
use crate::agent::{AgentClient, Command, Snapshot};
|
||||
use crate::client::{Client, Command, Snapshot};
|
||||
use crate::vip_status;
|
||||
use eframe::egui;
|
||||
use tsunagi::ipc::NetworkReport;
|
||||
use tsunagi::vip::{Backend, Listener, Protocol, VipConfig};
|
||||
use tsunagi::vip::VipConfig;
|
||||
#[cfg(test)]
|
||||
use tsunagi::vip::{Listener, Protocol};
|
||||
#[derive(Clone)]
|
||||
struct Draft {
|
||||
config: VipConfig,
|
||||
@@ -25,7 +26,8 @@ impl Draft {
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Window {
|
||||
/// A network’s edit draft, selection and traffic history.
|
||||
pub struct Window {
|
||||
draft: Option<Draft>,
|
||||
pending: Option<String>,
|
||||
error: Option<String>,
|
||||
@@ -37,28 +39,30 @@ pub(crate) struct Window {
|
||||
acknowledged_generation: Option<u64>,
|
||||
}
|
||||
impl Window {
|
||||
/// Ask whether to discard an outstanding draft.
|
||||
pub fn request_close(&mut self) {
|
||||
self.close_question = true;
|
||||
self.close_after_save = true;
|
||||
}
|
||||
/// Whether closing needs confirmation.
|
||||
pub fn dirty(&self) -> bool {
|
||||
self.draft.as_ref().is_some_and(Draft::dirty) || self.pending.is_some()
|
||||
}
|
||||
}
|
||||
fn peer_name<'a>(n: &'a NetworkReport, id: &'a str) -> &'a str {
|
||||
n.members
|
||||
.iter()
|
||||
.find(|m| m.endpoint_id == id)
|
||||
.and_then(|m| m.hostname.as_deref())
|
||||
.unwrap_or(id)
|
||||
}
|
||||
pub(crate) fn show(
|
||||
/// Render the editor and overview. Returns true when its view can close.
|
||||
pub fn show(
|
||||
ctx: &egui::Context,
|
||||
agent: &AgentClient,
|
||||
agent: &dyn Client,
|
||||
state: &mut Window,
|
||||
n: &NetworkReport,
|
||||
snapshot: &Snapshot,
|
||||
) -> bool {
|
||||
if state.generation == 0
|
||||
&& state.draft.is_none()
|
||||
&& let [vip] = n.vips.as_slice()
|
||||
{
|
||||
state.draft = Some(Draft::new(vip.config.clone(), Some(vip.revision.clone())));
|
||||
}
|
||||
if state.generation != snapshot.generation {
|
||||
state.generation = snapshot.generation;
|
||||
if let Some(at) = snapshot.at {
|
||||
@@ -92,7 +96,7 @@ pub(crate) fn show(
|
||||
ui.heading(format!("VIP · {}", n.name));
|
||||
ui.weak("Configuration is shared with every member. Changes take effect only after Save.");
|
||||
if state.close_question {
|
||||
ui.horizontal(|ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label("Unsaved changes.");
|
||||
if ui
|
||||
.add_enabled(
|
||||
@@ -172,7 +176,7 @@ pub(crate) fn show(
|
||||
);
|
||||
}
|
||||
let busy = state.pending.is_some();
|
||||
ui.horizontal(|ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let valid = draft.config.validate(&tsunagi::Limits::default());
|
||||
if !n.active {
|
||||
ui.weak("Start the network to save changes.");
|
||||
@@ -229,7 +233,7 @@ pub(crate) fn show(
|
||||
.show(ui, |ui| {
|
||||
if state.configure {
|
||||
ui.add_enabled_ui(!busy, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label("Name");
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut draft.config.name)
|
||||
@@ -258,32 +262,23 @@ pub(crate) fn show(
|
||||
close
|
||||
}
|
||||
fn edit_listeners(ui: &mut egui::Ui, config: &mut VipConfig, n: &NetworkReport) {
|
||||
let mut remove = None;
|
||||
for (index, l) in config.listeners.iter_mut().enumerate() {
|
||||
ui.push_id(index,|ui|{egui::Frame::group(ui.style()).show(ui,|ui|{
|
||||
ui.horizontal(|ui|{egui::ComboBox::from_id_salt("protocol").selected_text(l.protocol.to_string()).show_ui(ui,|ui|{ui.selectable_value(&mut l.protocol,Protocol::Tcp,"TCP");ui.selectable_value(&mut l.protocol,Protocol::Udp,"UDP");});ui.label("Port");ui.add(egui::DragValue::new(&mut l.port).range(1..=65535));if ui.button("Remove listener").clicked(){remove=Some(index);}});
|
||||
if l.protocol==Protocol::Tcp{ui.checkbox(&mut l.port_check,"Active TCP port checks");}else{ui.weak("UDP health: encrypted path probes and explicit port errors; application readiness is unknown.");}
|
||||
ui.collapsing("Checks and flow expiry",|ui|{egui::Grid::new("settings").show(ui,|ui|{
|
||||
ui.label("Check interval, ms");ui.add(egui::DragValue::new(&mut l.check_interval_ms).range(250..=3_600_000));ui.end_row();
|
||||
ui.label("Check timeout, ms");ui.add(egui::DragValue::new(&mut l.check_timeout_ms).range(100..=60_000));ui.end_row();
|
||||
ui.label("Failures before exclusion");ui.add(egui::DragValue::new(&mut l.failure_threshold).range(1..=255));ui.end_row();
|
||||
ui.label("Successes before recovery");ui.add(egui::DragValue::new(&mut l.recovery_threshold).range(1..=255));ui.end_row();
|
||||
ui.label("Flow idle timeout, seconds");ui.add(egui::DragValue::new(&mut l.idle_timeout_secs).range(1..=604800));ui.end_row();
|
||||
});});
|
||||
let mut remove_backend=None;for(i,b)in l.backends.iter_mut().enumerate(){ui.push_id(i,|ui|{ui.horizontal(|ui|{
|
||||
egui::ComboBox::from_id_salt("node").width(240.).selected_text(peer_name(n,&b.peer)).show_ui(ui,|ui|{for m in &n.members{let label=format!("{} ({})",m.hostname.as_deref().unwrap_or("unnamed"),m.endpoint_id.chars().take(8).collect::<String>());ui.selectable_value(&mut b.peer,m.endpoint_id.clone(),label);}});
|
||||
ui.label("Target port");ui.add(egui::DragValue::new(&mut b.port).range(1..=65535));if ui.button("Remove").clicked(){remove_backend=Some(i);}
|
||||
});});}if let Some(i)=remove_backend{l.backends.remove(i);}
|
||||
if ui.button("+ Backend").clicked(){l.backends.push(Backend{peer:n.members.first().map(|m|m.endpoint_id.clone()).unwrap_or_default(),port:l.port});}
|
||||
});});
|
||||
}
|
||||
if let Some(index) = remove {
|
||||
config.listeners.remove(index);
|
||||
}
|
||||
if ui.button("+ Listener").clicked() {
|
||||
config.listeners.push(Listener::new(Protocol::Tcp, 443));
|
||||
}
|
||||
let members = n
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| {
|
||||
(
|
||||
m.endpoint_id.clone(),
|
||||
format!(
|
||||
"{} ({})",
|
||||
m.hostname.as_deref().unwrap_or("unnamed"),
|
||||
crate::format::short(&m.endpoint_id)
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
crate::listeners::edit(ui, config, &members);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
@@ -291,7 +286,17 @@ mod tests {
|
||||
use tsunagi::vip::VipStatus;
|
||||
#[test]
|
||||
fn editing_the_actual_form_sends_nothing_until_save_is_clicked() {
|
||||
let (agent, mut commands) = AgentClient::test_client();
|
||||
let (tx, commands) = std::sync::mpsc::channel();
|
||||
struct TestClient(std::sync::mpsc::Sender<Command>);
|
||||
impl Client for TestClient {
|
||||
fn send(&self, command: Command) {
|
||||
self.0.send(command).unwrap();
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
let agent = TestClient(tx);
|
||||
let ctx = egui::Context::default();
|
||||
let mut config = VipConfig::new("api");
|
||||
config.listeners.push(Listener::new(Protocol::Tcp, 443));
|
||||
@@ -2,7 +2,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use eframe::egui;
|
||||
use tsunagi::ipc::NetworkReport;
|
||||
use tsunagi::vip::{Backend, BackendStatus, Counters, ListenerStatus, Protocol, VipStatus};
|
||||
|
||||
@@ -61,12 +60,14 @@ fn key(v: &VipStatus, l: &ListenerStatus, b: &Backend) -> Key {
|
||||
)
|
||||
}
|
||||
struct Camera {
|
||||
layout_width: f32,
|
||||
rect: egui::Rect,
|
||||
members: Vec<Backend>,
|
||||
}
|
||||
impl Default for Camera {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
layout_width: 0.0,
|
||||
rect: egui::Rect::NOTHING,
|
||||
members: Vec::new(),
|
||||
}
|
||||
@@ -450,21 +451,36 @@ fn diagram(
|
||||
.entry((v.config.id.clone(), l.protocol.to_string(), l.port))
|
||||
.or_default();
|
||||
let members: Vec<_> = l.backends.iter().map(|b| b.backend.clone()).collect();
|
||||
let height = (members.len().max(1) as f32 * 92.0 + 32.0).max(180.0);
|
||||
let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(860.0, height));
|
||||
if camera.members != members || !camera.rect.is_positive() {
|
||||
let compact = ui.available_width() < 540.0;
|
||||
let width = if compact {
|
||||
ui.available_width().max(240.0)
|
||||
} else {
|
||||
860.0
|
||||
};
|
||||
let pitch = if compact { 66.0 } else { 92.0 };
|
||||
let height = (members.len().max(1) as f32 * pitch + 32.0).max(160.0);
|
||||
let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height));
|
||||
if camera.members != members
|
||||
|| !camera.rect.is_positive()
|
||||
|| (camera.layout_width - width).abs() > 1.0
|
||||
{
|
||||
camera.rect = bounds;
|
||||
camera.layout_width = width;
|
||||
camera.members = members;
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
legend(ui, "Traffic", ACTIVE, true);
|
||||
legend(ui, "Next new flow", NEXT, false);
|
||||
ui.weak("Click a backend · drag to pan · Ctrl+scroll to zoom");
|
||||
ui.weak(if compact {
|
||||
"Tap a backend · pinch to zoom"
|
||||
} else {
|
||||
"Click a backend · drag to pan · Ctrl+scroll to zoom"
|
||||
});
|
||||
if ui.small_button("Fit").clicked() {
|
||||
camera.rect = bounds;
|
||||
}
|
||||
});
|
||||
let size = egui::vec2(ui.available_width(), height.clamp(180.0, 360.0));
|
||||
let size = egui::vec2(ui.available_width(), height.clamp(160.0, 360.0));
|
||||
let (outer, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
ui.painter()
|
||||
.rect_filled(outer, 6.0, ui.visuals().extreme_bg_color);
|
||||
@@ -475,12 +491,19 @@ fn diagram(
|
||||
.show(&mut child, &mut camera.rect, |ui| {
|
||||
ui.set_min_size(bounds.size());
|
||||
let center = height / 2.0;
|
||||
let source =
|
||||
egui::Rect::from_min_size(egui::pos2(18.0, center - 32.0), egui::vec2(204.0, 64.0));
|
||||
let listener = egui::Rect::from_min_size(
|
||||
egui::pos2(290.0, center - 32.0),
|
||||
egui::vec2(146.0, 64.0),
|
||||
);
|
||||
let rect = |x, y, w, h| egui::Rect::from_min_size(egui::pos2(x, y), egui::vec2(w, h));
|
||||
let (source, listener) = if compact {
|
||||
let w = width * 0.40;
|
||||
(
|
||||
rect(8.0, center - 65.0, w, 52.0),
|
||||
rect(8.0, center + 12.0, w, 52.0),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
rect(18.0, center - 32.0, 204.0, 64.0),
|
||||
rect(290.0, center - 32.0, 146.0, 64.0),
|
||||
)
|
||||
};
|
||||
let active = l.backends.iter().any(|b| {
|
||||
view.backends
|
||||
.get(&key(v, l, &b.backend))
|
||||
@@ -488,8 +511,16 @@ fn diagram(
|
||||
});
|
||||
edge(
|
||||
ui,
|
||||
source.right_center(),
|
||||
listener.left_center(),
|
||||
if compact {
|
||||
source.center_bottom()
|
||||
} else {
|
||||
source.right_center()
|
||||
},
|
||||
if compact {
|
||||
listener.center_top()
|
||||
} else {
|
||||
listener.left_center()
|
||||
},
|
||||
if active { ACTIVE } else { NEXT },
|
||||
active,
|
||||
);
|
||||
@@ -513,10 +544,16 @@ fn diagram(
|
||||
let key = key(v, l, &b.backend);
|
||||
let rates = view.backends.get(&key);
|
||||
let state = branch(l, b, rates, Instant::now());
|
||||
let rect = egui::Rect::from_min_size(
|
||||
egui::pos2(558.0, 24.0 + index as f32 * 92.0),
|
||||
egui::vec2(278.0, 68.0),
|
||||
);
|
||||
let rect = if compact {
|
||||
rect(
|
||||
width * 0.51,
|
||||
10.0 + index as f32 * pitch,
|
||||
width * 0.49 - 8.0,
|
||||
56.0,
|
||||
)
|
||||
} else {
|
||||
rect(558.0, 24.0 + index as f32 * pitch, 278.0, 68.0)
|
||||
};
|
||||
let color = if state.active {
|
||||
ACTIVE
|
||||
} else if state.next {
|
||||
@@ -575,7 +612,7 @@ fn diagram(
|
||||
}
|
||||
if l.backends.is_empty() {
|
||||
ui.painter().text(
|
||||
egui::pos2(570.0, center),
|
||||
egui::pos2(if compact { width * 0.52 } else { 570.0 }, center),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"No backends",
|
||||
egui::FontId::proportional(15.0),
|
||||
@@ -648,14 +685,15 @@ fn text_line(
|
||||
painter.galley(position, painter.layout_job(job), color);
|
||||
}
|
||||
fn edge(ui: &egui::Ui, start: egui::Pos2, end: egui::Pos2, color: egui::Color32, active: bool) {
|
||||
let bend = (end.x - start.x) * 0.5;
|
||||
let delta = end - start;
|
||||
let direction = if delta.x.abs() < 1.0 {
|
||||
egui::Vec2::Y
|
||||
} else {
|
||||
egui::Vec2::X
|
||||
};
|
||||
let bend = direction * delta.dot(direction) * 0.5;
|
||||
let curve = egui::epaint::CubicBezierShape::from_points_stroke(
|
||||
[
|
||||
start,
|
||||
start + egui::vec2(bend, 0.0),
|
||||
end - egui::vec2(bend, 0.0),
|
||||
end,
|
||||
],
|
||||
[start, start + bend, end - bend, end],
|
||||
false,
|
||||
egui::Color32::TRANSPARENT,
|
||||
egui::Stroke::new(if active { 3.0_f32 } else { 1.5_f32 }, color),
|
||||
@@ -668,8 +706,8 @@ fn edge(ui: &egui::Ui, start: egui::Pos2, end: egui::Pos2, color: egui::Color32,
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(40));
|
||||
}
|
||||
ui.painter().arrow(
|
||||
end - egui::vec2(12.0, 0.0),
|
||||
egui::vec2(10.0, 0.0),
|
||||
end - direction * 12.0,
|
||||
direction * 10.0,
|
||||
egui::Stroke::new(1.5_f32, color),
|
||||
);
|
||||
}
|
||||
@@ -859,7 +897,7 @@ mod tests {
|
||||
let (n, v) = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut view = View::default();
|
||||
for width in [650.0, 1000.0, 1800.0, 650.0] {
|
||||
for width in [360.0, 412.0, 650.0, 1000.0, 1800.0, 360.0] {
|
||||
for _ in 0..2 {
|
||||
let _ = ctx.run(
|
||||
egui::RawInput {
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user