Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04b5ebc1a0 | ||
|
|
429fa36e3e | ||
|
|
ef67e1c0ae | ||
|
|
9dec056349 | ||
|
|
91227afbac | ||
|
|
66206544b0 | ||
|
|
2166ba4800 | ||
|
|
8a6216bccb | ||
|
|
2e7e238459 | ||
|
|
23af1a2d9d | ||
|
|
94318e7c16 | ||
|
|
2b0c938487 | ||
|
|
4e235cbac6 |
No files matched your search
@@ -127,7 +127,7 @@ jobs:
|
|||||||
# (x86_64 only) against the runner's glibc.
|
# (x86_64 only) against the runner's glibc.
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y --no-install-recommends \
|
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 \
|
cargo build --release --locked \
|
||||||
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
|
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
|
||||||
else
|
else
|
||||||
@@ -237,7 +237,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
version="${GITHUB_REF_NAME#v}"
|
version="${GITHUB_REF_NAME#v}"
|
||||||
pkgver="${version//-/_}"
|
pkgver="${version//-/}"
|
||||||
bash dist/arch/build-pkg.sh \
|
bash dist/arch/build-pkg.sh \
|
||||||
"target/${{ matrix.target }}/release/tsng" \
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
"${{ matrix.pkg_arch }}" \
|
"${{ matrix.pkg_arch }}" \
|
||||||
@@ -252,7 +252,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
version="${GITHUB_REF_NAME#v}"
|
version="${GITHUB_REF_NAME#v}"
|
||||||
pkgver="${version//-/_}"
|
pkgver="${version//-/}"
|
||||||
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
|
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
|
||||||
bash dist/deb/build-deb.sh \
|
bash dist/deb/build-deb.sh \
|
||||||
"target/${{ matrix.target }}/release/tsng" \
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
name: Release
|
name: Release
|
||||||
|
|
||||||
# GitHub version of the release pipeline. The build half mirrors the Gitea one
|
# Desktop builds mirror .gitea/workflows/release.yml. GitHub also builds and
|
||||||
# in .gitea/workflows/release.yml (static musl Linux via cargo-zigbuild, native
|
# signs the Android APK and attaches all platform packages to the tag with gh.
|
||||||
# macOS and Windows); only the publish half differs: it uses the current
|
|
||||||
# artifact actions (Node 24) and fills the release with `gh`.
|
|
||||||
#
|
#
|
||||||
# Every job is gated on `github.server_url == 'https://github.com'`, so this file
|
# 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
|
# runs only on GitHub. Gitea runs its own copy in .gitea/workflows (which pins
|
||||||
@@ -30,7 +28,7 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-26.04
|
||||||
target: x86_64-unknown-linux-musl
|
target: x86_64-unknown-linux-musl
|
||||||
asset: tsunagi-linux-x86_64
|
asset: tsunagi-linux-x86_64
|
||||||
archive: tar.gz
|
archive: tar.gz
|
||||||
@@ -129,7 +127,7 @@ jobs:
|
|||||||
# (x86_64 only) against the runner's glibc.
|
# (x86_64 only) against the runner's glibc.
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y --no-install-recommends \
|
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 \
|
cargo build --release --locked \
|
||||||
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
|
--target "${{ matrix.gnu_target }}" --bin tsunagi-tray
|
||||||
else
|
else
|
||||||
@@ -239,7 +237,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
version="${GITHUB_REF_NAME#v}"
|
version="${GITHUB_REF_NAME#v}"
|
||||||
pkgver="${version//-/_}"
|
pkgver="${version//-/}"
|
||||||
bash dist/arch/build-pkg.sh \
|
bash dist/arch/build-pkg.sh \
|
||||||
"target/${{ matrix.target }}/release/tsng" \
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
"${{ matrix.pkg_arch }}" \
|
"${{ matrix.pkg_arch }}" \
|
||||||
@@ -254,7 +252,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
version="${GITHUB_REF_NAME#v}"
|
version="${GITHUB_REF_NAME#v}"
|
||||||
pkgver="${version//-/_}"
|
pkgver="${version//-/}"
|
||||||
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
|
tray="target/${{ matrix.gnu_target }}/release/tsunagi-tray"
|
||||||
bash dist/deb/build-deb.sh \
|
bash dist/deb/build-deb.sh \
|
||||||
"target/${{ matrix.target }}/release/tsng" \
|
"target/${{ matrix.target }}/release/tsng" \
|
||||||
@@ -276,9 +274,77 @@ jobs:
|
|||||||
tsunagi-setup-*.exe
|
tsunagi-setup-*.exe
|
||||||
if-no-files-found: error
|
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:
|
publish:
|
||||||
name: Publish release
|
name: Publish release
|
||||||
needs: build
|
needs: [build, android]
|
||||||
if: ${{ github.server_url == 'https://github.com' }}
|
if: ${{ github.server_url == 'https://github.com' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
@@ -303,6 +369,9 @@ jobs:
|
|||||||
# download-artifact nests each artifact under its own directory, so
|
# download-artifact nests each artifact under its own directory, so
|
||||||
# the archives are artifacts/<asset>/<file>.
|
# the archives are artifacts/<asset>/<file>.
|
||||||
mapfile -t files < <(find artifacts -type f \( -name '*.tar.gz' -o -name '*.zip' -o -name '*.deb' -o -name '*.pkg.tar.zst' -o -name 'tsunagi-setup-*.exe' \))
|
mapfile -t files < <(find artifacts -type f \( -name '*.tar.gz' -o -name '*.zip' -o -name '*.deb' -o -name '*.pkg.tar.zst' -o -name 'tsunagi-setup-*.exe' \))
|
||||||
|
apk="artifacts/tsunagi-android/tsunagi-android-${TAG#v}-arm64-v8a.apk"
|
||||||
|
[[ -s "$apk" ]] || { echo "::error::Missing release APK at $apk"; exit 1; }
|
||||||
|
files+=("$apk")
|
||||||
printf 'asset: %s\n' "${files[@]}"
|
printf 'asset: %s\n' "${files[@]}"
|
||||||
|
|
||||||
prerelease=()
|
prerelease=()
|
||||||
@@ -320,3 +389,96 @@ jobs:
|
|||||||
--verify-tag \
|
--verify-tag \
|
||||||
"${prerelease[@]}"
|
"${prerelease[@]}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
notify-arch-repository:
|
||||||
|
name: Publish packages to the Arch repository
|
||||||
|
needs: publish
|
||||||
|
if: ${{ github.server_url == 'https://github.com' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions: {}
|
||||||
|
steps:
|
||||||
|
- name: Notify arch_repo of the completed release
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.ARCH_REPO_TOKEN }}
|
||||||
|
RELEASE_TAG: ${{ github.ref_name }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [[ -z "$GH_TOKEN" ]]; then
|
||||||
|
echo '::error::Set the ARCH_REPO_TOKEN Actions secret with Contents: write access to house-of-vanity/arch_repo.'
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
jq -n --arg repository "$GITHUB_REPOSITORY" --arg tag "$RELEASE_TAG" \
|
||||||
|
'{event_type: "new_package", client_payload: {repository: $repository, tag: $tag}}' \
|
||||||
|
| gh api --method POST repos/house-of-vanity/arch_repo/dispatches --input -
|
||||||
|
|
||||||
|
publish-openartifact:
|
||||||
|
name: Publish APT and pacman packages
|
||||||
|
needs: publish
|
||||||
|
if: github.server_url == 'https://github.com'
|
||||||
|
runs-on: ubuntu-26.04
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
id-token: write
|
||||||
|
env:
|
||||||
|
OA_SERVER: https://repo.hexor.cy
|
||||||
|
APT_SUITE: resolute
|
||||||
|
steps:
|
||||||
|
- name: Download packages attached to this release
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
gh release download "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" \
|
||||||
|
--pattern '*.deb' --pattern '*.pkg.tar.zst' --dir packages
|
||||||
|
|
||||||
|
- name: Publish packages
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
id_token=$(curl -fsS -G --data-urlencode "audience=$OA_SERVER" \
|
||||||
|
-H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
|
||||||
|
"$ACTIONS_ID_TOKEN_REQUEST_URL" | jq -er '.value')
|
||||||
|
oa_token=$(jq -n --arg token "$id_token" \
|
||||||
|
'{token:$token,policy:"github-tsunagi-release"}' | \
|
||||||
|
curl -fsS --json @- "$OA_SERVER/api/v1/auth/oidc/exchange" | jq -er '.access_token')
|
||||||
|
echo "::add-mask::$oa_token"
|
||||||
|
auth=(-H "Authorization: Bearer $oa_token")
|
||||||
|
|
||||||
|
for file in packages/*.deb packages/*.pkg.tar.zst; do
|
||||||
|
[[ -f "$file" ]] || { echo "Missing release artifact: $file"; exit 1; }
|
||||||
|
name=${file##*/}
|
||||||
|
case "$name" in
|
||||||
|
*.deb)
|
||||||
|
arch=$(dpkg-deb -f "$file" Architecture)
|
||||||
|
status=$(curl -sS -o "$RUNNER_TEMP/oa-upload.json" -w '%{http_code}' \
|
||||||
|
"${auth[@]}" -F "file=@$file" -F "distribution=$APT_SUITE" -F component=main \
|
||||||
|
"$OA_SERVER/api/v1/repositories/hexor-apt/debs")
|
||||||
|
;;
|
||||||
|
*.pkg.tar.zst)
|
||||||
|
stem=${name%.pkg.tar.zst}
|
||||||
|
arch=${stem##*-}
|
||||||
|
url="$OA_SERVER/repos/hexor-pacman/os/$arch/$name"
|
||||||
|
status=$(curl -sS -o "$RUNNER_TEMP/oa-upload.json" -w '%{http_code}' \
|
||||||
|
"${auth[@]}" -T "$file" "$url")
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
case "$status" in
|
||||||
|
2??) echo "Published $name" ;;
|
||||||
|
409)
|
||||||
|
# An immutable version may already exist after a partial run.
|
||||||
|
digest=$(sha256sum "$file" | cut -d ' ' -f1)
|
||||||
|
if [[ "$name" == *.deb ]]; then
|
||||||
|
index="$OA_SERVER/repos/hexor-apt/dists/$APT_SUITE/main/binary-$arch/Packages"
|
||||||
|
curl -fsS "${auth[@]}" "$index" | grep -Fx "SHA256: $digest" >/dev/null || {
|
||||||
|
echo "Existing $name has different contents or is outside $APT_SUITE" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
else
|
||||||
|
remote=$(curl -fsS "${auth[@]}" "$url" | sha256sum | cut -d ' ' -f1)
|
||||||
|
[[ "$remote" == "$digest" ]] || { echo "Different bytes for $name"; exit 1; }
|
||||||
|
fi
|
||||||
|
echo "Already published with matching SHA-256: $name"
|
||||||
|
;;
|
||||||
|
*) echo "Upload of $name returned HTTP $status" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
@@ -162,7 +162,7 @@ Keep these separate. Crossing them is the main thing to review for.
|
|||||||
| `crates/tsunagi-core/src/overlay/` | the one interface an agent owns: provisioning, the TUN, routing, source checks, broadcast host rules |
|
| `crates/tsunagi-core/src/overlay/` | the one interface an agent owns: provisioning, the TUN, routing, source checks, broadcast host rules |
|
||||||
| `crates/tsunagi-core/src/dataplane/` | the protocol contract and the authenticated packet transport |
|
| `crates/tsunagi-core/src/dataplane/` | the protocol contract and the authenticated packet transport |
|
||||||
| `crates/tsunagi-core/src/dns/` | the DNS view of a network: zone, server, resolver publication |
|
| `crates/tsunagi-core/src/dns/` | the DNS view of a network: zone, server, resolver publication |
|
||||||
| `crates/tsunagi-wg-quic/` | the `wg-quic` protocol: its keys, its announcement, its tunnels |
|
| `crates/tsunagi-wg-quic/` | the single internal WireGuard cipher, keys and opaque announcement; historical crate name |
|
||||||
| `crates/tsunagi/` | the command line agent, built as `tsng`; the only place that owns a runtime, a logger and signals |
|
| `crates/tsunagi/` | the command line agent, built as `tsng`; the only place that owns a runtime, a logger and signals |
|
||||||
| `tests/` | integration tests; `tests/common/` is the shared harness |
|
| `tests/` | integration tests; `tests/common/` is the shared harness |
|
||||||
|
|
||||||
|
|||||||
Generated
+147
-61
@@ -601,6 +601,12 @@ dependencies = [
|
|||||||
"syn 3.0.6",
|
"syn 3.0.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "byteorder"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "byteorder-lite"
|
name = "byteorder-lite"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -1171,6 +1177,46 @@ dependencies = [
|
|||||||
"syn 3.0.6",
|
"syn 3.0.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "defmt"
|
||||||
|
version = "0.3.101"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4deef977660e373c458df605a913d4ab121db0ccd18d1ad6976dff7d37cddb53"
|
||||||
|
dependencies = [
|
||||||
|
"defmt 1.2.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "defmt"
|
||||||
|
version = "1.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 1.3.2",
|
||||||
|
"defmt-macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "defmt-macros"
|
||||||
|
version = "1.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366"
|
||||||
|
dependencies = [
|
||||||
|
"defmt-parser",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "defmt-parser"
|
||||||
|
version = "1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0"
|
||||||
|
dependencies = [
|
||||||
|
"thiserror 2.0.20",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "der"
|
name = "der"
|
||||||
version = "0.8.2"
|
version = "0.8.2"
|
||||||
@@ -2366,6 +2412,15 @@ dependencies = [
|
|||||||
"zerocopy",
|
"zerocopy",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hash32"
|
||||||
|
version = "0.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
|
||||||
|
dependencies = [
|
||||||
|
"byteorder",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.15.5"
|
version = "0.15.5"
|
||||||
@@ -2404,6 +2459,16 @@ dependencies = [
|
|||||||
"hashbrown 0.17.1",
|
"hashbrown 0.17.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "heapless"
|
||||||
|
version = "0.8.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
|
||||||
|
dependencies = [
|
||||||
|
"hash32",
|
||||||
|
"stable_deref_trait",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "heck"
|
name = "heck"
|
||||||
version = "0.4.1"
|
version = "0.4.1"
|
||||||
@@ -2806,8 +2871,6 @@ checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "iroh"
|
name = "iroh"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b2f8d1cfffc83efe39a1031aab423ce09cb8048071baba550508931e9a81ce46"
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"backon",
|
"backon",
|
||||||
"blake3",
|
"blake3",
|
||||||
@@ -3190,25 +3253,6 @@ dependencies = [
|
|||||||
"vcpkg",
|
"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]]
|
[[package]]
|
||||||
name = "linux-raw-sys"
|
name = "linux-raw-sys"
|
||||||
version = "0.4.15"
|
version = "0.4.15"
|
||||||
@@ -3317,6 +3361,12 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "managed"
|
||||||
|
version = "0.8.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "matchers"
|
name = "matchers"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -3422,7 +3472,6 @@ dependencies = [
|
|||||||
"dpi",
|
"dpi",
|
||||||
"gtk",
|
"gtk",
|
||||||
"keyboard-types",
|
"keyboard-types",
|
||||||
"libxdo",
|
|
||||||
"objc2 0.6.4",
|
"objc2 0.6.4",
|
||||||
"objc2-app-kit 0.3.2",
|
"objc2-app-kit 0.3.2",
|
||||||
"objc2-core-foundation",
|
"objc2-core-foundation",
|
||||||
@@ -5518,6 +5567,20 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "smoltcp"
|
||||||
|
version = "0.12.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "dad095989c1533c1c266d9b1e8d70a1329dd3723c3edac6d03bbd67e7bf6f4bb"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 1.3.2",
|
||||||
|
"byteorder",
|
||||||
|
"cfg-if",
|
||||||
|
"defmt 0.3.101",
|
||||||
|
"heapless",
|
||||||
|
"managed",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "socket2"
|
name = "socket2"
|
||||||
version = "0.6.5"
|
version = "0.6.5"
|
||||||
@@ -6233,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi"
|
name = "tsunagi"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anstream",
|
"anstream",
|
||||||
"anstyle",
|
"anstyle",
|
||||||
@@ -6241,13 +6304,14 @@ dependencies = [
|
|||||||
"iroh",
|
"iroh",
|
||||||
"netwatch",
|
"netwatch",
|
||||||
"nix 0.31.3",
|
"nix 0.31.3",
|
||||||
|
"serde_json",
|
||||||
"simple-dns",
|
"simple-dns",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"tsunagi-awg",
|
|
||||||
"tsunagi-core",
|
"tsunagi-core",
|
||||||
|
"tsunagi-runtime",
|
||||||
"tsunagi-tcp-tls",
|
"tsunagi-tcp-tls",
|
||||||
"tsunagi-wg-quic",
|
"tsunagi-wg-quic",
|
||||||
"tsunagi-wireguard",
|
"tsunagi-wireguard",
|
||||||
@@ -6255,28 +6319,47 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-awg"
|
name = "tsunagi-android"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"boringtun",
|
|
||||||
"bytes",
|
"bytes",
|
||||||
"chacha20 0.9.1",
|
"egui",
|
||||||
|
"egui-phosphor",
|
||||||
|
"egui_glow",
|
||||||
"iroh",
|
"iroh",
|
||||||
"postcard",
|
"jni 0.21.1",
|
||||||
|
"jni 0.22.4",
|
||||||
"rand 0.10.3",
|
"rand 0.10.3",
|
||||||
"serde",
|
"rustls-platform-verifier",
|
||||||
|
"simple-dns",
|
||||||
|
"smoltcp",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
|
||||||
"tsunagi-core",
|
"tsunagi-core",
|
||||||
|
"tsunagi-runtime",
|
||||||
|
"tsunagi-ui",
|
||||||
"tsunagi-wg-quic",
|
"tsunagi-wg-quic",
|
||||||
"tsunagi-wireguard",
|
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tsunagi-awg"
|
||||||
|
version = "1.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"iroh",
|
||||||
|
"rand 0.10.3",
|
||||||
|
"smoltcp",
|
||||||
|
"tempfile",
|
||||||
|
"tokio",
|
||||||
|
"tsunagi-core",
|
||||||
|
"tsunagi-wg-quic",
|
||||||
|
"tsunagi-wireguard",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-core"
|
name = "tsunagi-core"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"arc-swap",
|
"arc-swap",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -6316,38 +6399,42 @@ dependencies = [
|
|||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tsunagi-runtime"
|
||||||
|
version = "1.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"tokio",
|
||||||
|
"tracing",
|
||||||
|
"tsunagi-awg",
|
||||||
|
"tsunagi-core",
|
||||||
|
"tsunagi-tcp-tls",
|
||||||
|
"tsunagi-wg-quic",
|
||||||
|
"tsunagi-wireguard",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-tcp-tls"
|
name = "tsunagi-tcp-tls"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"caps",
|
"caps",
|
||||||
"chacha20poly1305",
|
|
||||||
"hex",
|
|
||||||
"hkdf",
|
|
||||||
"iroh",
|
"iroh",
|
||||||
"netdev 0.46.3",
|
"netdev 0.46.3",
|
||||||
"postcard",
|
"postcard",
|
||||||
"rand 0.10.3",
|
|
||||||
"rcgen",
|
"rcgen",
|
||||||
"rustls",
|
"rustls",
|
||||||
"serde",
|
"serde",
|
||||||
"sha2",
|
|
||||||
"subtle",
|
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.20",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"tsunagi-core",
|
"tsunagi-core",
|
||||||
"x25519-dalek",
|
|
||||||
"zeroize",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-tray"
|
name = "tsunagi-tray"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"eframe",
|
"eframe",
|
||||||
"egui-phosphor",
|
"egui-phosphor",
|
||||||
@@ -6357,12 +6444,23 @@ dependencies = [
|
|||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"tray-icon",
|
"tray-icon",
|
||||||
"tsunagi-core",
|
"tsunagi-core",
|
||||||
|
"tsunagi-ui",
|
||||||
"winit",
|
"winit",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tsunagi-ui"
|
||||||
|
version = "1.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"egui",
|
||||||
|
"egui-phosphor",
|
||||||
|
"tsunagi-core",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-wg-quic"
|
name = "tsunagi-wg-quic"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"boringtun",
|
"boringtun",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -6382,26 +6480,24 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"tsunagi-core",
|
"tsunagi-core",
|
||||||
|
"tsunagi-tcp-tls",
|
||||||
|
"tsunagi-wireguard",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-wireguard"
|
name = "tsunagi-wireguard"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"boringtun",
|
"boringtun",
|
||||||
"bytes",
|
"bytes",
|
||||||
"data-encoding",
|
"chacha20 0.9.1",
|
||||||
"hex",
|
|
||||||
"iroh",
|
"iroh",
|
||||||
"netdev 0.46.3",
|
"netdev 0.46.3",
|
||||||
"postcard",
|
"postcard",
|
||||||
"rand 0.10.3",
|
"rand 0.10.3",
|
||||||
"rusqlite",
|
|
||||||
"serde",
|
"serde",
|
||||||
"subtle",
|
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.20",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
@@ -7557,16 +7653,6 @@ dependencies = [
|
|||||||
"web-sys",
|
"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]]
|
[[package]]
|
||||||
name = "x11-dl"
|
name = "x11-dl"
|
||||||
version = "2.21.0"
|
version = "2.21.0"
|
||||||
|
|||||||
+3
-1
@@ -4,12 +4,14 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
exclude = ["vendor/mainline"]
|
exclude = ["vendor/mainline", "vendor/iroh"]
|
||||||
|
|
||||||
# Mainline 8.0.0 treats Windows UDP read timeouts as socket failures.
|
# Mainline 8.0.0 treats Windows UDP read timeouts as socket failures.
|
||||||
# Keep the small receive-loop correction reproducible until an upstream fix.
|
# Keep the small receive-loop correction reproducible until an upstream fix.
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
mainline = { path = "vendor/mainline" }
|
mainline = { path = "vendor/mainline" }
|
||||||
|
# Backport bounded path retries until an iroh release includes the OOM fix.
|
||||||
|
iroh = { path = "vendor/iroh" }
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|||||||
@@ -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.
|
- **LAN games:** UDP broadcasts are relayed, so "LAN" lobbies show up across the mesh.
|
||||||
- **Several networks at once** on one device.
|
- **Several networks at once** on one device.
|
||||||
- **Tray app** for Windows, macOS and Linux; a command line for everything.
|
- **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
|
## Install
|
||||||
|
|
||||||
@@ -63,6 +64,7 @@ Grab a build from the [latest release](https://github.com/house-of-vanity/tsunag
|
|||||||
| Platform | How |
|
| Platform | How |
|
||||||
| --------------------- | -------------------------------------------------------------------------------- |
|
| --------------------- | -------------------------------------------------------------------------------- |
|
||||||
| **Windows** | Run `tsunagi-setup-<version>-x86_64.exe`. Installs the service, the tray and `tsng`. |
|
| **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` |
|
| **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) |
|
| **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` |
|
| **Arch** | `sudo pacman -U tsunagi-gui-<version>-1-x86_64.pkg.tar.zst` |
|
||||||
@@ -94,6 +96,19 @@ stopping a suspended network cancels its automatic resume.
|
|||||||
|
|
||||||
Machines are called `tsunagi-<id>` until you rename them: `tsng id hostname laptop`.
|
Machines are called `tsunagi-<id>` until you rename them: `tsng id hostname laptop`.
|
||||||
|
|
||||||
|
### Virtual services
|
||||||
|
|
||||||
|
```sh
|
||||||
|
tsng vip create home api
|
||||||
|
tsng vip port add home api tcp/443 --backend server1:6443 --backend server2:7443
|
||||||
|
tsng vip status home api --watch
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `api.home:443`. Each client selects the available backend with the lowest
|
||||||
|
measured data-plane RTT. A VIP can have multiple independent TCP and UDP ports.
|
||||||
|
Every member may edit it; the tray's **VIP** button opens a draft editor with
|
||||||
|
explicit Save. [Commands, health, metrics and limits](docs/vip.md).
|
||||||
|
|
||||||
### Exit nodes
|
### Exit nodes
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -123,9 +138,14 @@ tsng protocols home none # control plane only
|
|||||||
|
|
||||||
Exact network names, full ids and unique id prefixes work here. The choice is
|
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
|
local to this device, saved per network and applied immediately; an offline
|
||||||
change applies on the next start. In the tray, expand **protocols** on a network
|
change applies on the next start. In the tray, expand **data transports** on a network
|
||||||
tile to toggle protocols or change their preference order. Both endpoints need
|
tile to toggle protocols or change their preference order. Adjacent peers need a common external transport at the same wire version.
|
||||||
a common protocol at the same wire version. `tsng up --protocol` supplies the
|
Selection applies to this device's incoming and outgoing data links; control and
|
||||||
|
discovery are independent. A relay's next hop may use a different transport.
|
||||||
|
Every pair uses one internal WireGuard cipher, hidden from these controls.
|
||||||
|
Changing transport or moving direct → relay → direct preserves that channel,
|
||||||
|
addresses and interface. An existing TCP connection can resume after temporary
|
||||||
|
loss, subject to its own timeouts. `tsng up --protocol` supplies the
|
||||||
initial defaults for networks without a saved choice; it does not restrict
|
initial defaults for networks without a saved choice; it does not restrict
|
||||||
which built-in protocols can be enabled later.
|
which built-in protocols can be enabled later.
|
||||||
|
|
||||||
@@ -162,7 +182,8 @@ Online nodes and the currently selected exit node cannot be forgotten.
|
|||||||
² Newer and less battle-tested than on Linux.
|
² Newer and less battle-tested than on Linux.
|
||||||
³ Builds from source, not covered by CI.</sup>
|
³ 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
|
## NixOS
|
||||||
|
|
||||||
@@ -194,6 +215,11 @@ Just trying it: `nix run github:house-of-vanity/tsunagi#tsunagi-cli -- --help`.
|
|||||||
`packages.<system>.tsunagi` (with the tray) and `tsunagi-cli` are also exported,
|
`packages.<system>.tsunagi` (with the tray) and `tsunagi-cli` are also exported,
|
||||||
along with `overlays.default`.
|
along with `overlays.default`.
|
||||||
|
|
||||||
|
For development from a checkout, `nix develop` also exposes the tray's native
|
||||||
|
runtime libraries, including AppIndicator and graphics/windowing libraries.
|
||||||
|
Cargo-built binaries such as `target/debug/tsunagi-tray` can run directly inside
|
||||||
|
this shell, without installing the packaged wrapper.
|
||||||
|
|
||||||
## Build from source
|
## Build from source
|
||||||
|
|
||||||
Rust 1.91 or newer.
|
Rust 1.91 or newer.
|
||||||
@@ -203,6 +229,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)
|
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`.
|
Windows needs [Wintun](https://www.wintun.net) next to `tsng.exe`.
|
||||||
Per-platform notes: [Linux](dist/linux/README.md), [Arch](dist/arch/README.md),
|
Per-platform notes: [Linux](dist/linux/README.md), [Arch](dist/arch/README.md),
|
||||||
[macOS](dist/macos/README.md), [Windows](dist/windows/README.md).
|
[macOS](dist/macos/README.md), [Windows](dist/windows/README.md).
|
||||||
@@ -227,6 +265,7 @@ The [threat model](docs/threat-model.md) says what this does and doesn't protect
|
|||||||
[Pairwise Amnezia transport](docs/amnezia.md) ·
|
[Pairwise Amnezia transport](docs/amnezia.md) ·
|
||||||
[Routing](docs/routing.md) ·
|
[Routing](docs/routing.md) ·
|
||||||
[Exit nodes](docs/exit-node.md) ·
|
[Exit nodes](docs/exit-node.md) ·
|
||||||
|
[Virtual services](docs/vip.md) ·
|
||||||
[Threat model](docs/threat-model.md) ·
|
[Threat model](docs/threat-model.md) ·
|
||||||
[Contributing](AGENTS.md)
|
[Contributing](AGENTS.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,47 @@
|
|||||||
|
# Android client
|
||||||
|
|
||||||
|
Download `tsunagi-android-<version>-arm64-v8a.apk` from the project's GitHub release and open it on an ARM64 phone running Android 8 or later. If prompted, allow the app that opened the file to install it. Later releases can update the installed app and preserve the mesh identity. A prototype signed with a local debug key requires a fresh install to switch to the release signer. Uninstalling the prototype removes its local identity and saved networks. [GitHub Releases](https://github.com/house-of-vanity/tsunagi/releases)
|
||||||
|
|
||||||
|
## Build from source
|
||||||
|
|
||||||
|
Open this directory in Android Studio. The debug prototype targets ARM64 devices running Android 8 or later with OpenGL ES 3. Install SDK Platform 35 and the NDK with the SDK Manager. Point `ANDROID_HOME` at your SDK and `ANDROID_NDK_HOME` at the installed NDK directory. The Gradle launcher needs a JDK, such as the one bundled with Android Studio.
|
||||||
|
|
||||||
|
From the repository root, with Cargo and cargo-ndk on your PATH:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rustup target add aarch64-linux-android
|
||||||
|
cargo install cargo-ndk --version 4.1.2 --locked
|
||||||
|
cd android
|
||||||
|
./gradlew :app:assembleDebug
|
||||||
|
adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join with the existing network name and secret. Android keeps the established VPN service bound when the activity closes. **About → Stop VPN** disconnects it. The app-private state directory holds the device identity and its saved networks.
|
||||||
|
|
||||||
|
The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic.
|
||||||
|
|
||||||
|
Applications using Android’s system resolver can connect to `<member>.<network>` and `<vip>.<network>`, for example `k8s.tsng:6443`. The VPN answers UDP and TCP DNS questions locally using the same signed roster and service records as the desktop. Unknown names in a joined mesh receive an authoritative negative answer. Other names go to Android’s resolver on the underlying Wi-Fi or cellular network, including while using a remote exit. Android 10 and later support arbitrary external DNS record types. On Android 8 and 9 the system lookup API supplies external A and AAAA records.
|
||||||
|
|
||||||
|
The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard.
|
||||||
|
|
||||||
|
Open **Exit node…** on a network tile to compare remote gateways by control RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
|
||||||
|
|
||||||
|
## Configure GitHub release signing
|
||||||
|
|
||||||
|
The GitHub `Release` workflow builds and signs the ARM64 APK for each `v*` tag. The tag supplies the version name and the workflow run number supplies the Android version code. A rerun of the same workflow run keeps that code. The publish job attaches the verified APK alongside the desktop packages.
|
||||||
|
|
||||||
|
Before the first release, configure two repository Actions secrets. Use a dedicated single-key PKCS12 keystore with the same password for the keystore and key. Keep a private backup of the file and password so future releases can update existing installations. To create the first key, run this command once.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
keytool -genkeypair -storetype PKCS12 -keystore "$HOME/tsunagi-release.p12" \
|
||||||
|
-alias tsunagi -keyalg RSA -keysize 3072 -validity 10000
|
||||||
|
```
|
||||||
|
|
||||||
|
From this repository, upload the keystore. Enter its password when the second command prompts for it.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
base64 < "$HOME/tsunagi-release.p12" | gh secret set ANDROID_KEYSTORE_BASE64
|
||||||
|
gh secret set ANDROID_KEYSTORE_PASSWORD
|
||||||
|
```
|
||||||
|
|
||||||
|
Missing signing credentials or a failed APK check stop publication. After correcting the secrets, rerun the failed release jobs for the same tag.
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import groovy.json.JsonSlurper
|
||||||
|
|
||||||
|
plugins { id 'com.android.application' version '9.2.1' }
|
||||||
|
|
||||||
|
def workspace = rootProject.projectDir.parentFile
|
||||||
|
def abi = 'arm64-v8a'
|
||||||
|
android {
|
||||||
|
namespace 'cy.hexor.tsunagi'
|
||||||
|
compileSdk 35
|
||||||
|
def cargoNdk = providers.environmentVariable('ANDROID_NDK_HOME')
|
||||||
|
if (cargoNdk.isPresent()) {
|
||||||
|
ndkPath = cargoNdk.get()
|
||||||
|
def ndkProperties = new Properties()
|
||||||
|
file("$ndkPath/source.properties").withInputStream { ndkProperties.load(it) }
|
||||||
|
ndkVersion = ndkProperties.getProperty('Pkg.Revision')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cargo also builds standalone cdylibs for these dependencies. Their code
|
||||||
|
// is linked into tsunagi_android; the JVM loads only the application library.
|
||||||
|
packaging.jniLibs.excludes += ['**/libboringtun.so', '**/libiroh.so', '**/libiroh_relay.so']
|
||||||
|
defaultConfig {
|
||||||
|
applicationId 'cy.hexor.tsunagi'
|
||||||
|
minSdk 26
|
||||||
|
targetSdk 35
|
||||||
|
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
|
||||||
|
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.0')
|
||||||
|
ndk { abiFilters abi }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// rustls ships its Android trust manager as an AAR in the locked Cargo package.
|
||||||
|
def metadata = providers.exec {
|
||||||
|
workingDir workspace
|
||||||
|
commandLine 'cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'aarch64-linux-android'
|
||||||
|
}.standardOutput.asText.get()
|
||||||
|
def verifier = new JsonSlurper().parseText(metadata).packages.find { it.name == 'rustls-platform-verifier-android' }
|
||||||
|
repositories {
|
||||||
|
maven {
|
||||||
|
url new File(new File(verifier.manifest_path).parent, 'maven')
|
||||||
|
metadataSources { mavenPom() }
|
||||||
|
content { includeModule 'rustls', 'rustls-platform-verifier' }
|
||||||
|
}
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
dependencies { implementation "rustls:rustls-platform-verifier:${verifier.version}" }
|
||||||
|
|
||||||
|
abstract class BuildRust extends Exec {
|
||||||
|
@OutputDirectory abstract DirectoryProperty getJniLibs()
|
||||||
|
}
|
||||||
|
|
||||||
|
androidComponents.onVariants(androidComponents.selector().all()) { variant ->
|
||||||
|
def mode = variant.buildType
|
||||||
|
def libs = layout.buildDirectory.dir("generated/rust/${mode}")
|
||||||
|
def nativeBuild = tasks.register("cargo${mode.capitalize()}", BuildRust) {
|
||||||
|
workingDir workspace
|
||||||
|
inputs.files(fileTree(workspace) {
|
||||||
|
include 'Cargo.toml', 'Cargo.lock', '.cargo/**', 'crates/**/Cargo.toml', 'crates/**/src/**', 'vendor/**'
|
||||||
|
})
|
||||||
|
jniLibs.set(libs)
|
||||||
|
commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26', '-o', libs.get().asFile,
|
||||||
|
'build', '--locked', '--lib', '-p', 'tsunagi-android'
|
||||||
|
if (mode == 'release') args '--release'
|
||||||
|
}
|
||||||
|
variant.sources.jniLibs.addGeneratedSourceDirectory(nativeBuild) { it.jniLibs }
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||||
|
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
|
||||||
|
<application android:label="tsunagi" android:icon="@drawable/tsunagi"
|
||||||
|
android:enableOnBackInvokedCallback="false" android:allowBackup="false" android:theme="@android:style/Theme.Material.NoActionBar">
|
||||||
|
<activity android:name=".MainActivity" android:exported="true"
|
||||||
|
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<service android:name=".MeshVpn" android:permission="android.permission.BIND_VPN_SERVICE"
|
||||||
|
android:foregroundServiceType="systemExempted" android:exported="false">
|
||||||
|
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
|
||||||
|
<meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON" android:value="false" />
|
||||||
|
</service>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package cy.hexor.tsunagi
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.VpnService
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.WindowInsets
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
|
||||||
|
class MainActivity : Activity() {
|
||||||
|
private var askedForNotifications = false
|
||||||
|
internal fun requestExitNotifications() {
|
||||||
|
if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications &&
|
||||||
|
checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||||
|
askedForNotifications = true
|
||||||
|
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private lateinit var surface: MeshSurface
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
surface = MeshSurface(this)
|
||||||
|
val root = FrameLayout(this)
|
||||||
|
if (Build.VERSION.SDK_INT >= 30) {
|
||||||
|
window.setDecorFitsSystemWindows(false)
|
||||||
|
root.setOnApplyWindowInsetsListener { view, insets ->
|
||||||
|
val area = insets.getInsets(WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout() or WindowInsets.Type.ime())
|
||||||
|
view.setPadding(area.left, area.top, area.right, area.bottom)
|
||||||
|
insets
|
||||||
|
}
|
||||||
|
} else root.fitsSystemWindows = true
|
||||||
|
root.addView(surface)
|
||||||
|
setContentView(root)
|
||||||
|
}
|
||||||
|
internal fun requestVpn() {
|
||||||
|
val consent = VpnService.prepare(this)
|
||||||
|
if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java))
|
||||||
|
else startActivityForResult(consent, 1)
|
||||||
|
}
|
||||||
|
@Deprecated("Platform consent result")
|
||||||
|
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
|
||||||
|
super.onActivityResult(request, result, data)
|
||||||
|
if (request == 1) {
|
||||||
|
if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java))
|
||||||
|
else surface.input(5, "VPN permission was declined")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Deprecated("Forward system Back to the current Rust view")
|
||||||
|
override fun onBackPressed() { surface.dispatchBack() }
|
||||||
|
override fun onResume() { super.onResume(); surface.onResume() }
|
||||||
|
override fun onPause() { surface.onPause(); super.onPause() }
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package cy.hexor.tsunagi
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.opengl.GLSurfaceView
|
||||||
|
import android.text.InputType
|
||||||
|
import android.view.KeyEvent
|
||||||
|
import android.view.MotionEvent
|
||||||
|
import android.view.inputmethod.BaseInputConnection
|
||||||
|
import android.view.inputmethod.EditorInfo
|
||||||
|
import android.view.inputmethod.InputConnection
|
||||||
|
import android.view.inputmethod.InputMethodManager
|
||||||
|
import javax.microedition.khronos.egl.EGLConfig
|
||||||
|
import javax.microedition.khronos.opengles.GL10
|
||||||
|
|
||||||
|
/** Surface, input connection and clipboard bridge for egui. */
|
||||||
|
class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), GLSurfaceView.Renderer {
|
||||||
|
private val density get() = resources.displayMetrics.density
|
||||||
|
private val imm = activity.getSystemService(InputMethodManager::class.java)
|
||||||
|
private var imeMode = 0
|
||||||
|
private var widthPx = 0
|
||||||
|
private var heightPx = 0
|
||||||
|
private val repaint = Runnable { requestRender() }
|
||||||
|
init {
|
||||||
|
setEGLContextClientVersion(3)
|
||||||
|
preserveEGLContextOnPause = true
|
||||||
|
setRenderer(this)
|
||||||
|
renderMode = RENDERMODE_WHEN_DIRTY
|
||||||
|
isFocusableInTouchMode = true
|
||||||
|
requestFocus()
|
||||||
|
}
|
||||||
|
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
|
||||||
|
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
|
||||||
|
override fun onDrawFrame(gl: GL10?) {
|
||||||
|
val delay = Native.draw(this, widthPx, heightPx, density)
|
||||||
|
removeCallbacks(repaint)
|
||||||
|
postDelayed(repaint, delay.coerceAtLeast(16))
|
||||||
|
}
|
||||||
|
override fun onPause() { super.onPause(); removeCallbacks(repaint) }
|
||||||
|
override fun onTouchEvent(e: MotionEvent): Boolean {
|
||||||
|
val phase = when (e.actionMasked) {
|
||||||
|
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0
|
||||||
|
MotionEvent.ACTION_MOVE -> 1
|
||||||
|
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> 2
|
||||||
|
MotionEvent.ACTION_CANCEL -> 3
|
||||||
|
else -> return false
|
||||||
|
}
|
||||||
|
for (i in 0 until e.pointerCount) {
|
||||||
|
if ((phase == 0 || phase == 2) && i != e.actionIndex) continue
|
||||||
|
val id = e.getPointerId(i)
|
||||||
|
val x = e.getX(i) / density
|
||||||
|
val y = e.getY(i) / density
|
||||||
|
queueEvent { Native.touch(phase, id, x, y) }
|
||||||
|
}
|
||||||
|
requestRender()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startVpn() { post { activity.requestVpn() } }
|
||||||
|
fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } }
|
||||||
|
fun requestExitNotifications() { post { activity.requestExitNotifications() } }
|
||||||
|
fun closeScreen() { post { activity.finish() } }
|
||||||
|
fun openUrl(url: String) { post {
|
||||||
|
val uri = android.net.Uri.parse(url)
|
||||||
|
if (uri.scheme == "https") {
|
||||||
|
try { activity.startActivity(Intent(Intent.ACTION_VIEW, uri)) }
|
||||||
|
catch (_: android.content.ActivityNotFoundException) { }
|
||||||
|
}
|
||||||
|
} }
|
||||||
|
fun dispatchBack() { queueEvent { Native.back(this) }; requestRender() }
|
||||||
|
fun copyText(value: String) { post {
|
||||||
|
activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("tsunagi", value))
|
||||||
|
} }
|
||||||
|
fun copySecret(value: String) { post {
|
||||||
|
val clip = ClipData.newPlainText("tsunagi", value)
|
||||||
|
clip.description.extras = android.os.PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) }
|
||||||
|
activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(clip)
|
||||||
|
} }
|
||||||
|
fun pasteSecret() { post {
|
||||||
|
val clip = activity.getSystemService(ClipboardManager::class.java).primaryClip
|
||||||
|
val text = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
|
||||||
|
if (text != null && text.length <= 2048) input(4, text.toString())
|
||||||
|
} }
|
||||||
|
fun keyboard(mode: Int) { post {
|
||||||
|
imeMode = mode
|
||||||
|
if (mode == 0) {
|
||||||
|
imm.hideSoftInputFromWindow(windowToken, 0)
|
||||||
|
imm.restartInput(this)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
requestFocus()
|
||||||
|
imm.restartInput(this)
|
||||||
|
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
|
||||||
|
}
|
||||||
|
} }
|
||||||
|
fun input(kind: Int, value: String) {
|
||||||
|
queueEvent { Native.input(kind, value) }
|
||||||
|
requestRender()
|
||||||
|
}
|
||||||
|
private fun key(code: Int) { queueEvent { Native.key(code) }; requestRender() }
|
||||||
|
override fun onCheckIsTextEditor(): Boolean = imeMode != 0
|
||||||
|
override fun onCreateInputConnection(info: EditorInfo): InputConnection? {
|
||||||
|
if (imeMode == 0) return null
|
||||||
|
info.inputType = InputType.TYPE_CLASS_TEXT or (if (imeMode == 2) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)
|
||||||
|
info.imeOptions = EditorInfo.IME_ACTION_DONE or EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
|
||||||
|
return object : BaseInputConnection(this, false) {
|
||||||
|
private var composing: String? = null
|
||||||
|
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||||
|
if (composing == null) input(1, "")
|
||||||
|
composing = text?.toString().orEmpty()
|
||||||
|
input(2, composing.orEmpty())
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||||
|
input(if (composing == null) 0 else 3, text?.toString().orEmpty())
|
||||||
|
composing = null
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
override fun finishComposingText(): Boolean {
|
||||||
|
composing?.let { input(3, it) }
|
||||||
|
composing = null
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
override fun deleteSurroundingText(before: Int, after: Int): Boolean {
|
||||||
|
repeat(before.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_DEL) }
|
||||||
|
repeat(after.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_FORWARD_DEL) }
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
override fun sendKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event)
|
||||||
|
override fun performEditorAction(action: Int): Boolean { key(KeyEvent.KEYCODE_ENTER); return true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onKeyDown(code: Int, event: KeyEvent): Boolean {
|
||||||
|
when (code) {
|
||||||
|
KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_DEL,
|
||||||
|
KeyEvent.KEYCODE_FORWARD_DEL, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> key(code)
|
||||||
|
else -> {
|
||||||
|
val point = event.unicodeChar
|
||||||
|
if (point <= 0) return super.onKeyDown(code, event)
|
||||||
|
input(0, String(Character.toChars(point)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
package cy.hexor.tsunagi
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.DnsResolver
|
||||||
|
import android.net.Network
|
||||||
|
import android.net.LinkProperties
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import android.net.NetworkRequest
|
||||||
|
import android.net.VpnService
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.CancellationSignal
|
||||||
|
import android.os.Looper
|
||||||
|
import android.os.ParcelFileDescriptor
|
||||||
|
import android.system.OsConstants
|
||||||
|
import java.util.concurrent.CompletableFuture
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class MeshVpn : VpnService() {
|
||||||
|
companion object {
|
||||||
|
const val STOP_VPN = "cy.hexor.tsunagi.STOP_VPN"
|
||||||
|
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
|
||||||
|
private const val NOTIFICATION_ID = 1
|
||||||
|
private const val EXIT_CHANNEL = "exit-node"
|
||||||
|
}
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
private val notifications by lazy { getSystemService(NotificationManager::class.java) }
|
||||||
|
@Volatile private var instance = 0L
|
||||||
|
private var closed = false
|
||||||
|
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
|
||||||
|
@Volatile private var upstream: Network? = null
|
||||||
|
private var watching = false
|
||||||
|
private val changes = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) = useUnderlay(network)
|
||||||
|
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
|
||||||
|
if (network == upstream && !closed) updateAddresses(properties)
|
||||||
|
}
|
||||||
|
override fun onLost(network: Network) {
|
||||||
|
if (network != upstream || closed) return
|
||||||
|
upstream = null
|
||||||
|
// Keep the binding to the lost network until its replacement is ready.
|
||||||
|
// Falling back to the default network here could send iroh into its own TUN.
|
||||||
|
setUnderlyingNetworks(emptyArray())
|
||||||
|
physicalAddresses = ""
|
||||||
|
Native.networkChanged(instance, "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var physicalAddresses = ""
|
||||||
|
private fun addresses(properties: LinkProperties?) = properties?.linkAddresses.orEmpty()
|
||||||
|
.mapNotNull { it.address.hostAddress?.substringBefore('%') }.distinct().take(32).joinToString(",")
|
||||||
|
private fun updateAddresses(properties: LinkProperties) {
|
||||||
|
val next = addresses(properties)
|
||||||
|
if (next == physicalAddresses) return
|
||||||
|
physicalAddresses = next
|
||||||
|
Native.networkChanged(instance, next)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized private fun useUnderlay(network: Network) {
|
||||||
|
if (closed || !connectivity.bindProcessToNetwork(network)) return
|
||||||
|
upstream = network
|
||||||
|
setUnderlyingNetworks(arrayOf(network))
|
||||||
|
physicalAddresses = addresses(connectivity.getLinkProperties(network))
|
||||||
|
if (instance == 0L) {
|
||||||
|
Native.trust(applicationContext)
|
||||||
|
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses)
|
||||||
|
} else Native.networkChanged(instance, physicalAddresses)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
when (intent?.action) {
|
||||||
|
STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY }
|
||||||
|
DISCONNECT_EXIT -> {
|
||||||
|
val ids = intent.data?.pathSegments.orEmpty()
|
||||||
|
if (watching && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
|
||||||
|
if (!Native.disconnectExit(instance, ids[0], ids[1])) {
|
||||||
|
android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
} else if (!watching) stopSelf(startId)
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (watching) {
|
||||||
|
if (Native.failed(instance)) {
|
||||||
|
Native.stop(instance)
|
||||||
|
instance = 0
|
||||||
|
upstream?.let(::useUnderlay)
|
||||||
|
}
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
notifications.createNotificationChannel(NotificationChannel("vpn", "VPN", NotificationManager.IMPORTANCE_LOW))
|
||||||
|
notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW))
|
||||||
|
val startup = notification("vpn").setContentTitle("Starting mesh VPN")
|
||||||
|
if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
|
||||||
|
startForeground(NOTIFICATION_ID, startup.build())
|
||||||
|
watching = true
|
||||||
|
connectivity.requestNetwork(NetworkRequest.Builder()
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper()))
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notification(channel: String): Notification.Builder {
|
||||||
|
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
return Notification.Builder(this, channel).setSmallIcon(R.drawable.tsunagi)
|
||||||
|
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true).setShowWhen(false)
|
||||||
|
.setCategory(Notification.CATEGORY_SERVICE)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rust publishes a change even when the activity is closed. Android holds its
|
||||||
|
// own service binding for an established TUN, so mesh-only mode can leave
|
||||||
|
// foreground promotion and remove the app's notification.
|
||||||
|
fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String) {
|
||||||
|
main.post {
|
||||||
|
if (closed || session != instance) return@post
|
||||||
|
if (peer.isEmpty()) {
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
|
return@post
|
||||||
|
}
|
||||||
|
val target = android.net.Uri.Builder().scheme("tsunagi").authority("exit")
|
||||||
|
.appendPath(network).appendPath(peer).build()
|
||||||
|
val disconnect = PendingIntent.getService(this, 1,
|
||||||
|
Intent(this, MeshVpn::class.java).setAction(DISCONNECT_EXIT).setData(target).putExtra("instance", session),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
val notice = notification(EXIT_CHANNEL).setContentTitle(title).setContentText(text)
|
||||||
|
.addAction(Notification.Action.Builder(null, "Disconnect exit node", disconnect).build())
|
||||||
|
if (Build.VERSION.SDK_INT >= 31) notice.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
|
||||||
|
startForeground(NOTIFICATION_ID, notice.build())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called from Rust with the exhaustive local plan; detachFd transfers ownership.
|
||||||
|
@Synchronized fun establishTun(addresses: String, routes: String, dns: String, mtu: Int, fullTunnel: Boolean): Int {
|
||||||
|
if (closed) return -1
|
||||||
|
val builder = Builder().setSession("tsunagi").setMtu(mtu).setBlocking(false)
|
||||||
|
builder.setUnderlyingNetworks(upstream?.let { arrayOf(it) } ?: emptyArray())
|
||||||
|
addresses.split(',').forEach { builder.addAddress(it.substringBefore('/'), it.substringAfter('/').toInt()) }
|
||||||
|
routes.split(',').forEach { builder.addRoute(it.substringBefore('/'), it.substringAfter('/').toInt()) }
|
||||||
|
if (dns.isNotEmpty()) builder.addDnsServer(dns)
|
||||||
|
// Mesh exits currently carry IPv4. Android blocks an unconfigured family
|
||||||
|
// unless explicitly allowed. In split mode ordinary IPv6 should pass.
|
||||||
|
if (!fullTunnel) builder.allowFamily(OsConstants.AF_INET6)
|
||||||
|
return builder.establish()?.detachFd() ?: -1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called on a bounded Rust blocking worker, never on the UI or TUN reader.
|
||||||
|
@android.annotation.TargetApi(29)
|
||||||
|
fun resolveDns(query: ByteArray): ByteArray? {
|
||||||
|
val network = upstream ?: return null
|
||||||
|
val result = CompletableFuture<ByteArray>()
|
||||||
|
val cancel = CancellationSignal()
|
||||||
|
return try {
|
||||||
|
DnsResolver.getInstance().rawQuery(network, query, DnsResolver.FLAG_EMPTY, { it.run() }, cancel,
|
||||||
|
object : DnsResolver.Callback<ByteArray> {
|
||||||
|
override fun onAnswer(answer: ByteArray, rcode: Int) { result.complete(answer) }
|
||||||
|
override fun onError(error: DnsResolver.DnsException) { result.completeExceptionally(error) }
|
||||||
|
})
|
||||||
|
result.get(4, TimeUnit.SECONDS)
|
||||||
|
} catch (_: Exception) { null } finally { cancel.cancel() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Android 8 and 9 expose only address lookups through their system resolver.
|
||||||
|
fun resolveAddresses(host: String): String? = try {
|
||||||
|
upstream?.getAllByName(host)?.mapNotNull { it.hostAddress }?.joinToString(",")
|
||||||
|
} catch (_: java.net.UnknownHostException) { null }
|
||||||
|
|
||||||
|
// The endpoint uses the physical network. This one explicitly selected TCP
|
||||||
|
// socket must instead follow the same VPN as applications using the VIP.
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
fun bindOverlaySocket(fd: Int, source: String): Boolean {
|
||||||
|
val vpn = connectivity.allNetworks.firstOrNull { network ->
|
||||||
|
connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true &&
|
||||||
|
connectivity.getLinkProperties(network)?.linkAddresses?.any { it.address.hostAddress == source } == true
|
||||||
|
} ?: return false
|
||||||
|
return try {
|
||||||
|
ParcelFileDescriptor.fromFd(fd).use { vpn.bindSocket(it.fileDescriptor) }
|
||||||
|
true
|
||||||
|
} catch (_: java.io.IOException) { false }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onRevoke() { shutdown(); stopSelf() }
|
||||||
|
override fun onDestroy() { shutdown(); super.onDestroy() }
|
||||||
|
@Synchronized private fun shutdown() {
|
||||||
|
if (closed) return
|
||||||
|
closed = true
|
||||||
|
if (watching) connectivity.unregisterNetworkCallback(changes)
|
||||||
|
if (instance != 0L) Native.stop(instance)
|
||||||
|
connectivity.bindProcessToNetwork(null)
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package cy.hexor.tsunagi
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
|
||||||
|
/** OS entry points. Network commands and all views live in the Rust library. */
|
||||||
|
internal object Native {
|
||||||
|
init { System.loadLibrary("tsunagi_android") }
|
||||||
|
external fun trust(context: Context)
|
||||||
|
external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String): Long
|
||||||
|
external fun failed(instance: Long): Boolean
|
||||||
|
external fun stop(instance: Long)
|
||||||
|
external fun disconnectExit(instance: Long, network: String, peer: String): Boolean
|
||||||
|
external fun networkChanged(instance: Long, addresses: String)
|
||||||
|
|
||||||
|
external fun surface()
|
||||||
|
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long
|
||||||
|
external fun touch(action: Int, id: Int, x: Float, y: Float)
|
||||||
|
external fun input(kind: Int, value: String)
|
||||||
|
external fun key(key: Int)
|
||||||
|
external fun back(host: MeshSurface)
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="48dp" android:height="48dp" android:viewportWidth="128" android:viewportHeight="128">
|
||||||
|
<path android:fillColor="#2f80d8" android:pathData="M64,8a56,56 0,1 1,0 112a56,56 0,1 1,0 -112" />
|
||||||
|
<path android:strokeColor="#ffffff" android:strokeWidth="7" android:pathData="M64,34a30,30 0,1 1,0 60a30,30 0,1 1,0 -60" />
|
||||||
|
<path android:fillColor="#ffffff" android:pathData="M64,55a9,9 0,1 1,0 18a9,9 0,1 1,0 -18" />
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
android.useAndroidX=true
|
||||||
|
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
+248
@@ -0,0 +1,248 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+93
@@ -0,0 +1,93 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||||
|
rootProject.name = 'tsunagi-android'
|
||||||
|
include ':app'
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
apk=${1:?expected an APK}
|
||||||
|
version_name=${2:?expected the release version}
|
||||||
|
version_code=${3:?expected the Android version code}
|
||||||
|
build_tools=${4:?expected the Android SDK Build Tools directory}
|
||||||
|
|
||||||
|
badging=$("$build_tools/aapt" dump badging "$apk")
|
||||||
|
package="package: name='cy.hexor.tsunagi' versionCode='$version_code' versionName='$version_name'"
|
||||||
|
if [[ "$badging" != "$package "* ]]; then
|
||||||
|
echo "Expected tsunagi $version_name (version code $version_code) in the APK manifest" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if grep -Fxq 'application-debuggable' <<< "$badging"; then
|
||||||
|
echo "The release APK enables Android debugging" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! grep -Fxq "native-code: 'arm64-v8a'" <<< "$badging"; then
|
||||||
|
echo "Expected an arm64-v8a APK" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
library=$(mktemp)
|
||||||
|
trap 'rm -f "$library"' EXIT
|
||||||
|
unzip -p "$apk" lib/arm64-v8a/libtsunagi_android.so > "$library"
|
||||||
|
if [[ "$(LC_ALL=C file -b "$library")" != *"ARM aarch64"*", stripped"* ]]; then
|
||||||
|
echo "Expected a stripped ARM64 tsunagi native library" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
"$build_tools/zipalign" -c -P 16 4 "$apk"
|
||||||
|
"$build_tools/apksigner" verify --verbose --print-certs "$apk"
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsunagi-android"
|
||||||
|
version = "1.0.0"
|
||||||
|
description = "Android VPN client and egui views for tsunagi."
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.0" }
|
||||||
|
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||||
|
tsunagi-core = { path = "../tsunagi-core" }
|
||||||
|
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||||
|
egui = "0.31"
|
||||||
|
egui-phosphor = "0.9"
|
||||||
|
tokio.workspace = true
|
||||||
|
bytes.workspace = true
|
||||||
|
zeroize = "1.9"
|
||||||
|
simple-dns = "0.12"
|
||||||
|
|
||||||
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
rand = "0.10"
|
||||||
|
smoltcp = { version = "0.12", default-features = false, features = ["std", "medium-ip", "proto-ipv4", "socket-tcp", "socket-udp"] }
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "android")'.dependencies]
|
||||||
|
egui_glow = { version = "0.31", default-features = false }
|
||||||
|
jni = "0.21"
|
||||||
|
iroh.workspace = true
|
||||||
|
jni-verifier = { package = "jni", version = "0.22" }
|
||||||
|
rustls-platform-verifier = "0.7"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile.workspace = true
|
||||||
|
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets.
|
||||||
|
use crate::view::{Phone, SystemAction};
|
||||||
|
use egui::{
|
||||||
|
Event, ImeEvent, Key, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase,
|
||||||
|
};
|
||||||
|
use egui_glow::{Painter, glow};
|
||||||
|
use jni::{
|
||||||
|
JNIEnv,
|
||||||
|
objects::{JObject, JString, JValue},
|
||||||
|
sys::{jfloat, jint, jlong},
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
cell::RefCell,
|
||||||
|
ffi::{c_char, c_void},
|
||||||
|
sync::Arc,
|
||||||
|
time::Instant,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[link(name = "EGL")]
|
||||||
|
unsafe extern "C" {
|
||||||
|
fn eglGetProcAddress(name: *const c_char) -> *const c_void;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Display {
|
||||||
|
painter: Painter,
|
||||||
|
ctx: egui::Context,
|
||||||
|
ui: Phone,
|
||||||
|
events: Vec<Event>,
|
||||||
|
primary: Option<i32>,
|
||||||
|
start: Instant,
|
||||||
|
ime: i32,
|
||||||
|
exit_active: bool,
|
||||||
|
}
|
||||||
|
thread_local! { static DISPLAY: RefCell<Option<Display>> = const {RefCell::new(None)}; }
|
||||||
|
|
||||||
|
fn with_display<T: Default>(f: impl FnOnce(&mut Display) -> T) -> T {
|
||||||
|
DISPLAY.with_borrow_mut(|d| d.as_mut().map(f).unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) {
|
||||||
|
// SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current.
|
||||||
|
let gl = unsafe {
|
||||||
|
glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr()))
|
||||||
|
};
|
||||||
|
let Ok(painter) = Painter::new(Arc::new(gl), "", None, false) else {
|
||||||
|
let _ = env.throw_new(
|
||||||
|
"java/lang/IllegalStateException",
|
||||||
|
"Could not initialise OpenGL ES",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let ctx = egui::Context::default();
|
||||||
|
crate::view::configure(&ctx);
|
||||||
|
DISPLAY.with_borrow_mut(|d| {
|
||||||
|
// If Android discarded the old EGL context, its GPU resources are already gone.
|
||||||
|
let ui = d.take().map(|old| old.ui).unwrap_or_default();
|
||||||
|
*d = Some(Display {
|
||||||
|
painter,
|
||||||
|
ctx,
|
||||||
|
ui,
|
||||||
|
events: Vec::new(),
|
||||||
|
primary: None,
|
||||||
|
start: Instant::now(),
|
||||||
|
ime: -1,
|
||||||
|
exit_active: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
host: JObject,
|
||||||
|
w: jint,
|
||||||
|
h: jint,
|
||||||
|
scale: jfloat,
|
||||||
|
) -> jlong {
|
||||||
|
with_display(|d| {
|
||||||
|
let size = egui::vec2(w as f32, h as f32) / scale;
|
||||||
|
let mut input = egui::RawInput {
|
||||||
|
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
|
||||||
|
events: std::mem::take(&mut d.events),
|
||||||
|
time: Some(d.start.elapsed().as_secs_f64()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
if let Some(info) = input.viewports.get_mut(&egui::ViewportId::ROOT) {
|
||||||
|
info.native_pixels_per_point = Some(scale);
|
||||||
|
}
|
||||||
|
let mut action = None;
|
||||||
|
let state = super::status();
|
||||||
|
let exit_active = matches!(&state, crate::service::State::Ready(report, _) if report.networks.iter().any(|n| n.active && n.exit.via.is_some()));
|
||||||
|
if exit_active && !d.exit_active {
|
||||||
|
let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]);
|
||||||
|
}
|
||||||
|
d.exit_active = exit_active;
|
||||||
|
let output = d.ctx.run(input, |ctx| {
|
||||||
|
action = d.ui.draw(ctx, &state, super::send);
|
||||||
|
});
|
||||||
|
if let Some(action) = action {
|
||||||
|
let method = match action {
|
||||||
|
SystemAction::Start => "startVpn",
|
||||||
|
SystemAction::Stop => "stopVpn",
|
||||||
|
SystemAction::PasteSecret => "pasteSecret",
|
||||||
|
SystemAction::Finish => "closeScreen",
|
||||||
|
};
|
||||||
|
let _ = env.call_method(&host, method, "()V", &[]);
|
||||||
|
}
|
||||||
|
if let Some(secret) = d.ui.take_copied_secret()
|
||||||
|
&& let Ok(text) = env.new_string(secret.as_str())
|
||||||
|
{
|
||||||
|
let _ = env.call_method(
|
||||||
|
&host,
|
||||||
|
"copySecret",
|
||||||
|
"(Ljava/lang/String;)V",
|
||||||
|
&[JValue::Object(&text)],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for command in output.platform_output.commands {
|
||||||
|
let (method, value) = match command {
|
||||||
|
egui::OutputCommand::CopyText(text) => ("copyText", text),
|
||||||
|
egui::OutputCommand::OpenUrl(url) => ("openUrl", url.url),
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
if let Ok(text) = env.new_string(value) {
|
||||||
|
let _ = env.call_method(
|
||||||
|
&host,
|
||||||
|
method,
|
||||||
|
"(Ljava/lang/String;)V",
|
||||||
|
&[JValue::Object(&text)],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ime = if output.platform_output.ime.is_none() {
|
||||||
|
0
|
||||||
|
} else if d.ui.secret_focused(&d.ctx) {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
};
|
||||||
|
if ime != d.ime {
|
||||||
|
d.ime = ime;
|
||||||
|
let _ = env.call_method(&host, "keyboard", "(I)V", &[JValue::Int(ime)]);
|
||||||
|
}
|
||||||
|
let ppp = output.pixels_per_point;
|
||||||
|
let primitives = d.ctx.tessellate(output.shapes, ppp);
|
||||||
|
let pixels = [w as u32, h as u32];
|
||||||
|
d.painter.clear(pixels, [0.1, 0.1, 0.1, 1.0]);
|
||||||
|
d.painter
|
||||||
|
.paint_and_update_textures(pixels, ppp, &primitives, &output.textures_delta);
|
||||||
|
output
|
||||||
|
.viewport_output
|
||||||
|
.get(&egui::ViewportId::ROOT)
|
||||||
|
.map_or(1000, |v| {
|
||||||
|
v.repaint_delay.as_millis().clamp(16, 1000) as jlong
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_touch(
|
||||||
|
_: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
action: jint,
|
||||||
|
id: jint,
|
||||||
|
x: jfloat,
|
||||||
|
y: jfloat,
|
||||||
|
) {
|
||||||
|
with_display(|d| {
|
||||||
|
let pos = egui::pos2(x, y);
|
||||||
|
let phase = match action {
|
||||||
|
0 => TouchPhase::Start,
|
||||||
|
1 => TouchPhase::Move,
|
||||||
|
2 => TouchPhase::End,
|
||||||
|
_ => TouchPhase::Cancel,
|
||||||
|
};
|
||||||
|
d.events.push(Event::Touch {
|
||||||
|
device_id: TouchDeviceId(0),
|
||||||
|
id: TouchId(id as u64),
|
||||||
|
phase,
|
||||||
|
pos,
|
||||||
|
force: None,
|
||||||
|
});
|
||||||
|
if phase == TouchPhase::Start && d.primary.is_none() {
|
||||||
|
d.primary = Some(id);
|
||||||
|
}
|
||||||
|
if d.primary != Some(id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if phase != TouchPhase::Cancel {
|
||||||
|
d.events.push(Event::PointerMoved(pos));
|
||||||
|
}
|
||||||
|
if phase != TouchPhase::Move {
|
||||||
|
if phase == TouchPhase::Cancel {
|
||||||
|
d.events.push(Event::PointerGone);
|
||||||
|
}
|
||||||
|
d.events.push(Event::PointerButton {
|
||||||
|
pos,
|
||||||
|
button: PointerButton::Primary,
|
||||||
|
pressed: phase == TouchPhase::Start,
|
||||||
|
modifiers: Modifiers::NONE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if matches!(phase, TouchPhase::Cancel | TouchPhase::End) {
|
||||||
|
d.events.push(Event::PointerGone);
|
||||||
|
d.primary = None;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_input(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
kind: jint,
|
||||||
|
value: JString,
|
||||||
|
) {
|
||||||
|
let Ok(text) = env.get_string(&value) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let text = String::from(text);
|
||||||
|
with_display(|d| match kind {
|
||||||
|
0 => d.events.push(Event::Text(text)),
|
||||||
|
1 => d.events.push(Event::Ime(ImeEvent::Enabled)),
|
||||||
|
2 => d.events.push(Event::Ime(ImeEvent::Preedit(text))),
|
||||||
|
3 => {
|
||||||
|
d.events.push(Event::Ime(ImeEvent::Commit(text)));
|
||||||
|
d.events.push(Event::Ime(ImeEvent::Disabled));
|
||||||
|
}
|
||||||
|
4 => d.ui.paste_secret(text),
|
||||||
|
5 => d.ui.error(text),
|
||||||
|
_ => {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_key(_: JNIEnv, _: JObject, key: jint) {
|
||||||
|
let key = match key {
|
||||||
|
67 => Key::Backspace,
|
||||||
|
112 => Key::Delete,
|
||||||
|
66 => Key::Enter,
|
||||||
|
21 => Key::ArrowLeft,
|
||||||
|
22 => Key::ArrowRight,
|
||||||
|
61 => Key::Tab,
|
||||||
|
_ => return,
|
||||||
|
};
|
||||||
|
with_display(|d| {
|
||||||
|
for pressed in [true, false] {
|
||||||
|
d.events.push(Event::Key {
|
||||||
|
key,
|
||||||
|
physical_key: None,
|
||||||
|
pressed,
|
||||||
|
repeat: false,
|
||||||
|
modifiers: Modifiers::NONE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_back(mut env: JNIEnv, _: JObject, host: JObject) {
|
||||||
|
with_display(|d| {
|
||||||
|
if d.ui.back() == Some(SystemAction::Finish) {
|
||||||
|
let _ = env.call_method(&host, "closeScreen", "()V", &[]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
//! Android's physical-network resolver, including its Private DNS policy.
|
||||||
|
use crate::dns::Resolver;
|
||||||
|
use jni::{
|
||||||
|
JNIEnv, JavaVM,
|
||||||
|
objects::{GlobalRef, JByteArray, JString, JValue},
|
||||||
|
};
|
||||||
|
use simple_dns::{CLASS, Packet, PacketFlag, QTYPE, RCODE, ResourceRecord, TYPE, rdata::RData};
|
||||||
|
use std::{net::IpAddr, sync::Arc};
|
||||||
|
|
||||||
|
pub(super) fn resolver(vm: Arc<JavaVM>, service: GlobalRef, sdk: i32) -> Resolver {
|
||||||
|
Resolver::new(move |query| {
|
||||||
|
let mut env = vm.attach_current_thread().ok()?;
|
||||||
|
let response = env.with_local_frame(6, |env| {
|
||||||
|
if sdk < 29 {
|
||||||
|
return legacy(env, &service, query);
|
||||||
|
}
|
||||||
|
let bytes = env.byte_array_from_slice(query)?;
|
||||||
|
let reply = env
|
||||||
|
.call_method(&service, "resolveDns", "([B)[B", &[JValue::Object(&bytes)])?
|
||||||
|
.l()?;
|
||||||
|
if reply.is_null() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let reply = JByteArray::from(reply);
|
||||||
|
if env.get_array_length(&reply)? > i32::from(u16::MAX) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
env.convert_byte_array(reply).map(Some)
|
||||||
|
});
|
||||||
|
if env.exception_check().unwrap_or(false) {
|
||||||
|
let _ = env.exception_clear();
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
response.ok().flatten()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy(
|
||||||
|
env: &mut JNIEnv<'_>,
|
||||||
|
service: &GlobalRef,
|
||||||
|
query: &[u8],
|
||||||
|
) -> jni::errors::Result<Option<Vec<u8>>> {
|
||||||
|
let Some(packet) = Packet::parse(query).ok() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let [question] = packet.questions.as_slice() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let mut reply = Packet::new_reply(packet.id());
|
||||||
|
reply.questions.push(question.clone());
|
||||||
|
reply.set_flags(PacketFlag::RECURSION_AVAILABLE);
|
||||||
|
if packet.has_flags(PacketFlag::RECURSION_DESIRED) {
|
||||||
|
reply.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||||
|
}
|
||||||
|
if matches!(question.qtype, QTYPE::TYPE(TYPE::A | TYPE::AAAA)) {
|
||||||
|
let name = env.new_string(format!("{}.", question.qname))?;
|
||||||
|
let addresses = env
|
||||||
|
.call_method(
|
||||||
|
service,
|
||||||
|
"resolveAddresses",
|
||||||
|
"(Ljava/lang/String;)Ljava/lang/String;",
|
||||||
|
&[JValue::Object(&name)],
|
||||||
|
)?
|
||||||
|
.l()?;
|
||||||
|
if addresses.is_null() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let addresses: String = env.get_string(&JString::from(addresses))?.into();
|
||||||
|
for address in addresses
|
||||||
|
.split(',')
|
||||||
|
.take(128)
|
||||||
|
.filter_map(|s| s.parse::<IpAddr>().ok())
|
||||||
|
{
|
||||||
|
let data = match (question.qtype, address) {
|
||||||
|
(QTYPE::TYPE(TYPE::A), IpAddr::V4(v4)) => RData::A(v4.into()),
|
||||||
|
(QTYPE::TYPE(TYPE::AAAA), IpAddr::V6(v6)) => RData::AAAA(v6.into()),
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
reply.answers.push(ResourceRecord::new(
|
||||||
|
question.qname.clone(),
|
||||||
|
CLASS::IN,
|
||||||
|
0,
|
||||||
|
data,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
*reply.rcode_mut() = RCODE::NotImplemented;
|
||||||
|
}
|
||||||
|
Ok(reply.build_bytes_vec_compressed().ok())
|
||||||
|
}
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
//! Android process entry points. JNI owns references here, never in the core.
|
||||||
|
#![allow(unsafe_code)]
|
||||||
|
mod display;
|
||||||
|
mod dns;
|
||||||
|
use crate::{
|
||||||
|
plan::VpnPlan,
|
||||||
|
service::{Reply, Request, Response, State},
|
||||||
|
tun::AndroidTun,
|
||||||
|
};
|
||||||
|
use jni::{
|
||||||
|
JNIEnv, JavaVM,
|
||||||
|
objects::{GlobalRef, JObject, JString, JValue},
|
||||||
|
sys::jlong,
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
fs::File,
|
||||||
|
io,
|
||||||
|
os::fd::{AsRawFd, FromRawFd, OwnedFd},
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{Arc, Mutex, OnceLock},
|
||||||
|
};
|
||||||
|
use tokio::sync::{mpsc, oneshot, watch};
|
||||||
|
use tsunagi::{Agent, AgentConfig, StoragePaths, TransportPolicy, discovery::MainlineDiscovery};
|
||||||
|
use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin};
|
||||||
|
|
||||||
|
struct Session {
|
||||||
|
id: i64,
|
||||||
|
commands: mpsc::Sender<(Request, Reply)>,
|
||||||
|
state: watch::Receiver<State>,
|
||||||
|
underlay: watch::Sender<Vec<std::net::IpAddr>>,
|
||||||
|
stop: watch::Sender<bool>,
|
||||||
|
}
|
||||||
|
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||||
|
// Stop/start can cross on the Android main thread. The previous agent closes
|
||||||
|
// its fd, endpoint and directory lock before its successor opens that identity.
|
||||||
|
static LIFETIME: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
fn current() -> std::sync::MutexGuard<'static, Option<Session>> {
|
||||||
|
SESSION.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
fn status() -> State {
|
||||||
|
current()
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.state.borrow().clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||||
|
let (reply, result) = oneshot::channel();
|
||||||
|
current()
|
||||||
|
.as_ref()
|
||||||
|
.ok_or("VPN service stopped")?
|
||||||
|
.commands
|
||||||
|
.try_send((Request::Action(cmd), reply))
|
||||||
|
.map_err(|_| "VPN service is busy or stopped".to_owned())?;
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_trust(
|
||||||
|
mut env: jni_verifier::EnvUnowned,
|
||||||
|
_: jni_verifier::objects::JObject,
|
||||||
|
app: jni_verifier::objects::JObject,
|
||||||
|
) {
|
||||||
|
env.with_env(|env| rustls_platform_verifier::android::init_with_env(env, app))
|
||||||
|
.resolve::<jni_verifier::errors::ThrowRuntimeExAndDefault>();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn establish(vm: &JavaVM, service: &GlobalRef, plan: &VpnPlan) -> io::Result<File> {
|
||||||
|
let mut env = vm.attach_current_thread().map_err(io::Error::other)?;
|
||||||
|
let addresses = plan
|
||||||
|
.addresses_in_order()
|
||||||
|
.iter()
|
||||||
|
.map(ToString::to_string)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",");
|
||||||
|
let routes = plan.routes().join(",");
|
||||||
|
let result = env.with_local_frame(6, |env| -> jni::errors::Result<i32> {
|
||||||
|
let addresses = env.new_string(addresses)?;
|
||||||
|
let routes = env.new_string(routes)?;
|
||||||
|
let dns = env.new_string(
|
||||||
|
plan.dns_address()
|
||||||
|
.map(|a| a.to_string())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
)?;
|
||||||
|
env.call_method(
|
||||||
|
service,
|
||||||
|
"establishTun",
|
||||||
|
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)I",
|
||||||
|
&[
|
||||||
|
JValue::Object(&addresses),
|
||||||
|
JValue::Object(&routes),
|
||||||
|
JValue::Object(&dns),
|
||||||
|
JValue::Int(plan.mtu as i32),
|
||||||
|
JValue::Bool(plan.full_tunnel.into()),
|
||||||
|
],
|
||||||
|
)?
|
||||||
|
.i()
|
||||||
|
});
|
||||||
|
if env.exception_check().unwrap_or(false) {
|
||||||
|
let _ = env.exception_clear();
|
||||||
|
return Err(io::Error::other(
|
||||||
|
"Android could not establish the VPN. Check the VPN permission.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let fd = result.map_err(io::Error::other)?;
|
||||||
|
if fd < 0 {
|
||||||
|
return Err(io::Error::other("Android revoked the VPN permission"));
|
||||||
|
}
|
||||||
|
// SAFETY: establishTun transferred exclusive ownership with detachFd().
|
||||||
|
Ok(File::from(unsafe { OwnedFd::from_raw_fd(fd) }))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
service: JObject,
|
||||||
|
app: JObject,
|
||||||
|
state_dir: JString,
|
||||||
|
cache_dir: JString,
|
||||||
|
addresses: JString,
|
||||||
|
) -> jlong {
|
||||||
|
let result = (|| -> Result<i64, Box<dyn std::error::Error>> {
|
||||||
|
// Keep the application (never an activity) alive for DNS throughout the process.
|
||||||
|
static APPLICATION: OnceLock<GlobalRef> = OnceLock::new();
|
||||||
|
let vm = Arc::new(env.get_java_vm()?);
|
||||||
|
let application = env.new_global_ref(app)?;
|
||||||
|
if APPLICATION.set(application.clone()).is_ok() {
|
||||||
|
// SAFETY: the VM and this stored global reference live until process exit.
|
||||||
|
unsafe {
|
||||||
|
iroh::dns::install_android_jni_context(
|
||||||
|
vm.get_java_vm_pointer().cast(),
|
||||||
|
application.as_obj().as_raw().cast(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let service = env.new_global_ref(service)?;
|
||||||
|
let state_dir: String = env.get_string(&state_dir)?.into();
|
||||||
|
let cache_dir: String = env.get_string(&cache_dir)?.into();
|
||||||
|
let paths = StoragePaths::new(PathBuf::from(state_dir), PathBuf::from(cache_dir));
|
||||||
|
let tun_vm = vm.clone();
|
||||||
|
let tun_service = service.clone();
|
||||||
|
let notice_vm = vm.clone();
|
||||||
|
let notice_service = service.clone();
|
||||||
|
let sdk = env
|
||||||
|
.get_static_field("android/os/Build$VERSION", "SDK_INT", "I")?
|
||||||
|
.i()?;
|
||||||
|
let dns = dns::resolver(vm.clone(), service.clone(), sdk);
|
||||||
|
let factory = AndroidTun::new(
|
||||||
|
dns.clone(),
|
||||||
|
move |plan| establish(&tun_vm, &tun_service, plan),
|
||||||
|
move |socket, source| {
|
||||||
|
let mut env = vm.attach_current_thread().map_err(io::Error::other)?;
|
||||||
|
let result = env.with_local_frame(3, |env| -> jni::errors::Result<bool> {
|
||||||
|
let source = env.new_string(source.to_string())?;
|
||||||
|
env.call_method(
|
||||||
|
&service,
|
||||||
|
"bindOverlaySocket",
|
||||||
|
"(ILjava/lang/String;)Z",
|
||||||
|
&[JValue::Int(socket.as_raw_fd()), JValue::Object(&source)],
|
||||||
|
)?
|
||||||
|
.z()
|
||||||
|
});
|
||||||
|
if env.exception_check().unwrap_or(false) {
|
||||||
|
let _ = env.exception_clear();
|
||||||
|
return Err(io::Error::other("VPN socket binding failed"));
|
||||||
|
}
|
||||||
|
if result.map_err(io::Error::other)? {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(io::Error::other("VPN network is unavailable"))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let addresses: String = env.get_string(&addresses)?.into();
|
||||||
|
let (underlay, physical) = watch::channel(underlay_ips(&addresses));
|
||||||
|
let (commands, rx) = mpsc::channel(16);
|
||||||
|
let (state, state_rx) = watch::channel(State::Starting);
|
||||||
|
let (stop, stopped) = watch::channel(false);
|
||||||
|
static NEXT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
|
||||||
|
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
let mut slot = current();
|
||||||
|
if let Some(old) = slot.as_ref() {
|
||||||
|
old.stop.send_replace(true);
|
||||||
|
}
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name("tsunagi-agent".into())
|
||||||
|
.spawn(move || {
|
||||||
|
let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if *stopped.borrow() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let run = || -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(2)
|
||||||
|
.enable_all()
|
||||||
|
.build()?;
|
||||||
|
runtime.block_on(async {
|
||||||
|
let wg = WireguardPlugin::open(WireguardConfig::new(
|
||||||
|
paths.state_dir.join("wg-quic"),
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
|
let config = AgentConfig::new(paths)
|
||||||
|
.with_transport(TransportPolicy::N0Defaults)
|
||||||
|
.with_dht(MainlineDiscovery::default())
|
||||||
|
.with_interface(Arc::new(factory), "tsunagi-vpn", DEFAULT_MTU)
|
||||||
|
.with_tunnel(wg.clone());
|
||||||
|
let (config, carriers) = tsunagi_runtime::Carriers::configure(
|
||||||
|
config,
|
||||||
|
&[],
|
||||||
|
Some(physical),
|
||||||
|
|_| Vec::new(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let agent = Agent::spawn(config).await?;
|
||||||
|
let _listeners = carriers.listen(&agent);
|
||||||
|
crate::service::serve(agent, wg, dns, rx, &state, stopped, |notice| {
|
||||||
|
update_exit_notification(¬ice_vm, ¬ice_service, id, notice);
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
if let Err(e) = run() {
|
||||||
|
state.send_replace(State::Error(e.to_string()));
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
*slot = Some(Session {
|
||||||
|
id,
|
||||||
|
commands,
|
||||||
|
state: state_rx,
|
||||||
|
underlay,
|
||||||
|
stop,
|
||||||
|
});
|
||||||
|
Ok(id)
|
||||||
|
})();
|
||||||
|
match result {
|
||||||
|
Ok(id) => id,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = env.throw_new("java/lang/IllegalStateException", e.to_string());
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_exit_notification(
|
||||||
|
vm: &JavaVM,
|
||||||
|
service: &GlobalRef,
|
||||||
|
id: i64,
|
||||||
|
notice: Option<&crate::service::ExitNotice>,
|
||||||
|
) {
|
||||||
|
let Ok(mut env) = vm.attach_current_thread() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let _ = env.with_local_frame(6, |env| -> jni::errors::Result<()> {
|
||||||
|
let network = env.new_string(notice.map_or("", |n| &n.network))?;
|
||||||
|
let peer = env.new_string(notice.map_or("", |n| &n.peer))?;
|
||||||
|
let title = env.new_string(
|
||||||
|
notice
|
||||||
|
.map(|n| format!("Exit node · {}", n.name))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
)?;
|
||||||
|
let text = env.new_string(
|
||||||
|
notice
|
||||||
|
.map(|n| {
|
||||||
|
if n.online {
|
||||||
|
format!("IPv4 internet via {}", n.network_name)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"{} · Exit offline. IPv4 internet is blocked.",
|
||||||
|
n.network_name
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_default(),
|
||||||
|
)?;
|
||||||
|
env.call_method(
|
||||||
|
service,
|
||||||
|
"updateExitNotification",
|
||||||
|
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||||
|
&[
|
||||||
|
JValue::Long(id),
|
||||||
|
JValue::Object(&network),
|
||||||
|
JValue::Object(&peer),
|
||||||
|
JValue::Object(&title),
|
||||||
|
JValue::Object(&text),
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
if env.exception_check().unwrap_or(false) {
|
||||||
|
let _ = env.exception_clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_disconnectExit(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
id: jlong,
|
||||||
|
network: JString,
|
||||||
|
peer: JString,
|
||||||
|
) -> jni::sys::jboolean {
|
||||||
|
let (Ok(network), Ok(peer)) = (env.get_string(&network), env.get_string(&peer)) else {
|
||||||
|
return false.into();
|
||||||
|
};
|
||||||
|
current()
|
||||||
|
.as_ref()
|
||||||
|
.filter(|s| s.id == id)
|
||||||
|
.is_some_and(|s| {
|
||||||
|
s.commands
|
||||||
|
.try_send((
|
||||||
|
Request::DisconnectExit {
|
||||||
|
network: network.into(),
|
||||||
|
peer: peer.into(),
|
||||||
|
},
|
||||||
|
oneshot::channel().0,
|
||||||
|
))
|
||||||
|
.is_ok()
|
||||||
|
})
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_failed(
|
||||||
|
_: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
id: jlong,
|
||||||
|
) -> jni::sys::jboolean {
|
||||||
|
current()
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|s| s.id == id && matches!(*s.state.borrow(), State::Error(_)))
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_stop(_: JNIEnv, _: JObject, id: jlong) {
|
||||||
|
let mut slot = current();
|
||||||
|
if slot.as_ref().is_some_and(|s| s.id == id)
|
||||||
|
&& let Some(session) = slot.take()
|
||||||
|
{
|
||||||
|
session.stop.send_replace(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
|
||||||
|
addresses
|
||||||
|
.split(',')
|
||||||
|
.take(32)
|
||||||
|
.filter_map(|s| s.parse().ok())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
#[unsafe(no_mangle)]
|
||||||
|
extern "system" fn Java_cy_hexor_tsunagi_Native_networkChanged(
|
||||||
|
mut env: JNIEnv,
|
||||||
|
_: JObject,
|
||||||
|
id: jlong,
|
||||||
|
addresses: JString,
|
||||||
|
) {
|
||||||
|
let Ok(raw) = env.get_string(&addresses) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if let Some(s) = current().as_ref().filter(|s| s.id == id) {
|
||||||
|
s.underlay.send_replace(underlay_ips(&String::from(raw)));
|
||||||
|
let _ = s
|
||||||
|
.commands
|
||||||
|
.try_send((Request::NetworkChanged, oneshot::channel().0));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
//! Device-local split DNS. Only questions outside the signed mesh zones reach Android's resolver.
|
||||||
|
use simple_dns::{Packet, PacketFlag, RCODE};
|
||||||
|
use std::{net::Ipv4Addr, sync::Arc, time::Duration};
|
||||||
|
use tokio::sync::{Semaphore, watch};
|
||||||
|
use tsunagi::dns::{
|
||||||
|
Zones,
|
||||||
|
server::{MAX_MESSAGE_LEN, Resolution, parse_message, resolve},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(crate) mod stack;
|
||||||
|
|
||||||
|
type Upstream = dyn Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync;
|
||||||
|
|
||||||
|
/// One view of all joined zones, shared across TUN replacements.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Resolver {
|
||||||
|
zones: watch::Sender<Option<Arc<Zones>>>,
|
||||||
|
listening: watch::Sender<Option<Ipv4Addr>>,
|
||||||
|
upstream: Arc<Upstream>,
|
||||||
|
pending: Arc<Semaphore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Resolver {
|
||||||
|
/// The platform callback resolves a wire question on the selected physical network.
|
||||||
|
pub fn new(upstream: impl Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync + 'static) -> Self {
|
||||||
|
Self {
|
||||||
|
zones: watch::channel(None).0,
|
||||||
|
listening: watch::channel(None).0,
|
||||||
|
upstream: Arc::new(upstream),
|
||||||
|
pending: Arc::new(Semaphore::new(16)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Withhold forwarding while configured zones are loading or changing.
|
||||||
|
pub fn replace(&self, zones: Option<Zones>) {
|
||||||
|
self.zones.send_replace(zones.map(Arc::new));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(crate) fn publish(&self, address: Option<Ipv4Addr>) {
|
||||||
|
self.listening.send_replace(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn refresh(&self, networks: &[tsunagi::NetworkStatus]) -> tsunagi::ipc::DnsReport {
|
||||||
|
let view = tsunagi::dns::RosterZones::from_networks(networks);
|
||||||
|
let names = view.zones.names() as u32;
|
||||||
|
self.replace(Some(view.zones));
|
||||||
|
let address = *self.listening.borrow();
|
||||||
|
tsunagi::ipc::DnsReport {
|
||||||
|
listening: address.map(|ip| format!("{ip}:53")).into_iter().collect(),
|
||||||
|
publish_error: (address.is_none() && !view.labels.is_empty())
|
||||||
|
.then(|| "Waiting for a VPN interface with a DNS address.".into()),
|
||||||
|
zones: view.labels,
|
||||||
|
zone_warnings: view.warnings,
|
||||||
|
names,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answer a local DNS request. Slow public lookups never block a mesh answer.
|
||||||
|
pub async fn answer(&self, query: &[u8]) -> Option<Vec<u8>> {
|
||||||
|
if query.len() > MAX_MESSAGE_LEN {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let zones = self.zones.borrow().clone();
|
||||||
|
let Some(zones) = zones else {
|
||||||
|
let question = parse_message(query)?;
|
||||||
|
if question.has_flags(PacketFlag::RESPONSE) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
return error_reply(&question, RCODE::ServerFailure);
|
||||||
|
};
|
||||||
|
match resolve(&zones, query)? {
|
||||||
|
Resolution::Local(reply) => Some(reply),
|
||||||
|
Resolution::Outside(_) => {
|
||||||
|
let question = parse_message(query)?;
|
||||||
|
if let Ok(permit) = self.pending.clone().try_acquire_owned() {
|
||||||
|
let upstream = self.upstream.clone();
|
||||||
|
let wire = query.to_vec();
|
||||||
|
let job = tokio::task::spawn_blocking(move || {
|
||||||
|
let _permit = permit;
|
||||||
|
upstream(&wire)
|
||||||
|
});
|
||||||
|
if let Ok(Ok(Some(mut wire))) =
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), job).await
|
||||||
|
&& wire.len() <= usize::from(u16::MAX)
|
||||||
|
&& parse_message(&wire).is_some_and(|p| {
|
||||||
|
let [received] = p.questions.as_slice() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let sent = &question.questions[0]; // Resolution::Outside has exactly one IN question.
|
||||||
|
p.has_flags(PacketFlag::RESPONSE)
|
||||||
|
&& received.qtype == sent.qtype
|
||||||
|
&& received.qclass == sent.qclass
|
||||||
|
&& received
|
||||||
|
.qname
|
||||||
|
.to_string()
|
||||||
|
.eq_ignore_ascii_case(&sent.qname.to_string())
|
||||||
|
})
|
||||||
|
{
|
||||||
|
// Android's upstream transaction may have used its own ID.
|
||||||
|
wire[..2].copy_from_slice(&question.id().to_be_bytes());
|
||||||
|
return Some(wire);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
error_reply(&question, RCODE::ServerFailure)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_reply(query: &Packet<'_>, code: RCODE) -> Option<Vec<u8>> {
|
||||||
|
let mut answer = Packet::new_reply(query.id());
|
||||||
|
answer.questions.clone_from(&query.questions);
|
||||||
|
if query.has_flags(PacketFlag::RECURSION_DESIRED) {
|
||||||
|
answer.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||||
|
}
|
||||||
|
answer.set_flags(PacketFlag::RECURSION_AVAILABLE);
|
||||||
|
*answer.rcode_mut() = code;
|
||||||
|
answer.build_bytes_vec_compressed().ok()
|
||||||
|
}
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
//! A DNS-only endpoint on the application side of one Android TUN descriptor.
|
||||||
|
//! The kernel reserves port 53. smoltcp terminates UDP and TCP without root.
|
||||||
|
use super::Resolver;
|
||||||
|
use smoltcp::{
|
||||||
|
iface::{Config, Interface, SocketHandle, SocketSet},
|
||||||
|
phy::{self, Device, DeviceCapabilities, Medium},
|
||||||
|
socket::{tcp, udp},
|
||||||
|
time::Instant as NetTime,
|
||||||
|
wire::{HardwareAddress, IpAddress, IpCidr, IpEndpoint},
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
fs::File,
|
||||||
|
io::Write,
|
||||||
|
net::{IpAddr, Ipv4Addr},
|
||||||
|
sync::Arc,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
io::{Interest, unix::AsyncFd},
|
||||||
|
sync::mpsc,
|
||||||
|
task::{JoinHandle, JoinSet},
|
||||||
|
};
|
||||||
|
use tsunagi::dns::server::{MAX_MESSAGE_LEN, truncate_for_udp};
|
||||||
|
|
||||||
|
const PORT: u16 = 53;
|
||||||
|
const QUEUE: usize = 32;
|
||||||
|
const TCP_CLIENTS: usize = 8;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
|
||||||
|
pub(crate) struct DnsPort {
|
||||||
|
address: Ipv4Addr,
|
||||||
|
input: mpsc::Sender<Vec<u8>>,
|
||||||
|
worker: JoinHandle<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DnsPort {
|
||||||
|
pub(crate) fn start(
|
||||||
|
address: Ipv4Addr,
|
||||||
|
mtu: usize,
|
||||||
|
resolver: Resolver,
|
||||||
|
fd: Arc<AsyncFd<File>>,
|
||||||
|
) -> Self {
|
||||||
|
let (input, packets) = mpsc::channel(QUEUE);
|
||||||
|
let worker = tokio::spawn(run(address, mtu, resolver, packets, fd));
|
||||||
|
Self {
|
||||||
|
address,
|
||||||
|
input,
|
||||||
|
worker,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Consume only packets sent to our private endpoint by a local VPN address.
|
||||||
|
pub(crate) fn intercept(&self, bytes: &[u8], local: &[IpAddr]) -> bool {
|
||||||
|
let Ok(packet) = smoltcp::wire::Ipv4Packet::new_checked(bytes) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if packet.version() != 4 || packet.dst_addr() != self.address {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if local.contains(&IpAddr::V4(packet.src_addr())) {
|
||||||
|
let _ = self.input.try_send(bytes.to_vec());
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for DnsPort {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.worker.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Wire {
|
||||||
|
mtu: usize,
|
||||||
|
input: Option<Vec<u8>>,
|
||||||
|
output: VecDeque<Vec<u8>>,
|
||||||
|
}
|
||||||
|
struct Rx(Vec<u8>);
|
||||||
|
impl phy::RxToken for Rx {
|
||||||
|
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
|
||||||
|
f(&self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Tx<'a>(&'a mut VecDeque<Vec<u8>>);
|
||||||
|
impl phy::TxToken for Tx<'_> {
|
||||||
|
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
|
||||||
|
let mut packet = vec![0; len];
|
||||||
|
let result = f(&mut packet);
|
||||||
|
self.0.push_back(packet);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Device for Wire {
|
||||||
|
type RxToken<'a> = Rx;
|
||||||
|
type TxToken<'a> = Tx<'a>;
|
||||||
|
fn receive(&mut self, _: NetTime) -> Option<(Rx, Tx<'_>)> {
|
||||||
|
self.input
|
||||||
|
.take()
|
||||||
|
.map(|packet| (Rx(packet), Tx(&mut self.output)))
|
||||||
|
}
|
||||||
|
fn transmit(&mut self, _: NetTime) -> Option<Tx<'_>> {
|
||||||
|
(self.output.len() < QUEUE).then_some(Tx(&mut self.output))
|
||||||
|
}
|
||||||
|
fn capabilities(&self) -> DeviceCapabilities {
|
||||||
|
let mut caps = DeviceCapabilities::default();
|
||||||
|
caps.medium = Medium::Ip;
|
||||||
|
caps.max_transmission_unit = self.mtu;
|
||||||
|
caps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TcpSlot {
|
||||||
|
handle: SocketHandle,
|
||||||
|
pending: Option<u64>,
|
||||||
|
}
|
||||||
|
enum Client {
|
||||||
|
Udp(IpEndpoint),
|
||||||
|
Tcp { slot: usize, request: u64 },
|
||||||
|
}
|
||||||
|
type Jobs = JoinSet<(Client, Option<Vec<u8>>)>;
|
||||||
|
|
||||||
|
struct Stack {
|
||||||
|
iface: Interface,
|
||||||
|
wire: Wire,
|
||||||
|
sockets: SocketSet<'static>,
|
||||||
|
udp: SocketHandle,
|
||||||
|
tcp: Vec<TcpSlot>,
|
||||||
|
next_request: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stack {
|
||||||
|
fn new(address: Ipv4Addr, mtu: usize) -> Self {
|
||||||
|
let mut wire = Wire {
|
||||||
|
mtu,
|
||||||
|
input: None,
|
||||||
|
output: VecDeque::new(),
|
||||||
|
};
|
||||||
|
let mut config = Config::new(HardwareAddress::Ip);
|
||||||
|
config.random_seed = rand::random();
|
||||||
|
let mut iface = Interface::new(config, &mut wire, NetTime::from_millis(0));
|
||||||
|
// This is a point-to-point IP device. Its only neighbour is Android, whatever
|
||||||
|
// the OS chose as the source address among the attached networks.
|
||||||
|
iface.update_ip_addrs(|addrs| {
|
||||||
|
let _ = addrs.push(IpCidr::new(IpAddress::Ipv4(address), 0));
|
||||||
|
});
|
||||||
|
let mut sockets = SocketSet::new(Vec::new());
|
||||||
|
let datagrams = || {
|
||||||
|
udp::PacketBuffer::new(
|
||||||
|
vec![udp::PacketMetadata::EMPTY; QUEUE],
|
||||||
|
vec![0; QUEUE * mtu],
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let mut socket = udp::Socket::new(datagrams(), datagrams());
|
||||||
|
let _ = socket.bind(PORT);
|
||||||
|
let udp = sockets.add(socket);
|
||||||
|
let tcp = (0..TCP_CLIENTS)
|
||||||
|
.map(|_| {
|
||||||
|
let mut socket = tcp::Socket::new(
|
||||||
|
tcp::SocketBuffer::new(vec![0; MAX_MESSAGE_LEN + 2]),
|
||||||
|
tcp::SocketBuffer::new(vec![0; usize::from(u16::MAX) + 2]),
|
||||||
|
);
|
||||||
|
socket.set_timeout(Some(smoltcp::time::Duration::from_secs(10)));
|
||||||
|
let _ = socket.listen(PORT);
|
||||||
|
TcpSlot {
|
||||||
|
handle: sockets.add(socket),
|
||||||
|
pending: None,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Self {
|
||||||
|
iface,
|
||||||
|
wire,
|
||||||
|
sockets,
|
||||||
|
udp,
|
||||||
|
tcp,
|
||||||
|
next_request: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll(&mut self, now: NetTime) {
|
||||||
|
self.iface.poll(now, &mut self.wire, &mut self.sockets);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch(&mut self, resolver: &Resolver, jobs: &mut Jobs) {
|
||||||
|
let udp = self.sockets.get_mut::<udp::Socket>(self.udp);
|
||||||
|
while let Ok((wire, metadata)) = udp.recv() {
|
||||||
|
if jobs.len() >= QUEUE || wire.len() > MAX_MESSAGE_LEN {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let resolver = resolver.clone();
|
||||||
|
let query = wire.to_vec();
|
||||||
|
let limit = self.wire.mtu.saturating_sub(28);
|
||||||
|
jobs.spawn(async move {
|
||||||
|
let reply = resolver
|
||||||
|
.answer(&query)
|
||||||
|
.await
|
||||||
|
.map(|reply| truncate_for_udp(&query, reply, limit));
|
||||||
|
(Client::Udp(metadata.endpoint), reply)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (index, slot) in self.tcp.iter_mut().enumerate() {
|
||||||
|
let tcp = self.sockets.get_mut::<tcp::Socket>(slot.handle);
|
||||||
|
if !tcp.is_open() {
|
||||||
|
slot.pending = None;
|
||||||
|
let _ = tcp.listen(PORT);
|
||||||
|
}
|
||||||
|
if slot.pending.is_some() || tcp.send_queue() != 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if tcp.state() == tcp::State::CloseWait && tcp.recv_queue() < 2 {
|
||||||
|
tcp.close();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut header = [0; 2];
|
||||||
|
if tcp.peek_slice(&mut header) != Ok(2) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let len = usize::from(u16::from_be_bytes(header));
|
||||||
|
if !(12..=MAX_MESSAGE_LEN).contains(&len) {
|
||||||
|
tcp.abort();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if tcp.recv_queue() < len + 2 || jobs.len() >= QUEUE {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut query = vec![0; len];
|
||||||
|
if tcp.recv_slice(&mut header) != Ok(2) || tcp.recv_slice(&mut query) != Ok(len) {
|
||||||
|
tcp.abort();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
self.next_request = self.next_request.wrapping_add(1);
|
||||||
|
let request = self.next_request;
|
||||||
|
slot.pending = Some(request);
|
||||||
|
let resolver = resolver.clone();
|
||||||
|
jobs.spawn(async move {
|
||||||
|
(
|
||||||
|
Client::Tcp {
|
||||||
|
slot: index,
|
||||||
|
request,
|
||||||
|
},
|
||||||
|
resolver.answer(&query).await,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver(&mut self, client: Client, reply: Option<Vec<u8>>) {
|
||||||
|
match client {
|
||||||
|
Client::Udp(peer) => {
|
||||||
|
if let Some(reply) = reply {
|
||||||
|
let _ = self
|
||||||
|
.sockets
|
||||||
|
.get_mut::<udp::Socket>(self.udp)
|
||||||
|
.send_slice(&reply, peer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Client::Tcp { slot, request } => {
|
||||||
|
let slot = &mut self.tcp[slot];
|
||||||
|
if slot.pending != Some(request) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
slot.pending = None;
|
||||||
|
let tcp = self.sockets.get_mut::<tcp::Socket>(slot.handle);
|
||||||
|
if let Some(reply) = reply
|
||||||
|
&& let Ok(len) = u16::try_from(reply.len())
|
||||||
|
&& tcp.send_slice(&len.to_be_bytes()) == Ok(2)
|
||||||
|
&& tcp.send_slice(&reply) == Ok(reply.len())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tcp.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(
|
||||||
|
address: Ipv4Addr,
|
||||||
|
mtu: usize,
|
||||||
|
resolver: Resolver,
|
||||||
|
mut input: mpsc::Receiver<Vec<u8>>,
|
||||||
|
fd: Arc<AsyncFd<File>>,
|
||||||
|
) {
|
||||||
|
let mut stack = Stack::new(address, mtu);
|
||||||
|
let mut jobs = Jobs::new();
|
||||||
|
let start = Instant::now();
|
||||||
|
loop {
|
||||||
|
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
|
||||||
|
stack.poll(now);
|
||||||
|
stack.dispatch(&resolver, &mut jobs);
|
||||||
|
stack.poll(now);
|
||||||
|
while let Some(packet) = stack.wire.output.pop_front() {
|
||||||
|
if !matches!(fd.async_io(Interest::WRITABLE, |mut file| file.write(&packet)).await, Ok(n) if n == packet.len())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let delay = stack
|
||||||
|
.iface
|
||||||
|
.poll_delay(now, &stack.sockets)
|
||||||
|
.map(Duration::from);
|
||||||
|
tokio::select! {
|
||||||
|
packet = input.recv() => match packet { Some(packet) => stack.wire.input = Some(packet), None => return },
|
||||||
|
Some(Ok((client, reply))) = jobs.join_next(), if !jobs.is_empty() => stack.deliver(client, reply),
|
||||||
|
_ = async { if let Some(delay) = delay { tokio::time::sleep(delay).await } else { std::future::pending().await } } => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, TYPE};
|
||||||
|
use std::os::{fd::OwnedFd, unix::net::UnixDatagram};
|
||||||
|
use tsunagi::dns::{Zone, ZoneName, Zones};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn android_tun_dns_truncates_udp_and_returns_the_complete_answer_over_tcp() {
|
||||||
|
let address = Ipv4Addr::new(192, 0, 2, 53);
|
||||||
|
let phone = Ipv4Addr::new(10, 10, 0, 1);
|
||||||
|
let (fd, os) = UnixDatagram::pair().unwrap();
|
||||||
|
fd.set_nonblocking(true).unwrap();
|
||||||
|
os.set_nonblocking(true).unwrap();
|
||||||
|
let fd = AsyncFd::new(File::from(OwnedFd::from(fd))).unwrap();
|
||||||
|
let os = tokio::net::UnixDatagram::from_std(os).unwrap();
|
||||||
|
let resolver = Resolver::new(|_| panic!("a mesh name went upstream"));
|
||||||
|
resolver.replace(Some(Zones::new([Zone::new(
|
||||||
|
ZoneName::new("tsng").unwrap(),
|
||||||
|
(1..=90).map(|host| ("api".into(), Ipv4Addr::new(10, 1, 2, host))),
|
||||||
|
)])));
|
||||||
|
let port = DnsPort::start(address, 1280, resolver, Arc::new(fd));
|
||||||
|
let mut wire = Wire {
|
||||||
|
mtu: 1280,
|
||||||
|
input: None,
|
||||||
|
output: VecDeque::new(),
|
||||||
|
};
|
||||||
|
let mut iface = Interface::new(
|
||||||
|
Config::new(HardwareAddress::Ip),
|
||||||
|
&mut wire,
|
||||||
|
NetTime::from_millis(0),
|
||||||
|
);
|
||||||
|
iface.update_ip_addrs(|a| a.push(IpCidr::new(IpAddress::Ipv4(phone), 0)).unwrap());
|
||||||
|
let mut sockets = SocketSet::new(Vec::new());
|
||||||
|
let buf = || udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY; 4], vec![0; 4096]);
|
||||||
|
let mut datagram = udp::Socket::new(buf(), buf());
|
||||||
|
datagram.bind(41000).unwrap();
|
||||||
|
let mut packet = Packet::new_query(42);
|
||||||
|
packet.questions.push(Question::new(
|
||||||
|
Name::new("api.tsng").unwrap(),
|
||||||
|
TYPE::A.into(),
|
||||||
|
CLASS::IN.into(),
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
let query = packet.build_bytes_vec().unwrap();
|
||||||
|
datagram.send_slice(&query, (address, PORT)).unwrap();
|
||||||
|
let udp = sockets.add(datagram);
|
||||||
|
let tcp = sockets.add(tcp::Socket::new(
|
||||||
|
tcp::SocketBuffer::new(vec![0; 8192]),
|
||||||
|
tcp::SocketBuffer::new(vec![0; 512]),
|
||||||
|
));
|
||||||
|
let mut sent = false;
|
||||||
|
let mut received = Vec::new();
|
||||||
|
let mut buf = [0; 1500];
|
||||||
|
let start = Instant::now();
|
||||||
|
tokio::time::timeout(Duration::from_secs(4), async {
|
||||||
|
loop {
|
||||||
|
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
|
||||||
|
iface.poll(now, &mut wire, &mut sockets);
|
||||||
|
if let Ok((reply, from)) = sockets.get_mut::<udp::Socket>(udp).recv() {
|
||||||
|
assert_eq!(from.endpoint, (address, PORT).into());
|
||||||
|
let reply = Packet::parse(reply).unwrap();
|
||||||
|
assert_eq!(reply.id(), 42);
|
||||||
|
assert!(reply.has_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER));
|
||||||
|
sockets
|
||||||
|
.get_mut::<tcp::Socket>(tcp)
|
||||||
|
.connect(iface.context(), (address, PORT), 41001)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let stream = sockets.get_mut::<tcp::Socket>(tcp);
|
||||||
|
if stream.can_send() && !sent {
|
||||||
|
let mut frame = (query.len() as u16).to_be_bytes().to_vec();
|
||||||
|
frame.extend_from_slice(&query);
|
||||||
|
assert_eq!(stream.send_slice(&frame).unwrap(), frame.len());
|
||||||
|
sent = true;
|
||||||
|
}
|
||||||
|
while stream.can_recv() {
|
||||||
|
let n = stream.recv_slice(&mut buf).unwrap();
|
||||||
|
received.extend_from_slice(&buf[..n]);
|
||||||
|
}
|
||||||
|
if let Some(prefix) = received.first_chunk::<2>()
|
||||||
|
&& received.len() == 2 + usize::from(u16::from_be_bytes(*prefix))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
iface.poll(now, &mut wire, &mut sockets);
|
||||||
|
for outgoing in wire.output.drain(..) {
|
||||||
|
assert!(port.intercept(&outgoing, &[phone.into()]));
|
||||||
|
}
|
||||||
|
let delay = iface
|
||||||
|
.poll_delay(now, &sockets)
|
||||||
|
.map(Duration::from)
|
||||||
|
.unwrap_or(Duration::from_secs(4));
|
||||||
|
tokio::select! {
|
||||||
|
n = os.recv(&mut buf) => wire.input = Some(buf[..n.unwrap()].to_vec()),
|
||||||
|
_ = tokio::time::sleep(delay) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("DNS over the Android packet device must complete");
|
||||||
|
let reply = Packet::parse(&received[2..]).unwrap();
|
||||||
|
assert_eq!(reply.id(), 42);
|
||||||
|
assert!(!reply.has_flags(PacketFlag::TRUNCATION));
|
||||||
|
assert_eq!(reply.answers.len(), 90);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
//! The Android application. Mesh state belongs to one service-owned Rust agent.
|
||||||
|
|
||||||
|
pub mod dns;
|
||||||
|
pub mod plan;
|
||||||
|
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
mod android;
|
||||||
|
pub mod service;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub mod tun;
|
||||||
|
pub mod view;
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
//! All addresses and routes installed in the one Android VPN.
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
|
use tsunagi::overlay::Cidr;
|
||||||
|
|
||||||
|
/// An exhaustive VpnService configuration, derived from local core policy.
|
||||||
|
#[derive(Clone, Default, Debug, PartialEq, Eq)]
|
||||||
|
pub struct VpnPlan {
|
||||||
|
/// One address in each active, non-overlapping network.
|
||||||
|
pub addresses: Vec<Cidr>,
|
||||||
|
/// Payload MTU for every attached network.
|
||||||
|
pub mtu: u32,
|
||||||
|
/// Capture IPv4 traffic outside the mesh.
|
||||||
|
pub full_tunnel: bool,
|
||||||
|
/// Preferred IPv4 source for the default route.
|
||||||
|
pub exit: Option<IpAddr>,
|
||||||
|
/// Capture the limited broadcast when requested by the core.
|
||||||
|
pub broadcast: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VpnPlan {
|
||||||
|
/// Device-local DNS endpoint. Never take an address from a joined mesh.
|
||||||
|
pub fn dns_address(&self) -> Option<Ipv4Addr> {
|
||||||
|
if self.addresses.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
[
|
||||||
|
Ipv4Addr::new(192, 0, 2, 53),
|
||||||
|
Ipv4Addr::new(198, 51, 100, 53),
|
||||||
|
Ipv4Addr::new(203, 0, 113, 53),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.find(|candidate| {
|
||||||
|
!self.addresses.iter().any(|cidr| {
|
||||||
|
let IpAddr::V4(base) = cidr.addr else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
tsunagi::state::Ipv4Range {
|
||||||
|
base,
|
||||||
|
prefix_len: cidr.prefix_len,
|
||||||
|
}
|
||||||
|
.contains(*candidate)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Android uses the first address as primary for unscoped IPv4 traffic.
|
||||||
|
pub fn addresses_in_order(&self) -> Vec<Cidr> {
|
||||||
|
let mut ordered = self.addresses.clone();
|
||||||
|
ordered.sort_by_key(|cidr| (Some(cidr.addr) != self.exit, *cidr));
|
||||||
|
ordered
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Explicitly route the entire agreed subnet, including its virtual services.
|
||||||
|
pub fn routes(&self) -> Vec<String> {
|
||||||
|
let mut routes: Vec<_> = self
|
||||||
|
.addresses
|
||||||
|
.iter()
|
||||||
|
.map(|cidr| {
|
||||||
|
let p = cidr.prefix_len;
|
||||||
|
let base = match cidr.addr {
|
||||||
|
IpAddr::V4(a) => IpAddr::V4(Ipv4Addr::from(
|
||||||
|
u32::from(a) & u32::MAX.checked_shl(u32::from(32 - p)).unwrap_or(0),
|
||||||
|
)),
|
||||||
|
IpAddr::V6(a) => IpAddr::V6(Ipv6Addr::from(
|
||||||
|
u128::from(a) & u128::MAX.checked_shl(u32::from(128 - p)).unwrap_or(0),
|
||||||
|
)),
|
||||||
|
};
|
||||||
|
format!("{base}/{p}")
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if let Some(dns) = self.dns_address() {
|
||||||
|
routes.push(format!("{dns}/32"));
|
||||||
|
}
|
||||||
|
if self.full_tunnel {
|
||||||
|
routes.push("0.0.0.0/0".into());
|
||||||
|
}
|
||||||
|
if self.broadcast {
|
||||||
|
routes.push("255.255.255.255/32".into());
|
||||||
|
}
|
||||||
|
routes.sort();
|
||||||
|
routes.dedup();
|
||||||
|
routes
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
//! Actions and status for the service-owned Rust agent.
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
use tokio::sync::{mpsc, watch};
|
||||||
|
use tsunagi::{
|
||||||
|
Agent, NetworkName, NetworkSecret,
|
||||||
|
ipc::{PrivilegeReport, ProtocolReport, StatusReport},
|
||||||
|
vip::VipStatus,
|
||||||
|
};
|
||||||
|
use tsunagi_ui::client::Command;
|
||||||
|
use tsunagi_wg_quic::WireguardPlugin;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// A platform notification or user gesture.
|
||||||
|
pub enum Request {
|
||||||
|
/// A command from the same form used by the tray.
|
||||||
|
Action(Command),
|
||||||
|
/// The physical network changed.
|
||||||
|
NetworkChanged,
|
||||||
|
/// Disable only the exit identified by the notification the user tapped.
|
||||||
|
DisconnectExit {
|
||||||
|
/// Network id captured in the immutable action.
|
||||||
|
network: String,
|
||||||
|
/// Endpoint id captured at the same time.
|
||||||
|
peer: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A configured default route stays visible if its remote peer goes offline.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ExitNotice {
|
||||||
|
/// Active network identity for the notification action.
|
||||||
|
pub network: String,
|
||||||
|
/// Selected remote device identity.
|
||||||
|
pub peer: String,
|
||||||
|
/// Human-readable mesh name.
|
||||||
|
pub network_name: String,
|
||||||
|
/// Same name shown in the exit chooser.
|
||||||
|
pub name: String,
|
||||||
|
/// Whether the peer still offers its exit.
|
||||||
|
pub online: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only an active network with a selected remote exit needs an ongoing notice.
|
||||||
|
pub fn exit_notice(report: &StatusReport) -> Option<ExitNotice> {
|
||||||
|
report.networks.iter().filter(|n| n.active).find_map(|n| {
|
||||||
|
let peer = n.exit.via.as_ref()?;
|
||||||
|
Some(ExitNotice {
|
||||||
|
network: n.network_id.clone(),
|
||||||
|
peer: peer.clone(),
|
||||||
|
network_name: n.name.clone(),
|
||||||
|
name: tsunagi_ui::devices::name_of(n, peer),
|
||||||
|
online: n.exit.via_online,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Actions are serialized in the service command loop. An old PendingIntent cannot
|
||||||
|
/// clear a replacement exit selected in this or another network.
|
||||||
|
pub async fn disconnect_exit(
|
||||||
|
agent: &Agent,
|
||||||
|
network: &str,
|
||||||
|
peer: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let network = network.parse()?;
|
||||||
|
let peer = peer.parse()?;
|
||||||
|
if agent.is_active(network).await && agent.network_status(network).await?.exit_via == Some(peer)
|
||||||
|
{
|
||||||
|
agent.set_exit_via(network, None).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Private reply delivered only to the UI that requested the action.
|
||||||
|
pub enum Outcome {
|
||||||
|
/// The agent has applied the action.
|
||||||
|
Applied,
|
||||||
|
/// Revisions returned by a successful signed write.
|
||||||
|
Saved(Vec<VipStatus>),
|
||||||
|
/// A user-requested, single-use clipboard export.
|
||||||
|
Clipboard(Zeroizing<String>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivery channel for a request.
|
||||||
|
pub type Reply = tokio::sync::oneshot::Sender<Result<Outcome, String>>;
|
||||||
|
/// Pending acknowledgement of a UI action.
|
||||||
|
pub type Response = tokio::sync::oneshot::Receiver<Result<Outcome, String>>;
|
||||||
|
|
||||||
|
/// Execute exactly the selection and revision supplied by the form.
|
||||||
|
pub async fn apply(
|
||||||
|
command: Command,
|
||||||
|
agent: &Agent,
|
||||||
|
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
match command {
|
||||||
|
Command::Join { name, secret } => {
|
||||||
|
agent
|
||||||
|
.join_network(&NetworkName::new(name)?, &NetworkSecret::decode(&secret)?)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Command::SetActive { network_id, active } => {
|
||||||
|
let id = network_id.parse()?;
|
||||||
|
if active {
|
||||||
|
agent.switch_network(id).await?;
|
||||||
|
} else {
|
||||||
|
agent.pause_network(id).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Leave { network_id } => {
|
||||||
|
agent.leave_network(network_id.parse()?).await?;
|
||||||
|
}
|
||||||
|
Command::SetBroadcast {
|
||||||
|
network_id,
|
||||||
|
enabled,
|
||||||
|
} => agent.set_broadcast(network_id.parse()?, enabled).await?,
|
||||||
|
Command::SetProtocols {
|
||||||
|
network_id,
|
||||||
|
protocols,
|
||||||
|
} => agent.set_protocols(network_id.parse()?, protocols).await?,
|
||||||
|
Command::SetHostname(hostname) => {
|
||||||
|
agent.set_hostname(&hostname).await?;
|
||||||
|
}
|
||||||
|
Command::ForgetNode {
|
||||||
|
network_id,
|
||||||
|
peer,
|
||||||
|
expected_version,
|
||||||
|
} => {
|
||||||
|
agent
|
||||||
|
.forget_node(network_id.parse()?, peer.parse()?, expected_version)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Command::SetExitNode { network_id, peer } => {
|
||||||
|
agent
|
||||||
|
.set_exit_via(network_id.parse()?, peer.map(|p| p.parse()).transpose()?)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
Command::SetExitOffer { .. } => {
|
||||||
|
return Err("This phone can only use a remote exit node.".into());
|
||||||
|
}
|
||||||
|
Command::SaveVip {
|
||||||
|
network_id,
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
return Ok(Outcome::Saved(
|
||||||
|
agent
|
||||||
|
.save_vip(network_id.parse()?, config, expected, delete)
|
||||||
|
.await?,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Command::CopySecret { network_id } => {
|
||||||
|
return Ok(Outcome::Clipboard(
|
||||||
|
agent.network_secret(network_id.parse()?).await?.encode(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Outcome::Applied)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// State visible to an activity which may be recreated while the service runs.
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub enum State {
|
||||||
|
/// The user can start the VPN.
|
||||||
|
#[default]
|
||||||
|
Off,
|
||||||
|
/// Opening the endpoint or waiting for connectivity.
|
||||||
|
Starting,
|
||||||
|
/// The last complete snapshot and its monotonic observation time.
|
||||||
|
Ready(Arc<StatusReport>, Instant),
|
||||||
|
/// Actionable startup or status error.
|
||||||
|
Error(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the same network and counter reports used by the desktop client.
|
||||||
|
pub async fn report(
|
||||||
|
agent: &Agent,
|
||||||
|
wg: Option<&WireguardPlugin>,
|
||||||
|
dns: &crate::dns::Resolver,
|
||||||
|
) -> tsunagi::Result<StatusReport> {
|
||||||
|
let status = agent.status().await?;
|
||||||
|
Ok(StatusReport {
|
||||||
|
networks: tsunagi_runtime::report::networks(&status, agent.overlay().as_ref(), wg),
|
||||||
|
dns: Some(dns.refresh(&status.networks)),
|
||||||
|
endpoint_id: status.endpoint_id.to_string(),
|
||||||
|
hostname: status.hostname,
|
||||||
|
bound_sockets: status
|
||||||
|
.bound_sockets
|
||||||
|
.iter()
|
||||||
|
.map(ToString::to_string)
|
||||||
|
.collect(),
|
||||||
|
cache_healthy: status.cache_healthy,
|
||||||
|
available_protocols: tsunagi_runtime::PROTOCOLS
|
||||||
|
.iter()
|
||||||
|
.map(|spec| ProtocolReport {
|
||||||
|
name: spec.name.into(),
|
||||||
|
summary: spec.summary.into(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
protocols: tsunagi_runtime::PROTOCOLS
|
||||||
|
.iter()
|
||||||
|
.map(|spec| format!("{} v{}", spec.name, spec.version))
|
||||||
|
.collect(),
|
||||||
|
privilege: PrivilegeReport::Available,
|
||||||
|
version: env!("CARGO_PKG_VERSION").into(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drive the agent until Android stops this service instance.
|
||||||
|
pub async fn serve(
|
||||||
|
agent: Agent,
|
||||||
|
wg: Arc<WireguardPlugin>,
|
||||||
|
dns: crate::dns::Resolver,
|
||||||
|
mut commands: mpsc::Receiver<(Request, Reply)>,
|
||||||
|
state: &watch::Sender<State>,
|
||||||
|
mut stop: watch::Receiver<bool>,
|
||||||
|
mut publish_exit: impl FnMut(Option<&ExitNotice>),
|
||||||
|
) {
|
||||||
|
let mut poll = tokio::time::interval(std::time::Duration::from_secs(2));
|
||||||
|
poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
let mut published_exit = None;
|
||||||
|
loop {
|
||||||
|
let reply = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = stop.wait_for(|stopped| *stopped) => break,
|
||||||
|
command = commands.recv() => {
|
||||||
|
let Some((request, reply)) = command else { break };
|
||||||
|
let result = match request {
|
||||||
|
Request::Action(cmd) => {
|
||||||
|
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||||
|
dns.replace(None);
|
||||||
|
}
|
||||||
|
apply(cmd, &agent).await.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
Request::NetworkChanged => {
|
||||||
|
agent.endpoint().network_change().await;
|
||||||
|
agent.recheck().await;
|
||||||
|
Ok(Outcome::Applied)
|
||||||
|
}
|
||||||
|
Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await
|
||||||
|
.map(|()| Outcome::Applied).map_err(|e| e.to_string()),
|
||||||
|
};
|
||||||
|
Some((reply, result))
|
||||||
|
}
|
||||||
|
_ = poll.tick() => None,
|
||||||
|
};
|
||||||
|
state.send_replace(match report(&agent, Some(&wg), &dns).await {
|
||||||
|
Ok(report) => {
|
||||||
|
let notice = exit_notice(&report);
|
||||||
|
if published_exit.as_ref() != Some(¬ice) {
|
||||||
|
publish_exit(notice.as_ref());
|
||||||
|
published_exit = Some(notice);
|
||||||
|
}
|
||||||
|
State::Ready(Arc::new(report), Instant::now())
|
||||||
|
}
|
||||||
|
Err(error) => State::Error(error.to_string()),
|
||||||
|
});
|
||||||
|
if let Some((reply, outcome)) = reply {
|
||||||
|
let _ = reply.send(outcome);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,651 @@
|
|||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use super::plan::VpnPlan;
|
||||||
|
use std::net::{IpAddr, Ipv4Addr};
|
||||||
|
use tsunagi::overlay::Cidr;
|
||||||
|
|
||||||
|
fn addr(octet: u8) -> Cidr {
|
||||||
|
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, octet, 42, 19)), 24).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() {
|
||||||
|
use crate::service::{disconnect_exit, exit_notice, report};
|
||||||
|
use tsunagi::{
|
||||||
|
discovery::SharedMemoryDiscovery,
|
||||||
|
testing::{TestAgent, network, wait_until},
|
||||||
|
};
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let phone = TestAgent::spawn(&discovery).await.unwrap();
|
||||||
|
let rules = std::sync::Arc::new(tsunagi::overlay::MockHostRules::new());
|
||||||
|
let tuns = tsunagi::overlay::MemoryTunFactory::new().with_host_rules(rules);
|
||||||
|
let exit = TestAgent::spawn_with(
|
||||||
|
|cfg| cfg.with_interface(std::sync::Arc::new(tuns), "gateway", 1280),
|
||||||
|
&discovery,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (name, secret) = network("travel");
|
||||||
|
let id = phone.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
exit.agent.set_hostname("gateway").await.unwrap();
|
||||||
|
exit.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
exit.agent.set_exit_offer(id, true).await.unwrap();
|
||||||
|
let peer = exit.agent.endpoint_id();
|
||||||
|
wait_until("authenticated exit offer", || async {
|
||||||
|
phone
|
||||||
|
.agent
|
||||||
|
.network_status(id)
|
||||||
|
.await
|
||||||
|
.ok()?
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.any(|p| p.endpoint_id == peer && p.exit_node)
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let dns = crate::dns::Resolver::new(|_| None);
|
||||||
|
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||||
|
phone.agent.set_exit_via(id, Some(peer)).await.unwrap();
|
||||||
|
let notice = exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).unwrap();
|
||||||
|
assert_eq!(notice.name, "gateway");
|
||||||
|
assert_eq!(notice.network_name, "travel");
|
||||||
|
assert!(notice.online);
|
||||||
|
disconnect_exit(
|
||||||
|
&phone.agent,
|
||||||
|
&id.to_string(),
|
||||||
|
&phone.agent.endpoint_id().to_string(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
phone.agent.network_status(id).await.unwrap().exit_via,
|
||||||
|
Some(peer)
|
||||||
|
);
|
||||||
|
exit.stop().await;
|
||||||
|
wait_until(
|
||||||
|
"offline exit remains selected in the notification",
|
||||||
|
|| async {
|
||||||
|
let report = report(&phone.agent, None, &dns).await.ok()?;
|
||||||
|
exit_notice(&report).filter(|n| !n.online)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||||
|
assert!(phone.agent.is_active(id).await);
|
||||||
|
phone.stop().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn vpn_dns_answers_hosts_and_vips_in_each_zone_and_only_forwards_external_names() {
|
||||||
|
use crate::dns::Resolver;
|
||||||
|
use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, RCODE, TYPE, rdata::RData};
|
||||||
|
use std::sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
};
|
||||||
|
use tsunagi::dns::{Zone, ZoneName, Zones};
|
||||||
|
|
||||||
|
fn query(name: &str, kind: TYPE) -> Vec<u8> {
|
||||||
|
let mut packet = Packet::new_query(119);
|
||||||
|
packet.set_flags(PacketFlag::RECURSION_DESIRED);
|
||||||
|
packet.questions.push(Question::new(
|
||||||
|
Name::new(name).unwrap(),
|
||||||
|
kind.into(),
|
||||||
|
CLASS::IN.into(),
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
packet.build_bytes_vec().unwrap()
|
||||||
|
}
|
||||||
|
let calls = Arc::new(AtomicUsize::new(0));
|
||||||
|
let forwarded = calls.clone();
|
||||||
|
let resolver = Resolver::new(move |wire| {
|
||||||
|
forwarded.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let query = Packet::parse(wire).unwrap();
|
||||||
|
let mut answer = Packet::new_reply(999);
|
||||||
|
answer.questions = query.questions;
|
||||||
|
answer.build_bytes_vec().ok()
|
||||||
|
});
|
||||||
|
let private = query("k8s.tsng", TYPE::A);
|
||||||
|
let answer = resolver.answer(&private).await.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
Packet::parse(&answer).unwrap().rcode(),
|
||||||
|
RCODE::ServerFailure
|
||||||
|
);
|
||||||
|
let lab = |name, members| Zone::new(ZoneName::new(name).unwrap(), members);
|
||||||
|
resolver.replace(Some(Zones::new([
|
||||||
|
lab(
|
||||||
|
"tsng",
|
||||||
|
vec![
|
||||||
|
("ai".into(), [10, 1, 1, 100].into()),
|
||||||
|
("k8s".into(), [10, 1, 1, 106].into()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
lab("lab", vec![("ai".into(), [10, 2, 1, 100].into())]),
|
||||||
|
])));
|
||||||
|
for (name, ip) in [
|
||||||
|
("AI.TSNG", [10, 1, 1, 100]),
|
||||||
|
("k8s.tsng", [10, 1, 1, 106]),
|
||||||
|
("ai.lab", [10, 2, 1, 100]),
|
||||||
|
] {
|
||||||
|
let reply = resolver.answer(&query(name, TYPE::A)).await.unwrap();
|
||||||
|
let packet = Packet::parse(&reply).unwrap();
|
||||||
|
assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
|
||||||
|
assert!(
|
||||||
|
matches!(&packet.answers[0].rdata, RData::A(a) if Ipv4Addr::from(a.address) == Ipv4Addr::from(ip))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (name, kind, code) in [
|
||||||
|
("missing.tsng", TYPE::A, RCODE::NameError),
|
||||||
|
("k8s.tsng", TYPE::AAAA, RCODE::NoError),
|
||||||
|
] {
|
||||||
|
let reply = resolver.answer(&query(name, kind)).await.unwrap();
|
||||||
|
let packet = Packet::parse(&reply).unwrap();
|
||||||
|
assert_eq!(packet.rcode(), code);
|
||||||
|
assert!(packet.answers.is_empty());
|
||||||
|
assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER));
|
||||||
|
}
|
||||||
|
assert!(resolver.answer(b"invalid").await.is_none());
|
||||||
|
assert_eq!(calls.load(Ordering::Relaxed), 0);
|
||||||
|
let reply = resolver
|
||||||
|
.answer(&query("example.org", TYPE::HTTPS))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let packet = Packet::parse(&reply).unwrap();
|
||||||
|
assert_eq!(packet.id(), 119);
|
||||||
|
assert_eq!(packet.questions[0].qtype, TYPE::HTTPS.into());
|
||||||
|
assert_eq!(calls.load(Ordering::Relaxed), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_dns_address_is_routed_and_cannot_claim_an_overlay_ip() {
|
||||||
|
let mut plan = VpnPlan {
|
||||||
|
addresses: vec![addr(1)],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let dns = plan.dns_address().unwrap();
|
||||||
|
assert!(plan.routes().contains(&format!("{dns}/32")));
|
||||||
|
plan.addresses.push(Cidr::new(dns.into(), 24).unwrap());
|
||||||
|
let other = plan.dns_address().unwrap();
|
||||||
|
assert_ne!(other, dns);
|
||||||
|
assert!(plan.routes().contains(&format!("{other}/32")));
|
||||||
|
plan.addresses.clear();
|
||||||
|
assert!(plan.dns_address().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn service_dns_tracks_signed_hostnames_vip_deletion_and_reverse_ranges() {
|
||||||
|
use tsunagi::{
|
||||||
|
Agent,
|
||||||
|
dns::{Answer, Query, RosterZones},
|
||||||
|
testing,
|
||||||
|
vip::VipConfig,
|
||||||
|
};
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let agent = Agent::spawn(testing::local_config(dir.path()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (network, secret) = testing::network("tsng");
|
||||||
|
let id = agent.join_network(&network, &secret).await.unwrap();
|
||||||
|
agent.set_hostname("worker").await.unwrap();
|
||||||
|
let vip = agent
|
||||||
|
.save_vip(id, VipConfig::new("k8s"), None, false)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.remove(0);
|
||||||
|
let status = agent.status().await.unwrap();
|
||||||
|
let roster = RosterZones::from_networks(&status.networks);
|
||||||
|
let worker = status.networks[0]
|
||||||
|
.members
|
||||||
|
.iter()
|
||||||
|
.find(|m| m.hostname.as_deref() == Some("worker"))
|
||||||
|
.unwrap()
|
||||||
|
.overlay_address_v4
|
||||||
|
.unwrap();
|
||||||
|
for (name, ip) in [("worker.tsng", worker), ("k8s.tsng", vip.address.unwrap())] {
|
||||||
|
assert_eq!(
|
||||||
|
roster.zones.lookup(name, Query::A).unwrap().1,
|
||||||
|
Answer::Addresses(vec![ip])
|
||||||
|
);
|
||||||
|
let [a, b, c, d] = ip.octets();
|
||||||
|
assert_eq!(
|
||||||
|
roster
|
||||||
|
.zones
|
||||||
|
.lookup(&format!("{d}.{c}.{b}.{a}.in-addr.arpa"), Query::Ptr)
|
||||||
|
.unwrap()
|
||||||
|
.1,
|
||||||
|
Answer::Name(name.into())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
roster
|
||||||
|
.zones
|
||||||
|
.lookup("8.8.8.8.in-addr.arpa", Query::Ptr)
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
agent
|
||||||
|
.save_vip(id, vip.config, Some(vip.revision), true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let zones = RosterZones::from_networks(&agent.status().await.unwrap().networks).zones;
|
||||||
|
assert_eq!(
|
||||||
|
zones.lookup("k8s.tsng", Query::A).unwrap().1,
|
||||||
|
Answer::NoSuchName
|
||||||
|
);
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn changing_the_exit_keeps_every_mesh_route_and_prefers_the_selected_source() {
|
||||||
|
let first = addr(2);
|
||||||
|
let second = addr(5);
|
||||||
|
let mut plan = VpnPlan {
|
||||||
|
addresses: vec![first, second],
|
||||||
|
mtu: 1280,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
plan.routes(),
|
||||||
|
["10.2.42.0/24", "10.5.42.0/24", "192.0.2.53/32"]
|
||||||
|
);
|
||||||
|
assert_eq!(plan.addresses_in_order(), [first, second]);
|
||||||
|
plan.full_tunnel = true;
|
||||||
|
plan.exit = Some(second.addr);
|
||||||
|
assert_eq!(plan.addresses_in_order(), [second, first]);
|
||||||
|
assert!(plan.routes().contains(&"0.0.0.0/0".into()));
|
||||||
|
assert!(plan.routes().contains(&"10.2.42.0/24".into()));
|
||||||
|
plan.full_tunnel = false;
|
||||||
|
plan.exit = None;
|
||||||
|
plan.addresses.remove(0);
|
||||||
|
assert_eq!(plan.routes(), ["10.5.42.0/24", "192.0.2.53/32"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broadcast_route_is_only_present_when_requested() {
|
||||||
|
let mut plan = VpnPlan {
|
||||||
|
addresses: vec![addr(1)],
|
||||||
|
mtu: 1280,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
plan.broadcast = true;
|
||||||
|
assert!(plan.routes().contains(&"255.255.255.255/32".into()));
|
||||||
|
plan.broadcast = false;
|
||||||
|
assert_eq!(plan.routes(), ["10.1.42.0/24", "192.0.2.53/32"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preference() {
|
||||||
|
use tsunagi::{Agent, testing};
|
||||||
|
use tsunagi_runtime::{Carriers, PROTOCOLS};
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let names = ["wg", "awg", "wg-quic", "tcp-tls"];
|
||||||
|
let (network, secret) = testing::network("carriers");
|
||||||
|
for restart in [false, true] {
|
||||||
|
let config = testing::local_config(dir.path());
|
||||||
|
let (config, carriers) = Carriers::configure(config, &[], None, |spec| {
|
||||||
|
if spec.name == "tcp-tls" {
|
||||||
|
vec![("port".into(), "0".into())]
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
config
|
||||||
|
.carriers
|
||||||
|
.iter()
|
||||||
|
.map(|c| c.protocol_id())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
names
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
config
|
||||||
|
.carriers
|
||||||
|
.iter()
|
||||||
|
.zip(PROTOCOLS)
|
||||||
|
.all(|(c, spec)| c.protocol_version() == spec.version)
|
||||||
|
);
|
||||||
|
let agent = Agent::spawn(config).await.unwrap();
|
||||||
|
let _listeners = carriers.listen(&agent);
|
||||||
|
let id = agent.join_network(&network, &secret).await.unwrap();
|
||||||
|
let saved = agent.network_status(id).await.unwrap().protocols;
|
||||||
|
if restart {
|
||||||
|
assert_eq!(saved, ["tcp-tls", "wg"]);
|
||||||
|
} else {
|
||||||
|
assert_eq!(saved, names);
|
||||||
|
agent
|
||||||
|
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (other, secret) = testing::network("other");
|
||||||
|
let second = agent.join_network(&other, &secret).await.unwrap();
|
||||||
|
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
|
||||||
|
}
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn commands_scope_vip_edits_and_leaving_to_the_selected_network() {
|
||||||
|
use crate::service::apply;
|
||||||
|
use tsunagi::vip::VipConfig;
|
||||||
|
use tsunagi::{Agent, NetworkName, NetworkSecret, testing};
|
||||||
|
use tsunagi_ui::client::Command;
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let agent = Agent::spawn(testing::local_config(dir.path()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let name = NetworkName::new("shared-name").unwrap();
|
||||||
|
let one = NetworkSecret::generate();
|
||||||
|
let two = NetworkSecret::generate();
|
||||||
|
for secret in [&one, &two] {
|
||||||
|
apply(
|
||||||
|
Command::Join {
|
||||||
|
name: name.to_string(),
|
||||||
|
secret: secret.encode(),
|
||||||
|
},
|
||||||
|
&agent,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let first = tsunagi::identity::NetworkKeys::derive(&name, &one)
|
||||||
|
.network_id()
|
||||||
|
.to_string();
|
||||||
|
let second = tsunagi::identity::NetworkKeys::derive(&name, &two).network_id();
|
||||||
|
let config = VipConfig::new("web");
|
||||||
|
let save = |expected, delete| Command::SaveVip {
|
||||||
|
token: "draft".into(),
|
||||||
|
network_id: first.clone(),
|
||||||
|
config: config.clone(),
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
};
|
||||||
|
apply(save(None, false), &agent).await.unwrap();
|
||||||
|
assert!(
|
||||||
|
apply(save(Some("stale".into()), true), &agent)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
agent
|
||||||
|
.network_status(first.parse().unwrap())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.vips
|
||||||
|
.len(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert!(agent.network_status(second).await.unwrap().vips.is_empty());
|
||||||
|
assert!(
|
||||||
|
apply(
|
||||||
|
Command::SetExitNode {
|
||||||
|
network_id: second.to_string(),
|
||||||
|
peer: Some(agent.endpoint_id().to_string())
|
||||||
|
},
|
||||||
|
&agent
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
apply(
|
||||||
|
Command::SetExitOffer {
|
||||||
|
network_id: second.to_string(),
|
||||||
|
enabled: true
|
||||||
|
},
|
||||||
|
&agent
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
apply(Command::Leave { network_id: first }, &agent)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let saved = agent.list_networks().await.unwrap();
|
||||||
|
assert_eq!(saved.len(), 1);
|
||||||
|
assert_eq!(saved[0].network_id, second);
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tun_reader_survives_address_changes_failed_establish_and_last_network_leaving() {
|
||||||
|
use std::io;
|
||||||
|
use std::os::{fd::OwnedFd, unix::net::UnixDatagram};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tsunagi::overlay::{TunFactory, TunRequest};
|
||||||
|
let sockets = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let peers = sockets.clone();
|
||||||
|
let factory = crate::tun::AndroidTun::new(
|
||||||
|
crate::dns::Resolver::new(|_| None),
|
||||||
|
move |plan| {
|
||||||
|
if plan.addresses.contains(&addr(9)) {
|
||||||
|
return Err(io::Error::other("permission revoked"));
|
||||||
|
}
|
||||||
|
let (dev, os) = UnixDatagram::pair()?;
|
||||||
|
dev.set_nonblocking(true)?;
|
||||||
|
peers.lock().unwrap().push(os);
|
||||||
|
Ok(OwnedFd::from(dev).into())
|
||||||
|
},
|
||||||
|
|_, _| Ok(()),
|
||||||
|
);
|
||||||
|
let mut req = TunRequest::bare("tsun0", 1280);
|
||||||
|
let dev = factory.create(req.clone()).await.unwrap();
|
||||||
|
let reader = tokio::spawn({
|
||||||
|
let dev = dev.clone();
|
||||||
|
async move { dev.recv().await.unwrap() }
|
||||||
|
});
|
||||||
|
req.addresses = vec![addr(2)];
|
||||||
|
factory.reconfigure(req.clone()).await.unwrap();
|
||||||
|
assert_eq!(factory.assigned_addresses(), [addr(2).addr]);
|
||||||
|
req.addresses.push(addr(9));
|
||||||
|
assert!(factory.reconfigure(req.clone()).await.is_err());
|
||||||
|
assert_eq!(factory.assigned_addresses(), [addr(2).addr]);
|
||||||
|
sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.last()
|
||||||
|
.unwrap()
|
||||||
|
.send(b"first")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
&tokio::time::timeout(std::time::Duration::from_secs(2), reader)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()[..],
|
||||||
|
b"first"
|
||||||
|
);
|
||||||
|
req.addresses.clear();
|
||||||
|
factory.reconfigure(req.clone()).await.unwrap();
|
||||||
|
assert!(
|
||||||
|
dev.send(bytes::Bytes::from_static(b"offline"))
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(factory.assigned_addresses().is_empty());
|
||||||
|
req.addresses = vec![addr(5)];
|
||||||
|
factory.reconfigure(req).await.unwrap();
|
||||||
|
sockets
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.last()
|
||||||
|
.unwrap()
|
||||||
|
.send(b"second")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(&dev.recv().await.unwrap()[..], b"second");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() {
|
||||||
|
use crate::{
|
||||||
|
service::{State, report},
|
||||||
|
view::{Phone, configure},
|
||||||
|
};
|
||||||
|
use egui::epaint::Shape;
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let agent = tsunagi::Agent::spawn(tsunagi::testing::local_config(dir.path()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (name, secret) = tsunagi::testing::network("layout");
|
||||||
|
agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
let mut sample = report(&agent, None, &crate::dns::Resolver::new(|_| None))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sample.networks[0].overlay = Some(tsunagi::ipc::OverlayReport {
|
||||||
|
address: Some("10.1.2.3".into()),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let state = State::Ready(Arc::new(sample), Instant::now());
|
||||||
|
let ctx = egui::Context::default();
|
||||||
|
configure(&ctx);
|
||||||
|
let mut phone = Phone::default();
|
||||||
|
let frame = ctx.run(
|
||||||
|
egui::RawInput {
|
||||||
|
screen_rect: Some(egui::Rect::from_min_size(
|
||||||
|
egui::Pos2::ZERO,
|
||||||
|
egui::vec2(360., 720.),
|
||||||
|
)),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
|ctx| {
|
||||||
|
phone.draw(ctx, &state, |_| {
|
||||||
|
panic!("drawing the overview issued a command")
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let y = |label: &str| {
|
||||||
|
frame
|
||||||
|
.shapes
|
||||||
|
.iter()
|
||||||
|
.find_map(|shape| match &shape.shape {
|
||||||
|
Shape::Text(text) if text.galley.text() == label => Some(text.pos.y),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| panic!("missing label {label}"))
|
||||||
|
};
|
||||||
|
assert!((0.0..=26.0).contains(&(y("host") - y("device"))));
|
||||||
|
assert!((0.0..=26.0).contains(&(y("range") - y("id"))));
|
||||||
|
assert!((0.0..=26.0).contains(&(y("peers") - y("addr"))));
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
|
||||||
|
use crate::service::State;
|
||||||
|
use crate::view::{Phone, configure};
|
||||||
|
use egui::{Event, PointerButton, Pos2, RawInput, Rect, Shape};
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
use tsunagi::{
|
||||||
|
ipc::{NetworkReport, StatusReport},
|
||||||
|
vip::{
|
||||||
|
Backend, BackendStatus, Counters, Listener, ListenerStatus, Protocol, VipConfig,
|
||||||
|
VipStatus,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let backend = Backend {
|
||||||
|
peer: "node".into(),
|
||||||
|
port: 8080,
|
||||||
|
};
|
||||||
|
let mut config = VipConfig::new("web");
|
||||||
|
let mut listener = Listener::new(Protocol::Tcp, 80);
|
||||||
|
listener.backends.push(backend.clone());
|
||||||
|
config.listeners.push(listener);
|
||||||
|
let network = NetworkReport {
|
||||||
|
active: true,
|
||||||
|
name: "lab".into(),
|
||||||
|
network_id: "network".into(),
|
||||||
|
vips: vec![VipStatus {
|
||||||
|
config,
|
||||||
|
address: None,
|
||||||
|
revision: "r1".into(),
|
||||||
|
error: None,
|
||||||
|
listeners: vec![ListenerStatus {
|
||||||
|
protocol: Protocol::Tcp,
|
||||||
|
port: 80,
|
||||||
|
selected: Some(backend.clone()),
|
||||||
|
counters: Counters::default(),
|
||||||
|
backends: vec![BackendStatus {
|
||||||
|
backend,
|
||||||
|
state: "ready".into(),
|
||||||
|
rtt_us: Some(1000),
|
||||||
|
measurement_age_ms: Some(1),
|
||||||
|
active_flows: 1,
|
||||||
|
counters: Counters::default(),
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let state = State::Ready(
|
||||||
|
Arc::new(StatusReport {
|
||||||
|
networks: vec![network],
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
Instant::now(),
|
||||||
|
);
|
||||||
|
let ctx = egui::Context::default();
|
||||||
|
configure(&ctx);
|
||||||
|
let mut phone = Phone::default();
|
||||||
|
let mut frame = |events| {
|
||||||
|
ctx.run(
|
||||||
|
RawInput {
|
||||||
|
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(360., 800.))),
|
||||||
|
events,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
|ctx| {
|
||||||
|
phone.draw(ctx, &state, |_| panic!("navigation wrote to the network"));
|
||||||
|
},
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let position = |output: &egui::FullOutput, label: &str| {
|
||||||
|
output
|
||||||
|
.shapes
|
||||||
|
.iter()
|
||||||
|
.find_map(|s| match &s.shape {
|
||||||
|
Shape::Text(t) if t.galley.text() == label => {
|
||||||
|
Some(t.pos + t.galley.rect.center().to_vec2())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| panic!("missing {label}"))
|
||||||
|
};
|
||||||
|
let mut click = |label: &str| {
|
||||||
|
frame(vec![]);
|
||||||
|
let p = position(&frame(vec![]), label);
|
||||||
|
for pressed in [true, false] {
|
||||||
|
frame(vec![
|
||||||
|
Event::PointerMoved(p),
|
||||||
|
Event::PointerButton {
|
||||||
|
pos: p,
|
||||||
|
button: PointerButton::Primary,
|
||||||
|
pressed,
|
||||||
|
modifiers: Default::default(),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
frame(vec![])
|
||||||
|
};
|
||||||
|
let live = click("VIP");
|
||||||
|
for label in ["Overview", "Configuration", "Next new flow", "node:8080"] {
|
||||||
|
let p = position(&live, label);
|
||||||
|
assert!(
|
||||||
|
(0.0..360.0).contains(&p.x),
|
||||||
|
"{label} is outside the portrait view"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let editor = click("Configuration");
|
||||||
|
for label in [
|
||||||
|
"Active TCP port checks",
|
||||||
|
"Checks and flow expiry",
|
||||||
|
"+ Backend",
|
||||||
|
"+ Listener",
|
||||||
|
] {
|
||||||
|
position(&editor, label);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
//! A stable packet device over the file descriptors replaced by VpnService.
|
||||||
|
use crate::dns::{Resolver, stack::DnsPort};
|
||||||
|
use crate::plan::VpnPlan;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use std::{
|
||||||
|
fmt,
|
||||||
|
fs::File,
|
||||||
|
io::{self, Read, Write},
|
||||||
|
sync::Arc,
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
io::unix::AsyncFd,
|
||||||
|
sync::{Mutex, watch},
|
||||||
|
};
|
||||||
|
use tsunagi::{
|
||||||
|
BoxFuture,
|
||||||
|
overlay::{
|
||||||
|
OverlayError, TunDevice, TunFactory, TunRequest,
|
||||||
|
hostrules::{
|
||||||
|
BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan,
|
||||||
|
ExitHostReport, ExitHostRules, RuleOutcome,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
type Establish = dyn Fn(&VpnPlan) -> io::Result<File> + Send + Sync;
|
||||||
|
type BindSocket =
|
||||||
|
dyn Fn(&tokio::net::TcpSocket, std::net::Ipv4Addr) -> io::Result<()> + Send + Sync;
|
||||||
|
struct Attachment {
|
||||||
|
device: Arc<AsyncFd<File>>,
|
||||||
|
addresses: Vec<std::net::IpAddr>,
|
||||||
|
dns: DnsPort,
|
||||||
|
}
|
||||||
|
type Descriptor = Option<Arc<Attachment>>;
|
||||||
|
|
||||||
|
/// The only OS call is supplied by the Android service. Tokio owns the detached fd.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AndroidTun(Arc<Inner>);
|
||||||
|
struct Inner {
|
||||||
|
establish: Box<Establish>,
|
||||||
|
bind: Box<BindSocket>,
|
||||||
|
resolver: Resolver,
|
||||||
|
plan: Mutex<VpnPlan>,
|
||||||
|
current: watch::Sender<Descriptor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for AndroidTun {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("AndroidTun")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl AndroidTun {
|
||||||
|
/// Attach a nonblocking device returned by Builder.establish().
|
||||||
|
pub fn new(
|
||||||
|
resolver: Resolver,
|
||||||
|
establish: impl Fn(&VpnPlan) -> io::Result<File> + Send + Sync + 'static,
|
||||||
|
bind: impl Fn(&tokio::net::TcpSocket, std::net::Ipv4Addr) -> io::Result<()>
|
||||||
|
+ Send
|
||||||
|
+ Sync
|
||||||
|
+ 'static,
|
||||||
|
) -> Self {
|
||||||
|
Self(Arc::new(Inner {
|
||||||
|
establish: Box::new(establish),
|
||||||
|
bind: Box::new(bind),
|
||||||
|
resolver,
|
||||||
|
plan: Mutex::default(),
|
||||||
|
current: watch::channel(None).0,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update(&self, edit: impl FnOnce(&mut VpnPlan)) -> Result<(), OverlayError> {
|
||||||
|
let mut applied = self.0.plan.lock().await;
|
||||||
|
let mut next = applied.clone();
|
||||||
|
edit(&mut next);
|
||||||
|
if *applied == next {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let dns_address = next.dns_address();
|
||||||
|
let fd = if next.addresses.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let address = dns_address.ok_or_else(|| OverlayError::Unavailable(
|
||||||
|
"Mesh ranges overlap every device-local DNS address. Choose a narrower mesh range.".into()
|
||||||
|
))?;
|
||||||
|
let file = (self.0.establish)(&next)
|
||||||
|
.and_then(AsyncFd::new)
|
||||||
|
.map(Arc::new)
|
||||||
|
.map_err(|err| OverlayError::Unavailable(err.to_string()))?;
|
||||||
|
let dns = DnsPort::start(
|
||||||
|
address,
|
||||||
|
next.mtu as usize,
|
||||||
|
self.0.resolver.clone(),
|
||||||
|
file.clone(),
|
||||||
|
);
|
||||||
|
Some(Arc::new(Attachment {
|
||||||
|
device: file,
|
||||||
|
addresses: next.addresses.iter().map(|a| a.addr).collect(),
|
||||||
|
dns,
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
self.0.current.send_replace(fd);
|
||||||
|
self.0.resolver.publish(dns_address);
|
||||||
|
*applied = next;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Device {
|
||||||
|
name: String,
|
||||||
|
mtu: u32,
|
||||||
|
tun: AndroidTun,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TunDevice for Device {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
fn mtu(&self) -> u32 {
|
||||||
|
self.mtu
|
||||||
|
}
|
||||||
|
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut rx = self.tun.0.current.subscribe();
|
||||||
|
let mut buffer = vec![0; self.mtu as usize + 1];
|
||||||
|
loop {
|
||||||
|
let fd = rx.borrow_and_update().clone();
|
||||||
|
if let Some(fd) = fd {
|
||||||
|
let result = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = rx.changed() => continue,
|
||||||
|
read = fd.device.async_io(tokio::io::Interest::READABLE, |mut file| file.read(&mut buffer)) => read,
|
||||||
|
};
|
||||||
|
if let Ok(len @ 1..) = result {
|
||||||
|
if fd.dns.intercept(&buffer[..len], &fd.addresses) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
buffer.truncate(len);
|
||||||
|
return Some(buffer.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No networks yet, last one left, or Android revoked this fd.
|
||||||
|
// A later establish wakes the same reader on the new device.
|
||||||
|
rx.changed().await.ok()?;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn send<'a>(&'a self, packet: Bytes) -> BoxFuture<'a, Result<(), OverlayError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut rx = self.tun.0.current.subscribe();
|
||||||
|
let fd = rx
|
||||||
|
.borrow_and_update()
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| OverlayError::Unavailable("VPN has no addresses".into()))?;
|
||||||
|
let len = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())),
|
||||||
|
write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) =>
|
||||||
|
write.map_err(|e| OverlayError::Other(e.to_string()))?,
|
||||||
|
};
|
||||||
|
if len != packet.len() {
|
||||||
|
return Err(OverlayError::Other("short VPN datagram write".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TunFactory for AndroidTun {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"Android VpnService"
|
||||||
|
}
|
||||||
|
fn bind_overlay_socket(
|
||||||
|
&self,
|
||||||
|
socket: &tokio::net::TcpSocket,
|
||||||
|
source: std::net::Ipv4Addr,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
(self.0.bind)(socket, source)?;
|
||||||
|
socket.bind((source, 0).into())
|
||||||
|
}
|
||||||
|
fn assigned_addresses(&self) -> Vec<std::net::IpAddr> {
|
||||||
|
self.0
|
||||||
|
.current
|
||||||
|
.borrow()
|
||||||
|
.as_ref()
|
||||||
|
.map(|fd| fd.addresses.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
fn on_host(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
fn create<'a>(
|
||||||
|
&'a self,
|
||||||
|
req: TunRequest,
|
||||||
|
) -> BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let dev = Device {
|
||||||
|
name: req.name.clone(),
|
||||||
|
mtu: req.mtu,
|
||||||
|
tun: self.clone(),
|
||||||
|
};
|
||||||
|
self.reconfigure(req).await?;
|
||||||
|
Ok(Arc::new(dev) as Arc<dyn TunDevice>)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn reconfigure<'a>(&'a self, req: TunRequest) -> BoxFuture<'a, Result<(), OverlayError>> {
|
||||||
|
Box::pin(self.update(move |plan| {
|
||||||
|
plan.addresses = req.addresses;
|
||||||
|
plan.mtu = req.mtu;
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
fn host_rules(&self) -> Option<Arc<dyn BroadcastHostRules>> {
|
||||||
|
Some(Arc::new(self.clone()))
|
||||||
|
}
|
||||||
|
fn destroy<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async {
|
||||||
|
let _ = self.update(|plan| *plan = VpnPlan::default()).await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outcome(result: Result<(), OverlayError>) -> RuleOutcome {
|
||||||
|
match result {
|
||||||
|
Ok(()) => RuleOutcome::Applied,
|
||||||
|
Err(error) => RuleOutcome::Failed(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl BroadcastHostRules for AndroidTun {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"Android VpnService"
|
||||||
|
}
|
||||||
|
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let route = outcome(self.update(|p| p.broadcast = true).await);
|
||||||
|
BroadcastRulesReport {
|
||||||
|
plan: plan.clone(),
|
||||||
|
route,
|
||||||
|
// Android delivers accepted traffic directly through the VPN fd.
|
||||||
|
firewall: RuleOutcome::Applied,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async {
|
||||||
|
let _ = self.update(|p| p.broadcast = false).await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl ExitHostRules for AndroidTun {
|
||||||
|
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let result = self
|
||||||
|
.update(|p| {
|
||||||
|
p.full_tunnel = plan.client;
|
||||||
|
p.exit = plan.client_source.map(Into::into);
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
ExitHostReport {
|
||||||
|
offer: plan
|
||||||
|
.offer
|
||||||
|
.iter()
|
||||||
|
.map(|range| {
|
||||||
|
(
|
||||||
|
*range,
|
||||||
|
RuleOutcome::Failed("Android supports exit clients only".into()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
forwarding: None,
|
||||||
|
client: plan.client.then(|| outcome(result)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
Box::pin(async {
|
||||||
|
let _ = self
|
||||||
|
.update(|p| {
|
||||||
|
p.full_tunnel = false;
|
||||||
|
p.exit = None;
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,361 @@
|
|||||||
|
//! Android supplies navigation and the VPN lifecycle to the shared egui forms.
|
||||||
|
use crate::service::{Outcome, Response, State};
|
||||||
|
use egui::{Color32, Context};
|
||||||
|
use egui_phosphor::regular as icon;
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use tsunagi_ui::{
|
||||||
|
about,
|
||||||
|
client::{Client, Command, Snapshot, VipSaveResult},
|
||||||
|
devices,
|
||||||
|
home::{self, UiState},
|
||||||
|
stats::{Traffic, Unit},
|
||||||
|
vip,
|
||||||
|
};
|
||||||
|
use zeroize::{Zeroize, Zeroizing};
|
||||||
|
|
||||||
|
const BAD: Color32 = Color32::from_rgb(0xd0, 0x4a, 0x3c);
|
||||||
|
|
||||||
|
#[derive(Default, PartialEq, Eq)]
|
||||||
|
enum Page {
|
||||||
|
#[default]
|
||||||
|
Home,
|
||||||
|
About,
|
||||||
|
Join,
|
||||||
|
Devices(String),
|
||||||
|
Vips(String),
|
||||||
|
Exit(String),
|
||||||
|
Leave(String),
|
||||||
|
}
|
||||||
|
impl Page {
|
||||||
|
fn network(&self) -> Option<&str> {
|
||||||
|
match self {
|
||||||
|
Self::Devices(id) | Self::Vips(id) | Self::Exit(id) | Self::Leave(id) => Some(id),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn title(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Home => "tsunagi",
|
||||||
|
Self::About => "About",
|
||||||
|
Self::Join => "Join a network",
|
||||||
|
Self::Devices(_) => "Devices",
|
||||||
|
Self::Vips(_) => "VIP",
|
||||||
|
Self::Exit(_) => "Exit node",
|
||||||
|
Self::Leave(_) => "Leave network",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Operations that require the Android activity.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum SystemAction {
|
||||||
|
/// Request VPN consent and start the foreground service.
|
||||||
|
Start,
|
||||||
|
/// Stop the service while preserving this identity and its networks.
|
||||||
|
Stop,
|
||||||
|
/// Read the clipboard after a user gesture.
|
||||||
|
PasteSecret,
|
||||||
|
/// Return to the previous Android activity.
|
||||||
|
Finish,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Actions {
|
||||||
|
command: RefCell<Option<Command>>,
|
||||||
|
busy: bool,
|
||||||
|
}
|
||||||
|
impl Client for Actions {
|
||||||
|
fn send(&self, cmd: Command) {
|
||||||
|
if !self.busy() {
|
||||||
|
self.command.replace(Some(cmd));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn busy(&self) -> bool {
|
||||||
|
self.busy || self.command.borrow().is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Pending {
|
||||||
|
result: Response,
|
||||||
|
vip: Option<String>,
|
||||||
|
go_home: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Presentation state of the single Android viewport.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Phone {
|
||||||
|
page: Page,
|
||||||
|
forms: UiState,
|
||||||
|
traffic: Traffic,
|
||||||
|
snapshot: Snapshot,
|
||||||
|
pending: Option<Pending>,
|
||||||
|
error: Option<String>,
|
||||||
|
clipboard: Option<Zeroizing<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep reads at tray density. Extra hit area is reserved for the navigation bar.
|
||||||
|
pub fn configure(ctx: &Context) {
|
||||||
|
ctx.set_fonts(tsunagi_ui::app_fonts());
|
||||||
|
ctx.style_mut(|style| {
|
||||||
|
style.spacing.interact_size.y = 19.0;
|
||||||
|
style.spacing.button_padding = egui::vec2(6.0, 3.0);
|
||||||
|
style.spacing.item_spacing = egui::vec2(6.0, 3.0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Phone {
|
||||||
|
fn home(&mut self) {
|
||||||
|
if let Page::Vips(id) = &self.page {
|
||||||
|
self.forms.vip_windows.remove(id);
|
||||||
|
}
|
||||||
|
self.forms.join.name.clear();
|
||||||
|
self.forms.join.secret.zeroize();
|
||||||
|
self.forms.exit_confirm = None;
|
||||||
|
self.forms.forget_confirm = None;
|
||||||
|
self.page = Page::Home;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// System Back and toolbar Back use the same draft and confirmation state.
|
||||||
|
pub fn back(&mut self) -> Option<SystemAction> {
|
||||||
|
if self.pending.is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if self.forms.exit_confirm.take().is_some() || self.forms.forget_confirm.take().is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if let Page::Vips(id) = &self.page
|
||||||
|
&& let Some(editor) = self.forms.vip_windows.get_mut(id)
|
||||||
|
&& editor.dirty()
|
||||||
|
{
|
||||||
|
editor.request_close();
|
||||||
|
} else if self.page == Page::Home {
|
||||||
|
return Some(SystemAction::Finish);
|
||||||
|
} else {
|
||||||
|
self.home();
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
/// Accept a user-initiated paste into the join form.
|
||||||
|
pub fn paste_secret(&mut self, value: String) {
|
||||||
|
if self.page == Page::Join {
|
||||||
|
self.forms.join.secret.zeroize();
|
||||||
|
self.forms.join.secret = Zeroizing::new(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Request password input with IME suggestions disabled.
|
||||||
|
pub fn secret_focused(&self, ctx: &Context) -> bool {
|
||||||
|
ctx.memory(|m| m.has_focus("join-secret".into()))
|
||||||
|
}
|
||||||
|
/// Present an error from an Android operation.
|
||||||
|
pub fn error(&mut self, message: String) {
|
||||||
|
self.error = Some(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Take a secret once for the platform’s sensitive clipboard.
|
||||||
|
pub fn take_copied_secret(&mut self) -> Option<Zeroizing<String>> {
|
||||||
|
self.clipboard.take()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn acknowledge(&mut self) {
|
||||||
|
let Some(pending) = &mut self.pending else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let outcome = match pending.result.try_recv() {
|
||||||
|
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return,
|
||||||
|
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
|
||||||
|
Err("VPN service stopped".to_owned())
|
||||||
|
}
|
||||||
|
Ok(v) => v,
|
||||||
|
};
|
||||||
|
if let Some(token) = pending.vip.take() {
|
||||||
|
let result = outcome.and_then(|r| match r {
|
||||||
|
Outcome::Saved(vips) => Ok(vips),
|
||||||
|
_ => Err("Missing VIP save acknowledgement".into()),
|
||||||
|
});
|
||||||
|
self.snapshot.vip_result = Some(VipSaveResult { token, result });
|
||||||
|
} else {
|
||||||
|
match outcome {
|
||||||
|
Ok(Outcome::Clipboard(text)) => self.clipboard = Some(text),
|
||||||
|
Ok(_) if pending.go_home => self.home(),
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) => self.error = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.pending = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render a tray view in this viewport and send gestures to the service.
|
||||||
|
pub fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &Context,
|
||||||
|
state: &State,
|
||||||
|
mut submit: impl FnMut(Command) -> Result<Response, String>,
|
||||||
|
) -> Option<SystemAction> {
|
||||||
|
self.acknowledge();
|
||||||
|
let report = if let State::Ready(report, at) = state {
|
||||||
|
if self.snapshot.at != Some(*at) {
|
||||||
|
self.snapshot.generation = self.snapshot.generation.wrapping_add(1);
|
||||||
|
self.snapshot.at = Some(*at);
|
||||||
|
self.snapshot.status = Some(Ok(report.clone()));
|
||||||
|
self.traffic.observe(report, *at);
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.page
|
||||||
|
.network()
|
||||||
|
.is_some_and(|id| !report.networks.iter().any(|n| n.network_id == id))
|
||||||
|
{
|
||||||
|
self.home();
|
||||||
|
}
|
||||||
|
Some(report)
|
||||||
|
} else {
|
||||||
|
if self.page.network().is_some() || self.page == Page::Join {
|
||||||
|
self.home();
|
||||||
|
}
|
||||||
|
self.snapshot = Snapshot::default();
|
||||||
|
self.traffic = Traffic::default();
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let actions = Actions {
|
||||||
|
command: RefCell::default(),
|
||||||
|
busy: self.pending.is_some(),
|
||||||
|
};
|
||||||
|
let mut system = None;
|
||||||
|
egui::TopBottomPanel::top("navigation").show(ctx, |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.spacing_mut().interact_size.y = 32.0;
|
||||||
|
if self.page != Page::Home && ui.button(icon::ARROW_LEFT).clicked() {
|
||||||
|
system = self.back();
|
||||||
|
}
|
||||||
|
ui.heading(self.page.title());
|
||||||
|
if self.page == Page::Home {
|
||||||
|
ui.weak(env!("CARGO_PKG_VERSION"));
|
||||||
|
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||||
|
if ui.button(icon::INFO).clicked() {
|
||||||
|
self.page = Page::About;
|
||||||
|
}
|
||||||
|
if report.is_some() {
|
||||||
|
ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes");
|
||||||
|
ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if self.page == Page::About
|
||||||
|
&& !matches!(state, State::Off)
|
||||||
|
&& ui.button("Stop VPN").clicked()
|
||||||
|
{
|
||||||
|
system = Some(SystemAction::Stop);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let Some(error) = &self.error {
|
||||||
|
ui.colored_label(BAD, error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let selected = self
|
||||||
|
.page
|
||||||
|
.network()
|
||||||
|
.and_then(|id| report?.networks.iter().find(|n| n.network_id == id));
|
||||||
|
match (&self.page, selected) {
|
||||||
|
(Page::About, _) => about::show(ctx, None, &self.snapshot),
|
||||||
|
(Page::Vips(id), Some(network)) => {
|
||||||
|
let editor = self.forms.vip_windows.entry(id.clone()).or_default();
|
||||||
|
if vip::show(ctx, &actions, editor, network, &self.snapshot) {
|
||||||
|
self.home();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Page::Devices(_), Some(network)) => {
|
||||||
|
if let Some(report) = report {
|
||||||
|
devices::show(
|
||||||
|
ctx,
|
||||||
|
&actions,
|
||||||
|
&mut self.forms.unit,
|
||||||
|
(&mut self.forms.exit_confirm, &mut self.forms.forget_confirm),
|
||||||
|
network,
|
||||||
|
&report.endpoint_id,
|
||||||
|
&self.traffic,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
egui::CentralPanel::default().show(ctx, |ui| {
|
||||||
|
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||||
|
let Some(report) = report else {
|
||||||
|
match state {
|
||||||
|
State::Starting => {ui.spinner(); ui.label("Starting VPN…");}
|
||||||
|
_ => {
|
||||||
|
if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("VPN is stopped");}
|
||||||
|
if ui.button("Start VPN").clicked() {system = Some(SystemAction::Start);}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match &self.page {
|
||||||
|
Page::Home => {
|
||||||
|
home::draw_header(ui, &actions, &mut self.forms, report);
|
||||||
|
ui.separator();
|
||||||
|
if ui.button("Join or create a network").clicked() {self.page = Page::Join;}
|
||||||
|
for n in &report.networks {
|
||||||
|
if home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false) {self.page = Page::Exit(n.network_id.clone());}
|
||||||
|
if self.forms.open_devices.remove(&n.network_id) {self.page = Page::Devices(n.network_id.clone());}
|
||||||
|
if self.forms.vip_windows.contains_key(&n.network_id) {self.page = Page::Vips(n.network_id.clone());}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Page::Join => {
|
||||||
|
home::draw_join(ui, &actions, &mut self.forms.join);
|
||||||
|
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
|
||||||
|
}
|
||||||
|
Page::Exit(_) => {
|
||||||
|
if let Some(n) = selected && let Some(choice) = devices::choose_exit(ui, n, &report.endpoint_id) {
|
||||||
|
self.forms.exit_confirm = Some(choice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Page::Leave(id) => {
|
||||||
|
if let Some(n) = selected {
|
||||||
|
ui.label(format!("Leave {} on this phone? You will need its secret to join again.", n.name));
|
||||||
|
if ui.button("Leave network").clicked() {actions.send(Command::Leave {network_id: id.clone()});}
|
||||||
|
if ui.button("Cancel").clicked() {self.home();}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(command) = actions.command.into_inner() {
|
||||||
|
self.error = None;
|
||||||
|
if let Command::Leave { network_id } = &command
|
||||||
|
&& !matches!(self.page, Page::Leave(_))
|
||||||
|
{
|
||||||
|
self.page = Page::Leave(network_id.clone());
|
||||||
|
} else {
|
||||||
|
let token = match &command {
|
||||||
|
Command::SaveVip { token, .. } => Some(token.clone()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let go_home = matches!(
|
||||||
|
command,
|
||||||
|
Command::Join { .. } | Command::Leave { .. } | Command::SetExitNode { .. }
|
||||||
|
);
|
||||||
|
match submit(command) {
|
||||||
|
Ok(result) => {
|
||||||
|
self.pending = Some(Pending {
|
||||||
|
result,
|
||||||
|
vip: token,
|
||||||
|
go_home,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
if let Some(token) = token {
|
||||||
|
self.snapshot.vip_result = Some(VipSaveResult {
|
||||||
|
token,
|
||||||
|
result: Err(error),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
self.error = Some(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
system
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-awg"
|
name = "tsunagi-awg"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -8,23 +8,17 @@ license = "WTFPL AND Apache-2.0"
|
|||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tsunagi-core = { path = "../tsunagi-core" }
|
|
||||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
|
||||||
tsunagi-wireguard = { path = "../tsunagi-wireguard" }
|
tsunagi-wireguard = { path = "../tsunagi-wireguard" }
|
||||||
iroh.workspace = true
|
|
||||||
tokio = { workspace = true, features = ["net", "time", "sync", "macros"] }
|
|
||||||
serde.workspace = true
|
|
||||||
postcard.workspace = true
|
|
||||||
bytes.workspace = true
|
|
||||||
tracing.workspace = true
|
|
||||||
rand = "0.10"
|
|
||||||
zeroize = { version = "1.9", features = ["derive"] }
|
|
||||||
boringtun = { version = "0.7.1", default-features = false }
|
|
||||||
chacha20 = "0.9"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||||
|
iroh.workspace = true
|
||||||
|
tokio = { workspace = true, features = ["net", "time", "sync", "macros"] }
|
||||||
|
bytes.workspace = true
|
||||||
|
rand = "0.10"
|
||||||
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
||||||
tempfile.workspace = true
|
tempfile.workspace = true
|
||||||
|
smoltcp = { version = "0.12", default-features = false, features = ["std", "medium-ip", "proto-ipv4", "socket-tcp"] }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
# Amnezia packet engine
|
# Amnezia packet engine
|
||||||
|
|
||||||
`src/masking.rs` is adapted from `src/core/amnezia.rs` in
|
`../tsunagi-wireguard/src/masking.rs` is adapted from `src/core/amnezia.rs` in
|
||||||
https://github.com/RunaRoo/AmneziaWG-RS at
|
https://github.com/RunaRoo/AmneziaWG-RS at
|
||||||
`51579a7d6e8882d1d8d6d00822f09e18a9423b73`, under Apache-2.0.
|
`51579a7d6e8882d1d8d6d00822f09e18a9423b73`, under Apache-2.0.
|
||||||
The upstream license is retained in `LICENSE-AmneziaWG-RS`.
|
The upstream license is retained in both packages as `LICENSE-AmneziaWG-RS`.
|
||||||
|
|
||||||
The adaptation replaces configuration-file loading with bounded typed pair
|
The adaptation replaces configuration-file loading with bounded typed pair
|
||||||
profiles, updates RNG calls to rand 0.10, removes an unnecessary unwrap, and
|
profiles, updates RNG calls to rand 0.10, removes an unnecessary unwrap, and
|
||||||
@@ -11,7 +11,7 @@ does not embed upstream's Node, global executors, OS interface operations or
|
|||||||
detached tasks. Noise/WireGuard is supplied by boringtun, already used by
|
detached tasks. Noise/WireGuard is supplied by boringtun, already used by
|
||||||
Tsunagi. Each pair owns one socket and one cancellable packet-engine task.
|
Tsunagi. Each pair owns one socket and one cancellable packet-engine task.
|
||||||
|
|
||||||
This is Tsunagi AWG wire version 1, not a claim of compatibility with external
|
This is Tsunagi AWG wire version 2, not a claim of compatibility with external
|
||||||
Amnezia servers. The masking engine substitutes message headers outside the
|
Amnezia servers. The masking engine substitutes message headers outside the
|
||||||
standard WireGuard state machine and restores them before Noise validation.
|
standard WireGuard state machine and restores them before Noise validation.
|
||||||
There are no remote file paths, shell hooks, or persisted pair profiles.
|
There are no remote file paths, shell hooks, or persisted pair profiles.
|
||||||
|
|||||||
@@ -1,16 +1,5 @@
|
|||||||
//! Pairwise, ephemeral Amnezia packet transport with independent end-to-end tunnels.
|
//! Amnezia-masked UDP carrier using the independent per-neighbour WireGuard engine.
|
||||||
//! All negotiation travels over authenticated Tsunagi control sessions.
|
pub use tsunagi_wireguard::{
|
||||||
mod masking;
|
AWG_PROTOCOL, AWG_WIRE_VERSION, PairOverview, UdpCarrier as AwgPlugin,
|
||||||
mod plugin;
|
UdpTransport as AwgTransport, profile,
|
||||||
pub mod profile;
|
};
|
||||||
mod session;
|
|
||||||
mod stun;
|
|
||||||
mod transport;
|
|
||||||
|
|
||||||
pub use plugin::AwgPlugin;
|
|
||||||
pub use transport::{AwgTransport, PairOverview};
|
|
||||||
|
|
||||||
/// Protocol identifier and default second-choice direct transport.
|
|
||||||
pub const AWG_PROTOCOL: &str = "awg";
|
|
||||||
/// Tsunagi AWG wire version, independent of software releases.
|
|
||||||
pub const AWG_WIRE_VERSION: u16 = 1;
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
//! End-to-end encryption remains independent of physical Amnezia pair links.
|
|
||||||
use crate::{AWG_PROTOCOL, AWG_WIRE_VERSION, AwgTransport};
|
|
||||||
use iroh::EndpointId;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use tsunagi::dataplane::transport::SharedLink;
|
|
||||||
use tsunagi::dataplane::{IpPlugin, PluginCapability, PluginContext, PluginError, ProtocolOption};
|
|
||||||
use tsunagi::state::Ipv4Range;
|
|
||||||
use tsunagi::{BoxFuture, NetworkId};
|
|
||||||
use tsunagi_wg_quic::{NetworkOverview, WireguardConfig, WireguardPlugin};
|
|
||||||
|
|
||||||
/// AWG capability and an independent end-to-end WireGuard engine.
|
|
||||||
/// Pair transport keys/profiles never enter its durable end-to-end key store.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct AwgPlugin {
|
|
||||||
inner: Arc<WireguardPlugin>,
|
|
||||||
transport: Arc<AwgTransport>,
|
|
||||||
}
|
|
||||||
impl AwgPlugin {
|
|
||||||
/// Uses standard tunnel MTU/keepalive options; pair ports and profiles are ephemeral.
|
|
||||||
pub const OPTIONS: &'static [ProtocolOption] = &[
|
|
||||||
ProtocolOption {
|
|
||||||
key: "keepalive",
|
|
||||||
value: "SECONDS",
|
|
||||||
help: "end-to-end tunnel keepalive; 0 disables it",
|
|
||||||
default: Some("25"),
|
|
||||||
},
|
|
||||||
ProtocolOption {
|
|
||||||
key: "mtu",
|
|
||||||
value: "BYTES",
|
|
||||||
help: "maximum overlay packet size",
|
|
||||||
default: Some("1280"),
|
|
||||||
},
|
|
||||||
ProtocolOption {
|
|
||||||
key: "stun",
|
|
||||||
value: "HOST:PORT|off",
|
|
||||||
help: "UDP public mapping discovery; disabled in local reach mode",
|
|
||||||
default: Some("stun.l.google.com:19302"),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
/// Opens the end-to-end engine, retaining separate pair transport state.
|
|
||||||
pub async fn open(
|
|
||||||
mut config: WireguardConfig,
|
|
||||||
transport: Arc<AwgTransport>,
|
|
||||||
) -> Result<Arc<Self>, PluginError> {
|
|
||||||
config.protocol = AWG_PROTOCOL;
|
|
||||||
Ok(Arc::new(Self {
|
|
||||||
inner: WireguardPlugin::open(config).await?,
|
|
||||||
transport,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
/// Reports end-to-end tunnel health and traffic counters.
|
|
||||||
pub fn overview(&self, network: NetworkId) -> Option<NetworkOverview> {
|
|
||||||
self.inner.overview(network)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl IpPlugin for AwgPlugin {
|
|
||||||
fn protocol_id(&self) -> &str {
|
|
||||||
AWG_PROTOCOL
|
|
||||||
}
|
|
||||||
fn protocol_version(&self) -> u16 {
|
|
||||||
AWG_WIRE_VERSION
|
|
||||||
}
|
|
||||||
fn options(&self) -> &'static [ProtocolOption] {
|
|
||||||
Self::OPTIONS
|
|
||||||
}
|
|
||||||
fn attach(&self, context: PluginContext) {
|
|
||||||
self.inner.attach(context);
|
|
||||||
}
|
|
||||||
fn local_capability(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
) -> Result<Option<PluginCapability>, PluginError> {
|
|
||||||
self.inner.local_capability(network).map(|cap| {
|
|
||||||
cap.map(|mut cap| {
|
|
||||||
cap.protocol = AWG_PROTOCOL.into();
|
|
||||||
cap.version = AWG_WIRE_VERSION;
|
|
||||||
cap
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
fn on_network_activated(&self, network: NetworkId) {
|
|
||||||
self.inner.on_network_activated(network);
|
|
||||||
}
|
|
||||||
fn on_peer_capability(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
capability: &PluginCapability,
|
|
||||||
) -> Result<(), PluginError> {
|
|
||||||
if capability.protocol != AWG_PROTOCOL
|
|
||||||
|| capability.version != AWG_WIRE_VERSION
|
|
||||||
|| !capability.enabled
|
|
||||||
{
|
|
||||||
return Err(PluginError::Rejected("unsupported AWG capability".into()));
|
|
||||||
}
|
|
||||||
self.inner.on_peer_capability(network, peer, capability)?;
|
|
||||||
self.transport.allow_peer(network, peer);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn on_address_allocation(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
range: Ipv4Range,
|
|
||||||
allocations: &[(EndpointId, std::net::Ipv4Addr)],
|
|
||||||
) {
|
|
||||||
self.inner
|
|
||||||
.on_address_allocation(network, range, allocations);
|
|
||||||
}
|
|
||||||
fn carry(&self, network: NetworkId, peer: EndpointId, packet: bytes::Bytes) -> bool {
|
|
||||||
self.inner.carry(network, peer, packet)
|
|
||||||
}
|
|
||||||
fn on_peer_link(&self, network: NetworkId, peer: EndpointId, link: SharedLink) {
|
|
||||||
self.inner.on_peer_link(network, peer, link);
|
|
||||||
}
|
|
||||||
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) {
|
|
||||||
self.transport.forget_peer(network, peer);
|
|
||||||
self.inner.on_peer_gone(network, peer);
|
|
||||||
}
|
|
||||||
fn on_network_deactivated(&self, network: NetworkId) {
|
|
||||||
self.transport.stop_network(network);
|
|
||||||
self.inner.on_network_deactivated(network);
|
|
||||||
}
|
|
||||||
fn on_network_forgotten(&self, network: NetworkId) {
|
|
||||||
self.inner.on_network_forgotten(network);
|
|
||||||
}
|
|
||||||
fn shutdown(&self) -> BoxFuture<'_, ()> {
|
|
||||||
Box::pin(async move {
|
|
||||||
self.transport.shutdown();
|
|
||||||
self.inner.shutdown().await;
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,720 +0,0 @@
|
|||||||
//! Private pair negotiation. No secret profiles in capabilities or durable state.
|
|
||||||
use crate::{
|
|
||||||
AWG_PROTOCOL, AWG_WIRE_VERSION,
|
|
||||||
profile::PairProfile,
|
|
||||||
session::{self, PairLink},
|
|
||||||
};
|
|
||||||
use boringtun::{
|
|
||||||
noise::Tunn,
|
|
||||||
x25519::{PublicKey, StaticSecret},
|
|
||||||
};
|
|
||||||
use iroh::EndpointId;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
use std::net::{Ipv4Addr, SocketAddr};
|
|
||||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
|
||||||
use std::time::Duration;
|
|
||||||
use tokio::net::UdpSocket;
|
|
||||||
use tokio::sync::{mpsc, oneshot, watch};
|
|
||||||
use tsunagi::dataplane::transport::TransportPayload;
|
|
||||||
use tsunagi::dataplane::transport::{
|
|
||||||
ControlSender, InboundLink, PacketLink, PacketTransport, SharedLink, TransportError,
|
|
||||||
};
|
|
||||||
use tsunagi::{BoxFuture, NetworkId};
|
|
||||||
|
|
||||||
type Pair = (NetworkId, EndpointId);
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Negotiation {
|
|
||||||
Offer {
|
|
||||||
version: u16,
|
|
||||||
profile: PairProfile,
|
|
||||||
key: [u8; 32],
|
|
||||||
#[serde(deserialize_with = "bounded_addresses")]
|
|
||||||
addresses: Vec<SocketAddr>,
|
|
||||||
},
|
|
||||||
Answer {
|
|
||||||
attempt: [u8; 16],
|
|
||||||
key: [u8; 32],
|
|
||||||
#[serde(deserialize_with = "bounded_addresses")]
|
|
||||||
addresses: Vec<SocketAddr>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
fn bounded_addresses<'de, D: serde::Deserializer<'de>>(
|
|
||||||
deserializer: D,
|
|
||||||
) -> Result<Vec<SocketAddr>, D::Error> {
|
|
||||||
struct Visitor;
|
|
||||||
impl<'de> serde::de::Visitor<'de> for Visitor {
|
|
||||||
type Value = Vec<SocketAddr>;
|
|
||||||
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.write_str("at most 32 UDP candidates")
|
|
||||||
}
|
|
||||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(
|
|
||||||
self,
|
|
||||||
mut sequence: A,
|
|
||||||
) -> Result<Self::Value, A::Error> {
|
|
||||||
if sequence.size_hint().is_some_and(|n| n > 32) {
|
|
||||||
return Err(serde::de::Error::custom("too many UDP candidates"));
|
|
||||||
}
|
|
||||||
let mut addresses = Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(32));
|
|
||||||
while let Some(address) = sequence.next_element()? {
|
|
||||||
if addresses.len() == 32 {
|
|
||||||
return Err(serde::de::Error::custom("too many UDP candidates"));
|
|
||||||
}
|
|
||||||
addresses.push(address);
|
|
||||||
}
|
|
||||||
Ok(addresses)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
deserializer.deserialize_seq(Visitor)
|
|
||||||
}
|
|
||||||
struct Pending {
|
|
||||||
profile: PairProfile,
|
|
||||||
key: StaticSecret,
|
|
||||||
socket: UdpSocket,
|
|
||||||
reply: oneshot::Sender<Result<SharedLink, TransportError>>,
|
|
||||||
}
|
|
||||||
struct Inner {
|
|
||||||
stopped: watch::Sender<bool>,
|
|
||||||
local: EndpointId,
|
|
||||||
bind: Ipv4Addr,
|
|
||||||
stun: Option<String>,
|
|
||||||
busy: Mutex<HashSet<Pair>>,
|
|
||||||
control: OnceLock<Arc<dyn ControlSender>>,
|
|
||||||
allowed: Mutex<HashSet<Pair>>,
|
|
||||||
pending: Mutex<HashMap<Pair, Pending>>,
|
|
||||||
links: Mutex<HashMap<Pair, Arc<PairLink>>>,
|
|
||||||
inbound: mpsc::Sender<InboundLink>,
|
|
||||||
port_by_pair: Mutex<HashMap<Pair, u16>>,
|
|
||||||
}
|
|
||||||
/// Public diagnostics for one pair. No key or masking parameters are exposed.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct PairOverview {
|
|
||||||
/// Other endpoint's authenticated identity.
|
|
||||||
pub peer: EndpointId,
|
|
||||||
/// Fresh connection-attempt identifier.
|
|
||||||
pub attempt: [u8; 16],
|
|
||||||
/// Last known UDP port; None if diagnostics race with pair retirement.
|
|
||||||
pub local_port: Option<u16>,
|
|
||||||
/// Actual transport path, if established.
|
|
||||||
pub path: String,
|
|
||||||
/// Whether this attempt has been retired.
|
|
||||||
pub closed: bool,
|
|
||||||
}
|
|
||||||
/// A bounded set of independently configured pair engines.
|
|
||||||
pub struct AwgTransport {
|
|
||||||
inner: Arc<Inner>,
|
|
||||||
commands: mpsc::Sender<(NetworkId, EndpointId, Negotiation)>,
|
|
||||||
incoming: tokio::sync::Mutex<mpsc::Receiver<InboundLink>>,
|
|
||||||
}
|
|
||||||
impl std::fmt::Debug for AwgTransport {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.debug_struct("AwgTransport")
|
|
||||||
.field("local", &self.inner.local)
|
|
||||||
.finish_non_exhaustive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
|
||||||
match mutex.lock() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn error(text: &str) -> TransportError {
|
|
||||||
TransportError::Other(text.into())
|
|
||||||
}
|
|
||||||
async fn addresses(inner: &Inner, socket: &UdpSocket) -> Result<Vec<SocketAddr>, TransportError> {
|
|
||||||
let local = socket
|
|
||||||
.local_addr()
|
|
||||||
.map_err(|_| error("AWG socket address unavailable"))?;
|
|
||||||
let mut candidates = if inner.bind.is_loopback() {
|
|
||||||
vec![local]
|
|
||||||
} else {
|
|
||||||
tsunagi_wireguard::local_ip_candidates()
|
|
||||||
.into_iter()
|
|
||||||
.filter(|ip| ip.is_ipv4())
|
|
||||||
.take(31)
|
|
||||||
.map(|ip| SocketAddr::new(ip, local.port()))
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
if let Some(server) = &inner.stun
|
|
||||||
&& let Some(mapped) = crate::stun::mapped(socket, server).await
|
|
||||||
&& !candidates.contains(&mapped)
|
|
||||||
{
|
|
||||||
candidates.push(mapped);
|
|
||||||
}
|
|
||||||
if candidates.is_empty() {
|
|
||||||
return Err(error("AWG has no UDP address candidates"));
|
|
||||||
}
|
|
||||||
Ok(candidates)
|
|
||||||
}
|
|
||||||
fn validate_endpoint(key: &[u8; 32], addresses: &[SocketAddr]) -> Result<(), TransportError> {
|
|
||||||
if *key == [0; 32]
|
|
||||||
|| addresses.is_empty()
|
|
||||||
|| addresses.len() > 32
|
|
||||||
|| addresses.iter().any(|address| {
|
|
||||||
address.port() == 0
|
|
||||||
|| !address.is_ipv4()
|
|
||||||
|| address.ip().is_unspecified()
|
|
||||||
|| address.ip().is_multicast()
|
|
||||||
|| matches!(address.ip(), std::net::IpAddr::V4(ip) if ip.is_broadcast())
|
|
||||||
})
|
|
||||||
{
|
|
||||||
return Err(error("invalid AWG endpoint"));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AwgTransport {
|
|
||||||
/// Starts the coordinator. Production binds wildcard IPv4; tests use loopback.
|
|
||||||
pub fn new(local: EndpointId, bind: Ipv4Addr) -> Arc<Self> {
|
|
||||||
Self::new_with_stun(local, bind, None)
|
|
||||||
}
|
|
||||||
/// Enables an optional STUN server (host:port) for this pair's own socket.
|
|
||||||
/// Local-only callers pass None; failure still permits local UDP candidates.
|
|
||||||
pub fn new_with_stun(local: EndpointId, bind: Ipv4Addr, stun: Option<String>) -> Arc<Self> {
|
|
||||||
let (commands, mut rx) = mpsc::channel(64);
|
|
||||||
let (inbound, incoming) = mpsc::channel(64);
|
|
||||||
let (stopped, _) = watch::channel(false);
|
|
||||||
let inner = Arc::new(Inner {
|
|
||||||
stopped,
|
|
||||||
local,
|
|
||||||
bind,
|
|
||||||
stun,
|
|
||||||
busy: Mutex::default(),
|
|
||||||
control: OnceLock::new(),
|
|
||||||
allowed: Mutex::default(),
|
|
||||||
pending: Mutex::default(),
|
|
||||||
links: Mutex::default(),
|
|
||||||
inbound,
|
|
||||||
port_by_pair: Mutex::default(),
|
|
||||||
});
|
|
||||||
let weak = Arc::downgrade(&inner);
|
|
||||||
let mut stopped = inner.stopped.subscribe();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
while let Some((network, peer, message)) =
|
|
||||||
tokio::select! { biased; _=stopped.changed()=>None, message=rx.recv()=>message }
|
|
||||||
{
|
|
||||||
let Some(inner) = weak.upgrade() else {
|
|
||||||
break;
|
|
||||||
};
|
|
||||||
if !lock(&inner.allowed).contains(&(network, peer))
|
|
||||||
|| !lock(&inner.busy).insert((network, peer))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut stop = inner.stopped.subscribe();
|
|
||||||
tokio::select! {biased; _=stop.changed()=>{}, _=async {
|
|
||||||
if let Err(err)=receive(&inner,(network,peer),message).await {tracing::debug!(%err,"AWG pair negotiation rejected");}
|
|
||||||
}=>{}}
|
|
||||||
lock(&inner.busy).remove(&(network, peer));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Arc::new(Self {
|
|
||||||
inner,
|
|
||||||
commands,
|
|
||||||
incoming: tokio::sync::Mutex::new(incoming),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
/// Registers a peer after its authenticated capability has been validated.
|
|
||||||
pub fn allow_peer(&self, network: NetworkId, peer: EndpointId) {
|
|
||||||
let mut allowed = lock(&self.inner.allowed);
|
|
||||||
if !*self.inner.stopped.borrow() && allowed.len() < 128 {
|
|
||||||
allowed.insert((network, peer));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// Retires a pair when its network membership session goes away.
|
|
||||||
pub fn forget_peer(&self, network: NetworkId, peer: EndpointId) {
|
|
||||||
let pair = (network, peer);
|
|
||||||
lock(&self.inner.allowed).remove(&pair);
|
|
||||||
lock(&self.inner.pending).remove(&pair);
|
|
||||||
lock(&self.inner.port_by_pair).remove(&pair);
|
|
||||||
if let Some(link) = lock(&self.inner.links).remove(&pair) {
|
|
||||||
link.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// Stops all pair engines in this network.
|
|
||||||
pub fn stop_network(&self, network: NetworkId) {
|
|
||||||
let peers: Vec<_> = lock(&self.inner.allowed)
|
|
||||||
.iter()
|
|
||||||
.filter(|(n, _)| *n == network)
|
|
||||||
.map(|(_, p)| *p)
|
|
||||||
.collect();
|
|
||||||
for peer in peers {
|
|
||||||
self.forget_peer(network, peer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// Stops all sockets and coordinator work without waiting for remote peers.
|
|
||||||
pub fn shutdown(&self) {
|
|
||||||
self.inner.stopped.send_replace(true);
|
|
||||||
lock(&self.inner.allowed).clear();
|
|
||||||
lock(&self.inner.pending).clear();
|
|
||||||
for (_, link) in lock(&self.inner.links).drain() {
|
|
||||||
link.close();
|
|
||||||
}
|
|
||||||
lock(&self.inner.port_by_pair).clear();
|
|
||||||
}
|
|
||||||
/// Receives a successfully negotiated and authenticated inbound pair link.
|
|
||||||
pub async fn next_inbound(&self) -> Option<InboundLink> {
|
|
||||||
let mut stopped = self.inner.stopped.subscribe();
|
|
||||||
if *stopped.borrow() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let mut incoming = self.incoming.lock().await;
|
|
||||||
tokio::select! {biased; _=stopped.changed()=>None, link=incoming.recv()=>link}
|
|
||||||
}
|
|
||||||
/// Takes a public snapshot of this network's pair attempts.
|
|
||||||
pub fn overview(&self, network: NetworkId) -> Vec<PairOverview> {
|
|
||||||
let links = lock(&self.inner.links);
|
|
||||||
let ports = lock(&self.inner.port_by_pair);
|
|
||||||
links
|
|
||||||
.iter()
|
|
||||||
.filter(|((n, _), _)| *n == network)
|
|
||||||
.map(|((_, peer), link)| PairOverview {
|
|
||||||
peer: *peer,
|
|
||||||
attempt: link.attempt,
|
|
||||||
local_port: ports.get(&(network, *peer)).copied(),
|
|
||||||
path: link.path_description(),
|
|
||||||
closed: link.is_closed(),
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl PacketTransport for AwgTransport {
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
AWG_PROTOCOL
|
|
||||||
}
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
fn attach_control(&self, control: Arc<dyn ControlSender>) {
|
|
||||||
let _ = self.inner.control.set(control);
|
|
||||||
}
|
|
||||||
fn on_control(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
protocol: &str,
|
|
||||||
payload: &[u8],
|
|
||||||
) -> Result<(), TransportError> {
|
|
||||||
if protocol != AWG_PROTOCOL || !lock(&self.inner.allowed).contains(&(network, peer)) {
|
|
||||||
return Err(TransportError::Declined(protocol.into()));
|
|
||||||
}
|
|
||||||
if payload.len() > 4096 {
|
|
||||||
return Err(error("AWG negotiation too large"));
|
|
||||||
}
|
|
||||||
let message: Negotiation =
|
|
||||||
postcard::from_bytes(payload).map_err(|_| error("malformed AWG negotiation"))?;
|
|
||||||
match &message {
|
|
||||||
Negotiation::Offer {
|
|
||||||
version,
|
|
||||||
profile,
|
|
||||||
key,
|
|
||||||
addresses,
|
|
||||||
} => {
|
|
||||||
if *version != AWG_WIRE_VERSION || peer.as_bytes() >= self.inner.local.as_bytes() {
|
|
||||||
return Err(error("invalid AWG offer role/version"));
|
|
||||||
}
|
|
||||||
profile.validate().map_err(error)?;
|
|
||||||
validate_endpoint(key, addresses)?;
|
|
||||||
}
|
|
||||||
Negotiation::Answer { key, addresses, .. } => validate_endpoint(key, addresses)?,
|
|
||||||
}
|
|
||||||
self.commands
|
|
||||||
.try_send((network, peer, message))
|
|
||||||
.map_err(|_| error("AWG negotiation queue full"))
|
|
||||||
}
|
|
||||||
fn open<'a>(
|
|
||||||
&'a self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
protocol: &'a str,
|
|
||||||
) -> BoxFuture<'a, Result<SharedLink, TransportError>> {
|
|
||||||
Box::pin(async move {
|
|
||||||
let pair = (network, peer);
|
|
||||||
if protocol != AWG_PROTOCOL
|
|
||||||
|| self.inner.local.as_bytes() >= peer.as_bytes()
|
|
||||||
|| !lock(&self.inner.allowed).contains(&pair)
|
|
||||||
{
|
|
||||||
return Err(TransportError::Declined(protocol.into()));
|
|
||||||
}
|
|
||||||
let control = self
|
|
||||||
.inner
|
|
||||||
.control
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| error("AWG control plane unavailable"))?;
|
|
||||||
let socket = UdpSocket::bind((self.inner.bind, 0))
|
|
||||||
.await
|
|
||||||
.map_err(|_| error("AWG UDP bind failed"))?;
|
|
||||||
let profile = PairProfile::generate();
|
|
||||||
let attempt = profile.id();
|
|
||||||
let key = StaticSecret::from(rand::random::<[u8; 32]>());
|
|
||||||
let public = PublicKey::from(&key).to_bytes();
|
|
||||||
let message = Negotiation::Offer {
|
|
||||||
version: AWG_WIRE_VERSION,
|
|
||||||
profile: profile.clone(),
|
|
||||||
key: public,
|
|
||||||
addresses: addresses(&self.inner, &socket).await?,
|
|
||||||
};
|
|
||||||
let (reply, rx) = oneshot::channel();
|
|
||||||
if lock(&self.inner.pending).len() >= 128 {
|
|
||||||
return Err(error("too many AWG pair negotiations"));
|
|
||||||
}
|
|
||||||
lock(&self.inner.pending).insert(
|
|
||||||
pair,
|
|
||||||
Pending {
|
|
||||||
profile,
|
|
||||||
key,
|
|
||||||
socket,
|
|
||||||
reply,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
// A cancellation guard also retires partially started attempts.
|
|
||||||
let mut guard = AttemptGuard {
|
|
||||||
inner: Arc::downgrade(&self.inner),
|
|
||||||
pair,
|
|
||||||
attempt,
|
|
||||||
completed: false,
|
|
||||||
};
|
|
||||||
let bytes =
|
|
||||||
postcard::to_stdvec(&message).map_err(|_| error("AWG offer encoding failed"))?;
|
|
||||||
control
|
|
||||||
.send(network, peer, AWG_PROTOCOL, TransportPayload::new(bytes))
|
|
||||||
.await?;
|
|
||||||
let result = tokio::time::timeout(Duration::from_secs(15), rx)
|
|
||||||
.await
|
|
||||||
.map_err(|_| error("AWG negotiation/handshake timed out"))?
|
|
||||||
.map_err(|_| error("AWG attempt cancelled"))?;
|
|
||||||
guard.completed = result.is_ok();
|
|
||||||
result
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
struct AttemptGuard {
|
|
||||||
inner: Weak<Inner>,
|
|
||||||
pair: Pair,
|
|
||||||
attempt: [u8; 16],
|
|
||||||
completed: bool,
|
|
||||||
}
|
|
||||||
impl Drop for AttemptGuard {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Some(inner) = self.inner.upgrade() {
|
|
||||||
let mut pending = lock(&inner.pending);
|
|
||||||
if pending
|
|
||||||
.get(&self.pair)
|
|
||||||
.is_some_and(|p| p.profile.id() == self.attempt)
|
|
||||||
{
|
|
||||||
pending.remove(&self.pair);
|
|
||||||
}
|
|
||||||
drop(pending);
|
|
||||||
if !self.completed
|
|
||||||
&& let Some(link) = lock(&inner.links).get(&self.pair)
|
|
||||||
&& link.attempt == self.attempt
|
|
||||||
{
|
|
||||||
link.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async fn receive(
|
|
||||||
inner: &Arc<Inner>,
|
|
||||||
pair: Pair,
|
|
||||||
message: Negotiation,
|
|
||||||
) -> Result<(), TransportError> {
|
|
||||||
if !lock(&inner.allowed).contains(&pair) {
|
|
||||||
return Err(error("AWG peer no longer authenticated"));
|
|
||||||
}
|
|
||||||
match message {
|
|
||||||
Negotiation::Offer {
|
|
||||||
profile,
|
|
||||||
key,
|
|
||||||
addresses: candidates,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
if let Some(link) = lock(&inner.links).get(&pair) {
|
|
||||||
if link.attempt == profile.id() {
|
|
||||||
return Err(error("duplicate AWG offer"));
|
|
||||||
}
|
|
||||||
link.close();
|
|
||||||
}
|
|
||||||
let socket = UdpSocket::bind((inner.bind, 0))
|
|
||||||
.await
|
|
||||||
.map_err(|_| error("AWG UDP bind failed"))?;
|
|
||||||
let local_port = socket
|
|
||||||
.local_addr()
|
|
||||||
.map_err(|_| error("AWG socket address unavailable"))?
|
|
||||||
.port();
|
|
||||||
let local_key = StaticSecret::from(rand::random::<[u8; 32]>());
|
|
||||||
let public = PublicKey::from(&local_key).to_bytes();
|
|
||||||
let answer = Negotiation::Answer {
|
|
||||||
attempt: profile.id(),
|
|
||||||
key: public,
|
|
||||||
addresses: addresses(inner, &socket).await?,
|
|
||||||
};
|
|
||||||
let tunn = Tunn::new(
|
|
||||||
local_key,
|
|
||||||
PublicKey::from(key),
|
|
||||||
Some(profile.psk),
|
|
||||||
Some(1),
|
|
||||||
rand::random(),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
let link = session::start(
|
|
||||||
pair.0,
|
|
||||||
pair.1,
|
|
||||||
socket,
|
|
||||||
tunn,
|
|
||||||
profile,
|
|
||||||
candidates,
|
|
||||||
inner.stopped.subscribe(),
|
|
||||||
);
|
|
||||||
if !lock(&inner.allowed).contains(&pair) {
|
|
||||||
link.close();
|
|
||||||
return Err(error("AWG membership ended"));
|
|
||||||
}
|
|
||||||
lock(&inner.links).insert(pair, link.clone());
|
|
||||||
lock(&inner.port_by_pair).insert(pair, local_port);
|
|
||||||
let control = inner
|
|
||||||
.control
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| error("AWG control unavailable"))?;
|
|
||||||
if let Err(err) = control
|
|
||||||
.send(
|
|
||||||
pair.0,
|
|
||||||
pair.1,
|
|
||||||
AWG_PROTOCOL,
|
|
||||||
TransportPayload::new(
|
|
||||||
postcard::to_stdvec(&answer)
|
|
||||||
.map_err(|_| error("AWG answer encoding failed"))?,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
link.close();
|
|
||||||
return Err(err);
|
|
||||||
}
|
|
||||||
publish_when_up(Arc::downgrade(inner), pair, link, None);
|
|
||||||
}
|
|
||||||
Negotiation::Answer {
|
|
||||||
attempt,
|
|
||||||
key,
|
|
||||||
addresses: candidates,
|
|
||||||
} => {
|
|
||||||
if !lock(&inner.pending)
|
|
||||||
.get(&pair)
|
|
||||||
.is_some_and(|p| p.profile.id() == attempt)
|
|
||||||
{
|
|
||||||
return Err(error("stale AWG answer"));
|
|
||||||
}
|
|
||||||
let pending = lock(&inner.pending)
|
|
||||||
.remove(&pair)
|
|
||||||
.ok_or_else(|| error("AWG attempt cancelled"))?;
|
|
||||||
let local_port = pending
|
|
||||||
.socket
|
|
||||||
.local_addr()
|
|
||||||
.map_err(|_| error("AWG socket address unavailable"))?
|
|
||||||
.port();
|
|
||||||
let tunn = Tunn::new(
|
|
||||||
pending.key,
|
|
||||||
PublicKey::from(key),
|
|
||||||
Some(pending.profile.psk),
|
|
||||||
Some(1),
|
|
||||||
rand::random(),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
let link = session::start(
|
|
||||||
pair.0,
|
|
||||||
pair.1,
|
|
||||||
pending.socket,
|
|
||||||
tunn,
|
|
||||||
pending.profile,
|
|
||||||
candidates,
|
|
||||||
inner.stopped.subscribe(),
|
|
||||||
);
|
|
||||||
if !lock(&inner.allowed).contains(&pair) {
|
|
||||||
link.close();
|
|
||||||
return Err(error("AWG membership ended"));
|
|
||||||
}
|
|
||||||
lock(&inner.links).insert(pair, link.clone());
|
|
||||||
lock(&inner.port_by_pair).insert(pair, local_port);
|
|
||||||
publish_when_up(Arc::downgrade(inner), pair, link, Some(pending.reply));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn publish_when_up(
|
|
||||||
inner: Weak<Inner>,
|
|
||||||
pair: Pair,
|
|
||||||
link: Arc<PairLink>,
|
|
||||||
reply: Option<oneshot::Sender<Result<SharedLink, TransportError>>>,
|
|
||||||
) {
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut reply = reply;
|
|
||||||
let result = tokio::time::timeout(Duration::from_secs(14), async {
|
|
||||||
loop {
|
|
||||||
if link.is_closed() || reply.as_ref().is_some_and(oneshot::Sender::is_closed) {
|
|
||||||
return Err(error("AWG pair closed during handshake"));
|
|
||||||
}
|
|
||||||
if link.has_authenticated_path() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
if !matches!(result, Ok(Ok(()))) {
|
|
||||||
link.close();
|
|
||||||
if let Some(reply) = reply.take() {
|
|
||||||
let _ = reply.send(Err(error("AWG authenticated data path timed out")));
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let Some(inner) = inner.upgrade() else {
|
|
||||||
link.close();
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
if !lock(&inner.allowed).contains(&pair) {
|
|
||||||
link.close();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if link.is_closed()
|
|
||||||
|| !lock(&inner.links)
|
|
||||||
.get(&pair)
|
|
||||||
.is_some_and(|current| current.attempt == link.attempt)
|
|
||||||
{
|
|
||||||
link.close();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let shared: SharedLink = link.clone();
|
|
||||||
if let Some(reply) = reply {
|
|
||||||
if reply.send(Ok(shared)).is_err() {
|
|
||||||
link.close();
|
|
||||||
}
|
|
||||||
} else if inner
|
|
||||||
.inbound
|
|
||||||
.try_send(InboundLink {
|
|
||||||
network: pair.0,
|
|
||||||
peer: pair.1,
|
|
||||||
protocol: AWG_PROTOCOL.into(),
|
|
||||||
link: shared,
|
|
||||||
})
|
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
link.close();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
impl Drop for AwgTransport {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
|
||||||
use super::*;
|
|
||||||
#[tokio::test]
|
|
||||||
async fn concurrent_admission_is_bounded_across_networks_and_retirement_releases_slots() {
|
|
||||||
let identity = tsunagi::identity::DeviceIdentity::generate();
|
|
||||||
let transport = AwgTransport::new(identity.endpoint_id(), Ipv4Addr::LOCALHOST);
|
|
||||||
let peer = tsunagi::identity::DeviceIdentity::generate().endpoint_id();
|
|
||||||
std::thread::scope(|scope| {
|
|
||||||
for thread in 0..8u8 {
|
|
||||||
let transport = &transport;
|
|
||||||
scope.spawn(move || {
|
|
||||||
for item in 0..32u8 {
|
|
||||||
let mut id = [0; 32];
|
|
||||||
id[0] = thread;
|
|
||||||
id[1] = item;
|
|
||||||
transport.allow_peer(NetworkId::from_bytes(id), peer);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
assert_eq!(lock(&transport.inner.allowed).len(), 128);
|
|
||||||
let network = lock(&transport.inner.allowed).iter().next().unwrap().0;
|
|
||||||
transport.stop_network(network);
|
|
||||||
let new = NetworkId::from_bytes([255; 32]);
|
|
||||||
transport.allow_peer(new, peer);
|
|
||||||
assert!(lock(&transport.inner.allowed).contains(&(new, peer)));
|
|
||||||
assert_eq!(lock(&transport.inner.allowed).len(), 128);
|
|
||||||
transport.shutdown();
|
|
||||||
assert!(lock(&transport.inner.allowed).is_empty());
|
|
||||||
}
|
|
||||||
#[tokio::test]
|
|
||||||
async fn private_negotiation_bounds_roles_and_membership_before_starting_engines() {
|
|
||||||
let mut ids = [
|
|
||||||
tsunagi::identity::DeviceIdentity::generate().endpoint_id(),
|
|
||||||
tsunagi::identity::DeviceIdentity::generate().endpoint_id(),
|
|
||||||
];
|
|
||||||
ids.sort_by_key(|id| *id.as_bytes());
|
|
||||||
let peer = ids[0];
|
|
||||||
let local = ids[1];
|
|
||||||
let network = NetworkId::from_bytes([7; 32]);
|
|
||||||
let transport = AwgTransport::new(local, Ipv4Addr::LOCALHOST);
|
|
||||||
let offer = |version, key, addresses| Negotiation::Offer {
|
|
||||||
version,
|
|
||||||
profile: PairProfile::generate(),
|
|
||||||
key,
|
|
||||||
addresses,
|
|
||||||
};
|
|
||||||
let address = SocketAddr::from((Ipv4Addr::LOCALHOST, 12345));
|
|
||||||
let encode = |message: &Negotiation| postcard::to_stdvec(message).unwrap();
|
|
||||||
let valid = encode(&offer(AWG_WIRE_VERSION, [1; 32], vec![address]));
|
|
||||||
assert!(
|
|
||||||
transport
|
|
||||||
.on_control(network, peer, AWG_PROTOCOL, &valid)
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
transport.allow_peer(network, peer);
|
|
||||||
assert!(
|
|
||||||
transport
|
|
||||||
.on_control(network, peer, "wrong-protocol", &valid)
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
transport
|
|
||||||
.on_control(network, peer, AWG_PROTOCOL, &[0; 4097])
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
for bytes in [
|
|
||||||
encode(&offer(99, [1; 32], vec![address])),
|
|
||||||
encode(&offer(AWG_WIRE_VERSION, [0; 32], vec![address])),
|
|
||||||
encode(&offer(AWG_WIRE_VERSION, [1; 32], vec![])),
|
|
||||||
encode(&offer(AWG_WIRE_VERSION, [1; 32], vec![address; 33])),
|
|
||||||
] {
|
|
||||||
assert!(
|
|
||||||
transport
|
|
||||||
.on_control(network, peer, AWG_PROTOCOL, &bytes)
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
for len in 0..valid.len() {
|
|
||||||
assert!(
|
|
||||||
transport
|
|
||||||
.on_control(network, peer, AWG_PROTOCOL, &valid[..len])
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let wrong_role = AwgTransport::new(peer, Ipv4Addr::LOCALHOST);
|
|
||||||
wrong_role.allow_peer(network, local);
|
|
||||||
assert!(
|
|
||||||
wrong_role
|
|
||||||
.on_control(network, local, AWG_PROTOCOL, &valid)
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
transport.forget_peer(network, peer);
|
|
||||||
assert!(
|
|
||||||
transport
|
|
||||||
.on_control(network, peer, AWG_PROTOCOL, &valid)
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
assert!(transport.overview(network).is_empty());
|
|
||||||
transport.shutdown();
|
|
||||||
wrong_role.shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
//! A real userspace TCP stack attached to each memory TUN, without host routes.
|
||||||
|
use bytes::Bytes;
|
||||||
|
use smoltcp::{
|
||||||
|
iface::{Config, Interface, SocketHandle, SocketSet},
|
||||||
|
phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken},
|
||||||
|
socket::tcp,
|
||||||
|
time::Instant as TcpInstant,
|
||||||
|
wire::{HardwareAddress, IpAddress, IpCidr},
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
net::Ipv4Addr,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tsunagi::overlay::MemoryTun;
|
||||||
|
|
||||||
|
struct TunDevice {
|
||||||
|
input: Arc<Mutex<VecDeque<Vec<u8>>>>,
|
||||||
|
tun: Arc<MemoryTun>,
|
||||||
|
}
|
||||||
|
struct Rx(Vec<u8>);
|
||||||
|
impl RxToken for Rx {
|
||||||
|
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
|
||||||
|
f(&self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Tx(Arc<MemoryTun>);
|
||||||
|
impl TxToken for Tx {
|
||||||
|
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
|
||||||
|
let mut packet = vec![0; len];
|
||||||
|
let result = f(&mut packet);
|
||||||
|
self.0.push_from_os(Bytes::from(packet));
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Device for TunDevice {
|
||||||
|
type RxToken<'a>
|
||||||
|
= Rx
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
type TxToken<'a>
|
||||||
|
= Tx
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
fn receive(&mut self, _: TcpInstant) -> Option<(Rx, Tx)> {
|
||||||
|
self.input
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.pop_front()
|
||||||
|
.map(|packet| (Rx(packet), Tx(self.tun.clone())))
|
||||||
|
}
|
||||||
|
fn transmit(&mut self, _: TcpInstant) -> Option<Tx> {
|
||||||
|
Some(Tx(self.tun.clone()))
|
||||||
|
}
|
||||||
|
fn capabilities(&self) -> DeviceCapabilities {
|
||||||
|
let mut caps = DeviceCapabilities::default();
|
||||||
|
caps.medium = Medium::Ip;
|
||||||
|
caps.max_transmission_unit = 1280;
|
||||||
|
caps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Stack {
|
||||||
|
iface: Interface,
|
||||||
|
sockets: SocketSet<'static>,
|
||||||
|
socket: SocketHandle,
|
||||||
|
device: TunDevice,
|
||||||
|
reader: tokio::task::JoinHandle<()>,
|
||||||
|
}
|
||||||
|
impl Stack {
|
||||||
|
fn new(tun: Arc<MemoryTun>, address: Ipv4Addr) -> Self {
|
||||||
|
let input = Arc::new(Mutex::new(VecDeque::new()));
|
||||||
|
let queue = input.clone();
|
||||||
|
let received = tun.clone();
|
||||||
|
let reader = tokio::spawn(async move {
|
||||||
|
while let Some(packet) = received.pop_to_os().await {
|
||||||
|
let mut queue = queue.lock().unwrap();
|
||||||
|
assert!(queue.len() < 256);
|
||||||
|
queue.push_back(packet.to_vec());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let mut device = TunDevice { input, tun };
|
||||||
|
let mut config = Config::new(HardwareAddress::Ip);
|
||||||
|
config.random_seed = rand::random();
|
||||||
|
let mut iface = Interface::new(config, &mut device, TcpInstant::from_millis(0));
|
||||||
|
let [a, b, c, d] = address.octets();
|
||||||
|
iface.update_ip_addrs(|addresses| {
|
||||||
|
addresses
|
||||||
|
.push(IpCidr::new(IpAddress::v4(a, b, c, d), 24))
|
||||||
|
.unwrap()
|
||||||
|
});
|
||||||
|
let mut sockets = SocketSet::new(Vec::new());
|
||||||
|
let socket = sockets.add(tcp::Socket::new(
|
||||||
|
tcp::SocketBuffer::new(vec![0; 65536]),
|
||||||
|
tcp::SocketBuffer::new(vec![0; 65536]),
|
||||||
|
));
|
||||||
|
Self {
|
||||||
|
iface,
|
||||||
|
sockets,
|
||||||
|
socket,
|
||||||
|
device,
|
||||||
|
reader,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn tcp(&mut self) -> &mut tcp::Socket<'static> {
|
||||||
|
self.sockets.get_mut(self.socket)
|
||||||
|
}
|
||||||
|
fn poll(&mut self, now: TcpInstant) {
|
||||||
|
self.iface.poll(now, &mut self.device, &mut self.sockets);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for Stack {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.reader.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct TcpPair {
|
||||||
|
client: Stack,
|
||||||
|
server: Stack,
|
||||||
|
started: Instant,
|
||||||
|
}
|
||||||
|
impl TcpPair {
|
||||||
|
pub(super) async fn connect(
|
||||||
|
a: Arc<MemoryTun>,
|
||||||
|
a_ip: Ipv4Addr,
|
||||||
|
b: Arc<MemoryTun>,
|
||||||
|
b_ip: Ipv4Addr,
|
||||||
|
) -> Self {
|
||||||
|
let mut pair = Self {
|
||||||
|
client: Stack::new(a, a_ip),
|
||||||
|
server: Stack::new(b, b_ip),
|
||||||
|
started: Instant::now(),
|
||||||
|
};
|
||||||
|
pair.server.tcp().listen(22).unwrap();
|
||||||
|
let [a, b, c, d] = b_ip.octets();
|
||||||
|
pair.client
|
||||||
|
.sockets
|
||||||
|
.get_mut::<tcp::Socket>(pair.client.socket)
|
||||||
|
.connect(
|
||||||
|
pair.client.iface.context(),
|
||||||
|
(IpAddress::v4(a, b, c, d), 22),
|
||||||
|
40000,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
pair.until(|p| {
|
||||||
|
p.client.tcp().state() == tcp::State::Established
|
||||||
|
&& p.server.tcp().state() == tcp::State::Established
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
pair
|
||||||
|
}
|
||||||
|
fn poll(&mut self) {
|
||||||
|
let now = TcpInstant::from_millis(self.started.elapsed().as_millis() as i64);
|
||||||
|
self.client.poll(now);
|
||||||
|
self.server.poll(now);
|
||||||
|
}
|
||||||
|
async fn until(&mut self, mut ready: impl FnMut(&mut Self) -> bool) {
|
||||||
|
tokio::time::timeout(Duration::from_secs(10), async {
|
||||||
|
let mut ticks = tokio::time::interval(Duration::from_millis(2));
|
||||||
|
loop {
|
||||||
|
ticks.tick().await;
|
||||||
|
self.poll();
|
||||||
|
if ready(self) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("same TCP connection must progress across carrier/route changes");
|
||||||
|
}
|
||||||
|
pub(super) fn queue_while_unreachable(&mut self, payload: &[u8]) {
|
||||||
|
assert_eq!(
|
||||||
|
self.client.tcp().send_slice(payload).unwrap(),
|
||||||
|
payload.len()
|
||||||
|
);
|
||||||
|
self.poll();
|
||||||
|
}
|
||||||
|
pub(super) async fn receive_queued(&mut self, payload: &[u8]) {
|
||||||
|
let mut received = Vec::new();
|
||||||
|
self.until(|p| {
|
||||||
|
if p.server.tcp().can_recv() {
|
||||||
|
p.server
|
||||||
|
.tcp()
|
||||||
|
.recv(|bytes| {
|
||||||
|
received.extend_from_slice(bytes);
|
||||||
|
(bytes.len(), ())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
received.len() >= payload.len()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(received, payload);
|
||||||
|
assert_eq!(self.client.tcp().state(), tcp::State::Established);
|
||||||
|
assert_eq!(self.server.tcp().state(), tcp::State::Established);
|
||||||
|
}
|
||||||
|
pub(super) async fn exchange(&mut self, payload: &[u8]) {
|
||||||
|
self.queue_while_unreachable(payload);
|
||||||
|
self.receive_queued(payload).await;
|
||||||
|
assert_eq!(
|
||||||
|
self.server.tcp().send_slice(payload).unwrap(),
|
||||||
|
payload.len()
|
||||||
|
);
|
||||||
|
let mut received = Vec::new();
|
||||||
|
self.until(|p| {
|
||||||
|
if p.client.tcp().can_recv() {
|
||||||
|
p.client
|
||||||
|
.tcp()
|
||||||
|
.recv(|bytes| {
|
||||||
|
received.extend_from_slice(bytes);
|
||||||
|
(bytes.len(), ())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
received.len() >= payload.len()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(received, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
//! Real membership, UDP sockets, pair negotiation and nested WireGuard encryption.
|
//! Real membership, UDP sockets, pair negotiation and nested WireGuard encryption.
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
#[path = "common/tcp.rs"]
|
||||||
|
mod tcp;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use std::{
|
use std::{
|
||||||
net::Ipv4Addr,
|
net::Ipv4Addr,
|
||||||
@@ -24,8 +26,7 @@ use tsunagi_wg_quic::WireguardConfig;
|
|||||||
|
|
||||||
struct Node {
|
struct Node {
|
||||||
agent: Agent,
|
agent: Agent,
|
||||||
plugin: Arc<AwgPlugin>,
|
plugin: Arc<tsunagi_wg_quic::WireguardPlugin>,
|
||||||
quic: Option<Arc<tsunagi_wg_quic::WireguardPlugin>>,
|
|
||||||
transport: Arc<AwgTransport>,
|
transport: Arc<AwgTransport>,
|
||||||
tuns: MemoryTunFactory,
|
tuns: MemoryTunFactory,
|
||||||
loss: Arc<AtomicBool>,
|
loss: Arc<AtomicBool>,
|
||||||
@@ -65,11 +66,10 @@ impl Node {
|
|||||||
.load_or_create_device_identity()
|
.load_or_create_device_identity()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let transport = AwgTransport::new(identity.endpoint_id(), Ipv4Addr::LOCALHOST);
|
let transport = AwgTransport::new(identity.endpoint_id(), Ipv4Addr::LOCALHOST);
|
||||||
let plugin = AwgPlugin::open(
|
let plugin = tsunagi_wg_quic::WireguardPlugin::open(
|
||||||
WireguardConfig::new(root.join("awg"))
|
WireguardConfig::new(root.join("awg"))
|
||||||
.with_mtu(mtu)
|
.with_mtu(mtu)
|
||||||
.with_reconcile(Duration::from_millis(20), Duration::from_millis(250)),
|
.with_reconcile(Duration::from_millis(20), Duration::from_millis(250)),
|
||||||
transport.clone(),
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -81,19 +81,13 @@ impl Node {
|
|||||||
let tuns = MemoryTunFactory::new();
|
let tuns = MemoryTunFactory::new();
|
||||||
let mut config = config_with(root, discovery)
|
let mut config = config_with(root, discovery)
|
||||||
.with_interface(Arc::new(tuns.clone()), interface, mtu)
|
.with_interface(Arc::new(tuns.clone()), interface, mtu)
|
||||||
.with_plugin(plugin.clone() as Arc<dyn IpPlugin>)
|
.with_tunnel(plugin.clone() as Arc<dyn IpPlugin>)
|
||||||
|
.with_carrier(AwgPlugin::new(transport.clone()))
|
||||||
.with_custom_transport(AWG_PROTOCOL, faults);
|
.with_custom_transport(AWG_PROTOCOL, faults);
|
||||||
let mut quic_plugin = None;
|
|
||||||
if fallback {
|
if fallback {
|
||||||
let quic = tsunagi_wg_quic::WireguardPlugin::open(
|
config = config.with_carrier(Arc::new(
|
||||||
WireguardConfig::new(root.join("wg-quic"))
|
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
|
||||||
.with_mtu(mtu)
|
));
|
||||||
.with_reconcile(Duration::from_millis(20), Duration::from_millis(250)),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
config = config.with_plugin(quic.clone());
|
|
||||||
quic_plugin = Some(quic);
|
|
||||||
}
|
}
|
||||||
config.default_protocols = default_protocols;
|
config.default_protocols = default_protocols;
|
||||||
let agent = Agent::spawn(config).await.unwrap();
|
let agent = Agent::spawn(config).await.unwrap();
|
||||||
@@ -109,7 +103,6 @@ impl Node {
|
|||||||
Self {
|
Self {
|
||||||
agent,
|
agent,
|
||||||
plugin,
|
plugin,
|
||||||
quic: quic_plugin,
|
|
||||||
transport,
|
transport,
|
||||||
tuns,
|
tuns,
|
||||||
loss,
|
loss,
|
||||||
@@ -252,7 +245,7 @@ async fn a_control_only_agent_enables_real_data_without_restart_and_cancels_stal
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn runtime_protocol_selection_replaces_real_tunnels_and_survives_restart() {
|
async fn runtime_protocol_selection_preserves_real_tunnels_and_survives_restart() {
|
||||||
let discovery = SharedMemoryDiscovery::new();
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
let a = Node::open_with_fallback(roots[0].path(), &discovery, "runtime-a", true).await;
|
let a = Node::open_with_fallback(roots[0].path(), &discovery, "runtime-a", true).await;
|
||||||
@@ -263,6 +256,12 @@ async fn runtime_protocol_selection_replaces_real_tunnels_and_survives_restart()
|
|||||||
a.ready(id, 1).await;
|
a.ready(id, 1).await;
|
||||||
b.ready(id, 1).await;
|
b.ready(id, 1).await;
|
||||||
exchange(&a, &b, id).await;
|
exchange(&a, &b, id).await;
|
||||||
|
let original_key = a.plugin.overview(id).unwrap().public_key;
|
||||||
|
let original_stats = a.plugin.overview(id).unwrap().peers[0]
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats;
|
||||||
|
|
||||||
let (other_name, other_secret, other_id) = loop {
|
let (other_name, other_secret, other_id) = loop {
|
||||||
let (name, secret) = network("unchanged-runtime-network");
|
let (name, secret) = network("unchanged-runtime-network");
|
||||||
@@ -338,13 +337,25 @@ async fn runtime_protocol_selection_replaces_real_tunnels_and_survives_restart()
|
|||||||
.then_some(())
|
.then_some(())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
// Get addresses from the system allocation: the disabled AWG plugin no
|
assert_eq!(a.plugin.overview(id).unwrap().public_key, original_key);
|
||||||
// longer has a live view of this network.
|
let stats = a.plugin.overview(id).unwrap().peers[0]
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats;
|
||||||
|
assert_eq!(stats.counter_epoch, original_stats.counter_epoch);
|
||||||
|
assert!(stats.tx_bytes >= original_stats.tx_bytes);
|
||||||
|
assert!(stats.rx_bytes >= original_stats.rx_bytes);
|
||||||
|
assert!(a.plugin.overview(id).unwrap().peers.iter().any(|peer| {
|
||||||
|
peer.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|tunnel| tunnel.health.is_up())
|
||||||
|
}));
|
||||||
|
// The same internal plugin supplies addresses and counters on the new carrier.
|
||||||
for (source, dest) in [(&a, &b), (&b, &a)] {
|
for (source, dest) in [(&a, &b), (&b, &a)] {
|
||||||
wait_until("QUIC end-to-end handshake", || async {
|
wait_until("QUIC end-to-end handshake", || async {
|
||||||
source
|
source
|
||||||
.quic
|
.plugin
|
||||||
.as_ref()?
|
|
||||||
.overview(id)?
|
.overview(id)?
|
||||||
.peers
|
.peers
|
||||||
.iter()
|
.iter()
|
||||||
@@ -352,15 +363,7 @@ async fn runtime_protocol_selection_replaces_real_tunnels_and_survives_restart()
|
|||||||
.then_some(())
|
.then_some(())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
let addr = |n: &Node| {
|
let addr = |n: &Node| n.plugin.overview(id).unwrap().overlay_address_v4.unwrap();
|
||||||
n.quic
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.overview(id)
|
|
||||||
.unwrap()
|
|
||||||
.overlay_address_v4
|
|
||||||
.unwrap()
|
|
||||||
};
|
|
||||||
let bytes = packet(addr(source), addr(dest), 1280);
|
let bytes = packet(addr(source), addr(dest), 1280);
|
||||||
source.tun().push_from_os(bytes.clone());
|
source.tun().push_from_os(bytes.clone());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -604,18 +607,13 @@ async fn persistent_runtime_loss_retires_the_pair_and_negotiates_fresh_parameter
|
|||||||
} else {
|
} else {
|
||||||
&b
|
&b
|
||||||
};
|
};
|
||||||
let received = initiator.plugin.overview(id).unwrap().peers[0]
|
|
||||||
.tunnel
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.stats
|
|
||||||
.rx_packets;
|
|
||||||
let attempt = initiator.transport.overview(id)[0].attempt;
|
let attempt = initiator.transport.overview(id)[0].attempt;
|
||||||
|
let received = initiator.transport.overview(id)[0].delivery_checks;
|
||||||
wait_until(
|
wait_until(
|
||||||
"fresh pair delivery checks answered after installation",
|
"fresh physical delivery checks answered after installation",
|
||||||
|| async {
|
|| async {
|
||||||
let view = initiator.plugin.overview(id)?;
|
(initiator.transport.overview(id).first()?.delivery_checks >= received + 3)
|
||||||
(view.peers.first()?.tunnel.as_ref()?.stats.rx_packets >= received + 3).then_some(())
|
.then_some(())
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -749,11 +747,11 @@ async fn encrypted_health_checks_fit_a_smaller_peers_configured_interface_mtu()
|
|||||||
bytes
|
bytes
|
||||||
);
|
);
|
||||||
wait_until(
|
wait_until(
|
||||||
"encrypted delivery checks answered with a small MTU",
|
"physical delivery checks do not depend on overlay MTU",
|
||||||
|| async {
|
|| async {
|
||||||
let view = a.plugin.overview(id)?;
|
(a.transport.overview(id).first()?.delivery_checks >= 4
|
||||||
let peer = view.peers.first()?.tunnel.as_ref()?;
|
&& b.transport.overview(id).first()?.delivery_checks >= 4)
|
||||||
(peer.stats.rx_packets >= 3).then_some(())
|
.then_some(())
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -771,3 +769,179 @@ async fn encrypted_health_checks_fit_a_smaller_peers_configured_interface_mtu()
|
|||||||
a.agent.shutdown().await;
|
a.agent.shutdown().await;
|
||||||
b.agent.shutdown().await;
|
b.agent.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn disjoint_external_policies_relay_the_same_internal_tunnel_and_keep_it_when_routes_change()
|
||||||
|
{
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
TempDir::new().unwrap(),
|
||||||
|
];
|
||||||
|
let a = Node::open_selected(
|
||||||
|
roots[0].path(),
|
||||||
|
&discovery,
|
||||||
|
"only-awg",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec!["awg".into()]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let b = Node::open_with_fallback(roots[1].path(), &discovery, "mixed-relay", true).await;
|
||||||
|
let c = Node::open_selected(
|
||||||
|
roots[2].path(),
|
||||||
|
&discovery,
|
||||||
|
"only-quic",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec!["wg-quic".into()]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (name, secret) = network("independent-internal-encryption");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
c.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
for node in [&a, &b, &c] {
|
||||||
|
wait_for_peers(&node.agent, id, 2).await;
|
||||||
|
}
|
||||||
|
wait_until("AWG-only to QUIC-only through an authenticated mixed relay", || async {
|
||||||
|
let status = a.agent.network_status(id).await.ok()?;
|
||||||
|
let peer = status.peers.iter().find(|p| p.endpoint_id == c.agent.endpoint_id())?;
|
||||||
|
(matches!(peer.data_path, tsunagi::agent::DataPath::Relayed { via, .. } if via == b.agent.endpoint_id()) && a.plugin.overview(id)?.established_peers() == 2 && c.plugin.overview(id)?.established_peers() == 2).then_some(())
|
||||||
|
}).await;
|
||||||
|
exchange(&a, &c, id).await;
|
||||||
|
exchange(&c, &a, id).await;
|
||||||
|
let mut tcp = tcp::TcpPair::connect(a.tun(), a.addr(id), c.tun(), c.addr(id)).await;
|
||||||
|
tcp.exchange(b"SSH-like TCP stream over the initial relay")
|
||||||
|
.await;
|
||||||
|
let key = a.plugin.overview(id).unwrap().public_key;
|
||||||
|
let before = a
|
||||||
|
.plugin
|
||||||
|
.overview(id)
|
||||||
|
.unwrap()
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.endpoint_id == c.agent.endpoint_id())
|
||||||
|
.unwrap()
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.tx_packets;
|
||||||
|
// A's additional permission creates a direct QUIC route without replacing its IP tunnel.
|
||||||
|
a.agent
|
||||||
|
.set_protocols(id, vec!["wg-quic".into(), "awg".into()])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
wait_until("direct carrier replaces the relay", || async {
|
||||||
|
let status = a.agent.network_status(id).await.ok()?;
|
||||||
|
matches!(
|
||||||
|
status
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.endpoint_id == c.agent.endpoint_id())?
|
||||||
|
.data_path,
|
||||||
|
tsunagi::agent::DataPath::Direct { .. }
|
||||||
|
)
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
tcp.exchange(b"same TCP socket after changing the carrier and next hop")
|
||||||
|
.await;
|
||||||
|
assert_eq!(a.plugin.overview(id).unwrap().public_key, key);
|
||||||
|
assert!(
|
||||||
|
a.plugin
|
||||||
|
.overview(id)
|
||||||
|
.unwrap()
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.endpoint_id == c.agent.endpoint_id())
|
||||||
|
.unwrap()
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.tx_packets
|
||||||
|
> before
|
||||||
|
);
|
||||||
|
a.agent.set_protocols(id, Vec::new()).await.unwrap();
|
||||||
|
// Poll the actual TCP stack while the route is absent: its first transmission is lost.
|
||||||
|
let pending = b"TCP retransmission survives the temporary absence of every data carrier";
|
||||||
|
tcp.queue_while_unreachable(pending);
|
||||||
|
a.agent.set_protocols(id, vec!["awg".into()]).await.unwrap();
|
||||||
|
wait_until("forbidden QUIC removed and relay restored", || async {
|
||||||
|
let status = a.agent.network_status(id).await.ok()?;
|
||||||
|
matches!(
|
||||||
|
status
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.endpoint_id == c.agent.endpoint_id())?
|
||||||
|
.data_path,
|
||||||
|
tsunagi::agent::DataPath::Relayed { .. }
|
||||||
|
)
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(a.plugin.overview(id).unwrap().public_key, key);
|
||||||
|
tcp.receive_queued(pending).await;
|
||||||
|
tcp.exchange(b"same TCP connection after returning to AWG and the relay")
|
||||||
|
.await;
|
||||||
|
drop(tcp);
|
||||||
|
// Transit ciphertext must never be delivered to the middle agent's IP interface.
|
||||||
|
assert!(
|
||||||
|
tokio::time::timeout(Duration::from_millis(150), b.tun().pop_to_os())
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
for node in [&a, &b, &c] {
|
||||||
|
node.agent.shutdown().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn no_common_carrier_is_an_actionable_policy_error_without_disabling_control() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let roots = [TempDir::new().unwrap(), TempDir::new().unwrap()];
|
||||||
|
let a = Node::open_selected(
|
||||||
|
roots[0].path(),
|
||||||
|
&discovery,
|
||||||
|
"awg-policy",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec!["awg".into()]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let b = Node::open_selected(
|
||||||
|
roots[1].path(),
|
||||||
|
&discovery,
|
||||||
|
"quic-policy",
|
||||||
|
true,
|
||||||
|
1280,
|
||||||
|
Some(vec!["wg-quic".into()]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (name, secret) = network("no-common-carrier");
|
||||||
|
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
wait_until("explain independent external policies", || async {
|
||||||
|
let status = a.agent.network_status(id).await.ok()?;
|
||||||
|
let peer = status.peers.first()?;
|
||||||
|
peer.data_error
|
||||||
|
.as_ref()?
|
||||||
|
.contains("no common external transport")
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
a.agent
|
||||||
|
.network_status(id)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.metrics
|
||||||
|
.data_links_established,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
a.agent.shutdown().await;
|
||||||
|
b.agent.shutdown().await;
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-core"
|
name = "tsunagi-core"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
|
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"
|
readme = "../../README.md"
|
||||||
keywords = ["mesh", "p2p", "iroh", "networking"]
|
keywords = ["mesh", "p2p", "iroh", "networking"]
|
||||||
|
|||||||
@@ -135,6 +135,10 @@ impl Inner {
|
|||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(interface) => {
|
Ok(interface) => {
|
||||||
|
self.adapter.exclude_interface(interface.name());
|
||||||
|
for carrier in &self.config.carriers {
|
||||||
|
carrier.on_interface_ready(interface.name());
|
||||||
|
}
|
||||||
let _ = self.interface.set(Arc::new(interface));
|
let _ = self.interface.set(Arc::new(interface));
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
@@ -188,14 +192,13 @@ impl PacketCarrier for Carrier {
|
|||||||
let Some(inner) = self.0.upgrade() else {
|
let Some(inner) = self.0.upgrade() else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
// Offered to each protocol in turn. With one configured this is a
|
// Every routed IP packet enters the same internal cipher, whatever
|
||||||
// single call; the shape is what allows several to be live at once,
|
// physical carrier currently supplies the logical peer link.
|
||||||
// each carrying the peers it has a link to.
|
|
||||||
inner
|
inner
|
||||||
.config
|
.config
|
||||||
.plugins
|
.tunnel
|
||||||
.iter()
|
.as_ref()
|
||||||
.any(|plugin| plugin.carry(route.network, route.peer, packet.clone()))
|
.is_some_and(|tunnel| tunnel.carry(route.network, route.peer, packet))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,21 +216,6 @@ impl PacketSink for Sink {
|
|||||||
let Some(inner) = self.0.upgrade() else {
|
let Some(inner) = self.0.upgrade() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
if let Some(payload) = crate::dataplane::transport::health::ip_payload(&packet) {
|
|
||||||
if let Some(header) = crate::overlay::IpHeader::parse(&packet)
|
|
||||||
&& let (std::net::IpAddr::V4(source), std::net::IpAddr::V4(destination)) =
|
|
||||||
(header.source(), header.destination())
|
|
||||||
&& inner.routes.may_send_from(network, peer, source)
|
|
||||||
&& inner.routes.is_local_destination(network, destination)
|
|
||||||
&& let Some(handle) = inner.networks.read().await.get(&network)
|
|
||||||
{
|
|
||||||
let _ = handle.commands.try_send(NetCommand::HealthProbe {
|
|
||||||
peer,
|
|
||||||
packet: bytes::Bytes::copy_from_slice(payload),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let Some(interface) = inner.interface.get() else {
|
let Some(interface) = inner.interface.get() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -301,7 +289,7 @@ impl TransportContext for TransportCtx {
|
|||||||
}
|
}
|
||||||
inner
|
inner
|
||||||
.config
|
.config
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.any(|plugin| plugin.protocol_id() == protocol)
|
.any(|plugin| plugin.protocol_id() == protocol)
|
||||||
})
|
})
|
||||||
@@ -309,6 +297,28 @@ impl TransportContext for TransportCtx {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Agent {
|
impl Agent {
|
||||||
|
/// Atomically saves or removes a version-checked shared VIP draft.
|
||||||
|
/// Every authenticated network member may edit any service.
|
||||||
|
pub async fn save_vip(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
config: crate::vip::VipConfig,
|
||||||
|
expected: Option<String>,
|
||||||
|
delete: bool,
|
||||||
|
) -> Result<Vec<crate::vip::VipStatus>> {
|
||||||
|
let (reply, receive) = oneshot::channel();
|
||||||
|
self.command(
|
||||||
|
network,
|
||||||
|
NetCommand::SaveVip {
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
reply,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
receive.await.map_err(|_| Error::Stopped)?
|
||||||
|
}
|
||||||
/// Retires one offline member's observed claim without revoking membership.
|
/// Retires one offline member's observed claim without revoking membership.
|
||||||
/// Every member has this right. The version must still match the selection.
|
/// Every member has this right. The version must still match the selection.
|
||||||
pub async fn forget_node(
|
pub async fn forget_node(
|
||||||
@@ -337,20 +347,23 @@ impl Agent {
|
|||||||
.unwrap_or_else(|| {
|
.unwrap_or_else(|| {
|
||||||
self.inner
|
self.inner
|
||||||
.config
|
.config
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.map(|p| p.protocol_id().to_owned())
|
.map(|p| p.protocol_id().to_owned())
|
||||||
.collect()
|
.collect()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn selected_plugins(&self, protocols: &[String]) -> Vec<crate::dataplane::SharedPlugin> {
|
fn selected_carriers(
|
||||||
|
&self,
|
||||||
|
protocols: &[String],
|
||||||
|
) -> Vec<crate::dataplane::transport::SharedCarrier> {
|
||||||
protocols
|
protocols
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|name| {
|
.filter_map(|name| {
|
||||||
self.inner
|
self.inner
|
||||||
.config
|
.config
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.find(|p| p.protocol_id() == name)
|
.find(|p| p.protocol_id() == name)
|
||||||
.cloned()
|
.cloned()
|
||||||
@@ -366,7 +379,7 @@ impl Agent {
|
|||||||
if !self
|
if !self
|
||||||
.inner
|
.inner
|
||||||
.config
|
.config
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.any(|p| p.protocol_id() == name)
|
.any(|p| p.protocol_id() == name)
|
||||||
{
|
{
|
||||||
@@ -407,7 +420,7 @@ impl Agent {
|
|||||||
if let Some(protocols) = &config.default_protocols {
|
if let Some(protocols) = &config.default_protocols {
|
||||||
crate::dataplane::validate_protocols(protocols, config.limits.max_capabilities)?;
|
crate::dataplane::validate_protocols(protocols, config.limits.max_capabilities)?;
|
||||||
for name in protocols {
|
for name in protocols {
|
||||||
if !config.plugins.iter().any(|p| p.protocol_id() == name) {
|
if !config.carriers.iter().any(|p| p.protocol_id() == name) {
|
||||||
return Err(Error::InvalidProtocols(format!(
|
return Err(Error::InvalidProtocols(format!(
|
||||||
"this agent has no `{name}` plugin"
|
"this agent has no `{name}` plugin"
|
||||||
)));
|
)));
|
||||||
@@ -486,7 +499,7 @@ impl Agent {
|
|||||||
// Plugins get a handle to ask for re-announcements and report errors.
|
// Plugins get a handle to ask for re-announcements and report errors.
|
||||||
// A bounded queue keeps a noisy plugin from growing memory without
|
// A bounded queue keeps a noisy plugin from growing memory without
|
||||||
// bound; overflow drops the request rather than stalling the plugin.
|
// bound; overflow drops the request rather than stalling the plugin.
|
||||||
if !inner.config.plugins.is_empty() {
|
if !inner.config.carriers.is_empty() || inner.config.tunnel.is_some() {
|
||||||
let (plugin_tx, plugin_rx) = mpsc::channel(64);
|
let (plugin_tx, plugin_rx) = mpsc::channel(64);
|
||||||
let sink = inner
|
let sink = inner
|
||||||
.config
|
.config
|
||||||
@@ -494,8 +507,8 @@ impl Agent {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|_| Arc::new(Sink(Arc::downgrade(&inner))) as Arc<dyn PacketSink>);
|
.map(|_| Arc::new(Sink(Arc::downgrade(&inner))) as Arc<dyn PacketSink>);
|
||||||
let context = PluginContext::new(plugin_tx, inner.identity.endpoint_id(), sink);
|
let context = PluginContext::new(plugin_tx, inner.identity.endpoint_id(), sink);
|
||||||
for plugin in &inner.config.plugins {
|
if let Some(tunnel) = &inner.config.tunnel {
|
||||||
plugin.attach(context.clone());
|
tunnel.attach(context);
|
||||||
}
|
}
|
||||||
let task = tokio::spawn(plugin_request_loop(Arc::downgrade(&inner), plugin_rx));
|
let task = tokio::spawn(plugin_request_loop(Arc::downgrade(&inner), plugin_rx));
|
||||||
if let Ok(mut guard) = inner.plugin_task.lock() {
|
if let Ok(mut guard) = inner.plugin_task.lock() {
|
||||||
@@ -916,6 +929,34 @@ impl Agent {
|
|||||||
.storage
|
.storage
|
||||||
.retirements(network_id, self.inner.limits.max_retirements)
|
.retirements(network_id, self.inner.limits.max_retirements)
|
||||||
.await?;
|
.await?;
|
||||||
|
let vip_entries = self
|
||||||
|
.inner
|
||||||
|
.storage
|
||||||
|
.vip_fields(
|
||||||
|
network_id,
|
||||||
|
self.inner
|
||||||
|
.limits
|
||||||
|
.max_vips
|
||||||
|
.saturating_mul(self.inner.limits.max_vip_fields)
|
||||||
|
.saturating_add(self.inner.limits.max_vip_tombstones),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let mut vips = crate::vip::VipSet::default();
|
||||||
|
for id in vip_entries
|
||||||
|
.iter()
|
||||||
|
.map(|e| e.vip.clone())
|
||||||
|
.collect::<std::collections::BTreeSet<_>>()
|
||||||
|
{
|
||||||
|
vips.merge(
|
||||||
|
network_id,
|
||||||
|
vip_entries
|
||||||
|
.iter()
|
||||||
|
.filter(|e| e.vip == id)
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
|
&self.inner.limits,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
let range = self.desired_range(network_id).await?;
|
let range = self.desired_range(network_id).await?;
|
||||||
if let Some(range) = range {
|
if let Some(range) = range {
|
||||||
let conflicts = self.inner.routes.overlapping_networks(network_id, range);
|
let conflicts = self.inner.routes.overlapping_networks(network_id, range);
|
||||||
@@ -958,7 +999,7 @@ impl Agent {
|
|||||||
let broadcast = stored.as_ref().is_none_or(|stored| stored.broadcast);
|
let broadcast = stored.as_ref().is_none_or(|stored| stored.broadcast);
|
||||||
let protocols =
|
let protocols =
|
||||||
self.effective_protocols(stored.as_ref().and_then(|s| s.protocols.as_ref()));
|
self.effective_protocols(stored.as_ref().and_then(|s| s.protocols.as_ref()));
|
||||||
let plugins = self.selected_plugins(&protocols);
|
let plugins = self.selected_carriers(&protocols);
|
||||||
if !plugins.is_empty() {
|
if !plugins.is_empty() {
|
||||||
self.inner.ensure_interface().await;
|
self.inner.ensure_interface().await;
|
||||||
}
|
}
|
||||||
@@ -968,6 +1009,7 @@ impl Agent {
|
|||||||
.and_then(|stored| stored.exit_via)
|
.and_then(|stored| stored.exit_via)
|
||||||
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok());
|
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok());
|
||||||
let handle = network::spawn(RuntimeParams {
|
let handle = network::spawn(RuntimeParams {
|
||||||
|
vips,
|
||||||
retirements,
|
retirements,
|
||||||
broadcast,
|
broadcast,
|
||||||
exit_offer,
|
exit_offer,
|
||||||
@@ -981,8 +1023,9 @@ impl Agent {
|
|||||||
discovery,
|
discovery,
|
||||||
discovery_interval: self.inner.config.discovery_interval,
|
discovery_interval: self.inner.config.discovery_interval,
|
||||||
discovery_policy: self.inner.config.discovery_policy.clone(),
|
discovery_policy: self.inner.config.discovery_policy.clone(),
|
||||||
available_plugins: self.inner.config.plugins.clone(),
|
available_carriers: self.inner.config.carriers.clone(),
|
||||||
plugins: plugins.clone(),
|
tunnel: self.inner.config.tunnel.clone(),
|
||||||
|
carriers: plugins.clone(),
|
||||||
routes: Arc::clone(&self.inner.routes),
|
routes: Arc::clone(&self.inner.routes),
|
||||||
interface: self.inner.interface.get().cloned(),
|
interface: self.inner.interface.get().cloned(),
|
||||||
hostname: self.inner.read_hostname(),
|
hostname: self.inner.read_hostname(),
|
||||||
@@ -999,6 +1042,9 @@ impl Agent {
|
|||||||
for plugin in &plugins {
|
for plugin in &plugins {
|
||||||
plugin.on_network_activated(network_id);
|
plugin.on_network_activated(network_id);
|
||||||
}
|
}
|
||||||
|
if let Some(tunnel) = &self.inner.config.tunnel {
|
||||||
|
tunnel.on_network_activated(network_id);
|
||||||
|
}
|
||||||
|
|
||||||
let _ = self.inner.events.send(Event::NetworkActivated {
|
let _ = self.inner.events.send(Event::NetworkActivated {
|
||||||
network: network_id,
|
network: network_id,
|
||||||
@@ -1043,9 +1089,12 @@ impl Agent {
|
|||||||
.ok_or(Error::NetworkNotActive(network_id))?
|
.ok_or(Error::NetworkNotActive(network_id))?
|
||||||
};
|
};
|
||||||
handle.stop().await;
|
handle.stop().await;
|
||||||
for plugin in &self.inner.config.plugins {
|
for plugin in &self.inner.config.carriers {
|
||||||
plugin.on_network_deactivated(network_id);
|
plugin.on_network_deactivated(network_id);
|
||||||
}
|
}
|
||||||
|
if let Some(tunnel) = &self.inner.config.tunnel {
|
||||||
|
tunnel.on_network_deactivated(network_id);
|
||||||
|
}
|
||||||
// The network's addresses come off the interface; the interface
|
// The network's addresses come off the interface; the interface
|
||||||
// itself stays, because the agent owns it and other networks may
|
// itself stays, because the agent owns it and other networks may
|
||||||
// still be using it.
|
// still be using it.
|
||||||
@@ -1078,9 +1127,12 @@ impl Agent {
|
|||||||
self.stop_network_locked(network_id).await?;
|
self.stop_network_locked(network_id).await?;
|
||||||
}
|
}
|
||||||
self.inner.storage.remove_network(network_id).await?;
|
self.inner.storage.remove_network(network_id).await?;
|
||||||
for plugin in &self.inner.config.plugins {
|
for plugin in &self.inner.config.carriers {
|
||||||
plugin.on_network_forgotten(network_id);
|
plugin.on_network_forgotten(network_id);
|
||||||
}
|
}
|
||||||
|
if let Some(tunnel) = &self.inner.config.tunnel {
|
||||||
|
tunnel.on_network_forgotten(network_id).await;
|
||||||
|
}
|
||||||
self.resume_networks_locked().await
|
self.resume_networks_locked().await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1127,6 +1179,19 @@ impl Agent {
|
|||||||
self.inner.networks.read().await.contains_key(&network_id)
|
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.
|
/// Lists configured networks and whether each is running.
|
||||||
pub async fn list_networks(&self) -> Result<Vec<ConfiguredNetwork>> {
|
pub async fn list_networks(&self) -> Result<Vec<ConfiguredNetwork>> {
|
||||||
let active: Vec<NetworkId> = self.inner.networks.read().await.keys().copied().collect();
|
let active: Vec<NetworkId> = self.inner.networks.read().await.keys().copied().collect();
|
||||||
@@ -1215,7 +1280,43 @@ impl Agent {
|
|||||||
let keys = NetworkKeys::derive(&stored.name, &stored.secret);
|
let keys = NetworkKeys::derive(&stored.name, &stored.secret);
|
||||||
let range = self.desired_range(stored.network_id).await?;
|
let range = self.desired_range(stored.network_id).await?;
|
||||||
let range_conflicts = self.range_conflicts(stored.network_id, range).await?;
|
let range_conflicts = self.range_conflicts(stored.network_id, range).await?;
|
||||||
|
let fields = self
|
||||||
|
.inner
|
||||||
|
.storage
|
||||||
|
.vip_fields(
|
||||||
|
stored.network_id,
|
||||||
|
self.inner
|
||||||
|
.limits
|
||||||
|
.max_vips
|
||||||
|
.saturating_mul(self.inner.limits.max_vip_fields)
|
||||||
|
.saturating_add(self.inner.limits.max_vip_tombstones),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let mut service_state = crate::vip::VipSet::default();
|
||||||
|
for id in fields
|
||||||
|
.iter()
|
||||||
|
.map(|e| e.vip.clone())
|
||||||
|
.collect::<std::collections::BTreeSet<_>>()
|
||||||
|
{
|
||||||
|
service_state.merge(
|
||||||
|
stored.network_id,
|
||||||
|
fields.iter().filter(|e| e.vip == id).cloned().collect(),
|
||||||
|
&self.inner.limits,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
let vips = service_state
|
||||||
|
.configs()
|
||||||
|
.into_iter()
|
||||||
|
.map(|config| crate::vip::VipStatus {
|
||||||
|
revision: service_state.revision(&config.id),
|
||||||
|
config,
|
||||||
|
address: None,
|
||||||
|
error: Some("network is inactive".into()),
|
||||||
|
listeners: vec![],
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
networks.push(NetworkStatus {
|
networks.push(NetworkStatus {
|
||||||
|
vips,
|
||||||
protocols: self.effective_protocols(stored.protocols.as_ref()),
|
protocols: self.effective_protocols(stored.protocols.as_ref()),
|
||||||
auto_start: stored.auto_start,
|
auto_start: stored.auto_start,
|
||||||
broadcast: stored.broadcast,
|
broadcast: stored.broadcast,
|
||||||
@@ -1336,7 +1437,7 @@ impl Agent {
|
|||||||
|
|
||||||
// Plugins remove whatever system objects they created. A plugin that
|
// Plugins remove whatever system objects they created. A plugin that
|
||||||
// misbehaves here must not hold up the agent, so this is bounded.
|
// misbehaves here must not hold up the agent, so this is bounded.
|
||||||
for plugin in &self.inner.config.plugins {
|
for plugin in &self.inner.config.carriers {
|
||||||
if tokio::time::timeout(PLUGIN_SHUTDOWN_GRACE, plugin.shutdown())
|
if tokio::time::timeout(PLUGIN_SHUTDOWN_GRACE, plugin.shutdown())
|
||||||
.await
|
.await
|
||||||
.is_err()
|
.is_err()
|
||||||
@@ -1348,6 +1449,14 @@ impl Agent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(tunnel) = &self.inner.config.tunnel
|
||||||
|
&& tokio::time::timeout(PLUGIN_SHUTDOWN_GRACE, tunnel.shutdown())
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
tracing::warn!("data encryption engine did not shut down in time");
|
||||||
|
}
|
||||||
|
|
||||||
// Release the directory so another instance can claim it right away.
|
// Release the directory so another instance can claim it right away.
|
||||||
self.inner.storage.release_ownership_lock();
|
self.inner.storage.release_ownership_lock();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use tokio::sync::{broadcast, mpsc, oneshot};
|
|||||||
use tokio::task::JoinHandle;
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
use crate::config::{DiscoveryPolicy, Limits, ReconnectPolicy};
|
use crate::config::{DiscoveryPolicy, Limits, ReconnectPolicy};
|
||||||
use crate::dataplane::transport::health::{HealthLink, ProbeRoute, Settings as HealthSettings};
|
use crate::dataplane::transport::health::{HealthLink, Settings as HealthSettings};
|
||||||
use crate::dataplane::transport::{InboundLink, PacketLink, PacketTransport, SharedLink};
|
use crate::dataplane::transport::{InboundLink, PacketLink, PacketTransport, SharedLink};
|
||||||
use crate::dataplane::{PluginCapability, SharedPlugin};
|
use crate::dataplane::{PluginCapability, SharedPlugin};
|
||||||
use crate::discovery::worker::DiscoveryWorker;
|
use crate::discovery::worker::DiscoveryWorker;
|
||||||
@@ -50,6 +50,12 @@ pub(crate) struct InboundSession {
|
|||||||
|
|
||||||
/// Commands accepted by a network runtime.
|
/// Commands accepted by a network runtime.
|
||||||
pub(crate) enum NetCommand {
|
pub(crate) enum NetCommand {
|
||||||
|
SaveVip {
|
||||||
|
config: crate::vip::VipConfig,
|
||||||
|
expected: Option<String>,
|
||||||
|
delete: bool,
|
||||||
|
reply: oneshot::Sender<Result<Vec<crate::vip::VipStatus>>>,
|
||||||
|
},
|
||||||
ForgetNode {
|
ForgetNode {
|
||||||
peer: EndpointId,
|
peer: EndpointId,
|
||||||
expected_version: u64,
|
expected_version: u64,
|
||||||
@@ -67,10 +73,6 @@ pub(crate) enum NetCommand {
|
|||||||
},
|
},
|
||||||
/// A peer opened a data plane link towards us.
|
/// A peer opened a data plane link towards us.
|
||||||
InboundLink(Box<InboundLink>),
|
InboundLink(Box<InboundLink>),
|
||||||
HealthProbe {
|
|
||||||
peer: EndpointId,
|
|
||||||
packet: bytes::Bytes,
|
|
||||||
},
|
|
||||||
Status {
|
Status {
|
||||||
reply: oneshot::Sender<Box<NetworkStatus>>,
|
reply: oneshot::Sender<Box<NetworkStatus>>,
|
||||||
},
|
},
|
||||||
@@ -125,6 +127,7 @@ pub(crate) enum NetCommand {
|
|||||||
impl std::fmt::Debug for NetCommand {
|
impl std::fmt::Debug for NetCommand {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
|
NetCommand::SaveVip { .. } => f.write_str("SaveVip"),
|
||||||
NetCommand::ForgetNode { peer, .. } => write!(f, "ForgetNode({peer})"),
|
NetCommand::ForgetNode { peer, .. } => write!(f, "ForgetNode({peer})"),
|
||||||
NetCommand::Inbound(_) => f.write_str("Inbound"),
|
NetCommand::Inbound(_) => f.write_str("Inbound"),
|
||||||
NetCommand::InboundLink(link) => write!(f, "InboundLink({})", link.protocol),
|
NetCommand::InboundLink(link) => write!(f, "InboundLink({})", link.protocol),
|
||||||
@@ -142,7 +145,6 @@ impl std::fmt::Debug for NetCommand {
|
|||||||
NetCommand::SetHostname(_) => f.write_str("SetHostname"),
|
NetCommand::SetHostname(_) => f.write_str("SetHostname"),
|
||||||
NetCommand::Release { .. } => f.write_str("Release"),
|
NetCommand::Release { .. } => f.write_str("Release"),
|
||||||
NetCommand::PluginError { protocol, .. } => write!(f, "PluginError({protocol})"),
|
NetCommand::PluginError { protocol, .. } => write!(f, "PluginError({protocol})"),
|
||||||
NetCommand::HealthProbe { peer, .. } => write!(f, "HealthProbe({})", peer.fmt_short()),
|
|
||||||
NetCommand::ProtocolFailure { peer, protocol, .. } => {
|
NetCommand::ProtocolFailure { peer, protocol, .. } => {
|
||||||
write!(f, "ProtocolFailure({}, {protocol})", peer.fmt_short())
|
write!(f, "ProtocolFailure({}, {protocol})", peer.fmt_short())
|
||||||
}
|
}
|
||||||
@@ -170,6 +172,7 @@ impl NetworkHandle {
|
|||||||
|
|
||||||
/// Everything a network runtime needs to run.
|
/// Everything a network runtime needs to run.
|
||||||
pub(crate) struct RuntimeParams {
|
pub(crate) struct RuntimeParams {
|
||||||
|
pub(crate) vips: crate::vip::VipSet,
|
||||||
pub(crate) retirements: Vec<SignedRetirement>,
|
pub(crate) retirements: Vec<SignedRetirement>,
|
||||||
pub(crate) broadcast: bool,
|
pub(crate) broadcast: bool,
|
||||||
/// This agent offers itself as an exit node here.
|
/// This agent offers itself as an exit node here.
|
||||||
@@ -185,8 +188,9 @@ pub(crate) struct RuntimeParams {
|
|||||||
pub(crate) discovery: Option<Arc<dyn NetworkDiscovery>>,
|
pub(crate) discovery: Option<Arc<dyn NetworkDiscovery>>,
|
||||||
pub(crate) discovery_interval: Duration,
|
pub(crate) discovery_interval: Duration,
|
||||||
pub(crate) discovery_policy: DiscoveryPolicy,
|
pub(crate) discovery_policy: DiscoveryPolicy,
|
||||||
pub(crate) plugins: Vec<SharedPlugin>,
|
pub(crate) carriers: Vec<crate::dataplane::transport::SharedCarrier>,
|
||||||
pub(crate) available_plugins: Vec<SharedPlugin>,
|
pub(crate) available_carriers: Vec<crate::dataplane::transport::SharedCarrier>,
|
||||||
|
pub(crate) tunnel: Option<SharedPlugin>,
|
||||||
/// Who holds which overlay address, shared with every other network.
|
/// Who holds which overlay address, shared with every other network.
|
||||||
pub(crate) routes: Arc<crate::overlay::RoutingTable>,
|
pub(crate) routes: Arc<crate::overlay::RoutingTable>,
|
||||||
/// The one interface, when the agent has one.
|
/// The one interface, when the agent has one.
|
||||||
@@ -376,6 +380,8 @@ struct Runtime {
|
|||||||
/// Snapshots received while dispatching, handled on the next loop pass.
|
/// Snapshots received while dispatching, handled on the next loop pass.
|
||||||
pending_state: Vec<(EndpointId, Vec<SignedRecord>)>,
|
pending_state: Vec<(EndpointId, Vec<SignedRecord>)>,
|
||||||
pending_retirements: Vec<(EndpointId, Vec<SignedRetirement>)>,
|
pending_retirements: Vec<(EndpointId, Vec<SignedRetirement>)>,
|
||||||
|
pending_vips: Vec<Vec<crate::vip::VipEntry>>,
|
||||||
|
vip_cursor: HashMap<EndpointId, usize>,
|
||||||
/// Next cleanup batch per live session; prevents queue pressure starving a suffix.
|
/// Next cleanup batch per live session; prevents queue pressure starving a suffix.
|
||||||
retirement_cursor: HashMap<EndpointId, usize>,
|
retirement_cursor: HashMap<EndpointId, usize>,
|
||||||
/// The highest version this agent has ever published for this network.
|
/// The highest version this agent has ever published for this network.
|
||||||
@@ -388,6 +394,8 @@ struct Runtime {
|
|||||||
/// The last hostname each peer announced, kept across restarts so a
|
/// The last hostname each peer announced, kept across restarts so a
|
||||||
/// member that is away can still be called by name.
|
/// member that is away can still be called by name.
|
||||||
known_hostnames: HashMap<EndpointId, String>,
|
known_hostnames: HashMap<EndpointId, String>,
|
||||||
|
data_errors: HashMap<EndpointId, String>,
|
||||||
|
tunnel_errors: HashMap<EndpointId, String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Runtime {
|
impl Runtime {
|
||||||
@@ -408,7 +416,7 @@ impl Runtime {
|
|||||||
// preferred when a neighbour can be reached over more than one.
|
// preferred when a neighbour can be reached over more than one.
|
||||||
hub.set_priority(
|
hub.set_priority(
|
||||||
params
|
params
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.map(|plugin| plugin.protocol_id().to_string())
|
.map(|plugin| plugin.protocol_id().to_string())
|
||||||
.collect(),
|
.collect(),
|
||||||
@@ -461,11 +469,15 @@ impl Runtime {
|
|||||||
state: StateSet::new(),
|
state: StateSet::new(),
|
||||||
pending_state: Vec::new(),
|
pending_state: Vec::new(),
|
||||||
pending_retirements: Vec::new(),
|
pending_retirements: Vec::new(),
|
||||||
|
pending_vips: Vec::new(),
|
||||||
|
vip_cursor: HashMap::new(),
|
||||||
retirement_cursor: HashMap::new(),
|
retirement_cursor: HashMap::new(),
|
||||||
own_version: 0,
|
own_version: 0,
|
||||||
exit_via_was_online: false,
|
exit_via_was_online: false,
|
||||||
announced_exit: false,
|
announced_exit: false,
|
||||||
known_hostnames: HashMap::new(),
|
known_hostnames: HashMap::new(),
|
||||||
|
data_errors: HashMap::new(),
|
||||||
|
tunnel_errors: HashMap::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -561,6 +573,15 @@ impl Runtime {
|
|||||||
|
|
||||||
async fn handle_command(&mut self, command: NetCommand) {
|
async fn handle_command(&mut self, command: NetCommand) {
|
||||||
match command {
|
match command {
|
||||||
|
NetCommand::SaveVip {
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
reply,
|
||||||
|
} => {
|
||||||
|
let result = self.save_vip(config, expected, delete).await;
|
||||||
|
let _ = reply.send(result);
|
||||||
|
}
|
||||||
NetCommand::ForgetNode {
|
NetCommand::ForgetNode {
|
||||||
peer,
|
peer,
|
||||||
expected_version,
|
expected_version,
|
||||||
@@ -608,7 +629,7 @@ impl Runtime {
|
|||||||
self.params.interface = interface;
|
self.params.interface = interface;
|
||||||
let current: Vec<_> = self
|
let current: Vec<_> = self
|
||||||
.params
|
.params
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.map(|p| p.protocol_id().to_owned())
|
.map(|p| p.protocol_id().to_owned())
|
||||||
.collect();
|
.collect();
|
||||||
@@ -617,22 +638,22 @@ impl Runtime {
|
|||||||
for peer in &peers {
|
for peer in &peers {
|
||||||
self.reset_peer_data(*peer, "local protocol selection changed");
|
self.reset_peer_data(*peer, "local protocol selection changed");
|
||||||
}
|
}
|
||||||
for plugin in &self.params.plugins {
|
for plugin in &self.params.carriers {
|
||||||
if !protocols.iter().any(|name| name == plugin.protocol_id()) {
|
if !protocols.iter().any(|name| name == plugin.protocol_id()) {
|
||||||
plugin.on_network_deactivated(self.network_id);
|
plugin.on_network_deactivated(self.network_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.params.plugins = protocols
|
self.params.carriers = protocols
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|name| {
|
.filter_map(|name| {
|
||||||
self.params
|
self.params
|
||||||
.available_plugins
|
.available_carriers
|
||||||
.iter()
|
.iter()
|
||||||
.find(|p| p.protocol_id() == name)
|
.find(|p| p.protocol_id() == name)
|
||||||
.cloned()
|
.cloned()
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
for plugin in &self.params.plugins {
|
for plugin in &self.params.carriers {
|
||||||
if !current.iter().any(|name| name == plugin.protocol_id()) {
|
if !current.iter().any(|name| name == plugin.protocol_id()) {
|
||||||
plugin.on_network_activated(self.network_id);
|
plugin.on_network_activated(self.network_id);
|
||||||
}
|
}
|
||||||
@@ -732,13 +753,6 @@ impl Runtime {
|
|||||||
reason,
|
reason,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
NetCommand::HealthProbe { peer, packet } => {
|
|
||||||
for ((p, _), link) in &self.links {
|
|
||||||
if *p == peer {
|
|
||||||
link.receive_probe(packet.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
NetCommand::ProtocolFailure {
|
NetCommand::ProtocolFailure {
|
||||||
peer,
|
peer,
|
||||||
protocol,
|
protocol,
|
||||||
@@ -830,6 +844,7 @@ impl Runtime {
|
|||||||
// the check is a comparison when nothing has changed.
|
// the check is a comparison when nothing has changed.
|
||||||
self.ensure_own_claim().await;
|
self.ensure_own_claim().await;
|
||||||
self.report_hostname_taken();
|
self.report_hostname_taken();
|
||||||
|
self.broadcast_vips();
|
||||||
self.broadcast_retirements();
|
self.broadcast_retirements();
|
||||||
// The same timer repairs the relay picture: reachability is soft
|
// The same timer repairs the relay picture: reachability is soft
|
||||||
// state, repeated while it holds and forgotten when it stops.
|
// state, repeated while it holds and forgotten when it stops.
|
||||||
@@ -910,7 +925,8 @@ impl Runtime {
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_candidate(&mut self, candidate: Candidate) {
|
fn add_candidate(&mut self, mut candidate: Candidate) {
|
||||||
|
candidate.addr = self.underlay_addr(candidate.addr);
|
||||||
let peer = candidate.endpoint_id();
|
let peer = candidate.endpoint_id();
|
||||||
if peer == self.local_id {
|
if peer == self.local_id {
|
||||||
return;
|
return;
|
||||||
@@ -1104,7 +1120,8 @@ impl Runtime {
|
|||||||
.own_record_version(self.network_id, self.local_id)
|
.own_record_version(self.network_id, self.local_id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or(0)
|
.unwrap_or(0)
|
||||||
.max(self.state.authored_version(&self.local_id));
|
.max(self.state.authored_version(&self.local_id))
|
||||||
|
.max(self.params.vips.authored_version(self.local_id));
|
||||||
for (id, hostname) in self
|
for (id, hostname) in self
|
||||||
.params
|
.params
|
||||||
.storage
|
.storage
|
||||||
@@ -1178,11 +1195,26 @@ impl Runtime {
|
|||||||
match self.state.address_of(&self.local_id) {
|
match self.state.address_of(&self.local_id) {
|
||||||
Some(mine) if range.contains(mine) => Some(mine),
|
Some(mine) if range.contains(mine) => Some(mine),
|
||||||
_ => {
|
_ => {
|
||||||
let taken: std::collections::HashSet<std::net::Ipv4Addr> = holders
|
let mut taken: std::collections::HashSet<std::net::Ipv4Addr> = holders
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(_, holder)| **holder != self.local_id)
|
.filter(|(_, holder)| **holder != self.local_id)
|
||||||
.map(|(address, _)| *address)
|
.map(|(address, _)| *address)
|
||||||
.collect();
|
.collect();
|
||||||
|
for vip in self.params.vips.views(
|
||||||
|
Some(range),
|
||||||
|
taken.clone(),
|
||||||
|
&std::collections::BTreeSet::new(),
|
||||||
|
&self.params.limits,
|
||||||
|
) {
|
||||||
|
if let Some(address) = vip.address {
|
||||||
|
taken.insert(address);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for vip in self.params.routes.vips.statuses(self.network_id) {
|
||||||
|
if let Some(address) = vip.address {
|
||||||
|
taken.insert(address);
|
||||||
|
}
|
||||||
|
}
|
||||||
match allocate(
|
match allocate(
|
||||||
self.network_id,
|
self.network_id,
|
||||||
self.local_id,
|
self.local_id,
|
||||||
@@ -1460,8 +1492,188 @@ impl Runtime {
|
|||||||
self.broadcast_state();
|
self.broadcast_state();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn update_vips(&self) {
|
||||||
|
let taken = self.state.address_holders().into_keys().collect();
|
||||||
|
let names = self
|
||||||
|
.state
|
||||||
|
.active_records()
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|r| {
|
||||||
|
r.author_id()
|
||||||
|
.ok()
|
||||||
|
.and_then(|p| self.state.hostname_of(&p).map(str::to_owned))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let views =
|
||||||
|
self.params
|
||||||
|
.vips
|
||||||
|
.views(self.effective_range(), taken, &names, &self.params.limits);
|
||||||
|
let peers = self
|
||||||
|
.state
|
||||||
|
.address_holders()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(a, p)| (p, a, self.hub.reachable(p)))
|
||||||
|
.collect();
|
||||||
|
self.params.routes.vips.configure(
|
||||||
|
self.network_id,
|
||||||
|
self.local_id,
|
||||||
|
self.state.address_of(&self.local_id),
|
||||||
|
views,
|
||||||
|
peers,
|
||||||
|
&self.params.limits,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
async fn save_vip(
|
||||||
|
&mut self,
|
||||||
|
config: crate::vip::VipConfig,
|
||||||
|
expected: Option<String>,
|
||||||
|
delete: bool,
|
||||||
|
) -> Result<Vec<crate::vip::VipStatus>> {
|
||||||
|
if self.released || self.shutdown.is_triggered() {
|
||||||
|
return Err(Error::Stopped);
|
||||||
|
}
|
||||||
|
let version = self
|
||||||
|
.own_version
|
||||||
|
.checked_add(1)
|
||||||
|
.filter(|n| *n <= i64::MAX as u64)
|
||||||
|
.ok_or_else(|| crate::vip::invalid("author counter exhausted"))?;
|
||||||
|
let entries = if delete {
|
||||||
|
self.params.vips.delete(
|
||||||
|
self.network_id,
|
||||||
|
&self.params.device_secret,
|
||||||
|
version,
|
||||||
|
&config.id,
|
||||||
|
expected.as_deref().unwrap_or(""),
|
||||||
|
)?
|
||||||
|
} else {
|
||||||
|
self.params.vips.edit(
|
||||||
|
self.network_id,
|
||||||
|
&self.params.device_secret,
|
||||||
|
version,
|
||||||
|
&config,
|
||||||
|
expected.as_deref(),
|
||||||
|
&self.params.limits,
|
||||||
|
)?
|
||||||
|
};
|
||||||
|
let mut candidate = self.params.vips.clone();
|
||||||
|
candidate.merge(self.network_id, entries, &self.params.limits)?;
|
||||||
|
if !delete {
|
||||||
|
let duplicate = candidate
|
||||||
|
.configs()
|
||||||
|
.iter()
|
||||||
|
.any(|v| v.id != config.id && v.name == config.name)
|
||||||
|
|| self.state.active_records().iter().any(|r| {
|
||||||
|
r.author_id().ok().and_then(|p| self.state.hostname_of(&p))
|
||||||
|
== Some(config.name.as_str())
|
||||||
|
});
|
||||||
|
if duplicate {
|
||||||
|
return Err(crate::vip::invalid(
|
||||||
|
"VIP name is already used by a node or another VIP",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let snapshot = candidate.entries(&config.id);
|
||||||
|
self.validate_vip_frame(&snapshot)?;
|
||||||
|
self.params
|
||||||
|
.storage
|
||||||
|
.put_vip_fields(
|
||||||
|
self.network_id,
|
||||||
|
snapshot.clone(),
|
||||||
|
Some((*self.local_id.as_bytes(), version)),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
self.own_version = version;
|
||||||
|
self.params.vips = candidate;
|
||||||
|
self.update_vips();
|
||||||
|
let peers: Vec<_> = self.sessions.keys().copied().collect();
|
||||||
|
for peer in peers {
|
||||||
|
let _ = self.send_to(
|
||||||
|
peer,
|
||||||
|
ControlMessage::Vips {
|
||||||
|
entries: snapshot.clone(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(self.params.routes.vips.statuses(self.network_id))
|
||||||
|
}
|
||||||
|
async fn receive_vips(&mut self, entries: Vec<crate::vip::VipEntry>) -> Result<()> {
|
||||||
|
let Some(id) = entries.first().map(|e| e.vip.clone()) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
if entries.iter().any(|e| e.vip != id) {
|
||||||
|
return Err(crate::vip::invalid("VIP snapshot mixes service identities"));
|
||||||
|
}
|
||||||
|
let own_seen = entries
|
||||||
|
.iter()
|
||||||
|
.filter(|e| e.author == *self.local_id.as_bytes())
|
||||||
|
.map(|e| e.version)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0);
|
||||||
|
let mut candidate = self.params.vips.clone();
|
||||||
|
let changed = candidate.merge(self.network_id, entries, &self.params.limits)?;
|
||||||
|
if !changed && own_seen <= self.own_version {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let counter =
|
||||||
|
(own_seen > self.own_version).then_some((*self.local_id.as_bytes(), own_seen));
|
||||||
|
let snapshot = candidate.entries(&id);
|
||||||
|
self.validate_vip_frame(&snapshot)?;
|
||||||
|
self.params
|
||||||
|
.storage
|
||||||
|
.put_vip_fields(self.network_id, snapshot, counter)
|
||||||
|
.await?;
|
||||||
|
self.own_version = self.own_version.max(own_seen);
|
||||||
|
self.params.vips = candidate;
|
||||||
|
self.update_vips();
|
||||||
|
self.broadcast_vips();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn validate_vip_frame(&self, entries: &[crate::vip::VipEntry]) -> Result<()> {
|
||||||
|
let frame = Envelope {
|
||||||
|
network_id: *self.network_id.as_bytes(),
|
||||||
|
message: ControlMessage::Vips {
|
||||||
|
entries: entries.to_vec(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let bytes = encode(&frame).map_err(|e| crate::vip::invalid(e.to_string()))?;
|
||||||
|
if bytes.len() > self.params.limits.max_frame_len {
|
||||||
|
return Err(crate::vip::invalid(
|
||||||
|
"VIP snapshot exceeds the control frame limit",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn broadcast_vips(&mut self) {
|
||||||
|
let ids = self.params.vips.ids();
|
||||||
|
if ids.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let peers: Vec<_> = self.sessions.keys().copied().collect();
|
||||||
|
for peer in peers {
|
||||||
|
let start = self.vip_cursor.get(&peer).copied().unwrap_or(0) % ids.len();
|
||||||
|
for step in 0..ids.len() {
|
||||||
|
let index = (start + step) % ids.len();
|
||||||
|
let entries = self.params.vips.entries(&ids[index]);
|
||||||
|
if self
|
||||||
|
.send_to(peer, ControlMessage::Vips { entries })
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
self.vip_cursor.insert(peer, index);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
self.vip_cursor.insert(peer, (index + 1) % ids.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Handles snapshots collected while dispatching messages.
|
/// Handles snapshots collected while dispatching messages.
|
||||||
async fn drain_pending_state(&mut self) {
|
async fn drain_pending_state(&mut self) {
|
||||||
|
for entries in std::mem::take(&mut self.pending_vips) {
|
||||||
|
if let Err(err) = self.receive_vips(entries).await {
|
||||||
|
self.metrics.protocol_violations += 1;
|
||||||
|
tracing::warn!(%err,"rejecting VIP snapshot");
|
||||||
|
}
|
||||||
|
}
|
||||||
for (peer, markers) in std::mem::take(&mut self.pending_retirements) {
|
for (peer, markers) in std::mem::take(&mut self.pending_retirements) {
|
||||||
self.receive_retirements(peer, markers).await;
|
self.receive_retirements(peer, markers).await;
|
||||||
}
|
}
|
||||||
@@ -1473,6 +1685,7 @@ impl Runtime {
|
|||||||
|
|
||||||
/// Sends everything we know to every peer.
|
/// Sends everything we know to every peer.
|
||||||
fn broadcast_state(&mut self) {
|
fn broadcast_state(&mut self) {
|
||||||
|
self.broadcast_vips();
|
||||||
self.broadcast_retirements();
|
self.broadcast_retirements();
|
||||||
let mut records = self.state.records();
|
let mut records = self.state.records();
|
||||||
records.truncate(self.params.limits.max_state_records);
|
records.truncate(self.params.limits.max_state_records);
|
||||||
@@ -1671,8 +1884,9 @@ impl Runtime {
|
|||||||
self.params.range_changed.send_replace(());
|
self.params.range_changed.send_replace(());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for plugin in &self.params.plugins {
|
self.update_vips();
|
||||||
plugin.on_address_allocation(self.network_id, range, &allocations);
|
if let Some(tunnel) = &self.params.tunnel {
|
||||||
|
tunnel.on_address_allocation(self.network_id, range, &allocations);
|
||||||
}
|
}
|
||||||
if self.published_range != Some(range) {
|
if self.published_range != Some(range) {
|
||||||
self.published_range = Some(range);
|
self.published_range = Some(range);
|
||||||
@@ -1764,7 +1978,7 @@ impl Runtime {
|
|||||||
/// The protocols this agent speaks, with the version it speaks them at.
|
/// The protocols this agent speaks, with the version it speaks them at.
|
||||||
fn served_protocols(&self) -> Vec<(String, u16)> {
|
fn served_protocols(&self) -> Vec<(String, u16)> {
|
||||||
self.params
|
self.params
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.map(|plugin| (plugin.protocol_id().to_string(), plugin.protocol_version()))
|
.map(|plugin| (plugin.protocol_id().to_string(), plugin.protocol_version()))
|
||||||
.collect()
|
.collect()
|
||||||
@@ -1825,6 +2039,8 @@ impl Runtime {
|
|||||||
// reachable through somebody is decided below; the protocol's
|
// reachable through somebody is decided below; the protocol's
|
||||||
// link stays either way.
|
// link stays either way.
|
||||||
self.hub.clear_direct(peer, &protocol);
|
self.hub.clear_direct(peer, &protocol);
|
||||||
|
self.data_errors
|
||||||
|
.insert(peer, format!("{protocol}: {reason}"));
|
||||||
self.record_protocol_failure(peer, &protocol);
|
self.record_protocol_failure(peer, &protocol);
|
||||||
self.emit(Event::DataLinkDown {
|
self.emit(Event::DataLinkDown {
|
||||||
network: self.network_id,
|
network: self.network_id,
|
||||||
@@ -1949,6 +2165,7 @@ impl Runtime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let addr = self.underlay_addr(addr);
|
||||||
let fresh = !self.candidate_addrs.contains_key(&peer);
|
let fresh = !self.candidate_addrs.contains_key(&peer);
|
||||||
self.candidate_addrs
|
self.candidate_addrs
|
||||||
.entry(peer)
|
.entry(peer)
|
||||||
@@ -1964,6 +2181,10 @@ impl Runtime {
|
|||||||
learned
|
learned
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn underlay_addr(&self, addr: iroh::EndpointAddr) -> iroh::EndpointAddr {
|
||||||
|
without_overlay_addresses(addr, &self.params.routes.overlay_ranges())
|
||||||
|
}
|
||||||
|
|
||||||
/// Tells the peers it is talking to about the peers it knows.
|
/// Tells the peers it is talking to about the peers it knows.
|
||||||
///
|
///
|
||||||
/// A device told about one member ends up talking to all of them: a
|
/// A device told about one member ends up talking to all of them: a
|
||||||
@@ -2010,14 +2231,14 @@ impl Runtime {
|
|||||||
// other side's own discovery may be able to resolve it.
|
// other side's own discovery may be able to resolve it.
|
||||||
hints.push(crate::proto::message::PeerHint {
|
hints.push(crate::proto::message::PeerHint {
|
||||||
endpoint: *peer.as_bytes(),
|
endpoint: *peer.as_bytes(),
|
||||||
addrs: hint_addrs(addr),
|
addrs: hint_addrs(&self.underlay_addr(addr.clone())),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// This agent, too: it is the one member the others cannot be told
|
// This agent, too: it is the one member the others cannot be told
|
||||||
// about by anybody else.
|
// about by anybody else.
|
||||||
hints.push(crate::proto::message::PeerHint {
|
hints.push(crate::proto::message::PeerHint {
|
||||||
endpoint: *self.local_id.as_bytes(),
|
endpoint: *self.local_id.as_bytes(),
|
||||||
addrs: hint_addrs(&self.params.adapter.addr()),
|
addrs: hint_addrs(&self.underlay_addr(self.params.adapter.addr())),
|
||||||
});
|
});
|
||||||
hints.truncate(self.params.limits.max_state_records);
|
hints.truncate(self.params.limits.max_state_records);
|
||||||
if hints.is_empty() {
|
if hints.is_empty() {
|
||||||
@@ -2062,34 +2283,18 @@ impl Runtime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The protocol this agent and a member run their tunnel in, if they have
|
/// Matches the single internal encryption capability, independently of carrier policy.
|
||||||
/// one in common.
|
|
||||||
///
|
|
||||||
/// Both ends must name the same one without asking each other, and what
|
|
||||||
/// each side was configured to prefer can differ. So the member with the
|
|
||||||
/// lower id decides, by the order it announces its protocols in, and the
|
|
||||||
/// other side reads that order from the announcement it already has.
|
|
||||||
fn tunnel_protocol(&self, session: &Session) -> Option<String> {
|
fn tunnel_protocol(&self, session: &Session) -> Option<String> {
|
||||||
let usable = |ours: &[PluginCapability], theirs: &[PluginCapability], name: &str| {
|
let tunnel = self.params.tunnel.as_ref()?;
|
||||||
ours.iter().any(|capability| {
|
session
|
||||||
capability.enabled
|
.capabilities
|
||||||
&& capability.protocol == name
|
|
||||||
&& theirs.iter().any(|other| {
|
|
||||||
other.enabled
|
|
||||||
&& other.protocol == name
|
|
||||||
&& other.version == capability.version
|
|
||||||
})
|
|
||||||
})
|
|
||||||
};
|
|
||||||
let (decides, other) = if self.local_id.as_bytes() < session.peer.as_bytes() {
|
|
||||||
(&self.local_capabilities, &session.capabilities)
|
|
||||||
} else {
|
|
||||||
(&session.capabilities, &self.local_capabilities)
|
|
||||||
};
|
|
||||||
decides
|
|
||||||
.iter()
|
.iter()
|
||||||
.find(|capability| usable(decides, other, &capability.protocol))
|
.any(|cap| {
|
||||||
.map(|capability| capability.protocol.clone())
|
cap.enabled
|
||||||
|
&& cap.protocol == tunnel.protocol_id()
|
||||||
|
&& cap.version == tunnel.protocol_version()
|
||||||
|
})
|
||||||
|
.then(|| tunnel.protocol_id().to_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the graph off the packet path. Every remote row comes from that
|
/// Builds the graph off the packet path. Every remote row comes from that
|
||||||
@@ -2131,9 +2336,9 @@ impl Runtime {
|
|||||||
}
|
}
|
||||||
let Some(plugin) = self
|
let Some(plugin) = self
|
||||||
.params
|
.params
|
||||||
.plugins
|
.tunnel
|
||||||
.iter()
|
.as_ref()
|
||||||
.find(|plugin| plugin.protocol_id() == protocol)
|
.filter(|plugin| plugin.protocol_id() == protocol)
|
||||||
.cloned()
|
.cloned()
|
||||||
else {
|
else {
|
||||||
continue;
|
continue;
|
||||||
@@ -2154,6 +2359,7 @@ impl Runtime {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
self.update_vips();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_link_result(&mut self, outcome: LinkOutcome) {
|
fn handle_link_result(&mut self, outcome: LinkOutcome) {
|
||||||
@@ -2177,6 +2383,8 @@ impl Runtime {
|
|||||||
self.announce_reach(false);
|
self.announce_reach(false);
|
||||||
}
|
}
|
||||||
Err(reason) => {
|
Err(reason) => {
|
||||||
|
self.data_errors
|
||||||
|
.insert(outcome.peer, format!("{}: {reason}", outcome.protocol));
|
||||||
// A data plane that cannot be set up is reported, never fatal.
|
// A data plane that cannot be set up is reported, never fatal.
|
||||||
self.metrics.data_link_failures += 1;
|
self.metrics.data_link_failures += 1;
|
||||||
self.record_protocol_failure(outcome.peer, &outcome.protocol);
|
self.record_protocol_failure(outcome.peer, &outcome.protocol);
|
||||||
@@ -2235,7 +2443,7 @@ impl Runtime {
|
|||||||
link.close();
|
link.close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if !self.params.plugins.iter().any(|plugin| {
|
if !self.params.carriers.iter().any(|plugin| {
|
||||||
plugin.protocol_id() == protocol
|
plugin.protocol_id() == protocol
|
||||||
&& self.sessions.get(&peer).is_some_and(|s| {
|
&& self.sessions.get(&peer).is_some_and(|s| {
|
||||||
s.capabilities.iter().any(|c| {
|
s.capabilities.iter().any(|c| {
|
||||||
@@ -2249,6 +2457,7 @@ impl Runtime {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.data_errors.remove(&peer);
|
||||||
let key = (peer, protocol.clone());
|
let key = (peer, protocol.clone());
|
||||||
let settings = if self.local_id.as_bytes() < peer.as_bytes() {
|
let settings = if self.local_id.as_bytes() < peer.as_bytes() {
|
||||||
let settings = HealthSettings::fresh();
|
let settings = HealthSettings::fresh();
|
||||||
@@ -2265,21 +2474,7 @@ impl Runtime {
|
|||||||
} else {
|
} else {
|
||||||
self.pending_health.remove(&key)
|
self.pending_health.remove(&key)
|
||||||
};
|
};
|
||||||
let route = self
|
let link = HealthLink::new(link, self.local_id, settings);
|
||||||
.sessions
|
|
||||||
.get(&peer)
|
|
||||||
.and_then(|s| self.tunnel_protocol(s))
|
|
||||||
.and_then(|name| self.params.plugins.iter().find(|p| p.protocol_id() == name))
|
|
||||||
.map(|plugin| ProbeRoute {
|
|
||||||
plugin: plugin.clone(),
|
|
||||||
routes: self.params.routes.clone(),
|
|
||||||
network: self.network_id,
|
|
||||||
peer,
|
|
||||||
max_probe_size: self.params.interface.as_ref().map_or(540, |interface| {
|
|
||||||
(interface.mtu() as usize).saturating_sub(36)
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
let link = HealthLink::new(link, self.local_id, settings, route);
|
|
||||||
let path = link.path_description();
|
let path = link.path_description();
|
||||||
let max_datagram = link.max_datagram_size();
|
let max_datagram = link.max_datagram_size();
|
||||||
if let Some(old) = self.links.insert(key, Arc::clone(&link)) {
|
if let Some(old) = self.links.insert(key, Arc::clone(&link)) {
|
||||||
@@ -2303,14 +2498,21 @@ impl Runtime {
|
|||||||
|
|
||||||
/// Drops every link to a peer.
|
/// Drops every link to a peer.
|
||||||
fn drop_links_for(&mut self, peer: EndpointId) {
|
fn drop_links_for(&mut self, peer: EndpointId) {
|
||||||
|
self.tunnel_errors.remove(&peer);
|
||||||
self.retirement_cursor.remove(&peer);
|
self.retirement_cursor.remove(&peer);
|
||||||
|
self.vip_cursor.remove(&peer);
|
||||||
self.reset_peer_data(peer, "peer session ended");
|
self.reset_peer_data(peer, "peer session ended");
|
||||||
|
if let Some(tunnel) = &self.params.tunnel {
|
||||||
|
tunnel.on_peer_gone(self.network_id, peer);
|
||||||
|
}
|
||||||
|
self.hub.clear_peer_links(peer);
|
||||||
self.hub.remove_peer(peer);
|
self.hub.remove_peer(peer);
|
||||||
self.reachable.remove(&peer);
|
self.reachable.remove(&peer);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Retire only the data plane; authenticated membership and topology remain.
|
/// Retire only the data plane; authenticated membership and topology remain.
|
||||||
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
|
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
|
||||||
|
self.data_errors.remove(&peer);
|
||||||
self.link_attempts.retain(|(id, _), _| *id != peer);
|
self.link_attempts.retain(|(id, _), _| *id != peer);
|
||||||
self.opening.retain(|(id, _)| *id != peer);
|
self.opening.retain(|(id, _)| *id != peer);
|
||||||
self.link_tasks.retain(|(id, _), task| {
|
self.link_tasks.retain(|(id, _), task| {
|
||||||
@@ -2321,7 +2523,6 @@ impl Runtime {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
self.hub.clear_peer_links(peer);
|
|
||||||
let keys: Vec<_> = self
|
let keys: Vec<_> = self
|
||||||
.links
|
.links
|
||||||
.keys()
|
.keys()
|
||||||
@@ -2332,6 +2533,7 @@ impl Runtime {
|
|||||||
if let Some(link) = self.links.remove(&key) {
|
if let Some(link) = self.links.remove(&key) {
|
||||||
link.close();
|
link.close();
|
||||||
}
|
}
|
||||||
|
self.hub.clear_direct(peer, &key.1);
|
||||||
self.emit(Event::DataLinkDown {
|
self.emit(Event::DataLinkDown {
|
||||||
network: self.network_id,
|
network: self.network_id,
|
||||||
peer,
|
peer,
|
||||||
@@ -2342,7 +2544,7 @@ impl Runtime {
|
|||||||
self.protocol_dial_states.retain(|(id, _), _| *id != peer);
|
self.protocol_dial_states.retain(|(id, _), _| *id != peer);
|
||||||
self.last_failed_protocol.remove(&peer);
|
self.last_failed_protocol.remove(&peer);
|
||||||
self.pending_health.retain(|(id, _), _| *id != peer);
|
self.pending_health.retain(|(id, _), _| *id != peer);
|
||||||
for plugin in &self.params.plugins {
|
for plugin in &self.params.carriers {
|
||||||
plugin.on_peer_gone(self.network_id, peer);
|
plugin.on_peer_gone(self.network_id, peer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2428,11 +2630,27 @@ impl Runtime {
|
|||||||
fn local_announcement(&mut self) -> Announcement {
|
fn local_announcement(&mut self) -> Announcement {
|
||||||
let mut capabilities = Vec::new();
|
let mut capabilities = Vec::new();
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
for plugin in &self.params.plugins {
|
let sources = self
|
||||||
match plugin.local_capability(self.network_id) {
|
.params
|
||||||
Ok(Some(capability)) => capabilities.push(capability),
|
.carriers
|
||||||
|
.iter()
|
||||||
|
.map(|carrier| {
|
||||||
|
(
|
||||||
|
carrier.protocol_id().to_owned(),
|
||||||
|
carrier.local_capability(self.network_id),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.chain(self.params.tunnel.iter().map(|tunnel| {
|
||||||
|
(
|
||||||
|
tunnel.protocol_id().to_owned(),
|
||||||
|
tunnel.local_capability(self.network_id),
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
for (protocol, result) in sources {
|
||||||
|
match result {
|
||||||
|
Ok(Some(cap)) => capabilities.push(cap),
|
||||||
Ok(None) => {}
|
Ok(None) => {}
|
||||||
Err(err) => errors.push((plugin.protocol_id().to_string(), err.to_string())),
|
Err(err) => errors.push((protocol, err.to_string())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (protocol, reason) in errors {
|
for (protocol, reason) in errors {
|
||||||
@@ -2664,6 +2882,7 @@ impl Runtime {
|
|||||||
tracing::debug!(%err, "could not queue pong");
|
tracing::debug!(%err, "could not queue pong");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ControlMessage::Vips { entries } => self.pending_vips.push(entries.clone()),
|
||||||
ControlMessage::State { records } => {
|
ControlMessage::State { records } => {
|
||||||
self.pending_state.push((peer, records.clone()));
|
self.pending_state.push((peer, records.clone()));
|
||||||
}
|
}
|
||||||
@@ -2699,34 +2918,57 @@ impl Runtime {
|
|||||||
|
|
||||||
fn dispatch_capabilities(&mut self, peer: EndpointId, capabilities: &[PluginCapability]) {
|
fn dispatch_capabilities(&mut self, peer: EndpointId, capabilities: &[PluginCapability]) {
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
for capability in capabilities {
|
for cap in capabilities {
|
||||||
for plugin in &self.params.plugins {
|
let carriers = self
|
||||||
if plugin.protocol_id() != capability.protocol {
|
.params
|
||||||
continue;
|
.carriers
|
||||||
|
.iter()
|
||||||
|
.filter(|carrier| carrier.protocol_id() == cap.protocol)
|
||||||
|
.map(|carrier| {
|
||||||
|
(
|
||||||
|
carrier.protocol_version(),
|
||||||
|
if carrier.protocol_version() == cap.version {
|
||||||
|
carrier.on_peer_capability(self.network_id, peer, cap)
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
});
|
||||||
|
let tunnel = self
|
||||||
|
.params
|
||||||
|
.tunnel
|
||||||
|
.iter()
|
||||||
|
.filter(|tunnel| tunnel.protocol_id() == cap.protocol)
|
||||||
|
.map(|tunnel| {
|
||||||
|
(
|
||||||
|
tunnel.protocol_version(),
|
||||||
|
if tunnel.protocol_version() == cap.version {
|
||||||
|
tunnel.on_peer_capability(self.network_id, peer, cap)
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
});
|
||||||
|
for (version, result) in carriers.chain(tunnel) {
|
||||||
|
if version != cap.version {
|
||||||
|
if self.reported_mismatch.insert((peer, cap.protocol.clone())) {
|
||||||
|
errors.push((cap.protocol.clone(), format!("peer speaks {} version {} and this build speaks {version}; update both agents; control plane is unaffected", cap.protocol, cap.version)));
|
||||||
}
|
}
|
||||||
if plugin.protocol_version() != capability.version {
|
} else {
|
||||||
// Said once per peer and protocol. A version that will
|
let is_tunnel = self
|
||||||
// not match this build will not match it on the next
|
.params
|
||||||
// announcement either, and repeating it every round
|
.tunnel
|
||||||
// would bury everything else.
|
.as_ref()
|
||||||
let key = (peer, capability.protocol.clone());
|
.is_some_and(|t| t.protocol_id() == cap.protocol);
|
||||||
if self.reported_mismatch.insert(key) {
|
if let Err(err) = result {
|
||||||
errors.push((
|
if is_tunnel {
|
||||||
capability.protocol.clone(),
|
self.tunnel_errors
|
||||||
format!(
|
.insert(peer, format!("encrypted data channel: {err}"));
|
||||||
"peer speaks {} version {} and this build speaks {}, so there \
|
|
||||||
is no data plane with it; the control plane is unaffected",
|
|
||||||
capability.protocol,
|
|
||||||
capability.version,
|
|
||||||
plugin.protocol_version()
|
|
||||||
),
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
continue;
|
errors.push((cap.protocol.clone(), err.to_string()));
|
||||||
|
} else if is_tunnel {
|
||||||
|
self.tunnel_errors.remove(&peer);
|
||||||
}
|
}
|
||||||
// The core hands the opaque payload over without interpreting it.
|
|
||||||
if let Err(err) = plugin.on_peer_capability(self.network_id, peer, capability) {
|
|
||||||
errors.push((plugin.protocol_id().to_string(), err.to_string()));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2805,6 +3047,58 @@ impl Runtime {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn data_error(&self, session: &Session) -> Option<String> {
|
||||||
|
if self.params.carriers.is_empty() {
|
||||||
|
return Some("data transports disabled locally".into());
|
||||||
|
}
|
||||||
|
if self.params.tunnel.is_some() && self.tunnel_protocol(session).is_none() {
|
||||||
|
return Some(
|
||||||
|
"peer has no compatible encrypted data channel; update both agents".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(reason) = self.tunnel_errors.get(&session.peer) {
|
||||||
|
return Some(reason.clone());
|
||||||
|
}
|
||||||
|
if !matches!(self.data_path(session.peer), DataPath::None) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let served = self.served_protocols();
|
||||||
|
if !served.iter().any(|(name, version)| {
|
||||||
|
session
|
||||||
|
.capabilities
|
||||||
|
.iter()
|
||||||
|
.any(|cap| cap.enabled && cap.protocol == *name && cap.version == *version)
|
||||||
|
}) {
|
||||||
|
let local = served
|
||||||
|
.iter()
|
||||||
|
.map(|(name, _)| name.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",");
|
||||||
|
let remote = session
|
||||||
|
.capabilities
|
||||||
|
.iter()
|
||||||
|
.filter(|cap| {
|
||||||
|
cap.enabled
|
||||||
|
&& self
|
||||||
|
.params
|
||||||
|
.tunnel
|
||||||
|
.as_ref()
|
||||||
|
.is_none_or(|t| t.protocol_id() != cap.protocol)
|
||||||
|
})
|
||||||
|
.map(|cap| cap.protocol.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",");
|
||||||
|
return Some(format!(
|
||||||
|
"no common external transport (local: {local}; peer: {})",
|
||||||
|
if remote.is_empty() { "none" } else { &remote }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
self.data_errors
|
||||||
|
.get(&session.peer)
|
||||||
|
.cloned()
|
||||||
|
.or_else(|| Some("establishing external data transport".into()))
|
||||||
|
}
|
||||||
|
|
||||||
fn status(&self) -> NetworkStatus {
|
fn status(&self) -> NetworkStatus {
|
||||||
let served = self.served_protocols();
|
let served = self.served_protocols();
|
||||||
let mut peers: Vec<PeerStatus> = self
|
let mut peers: Vec<PeerStatus> = self
|
||||||
@@ -2832,6 +3126,7 @@ impl Runtime {
|
|||||||
})
|
})
|
||||||
.map(|capability| capability.protocol.clone())
|
.map(|capability| capability.protocol.clone())
|
||||||
.collect(),
|
.collect(),
|
||||||
|
data_error: self.data_error(session),
|
||||||
capabilities: session.capabilities.clone(),
|
capabilities: session.capabilities.clone(),
|
||||||
connected_for: session.established.elapsed(),
|
connected_for: session.established.elapsed(),
|
||||||
paths: snapshot.paths,
|
paths: snapshot.paths,
|
||||||
@@ -2891,9 +3186,10 @@ impl Runtime {
|
|||||||
members.dedup_by(|a, b| a.endpoint_id == b.endpoint_id);
|
members.dedup_by(|a, b| a.endpoint_id == b.endpoint_id);
|
||||||
|
|
||||||
NetworkStatus {
|
NetworkStatus {
|
||||||
|
vips: self.params.routes.vips.statuses(self.network_id),
|
||||||
protocols: self
|
protocols: self
|
||||||
.params
|
.params
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.map(|p| p.protocol_id().to_owned())
|
.map(|p| p.protocol_id().to_owned())
|
||||||
.collect(),
|
.collect(),
|
||||||
@@ -3041,10 +3337,43 @@ fn merge_addr(existing: &mut iroh::EndpointAddr, incoming: &iroh::EndpointAddr)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Introductions and discovery candidates are underlay addresses. An overlay
|
||||||
|
/// address here would send the tunnel's own transport recursively through itself.
|
||||||
|
fn without_overlay_addresses(
|
||||||
|
mut addr: iroh::EndpointAddr,
|
||||||
|
ranges: &[Ipv4Range],
|
||||||
|
) -> iroh::EndpointAddr {
|
||||||
|
addr.addrs.retain(|address| match address {
|
||||||
|
iroh::TransportAddr::Ip(socket) => match socket.ip() {
|
||||||
|
std::net::IpAddr::V4(ip) => !ranges.iter().any(|range| range.contains(ip)),
|
||||||
|
std::net::IpAddr::V6(_) => true,
|
||||||
|
},
|
||||||
|
_ => true,
|
||||||
|
});
|
||||||
|
addr
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn underlay_hints_exclude_overlay_subnets_but_preserve_lan_and_relay_candidates() {
|
||||||
|
let peer = crate::identity::DeviceIdentity::generate().endpoint_id();
|
||||||
|
let overlay = "10.13.37.99:1234".parse().unwrap();
|
||||||
|
let lan = "192.168.1.5:1234".parse().unwrap();
|
||||||
|
let relay: iroh::RelayUrl = "https://relay.example.com".parse().unwrap();
|
||||||
|
let addr = iroh::EndpointAddr::new(peer)
|
||||||
|
.with_ip_addr(overlay)
|
||||||
|
.with_ip_addr(lan)
|
||||||
|
.with_relay_url(relay.clone());
|
||||||
|
let filtered = without_overlay_addresses(addr, &[crate::state::DEFAULT_IPV4_RANGE]);
|
||||||
|
assert_eq!(filtered.ip_addrs().copied().collect::<Vec<_>>(), vec![lan]);
|
||||||
|
assert!(filtered.addrs.contains(&iroh::TransportAddr::Relay(relay)));
|
||||||
|
assert_eq!(filtered.id, peer);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_data_link_backoff_progression() {
|
fn test_data_link_backoff_progression() {
|
||||||
assert_eq!(data_link_backoff(0), Duration::ZERO);
|
assert_eq!(data_link_backoff(0), Duration::ZERO);
|
||||||
|
|||||||
@@ -158,6 +158,8 @@ pub struct PeerStatus {
|
|||||||
pub protocols: Vec<String>,
|
pub protocols: Vec<String>,
|
||||||
/// Capabilities the peer announced. Payloads stay opaque.
|
/// Capabilities the peer announced. Payloads stay opaque.
|
||||||
pub capabilities: Vec<PluginCapability>,
|
pub capabilities: Vec<PluginCapability>,
|
||||||
|
/// Why no data route is available, when known.
|
||||||
|
pub data_error: Option<String>,
|
||||||
/// How long the session has been up.
|
/// How long the session has been up.
|
||||||
pub connected_for: Duration,
|
pub connected_for: Duration,
|
||||||
/// Verified paths of the underlying connection.
|
/// Verified paths of the underlying connection.
|
||||||
@@ -225,6 +227,8 @@ pub struct RangeConflict {
|
|||||||
/// Status of one network.
|
/// Status of one network.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct NetworkStatus {
|
pub struct NetworkStatus {
|
||||||
|
/// Shared service configuration with this client's routing observations.
|
||||||
|
pub vips: Vec<crate::vip::VipStatus>,
|
||||||
/// Enabled local data-plane protocols, in preference order.
|
/// Enabled local data-plane protocols, in preference order.
|
||||||
pub protocols: Vec<String>,
|
pub protocols: Vec<String>,
|
||||||
/// Whether this network is requested to start or resume automatically.
|
/// Whether this network is requested to start or resume automatically.
|
||||||
|
|||||||
@@ -158,6 +158,22 @@ pub enum TransportPolicy {
|
|||||||
/// object where that is possible (notably [`Limits::max_frame_len`]).
|
/// object where that is possible (notably [`Limits::max_frame_len`]).
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Limits {
|
pub struct Limits {
|
||||||
|
/// Maximum active VIP identities per network.
|
||||||
|
pub max_vips: usize,
|
||||||
|
/// Maximum permanent VIP deletion tombstones per network.
|
||||||
|
pub max_vip_tombstones: usize,
|
||||||
|
/// Maximum concurrent active TCP port checks across the agent.
|
||||||
|
pub max_vip_checks: usize,
|
||||||
|
/// Maximum signed fields per VIP, including removed fields.
|
||||||
|
pub max_vip_fields: usize,
|
||||||
|
/// Maximum listeners per VIP.
|
||||||
|
pub max_vip_listeners: usize,
|
||||||
|
/// Maximum backend endpoints per listener.
|
||||||
|
pub max_vip_backends: usize,
|
||||||
|
/// Maximum simultaneous local VIP flow bindings.
|
||||||
|
pub max_vip_flows: usize,
|
||||||
|
/// Maximum incomplete IPv4 datagrams per network in VIP reassembly.
|
||||||
|
pub max_vip_fragments: usize,
|
||||||
/// Largest accepted control frame payload, in bytes.
|
/// Largest accepted control frame payload, in bytes.
|
||||||
pub max_frame_len: usize,
|
pub max_frame_len: usize,
|
||||||
/// Largest accepted hostname, in bytes.
|
/// Largest accepted hostname, in bytes.
|
||||||
@@ -205,6 +221,14 @@ pub struct Limits {
|
|||||||
impl Default for Limits {
|
impl Default for Limits {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
max_vips: 64,
|
||||||
|
max_vip_tombstones: 1024,
|
||||||
|
max_vip_checks: 32,
|
||||||
|
max_vip_fields: 192,
|
||||||
|
max_vip_listeners: 16,
|
||||||
|
max_vip_backends: 32,
|
||||||
|
max_vip_flows: 4096,
|
||||||
|
max_vip_fragments: 64,
|
||||||
max_frame_len: 64 * 1024,
|
max_frame_len: 64 * 1024,
|
||||||
max_hostname_len: 255,
|
max_hostname_len: 255,
|
||||||
max_capabilities: 16,
|
max_capabilities: 16,
|
||||||
@@ -329,10 +353,12 @@ pub struct AgentConfig {
|
|||||||
pub limits: Limits,
|
pub limits: Limits,
|
||||||
/// Reconnect backoff policy.
|
/// Reconnect backoff policy.
|
||||||
pub reconnect: ReconnectPolicy,
|
pub reconnect: ReconnectPolicy,
|
||||||
/// IP plugins whose capabilities are announced and dispatched.
|
/// External data carriers whose capabilities are announced and dispatched.
|
||||||
pub plugins: Vec<SharedPlugin>,
|
pub carriers: Vec<crate::dataplane::transport::SharedCarrier>,
|
||||||
|
/// The single internal end-to-end engine, independent of carrier selection.
|
||||||
|
pub tunnel: Option<SharedPlugin>,
|
||||||
/// Initial ordered selection for networks without a saved override.
|
/// Initial ordered selection for networks without a saved override.
|
||||||
/// `None` enables all registered plugins; an empty list is control-only.
|
/// `None` enables all registered carriers; an empty list is control-only.
|
||||||
pub default_protocols: Option<Vec<String>>,
|
pub default_protocols: Option<Vec<String>>,
|
||||||
/// Custom packet transports registered per protocol.
|
/// Custom packet transports registered per protocol.
|
||||||
pub custom_transports:
|
pub custom_transports:
|
||||||
@@ -381,7 +407,8 @@ impl AgentConfig {
|
|||||||
discovery_interval: Duration::from_secs(5),
|
discovery_interval: Duration::from_secs(5),
|
||||||
limits: Limits::default(),
|
limits: Limits::default(),
|
||||||
reconnect: ReconnectPolicy::default(),
|
reconnect: ReconnectPolicy::default(),
|
||||||
plugins: Vec::new(),
|
carriers: Vec::new(),
|
||||||
|
tunnel: None,
|
||||||
default_protocols: None,
|
default_protocols: None,
|
||||||
custom_transports: std::collections::HashMap::new(),
|
custom_transports: std::collections::HashMap::new(),
|
||||||
tun_factory: None,
|
tun_factory: None,
|
||||||
@@ -465,9 +492,15 @@ impl AgentConfig {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registers an IP plugin.
|
/// Registers an external data carrier.
|
||||||
pub fn with_plugin(mut self, plugin: SharedPlugin) -> Self {
|
pub fn with_carrier(mut self, plugin: crate::dataplane::transport::SharedCarrier) -> Self {
|
||||||
self.plugins.push(plugin);
|
self.carriers.push(plugin);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs the internal encryption engine. It is never a selectable carrier.
|
||||||
|
pub fn with_tunnel(mut self, tunnel: SharedPlugin) -> Self {
|
||||||
|
self.tunnel = Some(tunnel);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -521,9 +554,9 @@ impl std::fmt::Debug for AgentConfig {
|
|||||||
.field("limits", &self.limits)
|
.field("limits", &self.limits)
|
||||||
.field("reconnect", &self.reconnect)
|
.field("reconnect", &self.reconnect)
|
||||||
.field(
|
.field(
|
||||||
"plugins",
|
"carriers",
|
||||||
&self
|
&self
|
||||||
.plugins
|
.carriers
|
||||||
.iter()
|
.iter()
|
||||||
.map(|p| p.protocol_id().to_string())
|
.map(|p| p.protocol_id().to_string())
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
|
|||||||
@@ -1,28 +1,19 @@
|
|||||||
//! Boundary between the control plane core and future IP plugins.
|
//! Boundaries between the agent, one IP encryption tunnel, and external carriers.
|
||||||
//!
|
//!
|
||||||
//! The data plane is where actual IP connectivity is created. WireGuard is the
|
//! The core moves bounded opaque capabilities without parsing cipher payloads.
|
||||||
//! first planned plugin; none is implemented here.
|
//! An [`IpPlugin`] sees routed IP packets and a logical [`PacketLink`] per peer;
|
||||||
|
//! it never learns reachability or the network secret. The agent configures one
|
||||||
|
//! such plugin. Built-in agents use the same internal WireGuard cipher for every
|
||||||
|
//! peer, regardless of which external transports carry the encrypted bytes.
|
||||||
//!
|
//!
|
||||||
//! Two rules shape this module:
|
//! [`transport::DataCarrier`] owns external capability negotiation and lifecycle.
|
||||||
//!
|
//! It sees reachability but never plaintext overlay packets. A relay forwards
|
||||||
//! 1. **The core never parses plugin payloads.** A [`PluginCapability`] carries
|
//! the encrypted inner bytes without entering an IP plugin or the TUN.
|
||||||
//! a protocol id, a version, an enabled flag and a bounded opaque blob. The
|
//! Data-plane failure never stops control sessions or discovery.
|
||||||
//! core transports the blob and hands it to the matching plugin. It does not
|
|
||||||
//! know what a WireGuard configuration looks like.
|
|
||||||
//! 2. **Plugin keys and lifecycle are separate from iroh identity and from the
|
|
||||||
//! network secret.** A plugin owns its own keys and its own system objects.
|
|
||||||
//!
|
|
||||||
//! An iroh address is *not* automatically a WireGuard address. A future plugin
|
|
||||||
//! is expected to gather its own reachability information and ship it through
|
|
||||||
//! the control plane as its announcement payload.
|
|
||||||
//!
|
|
||||||
//! A data plane failure never stops the daemon: errors returned here are
|
|
||||||
//! recorded and surfaced, the control plane keeps running.
|
|
||||||
|
|
||||||
pub mod relay;
|
pub mod relay;
|
||||||
pub mod routing;
|
pub mod routing;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
pub mod tunnel;
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -35,7 +26,6 @@ use crate::identity::NetworkId;
|
|||||||
pub use transport::{
|
pub use transport::{
|
||||||
MultiPacketTransport, PacketLink, PacketTransport, SharedLink, TransportError,
|
MultiPacketTransport, PacketLink, PacketTransport, SharedLink, TransportError,
|
||||||
};
|
};
|
||||||
pub use tunnel::{GenericTunnelPlugin, TunnelCodec};
|
|
||||||
|
|
||||||
/// Maximum length of a plugin protocol identifier.
|
/// Maximum length of a plugin protocol identifier.
|
||||||
pub const MAX_PROTOCOL_ID_LEN: usize = 32;
|
pub const MAX_PROTOCOL_ID_LEN: usize = 32;
|
||||||
@@ -438,7 +428,9 @@ pub trait IpPlugin: Send + Sync + std::fmt::Debug + 'static {
|
|||||||
/// Always preceded by [`IpPlugin::on_network_deactivated`], so this is
|
/// Always preceded by [`IpPlugin::on_network_deactivated`], so this is
|
||||||
/// only about what outlives a session. Defaulted to nothing, for a
|
/// only about what outlives a session. Defaulted to nothing, for a
|
||||||
/// plugin that stores nothing.
|
/// plugin that stores nothing.
|
||||||
fn on_network_forgotten(&self, _network: NetworkId) {}
|
fn on_network_forgotten(&self, _network: NetworkId) -> BoxFuture<'_, ()> {
|
||||||
|
Box::pin(async {})
|
||||||
|
}
|
||||||
|
|
||||||
/// Called once when the agent shuts down.
|
/// Called once when the agent shuts down.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
//! External link negotiation, deliberately separate from the IP encryption plugin.
|
||||||
|
use crate::dataplane::{PluginCapability, PluginError, ProtocolOption};
|
||||||
|
use crate::{BoxFuture, NetworkId};
|
||||||
|
use iroh::EndpointId;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
/// Capability and lifecycle of one external data carrier.
|
||||||
|
/// Only this layer sees reachability. It never receives plaintext overlay IP packets.
|
||||||
|
pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
|
||||||
|
/// External protocol identifier used in local policy and peer negotiation.
|
||||||
|
fn protocol_id(&self) -> &str;
|
||||||
|
/// Wire version, independent of software releases and the internal tunnel.
|
||||||
|
fn protocol_version(&self) -> u16;
|
||||||
|
/// Supported carrier settings.
|
||||||
|
fn options(&self) -> &'static [ProtocolOption] {
|
||||||
|
&[]
|
||||||
|
}
|
||||||
|
/// Bounded opaque reachability/negotiation capability for one network.
|
||||||
|
fn local_capability(&self, network: NetworkId)
|
||||||
|
-> Result<Option<PluginCapability>, PluginError>;
|
||||||
|
/// Installs a capability received through an authenticated membership session.
|
||||||
|
fn on_peer_capability(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: EndpointId,
|
||||||
|
capability: &PluginCapability,
|
||||||
|
) -> Result<(), PluginError>;
|
||||||
|
/// Supplies the actual owned interface name, including kernel-assigned names.
|
||||||
|
fn on_interface_ready(&self, _name: &str) {}
|
||||||
|
/// Activates this carrier for one local network.
|
||||||
|
fn on_network_activated(&self, _network: NetworkId) {}
|
||||||
|
/// Retires all negotiation and links for this member.
|
||||||
|
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId);
|
||||||
|
/// Retires this network's sockets and negotiations.
|
||||||
|
fn on_network_deactivated(&self, network: NetworkId);
|
||||||
|
/// Forgets durable carrier settings, if any.
|
||||||
|
fn on_network_forgotten(&self, _network: NetworkId) {}
|
||||||
|
/// Stops carrier tasks, with the agent enforcing a shutdown deadline.
|
||||||
|
fn shutdown(&self) -> BoxFuture<'_, ()> {
|
||||||
|
Box::pin(async {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// One shared carrier adapter.
|
||||||
|
pub type SharedCarrier = Arc<dyn DataCarrier>;
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
//! Authenticated probes of the actual data link, independent of control RTT.
|
//! Authenticated probes of the actual data link, independent of control RTT.
|
||||||
//! Keys are negotiated privately for each physical link. No fixed wire magic.
|
//! Keys are negotiated privately for each physical link. No fixed wire magic.
|
||||||
use super::{PacketLink, SharedLink, TransportError};
|
use super::{PacketLink, SharedLink, TransportError};
|
||||||
use crate::dataplane::SharedPlugin;
|
|
||||||
use crate::overlay::RoutingTable;
|
|
||||||
use crate::{BoxFuture, NetworkId};
|
use crate::{BoxFuture, NetworkId};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use hmac::{Hmac, KeyInit, Mac};
|
use hmac::{Hmac, KeyInit, Mac};
|
||||||
@@ -70,52 +68,8 @@ impl Samples {
|
|||||||
&& self.recent.iter().filter(|ok| !**ok).count() * 100 >= self.recent.len() * 60
|
&& self.recent.iter().filter(|ok| !**ok).count() * 100 >= self.recent.len() * 60
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// This prefix is inside end-to-end encryption. It never appears on the UDP wire.
|
|
||||||
const IP_MAGIC: &[u8; 16] = b"tsunagi-health01";
|
|
||||||
pub(crate) fn ip_payload(packet: &[u8]) -> Option<&[u8]> {
|
|
||||||
(packet.len() >= 36 && packet[0] == 0x45 && packet[9] == 253 && &packet[20..36] == IP_MAGIC)
|
|
||||||
.then(|| &packet[36..])
|
|
||||||
}
|
|
||||||
/// Inject probes through the same encrypted tunnel as application IP packets.
|
|
||||||
/// This matters for pure WG: raw UDP probes could pass DPI while WG is blocked.
|
|
||||||
pub(crate) struct ProbeRoute {
|
|
||||||
pub(crate) plugin: SharedPlugin,
|
|
||||||
pub(crate) routes: Arc<RoutingTable>,
|
|
||||||
pub(crate) network: NetworkId,
|
|
||||||
pub(crate) peer: EndpointId,
|
|
||||||
pub(crate) max_probe_size: usize,
|
|
||||||
}
|
|
||||||
impl ProbeRoute {
|
|
||||||
fn send(&self, payload: Bytes) -> bool {
|
|
||||||
let Some((source, destination)) = self.routes.probe_addresses(self.network, self.peer)
|
|
||||||
else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let mut packet = vec![0; 36];
|
|
||||||
packet[0] = 0x45;
|
|
||||||
packet[8] = 64;
|
|
||||||
packet[9] = 253;
|
|
||||||
packet[12..16].copy_from_slice(&source.octets());
|
|
||||||
packet[16..20].copy_from_slice(&destination.octets());
|
|
||||||
packet[20..36].copy_from_slice(IP_MAGIC);
|
|
||||||
let length = (packet.len() + payload.len()) as u16;
|
|
||||||
packet[2..4].copy_from_slice(&length.to_be_bytes());
|
|
||||||
let sum = packet[..20]
|
|
||||||
.as_chunks::<2>()
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.map(|b| u32::from(u16::from_be_bytes(*b)))
|
|
||||||
.sum::<u32>();
|
|
||||||
let sum = (sum & 0xffff) + (sum >> 16);
|
|
||||||
packet[10..12].copy_from_slice(&(!(sum as u16)).to_be_bytes());
|
|
||||||
packet.extend_from_slice(&payload);
|
|
||||||
self.plugin
|
|
||||||
.carry(self.network, self.peer, Bytes::from(packet))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// A monitored physical link. It forwards application bytes unchanged.
|
/// A monitored physical link. It forwards application bytes unchanged.
|
||||||
pub(crate) struct HealthLink {
|
pub(crate) struct HealthLink {
|
||||||
probes: mpsc::Sender<Bytes>,
|
|
||||||
raw: SharedLink,
|
raw: SharedLink,
|
||||||
settings: Mutex<Option<Settings>>,
|
settings: Mutex<Option<Settings>>,
|
||||||
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||||
@@ -136,17 +90,10 @@ fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl HealthLink {
|
impl HealthLink {
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(raw: SharedLink, local: EndpointId, settings: Option<Settings>) -> Arc<Self> {
|
||||||
raw: SharedLink,
|
|
||||||
local: EndpointId,
|
|
||||||
settings: Option<Settings>,
|
|
||||||
route: Option<ProbeRoute>,
|
|
||||||
) -> Arc<Self> {
|
|
||||||
let (tx, rx) = mpsc::channel(64);
|
let (tx, rx) = mpsc::channel(64);
|
||||||
let (probe_tx, mut probe_rx) = mpsc::channel(64);
|
|
||||||
let (stop, _) = watch::channel(false);
|
let (stop, _) = watch::channel(false);
|
||||||
let link = Arc::new(Self {
|
let link = Arc::new(Self {
|
||||||
probes: probe_tx,
|
|
||||||
raw: raw.clone(),
|
raw: raw.clone(),
|
||||||
settings: Mutex::new(settings),
|
settings: Mutex::new(settings),
|
||||||
rx: tokio::sync::Mutex::new(rx),
|
rx: tokio::sync::Mutex::new(rx),
|
||||||
@@ -174,29 +121,21 @@ impl HealthLink {
|
|||||||
*lock(&link.reason)=Some("data delivery checks: at least 60% loss over the last 20 probes".into());break;
|
*lock(&link.reason)=Some("data delivery checks: at least 60% loss over the last 20 probes".into());break;
|
||||||
}
|
}
|
||||||
sequence=sequence.wrapping_add(1);
|
sequence=sequence.wrapping_add(1);
|
||||||
let size=route.as_ref().map_or(raw.max_datagram_size(),|route|route.max_probe_size);
|
let size=raw.max_datagram_size();
|
||||||
let packet=probe(&settings,local,1,sequence,size.min(1000));
|
let packet=probe(&settings,local,1,sequence,size.min(1000));
|
||||||
if let Some(route)=&route { if route.send(packet) {samples.sent(sequence,now);} }
|
samples.sent(sequence,now);
|
||||||
else { let _=raw.send(packet); samples.sent(sequence,now); }
|
let _=raw.send(packet);
|
||||||
}
|
}
|
||||||
packet=raw.recv()=>{
|
packet=raw.recv()=>{
|
||||||
let Some(packet)=packet else{break;};let Some(link)=weak.upgrade()else{break;};
|
let Some(packet)=packet else{break;};let Some(link)=weak.upgrade()else{break;};
|
||||||
let settings=lock(&link.settings).clone();
|
let settings=lock(&link.settings).clone();
|
||||||
if route.is_none() && let Some(settings)=settings && packet.starts_with(&settings.marker) {
|
if let Some(settings)=settings && packet.starts_with(&settings.marker) {
|
||||||
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
|
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
|
||||||
if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));}
|
if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));}
|
||||||
else if kind==2 {samples.acknowledge(seq);}
|
else if kind==2 {samples.acknowledge(seq);}
|
||||||
}
|
}
|
||||||
} else {let _=tx.try_send(packet);}
|
} else {let _=tx.try_send(packet);}
|
||||||
}
|
}
|
||||||
packet=probe_rx.recv(),if route.is_some()=>{
|
|
||||||
let Some(packet)=packet else {break;};let Some(link)=weak.upgrade()else{break;};
|
|
||||||
let Some(settings)=lock(&link.settings).clone()else{continue;};
|
|
||||||
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
|
|
||||||
if kind==1 { if let Some(route)=&route { route.send(probe(&settings,local,2,seq,packet.len().min(route.max_probe_size))); } }
|
|
||||||
else if kind==2 {samples.acknowledge(seq);}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -207,9 +146,6 @@ impl HealthLink {
|
|||||||
});
|
});
|
||||||
link
|
link
|
||||||
}
|
}
|
||||||
pub(crate) fn receive_probe(&self, packet: Bytes) {
|
|
||||||
let _ = self.probes.try_send(packet);
|
|
||||||
}
|
|
||||||
pub(crate) fn configure(&self, settings: Settings) {
|
pub(crate) fn configure(&self, settings: Settings) {
|
||||||
*lock(&self.settings) = Some(settings);
|
*lock(&self.settings) = Some(settings);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,49 @@ use crate::proto::{read_frame, write_frame};
|
|||||||
use super::fragments::{self, Reassembler};
|
use super::fragments::{self, Reassembler};
|
||||||
use super::{InboundLink, PacketLink, PacketTransport, SharedLink, TransportError};
|
use super::{InboundLink, PacketLink, PacketTransport, SharedLink, TransportError};
|
||||||
|
|
||||||
|
/// QUIC carrier capability. Encryption of end-to-end IP packets is independent.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct IrohCarrier;
|
||||||
|
|
||||||
|
impl super::DataCarrier for IrohCarrier {
|
||||||
|
fn protocol_id(&self) -> &str {
|
||||||
|
"wg-quic"
|
||||||
|
}
|
||||||
|
fn protocol_version(&self) -> u16 {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
fn local_capability(
|
||||||
|
&self,
|
||||||
|
_: NetworkId,
|
||||||
|
) -> Result<Option<crate::dataplane::PluginCapability>, crate::dataplane::PluginError> {
|
||||||
|
Ok(Some(crate::dataplane::PluginCapability {
|
||||||
|
protocol: self.protocol_id().into(),
|
||||||
|
version: self.protocol_version(),
|
||||||
|
enabled: true,
|
||||||
|
data: Vec::new(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
fn on_peer_capability(
|
||||||
|
&self,
|
||||||
|
_: NetworkId,
|
||||||
|
_: EndpointId,
|
||||||
|
capability: &crate::dataplane::PluginCapability,
|
||||||
|
) -> Result<(), crate::dataplane::PluginError> {
|
||||||
|
if capability.protocol != self.protocol_id()
|
||||||
|
|| capability.version != self.protocol_version()
|
||||||
|
|| !capability.enabled
|
||||||
|
|| !capability.data.is_empty()
|
||||||
|
{
|
||||||
|
return Err(crate::dataplane::PluginError::Rejected(
|
||||||
|
"unsupported QUIC carrier capability".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn on_peer_gone(&self, _: NetworkId, _: EndpointId) {}
|
||||||
|
fn on_network_deactivated(&self, _: NetworkId) {}
|
||||||
|
}
|
||||||
|
|
||||||
/// What the iroh transport needs from the agent.
|
/// What the iroh transport needs from the agent.
|
||||||
///
|
///
|
||||||
/// Implemented by the agent, which is the only thing that knows which networks
|
/// Implemented by the agent, which is the only thing that knows which networks
|
||||||
@@ -190,6 +233,10 @@ impl PacketLink for IrohLink {
|
|||||||
self.conn.close_reason().is_some()
|
self.conn.close_reason().is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn failure_reason(&self) -> Option<String> {
|
||||||
|
self.conn.close_reason().map(|reason| reason.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
fn path_description(&self) -> String {
|
fn path_description(&self) -> String {
|
||||||
// Report what iroh actually knows, never a guess.
|
// Report what iroh actually knows, never a guess.
|
||||||
let snapshot = crate::net::snapshot_connection(&self.conn);
|
let snapshot = crate::net::snapshot_connection(&self.conn);
|
||||||
@@ -264,7 +311,8 @@ impl IrohTransport {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let serves = self.lookup.serves(outcome.network_id, &open.protocol).await;
|
let serves = open.protocol == "wg-quic"
|
||||||
|
&& self.lookup.serves(outcome.network_id, &open.protocol).await;
|
||||||
if open.max_datagram == 0 || conn.max_datagram_size().is_none() {
|
if open.max_datagram == 0 || conn.max_datagram_size().is_none() {
|
||||||
return Err(TransportError::Other(
|
return Err(TransportError::Other(
|
||||||
"data channel has no datagram support".into(),
|
"data channel has no datagram support".into(),
|
||||||
@@ -325,6 +373,12 @@ impl PacketTransport for IrohTransport {
|
|||||||
"data channel protocol id is out of bounds".into(),
|
"data channel protocol id is out of bounds".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
// This default must never impersonate a missing native carrier.
|
||||||
|
if protocol != "wg-quic" {
|
||||||
|
return Err(TransportError::Declined(format!(
|
||||||
|
"no native `{protocol}` data transport registered"
|
||||||
|
)));
|
||||||
|
}
|
||||||
let keys = self
|
let keys = self
|
||||||
.lookup
|
.lookup
|
||||||
.snapshot()
|
.snapshot()
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ mod fragments;
|
|||||||
pub(crate) mod health;
|
pub(crate) mod health;
|
||||||
pub mod iroh_link;
|
pub mod iroh_link;
|
||||||
|
|
||||||
|
pub mod carrier;
|
||||||
|
pub use carrier::{DataCarrier, SharedCarrier};
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
|||||||
@@ -1,380 +0,0 @@
|
|||||||
//! Generic harness for IP tunnel plugins.
|
|
||||||
//!
|
|
||||||
//! Implementing [`super::IpPlugin`] directly requires managing per-peer background
|
|
||||||
//! tasks, synchronization, packet queues, and graceful shutdown.
|
|
||||||
//!
|
|
||||||
//! [`TunnelCodec`] provides a simplified interface where a plugin author only
|
|
||||||
//! defines cryptographic transformation and handshake payloads.
|
|
||||||
//! [`GenericTunnelPlugin`] adapts any [`TunnelCodec`] into a full [`super::IpPlugin`].
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
use std::sync::{Arc, Mutex, RwLock};
|
|
||||||
|
|
||||||
use bytes::Bytes;
|
|
||||||
use iroh::EndpointId;
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
|
|
||||||
use super::{IpPlugin, PluginCapability, PluginContext, PluginError, ProtocolOption, SharedLink};
|
|
||||||
use crate::BoxFuture;
|
|
||||||
use crate::identity::NetworkId;
|
|
||||||
|
|
||||||
/// The simplified contract for an IP tunnel protocol implementation.
|
|
||||||
///
|
|
||||||
/// Implementors only handle key announcements, link lifecycle events,
|
|
||||||
/// and packet encrypt/decrypt. Concurrency and task management are handled
|
|
||||||
/// by [`GenericTunnelPlugin`].
|
|
||||||
pub trait TunnelCodec: Send + Sync + 'static {
|
|
||||||
/// Protocol identifier, e.g. `tcp-tls`.
|
|
||||||
fn protocol_id(&self) -> &str;
|
|
||||||
|
|
||||||
/// Protocol wire version.
|
|
||||||
fn protocol_version(&self) -> u16;
|
|
||||||
|
|
||||||
/// Options accepted by the protocol.
|
|
||||||
fn options(&self) -> &'static [ProtocolOption] {
|
|
||||||
&[]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates local capability announcement data for a network.
|
|
||||||
fn local_capability_data(&self, network: NetworkId) -> Result<Vec<u8>, PluginError>;
|
|
||||||
|
|
||||||
/// Handles a peer's announced capability payload.
|
|
||||||
fn on_peer_capability_data(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<(), PluginError>;
|
|
||||||
|
|
||||||
/// Called when an authenticated link to a peer is established.
|
|
||||||
fn on_peer_link_up(&self, network: NetworkId, peer: EndpointId, link: &SharedLink) {
|
|
||||||
let _ = (network, peer, link);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Called when a peer goes away.
|
|
||||||
fn on_peer_down(&self, network: NetworkId, peer: EndpointId) {
|
|
||||||
let _ = (network, peer);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encrypts an outbound IP packet into a payload to send over the link.
|
|
||||||
fn encrypt(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
packet: &[u8],
|
|
||||||
) -> Result<Bytes, PluginError>;
|
|
||||||
|
|
||||||
/// Decrypts an inbound payload from the link into an IP packet.
|
|
||||||
fn decrypt(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
payload: &[u8],
|
|
||||||
) -> Result<Bytes, PluginError>;
|
|
||||||
|
|
||||||
/// Called during shutdown.
|
|
||||||
fn shutdown<'a>(&'a self) -> BoxFuture<'a, ()> {
|
|
||||||
Box::pin(async {})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TunnelPeerState {
|
|
||||||
link: SharedLink,
|
|
||||||
tx_packets: AtomicU64,
|
|
||||||
rx_packets: AtomicU64,
|
|
||||||
tx_bytes: AtomicU64,
|
|
||||||
rx_bytes: AtomicU64,
|
|
||||||
dropped: AtomicU64,
|
|
||||||
established_at: std::time::Instant,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Statistics and status for one active peer in [`GenericTunnelPlugin`].
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct TunnelPeerReport {
|
|
||||||
/// Peer endpoint identity.
|
|
||||||
pub peer: EndpointId,
|
|
||||||
/// Protocol identifier.
|
|
||||||
pub protocol: String,
|
|
||||||
/// Human-readable path description.
|
|
||||||
pub path: String,
|
|
||||||
/// Packets successfully encrypted and sent.
|
|
||||||
pub tx_packets: u64,
|
|
||||||
/// Packets successfully received and decrypted.
|
|
||||||
pub rx_packets: u64,
|
|
||||||
/// Plaintext bytes successfully encrypted and sent.
|
|
||||||
pub tx_bytes: u64,
|
|
||||||
/// Plaintext bytes successfully received and decrypted.
|
|
||||||
pub rx_bytes: u64,
|
|
||||||
/// Packets dropped due to encryption/decryption/send failures.
|
|
||||||
pub dropped: u64,
|
|
||||||
/// Uptime in seconds since the data link was established.
|
|
||||||
pub uptime_secs: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generic wrapper that turns a [`TunnelCodec`] into a full [`IpPlugin`].
|
|
||||||
pub struct GenericTunnelPlugin<C: TunnelCodec> {
|
|
||||||
codec: Arc<C>,
|
|
||||||
context: Mutex<Option<PluginContext>>,
|
|
||||||
links: RwLock<HashMap<(NetworkId, EndpointId), Arc<TunnelPeerState>>>,
|
|
||||||
tasks: Mutex<HashMap<(NetworkId, EndpointId), JoinHandle<()>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C: TunnelCodec> GenericTunnelPlugin<C> {
|
|
||||||
/// Wraps `codec` into an [`IpPlugin`].
|
|
||||||
pub fn new(codec: C) -> Self {
|
|
||||||
Self {
|
|
||||||
codec: Arc::new(codec),
|
|
||||||
context: Mutex::new(None),
|
|
||||||
links: RwLock::new(HashMap::new()),
|
|
||||||
tasks: Mutex::new(HashMap::new()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a reference to the underlying codec.
|
|
||||||
pub fn codec(&self) -> &C {
|
|
||||||
&self.codec
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the active peers with established data links for a network.
|
|
||||||
pub fn active_peers(&self, network: NetworkId) -> Vec<TunnelPeerReport> {
|
|
||||||
let guard = match self.links.read() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
guard
|
|
||||||
.iter()
|
|
||||||
.filter(|((net, _), _)| *net == network)
|
|
||||||
.map(|((_, peer), state)| TunnelPeerReport {
|
|
||||||
peer: *peer,
|
|
||||||
protocol: self.codec.protocol_id().to_string(),
|
|
||||||
path: state.link.path_description(),
|
|
||||||
tx_packets: state.tx_packets.load(Ordering::Relaxed),
|
|
||||||
rx_packets: state.rx_packets.load(Ordering::Relaxed),
|
|
||||||
tx_bytes: state.tx_bytes.load(Ordering::Relaxed),
|
|
||||||
rx_bytes: state.rx_bytes.load(Ordering::Relaxed),
|
|
||||||
dropped: state.dropped.load(Ordering::Relaxed),
|
|
||||||
uptime_secs: state.established_at.elapsed().as_secs(),
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C: TunnelCodec> std::fmt::Debug for GenericTunnelPlugin<C> {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.debug_struct("GenericTunnelPlugin")
|
|
||||||
.field("protocol_id", &self.codec.protocol_id())
|
|
||||||
.field("protocol_version", &self.codec.protocol_version())
|
|
||||||
.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C: TunnelCodec> IpPlugin for GenericTunnelPlugin<C> {
|
|
||||||
fn protocol_id(&self) -> &str {
|
|
||||||
self.codec.protocol_id()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn protocol_version(&self) -> u16 {
|
|
||||||
self.codec.protocol_version()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn options(&self) -> &'static [ProtocolOption] {
|
|
||||||
self.codec.options()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn attach(&self, context: PluginContext) {
|
|
||||||
if let Ok(mut guard) = self.context.lock() {
|
|
||||||
*guard = Some(context);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn local_capability(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
) -> Result<Option<PluginCapability>, PluginError> {
|
|
||||||
let data = self.codec.local_capability_data(network)?;
|
|
||||||
Ok(Some(PluginCapability {
|
|
||||||
protocol: self.codec.protocol_id().to_string(),
|
|
||||||
version: self.codec.protocol_version(),
|
|
||||||
enabled: true,
|
|
||||||
data,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_peer_capability(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
capability: &PluginCapability,
|
|
||||||
) -> Result<(), PluginError> {
|
|
||||||
if capability.protocol != self.codec.protocol_id() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
self.codec
|
|
||||||
.on_peer_capability_data(network, peer, &capability.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn carry(&self, network: NetworkId, peer: EndpointId, packet: bytes::Bytes) -> bool {
|
|
||||||
let state = {
|
|
||||||
let guard = match self.links.read() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
guard.get(&(network, peer)).cloned()
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(state) = state else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
match self.codec.encrypt(network, peer, &packet) {
|
|
||||||
Ok(ciphertext) => {
|
|
||||||
if state.link.send(ciphertext).is_ok() {
|
|
||||||
state.tx_packets.fetch_add(1, Ordering::Relaxed);
|
|
||||||
state
|
|
||||||
.tx_bytes
|
|
||||||
.fetch_add(packet.len() as u64, Ordering::Relaxed);
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
state.dropped.fetch_add(1, Ordering::Relaxed);
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
state.dropped.fetch_add(1, Ordering::Relaxed);
|
|
||||||
tracing::debug!(%peer, %err, "tunnel encrypt failed");
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_peer_link(&self, network: NetworkId, peer: EndpointId, link: SharedLink) {
|
|
||||||
let state = Arc::new(TunnelPeerState {
|
|
||||||
link: Arc::clone(&link),
|
|
||||||
tx_packets: AtomicU64::new(0),
|
|
||||||
rx_packets: AtomicU64::new(0),
|
|
||||||
tx_bytes: AtomicU64::new(0),
|
|
||||||
rx_bytes: AtomicU64::new(0),
|
|
||||||
dropped: AtomicU64::new(0),
|
|
||||||
established_at: std::time::Instant::now(),
|
|
||||||
});
|
|
||||||
{
|
|
||||||
let mut guard = match self.links.write() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
guard.insert((network, peer), Arc::clone(&state));
|
|
||||||
}
|
|
||||||
|
|
||||||
self.codec.on_peer_link_up(network, peer, &link);
|
|
||||||
|
|
||||||
let codec = Arc::clone(&self.codec);
|
|
||||||
let sink = match self.context.lock() {
|
|
||||||
Ok(g) => g.as_ref().map(|ctx| ctx.packet_sink()),
|
|
||||||
Err(p) => p.into_inner().as_ref().map(|ctx| ctx.packet_sink()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let rx_link = Arc::clone(&link);
|
|
||||||
let rx_state = Arc::clone(&state);
|
|
||||||
let handle = tokio::spawn(async move {
|
|
||||||
while let Some(payload) = rx_link.recv().await {
|
|
||||||
match codec.decrypt(network, peer, &payload) {
|
|
||||||
Ok(packet) => {
|
|
||||||
rx_state.rx_packets.fetch_add(1, Ordering::Relaxed);
|
|
||||||
rx_state
|
|
||||||
.rx_bytes
|
|
||||||
.fetch_add(packet.len() as u64, Ordering::Relaxed);
|
|
||||||
if let Some(ref sink) = sink {
|
|
||||||
sink.deliver(network, peer, packet).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
rx_state.dropped.fetch_add(1, Ordering::Relaxed);
|
|
||||||
tracing::debug!(%peer, %err, "tunnel decrypt failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let mut guard = match self.tasks.lock() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
if let Some(old) = guard.insert((network, peer), handle) {
|
|
||||||
old.abort();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) {
|
|
||||||
{
|
|
||||||
let mut guard = match self.tasks.lock() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
if let Some(task) = guard.remove(&(network, peer)) {
|
|
||||||
task.abort();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
{
|
|
||||||
let mut guard = match self.links.write() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
guard.remove(&(network, peer));
|
|
||||||
}
|
|
||||||
self.codec.on_peer_down(network, peer);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_network_deactivated(&self, network: NetworkId) {
|
|
||||||
let keys_to_remove: Vec<(NetworkId, EndpointId)> = {
|
|
||||||
let guard = match self.tasks.lock() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
guard
|
|
||||||
.keys()
|
|
||||||
.filter(|(net, _)| *net == network)
|
|
||||||
.copied()
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut guard = match self.tasks.lock() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
for key in &keys_to_remove {
|
|
||||||
if let Some(task) = guard.remove(key) {
|
|
||||||
task.abort();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut guard = match self.links.write() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
guard.retain(|(net, _), _| *net != network);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn shutdown<'a>(&'a self) -> BoxFuture<'a, ()> {
|
|
||||||
Box::pin(async move {
|
|
||||||
let mut tasks = Vec::new();
|
|
||||||
{
|
|
||||||
let mut guard = match self.tasks.lock() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
for (_, task) in guard.drain() {
|
|
||||||
tasks.push(task);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for task in tasks {
|
|
||||||
task.abort();
|
|
||||||
}
|
|
||||||
self.codec.shutdown().await;
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -59,6 +59,56 @@ pub fn listen_plan(port: u16) -> ListenPlan {
|
|||||||
pub use server::{DnsServer, SharedZone};
|
pub use server::{DnsServer, SharedZone};
|
||||||
pub use zone::{Answer, Query, Zone, ZoneError, ZoneName, Zones};
|
pub use zone::{Answer, Query, Zone, ZoneError, ZoneName, Zones};
|
||||||
|
|
||||||
|
/// Authoritative zones and the publication diagnostics for one agent snapshot.
|
||||||
|
pub struct RosterZones {
|
||||||
|
/// Member and service records indexed by zone.
|
||||||
|
pub zones: Zones,
|
||||||
|
/// Zone names in configured-network order.
|
||||||
|
pub labels: Vec<String>,
|
||||||
|
/// Unusable or potentially conflicting zone names.
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RosterZones {
|
||||||
|
/// Build the desktop and mobile DNS view from the same signed state.
|
||||||
|
pub fn from_networks(networks: &[crate::NetworkStatus]) -> Self {
|
||||||
|
let mut zones = Vec::new();
|
||||||
|
let mut labels = Vec::new();
|
||||||
|
let mut warnings = Vec::new();
|
||||||
|
for network in networks {
|
||||||
|
let zone = match ZoneName::new(network.name.as_str()) {
|
||||||
|
Ok(zone) => zone,
|
||||||
|
Err(err) => {
|
||||||
|
warnings.push(format!(
|
||||||
|
"`{}` cannot be a zone, so its members have no names: {err}",
|
||||||
|
network.name
|
||||||
|
));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(warning) = zone.collision() {
|
||||||
|
warnings.push(warning);
|
||||||
|
}
|
||||||
|
labels.push(zone.as_str().to_string());
|
||||||
|
let members = network
|
||||||
|
.members
|
||||||
|
.iter()
|
||||||
|
.filter_map(|member| Some((member.hostname.clone()?, member.overlay_address_v4?)));
|
||||||
|
let services = network
|
||||||
|
.vips
|
||||||
|
.iter()
|
||||||
|
.filter(|vip| vip.error.is_none())
|
||||||
|
.filter_map(|vip| Some((vip.config.name.clone(), vip.address?)));
|
||||||
|
zones.push(Zone::new(zone, members.chain(services)).with_reverse_range(network.range));
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
zones: Zones::new(zones),
|
||||||
|
labels,
|
||||||
|
warnings,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|||||||
@@ -81,7 +81,22 @@ impl SharedZone {
|
|||||||
/// server should reply to, and replying anyway would make this a useful
|
/// server should reply to, and replying anyway would make this a useful
|
||||||
/// amplifier for somebody spoofing a source address.
|
/// amplifier for somebody spoofing a source address.
|
||||||
pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
||||||
let packet = simple_dns::Packet::parse(query).ok()?;
|
match resolve(zones, query)? {
|
||||||
|
Resolution::Local(reply) | Resolution::Outside(reply) => Some(reply),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An authoritative decision for a host resolver that also handles external domains.
|
||||||
|
pub enum Resolution {
|
||||||
|
/// Answer locally, including authoritative denials and protocol errors.
|
||||||
|
Local(Vec<u8>),
|
||||||
|
/// A well-formed question outside all mesh zones, with the authoritative server's REFUSED reply.
|
||||||
|
Outside(Vec<u8>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Distinguish an external question from an unknown name inside a mesh zone.
|
||||||
|
pub fn resolve(zones: &Zones, query: &[u8]) -> Option<Resolution> {
|
||||||
|
let packet = parse_message(query)?;
|
||||||
if packet.has_flags(PacketFlag::RESPONSE) {
|
if packet.has_flags(PacketFlag::RESPONSE) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -95,18 +110,18 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
|||||||
|
|
||||||
if packet.opcode() != simple_dns::OPCODE::StandardQuery {
|
if packet.opcode() != simple_dns::OPCODE::StandardQuery {
|
||||||
*reply.rcode_mut() = RCODE::NotImplemented;
|
*reply.rcode_mut() = RCODE::NotImplemented;
|
||||||
return reply.build_bytes_vec().ok();
|
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exactly one question. Zero is nothing to answer; more than one has no
|
// Exactly one question. Zero is nothing to answer; more than one has no
|
||||||
// agreed meaning and every real server rejects it.
|
// agreed meaning and every real server rejects it.
|
||||||
let [question] = packet.questions.as_slice() else {
|
let [question] = packet.questions.as_slice() else {
|
||||||
*reply.rcode_mut() = RCODE::FormatError;
|
*reply.rcode_mut() = RCODE::FormatError;
|
||||||
return reply.build_bytes_vec().ok();
|
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||||
};
|
};
|
||||||
if !matches!(question.qclass, QCLASS::CLASS(simple_dns::CLASS::IN)) {
|
if !matches!(question.qclass, QCLASS::CLASS(simple_dns::CLASS::IN)) {
|
||||||
*reply.rcode_mut() = RCODE::Refused;
|
*reply.rcode_mut() = RCODE::Refused;
|
||||||
return reply.build_bytes_vec().ok();
|
return reply.build_bytes_vec().ok().map(Resolution::Local);
|
||||||
}
|
}
|
||||||
|
|
||||||
let qname = question.qname.to_string();
|
let qname = question.qname.to_string();
|
||||||
@@ -117,7 +132,10 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
|||||||
None => {
|
None => {
|
||||||
reply.questions.push(question.clone());
|
reply.questions.push(question.clone());
|
||||||
*reply.rcode_mut() = RCODE::Refused;
|
*reply.rcode_mut() = RCODE::Refused;
|
||||||
return reply.build_bytes_vec_compressed().ok();
|
return reply
|
||||||
|
.build_bytes_vec_compressed()
|
||||||
|
.ok()
|
||||||
|
.map(Resolution::Outside);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
reply.questions.push(question.clone());
|
reply.questions.push(question.clone());
|
||||||
@@ -163,7 +181,22 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option<Vec<u8>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reply.build_bytes_vec_compressed().ok()
|
reply
|
||||||
|
.build_bytes_vec_compressed()
|
||||||
|
.ok()
|
||||||
|
.map(Resolution::Local)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse a DNS message only after bounding its section allocations against the bytes received.
|
||||||
|
pub fn parse_message(wire: &[u8]) -> Option<simple_dns::Packet<'_>> {
|
||||||
|
let header = wire.get(..12)?;
|
||||||
|
let counts = |at: usize| usize::from(u16::from_be_bytes([header[at], header[at + 1]]));
|
||||||
|
// Even a root question needs five bytes. An empty root resource record needs eleven.
|
||||||
|
let minimum = 12 + counts(4) * 5 + (counts(6) + counts(8) + counts(10)) * 11;
|
||||||
|
if wire.len() < minimum || wire.len() > usize::from(u16::MAX) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
simple_dns::Packet::parse(wire).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The zone's start of authority.
|
/// The zone's start of authority.
|
||||||
@@ -202,8 +235,7 @@ fn query_kind(qtype: QTYPE) -> Query {
|
|||||||
|
|
||||||
/// Whether the client offered EDNS, and so how large an answer it will take.
|
/// Whether the client offered EDNS, and so how large an answer it will take.
|
||||||
fn udp_limit(query: &[u8]) -> usize {
|
fn udp_limit(query: &[u8]) -> usize {
|
||||||
simple_dns::Packet::parse(query)
|
parse_message(query)
|
||||||
.ok()
|
|
||||||
.and_then(|packet| packet.opt().map(|opt| opt.udp_packet_size as usize))
|
.and_then(|packet| packet.opt().map(|opt| opt.udp_packet_size as usize))
|
||||||
.unwrap_or(CLASSIC_UDP_LIMIT as u16 as usize)
|
.unwrap_or(CLASSIC_UDP_LIMIT as u16 as usize)
|
||||||
.clamp(CLASSIC_UDP_LIMIT, MAX_MESSAGE_LEN)
|
.clamp(CLASSIC_UDP_LIMIT, MAX_MESSAGE_LEN)
|
||||||
@@ -214,20 +246,19 @@ fn udp_limit(query: &[u8]) -> usize {
|
|||||||
/// The records are dropped and the truncated bit set, which tells a resolver
|
/// The records are dropped and the truncated bit set, which tells a resolver
|
||||||
/// to ask again over TCP. Sending a reply it cannot reassemble would just
|
/// to ask again over TCP. Sending a reply it cannot reassemble would just
|
||||||
/// look like packet loss.
|
/// look like packet loss.
|
||||||
fn truncate_for_udp(query: &[u8], reply: Vec<u8>) -> Vec<u8> {
|
pub fn truncate_for_udp(query: &[u8], reply: Vec<u8>, payload_limit: usize) -> Vec<u8> {
|
||||||
let limit = udp_limit(query);
|
let limit = udp_limit(query).min(payload_limit);
|
||||||
if reply.len() <= limit {
|
if reply.len() <= limit {
|
||||||
return reply;
|
return reply;
|
||||||
}
|
}
|
||||||
let Ok(parsed) = simple_dns::Packet::parse(&reply) else {
|
let Some(mut short) = parse_message(&reply) else {
|
||||||
return reply;
|
return reply;
|
||||||
};
|
};
|
||||||
let mut short = simple_dns::Packet::new_reply(parsed.id());
|
short.set_flags(PacketFlag::TRUNCATION);
|
||||||
short.set_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER);
|
short.answers.clear();
|
||||||
*short.rcode_mut() = parsed.rcode();
|
short.name_servers.clear();
|
||||||
for question in &parsed.questions {
|
short.additional_records.clear();
|
||||||
short.questions.push(question.clone());
|
*short.opt_mut() = None;
|
||||||
}
|
|
||||||
short.build_bytes_vec().unwrap_or(reply)
|
short.build_bytes_vec().unwrap_or(reply)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,7 +295,7 @@ impl DnsServer {
|
|||||||
let Some(reply) = respond(&udp_zone.get(), query) else {
|
let Some(reply) = respond(&udp_zone.get(), query) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let reply = truncate_for_udp(query, reply);
|
let reply = truncate_for_udp(query, reply, MAX_MESSAGE_LEN);
|
||||||
if let Err(err) = udp.send_to(&reply, from).await {
|
if let Err(err) = udp.send_to(&reply, from).await {
|
||||||
tracing::debug!(%err, "dns udp reply failed");
|
tracing::debug!(%err, "dns udp reply failed");
|
||||||
}
|
}
|
||||||
@@ -494,7 +525,7 @@ mod tests {
|
|||||||
"the test needs a big answer"
|
"the test needs a big answer"
|
||||||
);
|
);
|
||||||
|
|
||||||
let short = truncate_for_udp(&query, full);
|
let short = truncate_for_udp(&query, full, MAX_MESSAGE_LEN);
|
||||||
assert!(short.len() <= CLASSIC_UDP_LIMIT);
|
assert!(short.len() <= CLASSIC_UDP_LIMIT);
|
||||||
let parsed = simple_dns::Packet::parse(&short).unwrap();
|
let parsed = simple_dns::Packet::parse(&short).unwrap();
|
||||||
assert!(parsed.has_flags(PacketFlag::TRUNCATION));
|
assert!(parsed.has_flags(PacketFlag::TRUNCATION));
|
||||||
|
|||||||
@@ -208,6 +208,7 @@ pub enum Answer {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Zone {
|
pub struct Zone {
|
||||||
origin: ZoneName,
|
origin: ZoneName,
|
||||||
|
reverse_range: Option<crate::state::Ipv4Range>,
|
||||||
/// Name relative to the origin, to the addresses it answers to.
|
/// Name relative to the origin, to the addresses it answers to.
|
||||||
hosts: BTreeMap<String, Vec<Ipv4Addr>>,
|
hosts: BTreeMap<String, Vec<Ipv4Addr>>,
|
||||||
/// Address to the name that holds it.
|
/// Address to the name that holds it.
|
||||||
@@ -246,12 +247,23 @@ impl Zone {
|
|||||||
let serial = content_serial(&hosts);
|
let serial = content_serial(&hosts);
|
||||||
Self {
|
Self {
|
||||||
origin,
|
origin,
|
||||||
|
// Standalone authoritative zones retain their original broad PTR view.
|
||||||
|
// Agent snapshots scope the authority to each network's actual range.
|
||||||
|
reverse_range: Some(crate::state::Ipv4Range {
|
||||||
|
base: Ipv4Addr::UNSPECIFIED,
|
||||||
|
prefix_len: 0,
|
||||||
|
}),
|
||||||
hosts,
|
hosts,
|
||||||
names,
|
names,
|
||||||
serial,
|
serial,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn with_reverse_range(mut self, range: Option<crate::state::Ipv4Range>) -> Self {
|
||||||
|
self.reverse_range = range;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// The zone's origin.
|
/// The zone's origin.
|
||||||
pub fn origin(&self) -> &ZoneName {
|
pub fn origin(&self) -> &ZoneName {
|
||||||
&self.origin
|
&self.origin
|
||||||
@@ -300,6 +312,12 @@ impl Zone {
|
|||||||
/// Answers one question.
|
/// Answers one question.
|
||||||
pub fn lookup(&self, qname: &str, query: Query) -> Answer {
|
pub fn lookup(&self, qname: &str, query: Query) -> Answer {
|
||||||
if let Some(address) = reverse_address(qname) {
|
if let Some(address) = reverse_address(qname) {
|
||||||
|
if !self
|
||||||
|
.reverse_range
|
||||||
|
.is_some_and(|range| range.contains(address))
|
||||||
|
{
|
||||||
|
return Answer::NotOurs;
|
||||||
|
}
|
||||||
return match self.names.get(&address) {
|
return match self.names.get(&address) {
|
||||||
Some(name) if query == Query::Ptr => {
|
Some(name) if query == Query::Ptr => {
|
||||||
Answer::Name(format!("{name}.{}", self.origin.as_str()))
|
Answer::Name(format!("{name}.{}", self.origin.as_str()))
|
||||||
|
|||||||
@@ -171,6 +171,17 @@ pub fn default_control_socket_path() -> PathBuf {
|
|||||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum Request {
|
pub enum Request {
|
||||||
|
/// Save a complete version-checked service draft or its deletion.
|
||||||
|
SaveVip {
|
||||||
|
/// Exact network id.
|
||||||
|
network_id: String,
|
||||||
|
/// Entire desired configuration.
|
||||||
|
config: crate::vip::VipConfig,
|
||||||
|
/// Revision originally displayed; absent for creation.
|
||||||
|
expected: Option<String>,
|
||||||
|
/// Remove the service permanently.
|
||||||
|
delete: bool,
|
||||||
|
},
|
||||||
/// Retire the selected offline member's observed claim.
|
/// Retire the selected offline member's observed claim.
|
||||||
ForgetNode {
|
ForgetNode {
|
||||||
/// Exact public network id.
|
/// Exact public network id.
|
||||||
@@ -271,6 +282,9 @@ pub enum Request {
|
|||||||
impl std::fmt::Debug for Request {
|
impl std::fmt::Debug for Request {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
|
Request::SaveVip {
|
||||||
|
network_id, config, ..
|
||||||
|
} => write!(f, "SaveVip {{ {network_id}, {} }}", config.id),
|
||||||
Request::ForgetNode {
|
Request::ForgetNode {
|
||||||
network_id,
|
network_id,
|
||||||
peer,
|
peer,
|
||||||
@@ -317,6 +331,8 @@ impl std::fmt::Debug for Request {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum Response {
|
pub enum Response {
|
||||||
|
/// Accepted configuration with fresh local routing observations.
|
||||||
|
Vips(Vec<crate::vip::VipStatus>),
|
||||||
/// An observed offline claim was durably retired.
|
/// An observed offline claim was durably retired.
|
||||||
NodeForgotten(ForgottenNodeReport),
|
NodeForgotten(ForgottenNodeReport),
|
||||||
/// Accepted ordered protocol selection.
|
/// Accepted ordered protocol selection.
|
||||||
@@ -358,6 +374,57 @@ pub struct ForgottenNodeReport {
|
|||||||
pub peers_told: u32,
|
pub peers_told: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Saves a whole VIP draft through the running agent.
|
||||||
|
pub async fn save_vip(
|
||||||
|
socket: &Path,
|
||||||
|
network_id: &str,
|
||||||
|
config: crate::vip::VipConfig,
|
||||||
|
expected: Option<String>,
|
||||||
|
delete: bool,
|
||||||
|
) -> Result<Vec<crate::vip::VipStatus>> {
|
||||||
|
match exchange(
|
||||||
|
socket,
|
||||||
|
&Request::SaveVip {
|
||||||
|
network_id: network_id.into(),
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
},
|
||||||
|
EXCHANGE_TIMEOUT,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
Response::Vips(vips) => Ok(vips),
|
||||||
|
Response::Error(reason) => Err(Error::Rejected { reason }),
|
||||||
|
_ => Err(Error::Rejected {
|
||||||
|
reason: "unexpected VIP response".into(),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Resolves a service by exact name, full id or unique id prefix.
|
||||||
|
pub fn resolve_vip<'a>(
|
||||||
|
network: &'a NetworkReport,
|
||||||
|
selector: &str,
|
||||||
|
) -> std::result::Result<&'a crate::vip::VipStatus, String> {
|
||||||
|
let matches: Vec<_> = network
|
||||||
|
.vips
|
||||||
|
.iter()
|
||||||
|
.filter(|v| v.config.name == selector || v.config.id.starts_with(selector))
|
||||||
|
.collect();
|
||||||
|
match matches.as_slice() {
|
||||||
|
[vip] => Ok(vip),
|
||||||
|
[] => Err(format!("no VIP matches `{selector}`")),
|
||||||
|
_ => Err(format!(
|
||||||
|
"ambiguous VIP `{selector}`: {}",
|
||||||
|
matches
|
||||||
|
.iter()
|
||||||
|
.map(|v| format!("{} ({})", v.config.name, v.config.id))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolves a node by exact hostname, full id, unique id prefix or overlay IPv4.
|
/// Resolves a node by exact hostname, full id, unique id prefix or overlay IPv4.
|
||||||
/// Ambiguity is reported with names and full ids and never guessed.
|
/// Ambiguity is reported with names and full ids and never guessed.
|
||||||
pub fn resolve_node<'a>(
|
pub fn resolve_node<'a>(
|
||||||
@@ -642,6 +709,9 @@ pub struct ProtocolReport {
|
|||||||
/// One network.
|
/// One network.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct NetworkReport {
|
pub struct NetworkReport {
|
||||||
|
/// Shared VIPs and this client's routing observations.
|
||||||
|
#[serde(default)]
|
||||||
|
pub vips: Vec<crate::vip::VipStatus>,
|
||||||
/// Enabled local data-plane protocols, in preference order.
|
/// Enabled local data-plane protocols, in preference order.
|
||||||
pub protocols: Vec<String>,
|
pub protocols: Vec<String>,
|
||||||
/// Whether the network starts or resumes automatically when its range is free.
|
/// Whether the network starts or resumes automatically when its range is free.
|
||||||
@@ -758,6 +828,8 @@ pub struct MemberReport {
|
|||||||
/// One control plane peer.
|
/// One control plane peer.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct PeerReport {
|
pub struct PeerReport {
|
||||||
|
/// Actionable carrier failure or policy mismatch; absent for a usable route.
|
||||||
|
pub data_error: Option<String>,
|
||||||
/// The peer's endpoint id.
|
/// The peer's endpoint id.
|
||||||
pub endpoint_id: String,
|
pub endpoint_id: String,
|
||||||
/// Hostname it announced, if any.
|
/// Hostname it announced, if any.
|
||||||
@@ -847,10 +919,12 @@ pub struct HostRulesReport {
|
|||||||
/// One overlay peer.
|
/// One overlay peer.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct OverlayPeerReport {
|
pub struct OverlayPeerReport {
|
||||||
|
/// Opaque counter lifetime. A new tunnel or agent restart starts a new epoch.
|
||||||
|
pub counter_epoch: u64,
|
||||||
/// The peer's control plane identity, so a tunnel can be matched to the
|
/// The peer's control plane identity, so a tunnel can be matched to the
|
||||||
/// session and the member it belongs to.
|
/// session and the member it belongs to.
|
||||||
pub endpoint_id: String,
|
pub endpoint_id: String,
|
||||||
/// Protocol carrying overlay traffic for this peer (e.g. "tcp-tls", "wg-quic").
|
/// Reserved legacy field; the internal encryption protocol is not user selectable.
|
||||||
pub protocol: String,
|
pub protocol: String,
|
||||||
/// The peer's WireGuard public key (if applicable).
|
/// The peer's WireGuard public key (if applicable).
|
||||||
pub public_key: String,
|
pub public_key: String,
|
||||||
@@ -905,6 +979,16 @@ impl OverlayPeerReport {
|
|||||||
/// running and what they can report or change. That is what keeps this module
|
/// running and what they can report or change. That is what keeps this module
|
||||||
/// free of any knowledge of them.
|
/// free of any knowledge of them.
|
||||||
pub trait ReportSource: Send + Sync + 'static {
|
pub trait ReportSource: Send + Sync + 'static {
|
||||||
|
/// Atomically saves a complete VIP draft using its original revision.
|
||||||
|
fn save_vip(
|
||||||
|
&self,
|
||||||
|
_network: String,
|
||||||
|
_config: crate::vip::VipConfig,
|
||||||
|
_expected: Option<String>,
|
||||||
|
_delete: bool,
|
||||||
|
) -> BoxFuture<'_, std::result::Result<Vec<crate::vip::VipStatus>, String>> {
|
||||||
|
Box::pin(async { Err("this agent cannot manage VIPs".into()) })
|
||||||
|
}
|
||||||
/// Persists and announces a version-scoped node cleanup.
|
/// Persists and announces a version-scoped node cleanup.
|
||||||
fn forget_node(
|
fn forget_node(
|
||||||
&self,
|
&self,
|
||||||
@@ -1051,7 +1135,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
|||||||
///
|
///
|
||||||
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
||||||
/// changes shape.
|
/// changes shape.
|
||||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 21]);
|
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 23]);
|
||||||
|
|
||||||
/// Reads one request off an accepted stream, answers it, writes the response.
|
/// Reads one request off an accepted stream, answers it, writes the response.
|
||||||
///
|
///
|
||||||
@@ -1075,6 +1159,15 @@ where
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let response = match request {
|
let response = match request {
|
||||||
|
Request::SaveVip {
|
||||||
|
network_id,
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
} => match source.save_vip(network_id, config, expected, delete).await {
|
||||||
|
Ok(vips) => Response::Vips(vips),
|
||||||
|
Err(reason) => Response::Error(reason),
|
||||||
|
},
|
||||||
Request::ForgetNode {
|
Request::ForgetNode {
|
||||||
network_id,
|
network_id,
|
||||||
peer,
|
peer,
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ pub mod storage;
|
|||||||
pub mod task;
|
pub mod task;
|
||||||
#[cfg(feature = "testing")]
|
#[cfg(feature = "testing")]
|
||||||
pub mod testing;
|
pub mod testing;
|
||||||
|
pub mod vip;
|
||||||
|
|
||||||
pub use agent::{Agent, AgentStatus, Event, NetworkStatus, PeerStatus};
|
pub use agent::{Agent, AgentStatus, Event, NetworkStatus, PeerStatus};
|
||||||
pub use config::{AgentConfig, Limits, ReconnectPolicy, StoragePaths, TransportPolicy};
|
pub use config::{AgentConfig, Limits, ReconnectPolicy, StoragePaths, TransportPolicy};
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
//! own reachability data.
|
//! own reachability data.
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use iroh::endpoint::{
|
use iroh::endpoint::{
|
||||||
@@ -221,9 +222,18 @@ fn local_addr_string(addr: &iroh::endpoint::LocalTransportAddr) -> Option<String
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct EndpointAdapter {
|
pub struct EndpointAdapter {
|
||||||
endpoint: Endpoint,
|
endpoint: Endpoint,
|
||||||
|
owned_interface: Arc<std::sync::RwLock<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EndpointAdapter {
|
impl EndpointAdapter {
|
||||||
|
/// Excludes the real name after interface creation (macOS assigns utunN).
|
||||||
|
pub(crate) fn exclude_interface(&self, name: &str) {
|
||||||
|
*self
|
||||||
|
.owned_interface
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(|p| p.into_inner()) = name.to_lowercase();
|
||||||
|
}
|
||||||
|
|
||||||
/// Binds an endpoint according to `config`, reusing the persistent device key.
|
/// Binds an endpoint according to `config`, reusing the persistent device key.
|
||||||
pub async fn bind(config: &AgentConfig, identity: &DeviceIdentity) -> Result<Self> {
|
pub async fn bind(config: &AgentConfig, identity: &DeviceIdentity) -> Result<Self> {
|
||||||
let mut builder = Endpoint::builder(presets::Minimal)
|
let mut builder = Endpoint::builder(presets::Minimal)
|
||||||
@@ -240,12 +250,20 @@ impl EndpointAdapter {
|
|||||||
TransportPolicy::N0Defaults => builder.preset(presets::N0),
|
TransportPolicy::N0Defaults => builder.preset(presets::N0),
|
||||||
};
|
};
|
||||||
|
|
||||||
if matches!(
|
let owned_interface =
|
||||||
config.transport,
|
Arc::new(std::sync::RwLock::new(config.interface_name.to_lowercase()));
|
||||||
TransportPolicy::N0Defaults | TransportPolicy::DirectOnly
|
{
|
||||||
) {
|
let interface_filter = Arc::clone(&owned_interface);
|
||||||
let filter = iroh::address_lookup::AddrFilter::new(|addrs| {
|
let factory = config.tun_factory.clone();
|
||||||
|
let filter = iroh::address_lookup::AddrFilter::new(move |addrs| {
|
||||||
|
let owned_interface = interface_filter
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.clone();
|
||||||
let mut overlay_ips = std::collections::HashSet::new();
|
let mut overlay_ips = std::collections::HashSet::new();
|
||||||
|
if let Some(factory) = &factory {
|
||||||
|
overlay_ips.extend(factory.assigned_addresses());
|
||||||
|
}
|
||||||
for iface in netdev::get_interfaces() {
|
for iface in netdev::get_interfaces() {
|
||||||
let name = iface.name.to_lowercase();
|
let name = iface.name.to_lowercase();
|
||||||
let friendly = iface
|
let friendly = iface
|
||||||
@@ -258,7 +276,9 @@ impl EndpointAdapter {
|
|||||||
.as_deref()
|
.as_deref()
|
||||||
.map(str::to_lowercase)
|
.map(str::to_lowercase)
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
if name.starts_with("tsun")
|
if name == owned_interface
|
||||||
|
|| friendly == owned_interface
|
||||||
|
|| name.starts_with("tsun")
|
||||||
|| name.contains("tsunagi")
|
|| name.contains("tsunagi")
|
||||||
|| name.contains("wintun")
|
|| name.contains("wintun")
|
||||||
|| friendly.starts_with("tsun")
|
|| friendly.starts_with("tsun")
|
||||||
@@ -288,7 +308,9 @@ impl EndpointAdapter {
|
|||||||
.collect();
|
.collect();
|
||||||
std::borrow::Cow::Owned(filtered)
|
std::borrow::Cow::Owned(filtered)
|
||||||
});
|
});
|
||||||
builder = builder.addr_filter(filter);
|
builder = builder
|
||||||
|
.direct_addr_filter(filter.clone())
|
||||||
|
.addr_filter(filter);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "testing")]
|
#[cfg(feature = "testing")]
|
||||||
@@ -395,7 +417,10 @@ impl EndpointAdapter {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(Self { endpoint })
|
Ok(Self {
|
||||||
|
endpoint,
|
||||||
|
owned_interface,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The underlying iroh endpoint.
|
/// The underlying iroh endpoint.
|
||||||
|
|||||||
@@ -35,6 +35,8 @@ pub struct ExitHostPlan {
|
|||||||
pub offer: Vec<Ipv4Range>,
|
pub offer: Vec<Ipv4Range>,
|
||||||
/// Whether this device sends its internet traffic through a member.
|
/// Whether this device sends its internet traffic through a member.
|
||||||
pub client: bool,
|
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
|
/// 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
|
/// reads it, to keep this agent's own traffic *to* the overlay inside it
|
||||||
/// where the host has no per-user routing (macOS).
|
/// where the host has no per-user routing (macOS).
|
||||||
|
|||||||
@@ -407,6 +407,7 @@ mod tests {
|
|||||||
overlay: vec![range()],
|
overlay: vec![range()],
|
||||||
bypass: vec![Ipv4Addr::new(138, 201, 61, 182)],
|
bypass: vec![Ipv4Addr::new(138, 201, 61, 182)],
|
||||||
bypass_hosts: vec!["relay.example".into()],
|
bypass_hosts: vec!["relay.example".into()],
|
||||||
|
..Default::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -145,18 +145,19 @@ impl Tally {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The overlay interface.
|
/// The overlay interface.
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Interface {
|
pub struct Interface {
|
||||||
device: Arc<dyn TunDevice>,
|
device: Arc<dyn TunDevice>,
|
||||||
factory: Arc<dyn TunFactory>,
|
factory: Arc<dyn TunFactory>,
|
||||||
name: String,
|
name: String,
|
||||||
mtu: u32,
|
mtu: u32,
|
||||||
routes: Arc<RoutingTable>,
|
routes: Arc<RoutingTable>,
|
||||||
|
carrier: Arc<dyn PacketCarrier>,
|
||||||
tally: Arc<Tally>,
|
tally: Arc<Tally>,
|
||||||
/// What was last applied to the host, so an unchanged table is not
|
/// What was last applied to the host, so an unchanged table is not
|
||||||
/// re-applied on every pass.
|
/// re-applied on every pass.
|
||||||
applied: std::sync::Mutex<Vec<Cidr>>,
|
applied: std::sync::Mutex<Vec<Cidr>>,
|
||||||
task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||||
|
vip_task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||||
sync_lock: Arc<tokio::sync::Mutex<()>>,
|
sync_lock: Arc<tokio::sync::Mutex<()>>,
|
||||||
/// The host rules for this interface, when the factory manages the host.
|
/// The host rules for this interface, when the factory manages the host.
|
||||||
host_rules: Option<Arc<dyn BroadcastHostRules>>,
|
host_rules: Option<Arc<dyn BroadcastHostRules>>,
|
||||||
@@ -200,6 +201,14 @@ impl ExitState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Interface {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Interface")
|
||||||
|
.field("name", &self.name)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Interface {
|
impl Interface {
|
||||||
/// Creates the interface and starts moving packets.
|
/// Creates the interface and starts moving packets.
|
||||||
pub async fn start(
|
pub async fn start(
|
||||||
@@ -221,7 +230,33 @@ impl Interface {
|
|||||||
let name = device.name().to_string();
|
let name = device.name().to_string();
|
||||||
let tally = Arc::new(Tally::default());
|
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 {
|
||||||
|
let mut interval = tokio::time::interval(std::time::Duration::from_millis(250));
|
||||||
|
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
let mut checks = tokio::task::JoinSet::new();
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
_=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 {
|
||||||
|
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);}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
let task = {
|
let task = {
|
||||||
|
let carrier = Arc::clone(&carrier);
|
||||||
let device = Arc::clone(&device);
|
let device = Arc::clone(&device);
|
||||||
let routes = Arc::clone(&routes);
|
let routes = Arc::clone(&routes);
|
||||||
let tally = Arc::clone(&tally);
|
let tally = Arc::clone(&tally);
|
||||||
@@ -231,6 +266,26 @@ impl Interface {
|
|||||||
tally.malformed.fetch_add(1, Ordering::Relaxed);
|
tally.malformed.fetch_add(1, Ordering::Relaxed);
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
match routes.vips.outgoing(packet.clone()) {
|
||||||
|
crate::vip::router::Decision::Send(route, packet) => {
|
||||||
|
for part in crate::vip::packet::fragments(packet, mtu) {
|
||||||
|
if carrier.carry(route, part) {
|
||||||
|
tally.sent.fetch_add(1, Ordering::Relaxed);
|
||||||
|
} else {
|
||||||
|
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
crate::vip::router::Decision::Local(packet) => {
|
||||||
|
for part in crate::vip::packet::fragments(packet, mtu) {
|
||||||
|
let _ = device.send(part).await;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
crate::vip::router::Decision::Drop => continue,
|
||||||
|
crate::vip::router::Decision::Pass => {}
|
||||||
|
}
|
||||||
let destination = header.destination();
|
let destination = header.destination();
|
||||||
if let (IpAddr::V4(source), IpAddr::V4(destination)) =
|
if let (IpAddr::V4(source), IpAddr::V4(destination)) =
|
||||||
(header.source(), destination)
|
(header.source(), destination)
|
||||||
@@ -279,9 +334,11 @@ impl Interface {
|
|||||||
name,
|
name,
|
||||||
mtu,
|
mtu,
|
||||||
routes,
|
routes,
|
||||||
|
carrier,
|
||||||
tally,
|
tally,
|
||||||
applied: std::sync::Mutex::new(Vec::new()),
|
applied: std::sync::Mutex::new(Vec::new()),
|
||||||
task: std::sync::Mutex::new(Some(task)),
|
task: std::sync::Mutex::new(Some(task)),
|
||||||
|
vip_task: std::sync::Mutex::new(Some(vip_task)),
|
||||||
sync_lock: Arc::new(tokio::sync::Mutex::new(())),
|
sync_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||||
host_rules,
|
host_rules,
|
||||||
rules_report: std::sync::Mutex::new(None),
|
rules_report: std::sync::Mutex::new(None),
|
||||||
@@ -362,7 +419,7 @@ impl Interface {
|
|||||||
.collect();
|
.collect();
|
||||||
ranges.sort_by_key(|range| (range.base, range.prefix_len));
|
ranges.sort_by_key(|range| (range.base, range.prefix_len));
|
||||||
ranges.dedup();
|
ranges.dedup();
|
||||||
let client = self.routes.exit_via().is_some();
|
let (client, client_source) = self.routes.exit_client();
|
||||||
let overlay = self.routes.overlay_ranges();
|
let overlay = self.routes.overlay_ranges();
|
||||||
let (bypass, bypass_hosts) = if client && exit.needs_bypass() {
|
let (bypass, bypass_hosts) = if client && exit.needs_bypass() {
|
||||||
self.underlay_targets(&overlay)
|
self.underlay_targets(&overlay)
|
||||||
@@ -373,6 +430,7 @@ impl Interface {
|
|||||||
interface: self.name.clone(),
|
interface: self.name.clone(),
|
||||||
offer: ranges,
|
offer: ranges,
|
||||||
client,
|
client,
|
||||||
|
client_source,
|
||||||
overlay,
|
overlay,
|
||||||
bypass,
|
bypass,
|
||||||
bypass_hosts,
|
bypass_hosts,
|
||||||
@@ -716,6 +774,15 @@ impl Interface {
|
|||||||
task.abort();
|
task.abort();
|
||||||
let _ = task.await;
|
let _ = task.await;
|
||||||
}
|
}
|
||||||
|
let vip_task = self
|
||||||
|
.vip_task
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.take();
|
||||||
|
if let Some(task) = vip_task {
|
||||||
|
task.abort();
|
||||||
|
let _ = task.await;
|
||||||
|
}
|
||||||
self.factory.destroy(self.device.name()).await;
|
self.factory.destroy(self.device.name()).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -770,6 +837,24 @@ impl Interface {
|
|||||||
return Err(Rejected::WrongDestination);
|
return Err(Rejected::WrongDestination);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
// Source ownership was checked before any VIP reverse translation.
|
||||||
|
let packet = match self.routes.vips.incoming(network, peer, packet.clone()) {
|
||||||
|
crate::vip::router::Decision::Send(route, packet) => {
|
||||||
|
// Probe replies use the ordinary peer carrier, never the TUN.
|
||||||
|
self.carrier.carry(route, packet);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
crate::vip::router::Decision::Local(packet) => {
|
||||||
|
for part in crate::vip::packet::fragments(packet, self.mtu) {
|
||||||
|
if self.device.send(part).await.is_ok() {
|
||||||
|
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
crate::vip::router::Decision::Drop => return Ok(()),
|
||||||
|
crate::vip::router::Decision::Pass => packet,
|
||||||
|
};
|
||||||
// Remote broadcasts terminate here. Only local TUN ingress can fan out.
|
// Remote broadcasts terminate here. Only local TUN ingress can fan out.
|
||||||
if self.device.send(packet).await.is_ok() {
|
if self.device.send(packet).await.is_ok() {
|
||||||
if broadcast {
|
if broadcast {
|
||||||
@@ -794,6 +879,14 @@ impl Interface {
|
|||||||
|
|
||||||
impl Drop for Interface {
|
impl Drop for Interface {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
|
if let Some(task) = self
|
||||||
|
.vip_task
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.take()
|
||||||
|
{
|
||||||
|
task.abort();
|
||||||
|
}
|
||||||
if let Ok(mut guard) = self.task.lock()
|
if let Ok(mut guard) = self.task.lock()
|
||||||
&& let Some(task) = guard.take()
|
&& let Some(task) = guard.take()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -89,6 +89,7 @@ pub enum RouteError {
|
|||||||
/// Address ownership across every network this agent is in.
|
/// Address ownership across every network this agent is in.
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct RoutingTable {
|
pub struct RoutingTable {
|
||||||
|
pub(crate) vips: Arc<crate::vip::VipRouter>,
|
||||||
broadcast: ArcSwap<BroadcastTable>,
|
broadcast: ArcSwap<BroadcastTable>,
|
||||||
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
|
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
|
||||||
}
|
}
|
||||||
@@ -146,6 +147,7 @@ impl RoutingTable {
|
|||||||
|
|
||||||
/// Forgets a network.
|
/// Forgets a network.
|
||||||
pub fn remove_network(&self, network: NetworkId) {
|
pub fn remove_network(&self, network: NetworkId) {
|
||||||
|
self.vips.remove_network(network);
|
||||||
let mut networks = self.write();
|
let mut networks = self.write();
|
||||||
networks.remove(&network);
|
networks.remove(&network);
|
||||||
self.broadcast
|
self.broadcast
|
||||||
@@ -279,6 +281,15 @@ impl RoutingTable {
|
|||||||
exit_via(&self.read())
|
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
|
/// 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
|
/// agreed. A network that has not agreed one yet has nothing to
|
||||||
/// masquerade and is left out.
|
/// masquerade and is left out.
|
||||||
@@ -384,24 +395,6 @@ impl RoutingTable {
|
|||||||
conflicts
|
conflicts
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Current signed allocations used for encrypted data delivery checks.
|
|
||||||
pub(crate) fn probe_addresses(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
) -> Option<(Ipv4Addr, Ipv4Addr)> {
|
|
||||||
let table = self.read();
|
|
||||||
let routes = table.get(&network)?;
|
|
||||||
Some((
|
|
||||||
routes.local?,
|
|
||||||
routes
|
|
||||||
.peers
|
|
||||||
.iter()
|
|
||||||
.find(|(_, holder)| *holder == peer)
|
|
||||||
.map(|(address, _)| *address)?,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many networks the table covers.
|
/// How many networks the table covers.
|
||||||
pub fn len(&self) -> usize {
|
pub fn len(&self) -> usize {
|
||||||
self.read().len()
|
self.read().len()
|
||||||
|
|||||||
@@ -90,6 +90,21 @@ pub trait TunFactory: Send + Sync + std::fmt::Debug + 'static {
|
|||||||
/// land on the second.
|
/// land on the second.
|
||||||
fn on_host(&self) -> bool;
|
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.
|
/// Creates a device.
|
||||||
fn create<'a>(
|
fn create<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
@@ -229,12 +244,9 @@ impl TunDevice for MemoryTun {
|
|||||||
/// enough here: the agent chose the address, so anything else holding it is a
|
/// enough here: the agent chose the address, so anything else holding it is a
|
||||||
/// problem in its own right.
|
/// problem in its own right.
|
||||||
pub fn address_is_local(address: std::net::IpAddr) -> bool {
|
pub fn address_is_local(address: std::net::IpAddr) -> bool {
|
||||||
if std::net::UdpSocket::bind((address, 0)).is_ok() {
|
let bound = std::net::UdpSocket::bind((address, 0)).is_ok();
|
||||||
return true;
|
|
||||||
}
|
|
||||||
#[cfg(all(feature = "tun-device", target_os = "windows"))]
|
#[cfg(all(feature = "tun-device", target_os = "windows"))]
|
||||||
{
|
if !bound && let Ok(interfaces) = std::panic::catch_unwind(netdev::get_interfaces) {
|
||||||
if let Ok(interfaces) = std::panic::catch_unwind(netdev::get_interfaces) {
|
|
||||||
for iface in interfaces {
|
for iface in interfaces {
|
||||||
if iface.is_up() {
|
if iface.is_up() {
|
||||||
match address {
|
match address {
|
||||||
@@ -252,14 +264,14 @@ pub fn address_is_local(address: std::net::IpAddr) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
bound
|
||||||
false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates [`MemoryTun`] devices.
|
/// Creates [`MemoryTun`] devices.
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct MemoryTunFactory {
|
pub struct MemoryTunFactory {
|
||||||
created: Arc<std::sync::Mutex<Vec<Arc<MemoryTun>>>>,
|
created: Arc<std::sync::Mutex<Vec<Arc<MemoryTun>>>>,
|
||||||
|
rules: Option<Arc<dyn super::hostrules::BroadcastHostRules>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MemoryTunFactory {
|
impl MemoryTunFactory {
|
||||||
@@ -268,6 +280,12 @@ impl MemoryTunFactory {
|
|||||||
Self::default()
|
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.
|
/// The device created for an interface name, if any.
|
||||||
pub fn device(&self, name: &str) -> Option<Arc<MemoryTun>> {
|
pub fn device(&self, name: &str) -> Option<Arc<MemoryTun>> {
|
||||||
let guard = match self.created.lock() {
|
let guard = match self.created.lock() {
|
||||||
@@ -291,6 +309,9 @@ impl MemoryTunFactory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl TunFactory for MemoryTunFactory {
|
impl TunFactory for MemoryTunFactory {
|
||||||
|
fn host_rules(&self) -> Option<Arc<dyn super::hostrules::BroadcastHostRules>> {
|
||||||
|
self.rules.clone()
|
||||||
|
}
|
||||||
fn name(&self) -> &str {
|
fn name(&self) -> &str {
|
||||||
"memory"
|
"memory"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ use crate::error::ProtocolError;
|
|||||||
/// The version in the ALPN is the wire-compatibility version of the control
|
/// The version in the ALPN is the wire-compatibility version of the control
|
||||||
/// protocol. It is independent of the network identity scheme version, so
|
/// protocol. It is independent of the network identity scheme version, so
|
||||||
/// bumping it must not change any existing [`crate::NetworkId`].
|
/// bumping it must not change any existing [`crate::NetworkId`].
|
||||||
pub const ALPN: &[u8] = b"tsunagi/ctrl/7";
|
pub const ALPN: &[u8] = b"tsunagi/ctrl/8";
|
||||||
|
|
||||||
/// ALPN of the tsunagi data plane.
|
/// ALPN of the tsunagi data plane.
|
||||||
///
|
///
|
||||||
@@ -33,8 +33,10 @@ pub const ALPN: &[u8] = b"tsunagi/ctrl/7";
|
|||||||
/// transport fragmentation. Version 5 adds the end-to-end protocol to that
|
/// transport fragmentation. Version 5 adds the end-to-end protocol to that
|
||||||
/// envelope, so a tunnel no longer depends on the kind of link under it, and
|
/// envelope, so a tunnel no longer depends on the kind of link under it, and
|
||||||
/// a first-claimed time to a signed hostname claim. All members must upgrade
|
/// a first-claimed time to a signed hostname claim. All members must upgrade
|
||||||
/// together. Persistent identities and network configuration do not change.
|
/// together. Version 6 uses one fixed inner WireGuard channel and independent
|
||||||
pub const DATA_ALPN: &[u8] = b"tsunagi/data/5";
|
/// external carrier capabilities. Control authentication, persistent identities
|
||||||
|
/// and network configuration do not change.
|
||||||
|
pub const DATA_ALPN: &[u8] = b"tsunagi/data/6";
|
||||||
|
|
||||||
/// Largest plugin protocol identifier accepted when opening a data channel.
|
/// Largest plugin protocol identifier accepted when opening a data channel.
|
||||||
pub const MAX_DATA_PROTOCOL_LEN: usize = 32;
|
pub const MAX_DATA_PROTOCOL_LEN: usize = 32;
|
||||||
@@ -43,7 +45,7 @@ pub const MAX_DATA_PROTOCOL_LEN: usize = 32;
|
|||||||
pub const MAX_SIGNATURE_LEN: usize = 64;
|
pub const MAX_SIGNATURE_LEN: usize = 64;
|
||||||
|
|
||||||
/// Control protocol version carried inside the handshake.
|
/// Control protocol version carried inside the handshake.
|
||||||
pub const PROTOCOL_VERSION: u16 = 7;
|
pub const PROTOCOL_VERSION: u16 = 8;
|
||||||
|
|
||||||
pub use crate::dataplane::transport::{MAX_TRANSPORT_PAYLOAD, TransportPayload};
|
pub use crate::dataplane::transport::{MAX_TRANSPORT_PAYLOAD, TransportPayload};
|
||||||
|
|
||||||
@@ -181,6 +183,11 @@ pub enum ControlMessage {
|
|||||||
/// Short free-text reason.
|
/// Short free-text reason.
|
||||||
reason: String,
|
reason: String,
|
||||||
},
|
},
|
||||||
|
/// One complete signed VIP field snapshot, merged atomically.
|
||||||
|
Vips {
|
||||||
|
/// Signed registers bounded by the per-VIP field limit.
|
||||||
|
entries: Vec<crate::vip::VipEntry>,
|
||||||
|
},
|
||||||
/// Signed cleanup markers, each proving the retired claim version.
|
/// Signed cleanup markers, each proving the retired claim version.
|
||||||
Retirements {
|
Retirements {
|
||||||
/// Bounded by the per-message signed-state limit.
|
/// Bounded by the per-message signed-state limit.
|
||||||
@@ -278,6 +285,15 @@ pub fn validate_capability(
|
|||||||
/// network, the other networks or the agent.
|
/// network, the other networks or the agent.
|
||||||
pub fn validate(message: &ControlMessage, limits: &Limits) -> Result<(), ProtocolError> {
|
pub fn validate(message: &ControlMessage, limits: &Limits) -> Result<(), ProtocolError> {
|
||||||
match message {
|
match message {
|
||||||
|
ControlMessage::Vips { entries } => {
|
||||||
|
check_len("vip.fields", entries.len(), limits.max_vip_fields)?;
|
||||||
|
for e in entries {
|
||||||
|
check_len("vip.id", e.vip.len(), 32)?;
|
||||||
|
check_len("vip.key", e.key.len(), 160)?;
|
||||||
|
check_len("vip.value", e.value.as_ref().map_or(0, Vec::len), 256)?;
|
||||||
|
check_len("vip.signature", e.signature.len(), 64)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
ControlMessage::Retirements { markers } => {
|
ControlMessage::Retirements { markers } => {
|
||||||
check_len("retirements", markers.len(), limits.max_state_records)?;
|
check_len("retirements", markers.len(), limits.max_state_records)?;
|
||||||
for marker in markers {
|
for marker in markers {
|
||||||
@@ -373,6 +389,7 @@ pub fn kind(message: &ControlMessage) -> &'static str {
|
|||||||
ControlMessage::Pong { .. } => "pong",
|
ControlMessage::Pong { .. } => "pong",
|
||||||
ControlMessage::State { .. } => "state",
|
ControlMessage::State { .. } => "state",
|
||||||
ControlMessage::Retirements { .. } => "retirements",
|
ControlMessage::Retirements { .. } => "retirements",
|
||||||
|
ControlMessage::Vips { .. } => "vips",
|
||||||
ControlMessage::Reachable { .. } => "reachable",
|
ControlMessage::Reachable { .. } => "reachable",
|
||||||
ControlMessage::Peers { .. } => "peers",
|
ControlMessage::Peers { .. } => "peers",
|
||||||
ControlMessage::Bye { .. } => "bye",
|
ControlMessage::Bye { .. } => "bye",
|
||||||
|
|||||||
@@ -38,6 +38,8 @@
|
|||||||
//! `docs/sync-model.md` for the implemented cleanup semantics.
|
//! `docs/sync-model.md` for the implemented cleanup semantics.
|
||||||
|
|
||||||
pub mod allocator;
|
pub mod allocator;
|
||||||
|
/// Signed shared virtual service state and its merge rules.
|
||||||
|
pub mod vip;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::net::Ipv4Addr;
|
use std::net::Ipv4Addr;
|
||||||
|
|||||||
@@ -0,0 +1,439 @@
|
|||||||
|
//! Signed multi-writer virtual service registers and deterministic merge rules.
|
||||||
|
use crate::error::Result;
|
||||||
|
use crate::vip::{Backend, Listener, Protocol, VipConfig, VipStatus, invalid};
|
||||||
|
use crate::{Limits, NetworkId};
|
||||||
|
use iroh::{EndpointId, SecretKey, Signature};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::net::Ipv4Addr;
|
||||||
|
|
||||||
|
/// A signed, independently mergeable field. A removed field keeps its tombstone.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct VipEntry {
|
||||||
|
/// Network scope.
|
||||||
|
pub network: [u8; 32],
|
||||||
|
/// Stable service id.
|
||||||
|
pub vip: String,
|
||||||
|
/// Canonical field key.
|
||||||
|
pub key: String,
|
||||||
|
/// Encoded field value; absent means deletion.
|
||||||
|
pub value: Option<Vec<u8>>,
|
||||||
|
/// Lamport clock, independent of wall time.
|
||||||
|
pub clock: u64,
|
||||||
|
/// Persistent signing identity.
|
||||||
|
pub author: [u8; 32],
|
||||||
|
/// Author's durable network counter.
|
||||||
|
pub version: u64,
|
||||||
|
/// Ed25519 signature.
|
||||||
|
pub signature: Vec<u8>,
|
||||||
|
}
|
||||||
|
impl VipEntry {
|
||||||
|
fn bytes(&self) -> Vec<u8> {
|
||||||
|
let mut e = self.clone();
|
||||||
|
e.signature.clear();
|
||||||
|
let mut out = b"tsunagi-vip-field/v1\0".to_vec();
|
||||||
|
if let Ok(bytes) = postcard::to_stdvec(&e) {
|
||||||
|
out.extend(bytes);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
/// Verifies bounds, network and authorship before the entry is merged.
|
||||||
|
pub fn verify(&self, network: NetworkId) -> Result<()> {
|
||||||
|
if self.network != *network.as_bytes()
|
||||||
|
|| self.vip.len() != 32
|
||||||
|
|| hex::decode(&self.vip).is_err()
|
||||||
|
|| self.key.len() > 160
|
||||||
|
|| self.value.as_ref().is_some_and(|v| v.len() > 256)
|
||||||
|
|| self.version == 0
|
||||||
|
|| self.version > i64::MAX as u64
|
||||||
|
|| self.clock == 0
|
||||||
|
|| self.clock > i64::MAX as u64
|
||||||
|
{
|
||||||
|
return Err(invalid("invalid VIP field bounds or network"));
|
||||||
|
}
|
||||||
|
let author =
|
||||||
|
EndpointId::from_bytes(&self.author).map_err(|_| invalid("invalid VIP author"))?;
|
||||||
|
let raw: [u8; 64] = self
|
||||||
|
.signature
|
||||||
|
.as_slice()
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| invalid("invalid VIP signature length"))?;
|
||||||
|
author
|
||||||
|
.verify(&self.bytes(), &Signature::from_bytes(&raw))
|
||||||
|
.map_err(|_| invalid("invalid VIP signature"))?;
|
||||||
|
if self.key != "deleted"
|
||||||
|
&& self.key != "name"
|
||||||
|
&& !self.key.starts_with("l/")
|
||||||
|
&& !self.key.starts_with("b/")
|
||||||
|
{
|
||||||
|
return Err(invalid("unknown VIP field"));
|
||||||
|
}
|
||||||
|
match self.key.as_str() {
|
||||||
|
"deleted" => {
|
||||||
|
if self.value.as_deref() != Some(&[1][..]) {
|
||||||
|
return Err(invalid("invalid VIP deletion tombstone"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"name" => {
|
||||||
|
let value = self
|
||||||
|
.value
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| invalid("VIP name cannot be absent"))?;
|
||||||
|
let name: String =
|
||||||
|
postcard::from_bytes(value).map_err(|_| invalid("invalid VIP name field"))?;
|
||||||
|
VipConfig {
|
||||||
|
id: self.vip.clone(),
|
||||||
|
name,
|
||||||
|
listeners: vec![],
|
||||||
|
}
|
||||||
|
.validate(&Limits::default())?;
|
||||||
|
}
|
||||||
|
key if key.starts_with("l/") => {
|
||||||
|
let parts: Vec<_> = key.split('/').collect();
|
||||||
|
if parts.len() != 3
|
||||||
|
|| parts[1].parse::<Protocol>().is_err()
|
||||||
|
|| parts[2].parse::<u16>().ok().is_none_or(|p| p == 0)
|
||||||
|
{
|
||||||
|
return Err(invalid("invalid listener field key"));
|
||||||
|
}
|
||||||
|
if let Some(value) = &self.value {
|
||||||
|
let l: Listener = postcard::from_bytes(value)
|
||||||
|
.map_err(|_| invalid("invalid listener field"))?;
|
||||||
|
if !l.backends.is_empty() || key != format!("l/{}/{}", l.protocol, l.port) {
|
||||||
|
return Err(invalid("listener key does not match its value"));
|
||||||
|
}
|
||||||
|
VipConfig {
|
||||||
|
id: self.vip.clone(),
|
||||||
|
name: "validation".into(),
|
||||||
|
listeners: vec![l],
|
||||||
|
}
|
||||||
|
.validate(&Limits::default())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
key if key.starts_with("b/") => {
|
||||||
|
let parts: Vec<_> = key.split('/').collect();
|
||||||
|
if parts.len() != 6
|
||||||
|
|| parts[1].parse::<Protocol>().is_err()
|
||||||
|
|| parts[2].parse::<u16>().ok().is_none_or(|p| p == 0)
|
||||||
|
|| parts[3].len() != 32
|
||||||
|
|| hex::decode(parts[3]).is_err()
|
||||||
|
|| parts[4].parse::<EndpointId>().is_err()
|
||||||
|
|| parts[5].parse::<u16>().ok().is_none_or(|p| p == 0)
|
||||||
|
{
|
||||||
|
return Err(invalid("invalid backend field key"));
|
||||||
|
}
|
||||||
|
if let Some(value) = &self.value {
|
||||||
|
let b: Backend = postcard::from_bytes(value)
|
||||||
|
.map_err(|_| invalid("invalid backend field"))?;
|
||||||
|
if b.peer != parts[4] || b.port.to_string() != parts[5] {
|
||||||
|
return Err(invalid("backend key does not match its value"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return Err(invalid("unknown VIP field")),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn rank(&self) -> (u64, [u8; 32], Vec<u8>) {
|
||||||
|
(self.clock, self.author, self.bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Signed registers retained across absences, including deletion tombstones.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct VipSet {
|
||||||
|
entries: BTreeMap<(String, String), VipEntry>,
|
||||||
|
}
|
||||||
|
impl VipSet {
|
||||||
|
/// Highest retained version genuinely signed by this author.
|
||||||
|
pub fn authored_version(&self, author: EndpointId) -> u64 {
|
||||||
|
self.entries
|
||||||
|
.values()
|
||||||
|
.filter(|e| e.author == *author.as_bytes())
|
||||||
|
.map(|e| e.version)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
/// Complete independently verifiable state of one service, including tombstones.
|
||||||
|
pub fn entries(&self, id: &str) -> Vec<VipEntry> {
|
||||||
|
self.entries
|
||||||
|
.values()
|
||||||
|
.filter(|e| e.vip == id)
|
||||||
|
.cloned()
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
/// All retained service ids, including deleted services.
|
||||||
|
pub fn ids(&self) -> Vec<String> {
|
||||||
|
self.entries
|
||||||
|
.keys()
|
||||||
|
.map(|(id, _)| id.clone())
|
||||||
|
.collect::<BTreeSet<_>>()
|
||||||
|
.into_iter()
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
/// Opaque optimistic concurrency token for a whole service.
|
||||||
|
pub fn revision(&self, id: &str) -> String {
|
||||||
|
let mut hash = Sha256::new();
|
||||||
|
for e in self.entries(id) {
|
||||||
|
hash.update(e.bytes());
|
||||||
|
hash.update(&e.signature);
|
||||||
|
}
|
||||||
|
hex::encode(hash.finalize())
|
||||||
|
}
|
||||||
|
/// Atomically verifies and merges one complete service snapshot.
|
||||||
|
pub fn merge(
|
||||||
|
&mut self,
|
||||||
|
network: NetworkId,
|
||||||
|
entries: Vec<VipEntry>,
|
||||||
|
limits: &Limits,
|
||||||
|
) -> Result<bool> {
|
||||||
|
if entries.len() > limits.max_vip_fields {
|
||||||
|
return Err(invalid("too many VIP fields"));
|
||||||
|
}
|
||||||
|
let mut next = self.clone();
|
||||||
|
for e in entries {
|
||||||
|
e.verify(network)?;
|
||||||
|
let key = (e.vip.clone(), e.key.clone());
|
||||||
|
if next
|
||||||
|
.entries
|
||||||
|
.get(&key)
|
||||||
|
.is_none_or(|old| e.rank() > old.rank())
|
||||||
|
{
|
||||||
|
next.entries.insert(key, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let deleted: BTreeSet<_> = next
|
||||||
|
.entries
|
||||||
|
.values()
|
||||||
|
.filter(|e| e.key == "deleted" && e.value.is_some())
|
||||||
|
.map(|e| e.vip.clone())
|
||||||
|
.collect();
|
||||||
|
// A permanent service tombstone alone prevents every former field's replay.
|
||||||
|
next.entries
|
||||||
|
.retain(|(id, key), _| !deleted.contains(id) || key == "deleted");
|
||||||
|
let ids = next.ids();
|
||||||
|
if ids.len().saturating_sub(deleted.len()) > limits.max_vips
|
||||||
|
|| deleted.len() > limits.max_vip_tombstones
|
||||||
|
|| ids
|
||||||
|
.iter()
|
||||||
|
.any(|id| next.entries(id).len() > limits.max_vip_fields)
|
||||||
|
{
|
||||||
|
return Err(invalid(
|
||||||
|
"VIP state capacity exceeded; deletion protection is retained",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let changed = self.entries != next.entries;
|
||||||
|
*self = next;
|
||||||
|
Ok(changed)
|
||||||
|
}
|
||||||
|
/// Materialized configuration. A service tombstone permanently retires its id.
|
||||||
|
pub fn configs(&self) -> Vec<VipConfig> {
|
||||||
|
self.ids()
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|id| self.config(&id))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
fn config(&self, id: &str) -> Option<VipConfig> {
|
||||||
|
let fields = self.entries(id);
|
||||||
|
if fields
|
||||||
|
.iter()
|
||||||
|
.any(|e| e.key == "deleted" && e.value.is_some())
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let name = fields
|
||||||
|
.iter()
|
||||||
|
.find(|e| e.key == "name")?
|
||||||
|
.value
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|v| postcard::from_bytes::<String>(v).ok())?;
|
||||||
|
let mut listeners: Vec<Listener> = fields
|
||||||
|
.iter()
|
||||||
|
.filter(|e| e.key.starts_with("l/"))
|
||||||
|
.filter_map(|e| e.value.as_ref().and_then(|v| postcard::from_bytes(v).ok()))
|
||||||
|
.collect();
|
||||||
|
for l in &mut listeners {
|
||||||
|
l.backends = fields
|
||||||
|
.iter()
|
||||||
|
.filter(|e| {
|
||||||
|
e.key
|
||||||
|
.starts_with(&format!("b/{}/{}/{}/", l.protocol, l.port, l.id))
|
||||||
|
})
|
||||||
|
.filter_map(|e| e.value.as_ref().and_then(|v| postcard::from_bytes(v).ok()))
|
||||||
|
.collect();
|
||||||
|
l.backends.sort();
|
||||||
|
}
|
||||||
|
listeners.sort_by_key(|l| (l.protocol, l.port));
|
||||||
|
Some(VipConfig {
|
||||||
|
id: id.into(),
|
||||||
|
name,
|
||||||
|
listeners,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// Builds a signed patch from the user's complete, version-checked draft.
|
||||||
|
pub fn edit(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
secret: &SecretKey,
|
||||||
|
version: u64,
|
||||||
|
config: &VipConfig,
|
||||||
|
expected: Option<&str>,
|
||||||
|
limits: &Limits,
|
||||||
|
) -> Result<Vec<VipEntry>> {
|
||||||
|
config.validate(limits)?;
|
||||||
|
if let Some(revision) = expected {
|
||||||
|
if revision != self.revision(&config.id) {
|
||||||
|
return Err(invalid("VIP changed while editing; reload before saving"));
|
||||||
|
}
|
||||||
|
} else if !self.entries(&config.id).is_empty() {
|
||||||
|
return Err(invalid("VIP id already exists"));
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.entries
|
||||||
|
.get(&(config.id.clone(), "deleted".into()))
|
||||||
|
.is_some_and(|e| e.value.is_some())
|
||||||
|
{
|
||||||
|
return Err(invalid("VIP was deleted; create a new VIP"));
|
||||||
|
}
|
||||||
|
let before = self
|
||||||
|
.config(&config.id)
|
||||||
|
.map(|c| flatten(&c))
|
||||||
|
.transpose()?
|
||||||
|
.unwrap_or_default();
|
||||||
|
let after = flatten(config)?;
|
||||||
|
let keys: BTreeSet<_> = before.keys().chain(after.keys()).cloned().collect();
|
||||||
|
let changes = keys
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|key| {
|
||||||
|
let value = after.get(&key).cloned();
|
||||||
|
(before.get(&key) != value.as_ref()).then_some((key, value))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
self.sign(network, secret, version, &config.id, changes)
|
||||||
|
}
|
||||||
|
/// Builds a permanent service tombstone after checking the selected revision.
|
||||||
|
pub fn delete(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
secret: &SecretKey,
|
||||||
|
version: u64,
|
||||||
|
id: &str,
|
||||||
|
expected: &str,
|
||||||
|
) -> Result<Vec<VipEntry>> {
|
||||||
|
if self.config(id).is_none() || self.revision(id) != expected {
|
||||||
|
return Err(invalid("VIP missing or changed while editing"));
|
||||||
|
}
|
||||||
|
self.sign(
|
||||||
|
network,
|
||||||
|
secret,
|
||||||
|
version,
|
||||||
|
id,
|
||||||
|
vec![("deleted".into(), Some(vec![1]))],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
fn sign(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
secret: &SecretKey,
|
||||||
|
version: u64,
|
||||||
|
id: &str,
|
||||||
|
changes: Vec<(String, Option<Vec<u8>>)>,
|
||||||
|
) -> Result<Vec<VipEntry>> {
|
||||||
|
let clock = self
|
||||||
|
.entries
|
||||||
|
.values()
|
||||||
|
.map(|e| e.clock)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0)
|
||||||
|
.checked_add(1)
|
||||||
|
.filter(|n| *n <= i64::MAX as u64)
|
||||||
|
.ok_or_else(|| invalid("VIP clock exhausted"))?;
|
||||||
|
Ok(changes
|
||||||
|
.into_iter()
|
||||||
|
.map(|(key, value)| {
|
||||||
|
let mut e = VipEntry {
|
||||||
|
network: *network.as_bytes(),
|
||||||
|
vip: id.into(),
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
clock,
|
||||||
|
author: *secret.public().as_bytes(),
|
||||||
|
version,
|
||||||
|
signature: vec![],
|
||||||
|
};
|
||||||
|
e.signature = secret.sign(&e.bytes()).to_bytes().to_vec();
|
||||||
|
e
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub(crate) fn flatten(cfg: &VipConfig) -> Result<BTreeMap<String, Vec<u8>>> {
|
||||||
|
let mut fields = BTreeMap::new();
|
||||||
|
fields.insert(
|
||||||
|
"name".into(),
|
||||||
|
postcard::to_stdvec(&cfg.name).map_err(|e| invalid(e.to_string()))?,
|
||||||
|
);
|
||||||
|
for l in &cfg.listeners {
|
||||||
|
let mut settings = l.clone();
|
||||||
|
settings.backends.clear();
|
||||||
|
fields.insert(
|
||||||
|
format!("l/{}/{}", l.protocol, l.port),
|
||||||
|
postcard::to_stdvec(&settings).map_err(|e| invalid(e.to_string()))?,
|
||||||
|
);
|
||||||
|
for b in &l.backends {
|
||||||
|
fields.insert(
|
||||||
|
format!("b/{}/{}/{}/{}/{}", l.protocol, l.port, l.id, b.peer, b.port),
|
||||||
|
postcard::to_stdvec(b).map_err(|e| invalid(e.to_string()))?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(fields)
|
||||||
|
}
|
||||||
|
impl VipSet {
|
||||||
|
/// Allocates internal addresses deterministically against durable node claims.
|
||||||
|
pub(crate) fn views(
|
||||||
|
&self,
|
||||||
|
range: Option<crate::state::Ipv4Range>,
|
||||||
|
mut taken: std::collections::HashSet<Ipv4Addr>,
|
||||||
|
hostnames: &BTreeSet<String>,
|
||||||
|
limits: &Limits,
|
||||||
|
) -> Vec<VipStatus> {
|
||||||
|
let mut names = hostnames.clone();
|
||||||
|
let mut result = Vec::new();
|
||||||
|
for config in self.configs() {
|
||||||
|
let mut error = config.validate(limits).err().map(|e| e.to_string());
|
||||||
|
if !names.insert(config.name.clone()) {
|
||||||
|
error = Some("name conflicts with another VIP or node".into());
|
||||||
|
}
|
||||||
|
let address = range.and_then(|r| {
|
||||||
|
let usable = crate::state::allocator::usable_addresses(r);
|
||||||
|
if usable == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let digest = Sha256::digest(config.id.as_bytes());
|
||||||
|
let seed = u64::from_be_bytes([
|
||||||
|
digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6],
|
||||||
|
digest[7],
|
||||||
|
]);
|
||||||
|
let bits = 32 - u32::from(r.prefix_len);
|
||||||
|
let mask = if bits == 32 { 0 } else { u32::MAX << bits };
|
||||||
|
(0..usable).find_map(|step| {
|
||||||
|
let offset = (seed.wrapping_add(step) % usable + 1) as u32;
|
||||||
|
let ip = Ipv4Addr::from((u32::from(r.base) & mask) | offset);
|
||||||
|
taken.insert(ip).then_some(ip)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if address.is_none() {
|
||||||
|
error = Some("no free overlay address".into());
|
||||||
|
}
|
||||||
|
result.push(VipStatus {
|
||||||
|
revision: self.revision(&config.id),
|
||||||
|
config,
|
||||||
|
address,
|
||||||
|
error,
|
||||||
|
listeners: vec![],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -370,6 +370,25 @@ impl Storage {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Loads mandatory signed VIP fields with a strict capacity bound.
|
||||||
|
pub async fn vip_fields(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
max: usize,
|
||||||
|
) -> Result<Vec<crate::vip::VipEntry>> {
|
||||||
|
self.with_state(move |state| state.vip_fields(network, max))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
/// Stores a complete merged service snapshot and optional own counter.
|
||||||
|
pub async fn put_vip_fields(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
entries: Vec<crate::vip::VipEntry>,
|
||||||
|
own: Option<([u8; 32], u64)>,
|
||||||
|
) -> Result<()> {
|
||||||
|
self.with_state(move |state| state.put_vip_fields(network, &entries, own))
|
||||||
|
.await
|
||||||
|
}
|
||||||
/// Loads verified durable cleanup proofs off the executor.
|
/// Loads verified durable cleanup proofs off the executor.
|
||||||
pub async fn retirements(
|
pub async fn retirements(
|
||||||
&self,
|
&self,
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use crate::identity::{DeviceIdentity, NetworkId, NetworkName, NetworkSecret};
|
|||||||
use crate::state::{MAX_RETIREMENT_LEN, RecordBody, SignedRecord, SignedRetirement};
|
use crate::state::{MAX_RETIREMENT_LEN, RecordBody, SignedRecord, SignedRetirement};
|
||||||
|
|
||||||
/// Schema version written by this build.
|
/// Schema version written by this build.
|
||||||
pub const SCHEMA_VERSION: i64 = 9;
|
pub const SCHEMA_VERSION: i64 = 10;
|
||||||
|
|
||||||
/// Key of the stored hostname setting.
|
/// Key of the stored hostname setting.
|
||||||
const SETTING_HOSTNAME: &str = "hostname";
|
const SETTING_HOSTNAME: &str = "hostname";
|
||||||
@@ -263,6 +263,12 @@ impl StateStore {
|
|||||||
)
|
)
|
||||||
.map_err(|err| self.corrupt(format!("cannot migrate schema to 9: {err}")))?;
|
.map_err(|err| self.corrupt(format!("cannot migrate schema to 9: {err}")))?;
|
||||||
}
|
}
|
||||||
|
if found < 10 {
|
||||||
|
self.conn.execute_batch("BEGIN; CREATE TABLE IF NOT EXISTS vip_fields (
|
||||||
|
network_id BLOB NOT NULL, vip TEXT NOT NULL, field TEXT NOT NULL, data BLOB NOT NULL,
|
||||||
|
PRIMARY KEY(network_id, vip, field)); PRAGMA user_version = 10; COMMIT;")
|
||||||
|
.map_err(|err| self.corrupt(format!("cannot migrate VIP state: {err}")))?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,6 +282,7 @@ impl StateStore {
|
|||||||
"signed_records",
|
"signed_records",
|
||||||
"peer_hostnames",
|
"peer_hostnames",
|
||||||
"retirements",
|
"retirements",
|
||||||
|
"vip_fields",
|
||||||
] {
|
] {
|
||||||
let present: Option<String> = self
|
let present: Option<String> = self
|
||||||
.conn
|
.conn
|
||||||
@@ -894,8 +901,77 @@ impl StateStore {
|
|||||||
.map_err(|err| Error::Storage(format!("cannot commit retirement: {err}")))
|
.map_err(|err| Error::Storage(format!("cannot commit retirement: {err}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reads bounded mandatory VIP state; corrupt records fail activation.
|
||||||
|
pub fn vip_fields(&self, network: NetworkId, max: usize) -> Result<Vec<crate::vip::VipEntry>> {
|
||||||
|
let mut stmt = self.conn.prepare("SELECT CASE WHEN length(data) <= 1024 THEN data ELSE NULL END FROM vip_fields WHERE network_id=?1 ORDER BY vip, field")
|
||||||
|
.map_err(|e| self.corrupt(e.to_string()))?;
|
||||||
|
let mut rows = stmt
|
||||||
|
.query(params![network.as_bytes().as_slice()])
|
||||||
|
.map_err(|e| self.corrupt(e.to_string()))?;
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
while let Some(row) = rows.next().map_err(|e| self.corrupt(e.to_string()))? {
|
||||||
|
if entries.len() >= max {
|
||||||
|
return Err(self.corrupt("stored VIP state exceeds configured limits"));
|
||||||
|
}
|
||||||
|
let bytes: Option<Vec<u8>> = row.get(0).map_err(|e| self.corrupt(e.to_string()))?;
|
||||||
|
let bytes = bytes.ok_or_else(|| self.corrupt("oversized VIP field"))?;
|
||||||
|
let entry: crate::vip::VipEntry =
|
||||||
|
postcard::from_bytes(&bytes).map_err(|e| self.corrupt(e.to_string()))?;
|
||||||
|
entry
|
||||||
|
.verify(network)
|
||||||
|
.map_err(|e| self.corrupt(e.to_string()))?;
|
||||||
|
entries.push(entry);
|
||||||
|
}
|
||||||
|
Ok(entries)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commits a validated VIP snapshot and optional author counter atomically.
|
||||||
|
pub fn put_vip_fields(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
entries: &[crate::vip::VipEntry],
|
||||||
|
own: Option<([u8; 32], u64)>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let tx = self
|
||||||
|
.conn
|
||||||
|
.unchecked_transaction()
|
||||||
|
.map_err(|e| Error::Storage(e.to_string()))?;
|
||||||
|
if let Some(first) = entries.first() {
|
||||||
|
if entries.iter().any(|e| e.vip != first.vip) {
|
||||||
|
return Err(Error::Storage(
|
||||||
|
"VIP snapshot mixes service identities".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
tx.execute(
|
||||||
|
"DELETE FROM vip_fields WHERE network_id=?1 AND vip=?2",
|
||||||
|
params![network.as_bytes().as_slice(), first.vip],
|
||||||
|
)
|
||||||
|
.map_err(|e| Error::Storage(e.to_string()))?;
|
||||||
|
}
|
||||||
|
for e in entries {
|
||||||
|
e.verify(network)?;
|
||||||
|
let bytes = postcard::to_stdvec(e).map_err(|e| Error::Storage(e.to_string()))?;
|
||||||
|
if bytes.len() > 1024 {
|
||||||
|
return Err(Error::Storage("oversized VIP field".into()));
|
||||||
|
}
|
||||||
|
tx.execute("INSERT INTO vip_fields(network_id,vip,field,data) VALUES(?1,?2,?3,?4) ON CONFLICT(network_id,vip,field) DO UPDATE SET data=excluded.data",
|
||||||
|
params![network.as_bytes().as_slice(),e.vip,e.key,bytes]).map_err(|e|Error::Storage(e.to_string()))?;
|
||||||
|
}
|
||||||
|
if let Some((author, version)) = own {
|
||||||
|
tx.execute("INSERT INTO own_record_version(network_id,author,version) VALUES(?1,?2,?3) ON CONFLICT(network_id,author) DO UPDATE SET version=max(version,excluded.version)",
|
||||||
|
params![network.as_bytes().as_slice(),author.as_slice(),version as i64]).map_err(|e|Error::Storage(e.to_string()))?;
|
||||||
|
}
|
||||||
|
tx.commit().map_err(|e| Error::Storage(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
/// Drops a forgotten network's local cleanup proofs.
|
/// Drops a forgotten network's local cleanup proofs.
|
||||||
pub fn forget_retirements(&self, network: NetworkId) -> Result<()> {
|
pub fn forget_retirements(&self, network: NetworkId) -> Result<()> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"DELETE FROM vip_fields WHERE network_id = ?1",
|
||||||
|
params![network.as_bytes().as_slice()],
|
||||||
|
)
|
||||||
|
.map_err(|e| Error::Storage(e.to_string()))?;
|
||||||
self.conn
|
self.conn
|
||||||
.execute(
|
.execute(
|
||||||
"DELETE FROM retirements WHERE network_id = ?1",
|
"DELETE FROM retirements WHERE network_id = ?1",
|
||||||
@@ -1333,3 +1409,59 @@ mod broadcast_storage_tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod vip_tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn vip_migration_and_counter_failure_preserve_identity_and_rollback_fields() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
let path = dir.path().join("state.sqlite");
|
||||||
|
let store = StateStore::open(&path).unwrap();
|
||||||
|
let identity = store.load_or_create_device_identity().unwrap();
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute_batch("DROP TABLE vip_fields; PRAGMA user_version=9;")
|
||||||
|
.unwrap();
|
||||||
|
drop(store);
|
||||||
|
let store = StateStore::open(&path).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
store.device_identity().unwrap().unwrap().endpoint_id(),
|
||||||
|
identity.endpoint_id()
|
||||||
|
);
|
||||||
|
let net = NetworkId::from_bytes([7; 32]);
|
||||||
|
let key = identity.signing_key();
|
||||||
|
let config = crate::vip::VipConfig::new("api");
|
||||||
|
let fields = crate::vip::VipSet::default()
|
||||||
|
.edit(net, &key, 7, &config, None, &crate::Limits::default())
|
||||||
|
.unwrap();
|
||||||
|
store.conn.execute_batch("CREATE TRIGGER fail_vip_counter BEFORE INSERT ON own_record_version BEGIN SELECT RAISE(ABORT,'counter unavailable'); END;").unwrap();
|
||||||
|
assert!(
|
||||||
|
store
|
||||||
|
.put_vip_fields(net, &fields, Some((*key.public().as_bytes(), 7)))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(store.vip_fields(net, 192).unwrap().is_empty());
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute_batch("DROP TRIGGER fail_vip_counter;")
|
||||||
|
.unwrap();
|
||||||
|
store
|
||||||
|
.put_vip_fields(net, &fields, Some((*key.public().as_bytes(), 7)))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(store.vip_fields(net, 192).unwrap(), fields);
|
||||||
|
assert_eq!(store.own_record_version(net, key.public()).unwrap(), 7);
|
||||||
|
drop(store);
|
||||||
|
let reopened = StateStore::open(path).unwrap();
|
||||||
|
assert_eq!(reopened.vip_fields(net, 192).unwrap(), fields);
|
||||||
|
reopened
|
||||||
|
.conn
|
||||||
|
.execute("UPDATE vip_fields SET data=?1", params![vec![0xffu8; 1025]])
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
reopened.vip_fields(net, 192),
|
||||||
|
Err(Error::StateCorrupted { .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
//! Named, shared virtual services. Signed field registers converge without an
|
||||||
|
//! owner; routing, health and connection state remain local to each client.
|
||||||
|
use crate::Limits;
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use iroh::EndpointId;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::net::Ipv4Addr;
|
||||||
|
pub(crate) mod packet;
|
||||||
|
pub(crate) mod router;
|
||||||
|
pub use crate::state::vip::{VipEntry, VipSet};
|
||||||
|
pub(crate) use router::VipRouter;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
|
||||||
|
/// IP transport carried by a listener.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Protocol {
|
||||||
|
/// TCP.
|
||||||
|
Tcp,
|
||||||
|
/// UDP.
|
||||||
|
Udp,
|
||||||
|
}
|
||||||
|
impl std::fmt::Display for Protocol {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str(match self {
|
||||||
|
Self::Tcp => "tcp",
|
||||||
|
Self::Udp => "udp",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl std::str::FromStr for Protocol {
|
||||||
|
type Err = String;
|
||||||
|
fn from_str(s: &str) -> std::result::Result<Self, String> {
|
||||||
|
match s {
|
||||||
|
"tcp" => Ok(Self::Tcp),
|
||||||
|
"udp" => Ok(Self::Udp),
|
||||||
|
_ => Err("protocol must be tcp or udp".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// A node identity and its application port.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Backend {
|
||||||
|
/// Full device identity, resolved when editing.
|
||||||
|
pub peer: String,
|
||||||
|
/// Destination port.
|
||||||
|
pub port: u16,
|
||||||
|
}
|
||||||
|
/// One independently routed port of a VIP.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Listener {
|
||||||
|
/// Stable listener generation; prevents removed backend fields resurfacing on re-creation.
|
||||||
|
pub id: String,
|
||||||
|
/// TCP or UDP.
|
||||||
|
pub protocol: Protocol,
|
||||||
|
/// Client-facing port.
|
||||||
|
pub port: u16,
|
||||||
|
/// Enable active TCP connect checks; UDP uses path checks and ICMP errors.
|
||||||
|
pub port_check: bool,
|
||||||
|
/// Period between checks in milliseconds.
|
||||||
|
pub check_interval_ms: u32,
|
||||||
|
/// Deadline of a port check in milliseconds.
|
||||||
|
pub check_timeout_ms: u32,
|
||||||
|
/// Consecutive failed checks before exclusion.
|
||||||
|
pub failure_threshold: u8,
|
||||||
|
/// Consecutive successes before recovery.
|
||||||
|
pub recovery_threshold: u8,
|
||||||
|
/// Idle expiry for this listener's flows, in seconds.
|
||||||
|
pub idle_timeout_secs: u32,
|
||||||
|
/// Allowed destination nodes and ports.
|
||||||
|
pub backends: Vec<Backend>,
|
||||||
|
}
|
||||||
|
impl Listener {
|
||||||
|
/// Creates a listener with automatic recovery and bounded checks.
|
||||||
|
pub fn new(protocol: Protocol, port: u16) -> Self {
|
||||||
|
Self {
|
||||||
|
id: hex::encode(rand::random::<[u8; 16]>()),
|
||||||
|
protocol,
|
||||||
|
port,
|
||||||
|
port_check: true,
|
||||||
|
check_interval_ms: 3000,
|
||||||
|
check_timeout_ms: 2000,
|
||||||
|
failure_threshold: 2,
|
||||||
|
recovery_threshold: 1,
|
||||||
|
idle_timeout_secs: if protocol == Protocol::Tcp { 7200 } else { 120 },
|
||||||
|
backends: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Entire editable service; its address is an internal derived reservation.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct VipConfig {
|
||||||
|
/// Stable random 128-bit id in hexadecimal.
|
||||||
|
pub id: String,
|
||||||
|
/// One DNS label, unique within the network.
|
||||||
|
pub name: String,
|
||||||
|
/// Independent listeners.
|
||||||
|
pub listeners: Vec<Listener>,
|
||||||
|
}
|
||||||
|
impl VipConfig {
|
||||||
|
/// Creates an empty named service with a fresh stable identity.
|
||||||
|
pub fn new(name: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
id: hex::encode(rand::random::<[u8; 16]>()),
|
||||||
|
name: name.into(),
|
||||||
|
listeners: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Validates a complete draft before any state is changed.
|
||||||
|
pub fn validate(&self, limits: &Limits) -> Result<()> {
|
||||||
|
if self.id.len() != 32 || hex::decode(&self.id).is_err() {
|
||||||
|
return Err(invalid("invalid VIP id"));
|
||||||
|
}
|
||||||
|
if self.name.is_empty()
|
||||||
|
|| self.name.len() > 63
|
||||||
|
|| self.name.starts_with('-')
|
||||||
|
|| self.name.ends_with('-')
|
||||||
|
|| !self
|
||||||
|
.name
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||||
|
{
|
||||||
|
return Err(invalid(
|
||||||
|
"VIP name must be a lowercase DNS label (letters, digits and hyphens)",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self.listeners.len() > limits.max_vip_listeners {
|
||||||
|
return Err(invalid("too many VIP listeners"));
|
||||||
|
}
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
for l in &self.listeners {
|
||||||
|
if l.id.len() != 32 || hex::decode(&l.id).is_err() {
|
||||||
|
return Err(invalid("invalid listener identity"));
|
||||||
|
}
|
||||||
|
if l.port == 0 || !seen.insert((l.protocol, l.port)) {
|
||||||
|
return Err(invalid(
|
||||||
|
"listener ports must be nonzero and unique per protocol",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !(250..=3_600_000).contains(&l.check_interval_ms)
|
||||||
|
|| !(100..=60_000).contains(&l.check_timeout_ms)
|
||||||
|
|| l.failure_threshold == 0
|
||||||
|
|| l.recovery_threshold == 0
|
||||||
|
|| !(1..=604800).contains(&l.idle_timeout_secs)
|
||||||
|
{
|
||||||
|
return Err(invalid(
|
||||||
|
"invalid check interval, timeout, thresholds or flow idle timeout",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if l.backends.len() > limits.max_vip_backends {
|
||||||
|
return Err(invalid("too many listener backends"));
|
||||||
|
}
|
||||||
|
let mut backends = BTreeSet::new();
|
||||||
|
for b in &l.backends {
|
||||||
|
if b.port == 0 || b.peer.parse::<EndpointId>().is_err() || !backends.insert(b) {
|
||||||
|
return Err(invalid(
|
||||||
|
"backend must have a unique node identity and a nonzero port",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if crate::state::vip::flatten(self)?.len() > limits.max_vip_fields {
|
||||||
|
return Err(invalid("VIP configuration exceeds signed field capacity"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub(crate) fn invalid(reason: impl Into<String>) -> Error {
|
||||||
|
Error::Rejected {
|
||||||
|
reason: reason.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Cumulative IP traffic, excluding probes. Reset on agent restart.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Counters {
|
||||||
|
/// Outbound packets.
|
||||||
|
pub tx_packets: u64,
|
||||||
|
/// Outbound bytes.
|
||||||
|
pub tx_bytes: u64,
|
||||||
|
/// Inbound packets.
|
||||||
|
pub rx_packets: u64,
|
||||||
|
/// Inbound bytes.
|
||||||
|
pub rx_bytes: u64,
|
||||||
|
/// Created flow bindings.
|
||||||
|
pub flows: u64,
|
||||||
|
/// UDP failovers.
|
||||||
|
pub failovers: u64,
|
||||||
|
/// Packets rejected or lacking an eligible backend.
|
||||||
|
pub dropped: u64,
|
||||||
|
}
|
||||||
|
/// One backend, as seen by this client.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BackendStatus {
|
||||||
|
/// Configured endpoint.
|
||||||
|
pub backend: Backend,
|
||||||
|
/// Eligibility and reason.
|
||||||
|
pub state: String,
|
||||||
|
/// Smoothed full data-plane RTT, microseconds; unknown stays absent.
|
||||||
|
pub rtt_us: Option<u64>,
|
||||||
|
/// Last successful path measurement age.
|
||||||
|
pub measurement_age_ms: Option<u64>,
|
||||||
|
/// Current bindings.
|
||||||
|
pub active_flows: u32,
|
||||||
|
/// Local traffic counters.
|
||||||
|
pub counters: Counters,
|
||||||
|
}
|
||||||
|
/// Runtime view of one listener.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ListenerStatus {
|
||||||
|
/// Protocol.
|
||||||
|
pub protocol: Protocol,
|
||||||
|
/// Frontend port.
|
||||||
|
pub port: u16,
|
||||||
|
/// Best backend for a new flow, if measured and eligible.
|
||||||
|
pub selected: Option<Backend>,
|
||||||
|
/// Configured and draining endpoints.
|
||||||
|
pub backends: Vec<BackendStatus>,
|
||||||
|
/// Local counters.
|
||||||
|
pub counters: Counters,
|
||||||
|
}
|
||||||
|
/// Configuration and local diagnostics returned through the same API to CLI and GUI.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct VipStatus {
|
||||||
|
/// Persisted configuration.
|
||||||
|
pub config: VipConfig,
|
||||||
|
/// Opaque revision used when saving a draft.
|
||||||
|
pub revision: String,
|
||||||
|
/// Internal service address.
|
||||||
|
pub address: Option<Ipv4Addr>,
|
||||||
|
/// Conflict or allocation issue, if any.
|
||||||
|
pub error: Option<String>,
|
||||||
|
/// Local listener status.
|
||||||
|
pub listeners: Vec<ListenerStatus>,
|
||||||
|
}
|
||||||
@@ -0,0 +1,566 @@
|
|||||||
|
//! Bounded IPv4 parsing, NAT checksums and fragment reassembly at local ingress.
|
||||||
|
use super::Protocol;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::net::Ipv4Addr;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct Tuple {
|
||||||
|
pub src: Ipv4Addr,
|
||||||
|
pub dst: Ipv4Addr,
|
||||||
|
pub sport: u16,
|
||||||
|
pub dport: u16,
|
||||||
|
pub protocol: Protocol,
|
||||||
|
}
|
||||||
|
impl Tuple {
|
||||||
|
pub fn reverse(self) -> Self {
|
||||||
|
Self {
|
||||||
|
src: self.dst,
|
||||||
|
dst: self.src,
|
||||||
|
sport: self.dport,
|
||||||
|
dport: self.sport,
|
||||||
|
protocol: self.protocol,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub(crate) fn header(p: &[u8]) -> Option<usize> {
|
||||||
|
if p.len() < 20 || p[0] >> 4 != 4 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n = usize::from(p[0] & 15) * 4;
|
||||||
|
let total = usize::from(u16::from_be_bytes([p[2], p[3]]));
|
||||||
|
(n >= 20 && n <= p.len() && total == p.len() && checksum(&p[..n]) == 0).then_some(n)
|
||||||
|
}
|
||||||
|
pub(crate) fn addresses(p: &[u8]) -> Option<(Ipv4Addr, Ipv4Addr)> {
|
||||||
|
header(p)?;
|
||||||
|
Some((
|
||||||
|
Ipv4Addr::new(p[12], p[13], p[14], p[15]),
|
||||||
|
Ipv4Addr::new(p[16], p[17], p[18], p[19]),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
pub(crate) fn tuple(p: &[u8]) -> Option<Tuple> {
|
||||||
|
let n = header(p)?;
|
||||||
|
if u16::from_be_bytes([p[6], p[7]]) & 0x3fff != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let protocol = match p[9] {
|
||||||
|
6 => Protocol::Tcp,
|
||||||
|
17 => Protocol::Udp,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let min = if protocol == Protocol::Tcp { 20 } else { 8 };
|
||||||
|
if p.len() < n + min {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if protocol == Protocol::Tcp {
|
||||||
|
let h = usize::from(p[n + 12] >> 4) * 4;
|
||||||
|
if h < 20 || n + h > p.len() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
} else if usize::from(u16::from_be_bytes([p[n + 4], p[n + 5]])) != p.len() - n {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let (src, dst) = addresses(p)?;
|
||||||
|
Some(Tuple {
|
||||||
|
src,
|
||||||
|
dst,
|
||||||
|
sport: u16::from_be_bytes([p[n], p[n + 1]]),
|
||||||
|
dport: u16::from_be_bytes([p[n + 2], p[n + 3]]),
|
||||||
|
protocol,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub(crate) fn rewrite(p: &[u8], t: Tuple) -> Option<Bytes> {
|
||||||
|
let n = header(p)?;
|
||||||
|
if p.len() < n + if t.protocol == Protocol::Tcp { 20 } else { 8 } {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut out = p.to_vec();
|
||||||
|
out[12..16].copy_from_slice(&t.src.octets());
|
||||||
|
out[16..20].copy_from_slice(&t.dst.octets());
|
||||||
|
out[n..n + 2].copy_from_slice(&t.sport.to_be_bytes());
|
||||||
|
out[n + 2..n + 4].copy_from_slice(&t.dport.to_be_bytes());
|
||||||
|
finish(&mut out, n, t.protocol);
|
||||||
|
Some(Bytes::from(out))
|
||||||
|
}
|
||||||
|
fn finish(p: &mut [u8], n: usize, protocol: Protocol) {
|
||||||
|
p[10..12].fill(0);
|
||||||
|
let c = checksum(&p[..n]);
|
||||||
|
p[10..12].copy_from_slice(&c.to_be_bytes());
|
||||||
|
let offset = n + if protocol == Protocol::Tcp { 16 } else { 6 };
|
||||||
|
p[offset..offset + 2].fill(0);
|
||||||
|
let mut sum = 0u32;
|
||||||
|
for pair in p[12..20].as_chunks::<2>().0 {
|
||||||
|
sum += u32::from(u16::from_be_bytes([pair[0], pair[1]]));
|
||||||
|
}
|
||||||
|
sum += u32::from(p[9]) + (p.len() - n) as u32;
|
||||||
|
let c = checksum_seed(&p[n..], sum);
|
||||||
|
let c = if c == 0 && protocol == Protocol::Udp {
|
||||||
|
0xffff
|
||||||
|
} else {
|
||||||
|
c
|
||||||
|
};
|
||||||
|
p[offset..offset + 2].copy_from_slice(&c.to_be_bytes());
|
||||||
|
}
|
||||||
|
pub(crate) fn checksum(p: &[u8]) -> u16 {
|
||||||
|
checksum_seed(p, 0)
|
||||||
|
}
|
||||||
|
fn checksum_seed(p: &[u8], mut sum: u32) -> u16 {
|
||||||
|
for pair in p.chunks(2) {
|
||||||
|
sum += u32::from(u16::from_be_bytes([pair[0], *pair.get(1).unwrap_or(&0)]));
|
||||||
|
}
|
||||||
|
while sum >> 16 != 0 {
|
||||||
|
sum = (sum & 0xffff) + (sum >> 16);
|
||||||
|
}
|
||||||
|
!(sum as u16)
|
||||||
|
}
|
||||||
|
pub(crate) fn tcp_syn(p: &[u8]) -> bool {
|
||||||
|
header(p).is_some_and(|n| p[9] == 6 && p.get(n + 13).is_some_and(|f| f & 0x12 == 2))
|
||||||
|
}
|
||||||
|
pub(crate) fn syn_sequence(p: &[u8]) -> Option<u32> {
|
||||||
|
if !tcp_syn(p) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n = header(p)?;
|
||||||
|
let bytes = p.get(n + 4..n + 8)?;
|
||||||
|
Some(u32::from_be_bytes(bytes.try_into().ok()?))
|
||||||
|
}
|
||||||
|
pub(crate) fn empty_syn(p: &[u8]) -> bool {
|
||||||
|
header(p).is_some_and(|n| {
|
||||||
|
tcp_syn(p)
|
||||||
|
&& p.get(n + 12)
|
||||||
|
.is_some_and(|h| n + usize::from(h >> 4) * 4 == p.len())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub(crate) fn syn_ack(p: &[u8]) -> bool {
|
||||||
|
header(p).is_some_and(|n| p[9] == 6 && p.get(n + 13).is_some_and(|f| f & 0x12 == 0x12))
|
||||||
|
}
|
||||||
|
pub(crate) fn tcp_reset(p: &[u8]) -> bool {
|
||||||
|
header(p).is_some_and(|n| p[9] == 6 && p.get(n + 13).is_some_and(|f| f & 4 != 0))
|
||||||
|
}
|
||||||
|
/// Rewrites an ICMP error and its quoted original header after NAT lookup.
|
||||||
|
pub(crate) fn icmp_quote(p: &[u8]) -> Option<Tuple> {
|
||||||
|
let n = header(p)?;
|
||||||
|
if p[9] != 1 || p.len() < n + 8 + 28 || ![3, 11, 12].contains(&p[n]) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let q = &p[n + 8..];
|
||||||
|
let h = usize::from(q[0] & 15) * 4;
|
||||||
|
if q[0] >> 4 != 4 || h < 20 || q.len() < h + 8 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let protocol = match q[9] {
|
||||||
|
6 => Protocol::Tcp,
|
||||||
|
17 => Protocol::Udp,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(Tuple {
|
||||||
|
src: Ipv4Addr::new(q[12], q[13], q[14], q[15]),
|
||||||
|
dst: Ipv4Addr::new(q[16], q[17], q[18], q[19]),
|
||||||
|
sport: u16::from_be_bytes([q[h], q[h + 1]]),
|
||||||
|
dport: u16::from_be_bytes([q[h + 2], q[h + 3]]),
|
||||||
|
protocol,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub(crate) fn rewrite_icmp(p: &[u8], original: Tuple) -> Option<Bytes> {
|
||||||
|
let n = header(p)?;
|
||||||
|
icmp_quote(p)?;
|
||||||
|
let mut out = p.to_vec();
|
||||||
|
out[12..16].copy_from_slice(&original.dst.octets());
|
||||||
|
out[16..20].copy_from_slice(&original.src.octets());
|
||||||
|
let q = &mut out[n + 8..];
|
||||||
|
let h = usize::from(q[0] & 15) * 4;
|
||||||
|
// Incrementally update the quoted transport checksum when it is present.
|
||||||
|
let off = h + if original.protocol == Protocol::Tcp {
|
||||||
|
16
|
||||||
|
} else {
|
||||||
|
6
|
||||||
|
};
|
||||||
|
if q.len() >= off + 2 {
|
||||||
|
let old = u16::from_be_bytes([q[off], q[off + 1]]);
|
||||||
|
if old != 0 || original.protocol == Protocol::Tcp {
|
||||||
|
let mut sum = u32::from(!old);
|
||||||
|
let mut replacement = Vec::from(original.src.octets());
|
||||||
|
replacement.extend(original.dst.octets());
|
||||||
|
replacement.extend(original.sport.to_be_bytes());
|
||||||
|
replacement.extend(original.dport.to_be_bytes());
|
||||||
|
let previous = [&q[12..20], &q[h..h + 4]].concat();
|
||||||
|
for (a, b) in previous
|
||||||
|
.as_chunks::<2>()
|
||||||
|
.0
|
||||||
|
.iter()
|
||||||
|
.zip(replacement.as_chunks::<2>().0)
|
||||||
|
{
|
||||||
|
sum += u32::from(!u16::from_be_bytes([a[0], a[1]]))
|
||||||
|
+ u32::from(u16::from_be_bytes([b[0], b[1]]));
|
||||||
|
}
|
||||||
|
while sum >> 16 != 0 {
|
||||||
|
sum = (sum & 0xffff) + (sum >> 16);
|
||||||
|
}
|
||||||
|
let c = !(sum as u16);
|
||||||
|
q[off..off + 2].copy_from_slice(
|
||||||
|
&(if c == 0 && original.protocol == Protocol::Udp {
|
||||||
|
0xffff
|
||||||
|
} else {
|
||||||
|
c
|
||||||
|
})
|
||||||
|
.to_be_bytes(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
q[12..16].copy_from_slice(&original.src.octets());
|
||||||
|
q[16..20].copy_from_slice(&original.dst.octets());
|
||||||
|
q[h..h + 2].copy_from_slice(&original.sport.to_be_bytes());
|
||||||
|
q[h + 2..h + 4].copy_from_slice(&original.dport.to_be_bytes());
|
||||||
|
q[10..12].fill(0);
|
||||||
|
let c = checksum(&q[..h]);
|
||||||
|
q[10..12].copy_from_slice(&c.to_be_bytes());
|
||||||
|
out[n + 2..n + 4].fill(0);
|
||||||
|
let c = checksum(&out[n..]);
|
||||||
|
out[n + 2..n + 4].copy_from_slice(&c.to_be_bytes());
|
||||||
|
out[10..12].fill(0);
|
||||||
|
let c = checksum(&out[..n]);
|
||||||
|
out[10..12].copy_from_slice(&c.to_be_bytes());
|
||||||
|
Some(Bytes::from(out))
|
||||||
|
}
|
||||||
|
pub(crate) fn reject(p: &[u8]) -> Option<Bytes> {
|
||||||
|
let t = tuple(p)?;
|
||||||
|
let n = header(p)?;
|
||||||
|
if t.protocol == Protocol::Tcp {
|
||||||
|
if !tcp_syn(p) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut out = vec![0; 40];
|
||||||
|
out[0] = 0x45;
|
||||||
|
out[2..4].copy_from_slice(&40u16.to_be_bytes());
|
||||||
|
out[8] = 64;
|
||||||
|
out[9] = 6;
|
||||||
|
out[12..16].copy_from_slice(&t.dst.octets());
|
||||||
|
out[16..20].copy_from_slice(&t.src.octets());
|
||||||
|
out[20..22].copy_from_slice(&t.dport.to_be_bytes());
|
||||||
|
out[22..24].copy_from_slice(&t.sport.to_be_bytes());
|
||||||
|
let seq = u32::from_be_bytes(p[n + 4..n + 8].try_into().ok()?);
|
||||||
|
out[28..32].copy_from_slice(&seq.wrapping_add(1).to_be_bytes());
|
||||||
|
out[32] = 0x50;
|
||||||
|
out[33] = 0x14;
|
||||||
|
finish(&mut out, 20, Protocol::Tcp);
|
||||||
|
Some(Bytes::from(out))
|
||||||
|
} else {
|
||||||
|
let q = p.len().min(n + 8);
|
||||||
|
let mut out = vec![0; 28 + q];
|
||||||
|
out[0] = 0x45;
|
||||||
|
let len = out.len() as u16;
|
||||||
|
out[2..4].copy_from_slice(&len.to_be_bytes());
|
||||||
|
out[8] = 64;
|
||||||
|
out[9] = 1;
|
||||||
|
out[12..16].copy_from_slice(&t.dst.octets());
|
||||||
|
out[16..20].copy_from_slice(&t.src.octets());
|
||||||
|
out[20] = 3;
|
||||||
|
out[21] = 3;
|
||||||
|
out[28..].copy_from_slice(&p[..q]);
|
||||||
|
let c = checksum(&out[20..]);
|
||||||
|
out[22..24].copy_from_slice(&c.to_be_bytes());
|
||||||
|
let c = checksum(&out[..20]);
|
||||||
|
out[10..12].copy_from_slice(&c.to_be_bytes());
|
||||||
|
Some(Bytes::from(out))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Datagram {
|
||||||
|
at: Instant,
|
||||||
|
header: Option<Vec<u8>>,
|
||||||
|
parts: std::collections::BTreeMap<usize, Vec<u8>>,
|
||||||
|
end: Option<usize>,
|
||||||
|
bytes: usize,
|
||||||
|
}
|
||||||
|
type FragmentKey = (Option<[u8; 32]>, Ipv4Addr, Ipv4Addr, u16, u8);
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub(crate) struct Reassembly {
|
||||||
|
pending: HashMap<FragmentKey, Datagram>,
|
||||||
|
}
|
||||||
|
impl Reassembly {
|
||||||
|
pub fn expire(&mut self, now: Instant) {
|
||||||
|
self.pending
|
||||||
|
.retain(|_, d| now.duration_since(d.at) < Duration::from_secs(5));
|
||||||
|
}
|
||||||
|
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]]);
|
||||||
|
if flags & 0x3fff == 0 {
|
||||||
|
return Some(p);
|
||||||
|
}
|
||||||
|
let now = Instant::now();
|
||||||
|
self.pending
|
||||||
|
.retain(|_, d| now.duration_since(d.at) < Duration::from_secs(5));
|
||||||
|
let (src, dst) = addresses(&p)?;
|
||||||
|
let key = (scope, src, dst, u16::from_be_bytes([p[4], p[5]]), p[9]);
|
||||||
|
let start = usize::from(flags & 0x1fff) * 8;
|
||||||
|
let payload = &p[n..];
|
||||||
|
let end = start.checked_add(payload.len())?;
|
||||||
|
if payload.is_empty()
|
||||||
|
|| end > 65515
|
||||||
|
|| flags & 0x2000 != 0 && !payload.len().is_multiple_of(8)
|
||||||
|
{
|
||||||
|
self.pending.remove(&key);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if !self.pending.contains_key(&key) && self.pending.len() >= max {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let d = self.pending.entry(key).or_insert_with(|| Datagram {
|
||||||
|
at: now,
|
||||||
|
header: None,
|
||||||
|
parts: Default::default(),
|
||||||
|
end: None,
|
||||||
|
bytes: 0,
|
||||||
|
});
|
||||||
|
if d.parts
|
||||||
|
.get(&start)
|
||||||
|
.is_some_and(|bytes| bytes.as_slice() == payload)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if d.parts.iter().any(|(s, b)| *s < end && start < s + b.len()) {
|
||||||
|
self.pending.remove(&key);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if flags & 0x2000 == 0 {
|
||||||
|
if d.end.is_some_and(|e| e != end) {
|
||||||
|
self.pending.remove(&key);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
d.end = Some(end);
|
||||||
|
}
|
||||||
|
if d.end.is_some_and(|e| end > e) {
|
||||||
|
self.pending.remove(&key);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if start == 0 {
|
||||||
|
d.header = Some(p[..n].to_vec());
|
||||||
|
}
|
||||||
|
d.bytes += payload.len();
|
||||||
|
d.parts.insert(start, payload.to_vec());
|
||||||
|
let complete = d.end.is_some_and(|e| e == d.bytes) && d.header.is_some();
|
||||||
|
if !complete {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let d = self.pending.remove(&key)?;
|
||||||
|
let mut out = d.header?;
|
||||||
|
for part in d.parts.values() {
|
||||||
|
out.extend(part);
|
||||||
|
}
|
||||||
|
if out.len() > 65535 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let len = out.len() as u16;
|
||||||
|
out[2..4].copy_from_slice(&len.to_be_bytes());
|
||||||
|
out[6..8].fill(0);
|
||||||
|
out[10..12].fill(0);
|
||||||
|
let h = usize::from(out[0] & 15) * 4;
|
||||||
|
let c = checksum(&out[..h]);
|
||||||
|
out[10..12].copy_from_slice(&c.to_be_bytes());
|
||||||
|
Some(Bytes::from(out))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-fragments an assembled NAT datagram for the unchanged overlay MTU.
|
||||||
|
pub(crate) fn fragments(packet: Bytes, mtu: u32) -> Vec<Bytes> {
|
||||||
|
if packet.len() <= mtu as usize {
|
||||||
|
return vec![packet];
|
||||||
|
}
|
||||||
|
let Some(n) = header(&packet) else {
|
||||||
|
return vec![];
|
||||||
|
};
|
||||||
|
if u16::from_be_bytes([packet[6], packet[7]]) & 0x4000 != 0 {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
let size = (mtu as usize).saturating_sub(n) / 8 * 8;
|
||||||
|
if size == 0 {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
let mut copied = Vec::new();
|
||||||
|
let mut offset = 20;
|
||||||
|
while offset < n {
|
||||||
|
let kind = packet[offset];
|
||||||
|
if kind == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if kind == 1 {
|
||||||
|
offset += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(&len) = packet.get(offset + 1) else {
|
||||||
|
return vec![];
|
||||||
|
};
|
||||||
|
let len = usize::from(len);
|
||||||
|
if len < 2 || offset + len > n {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
if kind & 0x80 != 0 {
|
||||||
|
copied.extend_from_slice(&packet[offset..offset + len]);
|
||||||
|
}
|
||||||
|
offset += len;
|
||||||
|
}
|
||||||
|
while !copied.len().is_multiple_of(4) {
|
||||||
|
copied.push(0);
|
||||||
|
}
|
||||||
|
let mut result = Vec::new();
|
||||||
|
let payload = &packet[n..];
|
||||||
|
for (start, part) in payload.chunks(size).enumerate() {
|
||||||
|
let offset = start * size;
|
||||||
|
let mut out = if offset == 0 {
|
||||||
|
packet[..n].to_vec()
|
||||||
|
} else {
|
||||||
|
let mut h = packet[..20].to_vec();
|
||||||
|
h.extend_from_slice(&copied);
|
||||||
|
h[0] = 0x40 | (h.len() / 4) as u8;
|
||||||
|
h
|
||||||
|
};
|
||||||
|
let header_len = out.len();
|
||||||
|
out.extend(part);
|
||||||
|
let len = out.len() as u16;
|
||||||
|
out[2..4].copy_from_slice(&len.to_be_bytes());
|
||||||
|
let flags = (offset / 8) as u16
|
||||||
|
| if offset + part.len() < payload.len() {
|
||||||
|
0x2000
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
out[6..8].copy_from_slice(&flags.to_be_bytes());
|
||||||
|
out[10..12].fill(0);
|
||||||
|
let c = checksum(&out[..header_len]);
|
||||||
|
out[10..12].copy_from_slice(&c.to_be_bytes());
|
||||||
|
result.push(Bytes::from(out));
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
fn datagram() -> Bytes {
|
||||||
|
let mut p = vec![0; 3028];
|
||||||
|
p[0] = 0x45;
|
||||||
|
p[2..4].copy_from_slice(&3028u16.to_be_bytes());
|
||||||
|
p[8] = 64;
|
||||||
|
p[9] = 17;
|
||||||
|
p[12..16].copy_from_slice(&[10, 0, 0, 1]);
|
||||||
|
p[16..20].copy_from_slice(&[10, 0, 0, 2]);
|
||||||
|
p[20..22].copy_from_slice(&1000u16.to_be_bytes());
|
||||||
|
p[22..24].copy_from_slice(&2000u16.to_be_bytes());
|
||||||
|
p[24..26].copy_from_slice(&3008u16.to_be_bytes());
|
||||||
|
finish(&mut p, 20, Protocol::Udp);
|
||||||
|
Bytes::from(p)
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn fragmented_udp_reassembles_out_of_order_and_nat_checksums_are_valid() {
|
||||||
|
let p = datagram();
|
||||||
|
let parts = fragments(p.clone(), 1280);
|
||||||
|
assert_eq!(parts.len(), 3);
|
||||||
|
let mut reassembly = Reassembly::default();
|
||||||
|
let mut result = None;
|
||||||
|
for part in parts.into_iter().rev() {
|
||||||
|
if let Some(p) = reassembly.accept(part, 8, None) {
|
||||||
|
result = Some(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(result, Some(p.clone()));
|
||||||
|
let mut t = tuple(&p).unwrap();
|
||||||
|
t.dst = Ipv4Addr::new(10, 0, 0, 240);
|
||||||
|
t.dport = 53;
|
||||||
|
let out = rewrite(&p, t).unwrap();
|
||||||
|
assert_eq!(header(&out), Some(20));
|
||||||
|
let mut sum = 0u32;
|
||||||
|
for pair in out[12..20].as_chunks::<2>().0 {
|
||||||
|
sum += u32::from(u16::from_be_bytes([pair[0], pair[1]]));
|
||||||
|
}
|
||||||
|
sum += 17 + (out.len() - 20) as u32;
|
||||||
|
assert_eq!(checksum_seed(&out[20..], sum), 0);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn overlaps_and_capacity_are_rejected_without_allocating_unbounded_state() {
|
||||||
|
let parts = fragments(datagram(), 1280);
|
||||||
|
let mut r = Reassembly::default();
|
||||||
|
assert!(r.accept(parts[0].clone(), 0, None).is_none());
|
||||||
|
assert!(r.pending.is_empty());
|
||||||
|
assert!(r.accept(parts[0].clone(), 1, None).is_none());
|
||||||
|
assert!(r.accept(parts[0].clone(), 1, None).is_none());
|
||||||
|
assert_eq!(r.pending.len(), 1);
|
||||||
|
let mut conflict = parts[0].to_vec();
|
||||||
|
conflict[20] ^= 1;
|
||||||
|
assert!(r.accept(Bytes::from(conflict), 1, None).is_none());
|
||||||
|
assert!(r.pending.is_empty());
|
||||||
|
for size in 0..80 {
|
||||||
|
let p = vec![0xff; size];
|
||||||
|
assert!(tuple(&p).is_none());
|
||||||
|
assert!(icmp_quote(&p).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn fragment_assembly_is_scoped_to_authenticated_sender_and_expires_when_idle() {
|
||||||
|
let packet = datagram();
|
||||||
|
let parts = fragments(packet.clone(), 1280);
|
||||||
|
let mut r = Reassembly::default();
|
||||||
|
assert!(r.accept(parts[0].clone(), 8, Some([1; 32])).is_none());
|
||||||
|
assert!(r.accept(parts[1].clone(), 8, Some([2; 32])).is_none());
|
||||||
|
assert!(r.accept(parts[2].clone(), 8, Some([1; 32])).is_none());
|
||||||
|
assert_eq!(r.accept(parts[1].clone(), 8, Some([1; 32])), Some(packet));
|
||||||
|
assert_eq!(r.pending.len(), 1);
|
||||||
|
r.expire(Instant::now() + Duration::from_secs(6));
|
||||||
|
assert!(r.pending.is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod icmp_tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn pmtu_errors_restore_quoted_addresses_ports_and_checksums() {
|
||||||
|
let original = Tuple {
|
||||||
|
src: Ipv4Addr::new(10, 0, 0, 1),
|
||||||
|
dst: Ipv4Addr::new(10, 0, 0, 240),
|
||||||
|
sport: 40000,
|
||||||
|
dport: 53,
|
||||||
|
protocol: Protocol::Udp,
|
||||||
|
};
|
||||||
|
let mut p = vec![0; 36];
|
||||||
|
p[0] = 0x45;
|
||||||
|
p[2..4].copy_from_slice(&36u16.to_be_bytes());
|
||||||
|
p[8] = 64;
|
||||||
|
p[9] = 17;
|
||||||
|
p[24..26].copy_from_slice(&16u16.to_be_bytes());
|
||||||
|
let c = checksum(&p[..20]);
|
||||||
|
p[10..12].copy_from_slice(&c.to_be_bytes());
|
||||||
|
let p = rewrite(&p, original).unwrap();
|
||||||
|
let wire = Tuple {
|
||||||
|
dst: Ipv4Addr::new(10, 0, 0, 2),
|
||||||
|
sport: 50000,
|
||||||
|
dport: 5353,
|
||||||
|
..original
|
||||||
|
};
|
||||||
|
let translated = rewrite(&p, wire).unwrap();
|
||||||
|
let mut error = vec![0; 56];
|
||||||
|
error[0] = 0x45;
|
||||||
|
error[2..4].copy_from_slice(&56u16.to_be_bytes());
|
||||||
|
error[8] = 64;
|
||||||
|
error[9] = 1;
|
||||||
|
error[12..16].copy_from_slice(&wire.dst.octets());
|
||||||
|
error[16..20].copy_from_slice(&wire.src.octets());
|
||||||
|
error[20] = 3;
|
||||||
|
error[21] = 4;
|
||||||
|
error[26..28].copy_from_slice(&1200u16.to_be_bytes());
|
||||||
|
error[28..].copy_from_slice(&translated[..28]);
|
||||||
|
let c = checksum(&error[20..]);
|
||||||
|
error[22..24].copy_from_slice(&c.to_be_bytes());
|
||||||
|
let c = checksum(&error[..20]);
|
||||||
|
error[10..12].copy_from_slice(&c.to_be_bytes());
|
||||||
|
let restored = rewrite_icmp(&error, original).unwrap();
|
||||||
|
assert_eq!(icmp_quote(&restored), Some(original));
|
||||||
|
assert_eq!(checksum(&restored[20..]), 0);
|
||||||
|
assert_eq!(checksum(&restored[28..48]), 0);
|
||||||
|
assert_eq!(&restored[54..56], &p[26..28]);
|
||||||
|
assert_eq!(&restored[26..28], &1200u16.to_be_bytes());
|
||||||
|
assert_eq!(&restored[12..16], &original.dst.octets());
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,144 @@
|
|||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
use crate::NetworkId;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn concurrent_backend_edits_merge_and_deletion_cannot_resurrect() {
|
||||||
|
let net = NetworkId::from_bytes([7; 32]);
|
||||||
|
let a = iroh::SecretKey::generate();
|
||||||
|
let b = iroh::SecretKey::generate();
|
||||||
|
let limits = Limits::default();
|
||||||
|
let mut state = VipSet::default();
|
||||||
|
let id = hex::encode([9; 16]);
|
||||||
|
let initial = VipConfig {
|
||||||
|
id: id.clone(),
|
||||||
|
name: "api".into(),
|
||||||
|
listeners: vec![Listener::new(Protocol::Tcp, 443)],
|
||||||
|
};
|
||||||
|
let changes = state.edit(net, &a, 1, &initial, None, &limits).unwrap();
|
||||||
|
state.merge(net, changes, &limits).unwrap();
|
||||||
|
let revision = state.revision(&id);
|
||||||
|
let mut first = initial.clone();
|
||||||
|
first.listeners[0].backends.push(Backend {
|
||||||
|
peer: a.public().to_string(),
|
||||||
|
port: 6443,
|
||||||
|
});
|
||||||
|
let mut second = initial.clone();
|
||||||
|
second.listeners[0].backends.push(Backend {
|
||||||
|
peer: b.public().to_string(),
|
||||||
|
port: 7443,
|
||||||
|
});
|
||||||
|
let x = state
|
||||||
|
.edit(net, &a, 2, &first, Some(&revision), &limits)
|
||||||
|
.unwrap();
|
||||||
|
let y = state
|
||||||
|
.edit(net, &b, 1, &second, Some(&revision), &limits)
|
||||||
|
.unwrap();
|
||||||
|
let mut reverse = state.clone();
|
||||||
|
state.merge(net, x.clone(), &limits).unwrap();
|
||||||
|
state.merge(net, y.clone(), &limits).unwrap();
|
||||||
|
reverse.merge(net, y, &limits).unwrap();
|
||||||
|
reverse.merge(net, x, &limits).unwrap();
|
||||||
|
assert_eq!(state.configs(), reverse.configs());
|
||||||
|
assert_eq!(state.configs()[0].listeners[0].backends.len(), 2);
|
||||||
|
assert!(
|
||||||
|
state
|
||||||
|
.edit(net, &a, 3, &initial, Some(&revision), &limits)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
let removed = state.delete(net, &a, 3, &id, &state.revision(&id)).unwrap();
|
||||||
|
let old = state.entries(&id);
|
||||||
|
state.merge(net, removed, &limits).unwrap();
|
||||||
|
state.merge(net, old, &limits).unwrap();
|
||||||
|
assert!(state.configs().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn signed_fields_reject_tampering_wrong_network_and_limits() {
|
||||||
|
let net = NetworkId::from_bytes([2; 32]);
|
||||||
|
let key = iroh::SecretKey::generate();
|
||||||
|
let limits = Limits::default();
|
||||||
|
let state = VipSet::default();
|
||||||
|
let cfg = VipConfig {
|
||||||
|
id: hex::encode([3; 16]),
|
||||||
|
name: "dns".into(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let entries = state.edit(net, &key, 1, &cfg, None, &limits).unwrap();
|
||||||
|
let mut bad = entries.clone();
|
||||||
|
bad[0].clock += 1;
|
||||||
|
assert!(VipSet::default().merge(net, bad, &limits).is_err());
|
||||||
|
assert!(
|
||||||
|
VipSet::default()
|
||||||
|
.merge(NetworkId::from_bytes([4; 32]), entries.clone(), &limits)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
let mut small = limits.clone();
|
||||||
|
small.max_vips = 0;
|
||||||
|
assert!(VipSet::default().merge(net, entries, &small).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deletion_history_does_not_exhaust_active_capacity_or_accept_stale_fields() {
|
||||||
|
let network = NetworkId::from_bytes([9; 32]);
|
||||||
|
let key = iroh::SecretKey::generate();
|
||||||
|
let limits = Limits {
|
||||||
|
max_vips: 1,
|
||||||
|
max_vip_tombstones: 4,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut state = VipSet::default();
|
||||||
|
for index in 0..4 {
|
||||||
|
let config = VipConfig::new("reused-name");
|
||||||
|
let fields = state
|
||||||
|
.edit(network, &key, index * 2 + 1, &config, None, &limits)
|
||||||
|
.unwrap();
|
||||||
|
state.merge(network, fields.clone(), &limits).unwrap();
|
||||||
|
let deletion = state
|
||||||
|
.delete(
|
||||||
|
network,
|
||||||
|
&key,
|
||||||
|
index * 2 + 2,
|
||||||
|
&config.id,
|
||||||
|
&state.revision(&config.id),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
state.merge(network, deletion, &limits).unwrap();
|
||||||
|
assert_eq!(state.entries(&config.id).len(), 1);
|
||||||
|
assert!(!state.merge(network, fields, &limits).unwrap());
|
||||||
|
}
|
||||||
|
let next = VipConfig::new("next");
|
||||||
|
let fields = state.edit(network, &key, 9, &next, None, &limits).unwrap();
|
||||||
|
state.merge(network, fields, &limits).unwrap();
|
||||||
|
assert_eq!(state.configs().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reservations_avoid_nodes_and_name_conflicts_have_a_deterministic_holder() {
|
||||||
|
let network = NetworkId::from_bytes([4; 32]);
|
||||||
|
let key = iroh::SecretKey::generate();
|
||||||
|
let limits = Limits::default();
|
||||||
|
let mut state = VipSet::default();
|
||||||
|
for version in 1..=2 {
|
||||||
|
let config = VipConfig::new("shared-name");
|
||||||
|
let fields = state
|
||||||
|
.edit(network, &key, version, &config, None, &limits)
|
||||||
|
.unwrap();
|
||||||
|
state.merge(network, fields, &limits).unwrap();
|
||||||
|
}
|
||||||
|
let range = "10.0.0.0/29".parse().unwrap();
|
||||||
|
let taken = ["10.0.0.1".parse().unwrap()].into_iter().collect();
|
||||||
|
let views = state.views(Some(range), taken, &Default::default(), &limits);
|
||||||
|
assert!(views[0].error.is_none());
|
||||||
|
assert!(
|
||||||
|
views[1]
|
||||||
|
.error
|
||||||
|
.as_deref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("name conflicts")
|
||||||
|
);
|
||||||
|
assert_ne!(views[0].address, views[1].address);
|
||||||
|
for v in views {
|
||||||
|
assert_ne!(v.address, Some("10.0.0.1".parse().unwrap()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
//! The local candidate filter must affect actual hole-punch addresses, not only publications.
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use iroh::{
|
||||||
|
Endpoint, RelayMode, TransportAddr,
|
||||||
|
endpoint::{PortmapperConfig, presets},
|
||||||
|
};
|
||||||
|
use std::borrow::Cow;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn direct_candidate_filter_changes_the_address_watch_used_by_connections() {
|
||||||
|
let observed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
let called = observed.clone();
|
||||||
|
let endpoint = Endpoint::builder(presets::Minimal)
|
||||||
|
.relay_mode(RelayMode::Disabled)
|
||||||
|
.clear_address_lookup()
|
||||||
|
.portmapper_config(PortmapperConfig::Disabled)
|
||||||
|
.net_report_config(iroh::NetReportConfig::minimal())
|
||||||
|
.clear_ip_transports()
|
||||||
|
.bind_addr("127.0.0.1:0")
|
||||||
|
.unwrap()
|
||||||
|
// Stand in for addresses on the agent's own overlay interface.
|
||||||
|
.direct_addr_filter(iroh::address_lookup::AddrFilter::new(move |addrs| {
|
||||||
|
if addrs
|
||||||
|
.iter()
|
||||||
|
.any(|addr| matches!(addr, TransportAddr::Ip(_)))
|
||||||
|
{
|
||||||
|
called.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
Cow::Owned(
|
||||||
|
addrs
|
||||||
|
.iter()
|
||||||
|
.filter(|addr| !matches!(addr, TransportAddr::Ip(_)))
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}))
|
||||||
|
.bind()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
tsunagi::testing::wait_until("filter applied to actual bound candidates", || async {
|
||||||
|
observed
|
||||||
|
.load(std::sync::atomic::Ordering::Relaxed)
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(
|
||||||
|
!endpoint.bound_sockets().is_empty(),
|
||||||
|
"real UDP sockets are still bound"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
endpoint.addr().ip_addrs().next().is_none(),
|
||||||
|
"excluded local paths never reach iroh's connection candidates"
|
||||||
|
);
|
||||||
|
endpoint.close().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn carriers_exclude_the_kernel_assigned_interface_name_instead_of_the_requested_alias() {
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tsunagi::dataplane::transport::DataCarrier;
|
||||||
|
use tsunagi::dataplane::{PluginCapability, PluginError};
|
||||||
|
use tsunagi::overlay::{MemoryTunFactory, OverlayError, TunDevice, TunFactory, TunRequest};
|
||||||
|
use tsunagi::{BoxFuture, NetworkId};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct RenamingFactory(MemoryTunFactory);
|
||||||
|
impl TunFactory for RenamingFactory {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"kernel-name-test"
|
||||||
|
}
|
||||||
|
fn on_host(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
fn create<'a>(
|
||||||
|
&'a self,
|
||||||
|
mut request: TunRequest,
|
||||||
|
) -> BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
|
||||||
|
request.name = "kernel-assigned".into();
|
||||||
|
self.0.create(request)
|
||||||
|
}
|
||||||
|
fn reconfigure<'a>(
|
||||||
|
&'a self,
|
||||||
|
request: TunRequest,
|
||||||
|
) -> BoxFuture<'a, Result<(), OverlayError>> {
|
||||||
|
self.0.reconfigure(request)
|
||||||
|
}
|
||||||
|
fn destroy<'a>(&'a self, name: &'a str) -> BoxFuture<'a, ()> {
|
||||||
|
self.0.destroy(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Carrier(Mutex<Option<String>>);
|
||||||
|
impl DataCarrier for Carrier {
|
||||||
|
fn protocol_id(&self) -> &str {
|
||||||
|
"candidate-test"
|
||||||
|
}
|
||||||
|
fn protocol_version(&self) -> u16 {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
fn on_interface_ready(&self, name: &str) {
|
||||||
|
*self.0.lock().unwrap() = Some(name.into());
|
||||||
|
}
|
||||||
|
fn local_capability(&self, _: NetworkId) -> Result<Option<PluginCapability>, PluginError> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
fn on_peer_capability(
|
||||||
|
&self,
|
||||||
|
_: NetworkId,
|
||||||
|
_: iroh::EndpointId,
|
||||||
|
_: &PluginCapability,
|
||||||
|
) -> Result<(), PluginError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn on_peer_gone(&self, _: NetworkId, _: iroh::EndpointId) {}
|
||||||
|
fn on_network_deactivated(&self, _: NetworkId) {}
|
||||||
|
}
|
||||||
|
let root = tempfile::TempDir::new().unwrap();
|
||||||
|
let discovery = tsunagi::discovery::SharedMemoryDiscovery::new();
|
||||||
|
let carrier = Arc::new(Carrier::default());
|
||||||
|
let config = tsunagi::testing::config_with(root.path(), &discovery)
|
||||||
|
.with_interface(
|
||||||
|
Arc::new(RenamingFactory(MemoryTunFactory::new())),
|
||||||
|
"requested-alias",
|
||||||
|
1280,
|
||||||
|
)
|
||||||
|
.with_carrier(carrier.clone());
|
||||||
|
let agent = tsunagi::Agent::spawn(config).await.unwrap();
|
||||||
|
assert_eq!(agent.overlay().unwrap().interface, "kernel-assigned");
|
||||||
|
assert_eq!(
|
||||||
|
carrier.0.lock().unwrap().as_deref(),
|
||||||
|
Some("kernel-assigned")
|
||||||
|
);
|
||||||
|
agent.shutdown().await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
//! Exercise the vendored retry admission in the default workspace suite.
|
||||||
|
//! Transport integration tests still use real iroh endpoints.
|
||||||
|
#[path = "../../../vendor/iroh/src/socket/remote_map/remote_state/pending_paths.rs"]
|
||||||
|
mod pending_paths;
|
||||||
@@ -1,220 +1,9 @@
|
|||||||
//! Connectivity does not depend on what kind of link each hop happens to be,
|
//! Signed hostname ownership remains independent of connectivity and identity order.
|
||||||
//! and a member is online however far away it is.
|
|
||||||
|
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use tsunagi::{
|
||||||
use std::collections::{HashMap, HashSet};
|
discovery::SharedMemoryDiscovery,
|
||||||
use std::sync::{Arc, Mutex};
|
testing::{TestAgent, network, wait_for_peers, wait_until},
|
||||||
|
};
|
||||||
use bytes::Bytes;
|
|
||||||
use iroh::EndpointId;
|
|
||||||
use tsunagi::NetworkId;
|
|
||||||
use tsunagi::agent::DataPath;
|
|
||||||
use tsunagi::dataplane::transport::SharedLink;
|
|
||||||
use tsunagi::dataplane::{IpPlugin, PluginCapability, PluginError};
|
|
||||||
use tsunagi::discovery::SharedMemoryDiscovery;
|
|
||||||
use tsunagi::testing::{TestAgent, network, wait_for_peers, wait_until};
|
|
||||||
|
|
||||||
/// A protocol that moves bytes between two members unchanged and keeps the
|
|
||||||
/// link it was handed, so a test can use the link directly.
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct Carrier {
|
|
||||||
protocol: String,
|
|
||||||
links: Mutex<HashMap<EndpointId, SharedLink>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Carrier {
|
|
||||||
fn new(protocol: &str) -> Arc<Self> {
|
|
||||||
Arc::new(Self {
|
|
||||||
protocol: protocol.into(),
|
|
||||||
links: Mutex::default(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn link(&self, peer: EndpointId) -> Option<SharedLink> {
|
|
||||||
self.links.lock().unwrap().get(&peer).cloned()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IpPlugin for Carrier {
|
|
||||||
fn protocol_id(&self) -> &str {
|
|
||||||
&self.protocol
|
|
||||||
}
|
|
||||||
|
|
||||||
fn protocol_version(&self) -> u16 {
|
|
||||||
1
|
|
||||||
}
|
|
||||||
|
|
||||||
fn local_capability(
|
|
||||||
&self,
|
|
||||||
_network: NetworkId,
|
|
||||||
) -> Result<Option<PluginCapability>, PluginError> {
|
|
||||||
Ok(Some(PluginCapability {
|
|
||||||
protocol: self.protocol.clone(),
|
|
||||||
version: 1,
|
|
||||||
enabled: true,
|
|
||||||
data: Vec::new(),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_peer_capability(
|
|
||||||
&self,
|
|
||||||
_network: NetworkId,
|
|
||||||
_peer: EndpointId,
|
|
||||||
_capability: &PluginCapability,
|
|
||||||
) -> Result<(), PluginError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_peer_link(&self, _network: NetworkId, peer: EndpointId, link: SharedLink) {
|
|
||||||
self.links.lock().unwrap().insert(peer, link);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_peer_gone(&self, _network: NetworkId, peer: EndpointId) {
|
|
||||||
self.links.lock().unwrap().remove(&peer);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_network_deactivated(&self, _network: NetworkId) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Blocked = Arc<Mutex<HashSet<EndpointId>>>;
|
|
||||||
|
|
||||||
async fn member(
|
|
||||||
discovery: &SharedMemoryDiscovery,
|
|
||||||
plugins: &[Arc<Carrier>],
|
|
||||||
blocked: &Blocked,
|
|
||||||
) -> TestAgent {
|
|
||||||
let plugins: Vec<_> = plugins.to_vec();
|
|
||||||
let blocked = Arc::clone(blocked);
|
|
||||||
TestAgent::spawn_with(
|
|
||||||
move |config| {
|
|
||||||
let config = config.with_unreachable_data_peers(blocked);
|
|
||||||
plugins
|
|
||||||
.into_iter()
|
|
||||||
.fold(config, |config, plugin| config.with_plugin(plugin))
|
|
||||||
},
|
|
||||||
discovery,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn exchange(from: &SharedLink, to: &SharedLink, payload: &'static [u8]) {
|
|
||||||
from.send(Bytes::from_static(payload)).unwrap();
|
|
||||||
let got = tokio::time::timeout(tsunagi::testing::DEADLINE, to.recv())
|
|
||||||
.await
|
|
||||||
.expect("the datagram should arrive")
|
|
||||||
.expect("the link stays open");
|
|
||||||
assert_eq!(got, Bytes::from_static(payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_tunnel_crosses_a_member_that_shares_no_protocol_with_either_end_and_moves_to_a_direct_link_by_itself()
|
|
||||||
{
|
|
||||||
// A and B share one protocol and nothing else. C shares a different
|
|
||||||
// one with each, so every link here is of a different kind and the
|
|
||||||
// middle has never heard of what A and B speak. A and B cannot reach
|
|
||||||
// each other directly, which is the case a blocked UDP path produces.
|
|
||||||
let discovery = SharedMemoryDiscovery::new();
|
|
||||||
let (name, secret) = network("mixed-transports");
|
|
||||||
|
|
||||||
let blocked_a: Blocked = Arc::default();
|
|
||||||
let blocked_b: Blocked = Arc::default();
|
|
||||||
let a_shared = Carrier::new("shared");
|
|
||||||
let b_shared = Carrier::new("shared");
|
|
||||||
let a = member(
|
|
||||||
&discovery,
|
|
||||||
&[Carrier::new("a-and-c"), Arc::clone(&a_shared)],
|
|
||||||
&blocked_a,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let b = member(
|
|
||||||
&discovery,
|
|
||||||
&[Carrier::new("c-and-b"), Arc::clone(&b_shared)],
|
|
||||||
&blocked_b,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let c = member(
|
|
||||||
&discovery,
|
|
||||||
&[Carrier::new("a-and-c"), Carrier::new("c-and-b")],
|
|
||||||
&Blocked::default(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let (a_id, b_id, c_id) = (
|
|
||||||
a.agent.endpoint_id(),
|
|
||||||
b.agent.endpoint_id(),
|
|
||||||
c.agent.endpoint_id(),
|
|
||||||
);
|
|
||||||
blocked_a.lock().unwrap().insert(b_id);
|
|
||||||
blocked_b.lock().unwrap().insert(a_id);
|
|
||||||
|
|
||||||
let network_id = a.agent.join_network(&name, &secret).await.unwrap();
|
|
||||||
b.agent.join_network(&name, &secret).await.unwrap();
|
|
||||||
c.agent.join_network(&name, &secret).await.unwrap();
|
|
||||||
for agent in [&a, &b, &c] {
|
|
||||||
wait_for_peers(&agent.agent, network_id, 2).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The tunnel comes up through C, and data goes both ways.
|
|
||||||
let to_b = wait_until("a has a link to b", || async { a_shared.link(b_id) }).await;
|
|
||||||
let to_a = wait_until("b has a link to a", || async { b_shared.link(a_id) }).await;
|
|
||||||
exchange(&to_b, &to_a, b"a to b, sealed").await;
|
|
||||||
exchange(&to_a, &to_b, b"b to a, sealed").await;
|
|
||||||
|
|
||||||
// The status says what is true: online, and through whom.
|
|
||||||
let status = a.agent.network_status(network_id).await.unwrap();
|
|
||||||
let b_peer = status.peers.iter().find(|p| p.endpoint_id == b_id).unwrap();
|
|
||||||
assert_eq!(b_peer.data_path, DataPath::Relayed { hops: 2, via: c_id });
|
|
||||||
let c_peer = status.peers.iter().find(|p| p.endpoint_id == c_id).unwrap();
|
|
||||||
assert!(matches!(&c_peer.data_path, DataPath::Direct { transport } if transport == "a-and-c"));
|
|
||||||
let b_member = wait_until("a lists b as a member", || async {
|
|
||||||
let status = a.agent.network_status(network_id).await.ok()?;
|
|
||||||
status.members.into_iter().find(|m| m.endpoint_id == b_id)
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert!(b_member.online);
|
|
||||||
let carried = c.agent.network_status(network_id).await.unwrap().relay;
|
|
||||||
assert!(carried.forwarded >= 2, "{carried:?}");
|
|
||||||
|
|
||||||
// The direct path becomes possible: the same link carries on, now
|
|
||||||
// without C, and nobody has to do anything about it.
|
|
||||||
blocked_a.lock().unwrap().clear();
|
|
||||||
blocked_b.lock().unwrap().clear();
|
|
||||||
wait_until("a reaches b directly", || async {
|
|
||||||
let status = a.agent.network_status(network_id).await.ok()?;
|
|
||||||
let peer = status.peers.iter().find(|p| p.endpoint_id == b_id)?;
|
|
||||||
matches!(&peer.data_path, DataPath::Direct { transport } if transport == "shared")
|
|
||||||
.then_some(())
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
let forwarded = c
|
|
||||||
.agent
|
|
||||||
.network_status(network_id)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.relay
|
|
||||||
.forwarded;
|
|
||||||
exchange(&to_b, &to_a, b"direct now").await;
|
|
||||||
assert!(
|
|
||||||
Arc::ptr_eq(&to_b, &a_shared.link(b_id).unwrap()),
|
|
||||||
"the tunnel's link is the one it always had"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
c.agent
|
|
||||||
.network_status(network_id)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.relay
|
|
||||||
.forwarded,
|
|
||||||
forwarded,
|
|
||||||
"nothing goes through C any more"
|
|
||||||
);
|
|
||||||
|
|
||||||
a.stop().await;
|
|
||||||
b.stop().await;
|
|
||||||
c.stop().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_name_belongs_to_the_member_that_claimed_it_first_on_every_member() {
|
async fn a_name_belongs_to_the_member_that_claimed_it_first_on_every_member() {
|
||||||
let discovery = SharedMemoryDiscovery::new();
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ async fn opaque_plugin_capabilities_cross_the_control_plane() {
|
|||||||
let a = TestAgent::spawn_with(
|
let a = TestAgent::spawn_with(
|
||||||
{
|
{
|
||||||
let plugin = Arc::clone(&plugin_a);
|
let plugin = Arc::clone(&plugin_a);
|
||||||
move |cfg| cfg.with_plugin(plugin)
|
move |cfg| cfg.with_tunnel(plugin)
|
||||||
},
|
},
|
||||||
&discovery,
|
&discovery,
|
||||||
)
|
)
|
||||||
@@ -141,7 +141,7 @@ async fn opaque_plugin_capabilities_cross_the_control_plane() {
|
|||||||
let b = TestAgent::spawn_with(
|
let b = TestAgent::spawn_with(
|
||||||
{
|
{
|
||||||
let plugin = Arc::clone(&plugin_b);
|
let plugin = Arc::clone(&plugin_b);
|
||||||
move |cfg| cfg.with_plugin(plugin)
|
move |cfg| cfg.with_tunnel(plugin)
|
||||||
},
|
},
|
||||||
&discovery,
|
&discovery,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,207 @@
|
|||||||
|
//! Shared services use real membership, signed state and mandatory SQLite.
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use tsunagi::discovery::SharedMemoryDiscovery;
|
||||||
|
use tsunagi::testing::{TestAgent, config_with, network, wait_for_peers, wait_until};
|
||||||
|
use tsunagi::vip::{Backend, Listener, Protocol, VipConfig, VipStatus};
|
||||||
|
use tsunagi::{Agent, NetworkId};
|
||||||
|
async fn view(agent: &Agent, network: NetworkId, id: &str) -> VipStatus {
|
||||||
|
wait_until("VIP configuration reaches the replica", || async {
|
||||||
|
agent
|
||||||
|
.network_status(network)
|
||||||
|
.await
|
||||||
|
.ok()?
|
||||||
|
.vips
|
||||||
|
.into_iter()
|
||||||
|
.find(|v| v.config.id == id)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
async fn any_member_can_edit_services_and_an_offline_creator_is_not_required() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let a = TestAgent::spawn(&discovery).await.unwrap();
|
||||||
|
let b = TestAgent::spawn(&discovery).await.unwrap();
|
||||||
|
let (name, secret) = network("shared-vips");
|
||||||
|
let net = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
wait_for_peers(&a.agent, net, 1).await;
|
||||||
|
let cfg = VipConfig::new("api");
|
||||||
|
a.agent
|
||||||
|
.save_vip(net, cfg.clone(), None, false)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let before = view(&b.agent, net, &cfg.id).await;
|
||||||
|
let mut edited = before.config.clone();
|
||||||
|
let mut listener = Listener::new(Protocol::Tcp, 443);
|
||||||
|
listener.backends.push(Backend {
|
||||||
|
peer: b.agent.endpoint_id().to_string(),
|
||||||
|
port: 6443,
|
||||||
|
});
|
||||||
|
edited.listeners.push(listener);
|
||||||
|
b.agent
|
||||||
|
.save_vip(net, edited.clone(), Some(before.revision.clone()), false)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
b.agent
|
||||||
|
.save_vip(net, cfg.clone(), Some(before.revision), false)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
wait_until("creator observes another member's edit", || async {
|
||||||
|
(view(&a.agent, net, &cfg.id).await.config == edited).then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let a_dir = a.stop().await;
|
||||||
|
let c = TestAgent::spawn(&discovery).await.unwrap();
|
||||||
|
c.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
assert_eq!(view(&c.agent, net, &cfg.id).await.config, edited);
|
||||||
|
let a = Agent::spawn(config_with(a_dir.path(), &discovery))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(view(&a, net, &cfg.id).await.config, edited);
|
||||||
|
let current = view(&c.agent, net, &cfg.id).await;
|
||||||
|
c.agent
|
||||||
|
.save_vip(net, current.config, Some(current.revision), true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
wait_until("deletion reaches the original creator", || async {
|
||||||
|
a.network_status(net)
|
||||||
|
.await
|
||||||
|
.ok()?
|
||||||
|
.vips
|
||||||
|
.is_empty()
|
||||||
|
.then_some(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
a.shutdown().await;
|
||||||
|
b.stop().await;
|
||||||
|
c.stop().await;
|
||||||
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
async fn invalid_drafts_are_atomic_and_services_do_not_cross_networks() {
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let a = TestAgent::spawn(&discovery).await.unwrap();
|
||||||
|
let (name, secret) = network("vip-one");
|
||||||
|
let net = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
let (other, secret) = network("vip-two");
|
||||||
|
let second = a.agent.join_network(&other, &secret).await.unwrap();
|
||||||
|
let mut cfg = VipConfig::new("api");
|
||||||
|
cfg.listeners.push(Listener::new(Protocol::Udp, 53));
|
||||||
|
a.agent
|
||||||
|
.save_vip(net, cfg.clone(), None, false)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let before = view(&a.agent, net, &cfg.id).await;
|
||||||
|
let mut invalid = before.config.clone();
|
||||||
|
invalid.name = "renamed".into();
|
||||||
|
invalid.listeners.push(invalid.listeners[0].clone());
|
||||||
|
assert!(
|
||||||
|
a.agent
|
||||||
|
.save_vip(net, invalid, Some(before.revision.clone()), false)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
let after = view(&a.agent, net, &cfg.id).await;
|
||||||
|
assert_eq!(after.config, before.config);
|
||||||
|
assert_eq!(after.revision, before.revision);
|
||||||
|
assert!(
|
||||||
|
a.agent
|
||||||
|
.network_status(second)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.vips
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
a.stop().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_restored_author_advances_its_counter_past_its_own_updates_held_by_a_replica() {
|
||||||
|
use tsunagi::config::StoragePaths;
|
||||||
|
use tsunagi::storage::StateStore;
|
||||||
|
use tsunagi::vip::VipSet;
|
||||||
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
|
let a = TestAgent::spawn(&discovery).await.unwrap();
|
||||||
|
let b = TestAgent::spawn(&discovery).await.unwrap();
|
||||||
|
let (name, secret) = network("vip-author-recovery");
|
||||||
|
let net = a.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
b.agent.join_network(&name, &secret).await.unwrap();
|
||||||
|
wait_for_peers(&a.agent, net, 1).await;
|
||||||
|
let config = VipConfig::new("api");
|
||||||
|
a.agent
|
||||||
|
.save_vip(net, config.clone(), None, false)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
view(&b.agent, net, &config.id).await;
|
||||||
|
let author = a.agent.endpoint_id();
|
||||||
|
let adir = a.stop().await;
|
||||||
|
let bdir = b.stop().await;
|
||||||
|
let apath = StoragePaths::under(adir.path()).state_db();
|
||||||
|
let bpath = StoragePaths::under(bdir.path()).state_db();
|
||||||
|
// Model an old author backup with a newer, genuinely signed update retained
|
||||||
|
// by another offline replica. Connections and recovery below remain real.
|
||||||
|
tokio::task::spawn_blocking(move || {
|
||||||
|
let a = StateStore::open(apath).unwrap();
|
||||||
|
let b = StateStore::open(bpath).unwrap();
|
||||||
|
let mut set = VipSet::default();
|
||||||
|
set.merge(
|
||||||
|
net,
|
||||||
|
a.vip_fields(net, 192).unwrap(),
|
||||||
|
&tsunagi::Limits::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut cfg = set.configs().remove(0);
|
||||||
|
cfg.name = "newer".into();
|
||||||
|
let key =
|
||||||
|
iroh::SecretKey::from_bytes(&a.device_identity().unwrap().unwrap().secret_bytes());
|
||||||
|
let fields = set
|
||||||
|
.edit(
|
||||||
|
net,
|
||||||
|
&key,
|
||||||
|
100,
|
||||||
|
&cfg,
|
||||||
|
Some(&set.revision(&cfg.id)),
|
||||||
|
&tsunagi::Limits::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
set.merge(net, fields, &tsunagi::Limits::default()).unwrap();
|
||||||
|
b.put_vip_fields(net, &set.entries(&cfg.id), None).unwrap();
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let b = Agent::spawn(config_with(bdir.path(), &discovery))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let a = Agent::spawn(config_with(adir.path(), &discovery))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let learned = wait_until(
|
||||||
|
"the restored author learns its newer signed service",
|
||||||
|
|| async {
|
||||||
|
let v = view(&a, net, &config.id).await;
|
||||||
|
(v.config.name == "newer").then_some(v)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let mut next = learned.config;
|
||||||
|
next.name = "latest".into();
|
||||||
|
a.save_vip(net, next, Some(learned.revision), false)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
a.shutdown().await;
|
||||||
|
let path = StoragePaths::under(adir.path()).state_db();
|
||||||
|
let version = tokio::task::spawn_blocking(move || {
|
||||||
|
StateStore::open(path)
|
||||||
|
.unwrap()
|
||||||
|
.own_record_version(net, author)
|
||||||
|
.unwrap()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
version > 100,
|
||||||
|
"the observed author counter must not be reused"
|
||||||
|
);
|
||||||
|
b.shutdown().await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsunagi-runtime"
|
||||||
|
version = "1.0.0"
|
||||||
|
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.0" }
|
||||||
|
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.0" }
|
||||||
|
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.0" }
|
||||||
|
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.0" }
|
||||||
|
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.0" }
|
||||||
|
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,201 @@
|
|||||||
|
//! 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),
|
||||||
|
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,32 +1,23 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-tcp-tls"
|
name = "tsunagi-tcp-tls"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
description = "TCP TLS 443 transport and E2EE tunnel protocol for tsunagi mesh networks."
|
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tsunagi-core = { path = "../tsunagi-core", version = "0.1.0" }
|
tsunagi-core = { path = "../tsunagi-core", version = "1.0.0" }
|
||||||
iroh.workspace = true
|
iroh.workspace = true
|
||||||
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
||||||
rustls = "0.23"
|
rustls = "0.23"
|
||||||
tokio-rustls = "0.26"
|
tokio-rustls = "0.26"
|
||||||
rcgen = { version = "0.14", default-features = false, features = ["ring"] }
|
rcgen = { version = "0.14", default-features = false, features = ["ring"] }
|
||||||
x25519-dalek = { version = "2.0", features = ["static_secrets"] }
|
|
||||||
chacha20poly1305 = "0.10"
|
|
||||||
sha2 = "0.11"
|
|
||||||
hkdf = "0.13"
|
|
||||||
rand = "0.10"
|
|
||||||
subtle = "2.6"
|
|
||||||
zeroize = { version = "1.9", features = ["derive"] }
|
|
||||||
bytes.workspace = true
|
bytes.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
postcard.workspace = true
|
postcard.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
thiserror.workspace = true
|
|
||||||
hex.workspace = true
|
|
||||||
netdev = "0.46"
|
netdev = "0.46"
|
||||||
|
|
||||||
[target.'cfg(target_os = "linux")'.dependencies]
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
|
|||||||
@@ -1,104 +0,0 @@
|
|||||||
//! End-to-end packet encryption for `tcp-tls`.
|
|
||||||
//!
|
|
||||||
//! Uses X25519 Diffie-Hellman key exchange and ChaCha20-Poly1305 AEAD.
|
|
||||||
//! This ensures that even when traffic passes through intermediate relay nodes,
|
|
||||||
//! the intermediate nodes cannot inspect or tamper with the payload.
|
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
|
|
||||||
use chacha20poly1305::aead::{Aead, KeyInit};
|
|
||||||
use chacha20poly1305::{ChaCha20Poly1305, Nonce};
|
|
||||||
use hkdf::Hkdf;
|
|
||||||
use iroh::EndpointId;
|
|
||||||
use sha2::Sha256;
|
|
||||||
use tsunagi::dataplane::PluginError;
|
|
||||||
use x25519_dalek::{PublicKey, StaticSecret};
|
|
||||||
|
|
||||||
/// Length of the X25519 public key.
|
|
||||||
pub const KEY_LEN: usize = 32;
|
|
||||||
|
|
||||||
/// Domain separator for session key derivation.
|
|
||||||
const HKDF_SALT: &[u8] = b"tsunagi/e2ee/noise/v1";
|
|
||||||
|
|
||||||
/// A session cipher for communicating with one peer.
|
|
||||||
pub struct PeerCipher {
|
|
||||||
tx_cipher: ChaCha20Poly1305,
|
|
||||||
rx_cipher: ChaCha20Poly1305,
|
|
||||||
tx_nonce: AtomicU64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PeerCipher {
|
|
||||||
/// Establishes a new cipher between `local_id` and `remote_id` given
|
|
||||||
/// our local secret and their public key.
|
|
||||||
pub fn new(
|
|
||||||
local_id: EndpointId,
|
|
||||||
remote_id: EndpointId,
|
|
||||||
local_secret: &StaticSecret,
|
|
||||||
remote_public: &PublicKey,
|
|
||||||
) -> Self {
|
|
||||||
let shared = local_secret.diffie_hellman(remote_public);
|
|
||||||
let hk = Hkdf::<Sha256>::new(Some(HKDF_SALT), shared.as_bytes());
|
|
||||||
|
|
||||||
let mut key_a_to_b = [0u8; 32];
|
|
||||||
let mut key_b_to_a = [0u8; 32];
|
|
||||||
let _ = hk.expand(b"tsunagi-key-a-to-b", &mut key_a_to_b);
|
|
||||||
let _ = hk.expand(b"tsunagi-key-b-to-a", &mut key_b_to_a);
|
|
||||||
|
|
||||||
// Deterministic role: smaller EndpointId is party A.
|
|
||||||
let is_party_a = local_id.as_bytes() < remote_id.as_bytes();
|
|
||||||
let (tx_key, rx_key) = if is_party_a {
|
|
||||||
(key_a_to_b, key_b_to_a)
|
|
||||||
} else {
|
|
||||||
(key_b_to_a, key_a_to_b)
|
|
||||||
};
|
|
||||||
|
|
||||||
let tx_cipher = ChaCha20Poly1305::new(&tx_key.into());
|
|
||||||
let rx_cipher = ChaCha20Poly1305::new(&rx_key.into());
|
|
||||||
|
|
||||||
Self {
|
|
||||||
tx_cipher,
|
|
||||||
rx_cipher,
|
|
||||||
tx_nonce: AtomicU64::new(0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encrypts an outbound packet. Prefixes the ciphertext with the 8-byte nonce.
|
|
||||||
pub fn encrypt(&self, packet: &[u8]) -> Result<bytes::Bytes, PluginError> {
|
|
||||||
let counter = self.tx_nonce.fetch_add(1, Ordering::Relaxed);
|
|
||||||
let mut nonce_bytes = [0u8; 12];
|
|
||||||
nonce_bytes[4..12].copy_from_slice(&counter.to_be_bytes());
|
|
||||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
|
||||||
|
|
||||||
let ciphertext = self
|
|
||||||
.tx_cipher
|
|
||||||
.encrypt(nonce, packet)
|
|
||||||
.map_err(|err| PluginError::Other(format!("encryption failed: {err}")))?;
|
|
||||||
|
|
||||||
let mut out = Vec::with_capacity(8 + ciphertext.len());
|
|
||||||
out.extend_from_slice(&counter.to_be_bytes());
|
|
||||||
out.extend_from_slice(&ciphertext);
|
|
||||||
Ok(bytes::Bytes::from(out))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decrypts an inbound packet prefixed with the 8-byte nonce.
|
|
||||||
pub fn decrypt(&self, payload: &[u8]) -> Result<bytes::Bytes, PluginError> {
|
|
||||||
if payload.len() < 8 + 16 {
|
|
||||||
return Err(PluginError::Other("payload too short".into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let counter_bytes: [u8; 8] = match payload[..8].try_into() {
|
|
||||||
Ok(b) => b,
|
|
||||||
Err(_) => return Err(PluginError::Other("invalid nonce".into())),
|
|
||||||
};
|
|
||||||
let mut nonce_bytes = [0u8; 12];
|
|
||||||
nonce_bytes[4..12].copy_from_slice(&counter_bytes);
|
|
||||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
|
||||||
|
|
||||||
let plaintext = self
|
|
||||||
.rx_cipher
|
|
||||||
.decrypt(nonce, &payload[8..])
|
|
||||||
.map_err(|err| PluginError::Other(format!("decryption failed: {err}")))?;
|
|
||||||
|
|
||||||
Ok(bytes::Bytes::from(plaintext))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,8 @@
|
|||||||
//! The `tcp-tls` protocol: TCP with TLS 1.3 on port 443 with Noise E2EE.
|
//! TCP TLS 1.3 carrier for opaque, independently encrypted mesh datagrams.
|
||||||
|
|
||||||
pub mod cert;
|
pub mod cert;
|
||||||
pub mod crypto;
|
|
||||||
pub mod plugin;
|
pub mod plugin;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
|
|
||||||
pub use plugin::{
|
pub use plugin::{
|
||||||
TCP_TLS_PROTOCOL, TCP_TLS_VERSION, TcpTlsCodec, TcpTlsConfig, TcpTlsPlugin, local_ip_candidates,
|
TCP_TLS_PROTOCOL, TCP_TLS_VERSION, TcpTlsCarrier, TcpTlsConfig, local_ip_candidates,
|
||||||
};
|
};
|
||||||
pub use transport::TcpTlsTransport;
|
pub use transport::TcpTlsTransport;
|
||||||
@@ -1,26 +1,14 @@
|
|||||||
//! The `tcp-tls` IP plugin implementation.
|
//! TLS carrier options and bounded reachability announcements. No IP cipher lives here.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::{Arc, RwLock};
|
|
||||||
|
|
||||||
use bytes::Bytes;
|
|
||||||
use iroh::EndpointId;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use x25519_dalek::{PublicKey, StaticSecret};
|
|
||||||
|
|
||||||
use tsunagi::dataplane::tunnel::{GenericTunnelPlugin, TunnelCodec};
|
|
||||||
use tsunagi::dataplane::{PluginError, ProtocolOption};
|
|
||||||
use tsunagi::identity::NetworkId;
|
|
||||||
|
|
||||||
use crate::crypto::PeerCipher;
|
|
||||||
use crate::transport::TcpTlsTransport;
|
use crate::transport::TcpTlsTransport;
|
||||||
|
use iroh::EndpointId;
|
||||||
/// The wire protocol identifier for `tcp-tls`.
|
use serde::Deserialize;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tsunagi::NetworkId;
|
||||||
|
use tsunagi::dataplane::{PluginError, ProtocolOption};
|
||||||
|
/// External TLS carrier identifier.
|
||||||
pub const TCP_TLS_PROTOCOL: &str = "tcp-tls";
|
pub const TCP_TLS_PROTOCOL: &str = "tcp-tls";
|
||||||
|
/// Carrier announcement wire version.
|
||||||
/// Wire version for `tcp-tls`.
|
pub const TCP_TLS_VERSION: u16 = 2;
|
||||||
pub const TCP_TLS_VERSION: u16 = 1;
|
|
||||||
|
|
||||||
/// Configuration for the `tcp-tls` protocol plugin.
|
/// Configuration for the `tcp-tls` protocol plugin.
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct TcpTlsConfig {
|
pub struct TcpTlsConfig {
|
||||||
@@ -49,23 +37,22 @@ impl TcpTlsConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Announcement payload exchanged between peers for `tcp-tls`.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
pub struct TcpTlsAnnouncement {
|
|
||||||
/// X25519 public key for E2EE noise encryption.
|
|
||||||
pub noise_public: [u8; 32],
|
|
||||||
/// TCP port the peer is listening on.
|
|
||||||
pub port: u16,
|
|
||||||
/// Candidate IP addresses where this peer can be reached on `port`.
|
|
||||||
#[serde(default)]
|
|
||||||
pub addrs: Vec<std::net::IpAddr>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Discovers local network interface IPs to announce to peers.
|
/// Discovers local network interface IPs to announce to peers.
|
||||||
pub fn local_ip_candidates() -> Vec<std::net::IpAddr> {
|
pub fn local_ip_candidates() -> Vec<std::net::IpAddr> {
|
||||||
|
local_ip_candidates_excluding(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn local_ip_candidates_excluding(excluded_interface: Option<&str>) -> Vec<std::net::IpAddr> {
|
||||||
let mut candidates = Vec::new();
|
let mut candidates = Vec::new();
|
||||||
for iface in netdev::get_interfaces() {
|
for iface in netdev::get_interfaces() {
|
||||||
if !is_candidate_interface(&iface) {
|
if excluded_interface.is_some_and(|name| {
|
||||||
|
iface.name.eq_ignore_ascii_case(name)
|
||||||
|
|| iface
|
||||||
|
.friendly_name
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|friendly| friendly.eq_ignore_ascii_case(name))
|
||||||
|
}) || !is_candidate_interface(&iface)
|
||||||
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for ip in &iface.ipv4 {
|
for ip in &iface.ipv4 {
|
||||||
@@ -169,10 +156,7 @@ pub(crate) fn is_candidate_ip(addr: std::net::IpAddr) -> bool {
|
|||||||
}
|
}
|
||||||
let segments = v6.segments();
|
let segments = v6.segments();
|
||||||
// Filter link-local fe80::/10
|
// Filter link-local fe80::/10
|
||||||
if (segments[0] & 0xffc0) == 0xfe80 {
|
(segments[0] & 0xffc0) != 0xfe80
|
||||||
return false;
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -203,26 +187,7 @@ pub(crate) fn ip_priority(iface: &netdev::Interface, ip: std::net::IpAddr) -> u3
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl TcpTlsConfig {
|
||||||
/// The codec implementing cryptographic transformation and announcements for `tcp-tls`.
|
|
||||||
pub struct TcpTlsCodec {
|
|
||||||
local_id: EndpointId,
|
|
||||||
static_secret: StaticSecret,
|
|
||||||
public_key: PublicKey,
|
|
||||||
transport: Arc<TcpTlsTransport>,
|
|
||||||
ciphers: RwLock<HashMap<(NetworkId, EndpointId), Arc<PeerCipher>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Debug for TcpTlsCodec {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.debug_struct("TcpTlsCodec")
|
|
||||||
.field("local_id", &self.local_id.fmt_short().to_string())
|
|
||||||
.field("port", &self.transport.bound_port())
|
|
||||||
.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TcpTlsCodec {
|
|
||||||
/// Supported options for `tcp-tls`.
|
/// Supported options for `tcp-tls`.
|
||||||
pub const OPTIONS: &'static [ProtocolOption] = &[
|
pub const OPTIONS: &'static [ProtocolOption] = &[
|
||||||
ProtocolOption {
|
ProtocolOption {
|
||||||
@@ -239,22 +204,6 @@ impl TcpTlsCodec {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/// Creates a new `TcpTlsCodec`.
|
|
||||||
pub fn new(local_id: EndpointId, transport: Arc<TcpTlsTransport>) -> Self {
|
|
||||||
let mut secret_bytes = [0u8; 32];
|
|
||||||
rand::fill(&mut secret_bytes);
|
|
||||||
let static_secret = StaticSecret::from(secret_bytes);
|
|
||||||
let public_key = PublicKey::from(&static_secret);
|
|
||||||
|
|
||||||
Self {
|
|
||||||
local_id,
|
|
||||||
static_secret,
|
|
||||||
public_key,
|
|
||||||
transport,
|
|
||||||
ciphers: RwLock::new(HashMap::new()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Configures settings from parsed `-o` options.
|
/// Configures settings from parsed `-o` options.
|
||||||
pub fn configure(
|
pub fn configure(
|
||||||
mut config: TcpTlsConfig,
|
mut config: TcpTlsConfig,
|
||||||
@@ -281,250 +230,182 @@ impl TcpTlsCodec {
|
|||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/// TLS carrier announcements and lifecycle, independent of IP encryption.
|
||||||
impl TunnelCodec for TcpTlsCodec {
|
#[derive(Debug)]
|
||||||
|
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>>,
|
||||||
|
>,
|
||||||
|
}
|
||||||
|
impl TcpTlsCarrier {
|
||||||
|
/// Shares the transport's listener; creates no end-to-end cipher.
|
||||||
|
pub fn new(transport: Arc<TcpTlsTransport>) -> Arc<Self> {
|
||||||
|
Arc::new(Self {
|
||||||
|
transport,
|
||||||
|
excluded_interface: std::sync::Mutex::new(None),
|
||||||
|
underlay: Default::default(),
|
||||||
|
peers: Default::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// Registers a carrier while excluding the agent's own, possibly custom-named interface.
|
||||||
|
pub fn with_interface(transport: Arc<TcpTlsTransport>, interface: String) -> Arc<Self> {
|
||||||
|
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,
|
||||||
|
peer: EndpointId,
|
||||||
|
addrs: Option<Vec<std::net::SocketAddr>>,
|
||||||
|
) {
|
||||||
|
let mut peers = self.peers.lock().unwrap_or_else(|p| p.into_inner());
|
||||||
|
match addrs {
|
||||||
|
Some(addrs) => {
|
||||||
|
peers.insert((network, peer), addrs);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
peers.remove(&(network, peer));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut combined = peers
|
||||||
|
.iter()
|
||||||
|
.filter(|((_, id), _)| *id == peer)
|
||||||
|
.flat_map(|(_, addrs)| addrs.iter().copied())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
combined.sort_unstable();
|
||||||
|
combined.dedup();
|
||||||
|
combined.truncate(32);
|
||||||
|
self.transport.replace_peer_addrs(peer, combined);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||||
fn protocol_id(&self) -> &str {
|
fn protocol_id(&self) -> &str {
|
||||||
TCP_TLS_PROTOCOL
|
TCP_TLS_PROTOCOL
|
||||||
}
|
}
|
||||||
|
|
||||||
fn protocol_version(&self) -> u16 {
|
fn protocol_version(&self) -> u16 {
|
||||||
TCP_TLS_VERSION
|
2
|
||||||
}
|
}
|
||||||
|
fn on_interface_ready(&self, name: &str) {
|
||||||
fn options(&self) -> &'static [ProtocolOption] {
|
*self
|
||||||
Self::OPTIONS
|
.excluded_interface
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner()) = Some(name.into());
|
||||||
}
|
}
|
||||||
|
fn local_capability(
|
||||||
fn local_capability_data(&self, _network: NetworkId) -> Result<Vec<u8>, PluginError> {
|
&self,
|
||||||
let announcement = TcpTlsAnnouncement {
|
_: NetworkId,
|
||||||
noise_public: *self.public_key.as_bytes(),
|
) -> Result<Option<tsunagi::dataplane::PluginCapability>, PluginError> {
|
||||||
port: self.transport.bound_port(),
|
let ips = match self.underlay.get() {
|
||||||
addrs: local_ip_candidates(),
|
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(),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
postcard::to_allocvec(&announcement)
|
let data = postcard::to_allocvec(&(
|
||||||
.map_err(|err| PluginError::Other(format!("encode announcement failed: {err}")))
|
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 {
|
||||||
|
protocol: TCP_TLS_PROTOCOL.into(),
|
||||||
|
version: 2,
|
||||||
|
enabled: true,
|
||||||
|
data,
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
fn on_peer_capability(
|
||||||
fn on_peer_capability_data(
|
|
||||||
&self,
|
&self,
|
||||||
network: NetworkId,
|
network: NetworkId,
|
||||||
peer: EndpointId,
|
peer: EndpointId,
|
||||||
data: &[u8],
|
cap: &tsunagi::dataplane::PluginCapability,
|
||||||
) -> Result<(), PluginError> {
|
) -> Result<(), PluginError> {
|
||||||
let announcement: TcpTlsAnnouncement = postcard::from_bytes(data)
|
if !cap.enabled || cap.protocol != TCP_TLS_PROTOCOL || cap.version != 2 {
|
||||||
.map_err(|err| PluginError::Rejected(format!("invalid announcement: {err}")))?;
|
return Err(PluginError::Rejected("unsupported TLS carrier".into()));
|
||||||
|
|
||||||
for ip in &announcement.addrs {
|
|
||||||
if is_candidate_ip(*ip) {
|
|
||||||
self.transport
|
|
||||||
.set_peer_addr(peer, std::net::SocketAddr::new(*ip, announcement.port));
|
|
||||||
}
|
}
|
||||||
|
// Decode a fixed bounded array through the existing common announcement limit.
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Addresses(
|
||||||
|
u16,
|
||||||
|
#[serde(deserialize_with = "bounded_ips")] Vec<std::net::IpAddr>,
|
||||||
|
);
|
||||||
|
let Addresses(port, ips) = postcard::from_bytes(&cap.data)
|
||||||
|
.map_err(|_| PluginError::Rejected("invalid TLS carrier addresses".into()))?;
|
||||||
|
if port == 0 {
|
||||||
|
return Err(PluginError::Rejected("invalid TLS carrier port".into()));
|
||||||
}
|
}
|
||||||
|
self.update_peer(
|
||||||
let peer_noise_pubkey = PublicKey::from(announcement.noise_public);
|
network,
|
||||||
let cipher = Arc::new(PeerCipher::new(
|
|
||||||
self.local_id,
|
|
||||||
peer,
|
peer,
|
||||||
&self.static_secret,
|
Some(
|
||||||
&peer_noise_pubkey,
|
ips.into_iter()
|
||||||
));
|
.filter(|ip| is_candidate_ip(*ip))
|
||||||
|
.map(|ip| std::net::SocketAddr::new(ip, port))
|
||||||
let mut guard = match self.ciphers.write() {
|
.collect(),
|
||||||
Ok(g) => g,
|
),
|
||||||
Err(p) => p.into_inner(),
|
);
|
||||||
};
|
|
||||||
guard.insert((network, peer), cipher);
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) {
|
||||||
fn on_peer_down(&self, network: NetworkId, peer: EndpointId) {
|
self.update_peer(network, peer, None);
|
||||||
let mut guard = match self.ciphers.write() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
guard.remove(&(network, peer));
|
|
||||||
}
|
}
|
||||||
|
fn on_network_deactivated(&self, network: NetworkId) {
|
||||||
fn encrypt(
|
let peers: Vec<_> = self
|
||||||
&self,
|
.peers
|
||||||
network: NetworkId,
|
.lock()
|
||||||
peer: EndpointId,
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
packet: &[u8],
|
.keys()
|
||||||
) -> Result<Bytes, PluginError> {
|
.filter(|(id, _)| *id == network)
|
||||||
let cipher = {
|
.map(|(_, peer)| *peer)
|
||||||
let guard = match self.ciphers.read() {
|
.collect();
|
||||||
Ok(g) => g,
|
for peer in peers {
|
||||||
Err(p) => p.into_inner(),
|
self.update_peer(network, peer, None);
|
||||||
};
|
|
||||||
guard.get(&(network, peer)).cloned()
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(cipher) = cipher else {
|
|
||||||
return Err(PluginError::Unavailable("no cipher for peer".into()));
|
|
||||||
};
|
|
||||||
|
|
||||||
cipher.encrypt(packet)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decrypt(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
peer: EndpointId,
|
|
||||||
payload: &[u8],
|
|
||||||
) -> Result<Bytes, PluginError> {
|
|
||||||
let cipher = {
|
|
||||||
let guard = match self.ciphers.read() {
|
|
||||||
Ok(g) => g,
|
|
||||||
Err(p) => p.into_inner(),
|
|
||||||
};
|
|
||||||
guard.get(&(network, peer)).cloned()
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(cipher) = cipher else {
|
|
||||||
return Err(PluginError::Unavailable("no cipher for peer".into()));
|
|
||||||
};
|
|
||||||
|
|
||||||
cipher.decrypt(payload)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The complete `tcp-tls` plugin.
|
|
||||||
pub type TcpTlsPlugin = GenericTunnelPlugin<TcpTlsCodec>;
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_is_candidate_interface_filters_overlay_and_bridges() {
|
|
||||||
let mut iface = netdev::Interface::dummy();
|
|
||||||
iface.flags = 1; // UP
|
|
||||||
|
|
||||||
// Standard Ethernet - should pass
|
|
||||||
iface.name = "eth0".to_string();
|
|
||||||
assert!(is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Windows Ethernet with GUID name - should pass
|
|
||||||
iface.name = "{B6149D2C-1234-5678-9ABC-DEF012345678}".to_string();
|
|
||||||
iface.friendly_name = Some("Ethernet".to_string());
|
|
||||||
iface.description = Some("Intel(R) Ethernet Connection".to_string());
|
|
||||||
assert!(is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Linux tsun0 overlay - must be filtered
|
|
||||||
iface.name = "tsun0".to_string();
|
|
||||||
iface.friendly_name = None;
|
|
||||||
iface.description = None;
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Windows Wintun overlay (GUID name with tsun0 friendly name) - must be filtered!
|
|
||||||
iface.name = "{72D85D76-F1A5-42AC-BC49-2169527CDDDF}".to_string();
|
|
||||||
iface.friendly_name = Some("tsun0".to_string());
|
|
||||||
iface.description = Some("Wintun Userspace Tunnel".to_string());
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Windows Wintun overlay with description containing Wintun - must be filtered!
|
|
||||||
iface.friendly_name = Some("Local Area Connection 2".to_string());
|
|
||||||
iface.description = Some("Wintun Userspace Tunnel".to_string());
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Docker bridge - must be filtered
|
|
||||||
iface.name = "docker0".to_string();
|
|
||||||
iface.friendly_name = None;
|
|
||||||
iface.description = None;
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Docker network bridge br-* - must be filtered
|
|
||||||
iface.name = "br-4f6d3a9b1c2e".to_string();
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Virtual ethernet veth* - must be filtered
|
|
||||||
iface.name = "veth12345".to_string();
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Libvirt NAT bridge virbr* - must be filtered
|
|
||||||
iface.name = "virbr0".to_string();
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// CNI bridge - must be filtered
|
|
||||||
iface.name = "cni0".to_string();
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Hyper-V / WSL vEthernet switch on Windows - must be filtered
|
|
||||||
iface.name = "{A1B2C3D4-E5F6-7890-1234-567890ABCDEF}".to_string();
|
|
||||||
iface.friendly_name = Some("vEthernet (WSL)".to_string());
|
|
||||||
iface.description = Some("Hyper-V Virtual Ethernet Adapter".to_string());
|
|
||||||
assert!(!is_candidate_interface(&iface));
|
|
||||||
|
|
||||||
// Down interface - must be filtered
|
|
||||||
let mut down_iface = netdev::Interface::dummy();
|
|
||||||
down_iface.flags = 0; // Not UP
|
|
||||||
down_iface.name = "eth0".to_string();
|
|
||||||
assert!(!is_candidate_interface(&down_iface));
|
|
||||||
}
|
}
|
||||||
|
fn bounded_ips<'de, D: serde::Deserializer<'de>>(
|
||||||
#[test]
|
deserializer: D,
|
||||||
fn test_is_candidate_ip() {
|
) -> Result<Vec<std::net::IpAddr>, D::Error> {
|
||||||
// Valid LAN IP
|
struct Visitor;
|
||||||
assert!(is_candidate_ip(std::net::IpAddr::V4(Ipv4Addr::new(
|
impl<'de> serde::de::Visitor<'de> for Visitor {
|
||||||
192, 168, 1, 117
|
type Value = Vec<std::net::IpAddr>;
|
||||||
))));
|
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
// Valid Tailscale IP
|
f.write_str("at most 32 IP candidates")
|
||||||
assert!(is_candidate_ip(std::net::IpAddr::V4(Ipv4Addr::new(
|
|
||||||
100, 77, 155, 120
|
|
||||||
))));
|
|
||||||
// Valid Public IP
|
|
||||||
assert!(is_candidate_ip(std::net::IpAddr::V4(Ipv4Addr::new(
|
|
||||||
1, 1, 1, 1
|
|
||||||
))));
|
|
||||||
// Valid IPv6 GUA
|
|
||||||
assert!(is_candidate_ip(std::net::IpAddr::V6(Ipv6Addr::new(
|
|
||||||
0x2a01, 0x4b00, 0xb8e3, 0x4e00, 0, 0, 0, 1
|
|
||||||
))));
|
|
||||||
|
|
||||||
// Loopback - must be rejected
|
|
||||||
assert!(!is_candidate_ip(std::net::IpAddr::V4(Ipv4Addr::new(
|
|
||||||
127, 0, 0, 1
|
|
||||||
))));
|
|
||||||
assert!(!is_candidate_ip(std::net::IpAddr::V6(Ipv6Addr::LOCALHOST)));
|
|
||||||
|
|
||||||
// Unspecified - must be rejected
|
|
||||||
assert!(!is_candidate_ip(std::net::IpAddr::V4(
|
|
||||||
Ipv4Addr::UNSPECIFIED
|
|
||||||
)));
|
|
||||||
assert!(!is_candidate_ip(std::net::IpAddr::V6(
|
|
||||||
Ipv6Addr::UNSPECIFIED
|
|
||||||
)));
|
|
||||||
|
|
||||||
// Link-local - must be rejected
|
|
||||||
assert!(!is_candidate_ip(std::net::IpAddr::V4(Ipv4Addr::new(
|
|
||||||
169, 254, 1, 1
|
|
||||||
))));
|
|
||||||
assert!(!is_candidate_ip(std::net::IpAddr::V6(Ipv6Addr::new(
|
|
||||||
0xfe80, 0, 0, 0, 0, 0x1ff, 0xfe00, 1
|
|
||||||
))));
|
|
||||||
|
|
||||||
// Broadcast - must be rejected
|
|
||||||
assert!(!is_candidate_ip(std::net::IpAddr::V4(Ipv4Addr::BROADCAST)));
|
|
||||||
}
|
}
|
||||||
|
fn visit_seq<A: serde::de::SeqAccess<'de>>(
|
||||||
#[test]
|
self,
|
||||||
fn test_ip_priority_ordering() {
|
mut seq: A,
|
||||||
let mut iface_lan = netdev::Interface::dummy();
|
) -> Result<Self::Value, A::Error> {
|
||||||
iface_lan.flags = 1;
|
if seq.size_hint().is_some_and(|n| n > 32) {
|
||||||
iface_lan.gateway = Some(netdev::net::device::NetworkDevice::new());
|
return Err(serde::de::Error::custom("too many IP candidates"));
|
||||||
|
}
|
||||||
let mut iface_vpn = netdev::Interface::dummy();
|
let mut ips = Vec::new();
|
||||||
iface_vpn.flags = 1;
|
while let Some(ip) = seq.next_element()? {
|
||||||
iface_vpn.name = "tailscale0".to_string();
|
if ips.len() == 32 {
|
||||||
|
return Err(serde::de::Error::custom("too many IP candidates"));
|
||||||
let lan_ip = std::net::IpAddr::V4(Ipv4Addr::new(192, 168, 1, 117));
|
}
|
||||||
let tailscale_ip = std::net::IpAddr::V4(Ipv4Addr::new(100, 77, 155, 120));
|
ips.push(ip);
|
||||||
|
}
|
||||||
let p_lan = ip_priority(&iface_lan, lan_ip);
|
Ok(ips)
|
||||||
let p_ts = ip_priority(&iface_vpn, tailscale_ip);
|
|
||||||
|
|
||||||
// LAN IP with gateway should score higher than VPN IP without gateway
|
|
||||||
assert!(p_lan > p_ts);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
deserializer.deserialize_seq(Visitor)
|
||||||
|
}
|
||||||
@@ -464,6 +464,17 @@ impl TcpTlsTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Replaces a bounded candidate set learned through an authenticated session.
|
||||||
|
pub fn replace_peer_addrs(&self, peer: EndpointId, addresses: Vec<SocketAddr>) {
|
||||||
|
if let Ok(mut peers) = self.peer_addresses.write() {
|
||||||
|
if addresses.is_empty() {
|
||||||
|
peers.remove(&peer);
|
||||||
|
} else {
|
||||||
|
peers.insert(peer, addresses.into_iter().take(32).collect());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Runs the accept loop for inbound TCP TLS connections.
|
/// Runs the accept loop for inbound TCP TLS connections.
|
||||||
pub async fn accept_loop<F>(&self, on_inbound: F)
|
pub async fn accept_loop<F>(&self, on_inbound: F)
|
||||||
where
|
where
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
#![allow(missing_docs)]
|
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
|
||||||
|
|
||||||
use tsunagi_tcp_tls::crypto::PeerCipher;
|
|
||||||
use x25519_dalek::{PublicKey, StaticSecret};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_peer_cipher_bidirectional_roundtrip() {
|
|
||||||
let peer_a_id = iroh::SecretKey::generate().public();
|
|
||||||
let peer_b_id = iroh::SecretKey::generate().public();
|
|
||||||
|
|
||||||
let secret_a = StaticSecret::from([10u8; 32]);
|
|
||||||
let public_a = PublicKey::from(&secret_a);
|
|
||||||
|
|
||||||
let secret_b = StaticSecret::from([20u8; 32]);
|
|
||||||
let public_b = PublicKey::from(&secret_b);
|
|
||||||
|
|
||||||
let cipher_a = PeerCipher::new(peer_a_id, peer_b_id, &secret_a, &public_b);
|
|
||||||
let cipher_b = PeerCipher::new(peer_b_id, peer_a_id, &secret_b, &public_a);
|
|
||||||
|
|
||||||
// A -> B
|
|
||||||
let msg_from_a = b"hello from node A to node B over Noise E2EE";
|
|
||||||
let encrypted_by_a = cipher_a
|
|
||||||
.encrypt(msg_from_a)
|
|
||||||
.expect("encryption should succeed");
|
|
||||||
let decrypted_by_b = cipher_b
|
|
||||||
.decrypt(&encrypted_by_a)
|
|
||||||
.expect("decryption should succeed");
|
|
||||||
assert_eq!(&decrypted_by_b[..], msg_from_a);
|
|
||||||
|
|
||||||
// B -> A
|
|
||||||
let msg_from_b = b"hello back from node B to node A";
|
|
||||||
let encrypted_by_b = cipher_b
|
|
||||||
.encrypt(msg_from_b)
|
|
||||||
.expect("encryption should succeed");
|
|
||||||
let decrypted_by_a = cipher_a
|
|
||||||
.decrypt(&encrypted_by_b)
|
|
||||||
.expect("decryption should succeed");
|
|
||||||
assert_eq!(&decrypted_by_a[..], msg_from_b);
|
|
||||||
|
|
||||||
// Sequence nonces increment
|
|
||||||
let msg2 = b"packet 2";
|
|
||||||
let enc2 = cipher_a.encrypt(msg2).expect("encryption should succeed");
|
|
||||||
assert_ne!(encrypted_by_a[..8], enc2[..8], "nonces should differ");
|
|
||||||
let dec2 = cipher_b.decrypt(&enc2).expect("decryption should succeed");
|
|
||||||
assert_eq!(&dec2[..], msg2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_tampered_payload_rejected() {
|
|
||||||
let peer_a_id = iroh::SecretKey::generate().public();
|
|
||||||
let peer_b_id = iroh::SecretKey::generate().public();
|
|
||||||
|
|
||||||
let secret_a = StaticSecret::from([10u8; 32]);
|
|
||||||
let public_a = PublicKey::from(&secret_a);
|
|
||||||
|
|
||||||
let secret_b = StaticSecret::from([20u8; 32]);
|
|
||||||
let public_b = PublicKey::from(&secret_b);
|
|
||||||
|
|
||||||
let cipher_a = PeerCipher::new(peer_a_id, peer_b_id, &secret_a, &public_b);
|
|
||||||
let cipher_b = PeerCipher::new(peer_b_id, peer_a_id, &secret_b, &public_a);
|
|
||||||
|
|
||||||
let encrypted = cipher_a.encrypt(b"secret payload").expect("encrypt");
|
|
||||||
// Corrupt one byte of ciphertext
|
|
||||||
let len = encrypted.len();
|
|
||||||
let mut modified = encrypted.to_vec();
|
|
||||||
modified[len - 1] ^= 0xff;
|
|
||||||
|
|
||||||
assert!(
|
|
||||||
cipher_b.decrypt(&modified).is_err(),
|
|
||||||
"corrupted ciphertext must fail AEAD verification"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,149 +1,33 @@
|
|||||||
#![allow(missing_docs)]
|
//! Bounded TLS carrier announcements contain no end-to-end cipher selection.
|
||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use std::{net::IpAddr, sync::Arc};
|
||||||
use std::sync::Arc;
|
use tsunagi::{
|
||||||
use std::time::Duration;
|
dataplane::transport::DataCarrier,
|
||||||
|
identity::{DeviceIdentity, NetworkId},
|
||||||
use bytes::Bytes;
|
};
|
||||||
use tokio::sync::mpsc;
|
use tsunagi_tcp_tls::{TcpTlsCarrier, TcpTlsTransport};
|
||||||
use tsunagi::dataplane::transport::{InboundLink, PacketTransport};
|
|
||||||
use tsunagi::dataplane::{IpPlugin, PacketSink, PluginContext};
|
|
||||||
use tsunagi::identity::{DeviceIdentity, NetworkId};
|
|
||||||
use tsunagi_tcp_tls::{TcpTlsCodec, TcpTlsPlugin, TcpTlsTransport};
|
|
||||||
|
|
||||||
struct TestSink {
|
|
||||||
delivered: mpsc::Sender<(NetworkId, iroh::EndpointId, Bytes)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PacketSink for TestSink {
|
|
||||||
fn deliver(
|
|
||||||
&self,
|
|
||||||
network: NetworkId,
|
|
||||||
from: iroh::EndpointId,
|
|
||||||
packet: Bytes,
|
|
||||||
) -> tsunagi::BoxFuture<'_, ()> {
|
|
||||||
let delivered = self.delivered.clone();
|
|
||||||
Box::pin(async move {
|
|
||||||
let _ = delivered.send((network, from, packet)).await;
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_tcp_tls_plugin_end_to_end() {
|
async fn tls_capabilities_bound_addresses_and_reject_invalid_ports_and_versions() {
|
||||||
let identity_a = DeviceIdentity::generate();
|
let identity = DeviceIdentity::generate();
|
||||||
let peer_a = identity_a.endpoint_id();
|
let peer = DeviceIdentity::generate().endpoint_id();
|
||||||
|
let transport = Arc::new(
|
||||||
let identity_b = DeviceIdentity::generate();
|
TcpTlsTransport::bind(&identity, Some(0), None)
|
||||||
let peer_b = identity_b.endpoint_id();
|
|
||||||
|
|
||||||
let network = NetworkId::from_bytes([77u8; 32]);
|
|
||||||
|
|
||||||
// Transports
|
|
||||||
let transport_b = Arc::new(
|
|
||||||
TcpTlsTransport::bind(&identity_b, Some(0), None)
|
|
||||||
.await
|
.await
|
||||||
.expect("bind B"),
|
.unwrap(),
|
||||||
);
|
);
|
||||||
let port_b = transport_b.bound_port();
|
let carrier = TcpTlsCarrier::new(transport);
|
||||||
|
let network = NetworkId::from_bytes([7; 32]);
|
||||||
let transport_a = Arc::new(
|
let mut cap = carrier.local_capability(network).unwrap().unwrap();
|
||||||
TcpTlsTransport::bind(&identity_a, Some(0), None)
|
assert_eq!(cap.protocol, "tcp-tls");
|
||||||
.await
|
let addresses: Vec<IpAddr> = vec!["192.0.2.1".parse().unwrap(); 33];
|
||||||
.expect("bind A"),
|
cap.data = postcard::to_allocvec(&(443u16, addresses)).unwrap();
|
||||||
);
|
assert!(carrier.on_peer_capability(network, peer, &cap).is_err());
|
||||||
|
cap.data = postcard::to_allocvec(&(0u16, Vec::<IpAddr>::new())).unwrap();
|
||||||
// Codecs and plugins
|
assert!(carrier.on_peer_capability(network, peer, &cap).is_err());
|
||||||
let codec_a = TcpTlsCodec::new(peer_a, Arc::clone(&transport_a));
|
cap.data =
|
||||||
let plugin_a = Arc::new(TcpTlsPlugin::new(codec_a));
|
postcard::to_allocvec(&(443u16, vec!["192.0.2.1".parse::<IpAddr>().unwrap()])).unwrap();
|
||||||
|
carrier.on_peer_capability(network, peer, &cap).unwrap();
|
||||||
let codec_b = TcpTlsCodec::new(peer_b, Arc::clone(&transport_b));
|
cap.version += 1;
|
||||||
let plugin_b = Arc::new(TcpTlsPlugin::new(codec_b));
|
assert!(carrier.on_peer_capability(network, peer, &cap).is_err());
|
||||||
|
|
||||||
// Attach sinks
|
|
||||||
let (sink_a_tx, mut sink_a_rx) = mpsc::channel(10);
|
|
||||||
plugin_a.attach(PluginContext::with_sink(Arc::new(TestSink {
|
|
||||||
delivered: sink_a_tx,
|
|
||||||
})));
|
|
||||||
|
|
||||||
let (sink_b_tx, mut sink_b_rx) = mpsc::channel(10);
|
|
||||||
plugin_b.attach(PluginContext::with_sink(Arc::new(TestSink {
|
|
||||||
delivered: sink_b_tx,
|
|
||||||
})));
|
|
||||||
|
|
||||||
// Capability exchange
|
|
||||||
let cap_a = plugin_a
|
|
||||||
.local_capability(network)
|
|
||||||
.expect("cap A")
|
|
||||||
.expect("some cap A");
|
|
||||||
let cap_b = plugin_b
|
|
||||||
.local_capability(network)
|
|
||||||
.expect("cap B")
|
|
||||||
.expect("some cap B");
|
|
||||||
|
|
||||||
plugin_a
|
|
||||||
.on_peer_capability(network, peer_b, &cap_b)
|
|
||||||
.expect("A on cap B");
|
|
||||||
plugin_b
|
|
||||||
.on_peer_capability(network, peer_a, &cap_a)
|
|
||||||
.expect("B on cap A");
|
|
||||||
|
|
||||||
// Spawn accept loop on B
|
|
||||||
let (inbound_tx, mut inbound_rx) = mpsc::channel::<InboundLink>(1);
|
|
||||||
let transport_b_clone = Arc::clone(&transport_b);
|
|
||||||
tokio::spawn(async move {
|
|
||||||
transport_b_clone
|
|
||||||
.accept_loop(move |inbound| {
|
|
||||||
let _ = inbound_tx.try_send(inbound);
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Make sure A knows B's loopback address
|
|
||||||
transport_a.set_peer_addr(peer_b, format!("127.0.0.1:{port_b}").parse().unwrap());
|
|
||||||
|
|
||||||
// Connect link from A to B
|
|
||||||
let link_a = transport_a
|
|
||||||
.open(network, peer_b, "tcp-tls")
|
|
||||||
.await
|
|
||||||
.expect("open link from A");
|
|
||||||
let inbound_b = tokio::time::timeout(Duration::from_secs(5), inbound_rx.recv())
|
|
||||||
.await
|
|
||||||
.expect("recv timeout")
|
|
||||||
.expect("recv inbound");
|
|
||||||
let link_b = inbound_b.link;
|
|
||||||
|
|
||||||
// Install links into plugins
|
|
||||||
plugin_a.on_peer_link(network, peer_b, link_a);
|
|
||||||
plugin_b.on_peer_link(network, peer_a, link_b);
|
|
||||||
|
|
||||||
// Carry packet from A to B
|
|
||||||
let ip_packet_a = Bytes::from_static(b"4500003c000100004011e0e8c0a80101c0a8010200000000");
|
|
||||||
let carried_a = plugin_a.carry(network, peer_b, ip_packet_a.clone());
|
|
||||||
assert!(carried_a, "plugin A should carry packet");
|
|
||||||
|
|
||||||
let (net_received, from_peer, delivered_pkt) =
|
|
||||||
tokio::time::timeout(Duration::from_secs(3), sink_b_rx.recv())
|
|
||||||
.await
|
|
||||||
.expect("timeout waiting for delivery on B")
|
|
||||||
.expect("packet on B");
|
|
||||||
|
|
||||||
assert_eq!(net_received, network);
|
|
||||||
assert_eq!(from_peer, peer_a);
|
|
||||||
assert_eq!(delivered_pkt, ip_packet_a);
|
|
||||||
|
|
||||||
// Carry reply packet from B to A
|
|
||||||
let ip_packet_b = Bytes::from_static(b"reply-packet-from-b");
|
|
||||||
let carried_b = plugin_b.carry(network, peer_a, ip_packet_b.clone());
|
|
||||||
assert!(carried_b, "plugin B should carry packet");
|
|
||||||
|
|
||||||
let (net_received, from_peer, delivered_pkt) =
|
|
||||||
tokio::time::timeout(Duration::from_secs(3), sink_a_rx.recv())
|
|
||||||
.await
|
|
||||||
.expect("timeout waiting for delivery on A")
|
|
||||||
.expect("packet on A");
|
|
||||||
|
|
||||||
assert_eq!(net_received, network);
|
|
||||||
assert_eq!(from_peer, peer_b);
|
|
||||||
assert_eq!(delivered_pkt, ip_packet_b);
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-tray"
|
name = "tsunagi-tray"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
description = "Tray application to manage a running tsunagi agent."
|
description = "Tray application to manage a running tsunagi agent."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -12,14 +12,17 @@ name = "tsunagi-tray"
|
|||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||||
# The agent control client and the report types: the GUI is a thin client over
|
# 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
|
# the same local control interface the CLI uses, so it reuses these directly
|
||||||
# and never re-implements the protocol.
|
# and never re-implements the protocol.
|
||||||
tsunagi-core = { path = "../tsunagi-core", version = "0.1.0" }
|
tsunagi-core = { path = "../tsunagi-core", version = "1.0.0" }
|
||||||
# Native, lightweight GUI — no web engine. eframe re-exports egui.
|
# Native, lightweight GUI — no web engine. eframe re-exports egui.
|
||||||
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
|
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).
|
# 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.
|
# Background worker that talks to the agent off the UI thread.
|
||||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
|
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
|
|||||||
@@ -14,63 +14,21 @@ use std::time::{Duration, Instant};
|
|||||||
use eframe::egui;
|
use eframe::egui;
|
||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
use tsunagi::ipc::{self, StatusReport};
|
use tsunagi::ipc;
|
||||||
|
|
||||||
/// How often the worker refreshes status while idle.
|
/// How often the worker refreshes status while idle.
|
||||||
const POLL_INTERVAL: Duration = Duration::from_secs(2);
|
const POLL_INTERVAL: Duration = Duration::from_secs(2);
|
||||||
|
|
||||||
/// A request from the UI to the agent.
|
use tsunagi_ui::client::Client;
|
||||||
pub(crate) enum Command {
|
pub(crate) use tsunagi_ui::client::{Command, Snapshot, VipSaveResult};
|
||||||
/// 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 },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The latest the worker knows, read by the UI each frame.
|
impl Client for AgentClient {
|
||||||
#[derive(Clone, Default)]
|
fn send(&self, command: Command) {
|
||||||
pub(crate) struct Snapshot {
|
self.send(command);
|
||||||
/// The last status, or the reason it could not be read (agent down, no
|
}
|
||||||
/// permission on the socket, …).
|
fn busy(&self) -> bool {
|
||||||
pub status: Option<Result<StatusReport, String>>,
|
lock(&self.shared).busy
|
||||||
/// 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,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle the UI holds: send commands, read the latest snapshot.
|
/// Handle the UI holds: send commands, read the latest snapshot.
|
||||||
@@ -178,7 +136,7 @@ async fn refresh(shared: &Arc<Mutex<Snapshot>>, ctx: &egui::Context) {
|
|||||||
.map_err(|err| err.to_string());
|
.map_err(|err| err.to_string());
|
||||||
{
|
{
|
||||||
let mut guard = lock(shared);
|
let mut guard = lock(shared);
|
||||||
guard.status = Some(status);
|
guard.status = Some(status.map(Arc::new));
|
||||||
guard.generation = guard.generation.wrapping_add(1);
|
guard.generation = guard.generation.wrapping_add(1);
|
||||||
guard.at = Some(Instant::now());
|
guard.at = Some(Instant::now());
|
||||||
guard.socket = socket;
|
guard.socket = socket;
|
||||||
@@ -198,6 +156,22 @@ async fn run(
|
|||||||
ctx.request_repaint();
|
ctx.request_repaint();
|
||||||
|
|
||||||
let outcome: Result<String, String> = match command {
|
let outcome: Result<String, String> = match command {
|
||||||
|
Command::SaveVip {
|
||||||
|
token,
|
||||||
|
network_id,
|
||||||
|
config,
|
||||||
|
expected,
|
||||||
|
delete,
|
||||||
|
} => {
|
||||||
|
let result = ipc::save_vip(socket, &network_id, config, expected, delete)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string());
|
||||||
|
lock(shared).vip_result = Some(VipSaveResult {
|
||||||
|
token,
|
||||||
|
result: result.clone(),
|
||||||
|
});
|
||||||
|
result.map(|_| "VIP configuration saved".into())
|
||||||
|
}
|
||||||
Command::ForgetNode {
|
Command::ForgetNode {
|
||||||
network_id,
|
network_id,
|
||||||
peer,
|
peer,
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ use crate::devices;
|
|||||||
use crate::stats::Traffic;
|
use crate::stats::Traffic;
|
||||||
use crate::ui::{self, UiState};
|
use crate::ui::{self, UiState};
|
||||||
|
|
||||||
|
use tsunagi_ui::app_fonts;
|
||||||
|
|
||||||
/// The window's state.
|
/// The window's state.
|
||||||
pub(crate) struct App {
|
pub(crate) struct App {
|
||||||
agent: AgentClient,
|
agent: AgentClient,
|
||||||
@@ -34,9 +36,7 @@ impl App {
|
|||||||
let ctx = cc.egui_ctx.clone();
|
let ctx = cc.egui_ctx.clone();
|
||||||
// Add the Phosphor icon glyphs to the font set so the icon buttons
|
// Add the Phosphor icon glyphs to the font set so the icon buttons
|
||||||
// render instead of showing as tofu.
|
// render instead of showing as tofu.
|
||||||
let mut fonts = egui::FontDefinitions::default();
|
ctx.set_fonts(app_fonts());
|
||||||
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
|
|
||||||
ctx.set_fonts(fonts);
|
|
||||||
|
|
||||||
let agent = AgentClient::spawn(&runtime, ctx);
|
let agent = AgentClient::spawn(&runtime, ctx);
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
@@ -60,6 +60,7 @@ impl eframe::App for App {
|
|||||||
|
|
||||||
ui::draw(ctx, &self.agent, &mut self.state, &snapshot, &self.traffic);
|
ui::draw(ctx, &self.agent, &mut self.state, &snapshot, &self.traffic);
|
||||||
self.show_devices_windows(ctx, &snapshot);
|
self.show_devices_windows(ctx, &snapshot);
|
||||||
|
self.show_vip_windows(ctx, &snapshot);
|
||||||
self.show_about_window(ctx, &snapshot);
|
self.show_about_window(ctx, &snapshot);
|
||||||
|
|
||||||
// A secret the worker fetched for the clipboard: copy it here, on the
|
// A secret the worker fetched for the clipboard: copy it here, on the
|
||||||
@@ -74,6 +75,51 @@ impl eframe::App for App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
|
fn show_vip_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
||||||
|
let Some(Ok(report)) = &snapshot.status else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let ids: Vec<_> = self.state.vip_windows.keys().cloned().collect();
|
||||||
|
for id in ids {
|
||||||
|
let Some(network) = report.networks.iter().find(|n| n.network_id == id) else {
|
||||||
|
self.state.vip_windows.remove(&id);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(state) = self.state.vip_windows.get_mut(&id) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let builder = egui::ViewportBuilder::default()
|
||||||
|
.with_title(format!("tsunagi · VIP · {}", network.name))
|
||||||
|
.with_app_id(crate::icon::APP_ID)
|
||||||
|
.with_icon(crate::icon::window())
|
||||||
|
.with_inner_size([1280., 860.])
|
||||||
|
.with_min_inner_size([650., 400.]);
|
||||||
|
let keep = ctx.show_viewport_immediate(
|
||||||
|
egui::ViewportId::from_hash_of(("vip", &id)),
|
||||||
|
builder,
|
||||||
|
|vctx, _| {
|
||||||
|
let close = crate::vip::show(vctx, &self.agent, state, network, snapshot);
|
||||||
|
if close {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if vctx.input(|i| i.viewport().close_requested()) {
|
||||||
|
if state.dirty() {
|
||||||
|
state.request_close();
|
||||||
|
vctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if !keep {
|
||||||
|
self.state.vip_windows.remove(&id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
/// Renders the About window while it is open.
|
/// Renders the About window while it is open.
|
||||||
fn show_about_window(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
fn show_about_window(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
||||||
if !self.state.about_open {
|
if !self.state.about_open {
|
||||||
@@ -90,7 +136,7 @@ impl App {
|
|||||||
egui::ViewportId::from_hash_of("about"),
|
egui::ViewportId::from_hash_of("about"),
|
||||||
builder,
|
builder,
|
||||||
|vctx, _class| {
|
|vctx, _class| {
|
||||||
about::show(vctx, &socket, snapshot);
|
about::show(vctx, Some(&socket), snapshot);
|
||||||
!vctx.input(|i| i.viewport().close_requested())
|
!vctx.input(|i| i.viewport().close_requested())
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -143,3 +189,20 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn route_icons_have_an_embedded_font_in_the_app() {
|
||||||
|
let fonts = app_fonts();
|
||||||
|
assert!(fonts.font_data.contains_key("phosphor"));
|
||||||
|
assert!(
|
||||||
|
fonts
|
||||||
|
.families
|
||||||
|
.get(&egui::FontFamily::Proportional)
|
||||||
|
.is_some_and(|family| family.iter().any(|name| name == "phosphor"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,16 +9,15 @@
|
|||||||
// Nothing here is a library.
|
// Nothing here is a library.
|
||||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
mod about;
|
use tsunagi_ui::about;
|
||||||
mod agent;
|
mod agent;
|
||||||
mod app;
|
mod app;
|
||||||
mod devices;
|
use tsunagi_ui::devices;
|
||||||
mod exit;
|
|
||||||
mod format;
|
|
||||||
mod icon;
|
mod icon;
|
||||||
mod stats;
|
use tsunagi_ui::stats;
|
||||||
mod tray;
|
mod tray;
|
||||||
mod ui;
|
mod ui;
|
||||||
|
use tsunagi_ui::vip;
|
||||||
mod watch;
|
mod watch;
|
||||||
|
|
||||||
use eframe::egui;
|
use eframe::egui;
|
||||||
|
|||||||
@@ -1,122 +0,0 @@
|
|||||||
//! Traffic rates derived from successive status snapshots.
|
|
||||||
//!
|
|
||||||
//! The agent reports cumulative packet and byte counters, not rates. The GUI
|
|
||||||
//! samples them each time a fresh snapshot arrives and turns the deltas into
|
|
||||||
//! per-second rates plus short rolling histories for sparklines. One series per
|
|
||||||
//! key: a network total, and each peer within it. Both packets and bytes are
|
|
||||||
//! tracked so the UI can switch between them.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, VecDeque};
|
|
||||||
use std::time::Instant;
|
|
||||||
|
|
||||||
use tsunagi::ipc::StatusReport;
|
|
||||||
|
|
||||||
/// How many rate samples to keep for a sparkline.
|
|
||||||
const HISTORY: usize = 60;
|
|
||||||
|
|
||||||
/// Which quantity a rate or history is of.
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(crate) enum Unit {
|
|
||||||
/// Packets per second.
|
|
||||||
Packets,
|
|
||||||
/// Bytes per second.
|
|
||||||
Bytes,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One series' rolling packet and byte rates.
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(crate) struct Series {
|
|
||||||
last: Option<(Instant, u64, u64)>,
|
|
||||||
packets_rate: f32,
|
|
||||||
bytes_rate: f32,
|
|
||||||
packets_history: VecDeque<f32>,
|
|
||||||
bytes_history: VecDeque<f32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Series {
|
|
||||||
fn sample(&mut self, now: Instant, packets: u64, bytes: u64) {
|
|
||||||
if let Some((then, prev_packets, prev_bytes)) = self.last {
|
|
||||||
let dt = now.saturating_duration_since(then).as_secs_f32();
|
|
||||||
if dt > 0.0 {
|
|
||||||
self.packets_rate = packets.saturating_sub(prev_packets) as f32 / dt;
|
|
||||||
self.bytes_rate = bytes.saturating_sub(prev_bytes) as f32 / dt;
|
|
||||||
push(&mut self.packets_history, self.packets_rate);
|
|
||||||
push(&mut self.bytes_history, self.bytes_rate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.last = Some((now, packets, bytes));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The current rate in the chosen unit.
|
|
||||||
pub(crate) fn rate(&self, unit: Unit) -> f32 {
|
|
||||||
match unit {
|
|
||||||
Unit::Packets => self.packets_rate,
|
|
||||||
Unit::Bytes => self.bytes_rate,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The rolling history in the chosen unit.
|
|
||||||
pub(crate) fn history(&self, unit: Unit) -> &VecDeque<f32> {
|
|
||||||
match unit {
|
|
||||||
Unit::Packets => &self.packets_history,
|
|
||||||
Unit::Bytes => &self.bytes_history,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push(history: &mut VecDeque<f32>, value: f32) {
|
|
||||||
history.push_back(value);
|
|
||||||
while history.len() > HISTORY {
|
|
||||||
history.pop_front();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// All traffic series, keyed by a stable string.
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(crate) 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) {
|
|
||||||
for network in &report.networks {
|
|
||||||
let Some(overlay) = &network.overlay else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let (mut net_packets, mut net_bytes) = (0u64, 0u64);
|
|
||||||
for peer in &overlay.peers {
|
|
||||||
let packets = peer.tx_packets.saturating_add(peer.rx_packets);
|
|
||||||
let bytes = peer.tx_bytes.saturating_add(peer.rx_bytes);
|
|
||||||
net_packets = net_packets.saturating_add(packets);
|
|
||||||
net_bytes = net_bytes.saturating_add(bytes);
|
|
||||||
self.series
|
|
||||||
.entry(peer_key(&network.network_id, &peer.public_key))
|
|
||||||
.or_default()
|
|
||||||
.sample(now, packets, bytes);
|
|
||||||
}
|
|
||||||
self.series
|
|
||||||
.entry(net_key(&network.network_id))
|
|
||||||
.or_default()
|
|
||||||
.sample(now, net_packets, net_bytes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The network-total series, if sampled.
|
|
||||||
pub(crate) 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> {
|
|
||||||
self.series.get(&peer_key(network_id, public_key))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn net_key(network_id: &str) -> String {
|
|
||||||
format!("net:{network_id}")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn peer_key(network_id: &str, public_key: &str) -> String {
|
|
||||||
format!("peer:{network_id}:{public_key}")
|
|
||||||
}
|
|
||||||
@@ -3,65 +3,22 @@
|
|||||||
//! [`crate::devices`]), opened from each tile.
|
//! [`crate::devices`]), opened from each tile.
|
||||||
//!
|
//!
|
||||||
//! Pure rendering: state comes from the snapshot and the traffic sampler, a
|
//! 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
|
//! state (the join form, the unit toggle, which devices windows are open, an
|
||||||
//! in-progress hostname edit) lives in [`UiState`].
|
//! 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 eframe::egui;
|
||||||
use egui_phosphor::regular as icon;
|
use egui_phosphor::regular as icon;
|
||||||
|
|
||||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
use crate::agent::{AgentClient, Snapshot};
|
||||||
|
|
||||||
use crate::agent::{AgentClient, Command, Snapshot};
|
|
||||||
use crate::devices;
|
use crate::devices;
|
||||||
use crate::exit;
|
|
||||||
use crate::format;
|
|
||||||
use crate::stats::{Traffic, Unit};
|
use crate::stats::{Traffic, Unit};
|
||||||
|
|
||||||
const OK: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a);
|
const OK: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a);
|
||||||
const BAD: egui::Color32 = egui::Color32::from_rgb(0xd0, 0x4a, 0x3c);
|
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>,
|
|
||||||
/// 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(),
|
|
||||||
about_open: false,
|
|
||||||
exit_confirm: None,
|
|
||||||
forget_confirm: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Draws the main window.
|
/// Draws the main window.
|
||||||
pub(crate) fn draw(
|
pub(crate) fn draw(
|
||||||
@@ -126,7 +83,7 @@ pub(crate) fn draw(
|
|||||||
ui.weak("No networks yet — join one below.");
|
ui.weak("No networks yet — join one below.");
|
||||||
}
|
}
|
||||||
for network in &report.networks {
|
for network in &report.networks {
|
||||||
draw_network(ui, agent, state, traffic, network, report);
|
draw_network(ui, agent, state, traffic, network, report, true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -152,349 +109,3 @@ fn draw_unreachable(ui: &mut egui::Ui, agent: &AgentClient, error: &str) {
|
|||||||
(its group, mode 0660).",
|
(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);
|
|
||||||
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!("protocols {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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsunagi-ui"
|
||||||
|
version = "1.0.0"
|
||||||
|
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
|
//! half is whatever the agent says about itself, so a client and an agent that
|
||||||
//! are not the same build show up as such.
|
//! are not the same build show up as such.
|
||||||
|
|
||||||
use eframe::egui;
|
|
||||||
|
|
||||||
use tsunagi::ipc::{PrivilegeReport, StatusReport};
|
use tsunagi::ipc::{PrivilegeReport, StatusReport};
|
||||||
|
|
||||||
use crate::agent::Snapshot;
|
use crate::client::Snapshot;
|
||||||
use crate::format;
|
use crate::format;
|
||||||
|
|
||||||
const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
|
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");
|
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
|
|
||||||
/// Draws the window body into its viewport.
|
/// 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| {
|
egui::CentralPanel::default().show(ctx, |ui| {
|
||||||
// Long paths and a taller agent table must scroll rather than be cut.
|
// Long paths and a taller agent table must scroll rather than be cut.
|
||||||
egui::ScrollArea::both()
|
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.horizontal(|ui| {
|
||||||
ui.heading("tsunagi");
|
ui.heading("tsunagi");
|
||||||
@@ -61,11 +59,13 @@ fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) {
|
|||||||
|
|
||||||
ui.add_space(8.0);
|
ui.add_space(8.0);
|
||||||
section(ui, "agent");
|
section(ui, "agent");
|
||||||
let socket = socket.display().to_string();
|
let socket = socket.map(|p| p.display().to_string());
|
||||||
match &snapshot.status {
|
match &snapshot.status {
|
||||||
None => {
|
None => {
|
||||||
grid(ui, "about agent", |ui| {
|
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| {
|
row(ui, "state", |ui| {
|
||||||
ui.label("connecting…");
|
ui.label("connecting…");
|
||||||
});
|
});
|
||||||
@@ -73,7 +73,9 @@ fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) {
|
|||||||
}
|
}
|
||||||
Some(Err(error)) => {
|
Some(Err(error)) => {
|
||||||
grid(ui, "about agent", |ui| {
|
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| {
|
row(ui, "state", |ui| {
|
||||||
ui.colored_label(egui::Color32::from_rgb(0xd8, 0x4a, 0x3a), "unreachable");
|
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| {
|
grid(ui, "about agent", |ui| {
|
||||||
|
if let Some(socket) = socket {
|
||||||
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
||||||
|
}
|
||||||
row(ui, "state", |ui| {
|
row(ui, "state", |ui| {
|
||||||
ui.colored_label(egui::Color32::from_rgb(0x3c, 0xb0, 0x4a), "connected");
|
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");
|
ui.weak("unknown");
|
||||||
}
|
}
|
||||||
PrivilegeReport::Available => {
|
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(_) => {
|
PrivilegeReport::Missing(_) => {
|
||||||
ui.colored_label(egui::Color32::from_rgb(0xd8, 0x9a, 0x2a), "no privileges");
|
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;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,193 @@
|
|||||||
|
//! 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", "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.control_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 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();
|
||||||
|
}
|
||||||
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user