Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8b7787430 | ||
|
|
b47acb8321 | ||
|
|
e3b74babba | ||
|
|
7afed15f76 | ||
|
|
e7de9b44af | ||
|
|
200e716c28 | ||
|
|
fb7a959d23 | ||
|
|
6a0a87e76c | ||
|
|
e3e6089d0b | ||
|
|
50c0ecea45 | ||
|
|
8c4c2fa34e | ||
|
|
f9f67f88b1 | ||
|
|
a189d0ad3e |
No files matched your search
@@ -2,7 +2,7 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [master, main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -25,6 +25,8 @@ jobs:
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
- name: Check Debian release candidate upgrade ordering
|
||||
run: bash dist/deb/test-deb.sh
|
||||
|
||||
test:
|
||||
name: test (${{ matrix.os }})
|
||||
|
||||
@@ -5,6 +5,14 @@ on:
|
||||
branches: [master]
|
||||
paths:
|
||||
- '.github/workflows/subnet-source.yml'
|
||||
- 'crates/tsunagi-core/src/overlay/egress.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/egress/**'
|
||||
- 'crates/tsunagi-core/src/overlay/interface.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/router.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/linux_exit*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/linux.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/macos*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/windows*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/macos.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/windows.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/mod.rs'
|
||||
@@ -25,6 +33,8 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
test: overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit
|
||||
- os: macos-latest
|
||||
test: overlay::provision::macos::tests::unbound_sockets_choose_each_networks_source_on_one_real_utun
|
||||
- os: windows-latest
|
||||
@@ -51,10 +61,26 @@ jobs:
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
if ($tests -notcontains "$($env:TEST_NAME): test") { throw "Missing ignored test: $env:TEST_NAME" }
|
||||
"TEST_BINARY=$binary" >> $env:GITHUB_ENV
|
||||
- name: Verify separate forwarding and local egress in Linux namespaces
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
|
||||
- name: Verify source selection on a real utun
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
|
||||
- name: Verify exit routing and PF translation on two real utuns
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
timeout-minutes: 2
|
||||
env:
|
||||
EXIT_TEST: overlay::hostrules::macos_exit::kernel::exit_preserves_underlay_and_both_meshes
|
||||
run: |
|
||||
"$TEST_BINARY" --ignored --exact "$EXIT_TEST" --list | grep -Fx "$EXIT_TEST: test"
|
||||
previous=$(sysctl -n net.inet.ip.forwarding)
|
||||
trap 'sudo -n sysctl -w "net.inet.ip.forwarding=$previous"' EXIT
|
||||
sudo -n sysctl -w net.inet.ip.forwarding=1
|
||||
sudo -n -- "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --nocapture
|
||||
- name: Verify source selection on a real Wintun adapter
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
@@ -70,3 +96,24 @@ jobs:
|
||||
Copy-Item (Join-Path $directory 'wintun/bin/amd64/wintun.dll') (Split-Path -Parent $env:TEST_BINARY)
|
||||
& $env:TEST_BINARY --ignored --exact $env:TEST_NAME --nocapture
|
||||
exit $LASTEXITCODE
|
||||
- name: Verify forwarded and local traffic to the same destination
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
timeout-minutes: 2
|
||||
run: |
|
||||
$test = 'overlay::egress::tests::physical_member_sockets_survive_a_more_specific_wintun_route'
|
||||
$listing = @(& $env:TEST_BINARY --ignored --exact $test --list)
|
||||
if ($listing -notcontains "${test}: test") { throw "Missing ignored test $test" }
|
||||
& $env:TEST_BINARY --ignored --exact $test --nocapture
|
||||
exit $LASTEXITCODE
|
||||
- name: Verify one Windows exit bypass route through the physical gateway
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
timeout-minutes: 2
|
||||
run: |
|
||||
$test = 'overlay::hostrules::windows_exit::tests::windows_refresh_installs_only_the_external_test_address'
|
||||
$listing = @(& $env:TEST_BINARY --ignored --exact $test --list)
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
if ($listing -notcontains "${test}: test") { throw "Missing ignored test: $test" }
|
||||
& $env:TEST_BINARY --ignored --exact $test --nocapture
|
||||
exit $LASTEXITCODE
|
||||
Generated
+25
-10
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -6320,7 +6320,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"egui",
|
||||
@@ -6344,7 +6344,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"iroh",
|
||||
@@ -6359,7 +6359,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -6385,6 +6385,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"simple-dns",
|
||||
"smoltcp",
|
||||
"socket2",
|
||||
"subtle",
|
||||
"tempfile",
|
||||
"thiserror 2.0.20",
|
||||
@@ -6394,6 +6395,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsunagi-core",
|
||||
"tsunagi-speedtest",
|
||||
"tun",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
@@ -6402,7 +6404,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -6413,9 +6415,19 @@ dependencies = [
|
||||
"tsunagi-wireguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-speedtest"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"postcard",
|
||||
"serde",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"caps",
|
||||
@@ -6435,7 +6447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui-phosphor",
|
||||
@@ -6451,17 +6463,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"postcard",
|
||||
"rusqlite",
|
||||
"tempfile",
|
||||
"tsunagi-core",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wg-quic"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
@@ -6488,7 +6503,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
|
||||
@@ -141,8 +141,29 @@ tsng protocols home none # control plane only
|
||||
|
||||
Exact network names, full ids and unique id prefixes work here. The choice is
|
||||
local to this device, saved per network and applied immediately; an offline
|
||||
change applies on the next start. In the tray, expand **data transports** on a network
|
||||
tile to enable transports and set their initial preference order. Adjacent peers need a common external transport at the same wire version.
|
||||
change applies on the next start. In the tray or on Android, click the network
|
||||
name to expand its card. Open **data transports** to enable transports and set
|
||||
their initial preference order. **Show devices** lists peers and their reported
|
||||
Tsunagi versions. On Android, tap a device to see its version and traffic.
|
||||
|
||||
Select a peer’s speedometer in **Devices** to measure download and upload
|
||||
through its current encrypted mesh path. The cell shows live rates in Mbit/s.
|
||||
Select the result to test again, or use **Test exits** to check the network’s
|
||||
online, compatible exit nodes one at a time. The test ends at the peer, so its
|
||||
Internet uplink beyond that peer is outside the measurement. Hover or long-press
|
||||
the result for details. “At least” means the receiver sustained that rate and
|
||||
the test ended before it could confirm the limit. A missing direction means
|
||||
the sample was too short. Both peers need speed-test support.
|
||||
|
||||
A test runs for up to five seconds. It raises the offered rate in steps and
|
||||
tries a higher rate again after a slow start. The receiver counts unique payload
|
||||
bytes across sustained trains of packets, including the last train before the
|
||||
traffic budget runs out. The traffic ceiling is 96 MiB per direction for one
|
||||
peer, or 8 MiB when either endpoint reports a metered link.
|
||||
A batch shares 128 MiB per direction among its exits, or 16 MiB on a metered
|
||||
initiator. These ceilings count probe IP packets before tunnel overhead.
|
||||
|
||||
Adjacent peers need a common external transport at the same wire version.
|
||||
Peers that both support link comparison probe another mutually enabled transport
|
||||
while traffic continues on the current one. They can switch to a faster healthy link.
|
||||
`tsng status` and the tray show the direct data link's measured RTT separately
|
||||
@@ -175,6 +196,24 @@ when they reconnect. It does not ban the device: a newer signed claim can return
|
||||
Online nodes and the currently selected exit node cannot be forgotten.
|
||||
[State and limits](docs/sync-model.md#offline-node-cleanup).
|
||||
|
||||
### Traffic monitor
|
||||
|
||||
Open **Traffic monitor** (the pulse icon in the tray window or Android header) to
|
||||
start an empty live capture. **IP flows** groups both directions of a TCP or UDP
|
||||
address/port pair and repeated ICMP echoes for an address pair into one row. Select a network and peer, protocol or
|
||||
role to narrow it down. **Via exit node** shows your outgoing internet traffic.
|
||||
**Serving exit** shows traffic your device forwards for another peer.
|
||||
|
||||
**Transport** shows authenticated control sessions and encrypted datagrams
|
||||
forwarded between two other endpoints. For relay rows the arrows follow the
|
||||
two displayed endpoints in order. Rates update once per second. Select a row
|
||||
to see its packet counts. The monitor records header metadata and counters only.
|
||||
|
||||
Inactive rows expire after 60 seconds. **Keep until close** retains flows in a
|
||||
private temporary table owned by the window. Closing it discards the table and
|
||||
ends collection. Android pauses collection while the activity is in the background.
|
||||
Under heavy load the monitor displays the number of missed observations.
|
||||
|
||||
## Platforms
|
||||
|
||||
| Platform | Build | CLI `tsng` | Tray | Exit node: offer / use | Packages |
|
||||
|
||||
+6
-2
@@ -16,7 +16,7 @@ cd android
|
||||
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.
|
||||
Open **tsunagi** to start the agent. On first launch, accept Android’s VPN permission prompt so the agent can create its mesh interface. Join with the existing network name and secret. The service continues when the activity closes. Mesh changes update split DNS and the selected-exit notification in the background. Opening the activity also requests live traffic counters. **About → Stop Tsunagi Agent** keeps it stopped across launches. After stopping or declining consent, tap **Start Tsunagi Agent** to enable automatic startup again. The app-private state directory holds the device identity and its saved networks.
|
||||
|
||||
The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic.
|
||||
|
||||
@@ -26,7 +26,11 @@ Applications using Android’s system resolver can connect to `<member>.<network
|
||||
|
||||
The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard.
|
||||
|
||||
Open **Exit node…** on a network tile to compare remote gateways by measured data RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
|
||||
Rotate the phone to select a network on the left and see its settings on the right. **Show devices** opens a table sized to the screen. Tap a peer for its version, data path and traffic. A green check marks a ready data channel, an amber spinning arc indicates a pending connection, and a red warning opens the error details. Hold an icon for its label. Rotating the phone keeps the selected peer and any edits in the VIP editor.
|
||||
|
||||
Tap the network name to expand its card, then open **Exit node…** to compare remote gateways by measured data RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
|
||||
|
||||
To switch the exit from the notification shade, edit Android Quick Settings and add **Tsunagi Exit**. The first tap opens the exit chooser if you have never used one. Subsequent taps disconnect the selected exit or reconnect the last peer in its original network. The tile shows the peer name and whether the selected peer is offline. Mesh access stays available when the exit is off.
|
||||
|
||||
## Check two networks on an emulator
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ android {
|
||||
targetSdk 35
|
||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.2')
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.8')
|
||||
ndk { abiFilters abi }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.SystemClock
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Test
|
||||
|
||||
class AgentStartupTest {
|
||||
@Suppress("DEPRECATION")
|
||||
@Test fun launchStartsAgentAndExplicitStopSurvivesReopening() {
|
||||
val test = InstrumentationRegistry.getInstrumentation()
|
||||
val context = test.targetContext
|
||||
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
|
||||
val manager = context.getSystemService(ActivityManager::class.java)
|
||||
fun running() = manager.getRunningServices(Int.MAX_VALUE).any {
|
||||
it.service.className == MeshVpn::class.java.name && it.started
|
||||
}
|
||||
fun awaitRunning(expected: Boolean) {
|
||||
val deadline = SystemClock.elapsedRealtime() + 5000
|
||||
while (running() != expected) {
|
||||
check(SystemClock.elapsedRealtime() < deadline) { "Agent did not reach started=$expected" }
|
||||
SystemClock.sleep(25)
|
||||
}
|
||||
}
|
||||
fun launch() = test.startActivitySync(Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
|
||||
|
||||
val settings = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
|
||||
val old = settings.getBoolean("auto_start", true)
|
||||
var activity: MainActivity? = null
|
||||
try {
|
||||
settings.edit().remove("auto_start").commit()
|
||||
activity = launch()
|
||||
awaitRunning(true)
|
||||
test.runOnMainSync { activity!!.stopAgent(); activity!!.finish() }
|
||||
awaitRunning(false)
|
||||
activity = launch()
|
||||
test.waitForIdleSync()
|
||||
check(!running())
|
||||
test.runOnMainSync { activity!!.requestAgent() }
|
||||
awaitRunning(true)
|
||||
} finally {
|
||||
test.runOnMainSync { activity?.stopAgent(); activity?.finish() }
|
||||
awaitRunning(false)
|
||||
settings.edit().putBoolean("auto_start", old).commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Test
|
||||
|
||||
class ExitTileTest {
|
||||
@Test fun tileKeepsTheExactLastSelectionOnlyAfterTheAgentConfirmsIt() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
val info = context.packageManager.getServiceInfo(ComponentName(context, ExitTile::class.java), 0)
|
||||
check(info.permission == "android.permission.BIND_QUICK_SETTINGS_TILE")
|
||||
check(!context.packageManager.getActivityInfo(ExitTile.entry(context), 0).exported)
|
||||
check(Native.tileExit(0, "network", "peer", true, false) == "Tsunagi Agent stopped")
|
||||
val isolated = context.createDeviceProtectedStorageContext()
|
||||
val settings = isolated.getSharedPreferences("exit_tile", Context.MODE_PRIVATE)
|
||||
settings.edit().clear().commit()
|
||||
val first = ExitTile.Target("network-a", "peer", "Gateway")
|
||||
val last = ExitTile.Target("network-b", "peer", "Gateway")
|
||||
try {
|
||||
check(ExitTile.last(isolated) == null)
|
||||
ExitTile.publish(isolated, 1L, first, true)
|
||||
ExitTile.publish(isolated, 1L, last, true)
|
||||
ExitTile.publish(isolated, 1L, null, false)
|
||||
check(ExitTile.last(isolated) == last)
|
||||
ExitTile.reset(isolated)
|
||||
check(ExitTile.last(isolated) == last)
|
||||
} finally {
|
||||
ExitTile.reset(isolated)
|
||||
settings.edit().clear().commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,18 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity-alias android:name=".OpenExit" android:targetActivity=".MainActivity" android:exported="false" />
|
||||
<service android:name=".MeshVpn" android:permission="android.permission.BIND_VPN_SERVICE"
|
||||
android:foregroundServiceType="systemExempted" android:exported="false">
|
||||
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
|
||||
<meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON" android:value="false" />
|
||||
</service>
|
||||
<service android:name=".ExitTile" android:exported="true"
|
||||
android:label="Tsunagi Exit" android:icon="@drawable/exit_tile"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter><action android:name="android.service.quicksettings.action.QS_TILE" /></intent-filter>
|
||||
<meta-data android:name="android.service.quicksettings.ACTIVE_TILE" android:value="true" />
|
||||
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="true" />
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,113 @@
|
||||
package cy.hexor.tsunagi
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
import android.widget.Toast
|
||||
|
||||
/** Quick Settings changes the internet exit of the existing mesh agent. */
|
||||
class ExitTile : TileService() {
|
||||
internal data class Target(val network: String, val peer: String, val name: String)
|
||||
private data class Snapshot(val session: Long, val active: Target?, val online: Boolean)
|
||||
|
||||
companion object {
|
||||
internal fun entry(context: Context) = ComponentName(context, "${context.packageName}.OpenExit")
|
||||
private var live = Snapshot(0, null, false)
|
||||
private var pending = false
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
internal fun last(context: Context): Target? {
|
||||
val prefs = context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE)
|
||||
val network = prefs.getString("network", null) ?: return null
|
||||
val peer = prefs.getString("peer", null) ?: return null
|
||||
return Target(network, peer, prefs.getString("name", null) ?: peer.take(12))
|
||||
}
|
||||
private fun refresh(context: Context) {
|
||||
requestListeningState(context, ComponentName(context, ExitTile::class.java))
|
||||
}
|
||||
internal fun publish(context: Context, session: Long, active: Target?, online: Boolean) {
|
||||
// Only confirmed agent status updates the last selection. Clearing an exit or
|
||||
// stopping the process leaves the exact network and peer available for reuse.
|
||||
if (active != null && last(context) != active) {
|
||||
context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE).edit()
|
||||
.putString("network", active.network).putString("peer", active.peer)
|
||||
.putString("name", active.name).apply()
|
||||
}
|
||||
live = Snapshot(session, active, online)
|
||||
refresh(context)
|
||||
}
|
||||
internal fun reset(context: Context) {
|
||||
live = Snapshot(0, null, false)
|
||||
refresh(context)
|
||||
}
|
||||
internal fun restoreIfReady(context: Context, target: Target): Boolean {
|
||||
if (live.session == 0L) return false
|
||||
if (live.active == null) change(context, live.session, target, true, waitForDiscovery = true)
|
||||
return true
|
||||
}
|
||||
private fun change(context: Context, session: Long, target: Target, connect: Boolean, waitForDiscovery: Boolean = false) {
|
||||
if (pending) return
|
||||
pending = true
|
||||
refresh(context)
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val error = Native.tileExit(session, target.network, target.peer, connect, waitForDiscovery)
|
||||
main.post {
|
||||
pending = false
|
||||
if (error != null) Toast.makeText(app, error, Toast.LENGTH_LONG).show()
|
||||
refresh(app)
|
||||
}
|
||||
}, "tsunagi-exit-tile").start()
|
||||
}
|
||||
}
|
||||
|
||||
private var displayed = live
|
||||
private var remembered: Target? = null
|
||||
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
displayed = live
|
||||
remembered = last(this)
|
||||
val tile = qsTile ?: return
|
||||
val active = displayed.active
|
||||
val peer = active ?: remembered
|
||||
val subtitle = when {
|
||||
pending -> "Updating…"
|
||||
active != null && !displayed.online -> "${active.name} · offline"
|
||||
peer != null -> peer.name
|
||||
else -> "Choose exit node"
|
||||
}
|
||||
tile.state = when {
|
||||
pending -> Tile.STATE_UNAVAILABLE
|
||||
active != null -> Tile.STATE_ACTIVE
|
||||
else -> Tile.STATE_INACTIVE
|
||||
}
|
||||
tile.label = if (Build.VERSION.SDK_INT < 29 && peer != null) "Exit · ${peer.name}" else "Tsunagi Exit"
|
||||
if (Build.VERSION.SDK_INT >= 29) tile.subtitle = subtitle
|
||||
tile.contentDescription = "Tsunagi exit node, $subtitle"
|
||||
tile.updateTile()
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
if (pending || displayed != live) { onStartListening(); return }
|
||||
val target = displayed.active ?: remembered
|
||||
if (displayed.session != 0L && target != null) {
|
||||
change(this, displayed.session, target, displayed.active == null)
|
||||
return
|
||||
}
|
||||
// Consent, a stopped service, or the first selection needs an activity.
|
||||
val open = Intent().setComponent(entry(this))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
if (Build.VERSION.SDK_INT >= 34) {
|
||||
startActivityAndCollapse(PendingIntent.getActivity(this, 2, open, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT))
|
||||
} else startActivityAndCollapse(open)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,10 @@ import android.view.WindowInsets
|
||||
import android.widget.FrameLayout
|
||||
|
||||
class MainActivity : Activity() {
|
||||
private val settings by lazy { getSharedPreferences("agent", MODE_PRIVATE) }
|
||||
private var checkedAutoStart = false
|
||||
private var consentPending = false
|
||||
private var tileRequested = false
|
||||
private var askedForNotifications = false
|
||||
internal fun requestExitNotifications() {
|
||||
if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications &&
|
||||
@@ -20,6 +24,8 @@ class MainActivity : Activity() {
|
||||
private lateinit var surface: MeshSurface
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
consentPending = savedInstanceState?.getBoolean("consent_pending") == true
|
||||
tileRequested = savedInstanceState?.getBoolean("exit_tile") ?: (intent.component == ExitTile.entry(this))
|
||||
surface = MeshSurface(this)
|
||||
val root = FrameLayout(this)
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
@@ -33,17 +39,59 @@ class MainActivity : Activity() {
|
||||
root.addView(surface)
|
||||
setContentView(root)
|
||||
}
|
||||
internal fun requestVpn() {
|
||||
override fun onPostResume() {
|
||||
super.onPostResume()
|
||||
if (tileRequested && !consentPending) {
|
||||
checkedAutoStart = true
|
||||
requestAgent()
|
||||
return
|
||||
}
|
||||
if (checkedAutoStart) return
|
||||
checkedAutoStart = true
|
||||
if (!MeshVpn.started && settings.getBoolean("auto_start", true)) requestAgent()
|
||||
}
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
outState.putBoolean("consent_pending", consentPending)
|
||||
outState.putBoolean("exit_tile", tileRequested)
|
||||
}
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
if (intent.component == ExitTile.entry(this)) tileRequested = true
|
||||
}
|
||||
internal fun requestAgent() {
|
||||
if (consentPending) return
|
||||
val consent = VpnService.prepare(this)
|
||||
if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java))
|
||||
else startActivityForResult(consent, 1)
|
||||
if (consent == null) startAgent() else {
|
||||
consentPending = true
|
||||
startActivityForResult(consent, 1)
|
||||
}
|
||||
}
|
||||
private fun startAgent() {
|
||||
settings.edit().putBoolean("auto_start", true).apply()
|
||||
val service = Intent(this, MeshVpn::class.java)
|
||||
if (tileRequested) {
|
||||
tileRequested = false
|
||||
if (ExitTile.last(this) != null) service.action = MeshVpn.RESTORE_EXIT
|
||||
else surface.openExitPicker()
|
||||
}
|
||||
// A retry of an existing service may already have left foreground mode.
|
||||
if (MeshVpn.started) startService(service) else startForegroundService(service)
|
||||
}
|
||||
internal fun stopAgent() {
|
||||
settings.edit().putBoolean("auto_start", false).apply()
|
||||
startService(Intent(this, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN))
|
||||
}
|
||||
@Deprecated("Platform consent result")
|
||||
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
|
||||
super.onActivityResult(request, result, data)
|
||||
if (request == 1) {
|
||||
if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java))
|
||||
else surface.input(5, "VPN permission was declined")
|
||||
consentPending = false
|
||||
if (result == RESULT_OK) startAgent() else {
|
||||
tileRequested = false
|
||||
settings.edit().putBoolean("auto_start", false).apply()
|
||||
surface.input(5, "Android VPN permission was declined")
|
||||
}
|
||||
}
|
||||
}
|
||||
@Deprecated("Forward system Back to the current Rust view")
|
||||
|
||||
@@ -19,10 +19,13 @@ import javax.microedition.khronos.opengles.GL10
|
||||
class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), GLSurfaceView.Renderer {
|
||||
private val density get() = resources.displayMetrics.density
|
||||
private val imm = activity.getSystemService(InputMethodManager::class.java)
|
||||
@Volatile private var paused = false
|
||||
private var imeMode = 0
|
||||
private var widthPx = 0
|
||||
private var heightPx = 0
|
||||
private val repaint = Runnable { requestRender() }
|
||||
private val pickExit = java.util.concurrent.atomic.AtomicBoolean()
|
||||
fun openExitPicker() { pickExit.set(true); requestRender() }
|
||||
init {
|
||||
setEGLContextClientVersion(3)
|
||||
preserveEGLContextOnPause = true
|
||||
@@ -31,14 +34,23 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
|
||||
isFocusableInTouchMode = true
|
||||
requestFocus()
|
||||
}
|
||||
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
|
||||
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface(context.cacheDir.absolutePath)
|
||||
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
|
||||
override fun onDrawFrame(gl: GL10?) {
|
||||
val delay = Native.draw(this, widthPx, heightPx, density)
|
||||
if (paused) return
|
||||
if (pickExit.getAndSet(false)) Native.input(6, "")
|
||||
val landscape = resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE
|
||||
val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started, landscape)
|
||||
removeCallbacks(repaint)
|
||||
postDelayed(repaint, delay.coerceAtLeast(16))
|
||||
}
|
||||
override fun onPause() { super.onPause(); removeCallbacks(repaint) }
|
||||
override fun onPause() {
|
||||
paused = true
|
||||
queueEvent { Native.pauseTraffic() }
|
||||
super.onPause()
|
||||
removeCallbacks(repaint)
|
||||
}
|
||||
override fun onResume() { paused = false; super.onResume(); requestRender() }
|
||||
override fun onTouchEvent(e: MotionEvent): Boolean {
|
||||
val phase = when (e.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0
|
||||
@@ -58,8 +70,8 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
|
||||
return true
|
||||
}
|
||||
|
||||
fun startVpn() { post { activity.requestVpn() } }
|
||||
fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } }
|
||||
fun startAgent() { post { activity.requestAgent() } }
|
||||
fun stopAgent() { post { activity.stopAgent() } }
|
||||
fun requestExitNotifications() { post { activity.requestExitNotifications() } }
|
||||
fun closeScreen() { post { activity.finish() } }
|
||||
fun openUrl(url: String) { post {
|
||||
|
||||
@@ -24,19 +24,25 @@ import java.util.concurrent.TimeUnit
|
||||
class MeshVpn : VpnService() {
|
||||
companion object {
|
||||
const val STOP_VPN = "cy.hexor.tsunagi.STOP_VPN"
|
||||
const val RESTORE_EXIT = "cy.hexor.tsunagi.RESTORE_EXIT"
|
||||
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
|
||||
private const val NOTIFICATION_ID = 1
|
||||
private const val EXIT_CHANNEL = "exit-node"
|
||||
@Volatile var started = false
|
||||
private set
|
||||
}
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val notifications by lazy { getSystemService(NotificationManager::class.java) }
|
||||
@Volatile private var instance = 0L
|
||||
private var closed = false
|
||||
private var restore: ExitTile.Target? = null
|
||||
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
|
||||
@Volatile private var upstream: Network? = null
|
||||
private var watching = false
|
||||
private val changes = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) = useUnderlay(network)
|
||||
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
|
||||
if (network == upstream && !closed) Native.setMetered(instance, isMetered(capabilities))
|
||||
}
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
|
||||
if (network == upstream && !closed) updateAddresses(properties)
|
||||
}
|
||||
@@ -47,11 +53,15 @@ class MeshVpn : VpnService() {
|
||||
// Falling back to the default network here could send iroh into its own TUN.
|
||||
setUnderlyingNetworks(emptyArray())
|
||||
physicalAddresses = ""
|
||||
Native.setMetered(instance, true)
|
||||
Native.networkChanged(instance, "")
|
||||
}
|
||||
}
|
||||
|
||||
private var physicalAddresses = ""
|
||||
// Query the network the agent actually uses, even while its VPN is the app default.
|
||||
private fun isMetered(capabilities: NetworkCapabilities?) =
|
||||
capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) != true
|
||||
private fun addresses(properties: LinkProperties?) = properties?.linkAddresses.orEmpty()
|
||||
.mapNotNull { it.address.hostAddress?.substringBefore('%') }.distinct().take(32).joinToString(",")
|
||||
private fun updateAddresses(properties: LinkProperties) {
|
||||
@@ -66,26 +76,34 @@ class MeshVpn : VpnService() {
|
||||
upstream = network
|
||||
setUnderlyingNetworks(arrayOf(network))
|
||||
physicalAddresses = addresses(connectivity.getLinkProperties(network))
|
||||
val metered = isMetered(connectivity.getNetworkCapabilities(network))
|
||||
if (instance == 0L) {
|
||||
Native.trust(applicationContext)
|
||||
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses)
|
||||
} else Native.networkChanged(instance, physicalAddresses)
|
||||
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses, metered)
|
||||
} else {
|
||||
Native.setMetered(instance, metered)
|
||||
Native.networkChanged(instance, physicalAddresses)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY }
|
||||
RESTORE_EXIT -> {
|
||||
restore = ExitTile.last(this)
|
||||
restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null }
|
||||
}
|
||||
DISCONNECT_EXIT -> {
|
||||
val ids = intent.data?.pathSegments.orEmpty()
|
||||
if (watching && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
|
||||
if (started && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
|
||||
if (!Native.disconnectExit(instance, ids[0], ids[1])) {
|
||||
android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
} else if (!watching) stopSelf(startId)
|
||||
} else if (!started) stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
if (watching) {
|
||||
if (started) {
|
||||
if (Native.failed(instance)) {
|
||||
Native.stop(instance)
|
||||
instance = 0
|
||||
@@ -93,12 +111,13 @@ class MeshVpn : VpnService() {
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
notifications.createNotificationChannel(NotificationChannel("vpn", "VPN", NotificationManager.IMPORTANCE_LOW))
|
||||
closed = false
|
||||
notifications.createNotificationChannel(NotificationChannel("vpn", "Tsunagi Agent", NotificationManager.IMPORTANCE_LOW))
|
||||
notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW))
|
||||
val startup = notification("vpn").setContentTitle("Starting mesh VPN")
|
||||
val startup = notification("vpn").setContentTitle("Starting Tsunagi Agent")
|
||||
if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
|
||||
startForeground(NOTIFICATION_ID, startup.build())
|
||||
watching = true
|
||||
started = true
|
||||
connectivity.requestNetwork(NetworkRequest.Builder()
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper()))
|
||||
@@ -116,9 +135,12 @@ class MeshVpn : VpnService() {
|
||||
// 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) {
|
||||
fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String, name: String, online: Boolean) {
|
||||
main.post {
|
||||
if (closed || session != instance) return@post
|
||||
val selected = if (peer.isEmpty()) null else ExitTile.Target(network, peer, name)
|
||||
ExitTile.publish(this, session, selected, online)
|
||||
restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null }
|
||||
if (peer.isEmpty()) {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
return@post
|
||||
@@ -189,8 +211,14 @@ class MeshVpn : VpnService() {
|
||||
@Synchronized private fun shutdown() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
if (watching) connectivity.unregisterNetworkCallback(changes)
|
||||
restore = null
|
||||
ExitTile.reset(this)
|
||||
if (started) connectivity.unregisterNetworkCallback(changes)
|
||||
started = false
|
||||
if (instance != 0L) Native.stop(instance)
|
||||
instance = 0L
|
||||
upstream = null
|
||||
physicalAddresses = ""
|
||||
connectivity.bindProcessToNetwork(null)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
}
|
||||
|
||||
@@ -6,14 +6,17 @@ import android.content.Context
|
||||
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 start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String, metered: Boolean): Long
|
||||
external fun failed(instance: Long): Boolean
|
||||
external fun stop(instance: Long)
|
||||
external fun disconnectExit(instance: Long, network: String, peer: String): Boolean
|
||||
external fun tileExit(instance: Long, network: String, peer: String, connect: Boolean, waitForDiscovery: Boolean): String?
|
||||
external fun networkChanged(instance: Long, addresses: String)
|
||||
external fun setMetered(instance: Long, metered: Boolean)
|
||||
|
||||
external fun surface()
|
||||
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long
|
||||
external fun surface(cacheDir: String)
|
||||
external fun pauseTraffic()
|
||||
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean, landscape: Boolean): Long
|
||||
external fun touch(action: Int, id: Int, x: Float, y: Float)
|
||||
external fun input(kind: Int, value: String)
|
||||
external fun key(key: Int)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:strokeColor="#ffffff" android:strokeWidth="2"
|
||||
android:strokeLineCap="round" android:strokeLineJoin="round"
|
||||
android:pathData="M12,3H4v18h8 M9,12h12 M17,8l4,4l-4,4" />
|
||||
</vector>
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
description = "Android VPN client and egui views for tsunagi."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.2" }
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.8" }
|
||||
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||
|
||||
@@ -7,7 +7,7 @@ use egui_glow::{Painter, glow};
|
||||
use jni::{
|
||||
JNIEnv,
|
||||
objects::{JObject, JString, JValue},
|
||||
sys::{jfloat, jint, jlong},
|
||||
sys::{jboolean, jfloat, jint, jlong},
|
||||
};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
@@ -38,7 +38,15 @@ fn with_display<T: Default>(f: impl FnOnce(&mut Display) -> T) -> T {
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) {
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_pauseTraffic(_: JNIEnv, _: JObject) {
|
||||
with_display(|d| d.ui.pause_monitor());
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
cache: JString,
|
||||
) {
|
||||
// SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current.
|
||||
let gl = unsafe {
|
||||
glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr()))
|
||||
@@ -52,9 +60,22 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
crate::view::configure(&ctx);
|
||||
let cache = env.get_string(&cache).ok().map(String::from);
|
||||
DISPLAY.with_borrow_mut(|d| {
|
||||
// If Android discarded the old EGL context, its GPU resources are already gone.
|
||||
let ui = d.take().map(|old| old.ui).unwrap_or_default();
|
||||
let mut ui = d
|
||||
.take()
|
||||
.map(|old| {
|
||||
// A rotation can recreate EGL. Keep expanded peers and scroll positions
|
||||
// while the new context uploads its own font atlas.
|
||||
let data = old.ctx.data_mut(std::mem::take);
|
||||
ctx.data_mut(|current| *current = data);
|
||||
old.ui
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(cache) = cache {
|
||||
ui.set_cache_dir(cache.into());
|
||||
}
|
||||
*d = Some(Display {
|
||||
painter,
|
||||
ctx,
|
||||
@@ -75,8 +96,11 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||
w: jint,
|
||||
h: jint,
|
||||
scale: jfloat,
|
||||
service_started: jboolean,
|
||||
landscape: jboolean,
|
||||
) -> jlong {
|
||||
with_display(|d| {
|
||||
tsunagi_ui::widgets::set_landscape(&d.ctx, landscape != 0);
|
||||
let size = egui::vec2(w as f32, h as f32) / scale;
|
||||
let mut input = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
|
||||
@@ -88,19 +112,23 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||
info.native_pixels_per_point = Some(scale);
|
||||
}
|
||||
let mut action = None;
|
||||
let state = super::status();
|
||||
let state = match super::status() {
|
||||
crate::service::State::Off if service_started != 0 => crate::service::State::Starting,
|
||||
state => state,
|
||||
};
|
||||
let exit_active = matches!(&state, crate::service::State::Ready(report, _) if report.networks.iter().any(|n| n.active && n.exit.via.is_some()));
|
||||
if exit_active && !d.exit_active {
|
||||
let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]);
|
||||
}
|
||||
d.exit_active = exit_active;
|
||||
let output = d.ctx.run(input, |ctx| {
|
||||
action = d.ui.draw(ctx, &state, super::send);
|
||||
action = d.ui.draw(ctx, &state, super::send).or(action);
|
||||
});
|
||||
d.ui.poll_monitor(|| super::submit(crate::service::Request::WatchTraffic));
|
||||
if let Some(action) = action {
|
||||
let method = match action {
|
||||
SystemAction::Start => "startVpn",
|
||||
SystemAction::Stop => "stopVpn",
|
||||
SystemAction::Start => "startAgent",
|
||||
SystemAction::Stop => "stopAgent",
|
||||
SystemAction::PasteSecret => "pasteSecret",
|
||||
SystemAction::Finish => "closeScreen",
|
||||
};
|
||||
@@ -227,6 +255,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_input(
|
||||
}
|
||||
4 => d.ui.paste_secret(text),
|
||||
5 => d.ui.error(text),
|
||||
6 => d.ui.request_exit_picker(),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ mod display;
|
||||
mod dns;
|
||||
use crate::{
|
||||
plan::VpnPlan,
|
||||
service::{Reply, Request, Response, State},
|
||||
service::{Reply, Request, Response, ServiceSignals, State},
|
||||
tun::AndroidTun,
|
||||
};
|
||||
use jni::{
|
||||
@@ -25,10 +25,11 @@ use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin};
|
||||
|
||||
struct Session {
|
||||
id: i64,
|
||||
last_refresh: Option<std::time::Instant>,
|
||||
commands: mpsc::Sender<(Request, Reply)>,
|
||||
state: watch::Receiver<State>,
|
||||
underlay: watch::Sender<Vec<std::net::IpAddr>>,
|
||||
stop: watch::Sender<bool>,
|
||||
signals: watch::Sender<ServiceSignals>,
|
||||
}
|
||||
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||
// Stop/start can cross on the Android main thread. The previous agent closes
|
||||
@@ -39,19 +40,38 @@ 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()
|
||||
let mut current = current();
|
||||
let Some(session) = current.as_mut() else {
|
||||
return State::Off;
|
||||
};
|
||||
let state = session.state.borrow().clone();
|
||||
let report = match &state {
|
||||
State::Ready(report, _) => Some(report.as_ref()),
|
||||
_ => None,
|
||||
};
|
||||
if session
|
||||
.last_refresh
|
||||
.is_none_or(|last| last.elapsed() >= tsunagi_ui::client::status_poll_interval(report))
|
||||
&& session
|
||||
.commands
|
||||
.try_send((Request::Refresh, oneshot::channel().0))
|
||||
.is_ok()
|
||||
{
|
||||
session.last_refresh = Some(std::time::Instant::now());
|
||||
}
|
||||
state
|
||||
}
|
||||
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||
submit(Request::Action(cmd))
|
||||
}
|
||||
fn submit(request: Request) -> Result<Response, String> {
|
||||
let (reply, result) = oneshot::channel();
|
||||
current()
|
||||
.as_ref()
|
||||
.ok_or("VPN service stopped")?
|
||||
.ok_or("Tsunagi Agent stopped")?
|
||||
.commands
|
||||
.try_send((Request::Action(cmd), reply))
|
||||
.map_err(|_| "VPN service is busy or stopped".to_owned())?;
|
||||
.try_send((request, reply))
|
||||
.map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -119,6 +139,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
state_dir: JString,
|
||||
cache_dir: JString,
|
||||
addresses: JString,
|
||||
metered: jni::sys::jboolean,
|
||||
) -> jlong {
|
||||
let result = (|| -> Result<i64, Box<dyn std::error::Error>> {
|
||||
// Keep the application (never an activity) alive for DNS throughout the process.
|
||||
@@ -176,18 +197,21 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
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);
|
||||
let (signals, updates) = watch::channel(ServiceSignals {
|
||||
stopped: false,
|
||||
metered: metered != 0,
|
||||
});
|
||||
static NEXT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
|
||||
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut slot = current();
|
||||
if let Some(old) = slot.as_ref() {
|
||||
old.stop.send_replace(true);
|
||||
old.signals.send_modify(|s| s.stopped = true);
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name("tsunagi-agent".into())
|
||||
.spawn(move || {
|
||||
let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if *stopped.borrow() {
|
||||
if updates.borrow().stopped {
|
||||
return;
|
||||
}
|
||||
let run = || -> Result<(), Box<dyn std::error::Error>> {
|
||||
@@ -214,7 +238,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
.await?;
|
||||
let agent = Agent::spawn(config).await?;
|
||||
let _listeners = carriers.listen(&agent);
|
||||
crate::service::serve(agent, wg, dns, rx, &state, stopped, |notice| {
|
||||
crate::service::serve(agent, wg, dns, rx, &state, updates, |notice| {
|
||||
update_exit_notification(¬ice_vm, ¬ice_service, id, notice);
|
||||
})
|
||||
.await;
|
||||
@@ -227,10 +251,11 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
})?;
|
||||
*slot = Some(Session {
|
||||
id,
|
||||
last_refresh: None,
|
||||
commands,
|
||||
state: state_rx,
|
||||
underlay,
|
||||
stop,
|
||||
signals,
|
||||
});
|
||||
Ok(id)
|
||||
})();
|
||||
@@ -252,9 +277,10 @@ fn update_exit_notification(
|
||||
let Ok(mut env) = vm.attach_current_thread() else {
|
||||
return;
|
||||
};
|
||||
let _ = env.with_local_frame(6, |env| -> jni::errors::Result<()> {
|
||||
let _ = env.with_local_frame(8, |env| -> jni::errors::Result<()> {
|
||||
let network = env.new_string(notice.map_or("", |n| &n.network))?;
|
||||
let peer = env.new_string(notice.map_or("", |n| &n.peer))?;
|
||||
let name = env.new_string(notice.map_or("", |n| &n.name))?;
|
||||
let title = env.new_string(
|
||||
notice
|
||||
.map(|n| format!("Exit node · {}", n.name))
|
||||
@@ -277,13 +303,15 @@ fn update_exit_notification(
|
||||
env.call_method(
|
||||
service,
|
||||
"updateExitNotification",
|
||||
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V",
|
||||
&[
|
||||
JValue::Long(id),
|
||||
JValue::Object(&network),
|
||||
JValue::Object(&peer),
|
||||
JValue::Object(&title),
|
||||
JValue::Object(&text),
|
||||
JValue::Object(&name),
|
||||
JValue::Bool(notice.is_some_and(|n| n.online).into()),
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
@@ -321,6 +349,53 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_disconnectExit(
|
||||
.into()
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_tileExit(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
id: jlong,
|
||||
network: JString,
|
||||
peer: JString,
|
||||
connect: jni::sys::jboolean,
|
||||
wait_for_discovery: jni::sys::jboolean,
|
||||
) -> jni::sys::jstring {
|
||||
// Called on the tile's background worker. Never hold the session lock while awaiting the agent.
|
||||
let mut run = || -> Result<(), String> {
|
||||
let network: String = env.get_string(&network).map_err(|e| e.to_string())?.into();
|
||||
let peer: String = env.get_string(&peer).map_err(|e| e.to_string())?.into();
|
||||
let (commands, mut state) = current()
|
||||
.as_ref()
|
||||
.filter(|s| s.id == id)
|
||||
.map(|s| (s.commands.clone(), s.state.clone()))
|
||||
.ok_or("Tsunagi Agent stopped")?;
|
||||
if connect != 0 && wait_for_discovery != 0 {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?
|
||||
.block_on(crate::service::wait_for_exit_offer(
|
||||
&mut state, &network, &peer,
|
||||
))?;
|
||||
}
|
||||
let request = if connect != 0 {
|
||||
Request::RestoreExit { network, peer }
|
||||
} else {
|
||||
Request::DisconnectExit { network, peer }
|
||||
};
|
||||
let (reply, result) = oneshot::channel();
|
||||
commands
|
||||
.try_send((request, reply))
|
||||
.map_err(|_| "Tsunagi Agent is busy or stopped")?;
|
||||
result
|
||||
.blocking_recv()
|
||||
.map_err(|_| "Tsunagi Agent stopped")??;
|
||||
Ok(())
|
||||
};
|
||||
run()
|
||||
.err()
|
||||
.and_then(|e| env.new_string(e).ok())
|
||||
.map_or(std::ptr::null_mut(), JString::into_raw)
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_failed(
|
||||
_: JNIEnv,
|
||||
_: JObject,
|
||||
@@ -337,7 +412,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_stop(_: JNIEnv, _: JObject, id:
|
||||
if slot.as_ref().is_some_and(|s| s.id == id)
|
||||
&& let Some(session) = slot.take()
|
||||
{
|
||||
session.stop.send_replace(true);
|
||||
session.signals.send_modify(|s| s.stopped = true);
|
||||
}
|
||||
}
|
||||
fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
|
||||
@@ -348,6 +423,21 @@ fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
|
||||
.collect()
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_setMetered(
|
||||
_: JNIEnv,
|
||||
_: JObject,
|
||||
id: jlong,
|
||||
metered: jni::sys::jboolean,
|
||||
) {
|
||||
if let Some(s) = current().as_ref().filter(|s| s.id == id) {
|
||||
s.signals.send_if_modified(|signals| {
|
||||
let changed = signals.metered != (metered != 0);
|
||||
signals.metered = metered != 0;
|
||||
changed
|
||||
});
|
||||
}
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_networkChanged(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
|
||||
@@ -46,11 +46,7 @@ impl Resolver {
|
||||
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,
|
||||
@@ -58,6 +54,17 @@ impl Resolver {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_listener(
|
||||
&self,
|
||||
mut report: tsunagi::ipc::DnsReport,
|
||||
) -> tsunagi::ipc::DnsReport {
|
||||
let address = *self.listening.borrow();
|
||||
report.listening = address.map(|ip| format!("{ip}:53")).into_iter().collect();
|
||||
report.publish_error = (address.is_none() && !report.zones.is_empty())
|
||||
.then(|| "Waiting for a VPN interface with a DNS address.".into());
|
||||
report
|
||||
}
|
||||
|
||||
/// Answer a local DNS request. Slow public lookups never block a mesh answer.
|
||||
pub async fn answer(&self, query: &[u8]) -> Option<Vec<u8>> {
|
||||
if query.len() > MAX_MESSAGE_LEN {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The Android application. Mesh state belongs to one service-owned Rust agent.
|
||||
|
||||
pub mod dns;
|
||||
mod monitor;
|
||||
pub mod plan;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The GL thread holds a service subscription only while the inspector is visible.
|
||||
use crate::service::{Outcome, Response};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::oneshot::error::TryRecvError;
|
||||
use tsunagi::traffic::TrafficSubscription;
|
||||
use tsunagi_ui::monitor::Window;
|
||||
|
||||
pub(super) struct Monitor {
|
||||
pub view: Window,
|
||||
pending: Option<Response>,
|
||||
subscription: Option<TrafficSubscription>,
|
||||
next: Instant,
|
||||
failed: bool,
|
||||
}
|
||||
impl Monitor {
|
||||
pub fn new(cache: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
view: Window::new(cache),
|
||||
pending: None,
|
||||
subscription: None,
|
||||
next: Instant::now(),
|
||||
failed: false,
|
||||
}
|
||||
}
|
||||
pub fn pause(&mut self) {
|
||||
self.pending = None;
|
||||
self.subscription = None;
|
||||
}
|
||||
pub fn poll(&mut self, open: impl FnOnce() -> Result<Response, String>) {
|
||||
if self.failed {
|
||||
return;
|
||||
}
|
||||
if let Some(sub) = &self.subscription {
|
||||
if Instant::now() >= self.next {
|
||||
self.next = Instant::now() + Duration::from_secs(1);
|
||||
if !self.view.feed().sample(sub.snapshot()) {
|
||||
self.pause();
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let result = match &mut self.pending {
|
||||
Some(rx) => match rx.try_recv() {
|
||||
Ok(Ok(Outcome::Traffic(sub))) => {
|
||||
// Time spent in the background must expire old rows before new traffic can refresh them.
|
||||
self.view.feed().sample(Default::default());
|
||||
self.subscription = Some(sub);
|
||||
self.next = Instant::now() + Duration::from_secs(1);
|
||||
self.pending = None;
|
||||
return;
|
||||
}
|
||||
Ok(Err(e)) => Err(e),
|
||||
Err(TryRecvError::Empty) => return,
|
||||
_ => Err("Tsunagi Agent stopped".into()),
|
||||
},
|
||||
None => open().map(|r| self.pending = Some(r)),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
self.pending = None;
|
||||
self.failed = true;
|
||||
self.view.feed().error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ use std::{sync::Arc, time::Instant};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tsunagi::{
|
||||
Agent, NetworkName, NetworkSecret,
|
||||
ipc::{PrivilegeReport, ProtocolReport, StatusReport},
|
||||
ipc::{DnsReport, PrivilegeReport, ProtocolReport, StatusReport},
|
||||
vip::VipStatus,
|
||||
};
|
||||
use tsunagi_ui::client::Command;
|
||||
@@ -12,8 +12,12 @@ use zeroize::Zeroizing;
|
||||
|
||||
/// A platform notification or user gesture.
|
||||
pub enum Request {
|
||||
/// A visible monitor requested its own fresh observation interval.
|
||||
WatchTraffic,
|
||||
/// A command from the same form used by the tray.
|
||||
Action(Command),
|
||||
/// The visible activity requested current counters.
|
||||
Refresh,
|
||||
/// The physical network changed.
|
||||
NetworkChanged,
|
||||
/// Disable only the exit identified by the notification the user tapped.
|
||||
@@ -23,6 +27,22 @@ pub enum Request {
|
||||
/// Endpoint id captured at the same time.
|
||||
peer: String,
|
||||
},
|
||||
/// Restore a remembered network/peer pair only while no other exit is selected.
|
||||
RestoreExit {
|
||||
/// Network saved at the last successful selection.
|
||||
network: String,
|
||||
/// Peer used in that network.
|
||||
peer: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// The latest service lifecycle and cost of the physical network Android selected.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct ServiceSignals {
|
||||
/// End this instance.
|
||||
pub stopped: bool,
|
||||
/// Android reports that data on the current underlay may be billed.
|
||||
pub metered: bool,
|
||||
}
|
||||
|
||||
/// A configured default route stays visible if its remote peer goes offline.
|
||||
@@ -70,8 +90,70 @@ pub async fn disconnect_exit(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn restore_exit(agent: &Agent, network: &str, peer: &str) -> Result<Outcome, String> {
|
||||
let network = network.parse().map_err(|_| "Invalid saved network ID")?;
|
||||
let peer = peer.parse().map_err(|_| "Invalid saved peer ID")?;
|
||||
let status = agent.status().await.map_err(|e| e.to_string())?;
|
||||
for n in &status.networks {
|
||||
if n.state == tsunagi::agent::NetworkState::Active
|
||||
&& let Some(current) = n.exit_via
|
||||
{
|
||||
return if n.network_id == network && current == peer {
|
||||
Ok(Outcome::Applied)
|
||||
} else {
|
||||
Err("Another exit is already selected".into())
|
||||
};
|
||||
}
|
||||
}
|
||||
agent
|
||||
.set_exit_via(network, Some(peer))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Outcome::Applied)
|
||||
}
|
||||
|
||||
// On cold start the first snapshot often precedes peer discovery. Wait on the
|
||||
// service's roster notifications, outside the command loop, then let the usual
|
||||
// serialized command validate the selection again before touching the route.
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
pub(crate) async fn wait_for_exit_offer(
|
||||
state: &mut watch::Receiver<State>,
|
||||
network: &str,
|
||||
peer: &str,
|
||||
) -> Result<(), String> {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||
loop {
|
||||
match &*state.borrow_and_update() {
|
||||
State::Ready(report, _) => {
|
||||
let n = report
|
||||
.networks
|
||||
.iter()
|
||||
.find(|n| n.network_id == network && n.active)
|
||||
.ok_or("The saved exit network is no longer active")?;
|
||||
if report
|
||||
.networks
|
||||
.iter()
|
||||
.any(|n| n.active && n.exit.via.is_some())
|
||||
|| n.peers.iter().any(|p| p.endpoint_id == peer && p.exit_node)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
State::Off => return Err("Tsunagi Agent stopped".into()),
|
||||
State::Error(error) => return Err(error.clone()),
|
||||
State::Starting => {}
|
||||
}
|
||||
state.changed().await.map_err(|_| "Tsunagi Agent stopped")?;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "The saved peer is offline or no longer offers an exit")?
|
||||
}
|
||||
|
||||
/// Private reply delivered only to the UI that requested the action.
|
||||
pub enum Outcome {
|
||||
/// Owned by one traffic screen and dropped when capture stops.
|
||||
Traffic(tsunagi::traffic::TrafficSubscription),
|
||||
/// The agent has applied the action.
|
||||
Applied,
|
||||
/// Revisions returned by a successful signed write.
|
||||
@@ -89,6 +171,14 @@ pub type Response = tokio::sync::oneshot::Receiver<Result<Outcome, String>>;
|
||||
pub async fn apply(
|
||||
command: Command,
|
||||
agent: &Agent,
|
||||
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
|
||||
apply_on_link(command, agent, false).await
|
||||
}
|
||||
|
||||
async fn apply_on_link(
|
||||
command: Command,
|
||||
agent: &Agent,
|
||||
metered: bool,
|
||||
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
|
||||
match command {
|
||||
Command::Join { name, secret } => {
|
||||
@@ -132,6 +222,16 @@ pub async fn apply(
|
||||
.set_exit_via(network_id.parse()?, peer.map(|p| p.parse()).transpose()?)
|
||||
.await?
|
||||
}
|
||||
Command::StartSpeedTest { network_id, peer } => {
|
||||
agent
|
||||
.start_speed_test(
|
||||
network_id.parse()?,
|
||||
peer.map(|p| p.parse()).transpose()?,
|
||||
metered,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Command::StopSpeedTest { network_id } => agent.stop_speed_test(network_id.parse()?),
|
||||
Command::SetExitOffer { .. } => {
|
||||
return Err("This phone can only use a remote exit node.".into());
|
||||
}
|
||||
@@ -176,13 +276,22 @@ pub async fn report(
|
||||
agent: &Agent,
|
||||
wg: Option<&WireguardPlugin>,
|
||||
dns: &crate::dns::Resolver,
|
||||
) -> tsunagi::Result<StatusReport> {
|
||||
snapshot(agent, wg, dns, None).await
|
||||
}
|
||||
|
||||
async fn snapshot(
|
||||
agent: &Agent,
|
||||
wg: Option<&WireguardPlugin>,
|
||||
dns: &crate::dns::Resolver,
|
||||
cached_zones: Option<DnsReport>,
|
||||
) -> tsunagi::Result<StatusReport> {
|
||||
let status = agent.status().await?;
|
||||
let overlay = agent.overlay();
|
||||
Ok(StatusReport {
|
||||
networks: tsunagi_runtime::report::networks(&status, overlay.as_ref(), wg),
|
||||
overlay_config_error: overlay.and_then(|state| state.address_error),
|
||||
dns: Some(dns.refresh(&status.networks)),
|
||||
dns: Some(dns.with_listener(cached_zones.unwrap_or_else(|| dns.refresh(&status.networks)))),
|
||||
endpoint_id: status.endpoint_id.to_string(),
|
||||
hostname: status.hostname,
|
||||
bound_sockets: status
|
||||
@@ -215,24 +324,42 @@ pub async fn serve(
|
||||
dns: crate::dns::Resolver,
|
||||
mut commands: mpsc::Receiver<(Request, Reply)>,
|
||||
state: &watch::Sender<State>,
|
||||
mut stop: watch::Receiver<bool>,
|
||||
mut signals: watch::Receiver<ServiceSignals>,
|
||||
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 roster = agent.watch_roster();
|
||||
roster.mark_changed(); // Load the initial zones before waiting for any actions.
|
||||
let mut cached_zones = None;
|
||||
let mut retry = false;
|
||||
let mut published_exit = None;
|
||||
let mut link = *signals.borrow_and_update();
|
||||
agent.set_speed_test_metered(link.metered);
|
||||
loop {
|
||||
let reply = tokio::select! {
|
||||
if link.stopped {
|
||||
break;
|
||||
}
|
||||
let (reply, mut refresh_zones) = tokio::select! {
|
||||
biased;
|
||||
_ = stop.wait_for(|stopped| *stopped) => break,
|
||||
changed = signals.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
link = *signals.borrow_and_update();
|
||||
agent.set_speed_test_metered(link.metered);
|
||||
continue;
|
||||
}
|
||||
command = commands.recv() => {
|
||||
let Some((request, reply)) = command else { break };
|
||||
let refresh_zones = !matches!(request, Request::Refresh);
|
||||
let result = match request {
|
||||
Request::WatchTraffic => {
|
||||
let _ = reply.send(agent.subscribe_traffic().map(Outcome::Traffic));
|
||||
continue;
|
||||
}
|
||||
Request::Refresh => Ok(Outcome::Applied),
|
||||
Request::Action(cmd) => {
|
||||
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||
dns.replace(None);
|
||||
}
|
||||
apply(cmd, &agent).await.map_err(|e| e.to_string())
|
||||
apply_on_link(cmd, &agent, link.metered).await.map_err(|e| e.to_string())
|
||||
}
|
||||
Request::NetworkChanged => {
|
||||
agent.endpoint().network_change().await;
|
||||
@@ -241,22 +368,41 @@ pub async fn serve(
|
||||
}
|
||||
Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await
|
||||
.map(|()| Outcome::Applied).map_err(|e| e.to_string()),
|
||||
Request::RestoreExit {network, peer} => restore_exit(&agent, &network, &peer).await,
|
||||
};
|
||||
Some((reply, result))
|
||||
(Some((reply, result)), refresh_zones)
|
||||
}
|
||||
_ = poll.tick() => None,
|
||||
changed = roster.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
(None, true)
|
||||
}
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(2)), if retry => (None, true),
|
||||
};
|
||||
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);
|
||||
// A command may itself have changed the roster. Consume notifications
|
||||
// before taking the snapshot so changes during the read stay pending.
|
||||
refresh_zones |= roster.has_changed().unwrap_or(false);
|
||||
if refresh_zones {
|
||||
roster.borrow_and_update();
|
||||
cached_zones = None;
|
||||
}
|
||||
state.send_replace(
|
||||
match snapshot(&agent, Some(&wg), &dns, cached_zones.take()).await {
|
||||
Ok(report) => {
|
||||
retry = false;
|
||||
cached_zones.clone_from(&report.dns);
|
||||
let notice = exit_notice(&report);
|
||||
if published_exit.as_ref() != Some(¬ice) {
|
||||
publish_exit(notice.as_ref());
|
||||
published_exit = Some(notice);
|
||||
}
|
||||
State::Ready(Arc::new(report), Instant::now())
|
||||
}
|
||||
State::Ready(Arc::new(report), Instant::now())
|
||||
}
|
||||
Err(error) => State::Error(error.to_string()),
|
||||
});
|
||||
Err(error) => {
|
||||
retry = true;
|
||||
State::Error(error.to_string())
|
||||
}
|
||||
},
|
||||
);
|
||||
if let Some((reply, outcome)) = reply {
|
||||
let _ = reply.send(outcome);
|
||||
}
|
||||
|
||||
@@ -8,9 +8,101 @@ fn addr(octet: u8) -> Cidr {
|
||||
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, octet, 42, 19)), 24).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand() {
|
||||
use crate::service::{Request, State, serve};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tsunagi::{
|
||||
discovery::SharedMemoryDiscovery,
|
||||
testing::{TestAgent, network},
|
||||
};
|
||||
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let phone = TestAgent::spawn(&discovery).await.unwrap();
|
||||
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
|
||||
.await
|
||||
.unwrap();
|
||||
let (state, mut snapshots) = watch::channel(State::Starting);
|
||||
let (stop, stopped) = watch::channel(crate::service::ServiceSignals::default());
|
||||
let (commands, requests) = mpsc::channel(4);
|
||||
let agent = phone.agent.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
serve(
|
||||
agent,
|
||||
wg,
|
||||
crate::dns::Resolver::new(|_| None),
|
||||
requests,
|
||||
&state,
|
||||
stopped,
|
||||
|_| {},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(5), snapshots.changed())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matches!(*snapshots.borrow_and_update(), State::Ready(..)));
|
||||
// Occupy the other reader slots so this test observes the real service subscription
|
||||
// being acquired on screen open and released on both background and close.
|
||||
let other_windows: Vec<_> = (0..3)
|
||||
.map(|_| phone.agent.subscribe_traffic().unwrap())
|
||||
.collect();
|
||||
let mut monitor = crate::monitor::Monitor::new(None);
|
||||
for _ in 0..2 {
|
||||
monitor.poll(|| {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
commands.try_send((Request::WatchTraffic, tx)).unwrap();
|
||||
Ok(rx)
|
||||
});
|
||||
tsunagi::testing::wait_until("the visible Android monitor subscribed", || async {
|
||||
phone.agent.subscribe_traffic().is_err().then_some(())
|
||||
})
|
||||
.await;
|
||||
monitor.poll(|| panic!("a visible monitor must reuse its subscription"));
|
||||
monitor.pause();
|
||||
assert!(phone.agent.subscribe_traffic().is_ok());
|
||||
}
|
||||
drop((monitor, other_windows));
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(2200), snapshots.changed())
|
||||
.await
|
||||
.is_err(),
|
||||
"a hidden, idle service rebuilt the status"
|
||||
);
|
||||
let (tx, rx) = oneshot::channel();
|
||||
commands.send((Request::Refresh, tx)).await.unwrap();
|
||||
rx.await.unwrap().unwrap();
|
||||
assert!(snapshots.has_changed().unwrap());
|
||||
let (name, secret) = network("background-mesh");
|
||||
phone.agent.join_network(&name, &secret).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), snapshots.wait_for(|s| {
|
||||
matches!(s, State::Ready(r, _) if r.dns.as_ref().is_some_and(|d| d.zones.iter().any(|z| z == "background-mesh")))
|
||||
})).await.unwrap().unwrap();
|
||||
stop.send_modify(|s| s.stopped = true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() {
|
||||
use crate::service::{disconnect_exit, exit_notice, report};
|
||||
use crate::service::{ExitNotice, Request, State, disconnect_exit, serve, wait_for_exit_offer};
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||
async fn notice_matching(
|
||||
notices: &mut watch::Receiver<Option<ExitNotice>>,
|
||||
predicate: impl Fn(&Option<ExitNotice>) -> bool,
|
||||
) -> Option<ExitNotice> {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
notices.wait_for(predicate),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.clone()
|
||||
}
|
||||
use tsunagi::{
|
||||
discovery::SharedMemoryDiscovery,
|
||||
testing::{TestAgent, network, wait_until},
|
||||
@@ -43,13 +135,95 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
|
||||
.then_some(())
|
||||
})
|
||||
.await;
|
||||
let dns = crate::dns::Resolver::new(|_| None);
|
||||
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
|
||||
.await
|
||||
.unwrap();
|
||||
let agent = phone.agent.clone();
|
||||
let (commands, requests) = mpsc::channel(4);
|
||||
let (stop, stopped) = watch::channel(crate::service::ServiceSignals::default());
|
||||
let (published, mut notices) = watch::channel(None);
|
||||
let (state, mut live) = watch::channel(State::Starting);
|
||||
let task = tokio::spawn(async move {
|
||||
serve(
|
||||
agent,
|
||||
wg,
|
||||
crate::dns::Resolver::new(|_| None),
|
||||
requests,
|
||||
&state,
|
||||
stopped,
|
||||
|notice| {
|
||||
published.send_replace(notice.cloned());
|
||||
},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
phone.agent.set_exit_via(id, Some(peer)).await.unwrap();
|
||||
let notice = exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).unwrap();
|
||||
let notice = notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(notice.name, "gateway");
|
||||
assert_eq!(notice.network_name, "travel");
|
||||
assert!(notice.online);
|
||||
let restore = |peer: String| {
|
||||
let commands = commands.clone();
|
||||
let network = notice.network.clone();
|
||||
async move {
|
||||
let (reply, result) = oneshot::channel();
|
||||
commands
|
||||
.send((Request::RestoreExit { network, peer }, reply))
|
||||
.await
|
||||
.unwrap();
|
||||
result.await.unwrap()
|
||||
}
|
||||
};
|
||||
disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer)
|
||||
.await
|
||||
.unwrap();
|
||||
notice_matching(&mut notices, Option::is_none).await;
|
||||
assert!(
|
||||
restore(phone.agent.endpoint_id().to_string())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
phone
|
||||
.agent
|
||||
.network_status(id)
|
||||
.await
|
||||
.unwrap()
|
||||
.exit_via
|
||||
.is_none()
|
||||
);
|
||||
// A cold service can publish its first status before the gateway advertises.
|
||||
// Keep the command loop available while waiting for this exact peer.
|
||||
exit.agent.set_exit_offer(id, false).await.unwrap();
|
||||
drop(
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
live.wait_for(|s| {
|
||||
matches!(s, State::Ready(report, _) if
|
||||
report.networks[0].peers.iter().any(|p| p.endpoint_id == notice.peer && !p.exit_node))
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
);
|
||||
let waiting = wait_for_exit_offer(&mut live, ¬ice.network, ¬ice.peer);
|
||||
tokio::pin!(waiting);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = &mut waiting => panic!("restored before the peer offered an exit"),
|
||||
result = exit.agent.set_exit_offer(id, true) => result.unwrap(),
|
||||
}
|
||||
waiting.await.unwrap();
|
||||
assert!(restore(notice.peer.clone()).await.is_ok());
|
||||
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online)).await;
|
||||
assert!(
|
||||
restore(phone.agent.endpoint_id().to_string())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
disconnect_exit(
|
||||
&phone.agent,
|
||||
&id.to_string(),
|
||||
@@ -61,21 +235,20 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
|
||||
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)
|
||||
},
|
||||
)
|
||||
exit.agent.set_hostname("renamed-gateway").await.unwrap();
|
||||
notice_matching(&mut notices, |n| {
|
||||
n.as_ref().is_some_and(|n| n.name == "renamed-gateway")
|
||||
})
|
||||
.await;
|
||||
exit.stop().await;
|
||||
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| !n.online)).await;
|
||||
disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||
notice_matching(&mut notices, Option::is_none).await;
|
||||
assert!(phone.agent.is_active(id).await);
|
||||
phone.stop().await;
|
||||
stop.send_modify(|s| s.stopped = true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -480,7 +653,7 @@ async fn tun_reader_survives_address_changes_failed_establish_and_last_network_l
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() {
|
||||
async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded() {
|
||||
use crate::{
|
||||
service::{State, report},
|
||||
view::{Phone, configure},
|
||||
@@ -500,42 +673,157 @@ async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() {
|
||||
address: Some("10.1.2.3".into()),
|
||||
..Default::default()
|
||||
});
|
||||
let mut other = sample.networks[0].clone();
|
||||
other.network_id = "another-network".into();
|
||||
sample.networks.push(other);
|
||||
sample.networks[0].peers.push(tsunagi::ipc::PeerReport {
|
||||
endpoint_id: "exit-endpoint-id".into(),
|
||||
hostname: Some("gateway".into()),
|
||||
..Default::default()
|
||||
});
|
||||
sample.networks[0].exit = tsunagi::ipc::ExitReport {
|
||||
via: Some("exit-endpoint-id".into()),
|
||||
via_online: true,
|
||||
traffic: Some(tsunagi::overlay::exit::ExitTraffic {
|
||||
tx_bytes: 2048,
|
||||
rx_bytes: 512,
|
||||
}),
|
||||
client_rules: Some(tsunagi::ipc::RuleSetReport {
|
||||
ok: true,
|
||||
detail: String::new(),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let state = State::Ready(Arc::new(sample), Instant::now());
|
||||
let ctx = egui::Context::default();
|
||||
configure(&ctx);
|
||||
let mut phone = Phone::default();
|
||||
let 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| {
|
||||
let mut frame = |events| {
|
||||
ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(360., 720.),
|
||||
)),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
phone.draw(ctx, &state, |_| {
|
||||
panic!("drawing the overview issued a command")
|
||||
});
|
||||
},
|
||||
)
|
||||
};
|
||||
let positions = |frame: &egui::FullOutput, label: &str| {
|
||||
frame
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|shape| match &shape.shape {
|
||||
Shape::Text(text) if text.galley.text() == label => Some(text.pos.y),
|
||||
.filter_map(|shape| match &shape.shape {
|
||||
Shape::Text(text) if text.galley.text() == label => {
|
||||
Some(text.pos + text.galley.rect.center().to_vec2())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing label {label}"))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
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"))));
|
||||
frame(vec![]);
|
||||
let closed = frame(vec![]);
|
||||
let titles = positions(&closed, name.as_str());
|
||||
assert_eq!(titles.len(), 2);
|
||||
assert!(positions(&closed, "Show devices").is_empty());
|
||||
use egui_phosphor::regular::{ARROW_DOWN, ARROW_UP};
|
||||
let font = egui::TextStyle::Body.resolve(&ctx.style());
|
||||
for icon in [ARROW_UP, ARROW_DOWN] {
|
||||
assert!(ctx.fonts(|fonts| fonts.has_glyphs(&font, icon)));
|
||||
}
|
||||
for label in [
|
||||
"Exit via gateway".to_owned(),
|
||||
format!("{ARROW_UP} 2.0 kB"),
|
||||
format!("{ARROW_DOWN} 512 B"),
|
||||
] {
|
||||
assert_eq!(positions(&closed, &label).len(), 1, "missing {label}");
|
||||
}
|
||||
let mut click = |pos| {
|
||||
for pressed in [true, false] {
|
||||
frame(vec![
|
||||
egui::Event::PointerMoved(pos),
|
||||
egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
frame(vec![])
|
||||
};
|
||||
let opened = click(titles[0]);
|
||||
assert_eq!(positions(&opened, "Show devices").len(), 1);
|
||||
use egui_phosphor::regular as icon;
|
||||
let vip = format!("{} VIP", icon::NETWORK);
|
||||
let y = |label: &str| positions(&opened, label)[0].y;
|
||||
assert!((0.0..=26.0).contains(&(y(icon::DESKTOP_TOWER) - y(icon::FINGERPRINT))));
|
||||
assert!((0.0..=26.0).contains(&(y(icon::TREE_STRUCTURE) - y(icon::HASH))));
|
||||
assert!((0.0..=26.0).contains(&(y(icon::DEVICES) - y(icon::DEVICE_MOBILE))));
|
||||
assert!((y(&vip) - y("Show devices")).abs() < 2.0);
|
||||
assert!((y(&vip) - y(&format!("{} Copy secret", egui_phosphor::regular::COPY))).abs() < 2.0);
|
||||
let folded = click(positions(&opened, name.as_str())[0]);
|
||||
assert!(positions(&folded, "Show devices").is_empty());
|
||||
assert_eq!(positions(&folded, "Exit via gateway").len(), 1);
|
||||
agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
|
||||
fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_name() {
|
||||
use crate::{
|
||||
service::State,
|
||||
view::{Phone, configure},
|
||||
};
|
||||
use std::{sync::Arc, time::Instant};
|
||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||
let ctx = egui::Context::default();
|
||||
configure(&ctx);
|
||||
let mut phone = Phone::default();
|
||||
let draw = |phone: &mut Phone, state: &State| {
|
||||
let out = ctx.run(egui::RawInput::default(), |ctx| {
|
||||
phone.draw(ctx, state, |_| panic!("opening the tile selected a route"));
|
||||
});
|
||||
out.shapes
|
||||
.into_iter()
|
||||
.filter_map(|s| match s.shape {
|
||||
egui::Shape::Text(t) => Some(t.galley.text().to_owned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
phone.request_exit_picker();
|
||||
draw(&mut phone, &State::Starting);
|
||||
let networks =
|
||||
[("alpha", true), ("bravo", true), ("paused", false)].map(|(id, active)| NetworkReport {
|
||||
network_id: id.into(),
|
||||
name: "home".into(),
|
||||
active,
|
||||
..Default::default()
|
||||
});
|
||||
let state = State::Ready(
|
||||
Arc::new(StatusReport {
|
||||
networks: networks.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
Instant::now(),
|
||||
);
|
||||
draw(&mut phone, &state);
|
||||
let chooser = draw(&mut phone, &state);
|
||||
assert!(chooser.iter().any(|s| s == "home · alpha"));
|
||||
assert!(chooser.iter().any(|s| s == "home · bravo"));
|
||||
assert!(!chooser.iter().any(|s| s.contains("paused")));
|
||||
assert!(phone.back().is_none());
|
||||
assert!(draw(&mut phone, &state).iter().any(|s| s == "tsunagi"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotating_the_phone_keeps_the_selected_network_and_unsaved_vip_draft() {
|
||||
use crate::service::State;
|
||||
use crate::view::{Phone, configure};
|
||||
use egui::{Event, PointerButton, Pos2, RawInput, Rect, Shape};
|
||||
@@ -552,6 +840,7 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
|
||||
port: 8080,
|
||||
};
|
||||
let mut config = VipConfig::new("web");
|
||||
let name_field = egui::Id::new(("vip-name", &config.id));
|
||||
let mut listener = Listener::new(Protocol::Tcp, 80);
|
||||
listener.backends.push(backend.clone());
|
||||
config.listeners.push(listener);
|
||||
@@ -591,10 +880,11 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
|
||||
let ctx = egui::Context::default();
|
||||
configure(&ctx);
|
||||
let mut phone = Phone::default();
|
||||
let size = std::cell::Cell::new(egui::vec2(360., 800.));
|
||||
let mut frame = |events| {
|
||||
ctx.run(
|
||||
RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(360., 800.))),
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size.get())),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -631,21 +921,31 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
|
||||
}
|
||||
frame(vec![])
|
||||
};
|
||||
let live = click("VIP");
|
||||
for label in ["Overview", "Configuration", "Next new flow", "node:8080"] {
|
||||
click("lab");
|
||||
size.set(egui::vec2(800., 360.));
|
||||
let live = click(&format!("{} VIP", egui_phosphor::regular::NETWORK));
|
||||
for label in ["Overview", "Configuration", "web.lab", "node:8080"] {
|
||||
let p = position(&live, label);
|
||||
assert!(
|
||||
(0.0..360.0).contains(&p.x),
|
||||
"{label} is outside the portrait view"
|
||||
(0.0..800.0).contains(&p.x),
|
||||
"{label} is outside the landscape view"
|
||||
);
|
||||
}
|
||||
let editor = click("Configuration");
|
||||
position(&editor, "Name");
|
||||
ctx.memory_mut(|m| m.request_focus(name_field));
|
||||
frame(vec![Event::Text("-draft".into())]);
|
||||
size.set(egui::vec2(360., 800.));
|
||||
let editor_portrait = frame(vec![]);
|
||||
position(&editor_portrait, "Unsaved changes");
|
||||
assert!(editor_portrait.shapes.iter().any(|s| matches!(&s.shape,
|
||||
Shape::Text(t) if t.galley.text().contains("-draft"))));
|
||||
for label in [
|
||||
"Active TCP port checks",
|
||||
"Checks and flow expiry",
|
||||
"+ Backend",
|
||||
"+ Listener",
|
||||
] {
|
||||
position(&editor, label);
|
||||
position(&editor_portrait, label);
|
||||
}
|
||||
}
|
||||
@@ -20,10 +20,12 @@ enum Page {
|
||||
#[default]
|
||||
Home,
|
||||
About,
|
||||
Monitor,
|
||||
Join,
|
||||
Devices(String),
|
||||
Vips(String),
|
||||
Exit(String),
|
||||
ExitNetworks,
|
||||
Leave(String),
|
||||
}
|
||||
impl Page {
|
||||
@@ -37,10 +39,11 @@ impl Page {
|
||||
match self {
|
||||
Self::Home => "tsunagi",
|
||||
Self::About => "About",
|
||||
Self::Monitor => "Traffic monitor",
|
||||
Self::Join => "Join a network",
|
||||
Self::Devices(_) => "Devices",
|
||||
Self::Vips(_) => "VIP",
|
||||
Self::Exit(_) => "Exit node",
|
||||
Self::Exit(_) | Self::ExitNetworks => "Exit node",
|
||||
Self::Leave(_) => "Leave network",
|
||||
}
|
||||
}
|
||||
@@ -84,16 +87,22 @@ struct Pending {
|
||||
#[derive(Default)]
|
||||
pub struct Phone {
|
||||
page: Page,
|
||||
monitor: Option<crate::monitor::Monitor>,
|
||||
cache_dir: Option<std::path::PathBuf>,
|
||||
forms: UiState,
|
||||
traffic: Traffic,
|
||||
snapshot: Snapshot,
|
||||
pending: Option<Pending>,
|
||||
error: Option<String>,
|
||||
clipboard: Option<Zeroizing<String>>,
|
||||
landscape: bool,
|
||||
pick_exit: bool,
|
||||
before_picker: Option<Page>,
|
||||
}
|
||||
|
||||
/// Keep reads at tray density. Extra hit area is reserved for the navigation bar.
|
||||
pub fn configure(ctx: &Context) {
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
ctx.set_fonts(tsunagi_ui::app_fonts());
|
||||
ctx.style_mut(|style| {
|
||||
style.spacing.interact_size.y = 19.0;
|
||||
@@ -103,12 +112,33 @@ pub fn configure(ctx: &Context) {
|
||||
}
|
||||
|
||||
impl Phone {
|
||||
/// Private directory available to a window's temporary SQLite database.
|
||||
pub fn set_cache_dir(&mut self, path: std::path::PathBuf) {
|
||||
self.cache_dir = Some(path);
|
||||
}
|
||||
/// Release the agent subscription immediately when the activity goes into the background.
|
||||
pub fn pause_monitor(&mut self) {
|
||||
if let Some(m) = &mut self.monitor {
|
||||
m.pause();
|
||||
}
|
||||
}
|
||||
/// Poll the service only while a traffic screen is visible.
|
||||
pub fn poll_monitor(&mut self, open: impl FnOnce() -> Result<Response, String>) {
|
||||
if let Some(m) = &mut self.monitor {
|
||||
m.poll(open);
|
||||
}
|
||||
}
|
||||
fn home(&mut self) {
|
||||
self.monitor = None;
|
||||
if let Some(previous) = self.before_picker.take() {
|
||||
self.forms.exit_confirm = None;
|
||||
self.page = previous;
|
||||
return;
|
||||
}
|
||||
if let Page::Vips(id) = &self.page {
|
||||
self.forms.vip_windows.remove(id);
|
||||
}
|
||||
self.forms.join.name.clear();
|
||||
self.forms.join.secret.zeroize();
|
||||
self.forms.join = Default::default();
|
||||
self.forms.exit_confirm = None;
|
||||
self.forms.forget_confirm = None;
|
||||
self.page = Page::Home;
|
||||
@@ -127,6 +157,8 @@ impl Phone {
|
||||
&& editor.dirty()
|
||||
{
|
||||
editor.request_close();
|
||||
} else if self.page == Page::Home && self.landscape && self.forms.close_selection() {
|
||||
return None;
|
||||
} else if self.page == Page::Home {
|
||||
return Some(SystemAction::Finish);
|
||||
} else {
|
||||
@@ -150,6 +182,99 @@ impl Phone {
|
||||
self.error = Some(message);
|
||||
}
|
||||
|
||||
/// The first tile tap opens the chooser once the agent is ready.
|
||||
pub fn request_exit_picker(&mut self) {
|
||||
self.pick_exit = true;
|
||||
}
|
||||
|
||||
fn exit_networks(&mut self, ui: &mut egui::Ui, networks: &[tsunagi::ipc::NetworkReport]) {
|
||||
if networks.is_empty() {
|
||||
ui.label("Join a network to choose an exit node.");
|
||||
if ui.button("Join or create a network").clicked() {
|
||||
self.page = Page::Join;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !networks.iter().any(|n| n.active) {
|
||||
ui.label("Start a network to choose an exit node.");
|
||||
if ui.button("Show networks").clicked() {
|
||||
self.home();
|
||||
}
|
||||
return;
|
||||
}
|
||||
ui.label("Choose a network for the exit node");
|
||||
for n in networks.iter().filter(|n| n.active) {
|
||||
let ambiguous = networks.iter().any(|other| {
|
||||
other.active && other.name == n.name && other.network_id != n.network_id
|
||||
});
|
||||
let label = if ambiguous {
|
||||
format!("{} · {}", n.name, tsunagi_ui::format::short(&n.network_id))
|
||||
} else {
|
||||
n.name.clone()
|
||||
};
|
||||
if ui.button(label).clicked() {
|
||||
self.page = Page::Exit(n.network_id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn landscape_home(
|
||||
&mut self,
|
||||
ui: &mut egui::Ui,
|
||||
actions: &Actions,
|
||||
report: &tsunagi::ipc::StatusReport,
|
||||
) {
|
||||
let width = (ui.available_width() / 3.)
|
||||
.clamp(146., 300.)
|
||||
.min(ui.available_width() * 0.45);
|
||||
egui::SidePanel::left("network selector")
|
||||
.resizable(false)
|
||||
.exact_width(width)
|
||||
.show_inside(ui, |ui| {
|
||||
if ui.button("Join or create a network").clicked() {
|
||||
self.page = Page::Join;
|
||||
}
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("network list")
|
||||
.show(ui, |ui| {
|
||||
for network in &report.networks {
|
||||
home::draw_network_selector(ui, network, report, &mut self.forms);
|
||||
}
|
||||
});
|
||||
});
|
||||
egui::CentralPanel::default().show_inside(ui, |ui| {
|
||||
let selected = report
|
||||
.networks
|
||||
.iter()
|
||||
.find(|n| self.forms.selected_network.as_deref() == Some(&n.network_id));
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt(("network settings", selected.map(|n| &n.network_id)))
|
||||
.show(ui, |ui| {
|
||||
if let Some(n) = selected {
|
||||
ui.heading(&n.name);
|
||||
ui.push_id(&n.network_id, |ui| {
|
||||
if home::draw_network_details(
|
||||
ui,
|
||||
actions,
|
||||
&mut self.forms,
|
||||
&self.traffic,
|
||||
n,
|
||||
report,
|
||||
false,
|
||||
) {
|
||||
self.page = Page::Exit(n.network_id.clone());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
ui.heading("This device");
|
||||
ui.label("Tsunagi Agent is running");
|
||||
home::draw_header(ui, actions, &mut self.forms, report);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Take a secret once for the platform’s sensitive clipboard.
|
||||
pub fn take_copied_secret(&mut self) -> Option<Zeroizing<String>> {
|
||||
self.clipboard.take()
|
||||
@@ -162,7 +287,7 @@ impl Phone {
|
||||
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())
|
||||
Err("Tsunagi Agent stopped".to_owned())
|
||||
}
|
||||
Ok(v) => v,
|
||||
};
|
||||
@@ -191,6 +316,7 @@ impl Phone {
|
||||
mut submit: impl FnMut(Command) -> Result<Response, String>,
|
||||
) -> Option<SystemAction> {
|
||||
self.acknowledge();
|
||||
self.landscape = tsunagi_ui::widgets::landscape(ctx);
|
||||
let report = if let State::Ready(report, at) = state {
|
||||
if self.snapshot.at != Some(*at) {
|
||||
self.snapshot.generation = self.snapshot.generation.wrapping_add(1);
|
||||
@@ -205,9 +331,28 @@ impl Phone {
|
||||
{
|
||||
self.home();
|
||||
}
|
||||
if self
|
||||
.forms
|
||||
.selected_network
|
||||
.as_ref()
|
||||
.is_some_and(|id| !report.networks.iter().any(|n| &n.network_id == id))
|
||||
{
|
||||
self.forms.close_selection();
|
||||
}
|
||||
if self.pick_exit && self.pending.is_none() {
|
||||
self.pick_exit = false;
|
||||
let mut active = report.networks.iter().filter(|n| n.active);
|
||||
let picker = match (active.next(), active.next()) {
|
||||
(Some(n), None) => Page::Exit(n.network_id.clone()),
|
||||
_ => Page::ExitNetworks,
|
||||
};
|
||||
if !matches!(self.page, Page::Exit(_) | Page::ExitNetworks) {
|
||||
self.before_picker = Some(std::mem::replace(&mut self.page, picker));
|
||||
}
|
||||
}
|
||||
Some(report)
|
||||
} else {
|
||||
if self.page.network().is_some() || self.page == Page::Join {
|
||||
if self.page.network().is_some() || matches!(self.page, Page::Join | Page::Monitor) {
|
||||
self.home();
|
||||
}
|
||||
self.snapshot = Snapshot::default();
|
||||
@@ -222,25 +367,35 @@ impl Phone {
|
||||
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() {
|
||||
if self.page != Page::Home
|
||||
&& tsunagi_ui::widgets::icon_button(ui, icon::ARROW_LEFT, "Back").clicked()
|
||||
{
|
||||
system = self.back();
|
||||
}
|
||||
ui.heading(self.page.title());
|
||||
if self.page == Page::Home {
|
||||
ui.weak(env!("CARGO_PKG_VERSION"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(icon::INFO).clicked() {
|
||||
if tsunagi_ui::widgets::icon_button(ui, icon::INFO, "About Tsunagi")
|
||||
.clicked()
|
||||
{
|
||||
self.page = Page::About;
|
||||
}
|
||||
if report.is_some() {
|
||||
if tsunagi_ui::widgets::icon_button(ui, icon::PULSE, "Traffic monitor")
|
||||
.clicked()
|
||||
{
|
||||
self.page = Page::Monitor;
|
||||
}
|
||||
ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes");
|
||||
ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts");
|
||||
}
|
||||
});
|
||||
} else if self.page == Page::About
|
||||
&& !matches!(state, State::Off)
|
||||
&& ui.button("Stop VPN").clicked()
|
||||
&& ui.button("Stop Tsunagi Agent").clicked()
|
||||
{
|
||||
self.home();
|
||||
system = Some(SystemAction::Stop);
|
||||
}
|
||||
});
|
||||
@@ -252,7 +407,19 @@ impl Phone {
|
||||
.page
|
||||
.network()
|
||||
.and_then(|id| report?.networks.iter().find(|n| n.network_id == id));
|
||||
if self.page != Page::Monitor {
|
||||
self.monitor = None;
|
||||
}
|
||||
match (&self.page, selected) {
|
||||
(Page::Monitor, _) => {
|
||||
let m = self
|
||||
.monitor
|
||||
.get_or_insert_with(|| crate::monitor::Monitor::new(self.cache_dir.clone()));
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
m.view
|
||||
.show(ui, report.map(|r| r.as_ref()), self.snapshot.generation)
|
||||
});
|
||||
}
|
||||
(Page::About, _) => about::show(ctx, None, &self.snapshot),
|
||||
(Page::Vips(id), Some(network)) => {
|
||||
let editor = self.forms.vip_windows.entry(id.clone()).or_default();
|
||||
@@ -275,13 +442,17 @@ impl Phone {
|
||||
}
|
||||
_ => {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
if let Some(report) = report && self.page == Page::Home && self.landscape {
|
||||
self.landscape_home(ui, &actions, report);
|
||||
return;
|
||||
}
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
let Some(report) = report else {
|
||||
match state {
|
||||
State::Starting => {ui.spinner(); ui.label("Starting VPN…");}
|
||||
State::Starting => {ui.spinner(); ui.label("Starting Tsunagi Agent…");}
|
||||
_ => {
|
||||
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);}
|
||||
if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("Tsunagi Agent is stopped");}
|
||||
if ui.button("Start Tsunagi Agent").clicked() {self.error = None; system = Some(SystemAction::Start);}
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -293,8 +464,6 @@ impl Phone {
|
||||
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 => {
|
||||
@@ -306,6 +475,7 @@ impl Phone {
|
||||
self.forms.exit_confirm = Some(choice);
|
||||
}
|
||||
}
|
||||
Page::ExitNetworks => self.exit_networks(ui, &report.networks),
|
||||
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));
|
||||
@@ -317,6 +487,20 @@ impl Phone {
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(report) = report
|
||||
&& self.page == Page::Home
|
||||
{
|
||||
for n in &report.networks {
|
||||
if self.forms.open_devices.remove(&n.network_id) {
|
||||
self.page = Page::Devices(n.network_id.clone());
|
||||
break;
|
||||
}
|
||||
if self.forms.vip_windows.contains_key(&n.network_id) {
|
||||
self.page = Page::Vips(n.network_id.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -532,6 +532,9 @@ struct FaultLink {
|
||||
sequence: AtomicU64,
|
||||
}
|
||||
impl PacketLink for FaultLink {
|
||||
fn confirm_delivery(&self) {
|
||||
self.raw.confirm_delivery();
|
||||
}
|
||||
fn network(&self) -> NetworkId {
|
||||
self.raw.network()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
|
||||
readme = "../../README.md"
|
||||
keywords = ["mesh", "p2p", "iroh", "networking"]
|
||||
@@ -35,6 +35,7 @@ dns-publish = ["dep:zbus"]
|
||||
testing = ["dep:tempfile", "dep:tracing-subscriber"]
|
||||
|
||||
[dependencies]
|
||||
tsunagi-speedtest = { path = "../tsunagi-speedtest", version = "0.1.0" }
|
||||
arc-swap = "1.9"
|
||||
iroh.workspace = true
|
||||
# `net` for the local control interface: a Unix socket on Unix, a named pipe
|
||||
@@ -98,13 +99,18 @@ futures-util = { version = "0.3", default-features = false, optional = true }
|
||||
# before deciding what to change. Creating an adapter needs the process to be
|
||||
# elevated and `wintun.dll` to be reachable at run time.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Networking_WinSock",
|
||||
"Win32_Security",
|
||||
"Win32_Security_Authorization",
|
||||
"Win32_Foundation",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
# Its own tests use the harness it publishes.
|
||||
tsunagi-core = { path = ".", features = ["testing"] }
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "process", "test-util"] }
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::time::Duration;
|
||||
|
||||
use iroh::EndpointId;
|
||||
|
||||
use crate::identity::NetworkId;
|
||||
use crate::identity::{NetworkId, NetworkName};
|
||||
use crate::net::TransportKind;
|
||||
use crate::proto::ControlMessage;
|
||||
use crate::proto::handshake::Role;
|
||||
@@ -48,8 +48,12 @@ pub enum Event {
|
||||
PeerDisconnected {
|
||||
/// The network the session belonged to.
|
||||
network: NetworkId,
|
||||
/// Its locally configured name.
|
||||
network_name: NetworkName,
|
||||
/// The peer.
|
||||
peer: EndpointId,
|
||||
/// Last known name of the authenticated peer, when available.
|
||||
hostname: Option<String>,
|
||||
/// Why the session ended. Free of secrets.
|
||||
reason: String,
|
||||
},
|
||||
|
||||
@@ -22,12 +22,14 @@ mod events;
|
||||
mod network;
|
||||
mod session;
|
||||
mod shutdown;
|
||||
mod speed;
|
||||
mod status;
|
||||
|
||||
pub use events::Event;
|
||||
pub use status::{
|
||||
AgentStatus, CandidateStatus, DataPath, HostnameConflict, MemberStatus, NetworkMetrics,
|
||||
NetworkState, NetworkStatus, OverlayStatus, PeerStatus, RangeConflict,
|
||||
AgentStatus, CandidateStatus, DATA_CONNECTING, DATA_DISABLED, DataPath, HostnameConflict,
|
||||
MemberStatus, NetworkMetrics, NetworkState, NetworkStatus, OverlayStatus, PeerStatus,
|
||||
RangeConflict,
|
||||
};
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -94,6 +96,7 @@ pub struct Agent {
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
config: AgentConfig,
|
||||
speed: speed::SpeedTests,
|
||||
limits: Arc<Limits>,
|
||||
storage: Storage,
|
||||
identity: DeviceIdentity,
|
||||
@@ -106,6 +109,7 @@ struct Inner {
|
||||
/// Serialises start, stop, switching and conflict cleanup, including teardown.
|
||||
lifecycle: Arc<Mutex<()>>,
|
||||
range_changed: watch::Sender<()>,
|
||||
roster_changed: watch::Sender<()>,
|
||||
range_task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
accept_task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
plugin_task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
@@ -218,6 +222,9 @@ impl PacketSink for Sink {
|
||||
let Some(inner) = self.0.upgrade() else {
|
||||
return;
|
||||
};
|
||||
if speed::receive_packet(&inner, network, peer, &packet) {
|
||||
return;
|
||||
}
|
||||
let Some(interface) = inner.interface.get() else {
|
||||
return;
|
||||
};
|
||||
@@ -299,6 +306,13 @@ impl TransportContext for TransportCtx {
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
/// Start a fresh, independent observation interval for one local window.
|
||||
pub fn subscribe_traffic(
|
||||
&self,
|
||||
) -> std::result::Result<crate::traffic::TrafficSubscription, String> {
|
||||
self.inner.routes.traffic.subscribe()
|
||||
}
|
||||
|
||||
/// Atomically saves or removes a version-checked shared VIP draft.
|
||||
/// Every authenticated network member may edit any service.
|
||||
pub async fn save_vip(
|
||||
@@ -442,6 +456,7 @@ impl Agent {
|
||||
|
||||
let (range_changed, range_updates) = watch::channel(());
|
||||
let inner = Arc::new(Inner {
|
||||
speed: speed::SpeedTests::default(),
|
||||
limits,
|
||||
storage,
|
||||
identity,
|
||||
@@ -452,6 +467,7 @@ impl Agent {
|
||||
shutdown: Shutdown::new(),
|
||||
lifecycle: Arc::new(Mutex::new(())),
|
||||
range_changed,
|
||||
roster_changed: watch::channel(()).0,
|
||||
range_task: std::sync::Mutex::new(None),
|
||||
accept_task: std::sync::Mutex::new(None),
|
||||
plugin_task: std::sync::Mutex::new(None),
|
||||
@@ -508,7 +524,8 @@ impl Agent {
|
||||
.tun_factory
|
||||
.as_ref()
|
||||
.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, &inner.routes);
|
||||
if let Some(tunnel) = &inner.config.tunnel {
|
||||
tunnel.attach(context);
|
||||
}
|
||||
@@ -690,6 +707,7 @@ impl Agent {
|
||||
for sender in senders {
|
||||
let _ = sender.send(NetCommand::SetHostname(hostname.clone())).await;
|
||||
}
|
||||
self.inner.roster_changed.send_replace(());
|
||||
Ok(hostname)
|
||||
}
|
||||
|
||||
@@ -706,6 +724,13 @@ impl Agent {
|
||||
self.inner.events.subscribe()
|
||||
}
|
||||
|
||||
/// Subscribe to changes affecting the mesh DNS roster, exit offers or selected exit.
|
||||
/// Changes coalesce. Read the current status after subscribing and again on
|
||||
/// notification. Packet counters and routine control traffic do not wake subscribers.
|
||||
pub fn watch_roster(&self) -> watch::Receiver<()> {
|
||||
self.inner.roster_changed.subscribe()
|
||||
}
|
||||
|
||||
/// Makes this agent a member of a network, activating it.
|
||||
///
|
||||
/// The same `(name, secret)` always produces the same [`NetworkId`], on
|
||||
@@ -995,6 +1020,7 @@ impl Agent {
|
||||
self.inner.ensure_interface().await;
|
||||
}
|
||||
let handle = network::spawn(RuntimeParams {
|
||||
agent: Arc::downgrade(&self.inner),
|
||||
vips,
|
||||
retirements,
|
||||
broadcast,
|
||||
@@ -1019,6 +1045,7 @@ impl Agent {
|
||||
unreachable_data_peers: Arc::clone(&self.inner.config.unreachable_data_peers),
|
||||
ipv4_range: range,
|
||||
range_changed: self.inner.range_changed.clone(),
|
||||
roster_changed: self.inner.roster_changed.clone(),
|
||||
});
|
||||
networks.insert(network_id, handle);
|
||||
drop(networks);
|
||||
@@ -1030,6 +1057,7 @@ impl Agent {
|
||||
tunnel.on_network_activated(network_id);
|
||||
}
|
||||
|
||||
self.inner.roster_changed.send_replace(());
|
||||
let _ = self.inner.events.send(Event::NetworkActivated {
|
||||
network: network_id,
|
||||
});
|
||||
@@ -1066,6 +1094,7 @@ impl Agent {
|
||||
}
|
||||
|
||||
async fn stop_network_locked(&self, network_id: NetworkId) -> Result<()> {
|
||||
self.inner.speed.remove_network(network_id);
|
||||
let handle = {
|
||||
let mut networks = self.inner.networks.write().await;
|
||||
networks
|
||||
@@ -1097,6 +1126,7 @@ impl Agent {
|
||||
interface.sync_broadcast_rules().await;
|
||||
interface.sync_exit_rules().await;
|
||||
}
|
||||
self.inner.roster_changed.send_replace(());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1111,6 +1141,7 @@ impl Agent {
|
||||
self.stop_network_locked(network_id).await?;
|
||||
}
|
||||
self.inner.storage.remove_network(network_id).await?;
|
||||
self.inner.roster_changed.send_replace(());
|
||||
for plugin in &self.inner.config.carriers {
|
||||
plugin.on_network_forgotten(network_id);
|
||||
}
|
||||
@@ -1300,6 +1331,7 @@ impl Agent {
|
||||
})
|
||||
.collect();
|
||||
networks.push(NetworkStatus {
|
||||
speed: Default::default(),
|
||||
vips,
|
||||
protocols: self.effective_protocols(stored.protocols.as_ref()),
|
||||
auto_start: stored.auto_start,
|
||||
@@ -1309,6 +1341,7 @@ impl Agent {
|
||||
.exit_via
|
||||
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok()),
|
||||
exit_via_online: false,
|
||||
exit_traffic: None,
|
||||
exit_rules: Default::default(),
|
||||
descriptor: keys.descriptor(),
|
||||
name: stored.name,
|
||||
@@ -1378,6 +1411,7 @@ impl Agent {
|
||||
/// After this returns, the state directory can be opened by another agent.
|
||||
pub async fn shutdown(&self) {
|
||||
self.inner.shutdown.trigger();
|
||||
self.inner.speed.shutdown();
|
||||
let lifecycle_guard = self.inner.lifecycle.lock().await;
|
||||
|
||||
let handles: Vec<NetworkHandle> = {
|
||||
|
||||
@@ -38,8 +38,10 @@ use super::status::{
|
||||
CandidateStatus, DataPath, HostnameConflict, MemberStatus, NetworkMetrics, NetworkState,
|
||||
NetworkStatus, PeerStatus,
|
||||
};
|
||||
use sync::{Changes, SyncKey};
|
||||
|
||||
mod selection;
|
||||
mod sync;
|
||||
|
||||
/// An inbound connection that already passed the handshake.
|
||||
#[derive(Debug)]
|
||||
@@ -175,6 +177,7 @@ impl NetworkHandle {
|
||||
|
||||
/// Everything a network runtime needs to run.
|
||||
pub(crate) struct RuntimeParams {
|
||||
pub(super) agent: std::sync::Weak<super::Inner>,
|
||||
pub(crate) vips: crate::vip::VipSet,
|
||||
pub(crate) retirements: Vec<SignedRetirement>,
|
||||
pub(crate) broadcast: bool,
|
||||
@@ -205,6 +208,7 @@ pub(crate) struct RuntimeParams {
|
||||
pub(crate) ipv4_range: Option<Ipv4Range>,
|
||||
/// Coalesced notifications to the agent's lifecycle manager.
|
||||
pub(crate) range_changed: tokio::sync::watch::Sender<()>,
|
||||
pub(crate) roster_changed: tokio::sync::watch::Sender<()>,
|
||||
/// How data plane links are opened. `None` disables the data plane.
|
||||
pub(crate) transport: Option<Arc<dyn PacketTransport>>,
|
||||
}
|
||||
@@ -236,6 +240,54 @@ struct DialState {
|
||||
source: CandidateSource,
|
||||
}
|
||||
|
||||
/// Keep only paths that this runtime verified, long enough to reconnect when
|
||||
/// a session goes away while the host sends its default traffic into the mesh.
|
||||
#[derive(Default)]
|
||||
struct VerifiedUnderlay {
|
||||
peers: HashMap<EndpointId, (Instant, Vec<PathAddr>)>,
|
||||
}
|
||||
|
||||
impl VerifiedUnderlay {
|
||||
fn record(
|
||||
&mut self,
|
||||
peer: EndpointId,
|
||||
paths: impl IntoIterator<Item = PathAddr>,
|
||||
now: Instant,
|
||||
limit: usize,
|
||||
) {
|
||||
let paths: Vec<_> = paths
|
||||
.into_iter()
|
||||
.filter(|p| {
|
||||
matches!(
|
||||
p,
|
||||
PathAddr::Ip(std::net::SocketAddr::V4(_)) | PathAddr::Relay(_)
|
||||
)
|
||||
})
|
||||
.take(limit)
|
||||
.collect();
|
||||
if !paths.is_empty() {
|
||||
self.peers.insert(peer, (now, paths));
|
||||
}
|
||||
}
|
||||
|
||||
fn prune(&mut self, now: Instant, limit: usize, retired: impl Fn(EndpointId) -> bool) {
|
||||
self.peers.retain(|peer, (seen, _)| {
|
||||
!retired(*peer) && now.duration_since(*seen) < Duration::from_secs(120)
|
||||
});
|
||||
if self.peers.len() > limit {
|
||||
let mut oldest: Vec<_> = self
|
||||
.peers
|
||||
.iter()
|
||||
.map(|(peer, (seen, _))| (*seen, *peer))
|
||||
.collect();
|
||||
oldest.sort_unstable();
|
||||
for (_, peer) in oldest.into_iter().take(self.peers.len() - limit) {
|
||||
self.peers.remove(&peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DialState {
|
||||
fn new(source: CandidateSource) -> Self {
|
||||
Self {
|
||||
@@ -313,6 +365,7 @@ struct Runtime {
|
||||
local_id: EndpointId,
|
||||
shutdown: Shutdown,
|
||||
sessions: HashMap<EndpointId, Session>,
|
||||
verified_underlay: VerifiedUnderlay,
|
||||
dial_states: HashMap<EndpointId, DialState>,
|
||||
candidate_addrs: HashMap<EndpointId, iroh::EndpointAddr>,
|
||||
metrics: NetworkMetrics,
|
||||
@@ -380,10 +433,9 @@ struct Runtime {
|
||||
/// Snapshots received while dispatching, handled on the next loop pass.
|
||||
pending_state: Vec<(EndpointId, Vec<SignedRecord>)>,
|
||||
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.
|
||||
retirement_cursor: HashMap<EndpointId, usize>,
|
||||
pending_vips: Vec<(EndpointId, Vec<crate::vip::VipEntry>)>,
|
||||
changes: Changes,
|
||||
introductions: Vec<crate::proto::message::PeerHint>,
|
||||
/// The highest version this agent has ever published for this network.
|
||||
own_version: u64,
|
||||
/// Whether the exit node in use was reachable when last looked at, so
|
||||
@@ -411,7 +463,11 @@ impl Runtime {
|
||||
let (link_results_tx, link_results_rx) = mpsc::channel(64);
|
||||
let (candidate_tx, discovery_candidates) =
|
||||
mpsc::channel(params.limits.max_discovery_candidates.max(1));
|
||||
let hub = crate::dataplane::relay::RelayHub::new(network_id, local_id);
|
||||
let hub = crate::dataplane::relay::RelayHub::with_monitor(
|
||||
network_id,
|
||||
local_id,
|
||||
params.routes.traffic.clone(),
|
||||
);
|
||||
// The order the protocols were configured in is also how links are
|
||||
// preferred when a neighbour can be reached over more than one.
|
||||
hub.set_priority(
|
||||
@@ -441,6 +497,7 @@ impl Runtime {
|
||||
local_id,
|
||||
shutdown,
|
||||
sessions: HashMap::new(),
|
||||
verified_underlay: VerifiedUnderlay::default(),
|
||||
dial_states: HashMap::new(),
|
||||
candidate_addrs: HashMap::new(),
|
||||
metrics: NetworkMetrics::default(),
|
||||
@@ -471,8 +528,8 @@ impl Runtime {
|
||||
pending_state: Vec::new(),
|
||||
pending_retirements: Vec::new(),
|
||||
pending_vips: Vec::new(),
|
||||
vip_cursor: HashMap::new(),
|
||||
retirement_cursor: HashMap::new(),
|
||||
changes: Changes::default(),
|
||||
introductions: Vec::new(),
|
||||
own_version: 0,
|
||||
exit_via_was_online: false,
|
||||
announced_exit: false,
|
||||
@@ -495,10 +552,14 @@ impl Runtime {
|
||||
let mut ticker = tokio::time::interval(self.params.discovery_interval);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
|
||||
// Long discovery intervals must not let live transit edges expire.
|
||||
let mut reach_refresh = tokio::time::interval(REACH_EXPIRY / 3);
|
||||
reach_refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.shutdown.wait() => break,
|
||||
_ = reach_refresh.tick(), if self.params.discovery_interval > REACH_EXPIRY / 3 => self.announce_reach(false),
|
||||
_ = self.hub.changed() => {
|
||||
self.ensure_links();
|
||||
self.update_paths();
|
||||
@@ -600,7 +661,7 @@ impl Runtime {
|
||||
message,
|
||||
reply,
|
||||
} => {
|
||||
if matches!(&message, ControlMessage::Transport { .. })
|
||||
if matches!(&message, ControlMessage::Transport { protocol, .. } if protocol != tsunagi_speedtest::PROTOCOL)
|
||||
&& let Some(interface) = self.params.interface.clone()
|
||||
{
|
||||
// Locally bound pair sockets must be protected before their
|
||||
@@ -737,7 +798,6 @@ impl Runtime {
|
||||
// author, so the new version replaces the old name
|
||||
// rather than sitting beside it.
|
||||
self.ensure_own_claim().await;
|
||||
self.broadcast_state();
|
||||
}
|
||||
// Told to peers regardless, so a session that missed the
|
||||
// earlier announcement is not left with a stale name.
|
||||
@@ -816,6 +876,12 @@ impl Runtime {
|
||||
|
||||
match session.outbound.try_send(zeroize::Zeroizing::new(encoded)) {
|
||||
Ok(()) => {
|
||||
self.params.routes.traffic.control(
|
||||
network,
|
||||
peer,
|
||||
crate::traffic::Direction::Tx,
|
||||
bytes,
|
||||
);
|
||||
session.messages_sent += 1;
|
||||
session.bytes_sent += bytes;
|
||||
self.metrics.control_messages_sent += 1;
|
||||
@@ -844,12 +910,11 @@ impl Runtime {
|
||||
// the check is a comparison when nothing has changed.
|
||||
self.ensure_own_claim().await;
|
||||
self.report_hostname_taken();
|
||||
self.broadcast_vips();
|
||||
self.broadcast_retirements();
|
||||
self.flush_updates();
|
||||
// The same timer repairs the relay picture: reachability is soft
|
||||
// state, repeated while it holds and forgotten when it stops.
|
||||
self.update_paths();
|
||||
self.announce_reach(true);
|
||||
self.announce_reach(false);
|
||||
|
||||
let mut candidates: Vec<Candidate> = Vec::new();
|
||||
|
||||
@@ -902,7 +967,7 @@ impl Runtime {
|
||||
/// on: the verified direct IPv4 paths of every control connection, and
|
||||
/// the relays in use. Only hosts that cannot exempt the agent from an
|
||||
/// exit node's default route read it.
|
||||
async fn refresh_underlay(&self) {
|
||||
async fn refresh_underlay(&mut self) {
|
||||
let Some(interface) = self
|
||||
.params
|
||||
.interface
|
||||
@@ -913,17 +978,38 @@ impl Runtime {
|
||||
};
|
||||
let mut addresses = Vec::new();
|
||||
let mut hosts = Vec::new();
|
||||
for session in self.sessions.values() {
|
||||
for path in snapshot_connection(&session.conn).paths {
|
||||
match path.remote {
|
||||
PathAddr::Ip(std::net::SocketAddr::V4(socket)) => addresses.push(*socket.ip()),
|
||||
PathAddr::Relay(url) => hosts.extend(relay_host(&url)),
|
||||
_ => {}
|
||||
}
|
||||
let now = Instant::now();
|
||||
for (peer, session) in &self.sessions {
|
||||
let mut paths = snapshot_connection(&session.conn).paths;
|
||||
paths.sort_by_key(|path| !path.is_selected);
|
||||
self.verified_underlay.record(
|
||||
*peer,
|
||||
paths.into_iter().map(|p| p.remote),
|
||||
now,
|
||||
self.params.limits.max_hints_per_peer,
|
||||
);
|
||||
}
|
||||
self.verified_underlay
|
||||
.prune(now, self.params.limits.max_sessions_per_network, |peer| {
|
||||
self.state.is_retired(&peer)
|
||||
});
|
||||
for path in self
|
||||
.verified_underlay
|
||||
.peers
|
||||
.values()
|
||||
.flat_map(|(_, paths)| paths)
|
||||
{
|
||||
match path {
|
||||
PathAddr::Ip(std::net::SocketAddr::V4(socket)) => addresses.push(*socket.ip()),
|
||||
PathAddr::Relay(url) => hosts.extend(relay_host(url)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for url in self.params.adapter.snapshot().relay_urls {
|
||||
hosts.extend(relay_host(&url));
|
||||
// The endpoint stops advertising a disconnected relay, but still
|
||||
// attempts to reconnect to it through the physical network.
|
||||
use iroh::Watcher;
|
||||
for relay in self.params.adapter.endpoint().home_relay_status().get() {
|
||||
hosts.extend(relay_host(relay.url().as_str()));
|
||||
}
|
||||
interface
|
||||
.set_underlay(self.network_id, addresses, hosts)
|
||||
@@ -1139,6 +1225,7 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
self.index_stored_state();
|
||||
self.ensure_own_claim().await;
|
||||
self.publish_allocations().await;
|
||||
}
|
||||
@@ -1354,14 +1441,7 @@ impl Runtime {
|
||||
self.candidate_addrs.remove(&peer);
|
||||
self.publish_allocations().await;
|
||||
self.report_hostname_taken();
|
||||
let message = ControlMessage::Retirements {
|
||||
markers: vec![marker],
|
||||
};
|
||||
let peers: Vec<_> = self.sessions.keys().copied().collect();
|
||||
let peers_told = peers
|
||||
.into_iter()
|
||||
.filter(|peer| self.send_to(*peer, message.clone()).is_ok())
|
||||
.count();
|
||||
let peers_told = self.share_changes([SyncKey::Retirement(peer)]);
|
||||
Ok(super::ForgetNodeOutcome {
|
||||
target: peer,
|
||||
record_version: expected_version,
|
||||
@@ -1369,40 +1449,8 @@ impl Runtime {
|
||||
})
|
||||
}
|
||||
|
||||
fn broadcast_retirements(&mut self) -> usize {
|
||||
let markers = self.state.retirements();
|
||||
if markers.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
// Each proof has an encoded bound; reserve envelope/list overhead and
|
||||
// chunk every marker, so a low-id prefix cannot starve later cleanup.
|
||||
let batch = (self.params.limits.max_frame_len.saturating_sub(128) / MAX_RETIREMENT_LEN)
|
||||
.max(1)
|
||||
.min(self.params.limits.max_state_records.max(1));
|
||||
let mut delivered = HashSet::new();
|
||||
let peers: Vec<_> = self.sessions.keys().copied().collect();
|
||||
let chunks: Vec<_> = markers.chunks(batch).collect();
|
||||
for peer in peers {
|
||||
let start = self.retirement_cursor.get(&peer).copied().unwrap_or(0) % chunks.len();
|
||||
for offset in 0..chunks.len() {
|
||||
let index = (start + offset) % chunks.len();
|
||||
let message = ControlMessage::Retirements {
|
||||
markers: chunks[index].to_vec(),
|
||||
};
|
||||
if self.send_to(peer, message).is_err() {
|
||||
self.retirement_cursor.insert(peer, index);
|
||||
break;
|
||||
}
|
||||
delivered.insert(peer);
|
||||
self.retirement_cursor
|
||||
.insert(peer, (index + 1) % chunks.len());
|
||||
}
|
||||
}
|
||||
delivered.len()
|
||||
}
|
||||
|
||||
async fn receive_retirements(&mut self, peer: EndpointId, markers: Vec<SignedRetirement>) {
|
||||
let mut changed = false;
|
||||
let mut changed = Vec::new();
|
||||
for marker in markers {
|
||||
let mut candidate = self.state.clone();
|
||||
match candidate.merge_retirement(
|
||||
@@ -1424,11 +1472,7 @@ impl Runtime {
|
||||
}
|
||||
let target = marker.target.author_id().ok();
|
||||
if let Err(err) = self.params.storage.put_retirement(marker).await {
|
||||
self.emit(Event::PluginError {
|
||||
network: self.network_id,
|
||||
protocol: "state".into(),
|
||||
reason: format!("cannot persist cleanup proof: {err}"),
|
||||
});
|
||||
self.retry_signed_sync(peer, err);
|
||||
continue;
|
||||
}
|
||||
self.state = candidate;
|
||||
@@ -1440,14 +1484,16 @@ impl Runtime {
|
||||
self.dial_states.remove(&target);
|
||||
self.candidate_addrs.remove(&target);
|
||||
}
|
||||
changed = true;
|
||||
if let Some(target) = target {
|
||||
changed.push(SyncKey::Retirement(target));
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
if !changed.is_empty() {
|
||||
// A live target answers cleanup with a fresh claim; its identity
|
||||
// is still authenticated, and old hostname priority is not reused.
|
||||
self.ensure_own_claim().await;
|
||||
self.publish_allocations().await;
|
||||
self.broadcast_retirements();
|
||||
self.share_changes(changed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1494,7 +1540,7 @@ impl Runtime {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.broadcast_state();
|
||||
self.share_changes([SyncKey::Claim(self.local_id)]);
|
||||
}
|
||||
|
||||
fn update_vips(&self) {
|
||||
@@ -1583,25 +1629,21 @@ impl Runtime {
|
||||
.storage
|
||||
.put_vip_fields(
|
||||
self.network_id,
|
||||
snapshot.clone(),
|
||||
snapshot,
|
||||
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(),
|
||||
},
|
||||
);
|
||||
}
|
||||
self.share_changes([SyncKey::Vip(config.id)]);
|
||||
Ok(self.params.routes.vips.statuses(self.network_id))
|
||||
}
|
||||
async fn receive_vips(&mut self, entries: Vec<crate::vip::VipEntry>) -> Result<()> {
|
||||
async fn receive_vips(
|
||||
&mut self,
|
||||
peer: EndpointId,
|
||||
entries: Vec<crate::vip::VipEntry>,
|
||||
) -> Result<()> {
|
||||
let Some(id) = entries.first().map(|e| e.vip.clone()) else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -1623,14 +1665,21 @@ impl Runtime {
|
||||
(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
|
||||
if let Err(err) = self
|
||||
.params
|
||||
.storage
|
||||
.put_vip_fields(self.network_id, snapshot, counter)
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
self.retry_signed_sync(peer, err);
|
||||
return Ok(());
|
||||
}
|
||||
self.own_version = self.own_version.max(own_seen);
|
||||
self.params.vips = candidate;
|
||||
self.update_vips();
|
||||
self.broadcast_vips();
|
||||
if changed {
|
||||
self.share_changes([SyncKey::Vip(id)]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn validate_vip_frame(&self, entries: &[crate::vip::VipEntry]) -> Result<()> {
|
||||
@@ -1648,33 +1697,10 @@ impl Runtime {
|
||||
}
|
||||
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.
|
||||
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 {
|
||||
for (peer, entries) in std::mem::take(&mut self.pending_vips) {
|
||||
if let Err(err) = self.receive_vips(peer, entries).await {
|
||||
self.metrics.protocol_violations += 1;
|
||||
tracing::warn!(%err,"rejecting VIP snapshot");
|
||||
}
|
||||
@@ -1688,29 +1714,33 @@ impl Runtime {
|
||||
self.report_hostname_taken();
|
||||
}
|
||||
|
||||
/// Sends everything we know to every peer.
|
||||
fn broadcast_state(&mut self) {
|
||||
self.broadcast_vips();
|
||||
self.broadcast_retirements();
|
||||
let mut records = self.state.records();
|
||||
records.truncate(self.params.limits.max_state_records);
|
||||
if records.is_empty() {
|
||||
return;
|
||||
}
|
||||
let message = ControlMessage::State { records };
|
||||
let peers: Vec<EndpointId> = self.sessions.keys().copied().collect();
|
||||
for peer in peers {
|
||||
if let Err(err) = self.send_to(peer, message.clone()) {
|
||||
tracing::debug!(%err, "could not queue a state snapshot");
|
||||
}
|
||||
/// Reopening the affected reliable stream requests a full replay from
|
||||
/// this replica. A local write failure must not silently acknowledge it.
|
||||
fn retry_signed_sync(&self, peer: EndpointId, error: Error) {
|
||||
self.emit(Event::PluginError {
|
||||
network: self.network_id,
|
||||
protocol: "state".into(),
|
||||
reason: format!("cannot persist a signed update: {error}"),
|
||||
});
|
||||
if let Some(session) = self.sessions.get(&peer) {
|
||||
session
|
||||
.conn
|
||||
.close(1u32.into(), b"retry state synchronization");
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges a snapshot from a peer.
|
||||
async fn receive_state(&mut self, peer: EndpointId, records: Vec<SignedRecord>) {
|
||||
let before = self.state.records();
|
||||
let (outcomes, errors) = self.state.merge_all(self.network_id, records);
|
||||
|
||||
async fn receive_state(&mut self, peer: EndpointId, mut records: Vec<SignedRecord>) {
|
||||
// Older peers can send a full snapshot on someone else's update.
|
||||
// Exact copies of records already verified and committed are cheap.
|
||||
records.retain(|r| r.author_id().ok().and_then(|a| self.state.get(&a)) != Some(r));
|
||||
if records.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut authors: std::collections::BTreeSet<_> =
|
||||
records.iter().filter_map(|r| r.author_id().ok()).collect();
|
||||
let mut candidate = self.state.clone();
|
||||
let (outcomes, errors) = candidate.merge_all(self.network_id, records);
|
||||
for err in errors {
|
||||
self.metrics.protocol_violations += 1;
|
||||
self.emit(Event::ProtocolViolation {
|
||||
@@ -1719,43 +1749,30 @@ impl Runtime {
|
||||
reason: format!("unusable signed record: {err}"),
|
||||
});
|
||||
}
|
||||
for outcome in &outcomes {
|
||||
if *outcome == Merged::Conflicted {
|
||||
self.emit(Event::PluginError {
|
||||
network: self.network_id,
|
||||
protocol: "overlay".into(),
|
||||
reason: "two different records from one author at the same version; \
|
||||
a device key appears to be in use in two places"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
if outcomes.contains(&Merged::Conflicted) {
|
||||
self.emit(Event::PluginError {
|
||||
network: self.network_id,
|
||||
protocol: "overlay".into(),
|
||||
reason: "two different records from one author at the same version; a device key appears to be in use in two places".into(),
|
||||
});
|
||||
}
|
||||
|
||||
let changed = outcomes.iter().any(|outcome| {
|
||||
matches!(
|
||||
outcome,
|
||||
Merged::Added | Merged::Updated | Merged::Conflicted
|
||||
)
|
||||
});
|
||||
if !changed {
|
||||
authors.retain(|author| self.state.get(author) != candidate.get(author));
|
||||
if authors.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for record in self.state.records() {
|
||||
if record.author == *self.local_id.as_bytes() {
|
||||
continue;
|
||||
}
|
||||
if let Err(err) = self.params.storage.put_signed_record(record).await {
|
||||
tracing::debug!(%err, "cannot persist a record");
|
||||
for author in &authors {
|
||||
if *author != self.local_id
|
||||
&& let Some(record) = candidate.get(author)
|
||||
&& let Err(err) = self.params.storage.put_signed_record(record.clone()).await
|
||||
{
|
||||
self.retry_signed_sync(peer, err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Somebody may have taken the address we were using.
|
||||
self.state = candidate;
|
||||
self.share_changes(authors.into_iter().map(SyncKey::Claim));
|
||||
self.ensure_own_claim().await;
|
||||
self.publish_allocations().await;
|
||||
if self.state.records() != before {
|
||||
self.broadcast_state();
|
||||
}
|
||||
}
|
||||
|
||||
fn broadcast_policy(&self) -> crate::overlay::broadcast::BroadcastPolicy {
|
||||
@@ -1792,6 +1809,7 @@ impl Runtime {
|
||||
.routes
|
||||
.update_exit(self.network_id, |exit| exit.via = via);
|
||||
self.exit_via_was_online = via.is_some();
|
||||
self.params.roster_changed.send_replace(());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1836,6 +1854,7 @@ impl Runtime {
|
||||
return;
|
||||
}
|
||||
self.exit_via_was_online = online;
|
||||
self.params.roster_changed.send_replace(());
|
||||
if online {
|
||||
tracing::info!(
|
||||
network = %self.network_id,
|
||||
@@ -1908,6 +1927,7 @@ impl Runtime {
|
||||
}
|
||||
if self.published_range != Some(range) {
|
||||
self.published_range = Some(range);
|
||||
self.params.roster_changed.send_replace(());
|
||||
self.params.range_changed.send_replace(());
|
||||
}
|
||||
|
||||
@@ -2241,9 +2261,12 @@ impl Runtime {
|
||||
///
|
||||
/// A device told about one member ends up talking to all of them: a
|
||||
/// network is a mesh, and which member happened to be named on a
|
||||
/// command line should not decide who anybody talks to. Sent on every
|
||||
/// round, because it is cheap, bounded and self-repairing.
|
||||
/// command line should not decide who anybody talks to. A new stream or
|
||||
/// a changed, bounded address list is enough to update a replica.
|
||||
fn introduce_peers(&mut self) {
|
||||
if self.sessions.is_empty() || self.params.limits.max_state_records == 0 {
|
||||
return;
|
||||
}
|
||||
let mut hints: Vec<crate::proto::message::PeerHint> = Vec::new();
|
||||
|
||||
// What this agent can see for itself: where each peer it is
|
||||
@@ -2292,21 +2315,48 @@ impl Runtime {
|
||||
endpoint: *self.local_id.as_bytes(),
|
||||
addrs: hint_addrs(&self.underlay_addr(self.params.adapter.addr())),
|
||||
});
|
||||
hints.truncate(self.params.limits.max_state_records);
|
||||
if hints.is_empty() {
|
||||
return;
|
||||
hints.sort_unstable_by_key(|hint| hint.endpoint);
|
||||
if hints != self.introductions {
|
||||
let common = hints
|
||||
.iter()
|
||||
.zip(&self.introductions)
|
||||
.take_while(|(a, b)| a == b)
|
||||
.count();
|
||||
self.introductions = hints;
|
||||
for session in self.sessions.values_mut() {
|
||||
session.introductions_sent = session.introductions_sent.min(common);
|
||||
}
|
||||
}
|
||||
|
||||
let message = ControlMessage::Peers { peers: hints };
|
||||
let peers: Vec<EndpointId> = self.sessions.keys().copied().collect();
|
||||
for peer in peers {
|
||||
if let Err(err) = self.send_to(peer, message.clone()) {
|
||||
tracing::debug!(%err, "could not queue an introduction");
|
||||
use crate::proto::message::{MAX_HINT_ADDR_LEN, MAX_HINT_ADDRS};
|
||||
let max_hint_size = 40 + MAX_HINT_ADDRS * (MAX_HINT_ADDR_LEN + 2);
|
||||
let limits = &self.params.limits;
|
||||
let batch = (limits.max_frame_len.saturating_sub(128) / max_hint_size)
|
||||
.max(1)
|
||||
.min(limits.max_state_records);
|
||||
let pending: Vec<_> = self
|
||||
.sessions
|
||||
.values()
|
||||
.filter(|s| s.introductions_sent < self.introductions.len())
|
||||
.map(|s| (s.peer, s.introductions_sent))
|
||||
.collect();
|
||||
for (peer, mut start) in pending {
|
||||
while start < self.introductions.len() {
|
||||
let end = (start + batch).min(self.introductions.len());
|
||||
let message = ControlMessage::Peers {
|
||||
peers: self.introductions[start..end].to_vec(),
|
||||
};
|
||||
if self.send_to(peer, message).is_err() {
|
||||
break;
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
session.introductions_sent = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes only locally observed, protocol-specific transport edges.
|
||||
/// Publish changed edges immediately and refresh soft state before peers expire it.
|
||||
fn announce_reach(&mut self, force: bool) {
|
||||
let live: HashSet<_> = self
|
||||
.links
|
||||
@@ -2319,18 +2369,33 @@ impl Runtime {
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
if !force && live == self.announced_reach {
|
||||
if force || live != self.announced_reach {
|
||||
self.announced_reach = live;
|
||||
for session in self.sessions.values_mut() {
|
||||
session.reach_sent = None;
|
||||
}
|
||||
}
|
||||
let pending: Vec<_> = self
|
||||
.sessions
|
||||
.values()
|
||||
.filter(|s| {
|
||||
s.reach_sent
|
||||
.is_none_or(|last| last.elapsed() >= REACH_EXPIRY / 3)
|
||||
})
|
||||
.map(|s| s.peer)
|
||||
.collect();
|
||||
if pending.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.announced_reach = live.clone();
|
||||
let mut links: Vec<_> = live.into_iter().collect();
|
||||
let mut links: Vec<_> = self.announced_reach.iter().cloned().collect();
|
||||
links.sort_by(|a, b| (&a.protocol, a.peer).cmp(&(&b.protocol, b.peer)));
|
||||
links.truncate(self.params.limits.max_state_records);
|
||||
let message = ControlMessage::Reachable { links };
|
||||
let peers: Vec<_> = self.sessions.keys().copied().collect();
|
||||
for peer in peers {
|
||||
if let Err(err) = self.send_to(peer, message.clone()) {
|
||||
tracing::debug!(%err, "could not queue a reachability announcement");
|
||||
for peer in pending {
|
||||
if self.send_to(peer, message.clone()).is_ok()
|
||||
&& let Some(s) = self.sessions.get_mut(&peer)
|
||||
{
|
||||
s.reach_sent = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2555,8 +2620,6 @@ impl Runtime {
|
||||
/// Drops every link to a peer.
|
||||
fn drop_links_for(&mut self, peer: EndpointId) {
|
||||
self.tunnel_errors.remove(&peer);
|
||||
self.retirement_cursor.remove(&peer);
|
||||
self.vip_cursor.remove(&peer);
|
||||
self.reset_peer_data(peer, "peer session ended");
|
||||
if let Some(tunnel) = &self.params.tunnel {
|
||||
tunnel.on_peer_gone(self.network_id, peer);
|
||||
@@ -2639,6 +2702,9 @@ impl Runtime {
|
||||
return;
|
||||
}
|
||||
if let Some(old) = self.sessions.remove(&peer) {
|
||||
if let Some(inner) = self.params.agent.upgrade() {
|
||||
inner.speed.disconnected(self.network_id, peer);
|
||||
}
|
||||
old.abort();
|
||||
old.conn
|
||||
.close(0u32.into(), b"replaced by preferred session");
|
||||
@@ -2676,8 +2742,11 @@ impl Runtime {
|
||||
tracing::debug!(%err, "could not queue initial announcement");
|
||||
}
|
||||
|
||||
self.broadcast_state();
|
||||
self.flush_peer(peer);
|
||||
self.introduce_peers();
|
||||
self.announce_reach(false);
|
||||
|
||||
self.params.roster_changed.send_replace(());
|
||||
self.emit(Event::PeerConnected {
|
||||
network: self.network_id,
|
||||
peer,
|
||||
@@ -2724,6 +2793,12 @@ impl Runtime {
|
||||
if self.params.carriers.len() > 1 {
|
||||
capabilities.push(selection::capability());
|
||||
}
|
||||
if self.params.interface.is_some()
|
||||
&& self.params.tunnel.is_some()
|
||||
&& !self.params.carriers.is_empty()
|
||||
{
|
||||
capabilities.push(super::speed::capability());
|
||||
}
|
||||
capabilities.truncate(self.params.limits.max_capabilities);
|
||||
self.local_capabilities = capabilities
|
||||
.iter()
|
||||
@@ -2739,6 +2814,7 @@ impl Runtime {
|
||||
exit_node,
|
||||
hostname: self.params.hostname.clone(),
|
||||
capabilities,
|
||||
agent_version: Some(env!("CARGO_PKG_VERSION").to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2772,6 +2848,12 @@ impl Runtime {
|
||||
if current != Some(session_id) {
|
||||
return;
|
||||
}
|
||||
self.params.routes.traffic.control(
|
||||
self.network_id,
|
||||
peer,
|
||||
crate::traffic::Direction::Rx,
|
||||
bytes as u64,
|
||||
);
|
||||
self.metrics.control_messages_received += 1;
|
||||
self.metrics.control_bytes_received += bytes as u64;
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
@@ -2799,13 +2881,21 @@ impl Runtime {
|
||||
SessionEvent::Closed {
|
||||
session_id,
|
||||
peer,
|
||||
reason,
|
||||
mut reason,
|
||||
} => {
|
||||
let current = self.sessions.get(&peer).map(|session| session.id);
|
||||
if current != Some(session_id) {
|
||||
return;
|
||||
}
|
||||
if let Some(inner) = self.params.agent.upgrade() {
|
||||
inner.speed.disconnected(self.network_id, peer);
|
||||
}
|
||||
if let Some(session) = self.sessions.remove(&peer) {
|
||||
// Read the cause before local cleanup closes a still-open connection.
|
||||
if let Some(cause) = session.conn.close_reason() {
|
||||
reason =
|
||||
format!("{reason} ({})", super::session::describe_quic_close(cause));
|
||||
}
|
||||
session.abort();
|
||||
session.conn.close(0u32.into(), b"session ended");
|
||||
}
|
||||
@@ -2826,9 +2916,16 @@ impl Runtime {
|
||||
.or_insert_with(|| DialState::new(CandidateSource::Discovery));
|
||||
state.in_flight = false;
|
||||
state.next_attempt = Instant::now() + policy.initial_delay;
|
||||
self.params.roster_changed.send_replace(());
|
||||
self.emit(Event::PeerDisconnected {
|
||||
network: self.network_id,
|
||||
network_name: self.params.keys.name().clone(),
|
||||
peer,
|
||||
hostname: self
|
||||
.known_hostnames
|
||||
.get(&peer)
|
||||
.cloned()
|
||||
.or_else(|| self.state.hostname_of(&peer).map(str::to_owned)),
|
||||
reason,
|
||||
});
|
||||
}
|
||||
@@ -2849,6 +2946,7 @@ impl Runtime {
|
||||
return;
|
||||
}
|
||||
self.known_hostnames.insert(peer, hostname.to_string());
|
||||
self.params.roster_changed.send_replace(());
|
||||
let storage = self.params.storage.clone();
|
||||
let network_id = self.network_id;
|
||||
let hostname = hostname.to_string();
|
||||
@@ -2865,6 +2963,25 @@ impl Runtime {
|
||||
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
|
||||
match &message {
|
||||
ControlMessage::Transport { protocol, payload } => {
|
||||
if protocol == tsunagi_speedtest::PROTOCOL {
|
||||
if super::speed::supported(&self.local_capabilities)
|
||||
&& let Some(session) = self.sessions.get(&peer)
|
||||
&& super::speed::supported(&session.capabilities)
|
||||
&& let Some(message) =
|
||||
tsunagi_speedtest::Control::decode(payload.as_bytes())
|
||||
&& let Some(inner) = self.params.agent.upgrade()
|
||||
&& let Some(reply) = super::speed::receive_control(
|
||||
&inner,
|
||||
self.network_id,
|
||||
peer,
|
||||
message,
|
||||
|| snapshot_connection(&session.conn).rtt,
|
||||
)
|
||||
{
|
||||
let _ = self.send_to(peer, reply);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if protocol == selection::PROTOCOL {
|
||||
self.receive_choice(peer, payload.as_bytes());
|
||||
return;
|
||||
@@ -2917,7 +3034,7 @@ impl Runtime {
|
||||
let changed = self.sessions.get(&peer).is_some_and(|session| {
|
||||
let selection = |caps: &[PluginCapability]| {
|
||||
caps.iter()
|
||||
.filter(|c| c.enabled)
|
||||
.filter(|c| c.enabled && c.protocol != tsunagi_speedtest::PROTOCOL)
|
||||
.map(|c| (c.protocol.clone(), c.version))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
@@ -2928,8 +3045,14 @@ impl Runtime {
|
||||
}
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
session.hostname = Some(announcement.hostname.clone());
|
||||
session
|
||||
.agent_version
|
||||
.clone_from(&announcement.agent_version);
|
||||
session.broadcast = announcement.broadcast;
|
||||
session.exit_node = announcement.exit_node;
|
||||
if session.exit_node != announcement.exit_node {
|
||||
session.exit_node = announcement.exit_node;
|
||||
self.params.roster_changed.send_replace(());
|
||||
}
|
||||
session.capabilities = capabilities.clone();
|
||||
}
|
||||
self.remember_hostname(peer, &announcement.hostname);
|
||||
@@ -2949,7 +3072,7 @@ impl Runtime {
|
||||
tracing::debug!(%err, "could not queue pong");
|
||||
}
|
||||
}
|
||||
ControlMessage::Vips { entries } => self.pending_vips.push(entries.clone()),
|
||||
ControlMessage::Vips { entries } => self.pending_vips.push((peer, entries.clone())),
|
||||
ControlMessage::State { records } => {
|
||||
self.pending_state.push((peer, records.clone()));
|
||||
}
|
||||
@@ -2963,6 +3086,7 @@ impl Runtime {
|
||||
let learned = self.learn_peers(peers);
|
||||
if learned > 0 {
|
||||
self.start_dials();
|
||||
self.introduce_peers();
|
||||
}
|
||||
}
|
||||
// What that peer can reach, from that peer. Kept with the time
|
||||
@@ -3116,7 +3240,12 @@ impl Runtime {
|
||||
|
||||
fn data_error(&self, session: &Session) -> Option<String> {
|
||||
if self.params.carriers.is_empty() {
|
||||
return Some("data transports disabled locally".into());
|
||||
return Some(super::DATA_DISABLED.into());
|
||||
}
|
||||
// Capabilities arrive in the first authenticated announcement, after
|
||||
// the session is already visible in status.
|
||||
if session.hostname.is_none() {
|
||||
return Some(super::DATA_CONNECTING.into());
|
||||
}
|
||||
if self.params.tunnel.is_some() && self.tunnel_protocol(session).is_none() {
|
||||
return Some(
|
||||
@@ -3164,7 +3293,7 @@ impl Runtime {
|
||||
self.data_errors
|
||||
.get(&session.peer)
|
||||
.cloned()
|
||||
.or_else(|| Some("establishing external data transport".into()))
|
||||
.or_else(|| Some(super::DATA_CONNECTING.into()))
|
||||
}
|
||||
|
||||
fn status(&self) -> NetworkStatus {
|
||||
@@ -3189,6 +3318,7 @@ impl Runtime {
|
||||
exit_node: session.exit_node,
|
||||
endpoint_id: session.peer,
|
||||
role: session.role,
|
||||
agent_version: session.agent_version.clone(),
|
||||
hostname: session
|
||||
.hostname
|
||||
.clone()
|
||||
@@ -3265,6 +3395,18 @@ impl Runtime {
|
||||
|
||||
let exit = self.exit_policy();
|
||||
NetworkStatus {
|
||||
speed: self
|
||||
.params
|
||||
.agent
|
||||
.upgrade()
|
||||
.map(|inner| {
|
||||
inner.speed.report(
|
||||
self.network_id,
|
||||
&peers,
|
||||
super::speed::supported(&self.local_capabilities),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
vips: self.params.routes.vips.statuses(self.network_id),
|
||||
protocols: self
|
||||
.params
|
||||
@@ -3277,6 +3419,12 @@ impl Runtime {
|
||||
exit_offer: exit.offer,
|
||||
exit_via: exit.via,
|
||||
exit_via_online: exit.via.is_some_and(|via| self.exit_node_online(via)),
|
||||
exit_traffic: self
|
||||
.params
|
||||
.interface
|
||||
.as_ref()
|
||||
.and(exit.via)
|
||||
.and_then(|peer| self.params.routes.exit_traffic(self.network_id, peer)),
|
||||
exit_rules: self
|
||||
.params
|
||||
.interface
|
||||
@@ -3434,6 +3582,28 @@ mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn verified_reconnect_paths_expire_and_are_replaced_without_admitting_candidates() {
|
||||
let peer = crate::identity::DeviceIdentity::generate().endpoint_id();
|
||||
let addr = |last| PathAddr::Ip(([192, 0, 2, last], 7777).into());
|
||||
let now = Instant::now();
|
||||
let mut paths = VerifiedUnderlay::default();
|
||||
paths.record(peer, [addr(1), addr(2)], now, 1);
|
||||
assert_eq!(paths.peers[&peer].1, [addr(1)]);
|
||||
paths.record(peer, [addr(3)], now, 1);
|
||||
paths.prune(now + Duration::from_secs(30), 1, |_| false);
|
||||
assert_eq!(paths.peers[&peer].1, [addr(3)]);
|
||||
let other = crate::identity::DeviceIdentity::generate().endpoint_id();
|
||||
paths.record(other, [addr(4)], now + Duration::from_secs(31), 1);
|
||||
paths.prune(now + Duration::from_secs(32), 1, |_| false);
|
||||
assert!(!paths.peers.contains_key(&peer));
|
||||
paths.prune(now + Duration::from_secs(32), 1, |p| p == other);
|
||||
assert!(paths.peers.is_empty());
|
||||
paths.record(peer, [addr(5)], now, 1);
|
||||
paths.prune(now + Duration::from_secs(121), 1, |_| false);
|
||||
assert!(paths.peers.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn underlay_hints_exclude_overlay_subnets_but_preserve_lan_and_relay_candidates() {
|
||||
let peer = crate::identity::DeviceIdentity::generate().endpoint_id();
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Each ordered stream keeps a cursor into the latest signed state. A slow or
|
||||
//! reconnecting peer can catch up without a per-peer backlog of signed frames.
|
||||
use super::{ControlMessage, EndpointId, MAX_RETIREMENT_LEN, Runtime};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
|
||||
/// The stable identity of a signed object, including tombstones.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum SyncKey {
|
||||
Claim(EndpointId),
|
||||
Retirement(EndpointId),
|
||||
Vip(String),
|
||||
}
|
||||
|
||||
/// One entry per stored object, regardless of its edit count or the number of
|
||||
/// peers. Revisions are local scheduling information, never persisted or sent.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Changes {
|
||||
latest: u64,
|
||||
revisions: BTreeMap<SyncKey, u64>,
|
||||
order: BTreeMap<u64, SyncKey>,
|
||||
}
|
||||
|
||||
impl Changes {
|
||||
fn note(&mut self, key: SyncKey) {
|
||||
self.latest += 1;
|
||||
if let Some(previous) = self.revisions.insert(key.clone(), self.latest) {
|
||||
self.order.remove(&previous);
|
||||
}
|
||||
self.order.insert(self.latest, key);
|
||||
}
|
||||
|
||||
fn after(&self, cursor: u64) -> impl Iterator<Item = (u64, &SyncKey)> {
|
||||
self.order
|
||||
.range((Excluded(cursor), Unbounded))
|
||||
.map(|(&revision, key)| (revision, key))
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
pub(super) fn index_stored_state(&mut self) {
|
||||
for record in self.state.records() {
|
||||
if let Ok(author) = record.author_id() {
|
||||
self.changes.note(SyncKey::Claim(author));
|
||||
}
|
||||
}
|
||||
for marker in self.state.retirements() {
|
||||
if let Ok(target) = marker.target.author_id() {
|
||||
self.changes.note(SyncKey::Retirement(target));
|
||||
}
|
||||
}
|
||||
for id in self.params.vips.ids() {
|
||||
self.changes.note(SyncKey::Vip(id));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn share_changes(&mut self, keys: impl IntoIterator<Item = SyncKey>) -> usize {
|
||||
for key in keys {
|
||||
self.changes.note(key);
|
||||
}
|
||||
self.params.roster_changed.send_replace(());
|
||||
self.flush_updates();
|
||||
self.sessions
|
||||
.values()
|
||||
.filter(|session| session.state_sent == self.changes.latest)
|
||||
.count()
|
||||
}
|
||||
|
||||
pub(super) fn flush_updates(&mut self) {
|
||||
let peers: Vec<_> = self
|
||||
.sessions
|
||||
.values()
|
||||
.filter(|s| s.state_sent < self.changes.latest)
|
||||
.map(|s| s.peer)
|
||||
.collect();
|
||||
for peer in peers {
|
||||
self.flush_peer(peer);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn flush_peer(&mut self, peer: EndpointId) {
|
||||
// A retirement contains a signed claim plus a second signature, so its
|
||||
// size bound also covers a claim. VIPs are validated as complete frames.
|
||||
let limits = &self.params.limits;
|
||||
let batch = (limits.max_frame_len.saturating_sub(128) / MAX_RETIREMENT_LEN)
|
||||
.max(1)
|
||||
.min(limits.max_state_records.max(1));
|
||||
while let Some(session) = self.sessions.get(&peer) {
|
||||
if session.outbound.capacity() == 0 {
|
||||
break;
|
||||
}
|
||||
let cursor = session.state_sent;
|
||||
let Some((mut through, first)) = self.changes.after(cursor).next() else {
|
||||
break;
|
||||
};
|
||||
let message = {
|
||||
let pending = self.changes.after(cursor).take(batch);
|
||||
match first {
|
||||
SyncKey::Claim(_) => ControlMessage::State {
|
||||
records: pending
|
||||
.map_while(|(revision, key)| {
|
||||
let SyncKey::Claim(id) = key else { return None };
|
||||
through = revision;
|
||||
self.state.get(id).cloned()
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
SyncKey::Retirement(_) => ControlMessage::Retirements {
|
||||
markers: pending
|
||||
.map_while(|(revision, key)| {
|
||||
let SyncKey::Retirement(id) = key else {
|
||||
return None;
|
||||
};
|
||||
through = revision;
|
||||
self.state.retirement_of(id).cloned()
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
SyncKey::Vip(id) => ControlMessage::Vips {
|
||||
entries: self.params.vips.entries(id),
|
||||
},
|
||||
}
|
||||
};
|
||||
if self.send_to(peer, message).is_err() {
|
||||
break;
|
||||
}
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
session.state_sent = through;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn slow_and_returning_sessions_each_get_the_latest_revision() {
|
||||
let mut index = Changes::default();
|
||||
let first = SyncKey::Vip("first".into());
|
||||
let second = SyncKey::Vip("second".into());
|
||||
index.note(first.clone());
|
||||
let sent = index.latest;
|
||||
index.note(second.clone());
|
||||
index.note(first.clone());
|
||||
for cursor in [0, sent] {
|
||||
let pending: Vec<_> = index.after(cursor).map(|(_, key)| key.clone()).collect();
|
||||
assert_eq!(pending, [second.clone(), first.clone()]);
|
||||
}
|
||||
assert_eq!(index.after(index.latest).count(), 0);
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use iroh::EndpointId;
|
||||
use iroh::endpoint::{Connection, RecvStream, SendStream};
|
||||
use iroh::endpoint::{Connection, ConnectionError, RecvStream, SendStream};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
@@ -60,6 +60,22 @@ pub(crate) enum SessionEvent {
|
||||
},
|
||||
}
|
||||
|
||||
/// The transport category and code are useful in logs. Remote close text is
|
||||
/// arbitrary peer-supplied data and may contain secrets or control characters.
|
||||
pub(super) fn describe_quic_close(cause: ConnectionError) -> String {
|
||||
match cause {
|
||||
ConnectionError::ApplicationClosed(close) => {
|
||||
format!("QUIC closed by peer, application code {}", close.error_code)
|
||||
}
|
||||
ConnectionError::ConnectionClosed(close) => {
|
||||
format!("QUIC closed by peer, transport code {}", close.error_code)
|
||||
}
|
||||
ConnectionError::TransportError(error) => format!("QUIC transport error {}", error.code),
|
||||
ConnectionError::LocallyClosed => "QUIC closed locally".to_owned(),
|
||||
other => format!("QUIC: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A live session, as held by the network runtime.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Session {
|
||||
@@ -68,10 +84,15 @@ pub(crate) struct Session {
|
||||
pub(crate) role: Role,
|
||||
pub(crate) established: Instant,
|
||||
pub(crate) conn: Connection,
|
||||
/// Already encoded frame payloads, so the runtime can account for the exact
|
||||
/// number of control bytes it queues.
|
||||
/// Last signed-state revision queued on this ordered stream.
|
||||
pub(super) state_sent: u64,
|
||||
/// Prefix of the current introduction list already queued on this stream.
|
||||
pub(super) introductions_sent: usize,
|
||||
pub(super) reach_sent: Option<Instant>,
|
||||
/// Already encoded frames, accounted for when queued.
|
||||
pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>,
|
||||
pub(crate) hostname: Option<String>,
|
||||
pub(crate) agent_version: Option<String>,
|
||||
pub(crate) capabilities: Vec<PluginCapability>,
|
||||
pub(crate) broadcast: bool,
|
||||
/// The peer offers itself as an exit node in this network.
|
||||
@@ -227,7 +248,11 @@ pub(crate) fn spawn(
|
||||
established: Instant::now(),
|
||||
conn,
|
||||
outbound: outbound_tx,
|
||||
state_sent: 0,
|
||||
introductions_sent: 0,
|
||||
reach_sent: None,
|
||||
hostname: None,
|
||||
agent_version: None,
|
||||
capabilities: Vec::new(),
|
||||
broadcast: false,
|
||||
exit_node: false,
|
||||
|
||||
@@ -0,0 +1,606 @@
|
||||
//! Local ownership of one bounded throughput diagnostic. Control carries
|
||||
//! negotiation and receiver feedback. Every data packet uses the current cipher and carrier.
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, Weak};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use bytes::Bytes;
|
||||
use iroh::EndpointId;
|
||||
use tsunagi_speedtest as wire;
|
||||
|
||||
use super::{Agent, DataPath, Inner, PeerStatus};
|
||||
use crate::dataplane::PluginCapability;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::NetworkId;
|
||||
use crate::ipc::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
|
||||
use crate::overlay::router::DiagnosticPeer;
|
||||
use crate::proto::message::{ControlMessage, TransportPayload};
|
||||
|
||||
type Key = (NetworkId, EndpointId);
|
||||
|
||||
/// A batch can spend at most this many IPv4 bytes in *each* direction.
|
||||
/// Every remaining peer gets an equal reservation even when earlier probes are lost.
|
||||
const BATCH_BYTES: u32 = 128 * 1024 * 1024;
|
||||
const METERED_BATCH_BYTES: u32 = 16 * 1024 * 1024;
|
||||
|
||||
pub(super) fn capability() -> PluginCapability {
|
||||
PluginCapability {
|
||||
protocol: wire::PROTOCOL.into(),
|
||||
version: wire::VERSION,
|
||||
enabled: true,
|
||||
data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn supported(caps: &[PluginCapability]) -> bool {
|
||||
caps.iter()
|
||||
.any(|c| c.enabled && c.protocol == wire::PROTOCOL && c.version == wire::VERSION)
|
||||
}
|
||||
|
||||
fn envelope(message: &wire::Control) -> Option<ControlMessage> {
|
||||
Some(ControlMessage::Transport {
|
||||
protocol: wire::PROTOCOL.into(),
|
||||
payload: TransportPayload::new(message.encode().ok()?),
|
||||
})
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
}
|
||||
|
||||
struct Channel {
|
||||
key: Key,
|
||||
id: u64,
|
||||
limit: u32,
|
||||
addresses: DiagnosticPeer,
|
||||
handle: wire::Handle,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
generation: u64,
|
||||
network: NetworkId,
|
||||
batch: Option<SpeedBatchReport>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Jobs {
|
||||
job: Option<Job>,
|
||||
history: BTreeMap<Key, SpeedPeerReport>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SpeedTests {
|
||||
// Admission, completion and cancellation serialize here. Decrypted packets
|
||||
// only read the active channel and its receiver counter.
|
||||
jobs: Mutex<Jobs>,
|
||||
active: ArcSwapOption<Channel>,
|
||||
metered: AtomicBool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for SpeedTests {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SpeedTests").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl SpeedTests {
|
||||
fn lock(&self) -> MutexGuard<'_, Jobs> {
|
||||
self.jobs.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn clear_channel(&self, key: Key, id: u64) {
|
||||
// Called with the jobs lock held so an old task cannot clear its successor.
|
||||
if self
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.key == key && c.id == id)
|
||||
{
|
||||
self.active.store(None);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn report(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peers: &[PeerStatus],
|
||||
enabled: bool,
|
||||
) -> SpeedReport {
|
||||
let jobs = self.lock();
|
||||
SpeedReport {
|
||||
batch: jobs
|
||||
.job
|
||||
.as_ref()
|
||||
.filter(|j| j.network == network)
|
||||
.and_then(|j| j.batch),
|
||||
peers: jobs
|
||||
.history
|
||||
.iter()
|
||||
.filter(|((net, _), _)| *net == network)
|
||||
.map(|((_, peer), report)| (peer.to_string(), report.clone()))
|
||||
.collect(),
|
||||
capable: peers
|
||||
.iter()
|
||||
.filter(|p| enabled && supported(&p.capabilities))
|
||||
.map(|p| p.endpoint_id.to_string())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn disconnected(&self, network: NetworkId, peer: EndpointId) {
|
||||
if let Some(c) = self
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.key == (network, peer))
|
||||
{
|
||||
c.handle.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_locked(&self, jobs: &mut Jobs, network: NetworkId) {
|
||||
if let Some(c) = self.active.load().as_ref().filter(|c| c.key.0 == network) {
|
||||
c.handle.cancel();
|
||||
}
|
||||
if jobs.job.as_ref().is_some_and(|job| job.network == network) {
|
||||
jobs.job = None;
|
||||
for ((net, _), report) in &mut jobs.history {
|
||||
if *net == network
|
||||
&& matches!(
|
||||
report.phase,
|
||||
SpeedPhase::Queued
|
||||
| SpeedPhase::Preparing
|
||||
| SpeedPhase::Download
|
||||
| SpeedPhase::Upload
|
||||
)
|
||||
{
|
||||
match report.phase {
|
||||
SpeedPhase::Download => report.down = None,
|
||||
SpeedPhase::Upload => report.up = None,
|
||||
_ => {}
|
||||
}
|
||||
report.phase = SpeedPhase::Cancelled;
|
||||
report.measured_at_unix_secs = now();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn remove_network(&self, network: NetworkId) {
|
||||
let mut jobs = self.lock();
|
||||
self.cancel_locked(&mut jobs, network);
|
||||
jobs.history.retain(|(net, _), _| *net != network);
|
||||
}
|
||||
|
||||
pub(super) fn shutdown(&self) {
|
||||
let mut jobs = self.lock();
|
||||
jobs.job = None;
|
||||
if let Some(channel) = self.active.swap(None) {
|
||||
channel.handle.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognized probe frames never go to a host socket. Admission is stricter
|
||||
/// than exit traffic: both addresses must be the current signed overlay pair.
|
||||
pub(super) fn receive_packet(
|
||||
inner: &Inner,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
packet: &[u8],
|
||||
) -> bool {
|
||||
if !wire::is_test_packet(packet) {
|
||||
return false;
|
||||
}
|
||||
if let Some(channel) = inner.speed.active.load().as_ref()
|
||||
&& channel.key == (network, peer)
|
||||
&& let Some(data) = wire::decode_packet(packet)
|
||||
&& data.id == channel.id
|
||||
&& (data.destination, data.source) == (channel.addresses.local, channel.addresses.remote)
|
||||
&& channel.addresses.is_current(&inner.routes)
|
||||
{
|
||||
inner
|
||||
.routes
|
||||
.traffic
|
||||
.packet(network, peer, crate::traffic::Direction::Rx, packet, || {
|
||||
crate::traffic::Role::SpeedTest
|
||||
})
|
||||
.record();
|
||||
channel.handle.data(data);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn config(
|
||||
inner: &Inner,
|
||||
key: Key,
|
||||
id: u64,
|
||||
bytes: u32,
|
||||
rtt: Option<Duration>,
|
||||
) -> Option<(wire::Config, DiagnosticPeer)> {
|
||||
let addresses = inner.routes.diagnostic_peer(key.0, key.1)?;
|
||||
let ceiling = if inner.speed.metered.load(Ordering::Relaxed) {
|
||||
wire::METERED_BYTES
|
||||
} else {
|
||||
wire::NORMAL_BYTES
|
||||
};
|
||||
let cfg = wire::Config {
|
||||
id,
|
||||
local: addresses.local,
|
||||
remote: addresses.remote,
|
||||
mtu: u16::try_from(inner.config.interface_mtu).unwrap_or(u16::MAX),
|
||||
byte_limit: bytes.min(ceiling),
|
||||
rtt: rtt.unwrap_or(Duration::from_millis(100)),
|
||||
};
|
||||
Some((cfg, addresses))
|
||||
}
|
||||
|
||||
pub(super) fn receive_control(
|
||||
inner: &Arc<Inner>,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
message: wire::Control,
|
||||
rtt: impl FnOnce() -> Option<Duration>,
|
||||
) -> Option<ControlMessage> {
|
||||
let key = (network, peer);
|
||||
let id = message.id();
|
||||
if let wire::Control::Start(request) = message {
|
||||
let jobs = inner.speed.lock();
|
||||
if inner.shutdown.is_triggered()
|
||||
|| jobs.job.is_some()
|
||||
|| inner.speed.active.load().is_some()
|
||||
{
|
||||
return envelope(&wire::Control::Busy { id });
|
||||
}
|
||||
let (cfg, addresses) = config(inner, key, id, request.byte_limit, rtt())?;
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::respond(cfg, request);
|
||||
inner.speed.active.store(Some(Arc::new(Channel {
|
||||
key,
|
||||
id,
|
||||
limit,
|
||||
addresses,
|
||||
handle,
|
||||
})));
|
||||
drop(jobs);
|
||||
let io = TestIo::new(inner, key, None);
|
||||
tokio::spawn(async move {
|
||||
let owner = io.inner.clone();
|
||||
session.run(io).await;
|
||||
if let Some(inner) = owner.upgrade() {
|
||||
let _guard = inner.speed.lock();
|
||||
inner.speed.clear_channel(key, id);
|
||||
}
|
||||
});
|
||||
} else if let Some(c) = inner
|
||||
.speed
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.key == key && c.id == id)
|
||||
{
|
||||
c.handle.control(message);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
struct TestIo {
|
||||
inner: Weak<Inner>,
|
||||
key: Key,
|
||||
generation: Option<u64>,
|
||||
started: Instant,
|
||||
}
|
||||
|
||||
impl TestIo {
|
||||
fn new(inner: &Arc<Inner>, key: Key, generation: Option<u64>) -> Self {
|
||||
Self {
|
||||
inner: Arc::downgrade(inner),
|
||||
key,
|
||||
generation,
|
||||
started: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl wire::Io for TestIo {
|
||||
async fn control(&self, message: wire::Control) -> bool {
|
||||
let (Some(inner), Some(message)) = (self.inner.upgrade(), envelope(&message)) else {
|
||||
return false;
|
||||
};
|
||||
Agent { inner }
|
||||
.send(self.key.0, self.key.1, message)
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
self.inner.upgrade().is_some_and(|inner| {
|
||||
let observation = inner.routes.traffic.packet(
|
||||
self.key.0,
|
||||
self.key.1,
|
||||
crate::traffic::Direction::Tx,
|
||||
&packet,
|
||||
|| crate::traffic::Role::SpeedTest,
|
||||
);
|
||||
let sent = inner
|
||||
.config
|
||||
.tunnel
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.carry(self.key.0, self.key.1, packet));
|
||||
if sent {
|
||||
observation.record();
|
||||
}
|
||||
sent
|
||||
})
|
||||
}
|
||||
|
||||
fn progress(&self, update: wire::Progress) {
|
||||
if !matches!(
|
||||
update.state,
|
||||
wire::State::Starting | wire::State::Download | wire::State::Upload
|
||||
) {
|
||||
return; // Publish terminal results together with releasing the slot.
|
||||
}
|
||||
if let Some(generation) = self.generation
|
||||
&& let Some(inner) = self.inner.upgrade()
|
||||
{
|
||||
let mut jobs = inner.speed.lock();
|
||||
if jobs
|
||||
.job
|
||||
.as_ref()
|
||||
.is_some_and(|j| j.generation == generation)
|
||||
&& let Some(report) = jobs.history.get_mut(&self.key)
|
||||
{
|
||||
update_report(report, update, self.started);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_report(report: &mut SpeedPeerReport, progress: wire::Progress, started: Instant) {
|
||||
let live = matches!(progress.state, wire::State::Download | wire::State::Upload);
|
||||
let rate = |reading: wire::Reading| {
|
||||
reading
|
||||
.bps
|
||||
.filter(|_| match reading.quality {
|
||||
wire::Quality::Measured | wire::Quality::AtLeast => true,
|
||||
wire::Quality::Measuring => live,
|
||||
wire::Quality::Insufficient => false,
|
||||
})
|
||||
.map(|bps| SpeedRate {
|
||||
bps,
|
||||
lower_bound: reading.quality == wire::Quality::AtLeast,
|
||||
})
|
||||
};
|
||||
report.down = rate(progress.down);
|
||||
report.up = rate(progress.up);
|
||||
report.bytes = u64::from(progress.down.bytes) + u64::from(progress.up.bytes);
|
||||
report.elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
report.measured_at_unix_secs = now();
|
||||
report.phase = match progress.state {
|
||||
wire::State::Starting => SpeedPhase::Preparing,
|
||||
wire::State::Download => SpeedPhase::Download,
|
||||
wire::State::Upload => SpeedPhase::Upload,
|
||||
wire::State::Complete if report.down.is_some() || report.up.is_some() => SpeedPhase::Done,
|
||||
wire::State::Complete => SpeedPhase::Failed("Insufficient data for a reliable rate".into()),
|
||||
wire::State::Busy => SpeedPhase::Failed("Peer is already running a speed test".into()),
|
||||
wire::State::TimedOut => {
|
||||
SpeedPhase::Failed("Peer did not finish the speed test in time".into())
|
||||
}
|
||||
wire::State::Cancelled => SpeedPhase::Cancelled,
|
||||
wire::State::Failed => {
|
||||
SpeedPhase::Failed("The data path could not complete the speed test".into())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn describe_path(peer: &PeerStatus) -> Option<String> {
|
||||
match &peer.data_path {
|
||||
DataPath::None => None,
|
||||
DataPath::Direct { transport } => Some(match &peer.data_transport_detail {
|
||||
Some(detail) => format!("{transport} · {detail}"),
|
||||
None => transport.clone(),
|
||||
}),
|
||||
DataPath::Relayed { hops, via } => Some(format!("{hops} hops via {}", via.fmt_short())),
|
||||
}
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
/// Runs one peer diagnostic, or sequentially tests the capable exit nodes in the network.
|
||||
pub async fn start_speed_test(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: Option<EndpointId>,
|
||||
metered: bool,
|
||||
) -> Result<()> {
|
||||
let status = self.network_status(network).await?;
|
||||
let targets: Vec<_> = status
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
peer.map_or(p.exit_node, |selected| p.endpoint_id == selected)
|
||||
&& status.speed.capable.contains(&p.endpoint_id.to_string())
|
||||
})
|
||||
.map(|p| p.endpoint_id)
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return Err(Error::SpeedTest(
|
||||
if peer.is_some() {
|
||||
"Peer is offline or does not support this speed-test version"
|
||||
} else {
|
||||
"No online exit nodes support speed tests in this network"
|
||||
}
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let cap = self.inner.limits.max_speed_results;
|
||||
if targets.len() > cap {
|
||||
return Err(Error::SpeedTest("Too many peers for one test batch".into()));
|
||||
}
|
||||
let generation = rand::random();
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
if self.inner.shutdown.is_triggered() {
|
||||
return Err(Error::Stopped);
|
||||
}
|
||||
if jobs.job.is_some() || self.inner.speed.active.load().is_some() {
|
||||
return Err(Error::SpeedTest(
|
||||
"Another speed test is already running".into(),
|
||||
));
|
||||
}
|
||||
// Make room before inserting the queue, preserving results of other networks when possible.
|
||||
for target in &targets {
|
||||
jobs.history.remove(&(network, *target));
|
||||
}
|
||||
while jobs.history.len() + targets.len() > cap {
|
||||
let Some(oldest) = jobs
|
||||
.history
|
||||
.iter()
|
||||
.min_by_key(|(_, r)| r.measured_at_unix_secs)
|
||||
.map(|(k, _)| *k)
|
||||
else {
|
||||
break;
|
||||
};
|
||||
jobs.history.remove(&oldest);
|
||||
}
|
||||
let count = targets.len() as u32;
|
||||
jobs.job = Some(Job {
|
||||
generation,
|
||||
network,
|
||||
batch: peer.is_none().then_some(SpeedBatchReport {
|
||||
done: 0,
|
||||
total: count,
|
||||
}),
|
||||
});
|
||||
for target in &targets {
|
||||
jobs.history.insert(
|
||||
(network, *target),
|
||||
SpeedPeerReport {
|
||||
measured_at_unix_secs: now(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let owner = Arc::downgrade(&self.inner);
|
||||
let metered = metered || self.inner.speed.metered.load(Ordering::Relaxed);
|
||||
let per_peer = if metered {
|
||||
wire::METERED_BYTES
|
||||
} else {
|
||||
wire::NORMAL_BYTES
|
||||
};
|
||||
let limit = if peer.is_none() {
|
||||
per_peer.min(
|
||||
if metered {
|
||||
METERED_BATCH_BYTES
|
||||
} else {
|
||||
BATCH_BYTES
|
||||
} / count,
|
||||
)
|
||||
} else {
|
||||
per_peer
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
for (index, target) in targets.into_iter().enumerate() {
|
||||
let key = (network, target);
|
||||
let Some(inner) = owner.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let result = run_outgoing(&inner, key, generation, limit, peer.is_none()).await;
|
||||
let mut jobs = inner.speed.lock();
|
||||
if let Some((id, _, _)) = &result {
|
||||
inner.speed.clear_channel(key, *id);
|
||||
}
|
||||
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
|
||||
return;
|
||||
}
|
||||
if let Some(report) = jobs.history.get_mut(&key) {
|
||||
match result {
|
||||
Some((_, update, started)) => update_report(report, update, started),
|
||||
None => {
|
||||
report.phase = SpeedPhase::Failed(
|
||||
"Peer is no longer eligible or its overlay address is unavailable"
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if index + 1 == count as usize {
|
||||
jobs.job = None;
|
||||
} else if let Some(batch) = jobs.job.as_mut().and_then(|j| j.batch.as_mut()) {
|
||||
batch.done += 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cancels the current test and any queued peers in this network.
|
||||
pub fn stop_speed_test(&self, network: NetworkId) {
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
self.inner.speed.cancel_locked(&mut jobs, network);
|
||||
}
|
||||
|
||||
/// Applies the host's actual metered-link policy to incoming and outgoing measurements.
|
||||
pub fn set_speed_test_metered(&self, metered: bool) {
|
||||
if self.inner.speed.metered.swap(metered, Ordering::Relaxed) || !metered {
|
||||
return;
|
||||
}
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
if let Some(network) = jobs.job.as_ref().map(|j| j.network) {
|
||||
self.inner.speed.cancel_locked(&mut jobs, network);
|
||||
} else if let Some(c) = self
|
||||
.inner
|
||||
.speed
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.limit > wire::METERED_BYTES)
|
||||
{
|
||||
c.handle.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_outgoing(
|
||||
inner: &Arc<Inner>,
|
||||
key: Key,
|
||||
generation: u64,
|
||||
limit: u32,
|
||||
exits_only: bool,
|
||||
) -> Option<(u64, wire::Progress, Instant)> {
|
||||
let agent = Agent {
|
||||
inner: Arc::clone(inner),
|
||||
};
|
||||
let status = agent.network_status(key.0).await.ok()?;
|
||||
let peer = status.peers.iter().find(|p| {
|
||||
p.endpoint_id == key.1 && (!exits_only || p.exit_node) && supported(&p.capabilities)
|
||||
})?;
|
||||
let id = rand::random();
|
||||
let (cfg, addresses) = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::initiate(cfg);
|
||||
let io = TestIo::new(inner, key, Some(generation));
|
||||
{
|
||||
let mut jobs = inner.speed.lock();
|
||||
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
|
||||
return None;
|
||||
}
|
||||
let report = jobs.history.get_mut(&key)?;
|
||||
report.phase = SpeedPhase::Preparing;
|
||||
report.path = describe_path(peer);
|
||||
inner.speed.active.store(Some(Arc::new(Channel {
|
||||
key,
|
||||
id,
|
||||
limit,
|
||||
addresses,
|
||||
handle,
|
||||
})));
|
||||
}
|
||||
let started = io.started;
|
||||
let update = session.run(io).await;
|
||||
Some((id, update, started))
|
||||
}
|
||||
@@ -16,6 +16,11 @@ use crate::net::{ConnectionCounters, PathAddr, PathInfo, TransportKind};
|
||||
use crate::proto::handshake::Role;
|
||||
use crate::storage::CacheOutcome;
|
||||
|
||||
/// Informational data-channel diagnostics shared by the status UI and runtime.
|
||||
pub const DATA_CONNECTING: &str = "establishing external data transport";
|
||||
/// Data transport was disabled by local policy.
|
||||
pub const DATA_DISABLED: &str = "data transports disabled locally";
|
||||
|
||||
/// Whether a configured network is running locally.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NetworkState {
|
||||
@@ -152,6 +157,8 @@ pub struct PeerStatus {
|
||||
///
|
||||
/// A mutable binding, not an identity.
|
||||
pub hostname: Option<String>,
|
||||
/// Software version in the peer's latest authenticated announcement.
|
||||
pub agent_version: Option<String>,
|
||||
/// Protocols agreed with this peer: both sides have them at the same
|
||||
/// version.
|
||||
///
|
||||
@@ -233,6 +240,8 @@ pub struct RangeConflict {
|
||||
/// Status of one network.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NetworkStatus {
|
||||
/// Available mesh throughput tests, with local progress and results.
|
||||
pub speed: crate::ipc::SpeedReport,
|
||||
/// Shared service configuration with this client's routing observations.
|
||||
pub vips: Vec<crate::vip::VipStatus>,
|
||||
/// Enabled local data-plane protocols, in preference order.
|
||||
@@ -247,6 +256,8 @@ pub struct NetworkStatus {
|
||||
pub exit_via: Option<EndpointId>,
|
||||
/// Whether that member is connected and still offering to be one.
|
||||
pub exit_via_online: bool,
|
||||
/// IP byte totals since this exit route was selected.
|
||||
pub exit_traffic: Option<crate::overlay::exit::ExitTraffic>,
|
||||
/// What the host rules for the exit settings are doing.
|
||||
pub exit_rules: crate::overlay::ExitRulesReport,
|
||||
/// Immutable deterministic description of the network space.
|
||||
|
||||
@@ -21,6 +21,9 @@ use crate::error::Result;
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))]
|
||||
const APP_NAME: &str = "tsunagi";
|
||||
|
||||
/// Maximum length of the optional software release label in a peer announcement.
|
||||
pub const MAX_AGENT_VERSION_LEN: usize = 64;
|
||||
|
||||
/// Rendezvous slots per network; this bounds a discovery sample, not membership.
|
||||
pub const DHT_SLOTS: u8 = 16;
|
||||
/// BEP44 permits 1000 bencoded bytes; a 996-byte string has a four-byte prefix.
|
||||
@@ -47,6 +50,16 @@ pub const DATA_REASSEMBLY_TTL: Duration = Duration::from_secs(5);
|
||||
/// Completed or discarded packet IDs retained to ignore late duplicate fragments.
|
||||
pub const DATA_RECENT_IDS: usize = 128;
|
||||
|
||||
/// Simultaneous TCP, UDP and ICMP work on a userspace exit.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) const EXIT_FORWARD_FLOWS: usize = 256;
|
||||
/// Bounded packet queue shared by userspace exit clients.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) const EXIT_FORWARD_QUEUE: usize = 64;
|
||||
/// Concurrent fragmented datagrams accepted by a userspace exit.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) const EXIT_FORWARD_FRAGMENTS: usize = 32;
|
||||
|
||||
/// Where the two stores live.
|
||||
///
|
||||
/// The mandatory state and the disposable cache are separate both logically and
|
||||
@@ -208,6 +221,8 @@ pub struct Limits {
|
||||
pub max_discovery_candidates: usize,
|
||||
/// Maximum simultaneous authenticated sessions per network.
|
||||
pub max_sessions_per_network: usize,
|
||||
/// Maximum per-peer speed results or queued tests retained by the agent.
|
||||
pub max_speed_results: usize,
|
||||
/// Maximum simultaneous inbound connections being handshaken.
|
||||
pub max_inbound_handshakes: usize,
|
||||
/// Capacity of a session's outbound queue, providing backpressure.
|
||||
@@ -244,6 +259,7 @@ impl Default for Limits {
|
||||
max_concurrent_dials: 8,
|
||||
max_discovery_candidates: 16,
|
||||
max_sessions_per_network: 64,
|
||||
max_speed_results: 256,
|
||||
max_inbound_handshakes: 32,
|
||||
session_send_queue: 64,
|
||||
event_buffer: 512,
|
||||
@@ -566,3 +582,8 @@ impl std::fmt::Debug for AgentConfig {
|
||||
}
|
||||
/// Maximum number of transport links a routed datagram may traverse.
|
||||
pub const ROUTING_HOP_LIMIT: u8 = 16;
|
||||
|
||||
/// Maximum distinct flows per local reader between polls (fits one IPC frame).
|
||||
pub(crate) const MAX_INTERVAL_FLOWS: usize = 2048;
|
||||
/// Independent local monitor windows per agent.
|
||||
pub(crate) const MAX_TRAFFIC_READERS: usize = 4;
|
||||
@@ -15,7 +15,7 @@ pub mod relay;
|
||||
pub mod routing;
|
||||
pub mod transport;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use iroh::EndpointId;
|
||||
use tokio::sync::mpsc;
|
||||
@@ -176,6 +176,7 @@ pub struct PluginContext {
|
||||
/// Where decrypted packets go. Absent when nothing is carrying traffic,
|
||||
/// in which case a protocol still runs and its packets are discarded.
|
||||
sink: Option<Arc<dyn PacketSink>>,
|
||||
routes: Weak<crate::overlay::RoutingTable>,
|
||||
}
|
||||
|
||||
impl PluginContext {
|
||||
@@ -183,14 +184,23 @@ impl PluginContext {
|
||||
sender: mpsc::Sender<PluginRequest>,
|
||||
local: EndpointId,
|
||||
sink: Option<Arc<dyn PacketSink>>,
|
||||
routes: &Arc<crate::overlay::RoutingTable>,
|
||||
) -> Self {
|
||||
Self {
|
||||
sender: Some(sender),
|
||||
local: Some(local),
|
||||
sink,
|
||||
routes: Arc::downgrade(routes),
|
||||
}
|
||||
}
|
||||
|
||||
/// The peer whose tunnel should stay ready for traffic even while idle.
|
||||
/// Only the locally selected internet exit in its own network qualifies.
|
||||
pub fn warm_peer(&self, network: NetworkId) -> Option<EndpointId> {
|
||||
let (selected, peer) = self.routes.upgrade()?.exit_via()?;
|
||||
(selected == network).then_some(peer)
|
||||
}
|
||||
|
||||
/// Where to hand a decrypted packet.
|
||||
///
|
||||
/// Always answers: with no interface to write to, the packets are
|
||||
@@ -208,15 +218,15 @@ impl PluginContext {
|
||||
sender: None,
|
||||
local: None,
|
||||
sink: None,
|
||||
routes: Weak::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A context configured with a custom packet sink.
|
||||
pub fn with_sink(sink: Arc<dyn PacketSink>) -> Self {
|
||||
Self {
|
||||
sender: None,
|
||||
local: None,
|
||||
sink: Some(sink),
|
||||
..Self::detached()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,6 +241,7 @@ impl PluginContext {
|
||||
sender: Some(sender),
|
||||
local: Some(local),
|
||||
sink,
|
||||
..Self::detached()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -134,6 +134,8 @@ struct ForwardingTable {
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Plane {
|
||||
network: NetworkId,
|
||||
traffic: Arc<crate::traffic::TrafficMonitor>,
|
||||
local: PeerId,
|
||||
table: ArcSwap<ForwardingTable>,
|
||||
tally: Arc<Tally>,
|
||||
@@ -176,7 +178,15 @@ impl Plane {
|
||||
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
};
|
||||
let len = frame.len();
|
||||
if hop.send(envelope::decrement(frame)).is_ok() {
|
||||
self.traffic.relay(
|
||||
self.network,
|
||||
header.source,
|
||||
header.destination,
|
||||
header.protocol,
|
||||
len,
|
||||
);
|
||||
self.tally.forwarded.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -324,11 +334,21 @@ pub struct RelayHub {
|
||||
impl RelayHub {
|
||||
/// Creates the router at this network's local endpoint.
|
||||
pub fn new(network: NetworkId, local: EndpointId) -> Arc<Self> {
|
||||
Self::with_monitor(network, local, Arc::default())
|
||||
}
|
||||
|
||||
pub(crate) fn with_monitor(
|
||||
network: NetworkId,
|
||||
local: EndpointId,
|
||||
traffic: Arc<crate::traffic::TrafficMonitor>,
|
||||
) -> Arc<Self> {
|
||||
let tally = Arc::new(Tally::default());
|
||||
Arc::new(Self {
|
||||
network,
|
||||
state: Mutex::new(State {
|
||||
plane: Arc::new(Plane {
|
||||
network,
|
||||
traffic,
|
||||
local: *local.as_bytes(),
|
||||
table: ArcSwap::from_pointee(ForwardingTable::default()),
|
||||
tally: tally.clone(),
|
||||
|
||||
@@ -175,7 +175,10 @@ async fn ecmp_is_per_flow_direct_wins_and_existing_tunnel_survives_changes() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protocols() {
|
||||
let hub = RelayHub::new(network(), peer(2));
|
||||
use crate::traffic::{Flow, Role, TrafficMonitor};
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let window = monitor.subscribe().unwrap();
|
||||
let hub = RelayHub::with_monitor(network(), peer(2), monitor);
|
||||
let a = Wire::new(1, true);
|
||||
let c = Wire::new(3, true);
|
||||
hub.set_direct(peer(1), "ip", a.clone());
|
||||
@@ -199,6 +202,20 @@ async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protoc
|
||||
);
|
||||
assert_eq!(&sent[0][RELAY_OVERHEAD..], b"end-to-end encrypted");
|
||||
assert_eq!(hub.counters().forwarded, 1);
|
||||
let observed = window.snapshot();
|
||||
assert_eq!(observed.flows.len(), 1);
|
||||
let row = &observed.flows[0];
|
||||
assert_eq!(row.key.role, Role::Relay);
|
||||
assert_eq!(row.key.peer, id(1).min(id(4)));
|
||||
assert_eq!(
|
||||
row.key.flow,
|
||||
Flow::Relay {
|
||||
other: id(1).max(id(4)),
|
||||
wire_protocol: tag()
|
||||
}
|
||||
);
|
||||
assert_eq!(row.tx_bytes + row.rx_bytes, sent[0].len() as u64);
|
||||
assert_eq!(row.tx_packets + row.rx_packets, 1);
|
||||
hub.close();
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ impl std::fmt::Debug for Settings {
|
||||
}
|
||||
}
|
||||
struct Samples {
|
||||
pending: VecDeque<(u64, Instant)>,
|
||||
pending: VecDeque<(u64, Instant, usize)>,
|
||||
recent: VecDeque<Option<Duration>>,
|
||||
last_reply: Option<Instant>,
|
||||
}
|
||||
@@ -45,8 +45,8 @@ impl Samples {
|
||||
last_reply: None,
|
||||
}
|
||||
}
|
||||
fn sent(&mut self, seq: u64, now: Instant) {
|
||||
self.pending.push_back((seq, now));
|
||||
fn sent(&mut self, seq: u64, now: Instant, size: usize) {
|
||||
self.pending.push_back((seq, now, size));
|
||||
}
|
||||
fn record(&mut self, rtt: Option<Duration>) {
|
||||
if self.recent.len() == WINDOW {
|
||||
@@ -54,9 +54,12 @@ impl Samples {
|
||||
}
|
||||
self.recent.push_back(rtt);
|
||||
}
|
||||
fn acknowledge(&mut self, seq: u64, now: Instant) {
|
||||
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq)
|
||||
&& let Some((_, sent)) = self.pending.remove(i)
|
||||
fn acknowledge(&mut self, seq: u64, now: Instant, size: usize) -> bool {
|
||||
if let Some(i) = self
|
||||
.pending
|
||||
.iter()
|
||||
.position(|(n, _, expected)| *n == seq && *expected == size)
|
||||
&& let Some((_, sent, _)) = self.pending.remove(i)
|
||||
{
|
||||
let rtt = now.saturating_duration_since(sent);
|
||||
let success = rtt < PROBE_TIMEOUT;
|
||||
@@ -64,13 +67,15 @@ impl Samples {
|
||||
if success {
|
||||
self.last_reply = Some(now);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
false
|
||||
}
|
||||
fn expire(&mut self, now: Instant) {
|
||||
while self
|
||||
.pending
|
||||
.front()
|
||||
.is_some_and(|(_, at)| now.duration_since(*at) >= PROBE_TIMEOUT)
|
||||
.is_some_and(|(_, at, _)| now.duration_since(*at) >= PROBE_TIMEOUT)
|
||||
{
|
||||
self.pending.pop_front();
|
||||
self.record(None);
|
||||
@@ -160,7 +165,7 @@ impl HealthLink {
|
||||
sequence=sequence.wrapping_add(1);
|
||||
let size=raw.max_datagram_size();
|
||||
let packet=probe(&settings,local,1,sequence,size.min(1000));
|
||||
samples.sent(sequence,now);
|
||||
samples.sent(sequence,now,packet.len());
|
||||
let _=raw.send(packet);
|
||||
}
|
||||
packet=raw.recv()=>{
|
||||
@@ -170,7 +175,9 @@ impl HealthLink {
|
||||
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
|
||||
if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));}
|
||||
else if kind==2 && marker == Some(settings.marker) {
|
||||
samples.acknowledge(seq, Instant::now());
|
||||
if samples.acknowledge(seq, Instant::now(), packet.len()) {
|
||||
raw.confirm_delivery();
|
||||
}
|
||||
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
|
||||
}
|
||||
}
|
||||
@@ -305,19 +312,29 @@ impl Drop for HealthLink {
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn an_authenticated_short_reply_does_not_prove_full_size_delivery() {
|
||||
let start = Instant::now();
|
||||
let mut samples = Samples::new();
|
||||
samples.sent(7, start, 1000);
|
||||
assert!(!samples.acknowledge(7, start, 57));
|
||||
assert!(samples.quality().is_none());
|
||||
assert!(samples.acknowledge(7, start, 1000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quality_uses_matched_fresh_replies_and_keeps_losses_in_the_window() {
|
||||
let mut samples = Samples::new();
|
||||
let start = Instant::now();
|
||||
assert!(samples.quality().is_none());
|
||||
for (seq, delay) in [(1, 10), (2, 30), (3, 250)] {
|
||||
samples.sent(seq, start);
|
||||
samples.acknowledge(seq, start + Duration::from_millis(delay));
|
||||
samples.sent(seq, start, 1000);
|
||||
samples.acknowledge(seq, start + Duration::from_millis(delay), 1000);
|
||||
}
|
||||
samples.acknowledge(1, start + Duration::from_secs(1));
|
||||
samples.sent(4, start);
|
||||
assert!(!samples.acknowledge(1, start + Duration::from_secs(1), 1000));
|
||||
samples.sent(4, start, 1000);
|
||||
samples.expire(start + Duration::from_secs(3));
|
||||
samples.acknowledge(4, start + Duration::from_secs(4));
|
||||
assert!(!samples.acknowledge(4, start + Duration::from_secs(4), 1000));
|
||||
let measured = samples.quality().unwrap();
|
||||
assert_eq!(measured.rtt, Duration::from_millis(30));
|
||||
assert_eq!((measured.samples, measured.losses), (3, 1));
|
||||
@@ -326,8 +343,8 @@ mod tests {
|
||||
|
||||
for seq in 5..25 {
|
||||
let sent = start + Duration::from_secs(seq);
|
||||
samples.sent(seq, sent);
|
||||
samples.acknowledge(seq, sent + Duration::from_millis(80));
|
||||
samples.sent(seq, sent, 1000);
|
||||
samples.acknowledge(seq, sent + Duration::from_millis(80), 1000);
|
||||
}
|
||||
let recovered = samples.quality().unwrap();
|
||||
assert_eq!(recovered.rtt, Duration::from_millis(80));
|
||||
@@ -339,17 +356,17 @@ mod tests {
|
||||
let mut samples = Samples::new();
|
||||
let now = Instant::now();
|
||||
for seq in 0..20 {
|
||||
samples.sent(seq, now);
|
||||
samples.sent(seq, now, 1000);
|
||||
if seq % 5 == 0 {
|
||||
samples.acknowledge(seq, now);
|
||||
samples.acknowledge(seq, now, 1000);
|
||||
}
|
||||
}
|
||||
assert!(!samples.degraded());
|
||||
samples.expire(now + Duration::from_secs(4));
|
||||
assert!(samples.degraded());
|
||||
for seq in 20..40 {
|
||||
samples.sent(seq, now);
|
||||
samples.acknowledge(seq, now);
|
||||
samples.sent(seq, now, 1000);
|
||||
samples.acknowledge(seq, now, 1000);
|
||||
}
|
||||
samples.expire(now + Duration::from_secs(4));
|
||||
assert!(!samples.degraded());
|
||||
|
||||
@@ -150,6 +150,10 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
|
||||
None
|
||||
}
|
||||
|
||||
/// The link monitor received a timely, authenticated answer to a data probe
|
||||
/// on this very link. A carrier can use it in place of its own idle probe.
|
||||
fn confirm_delivery(&self) {}
|
||||
|
||||
/// A short description of the path in use, for diagnostics.
|
||||
///
|
||||
/// Reports what the transport actually knows. It must not invent a value.
|
||||
|
||||
@@ -15,6 +15,12 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// The local traffic monitor could not start or poll its subscription.
|
||||
#[error("{0}")]
|
||||
TrafficMonitor(String),
|
||||
/// A requested mesh throughput test cannot run.
|
||||
#[error("{0}")]
|
||||
SpeedTest(String),
|
||||
/// A node-history cleanup is unsafe, stale or cannot be performed.
|
||||
#[error("cannot forget node: {0}")]
|
||||
ForgetNode(String),
|
||||
|
||||
@@ -25,6 +25,11 @@
|
||||
//! rather than the crate's internal structures, so internal refactors do not
|
||||
//! silently change what a client sees.
|
||||
|
||||
mod traffic;
|
||||
pub use traffic::TrafficStream;
|
||||
mod speed;
|
||||
pub use speed::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
|
||||
|
||||
#[cfg(unix)]
|
||||
pub mod unix;
|
||||
#[cfg(windows)]
|
||||
@@ -171,6 +176,8 @@ pub fn default_control_socket_path() -> PathBuf {
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum Request {
|
||||
/// Open a dedicated, window-scoped local monitor connection.
|
||||
WatchTraffic,
|
||||
/// Save a complete version-checked service draft or its deletion.
|
||||
SaveVip {
|
||||
/// Exact network id.
|
||||
@@ -277,6 +284,20 @@ pub enum Request {
|
||||
/// The member's endpoint id, or `None` to stop using an exit node.
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Begin a peer test or a sequential batch of advertised exits.
|
||||
StartSpeedTest {
|
||||
/// Active network identifier.
|
||||
network_id: String,
|
||||
/// One peer, or all online exits when absent.
|
||||
peer: Option<String>,
|
||||
/// Apply the smaller metered-link byte budget.
|
||||
metered: bool,
|
||||
},
|
||||
/// Cancel the active local test or batch in this network.
|
||||
StopSpeedTest {
|
||||
/// Active network identifier.
|
||||
network_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Request {
|
||||
@@ -300,6 +321,16 @@ impl std::fmt::Debug for Request {
|
||||
f,
|
||||
"SetProtocols {{ {network_id}, protocols: {protocols:?} }}"
|
||||
),
|
||||
Request::StartSpeedTest {
|
||||
network_id,
|
||||
peer,
|
||||
metered,
|
||||
} => write!(
|
||||
f,
|
||||
"StartSpeedTest {{ {network_id}, peer: {peer:?}, metered: {metered} }}"
|
||||
),
|
||||
Request::StopSpeedTest { network_id } => write!(f, "StopSpeedTest({network_id})"),
|
||||
Request::WatchTraffic => f.write_str("WatchTraffic"),
|
||||
Request::Status => f.write_str("Status"),
|
||||
Request::SetBroadcast {
|
||||
network_id,
|
||||
@@ -331,6 +362,10 @@ impl std::fmt::Debug for Request {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum Response {
|
||||
/// The connection now accepts interval polls.
|
||||
TrafficReady,
|
||||
/// A speed-test action was accepted.
|
||||
SpeedTestAccepted,
|
||||
/// Accepted configuration with fresh local routing observations.
|
||||
Vips(Vec<crate::vip::VipStatus>),
|
||||
/// An observed offline claim was durably retired.
|
||||
@@ -711,6 +746,9 @@ pub struct ProtocolReport {
|
||||
/// One network.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct NetworkReport {
|
||||
/// Current capabilities and results of peer speed tests.
|
||||
#[serde(default)]
|
||||
pub speed: SpeedReport,
|
||||
/// Shared VIPs and this client's routing observations.
|
||||
#[serde(default)]
|
||||
pub vips: Vec<crate::vip::VipStatus>,
|
||||
@@ -830,6 +868,8 @@ pub struct MemberReport {
|
||||
/// One control plane peer.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerReport {
|
||||
/// The software version reported by this authenticated peer, when available.
|
||||
pub agent_version: Option<String>,
|
||||
/// Actionable carrier failure or policy mismatch; absent for a usable route.
|
||||
pub data_error: Option<String>,
|
||||
/// The peer's endpoint id.
|
||||
@@ -893,6 +933,8 @@ pub struct RuleSetReport {
|
||||
/// One network's exit-node settings and what they are doing.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ExitReport {
|
||||
/// IP bytes carried through this exit since selection, when locally observed.
|
||||
pub traffic: Option<crate::overlay::exit::ExitTraffic>,
|
||||
/// This agent offers itself as an exit node in this network.
|
||||
pub offering: bool,
|
||||
/// Masquerading and forwarding rules for members' traffic, when offering.
|
||||
@@ -936,10 +978,12 @@ pub struct OverlayPeerReport {
|
||||
pub public_key: String,
|
||||
/// The overlay address the network agreed it holds.
|
||||
pub address: Option<String>,
|
||||
/// Seconds since the last WireGuard handshake.
|
||||
///
|
||||
/// `None` means the tunnel has never handshaken and cannot carry traffic.
|
||||
/// Seconds since the last WireGuard handshake while its session key is usable.
|
||||
pub handshake_secs_ago: Option<u64>,
|
||||
/// An established tunnel has no recent or pending IP traffic. An expired
|
||||
/// key on a tunnel required to stay warm is reported as waiting instead.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
/// Packets encrypted and sent to this peer.
|
||||
pub tx_packets: u64,
|
||||
/// Packets decrypted from this peer.
|
||||
@@ -985,6 +1029,12 @@ impl OverlayPeerReport {
|
||||
/// running and what they can report or change. That is what keeps this module
|
||||
/// free of any knowledge of them.
|
||||
pub trait ReportSource: Send + Sync + 'static {
|
||||
/// Start a new independent interval subscription, when supported by the source.
|
||||
fn subscribe_traffic(
|
||||
&self,
|
||||
) -> std::result::Result<crate::traffic::TrafficSubscription, String> {
|
||||
Err("Traffic monitoring is unavailable".into())
|
||||
}
|
||||
/// Atomically saves a complete VIP draft using its original revision.
|
||||
fn save_vip(
|
||||
&self,
|
||||
@@ -1057,6 +1107,24 @@ pub trait ReportSource: Send + Sync + 'static {
|
||||
Box::pin(async move { Err("this agent cannot change broadcast participation".into()) })
|
||||
}
|
||||
|
||||
/// Queues a diagnostic against one peer, or all current exit peers.
|
||||
fn start_speed_test(
|
||||
&self,
|
||||
_network_id: String,
|
||||
_peer: Option<String>,
|
||||
_metered: bool,
|
||||
) -> BoxFuture<'_, std::result::Result<(), String>> {
|
||||
Box::pin(async { Err("this agent cannot test peer speeds".into()) })
|
||||
}
|
||||
|
||||
/// Cancels an individual test and any remaining batch members.
|
||||
fn stop_speed_test(
|
||||
&self,
|
||||
_network_id: String,
|
||||
) -> BoxFuture<'_, std::result::Result<(), String>> {
|
||||
Box::pin(async { Err("this agent cannot stop speed tests".into()) })
|
||||
}
|
||||
|
||||
/// Stops serving a network, or starts serving it again.
|
||||
///
|
||||
/// Defaulted to a refusal, like the others.
|
||||
@@ -1141,13 +1209,17 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
///
|
||||
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
||||
/// changes shape.
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 24]);
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 28]);
|
||||
|
||||
/// Reads one request off an accepted stream, answers it, writes the response.
|
||||
///
|
||||
/// The per-platform adapters call this for every connection they accept, so
|
||||
/// the request handling is identical on every transport.
|
||||
pub(crate) async fn serve_connection<S>(mut stream: S, source: Arc<dyn ReportSource>) -> Result<()>
|
||||
pub(crate) async fn serve_connection<S>(
|
||||
mut stream: S,
|
||||
source: Arc<dyn ReportSource>,
|
||||
mut stopped: tokio::sync::watch::Receiver<()>,
|
||||
) -> Result<()>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
@@ -1165,6 +1237,16 @@ where
|
||||
}
|
||||
};
|
||||
let response = match request {
|
||||
Request::WatchTraffic => match source.subscribe_traffic() {
|
||||
Ok(sub) => {
|
||||
drop(source);
|
||||
return tokio::select! {
|
||||
_ = stopped.changed() => Ok(()),
|
||||
result = traffic::serve(stream,sub) => result,
|
||||
};
|
||||
}
|
||||
Err(reason) => Response::Error(reason),
|
||||
},
|
||||
Request::SaveVip {
|
||||
network_id,
|
||||
config,
|
||||
@@ -1227,6 +1309,18 @@ where
|
||||
Ok(secret) => Response::Secret(RedactedText::new(secret)),
|
||||
Err(reason) => Response::Error(reason),
|
||||
},
|
||||
Request::StartSpeedTest {
|
||||
network_id,
|
||||
peer,
|
||||
metered,
|
||||
} => match source.start_speed_test(network_id, peer, metered).await {
|
||||
Ok(()) => Response::SpeedTestAccepted,
|
||||
Err(reason) => Response::Error(reason),
|
||||
},
|
||||
Request::StopSpeedTest { network_id } => match source.stop_speed_test(network_id).await {
|
||||
Ok(()) => Response::SpeedTestAccepted,
|
||||
Err(reason) => Response::Error(reason),
|
||||
},
|
||||
Request::SetExitOffer {
|
||||
network_id,
|
||||
enabled,
|
||||
@@ -1446,6 +1540,43 @@ pub async fn set_exit_node(
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures the mesh data path to one peer, or queues the network's online exit nodes.
|
||||
pub async fn start_speed_test(
|
||||
path: impl AsRef<Path>,
|
||||
network_id: &str,
|
||||
peer: Option<&str>,
|
||||
metered: bool,
|
||||
) -> Result<()> {
|
||||
speed_request(
|
||||
path.as_ref(),
|
||||
Request::StartSpeedTest {
|
||||
network_id: network_id.to_owned(),
|
||||
peer: peer.map(str::to_owned),
|
||||
metered,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stops the current local speed test and clears its remaining queue.
|
||||
pub async fn stop_speed_test(path: impl AsRef<Path>, network_id: &str) -> Result<()> {
|
||||
speed_request(
|
||||
path.as_ref(),
|
||||
Request::StopSpeedTest {
|
||||
network_id: network_id.to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn speed_request(path: &Path, request: Request) -> Result<()> {
|
||||
match exchange(path, &request, EXCHANGE_TIMEOUT).await? {
|
||||
Response::SpeedTestAccepted => Ok(()),
|
||||
Response::Error(reason) => Err(Error::SpeedTest(reason)),
|
||||
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks a running agent for a configured network's shared secret, in its
|
||||
/// `tsn1…` text form, so a local client can copy it. The secret is never
|
||||
/// logged by this path.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Local presentation of receiver-measured peer throughput.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Tests last requested on this device, scoped to one network.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedReport {
|
||||
/// Progress of the current sequential exit-node test.
|
||||
pub batch: Option<SpeedBatchReport>,
|
||||
/// Per-peer progress or the last local result, keyed by endpoint ID.
|
||||
pub peers: BTreeMap<String, SpeedPeerReport>,
|
||||
/// Currently connected peers advertising the same diagnostic wire version.
|
||||
pub capable: Vec<String>,
|
||||
}
|
||||
|
||||
/// Progress of an exit-node batch.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedBatchReport {
|
||||
/// Number of peers that have finished, including failures.
|
||||
pub done: u32,
|
||||
/// Number selected when the batch started.
|
||||
pub total: u32,
|
||||
}
|
||||
|
||||
/// A receiver-confirmed rate in decimal bits per second.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedRate {
|
||||
/// Measured bits per second.
|
||||
pub bps: u64,
|
||||
/// The test reached its budget before establishing a throughput ceiling.
|
||||
pub lower_bound: bool,
|
||||
}
|
||||
|
||||
/// Locally observed phase of one diagnostic.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum SpeedPhase {
|
||||
/// Waiting behind another exit in the same batch.
|
||||
#[default]
|
||||
Queued,
|
||||
/// Negotiating over the authenticated control session.
|
||||
Preparing,
|
||||
/// Receiving test data.
|
||||
Download,
|
||||
/// Sending test data.
|
||||
Upload,
|
||||
/// Measurement is complete.
|
||||
Done,
|
||||
/// The test could not produce a result, with an explanation for the user.
|
||||
Failed(String),
|
||||
/// The test was stopped.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// A single live or completed diagnostic on this device.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedPeerReport {
|
||||
/// Current or terminal phase.
|
||||
pub phase: SpeedPhase,
|
||||
/// Download rate from the remote peer.
|
||||
pub down: Option<SpeedRate>,
|
||||
/// Upload rate to the remote peer.
|
||||
pub up: Option<SpeedRate>,
|
||||
/// Time since the individual test began.
|
||||
pub elapsed_ms: u32,
|
||||
/// Unique payload bytes received across both directions.
|
||||
pub bytes: u64,
|
||||
/// Wall-clock time of the most recent update, for display only.
|
||||
pub measured_at_unix_secs: u64,
|
||||
/// Data path at the start of the measurement, when known.
|
||||
pub path: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! A dedicated local connection is the lifetime of one traffic window.
|
||||
use super::{
|
||||
EXCHANGE_TIMEOUT, Error, Path, Request, Response, Result, read_message, transport,
|
||||
write_message,
|
||||
};
|
||||
use crate::traffic::{TrafficSnapshot, TrafficSubscription};
|
||||
use std::{future::Future, time::Duration};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
#[cfg(unix)]
|
||||
type Socket = tokio::net::UnixStream;
|
||||
#[cfg(windows)]
|
||||
type Socket = tokio::net::windows::named_pipe::NamedPipeClient;
|
||||
|
||||
async fn bounded<T>(duration: Duration, f: impl Future<Output = Result<T>>) -> Result<T> {
|
||||
tokio::time::timeout(duration, f)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout {
|
||||
what: "local traffic monitor".into(),
|
||||
})?
|
||||
}
|
||||
|
||||
/// A local monitor stream. Dropping it releases the agent's interval buffer.
|
||||
pub struct TrafficStream(Socket);
|
||||
impl TrafficStream {
|
||||
/// Starts observing now, independently of any other open window.
|
||||
pub async fn open(path: &Path) -> Result<Self> {
|
||||
bounded(EXCHANGE_TIMEOUT, async {
|
||||
let mut socket = transport::connect(path).await?;
|
||||
write_message(&mut socket, &Request::WatchTraffic).await?;
|
||||
match read_message(&mut socket).await? {
|
||||
Response::TrafficReady => Ok(Self(socket)),
|
||||
Response::Error(reason) => Err(Error::TrafficMonitor(reason)),
|
||||
_ => Err(Error::TrafficMonitor(
|
||||
"Unexpected answer opening traffic monitor".into(),
|
||||
)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Drains only this reader's interval.
|
||||
pub async fn snapshot(&mut self) -> Result<TrafficSnapshot> {
|
||||
bounded(EXCHANGE_TIMEOUT, async {
|
||||
write_message(&mut self.0, &0u8).await?;
|
||||
read_message(&mut self.0).await
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn serve<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
mut socket: S,
|
||||
sub: TrafficSubscription,
|
||||
) -> Result<()> {
|
||||
bounded(
|
||||
EXCHANGE_TIMEOUT,
|
||||
write_message(&mut socket, &Response::TrafficReady),
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
// A wedged or suspended client cannot keep the collector running indefinitely.
|
||||
let token: u8 = bounded(Duration::from_secs(15), read_message(&mut socket)).await?;
|
||||
if token != 0 {
|
||||
return Err(Error::TrafficMonitor("Invalid monitor poll".into()));
|
||||
}
|
||||
bounded(
|
||||
EXCHANGE_TIMEOUT,
|
||||
write_message(&mut socket, &sub.snapshot()),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
@@ -148,13 +148,15 @@ fn set_mode(path: &Path, mode: u32) -> Result<()> {
|
||||
}
|
||||
|
||||
async fn serve(listener: UnixListener, source: Arc<dyn ReportSource>) {
|
||||
let (_lifetime, stopped) = tokio::sync::watch::channel(());
|
||||
loop {
|
||||
let Ok((stream, _)) = listener.accept().await else {
|
||||
continue;
|
||||
};
|
||||
let source = Arc::clone(&source);
|
||||
let stopped = stopped.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = super::serve_connection(stream, source).await {
|
||||
if let Err(err) = super::serve_connection(stream, source, stopped).await {
|
||||
tracing::debug!(%err, "local control request failed");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -217,6 +217,7 @@ async fn serve(
|
||||
first: tokio::net::windows::named_pipe::NamedPipeServer,
|
||||
source: Arc<dyn ReportSource>,
|
||||
) {
|
||||
let (_lifetime, stopped) = tokio::sync::watch::channel(());
|
||||
let mut server = first;
|
||||
loop {
|
||||
if server.connect().await.is_err() {
|
||||
@@ -235,15 +236,17 @@ async fn serve(
|
||||
// Nothing left to accept the next client on, but the one in
|
||||
// hand is still answered before the loop ends.
|
||||
let source = Arc::clone(&source);
|
||||
let stopped = stopped.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = super::serve_connection(connected, source).await;
|
||||
let _ = super::serve_connection(connected, source, stopped).await;
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
let source = Arc::clone(&source);
|
||||
let stopped = stopped.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = super::serve_connection(connected, source).await {
|
||||
if let Err(err) = super::serve_connection(connected, source, stopped).await {
|
||||
tracing::debug!(%err, "local control request failed");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -51,6 +51,7 @@ pub mod storage;
|
||||
pub mod task;
|
||||
#[cfg(feature = "testing")]
|
||||
pub mod testing;
|
||||
pub mod traffic;
|
||||
pub mod vip;
|
||||
|
||||
pub use agent::{Agent, AgentStatus, Event, NetworkStatus, PeerStatus};
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//! A Windows exit offer terminates its forwarded connections on physical
|
||||
//! sockets. This keeps them out of the destination-only routes used by local
|
||||
//! applications. The stack and its sockets live for the offer, independently
|
||||
//! of this device's upstream selection.
|
||||
use super::router::Route;
|
||||
use crate::identity::NetworkId;
|
||||
use crate::vip::{
|
||||
Protocol,
|
||||
packet::{self, Tuple},
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use smoltcp::wire::{IpAddress, TcpPacket, UdpPacket};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io,
|
||||
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
net::{TcpSocket, UdpSocket},
|
||||
sync::{mpsc, watch},
|
||||
task::{JoinHandle, JoinSet},
|
||||
};
|
||||
|
||||
mod tcp;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
use crate::config::{EXIT_FORWARD_FLOWS, EXIT_FORWARD_FRAGMENTS, EXIT_FORWARD_QUEUE};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Physical {
|
||||
pub index: u32,
|
||||
pub address: Ipv4Addr,
|
||||
}
|
||||
|
||||
impl Physical {
|
||||
async fn tcp(self, remote: SocketAddr) -> io::Result<tokio::net::TcpStream> {
|
||||
let socket = TcpSocket::new_v4()?;
|
||||
#[cfg(windows)]
|
||||
windows::pin(&socket, self.index)?;
|
||||
socket.bind((self.address, 0).into())?;
|
||||
socket.connect(remote).await
|
||||
}
|
||||
|
||||
fn datagram(self, protocol: socket2::Protocol) -> io::Result<UdpSocket> {
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
let ty = if protocol == Protocol::UDP {
|
||||
Type::DGRAM
|
||||
} else {
|
||||
Type::RAW
|
||||
};
|
||||
let socket = Socket::new(Domain::IPV4, ty, Some(protocol))?;
|
||||
#[cfg(windows)]
|
||||
windows::pin(&socket, self.index)?;
|
||||
socket.bind(&SocketAddr::V4(SocketAddrV4::new(self.address, 0)).into())?;
|
||||
socket.set_nonblocking(true)?;
|
||||
UdpSocket::from_std(socket.into())
|
||||
}
|
||||
}
|
||||
|
||||
type Reply = Arc<dyn Fn(Route, Bytes) + Send + Sync>;
|
||||
type Offers = Vec<(NetworkId, Physical)>;
|
||||
|
||||
pub(super) struct Gateway {
|
||||
input: mpsc::Sender<(Route, Bytes)>,
|
||||
offers: watch::Sender<Offers>,
|
||||
worker: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Gateway {
|
||||
pub fn new(mtu: u32, reply: impl Fn(Route, Bytes) + Send + Sync + 'static) -> Self {
|
||||
let (input, packets) = mpsc::channel(EXIT_FORWARD_QUEUE);
|
||||
let (offers, serving) = watch::channel(Vec::new());
|
||||
let worker = tokio::spawn(run(mtu, Arc::new(reply), packets, serving));
|
||||
Self {
|
||||
input,
|
||||
offers,
|
||||
worker,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configure(&self, mut offers: Offers) {
|
||||
offers.sort_by_key(|(network, _)| *network);
|
||||
self.offers.send_if_modified(|old| {
|
||||
if *old == offers {
|
||||
return false;
|
||||
}
|
||||
*old = offers;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
pub fn forward(&self, origin: Route, packet: Bytes) -> bool {
|
||||
self.offers
|
||||
.borrow()
|
||||
.iter()
|
||||
.any(|(network, _)| *network == origin.network)
|
||||
&& self.input.try_send((origin, packet)).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Gateway {
|
||||
fn drop(&mut self) {
|
||||
self.worker.abort();
|
||||
}
|
||||
}
|
||||
|
||||
type FlowKey = (NetworkId, iroh::EndpointId, Tuple);
|
||||
struct Flow {
|
||||
tx: mpsc::Sender<Bytes>,
|
||||
task: tokio::task::AbortHandle,
|
||||
}
|
||||
|
||||
async fn run(
|
||||
mtu: u32,
|
||||
reply: Reply,
|
||||
mut incoming: mpsc::Receiver<(Route, Bytes)>,
|
||||
mut serving: watch::Receiver<Offers>,
|
||||
) {
|
||||
let mut flows: HashMap<FlowKey, Flow> = HashMap::new();
|
||||
let mut jobs = JoinSet::new();
|
||||
let mut fragments = packet::Reassembly::default();
|
||||
loop {
|
||||
let (origin, part) = tokio::select! {
|
||||
biased;
|
||||
changed = serving.changed() => {
|
||||
if changed.is_err() { return; }
|
||||
let offers = serving.borrow_and_update();
|
||||
flows.retain(|(network, _, _), flow| {
|
||||
let keep = offers.iter().any(|(net, _)| net == network);
|
||||
if !keep { flow.task.abort(); }
|
||||
keep
|
||||
});
|
||||
// Incomplete datagrams from a withdrawn offer must not survive a rejoin.
|
||||
fragments = packet::Reassembly::default();
|
||||
continue;
|
||||
}
|
||||
Some(result) = jobs.join_next_with_id(), if !jobs.is_empty() => {
|
||||
if let Ok((id, Some(key))) = result
|
||||
&& flows.get(&key).is_some_and(|flow| flow.task.id() == id) {
|
||||
flows.remove(&key);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
input = incoming.recv() => match input { Some(input) => input, None => return },
|
||||
};
|
||||
let Some(physical) = serving
|
||||
.borrow()
|
||||
.iter()
|
||||
.find(|(net, _)| *net == origin.network)
|
||||
.map(|(_, p)| *p)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(packet) =
|
||||
fragments.accept(part, EXIT_FORWARD_FRAGMENTS, Some(*origin.peer.as_bytes()))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(n) = packet::header(&packet) else {
|
||||
continue;
|
||||
};
|
||||
if packet[8] <= 1 {
|
||||
continue;
|
||||
}
|
||||
if packet[9] == 1 {
|
||||
if jobs.len() < EXIT_FORWARD_FLOWS
|
||||
&& packet.get(n) == Some(&8)
|
||||
&& packet.len() >= n + 8
|
||||
&& packet[n + 1] == 0
|
||||
&& packet::checksum(&packet[n..]) == 0
|
||||
{
|
||||
let reply = reply.clone();
|
||||
let mut offers = serving.clone();
|
||||
jobs.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = offers.wait_for(|nets| !nets.iter().any(|(net, _)| *net == origin.network)) => {},
|
||||
_ = echo(physical, origin, packet, n, &reply, mtu) => {}
|
||||
}
|
||||
None
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(tuple) = packet::tuple(&packet) else {
|
||||
continue;
|
||||
};
|
||||
let src = IpAddress::Ipv4(tuple.src);
|
||||
let dst = IpAddress::Ipv4(tuple.dst);
|
||||
let valid =
|
||||
match tuple.protocol {
|
||||
Protocol::Tcp => TcpPacket::new_checked(&packet[n..])
|
||||
.is_ok_and(|p| p.verify_checksum(&src, &dst)),
|
||||
Protocol::Udp => UdpPacket::new_checked(&packet[n..])
|
||||
.is_ok_and(|p| p.verify_checksum(&src, &dst)),
|
||||
};
|
||||
if !valid {
|
||||
continue;
|
||||
}
|
||||
let key = (origin.network, origin.peer, tuple);
|
||||
if let Some(flow) = flows.get(&key) {
|
||||
let _ = flow.tx.try_send(packet);
|
||||
continue;
|
||||
}
|
||||
if jobs.len() >= EXIT_FORWARD_FLOWS
|
||||
|| (tuple.protocol == Protocol::Tcp && !packet::tcp_syn(&packet))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (tx, rx) = mpsc::channel(EXIT_FORWARD_QUEUE.min(16));
|
||||
let reply = reply.clone();
|
||||
let task = jobs.spawn(async move {
|
||||
match tuple.protocol {
|
||||
Protocol::Tcp => tcp::serve(physical, origin, tuple, packet, rx, reply, mtu).await,
|
||||
Protocol::Udp => {
|
||||
let _ = udp(physical, origin, tuple, packet, rx, reply, mtu).await;
|
||||
}
|
||||
}
|
||||
Some(key)
|
||||
});
|
||||
flows.insert(key, Flow { tx, task });
|
||||
}
|
||||
}
|
||||
|
||||
fn remote(t: Tuple) -> SocketAddr {
|
||||
SocketAddr::V4(SocketAddrV4::new(t.dst, t.dport))
|
||||
}
|
||||
|
||||
fn respond(reply: &Reply, origin: Route, packet: Bytes, mtu: u32) {
|
||||
for part in packet::fragments(packet, mtu) {
|
||||
reply(origin, part);
|
||||
}
|
||||
}
|
||||
|
||||
async fn udp(
|
||||
physical: Physical,
|
||||
origin: Route,
|
||||
tuple: Tuple,
|
||||
first: Bytes,
|
||||
mut incoming: mpsc::Receiver<Bytes>,
|
||||
reply: Reply,
|
||||
mtu: u32,
|
||||
) -> io::Result<()> {
|
||||
let socket = physical.datagram(socket2::Protocol::UDP)?;
|
||||
socket.connect(remote(tuple)).await?;
|
||||
let socket = &socket;
|
||||
let send = |p: Bytes| async move {
|
||||
if let Some(n) = packet::header(&p) {
|
||||
socket.send(&p[n + 8..]).await?;
|
||||
}
|
||||
Ok::<_, io::Error>(())
|
||||
};
|
||||
send(first).await?;
|
||||
let mut buf = vec![0; 65_507];
|
||||
loop {
|
||||
tokio::select! {
|
||||
packet = incoming.recv() => match packet { Some(p) => send(p).await?, None => return Ok(()) },
|
||||
result = socket.recv(&mut buf) => {
|
||||
let len = result?;
|
||||
if let Some(p) = udp_packet(tuple.reverse(), &buf[..len]) { respond(&reply, origin, p, mtu); }
|
||||
},
|
||||
_ = tokio::time::sleep(Duration::from_secs(120)) => return Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ip_packet(
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
proto: u8,
|
||||
payload_len: usize,
|
||||
) -> Option<Vec<u8>> {
|
||||
let len = u16::try_from(20usize.checked_add(payload_len)?).ok()?;
|
||||
let mut bytes = vec![0; usize::from(len)];
|
||||
bytes[0] = 0x45;
|
||||
bytes[2..4].copy_from_slice(&len.to_be_bytes());
|
||||
bytes[4..6].copy_from_slice(&rand::random::<u16>().to_be_bytes());
|
||||
bytes[8] = 64;
|
||||
bytes[9] = proto;
|
||||
bytes[12..16].copy_from_slice(&source.octets());
|
||||
bytes[16..20].copy_from_slice(&destination.octets());
|
||||
let checksum = packet::checksum(&bytes[..20]);
|
||||
bytes[10..12].copy_from_slice(&checksum.to_be_bytes());
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
fn udp_packet(tuple: Tuple, body: &[u8]) -> Option<Bytes> {
|
||||
let mut bytes = ip_packet(tuple.src, tuple.dst, 17, body.len().checked_add(8)?)?;
|
||||
let mut p = UdpPacket::new_unchecked(&mut bytes[20..]);
|
||||
p.set_src_port(tuple.sport);
|
||||
p.set_dst_port(tuple.dport);
|
||||
p.set_len((body.len() + 8) as u16);
|
||||
p.payload_mut().copy_from_slice(body);
|
||||
p.fill_checksum(&tuple.src.into(), &tuple.dst.into());
|
||||
Some(bytes.into())
|
||||
}
|
||||
|
||||
async fn echo(
|
||||
physical: Physical,
|
||||
origin: Route,
|
||||
packet: Bytes,
|
||||
n: usize,
|
||||
reply: &Reply,
|
||||
mtu: u32,
|
||||
) -> io::Result<()> {
|
||||
let Some((source, destination)) = packet::addresses(&packet) else {
|
||||
return Ok(());
|
||||
};
|
||||
let socket = physical.datagram(socket2::Protocol::ICMPV4)?;
|
||||
socket.set_ttl(u32::from(packet[8] - 1))?;
|
||||
socket.connect((destination, 0)).await?;
|
||||
// Raw ICMP sockets can observe other echo replies. An independent nonce and
|
||||
// the original data correlate a reply with this one authenticated request.
|
||||
let nonce = rand::random::<u32>().to_be_bytes();
|
||||
let mut request = packet[n..].to_vec();
|
||||
request[4..8].copy_from_slice(&nonce);
|
||||
request[2..4].fill(0);
|
||||
let checksum = packet::checksum(&request);
|
||||
request[2..4].copy_from_slice(&checksum.to_be_bytes());
|
||||
socket.send(&request).await?;
|
||||
// Winsock delivers unrelated replies to other raw ICMP sockets too. A longer
|
||||
// reply must not trigger WSAEMSGSIZE and abort this request.
|
||||
let mut buf = vec![0; usize::from(u16::MAX)];
|
||||
let until = tokio::time::Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
let len = tokio::time::timeout_at(until, socket.recv(&mut buf)).await??;
|
||||
let Some(h) = packet::header(&buf[..len]) else {
|
||||
continue;
|
||||
};
|
||||
let body = &buf[h..len];
|
||||
if buf[9] != 1
|
||||
|| body.len() != request.len()
|
||||
|| body[0..2] != [0, 0]
|
||||
|| body[4..] != request[4..]
|
||||
|| packet::checksum(body) != 0
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(mut out) = ip_packet(destination, source, 1, body.len()) {
|
||||
out[20..].copy_from_slice(body);
|
||||
out[24..28].copy_from_slice(&packet[n + 4..n + 8]);
|
||||
out[22..24].fill(0);
|
||||
let checksum = packet::checksum(&out[20..]);
|
||||
out[22..24].copy_from_slice(&checksum.to_be_bytes());
|
||||
respond(reply, origin, out.into(), mtu);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! smoltcp owns the member-facing half of one stream. The OS owns the
|
||||
//! physical TCP connection. Both directions apply backpressure independently.
|
||||
use super::*;
|
||||
use smoltcp::{
|
||||
iface::{Config, Interface, SocketSet},
|
||||
phy::{self, Device, DeviceCapabilities, Medium},
|
||||
socket::tcp::{Socket, SocketBuffer, State},
|
||||
time::Instant as NetTime,
|
||||
wire::{HardwareAddress, IpCidr},
|
||||
};
|
||||
use std::collections::VecDeque;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
struct Wire {
|
||||
mtu: usize,
|
||||
input: Option<Bytes>,
|
||||
output: VecDeque<Bytes>,
|
||||
}
|
||||
|
||||
struct Rx(Bytes);
|
||||
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<Bytes>);
|
||||
impl phy::TxToken for Tx<'_> {
|
||||
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
|
||||
let mut bytes = vec![0; len];
|
||||
let result = f(&mut bytes);
|
||||
self.0.push_back(bytes.into());
|
||||
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(|p| (Rx(p), Tx(&mut self.output)))
|
||||
}
|
||||
fn transmit(&mut self, _: NetTime) -> Option<Tx<'_>> {
|
||||
(self.output.len() < EXIT_FORWARD_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
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn serve(
|
||||
physical: Physical,
|
||||
origin: Route,
|
||||
flow: Tuple,
|
||||
syn: Bytes,
|
||||
mut incoming: mpsc::Receiver<Bytes>,
|
||||
reply: Reply,
|
||||
mtu: u32,
|
||||
) {
|
||||
let Ok(Ok(mut upstream)) =
|
||||
tokio::time::timeout(Duration::from_secs(8), physical.tcp(remote(flow))).await
|
||||
else {
|
||||
if let Some(reset) = packet::reject(&syn) {
|
||||
reply(origin, reset);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let mut wire = Wire {
|
||||
mtu: mtu as usize,
|
||||
input: Some(syn),
|
||||
output: VecDeque::new(),
|
||||
};
|
||||
let mut config = Config::new(HardwareAddress::Ip);
|
||||
config.random_seed = rand::random();
|
||||
let mut iface = Interface::new(config, &mut wire, NetTime::ZERO);
|
||||
iface.update_ip_addrs(|ips| {
|
||||
let _ = ips.push(IpCidr::new(flow.dst.into(), 0));
|
||||
});
|
||||
let mut sockets = SocketSet::new(Vec::new());
|
||||
let buffer = || SocketBuffer::new(vec![0; 64 * 1024]);
|
||||
let mut tcp = Socket::new(buffer(), buffer());
|
||||
tcp.set_timeout(Some(smoltcp::time::Duration::from_secs(120)));
|
||||
if tcp.listen((flow.dst, flow.dport)).is_err() {
|
||||
return;
|
||||
}
|
||||
let handle = sockets.add(tcp);
|
||||
let start = std::time::Instant::now();
|
||||
let mut remote_fin = false;
|
||||
let mut local_fin = false;
|
||||
loop {
|
||||
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
|
||||
iface.poll(now, &mut wire, &mut sockets);
|
||||
let tcp = sockets.get_mut::<Socket>(handle);
|
||||
if tcp.can_recv() {
|
||||
let write = tcp.recv(|buf| match upstream.try_write(buf) {
|
||||
Ok(n) => (n, Ok(n > 0)),
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => (0, Ok(false)),
|
||||
Err(e) => (0, Err(e)),
|
||||
});
|
||||
if matches!(write, Ok(Err(_))) {
|
||||
tcp.abort();
|
||||
}
|
||||
}
|
||||
if !local_fin
|
||||
&& !tcp.may_recv()
|
||||
&& matches!(
|
||||
tcp.state(),
|
||||
State::CloseWait | State::Closing | State::LastAck | State::TimeWait
|
||||
)
|
||||
{
|
||||
let _ = upstream.shutdown().await;
|
||||
local_fin = true;
|
||||
}
|
||||
if tcp.can_send() && !remote_fin {
|
||||
match tcp.send(|buf| match upstream.try_read(buf) {
|
||||
Ok(n) => (n, Ok(Some(n))),
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => (0, Ok(None)),
|
||||
Err(e) => (0, Err(e)),
|
||||
}) {
|
||||
Ok(Ok(Some(0))) => {
|
||||
remote_fin = true;
|
||||
tcp.close();
|
||||
}
|
||||
Ok(Err(_)) => tcp.abort(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
iface.poll(now, &mut wire, &mut sockets);
|
||||
for p in wire.output.drain(..) {
|
||||
reply(origin, p);
|
||||
}
|
||||
let tcp = sockets.get::<Socket>(handle);
|
||||
// A reset during the handshake returns smoltcp to Listen. This
|
||||
// worker owns exactly one physical connection and must never accept
|
||||
// a second SYN on that connection or retain an idle flow slot.
|
||||
if matches!(tcp.state(), State::Listen | State::Closed) {
|
||||
return;
|
||||
}
|
||||
let delay = iface
|
||||
.poll_delay(now, &sockets)
|
||||
.map(Duration::from)
|
||||
.unwrap_or(Duration::from_secs(3600));
|
||||
tokio::select! {
|
||||
packet = incoming.recv() => match packet { Some(p) => wire.input = Some(p), None => return },
|
||||
ready = upstream.readable(), if !remote_fin && tcp.can_send() => { if ready.is_err() { return; } }
|
||||
ready = upstream.writable(), if tcp.can_recv() => { if ready.is_err() { return; } }
|
||||
_ = tokio::time::sleep(delay) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
//! These run on loopback on every host. The gateway uses the same code as
|
||||
//! Windows, with a loopback source in place of the pinned physical adapter.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
use tokio::net::{TcpListener, UdpSocket};
|
||||
|
||||
fn route() -> Route {
|
||||
Route {
|
||||
network: NetworkId::from_bytes([4; 32]),
|
||||
peer: iroh::SecretKey::from_bytes(&[3; 32]).public(),
|
||||
}
|
||||
}
|
||||
|
||||
fn addr() -> Ipv4Addr {
|
||||
Ipv4Addr::new(10, 13, 37, 9)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_udp_flow_keeps_its_external_port_while_the_upstream_changes_and_stops_with_its_offer() {
|
||||
let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let route = route();
|
||||
let (replies, mut rx) = mpsc::channel(8);
|
||||
let gateway = Gateway::new(1280, move |r, p| {
|
||||
assert_eq!(r, route);
|
||||
let _ = replies.try_send(p);
|
||||
});
|
||||
let physical = Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
};
|
||||
gateway.configure(vec![(route.network, physical)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 10403,
|
||||
dport: server.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Udp,
|
||||
};
|
||||
let mut port = None;
|
||||
for body in [b"first".as_slice(), b"after upstream change"] {
|
||||
gateway.configure(vec![(route.network, physical)]);
|
||||
assert!(gateway.forward(route, udp_packet(flow, body).unwrap()));
|
||||
let mut buf = [0; 128];
|
||||
let (n, from) = tokio::time::timeout(Duration::from_secs(2), server.recv_from(&mut buf))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&buf[..n], body);
|
||||
assert_eq!(port.get_or_insert(from.port()), &from.port());
|
||||
server.send_to(body, from).await.unwrap();
|
||||
let answer = tokio::time::timeout(Duration::from_secs(2), rx.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(crate::vip::packet::tuple(&answer), Some(flow.reverse()));
|
||||
assert_eq!(&answer[28..], body);
|
||||
}
|
||||
gateway.configure(Vec::new());
|
||||
assert!(!gateway.forward(route, udp_packet(flow, b"withdrawn").unwrap()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refused_tcp_returns_a_reset_to_the_originating_client() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
let (tx, mut rx) = mpsc::channel(2);
|
||||
let route = route();
|
||||
let gateway = Gateway::new(1280, move |r, p| {
|
||||
assert_eq!(r, route);
|
||||
let _ = tx.try_send(p);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
route.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 42000,
|
||||
dport: port,
|
||||
protocol: Protocol::Tcp,
|
||||
};
|
||||
let mut syn = vec![0; 40];
|
||||
syn[0] = 0x45;
|
||||
syn[2..4].copy_from_slice(&40u16.to_be_bytes());
|
||||
syn[8] = 64;
|
||||
syn[9] = 6;
|
||||
syn[32] = 0x50;
|
||||
syn[33] = 2;
|
||||
let checksum = crate::vip::packet::checksum(&syn[..20]);
|
||||
syn[10..12].copy_from_slice(&checksum.to_be_bytes());
|
||||
assert!(gateway.forward(route, crate::vip::packet::rewrite(&syn, flow).unwrap()));
|
||||
let answer = tokio::time::timeout(Duration::from_secs(2), rx.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(crate::vip::packet::tcp_reset(&answer));
|
||||
assert_eq!(crate::vip::packet::tuple(&answer), Some(flow.reverse()));
|
||||
}
|
||||
|
||||
fn tcp_packet(tuple: Tuple, flags: u8, seq: u32, ack: u32, body: &[u8]) -> Bytes {
|
||||
let mut bytes = ip_packet(tuple.src, tuple.dst, 6, 20 + body.len()).unwrap();
|
||||
bytes[24..28].copy_from_slice(&seq.to_be_bytes());
|
||||
bytes[28..32].copy_from_slice(&ack.to_be_bytes());
|
||||
bytes[32] = 0x50;
|
||||
bytes[33] = flags;
|
||||
bytes[34..36].copy_from_slice(&65535u16.to_be_bytes());
|
||||
bytes[40..].copy_from_slice(body);
|
||||
packet::rewrite(&bytes, tuple).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_tcp_stream_to_the_same_destination_survives_offer_reconciliation() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
for expected in [b"one", b"two"] {
|
||||
let mut body = [0; 3];
|
||||
socket.read_exact(&mut body).await.unwrap();
|
||||
assert_eq!(&body, expected);
|
||||
socket.write_all(&body).await.unwrap();
|
||||
}
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(4), async {
|
||||
let route = route();
|
||||
let (tx, mut rx) = mpsc::channel(16);
|
||||
let gateway = Gateway::new(1280, move |r, p| {
|
||||
assert_eq!(r, route);
|
||||
let _ = tx.try_send(p);
|
||||
});
|
||||
let physical = Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
};
|
||||
gateway.configure(vec![(route.network, physical)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 43210,
|
||||
dport: port,
|
||||
protocol: Protocol::Tcp,
|
||||
};
|
||||
let mut seq: u32 = 123;
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 2, seq, 0, &[])));
|
||||
let synack = rx.recv().await.unwrap();
|
||||
assert!(packet::syn_ack(&synack));
|
||||
let mut ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
|
||||
seq += 1;
|
||||
for body in [b"one", b"two"] {
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 0x18, seq, ack, body)));
|
||||
seq += body.len() as u32;
|
||||
loop {
|
||||
let p = rx.recv().await.unwrap();
|
||||
let tcp = TcpPacket::new_checked(&p[20..]).unwrap();
|
||||
if !tcp.payload().is_empty() {
|
||||
assert_eq!(tcp.payload(), body);
|
||||
ack = ack.wrapping_add(body.len() as u32);
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 0x10, seq, ack, &[])));
|
||||
break;
|
||||
}
|
||||
}
|
||||
// A configuration change for a different membership cannot create a new B socket.
|
||||
gateway.configure(vec![
|
||||
(route.network, physical),
|
||||
(NetworkId::from_bytes([7; 32]), physical),
|
||||
]);
|
||||
}
|
||||
server.await.unwrap();
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Two disposable Wintun adapters provide an offline "WAN" and an upstream.
|
||||
/// A longer prefix on the latter captures local applications for the same IP.
|
||||
#[cfg(all(windows, feature = "tun-device"))]
|
||||
#[tokio::test]
|
||||
#[ignore = "requires an elevated disposable Windows runner and wintun.dll"]
|
||||
async fn physical_member_sockets_survive_a_more_specific_wintun_route() {
|
||||
use crate::overlay::{
|
||||
Cidr,
|
||||
provision::{InterfacePlan, InterfaceProvisioner, WintunProvisioner},
|
||||
tun::TunDevice,
|
||||
};
|
||||
let wan = Ipv4Addr::new(198, 18, 222, 1);
|
||||
let upstream = Ipv4Addr::new(198, 18, 222, 5);
|
||||
let site = Ipv4Addr::new(198, 18, 222, 6);
|
||||
for dev in netdev::get_interfaces() {
|
||||
assert!(
|
||||
dev.ipv4
|
||||
.iter()
|
||||
.all(|net| !net.contains(&wan) && !net.contains(&site)),
|
||||
"test subnet is in use on {}",
|
||||
dev.name
|
||||
);
|
||||
}
|
||||
async fn read(device: &dyn TunDevice, endpoint: SocketAddrV4, body: &[u8]) -> Tuple {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let p = device.recv().await.unwrap();
|
||||
if let Some(t) = packet::tuple(&p)
|
||||
&& t.dst == *endpoint.ip()
|
||||
&& t.dport == endpoint.port()
|
||||
&& p.get(28..) == Some(body)
|
||||
{
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
async fn wait_source(site: SocketAddrV4, wanted: Ipv4Addr) {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let s = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
|
||||
if s.connect(site).await.is_ok() && s.local_addr().unwrap().ip() == wanted {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let id = rand::random::<u32>();
|
||||
let provision = WintunProvisioner::new().unwrap();
|
||||
let uplink = provision
|
||||
.reconcile(&InterfacePlan::new(
|
||||
format!("tsfw-a-{id:x}"),
|
||||
1280,
|
||||
vec![Cidr::new(wan.into(), 24).unwrap()],
|
||||
))
|
||||
.await
|
||||
.unwrap()
|
||||
.device
|
||||
.unwrap();
|
||||
let site = SocketAddrV4::new(site, 38201);
|
||||
wait_source(site, wan).await;
|
||||
let index = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.find(|i| i.ipv4.iter().any(|a| a.addr() == wan))
|
||||
.unwrap()
|
||||
.index;
|
||||
let physical = Physical {
|
||||
index,
|
||||
address: wan,
|
||||
};
|
||||
let origin = route();
|
||||
let (tx, mut rx) = mpsc::channel(8);
|
||||
let gateway = Gateway::new(1280, move |_, packet| {
|
||||
let _ = tx.try_send(packet);
|
||||
});
|
||||
gateway.configure(vec![(origin.network, physical)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: *site.ip(),
|
||||
sport: 21002,
|
||||
dport: site.port(),
|
||||
protocol: Protocol::Udp,
|
||||
};
|
||||
let mut send = async |tuple, payload: &[u8]| {
|
||||
assert!(gateway.forward(origin, udp_packet(tuple, payload).unwrap()));
|
||||
let observed = read(&*uplink, site, payload).await;
|
||||
assert_eq!(observed.src, wan);
|
||||
uplink
|
||||
.send(udp_packet(observed.reverse(), payload).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let back = tokio::time::timeout(Duration::from_secs(5), rx.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(packet::tuple(&back), Some(tuple.reverse()));
|
||||
observed.sport
|
||||
};
|
||||
let initial = send(flow, b"before").await;
|
||||
let capture = provision
|
||||
.reconcile(&InterfacePlan::new(
|
||||
format!("tsfw-c-{id:x}"),
|
||||
1280,
|
||||
vec![Cidr::new(upstream.into(), 30).unwrap()],
|
||||
))
|
||||
.await
|
||||
.unwrap()
|
||||
.device
|
||||
.unwrap();
|
||||
wait_source(site, upstream).await;
|
||||
let local = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
|
||||
local.send_to(b"local B", site).await.unwrap();
|
||||
assert_eq!(read(&*capture, site, b"local B").await.src, upstream);
|
||||
assert_eq!(send(flow, b"same A socket").await, initial);
|
||||
send(
|
||||
Tuple {
|
||||
sport: 21003,
|
||||
..flow
|
||||
},
|
||||
b"new A socket",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Raw ICMP uses the identical physical interface selection and restores A's
|
||||
// identifier and sequence after reading the actual reply from the uplink.
|
||||
let mut ping = ip_packet(addr(), *site.ip(), 1, 12).unwrap();
|
||||
ping[20] = 8;
|
||||
ping[24..32].copy_from_slice(b"pingdata");
|
||||
let checksum = packet::checksum(&ping[20..]);
|
||||
ping[22..24].copy_from_slice(&checksum.to_be_bytes());
|
||||
assert!(gateway.forward(origin, ping.into()));
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let wire = uplink.recv().await.unwrap();
|
||||
let Some(n) = packet::header(&wire) else {
|
||||
continue;
|
||||
};
|
||||
if wire[9] != 1 || wire.get(n + 8..) != Some(b"data") {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(packet::addresses(&wire), Some((wan, *site.ip())));
|
||||
let mut pong = ip_packet(*site.ip(), wan, 1, wire.len() - n).unwrap();
|
||||
pong[20..].copy_from_slice(&wire[n..]);
|
||||
pong[20..24].fill(0);
|
||||
let checksum = packet::checksum(&pong[20..]);
|
||||
pong[22..24].copy_from_slice(&checksum.to_be_bytes());
|
||||
uplink.send(pong.into()).await.unwrap();
|
||||
break;
|
||||
}
|
||||
let reply = rx.recv().await.unwrap();
|
||||
assert_eq!(packet::addresses(&reply), Some((*site.ip(), addr())));
|
||||
assert_eq!(&reply[24..], b"pingdata");
|
||||
assert_eq!(packet::checksum(&reply[20..]), 0);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resetting_a_half_open_mesh_handshake_closes_the_physical_socket() {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let route = route();
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
let gateway = Gateway::new(1280, move |_, packet| {
|
||||
let _ = tx.try_send(packet);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
route.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 43211,
|
||||
dport: listener.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Tcp,
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 2, 500, 0, &[])));
|
||||
let (mut physical, _) = listener.accept().await.unwrap();
|
||||
let synack = rx.recv().await.unwrap();
|
||||
assert!(packet::syn_ack(&synack));
|
||||
let ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 0x14, 501, ack, &[])));
|
||||
assert_eq!(physical.read(&mut [0; 1]).await.unwrap(), 0);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_server_half_close_still_receives_the_members_final_bytes_and_fin() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let (out, mut rx) = mpsc::channel(8);
|
||||
let origin = route();
|
||||
let gateway = Gateway::new(1280, move |_, packet| {
|
||||
let _ = out.try_send(packet);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
origin.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 42041,
|
||||
dport: listener.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Tcp,
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
assert!(gateway.forward(origin, tcp_packet(flow, 2, 200, 0, &[])));
|
||||
let (mut server, _) = listener.accept().await.unwrap();
|
||||
server.shutdown().await.unwrap();
|
||||
let synack = rx.recv().await.unwrap();
|
||||
assert!(packet::syn_ack(&synack));
|
||||
let ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
|
||||
assert!(gateway.forward(origin, tcp_packet(flow, 0x10, 201, ack, &[])));
|
||||
loop {
|
||||
let p = rx.recv().await.unwrap();
|
||||
if TcpPacket::new_checked(&p[20..]).unwrap().fin() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(gateway.forward(
|
||||
origin,
|
||||
tcp_packet(flow, 0x19, 201, ack.wrapping_add(1), b"last bytes")
|
||||
));
|
||||
let mut received = Vec::new();
|
||||
server.read_to_end(&mut received).await.unwrap();
|
||||
assert_eq!(received, b"last bytes");
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn at_capacity_existing_udp_flows_continue_and_a_new_tuple_is_dropped() {
|
||||
let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let origin = route();
|
||||
let gateway = Gateway::new(1280, |_, _| {});
|
||||
gateway.configure(vec![(
|
||||
origin.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 1024,
|
||||
dport: server.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Udp,
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
let mut buf = [0; 2];
|
||||
for i in 0..EXIT_FORWARD_FLOWS {
|
||||
let p = udp_packet(
|
||||
Tuple {
|
||||
sport: flow.sport + i as u16,
|
||||
..flow
|
||||
},
|
||||
b"a",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(gateway.forward(origin, p));
|
||||
assert_eq!(server.recv(&mut buf).await.unwrap(), 1);
|
||||
}
|
||||
let extra = Tuple {
|
||||
sport: u16::MAX,
|
||||
..flow
|
||||
};
|
||||
assert!(gateway.forward(origin, udp_packet(extra, b"no").unwrap()));
|
||||
assert!(gateway.forward(origin, udp_packet(flow, b"ok").unwrap()));
|
||||
assert_eq!(server.recv(&mut buf).await.unwrap(), 2);
|
||||
assert_eq!(&buf, b"ok");
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Winsock takes the IPv4 interface index in network byte order.
|
||||
#![allow(unsafe_code)]
|
||||
use std::{io, os::windows::io::AsRawSocket};
|
||||
use windows_sys::Win32::Networking::WinSock::{
|
||||
IP_UNICAST_IF, IPPROTO_IP, SOCKET_ERROR, WSAGetLastError, setsockopt,
|
||||
};
|
||||
|
||||
pub(super) fn pin(socket: &impl AsRawSocket, index: u32) -> io::Result<()> {
|
||||
#[cfg(test)]
|
||||
if index == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if index == 0 {
|
||||
return Err(io::Error::other("no physical exit interface"));
|
||||
}
|
||||
let bytes = index.to_be_bytes();
|
||||
// The socket owner stays alive for the call. Winsock reads exactly the
|
||||
// four bytes of the interface index and retains no pointer to them.
|
||||
if unsafe {
|
||||
setsockopt(
|
||||
socket.as_raw_socket() as _,
|
||||
IPPROTO_IP,
|
||||
IP_UNICAST_IF,
|
||||
bytes.as_ptr(),
|
||||
4,
|
||||
)
|
||||
} == SOCKET_ERROR
|
||||
{
|
||||
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,6 +5,15 @@
|
||||
//! system sees. It is kept apart from the broadcast rules, which have a
|
||||
//! different lifetime and different tags.
|
||||
|
||||
/// Plaintext IP bytes carried through the client's currently selected internet exit.
|
||||
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExitTraffic {
|
||||
/// Bytes accepted by the carrier for off-mesh destinations.
|
||||
pub tx_bytes: u64,
|
||||
/// Internet reply bytes delivered to the local interface.
|
||||
pub rx_bytes: u64,
|
||||
}
|
||||
|
||||
/// How one set of host rules went.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RuleSetReport {
|
||||
|
||||
@@ -91,6 +91,12 @@ pub trait ExitHostRules: Send + Sync + std::fmt::Debug + 'static {
|
||||
Box::pin(async { None })
|
||||
}
|
||||
|
||||
/// The physical interface index and IPv4 address used by a userspace exit.
|
||||
/// Kernel-forwarding hosts do not need to expose an egress socket address.
|
||||
fn forwarded_uplink(&self) -> Option<(u32, std::net::Ipv4Addr)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether using an exit node on this host needs the underlay addresses
|
||||
/// the agent talks to, because the host cannot exempt the agent's own
|
||||
/// traffic from the default route by user id (Windows). The default is no.
|
||||
@@ -112,6 +118,9 @@ pub fn exit_tag_prefix(interface: &str) -> String {
|
||||
/// The one-line detail for a set of offer outcomes.
|
||||
pub fn offer_detail(outcome: &RuleOutcome, range: &Ipv4Range) -> String {
|
||||
match outcome {
|
||||
RuleOutcome::Applied if cfg!(windows) => {
|
||||
format!("physical TCP, UDP and ICMP echo forwarding for {range}")
|
||||
}
|
||||
RuleOutcome::Applied => format!("masquerade + forward for {range} in place"),
|
||||
RuleOutcome::Failed(reason) => reason.clone(),
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//!
|
||||
//! # Offering
|
||||
//!
|
||||
//! For every network that offers this agent as an exit node, three rules,
|
||||
//! For every network that offers this agent as an exit node, rules
|
||||
//! selected by that network's range and carrying the tag
|
||||
//! `tsunagi-exit:<if>:<range>`:
|
||||
//!
|
||||
@@ -11,6 +11,8 @@
|
||||
//! -t nat POSTROUTING -s <range> ! -o <if> -j MASQUERADE
|
||||
//! -t filter FORWARD -i <if> -s <range> ! -o <if> -j ACCEPT
|
||||
//! -t filter FORWARD -o <if> -d <range> -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
|
||||
//! -t mangle PREROUTING -i <if> -s <range> -j MARK --set-xmark <underlay bit>
|
||||
//! -t mangle PREROUTING ! -i <if> -m conntrack --ctorigsrc <range> --ctdir REPLY --ctstate SNAT -j MARK --set-xmark <underlay bit>
|
||||
//! ```
|
||||
//!
|
||||
//! `! -o <if>` is the egress without naming it: whatever interface the
|
||||
@@ -28,7 +30,7 @@
|
||||
//! 5205: from all fwmark 0x40000000/0x40000000 lookup main
|
||||
//! 5206: from all uidrange <euid>-<euid> lookup main
|
||||
//! 5290: from all lookup main suppress_prefixlength 0
|
||||
//! 5300: from all lookup 0x7473
|
||||
//! 5300: from all iif lo lookup 0x7473
|
||||
//! ```
|
||||
//!
|
||||
//! The first two keep the agent's *own* sockets and marked replies off the tunnel: its QUIC, relay,
|
||||
@@ -56,7 +58,11 @@ use super::linux::{
|
||||
use super::linux_exit_mark;
|
||||
|
||||
/// The chains the offering rules live in: `(table, chain)`.
|
||||
const CHAINS: [(&str, &str); 2] = [("nat", "POSTROUTING"), ("filter", "FORWARD")];
|
||||
const CHAINS: [(&str, &str); 3] = [
|
||||
("nat", "POSTROUTING"),
|
||||
("filter", "FORWARD"),
|
||||
("mangle", "PREROUTING"),
|
||||
];
|
||||
|
||||
/// One firewall rule: where it goes, and its match and target.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -70,7 +76,7 @@ fn owned(words: &[&str]) -> Vec<String> {
|
||||
words.iter().map(|word| word.to_string()).collect()
|
||||
}
|
||||
|
||||
/// The three rules of one offered range.
|
||||
/// The rules of one offered range.
|
||||
///
|
||||
/// Each carries a comment naming its interface and range, which is how it is
|
||||
/// found again. A kernel without the `comment` match (small router builds
|
||||
@@ -125,6 +131,37 @@ fn offer_rules(interface: &str, range: &Ipv4Range, comment: bool) -> Vec<Rule> {
|
||||
&["-j", "ACCEPT"],
|
||||
),
|
||||
},
|
||||
// These marks select the physical routing table for clients we
|
||||
// forward, including the reverse-path check on physical replies.
|
||||
// The conntrack original tuple survives switching our own upstream.
|
||||
Rule {
|
||||
table: "mangle",
|
||||
chain: "PREROUTING",
|
||||
spec: spec(
|
||||
&["-i", interface, "-s", &range_text],
|
||||
&["-j", "MARK", "--set-xmark", linux_exit_mark::MARK],
|
||||
),
|
||||
},
|
||||
Rule {
|
||||
table: "mangle",
|
||||
chain: "PREROUTING",
|
||||
spec: spec(
|
||||
&[
|
||||
"!",
|
||||
"-i",
|
||||
interface,
|
||||
"-m",
|
||||
"conntrack",
|
||||
"--ctorigsrc",
|
||||
&range_text,
|
||||
"--ctdir",
|
||||
"REPLY",
|
||||
"--ctstate",
|
||||
"SNAT",
|
||||
],
|
||||
&["-j", "MARK", "--set-xmark", linux_exit_mark::MARK],
|
||||
),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -159,7 +196,7 @@ struct Found {
|
||||
|
||||
/// Every rule in an `iptables -S <chain>` listing that is ours: carrying a
|
||||
/// tag that starts with `prefix`, or, on a kernel with no `comment` match,
|
||||
/// being exactly one of the three rules this module writes for some range.
|
||||
/// being exactly one of the rules this module writes for some range.
|
||||
/// Anything else in the chain is left alone.
|
||||
fn tagged_rules(listing: &str, chain: &str, prefix: &str) -> Vec<Found> {
|
||||
// `tsunagi-exit:<interface>:`
|
||||
@@ -198,7 +235,7 @@ fn uncommented_tag(interface: &str, chain: &str, rest: &[String]) -> Option<Stri
|
||||
}
|
||||
let range: Ipv4Range = rest
|
||||
.windows(2)
|
||||
.find(|pair| pair[0] == "-s" || pair[0] == "-d")
|
||||
.find(|pair| matches!(pair[0].as_str(), "-s" | "-d" | "--ctorigsrc"))
|
||||
.and_then(|pair| pair[1].parse().ok())?;
|
||||
offer_rules(interface, &range, false)
|
||||
.iter()
|
||||
@@ -380,7 +417,7 @@ fn read_sysctl(path: &str) -> Option<String> {
|
||||
std::fs::read_to_string(path).ok()
|
||||
}
|
||||
|
||||
fn check_kernel_rpf(overlay: &str) -> Result<(), String> {
|
||||
fn check_kernel_rpf(overlay: &str, uid: u32) -> Result<(), String> {
|
||||
let directory = "/proc/sys/net/ipv4/conf";
|
||||
let value = |name: &str, setting: &str| -> Result<u32, String> {
|
||||
read_sysctl(&format!("{directory}/{name}/{setting}"))
|
||||
@@ -391,7 +428,7 @@ fn check_kernel_rpf(overlay: &str) -> Result<(), String> {
|
||||
for entry in std::fs::read_dir(directory).map_err(|err| err.to_string())? {
|
||||
let entry = entry.map_err(|err| err.to_string())?;
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if name != "all" && name != "default" && name != "lo" && name != overlay {
|
||||
if name != "all" && name != "default" && name != "lo" && (name != overlay || uid == 0) {
|
||||
interfaces.push((
|
||||
name.clone(),
|
||||
value(&name, "rp_filter")?,
|
||||
@@ -481,7 +518,7 @@ impl LinuxHostRules {
|
||||
}
|
||||
let name = interface.to_string();
|
||||
let prepared = Self::blocking(move || {
|
||||
check_kernel_rpf(&name)?;
|
||||
check_kernel_rpf(&name, euid)?;
|
||||
linux_exit_mark::install(
|
||||
&run_firewall,
|
||||
&name,
|
||||
@@ -567,7 +604,7 @@ impl LinuxHostRules {
|
||||
.ok()
|
||||
.and_then(|s| parse_euid(&s))
|
||||
.ok_or("cannot read agent UID")?;
|
||||
check_kernel_rpf(&work_name)?;
|
||||
check_kernel_rpf(&work_name, uid)?;
|
||||
let v6 = std::path::Path::new("/proc/sys/net/ipv6").is_dir();
|
||||
let sockets = linux_exit_mark::local_sockets(uid, v6)?;
|
||||
if previous
|
||||
@@ -671,7 +708,21 @@ mod tests {
|
||||
#[test]
|
||||
fn the_rules_masquerade_the_range_out_of_every_other_interface_and_forward_it() {
|
||||
let rules = offer_rules("tsun0", &range(), true);
|
||||
assert_eq!(rules.len(), 3);
|
||||
assert_eq!(rules.len(), 5);
|
||||
let outgoing = words(&rules[3].spec);
|
||||
let replies = words(&rules[4].spec);
|
||||
assert!(
|
||||
outgoing.starts_with("-i tsun0 -s 10.13.37.0/24 "),
|
||||
"{outgoing}"
|
||||
);
|
||||
assert!(
|
||||
replies.contains("--ctorigsrc 10.13.37.0/24 --ctdir REPLY --ctstate SNAT"),
|
||||
"{replies}"
|
||||
);
|
||||
for rule in &rules[3..] {
|
||||
assert_eq!((rule.table, rule.chain), ("mangle", "PREROUTING"));
|
||||
assert!(words(&rule.spec).ends_with("-j MARK --set-xmark 0x40000000/0x40000000"));
|
||||
}
|
||||
assert_eq!(
|
||||
words(&rules[0].spec),
|
||||
"-s 10.13.37.0/24 ! -o tsun0 -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j MASQUERADE"
|
||||
@@ -805,7 +856,7 @@ mod tests {
|
||||
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||
let inserted = fake.verbs("-I");
|
||||
assert_eq!(inserted.len(), 3, "{inserted:?}");
|
||||
assert_eq!(inserted.len(), 5, "{inserted:?}");
|
||||
assert!(
|
||||
inserted.iter().all(|call| !call.contains("comment")),
|
||||
"{inserted:?}"
|
||||
@@ -837,12 +888,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_host_gets_the_three_rules() {
|
||||
fn a_fresh_host_gets_the_offer_rules() {
|
||||
let fake = Fake::new(false);
|
||||
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||
let inserted = fake.verbs("-I");
|
||||
assert_eq!(inserted.len(), 3, "{inserted:?}");
|
||||
assert_eq!(inserted.len(), 5, "{inserted:?}");
|
||||
assert!(inserted[0].contains("-t nat -I POSTROUTING 1"));
|
||||
assert!(fake.verbs("-D").is_empty());
|
||||
}
|
||||
@@ -857,6 +908,15 @@ mod tests {
|
||||
)
|
||||
.with_rule("filter", &format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"))
|
||||
.with_rule("filter", &format!("-A FORWARD -o tsun0 -m comment --comment {tag} -j ACCEPT"));
|
||||
let fake = offer_rules("tsun0", &range(), true)
|
||||
.into_iter()
|
||||
.filter(|rule| rule.chain == "PREROUTING")
|
||||
.fold(fake, |fake, rule| {
|
||||
fake.with_rule(
|
||||
rule.table,
|
||||
&format!("-A {} {}", rule.chain, words(&rule.spec)),
|
||||
)
|
||||
});
|
||||
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||
assert!(fake.verbs("-I").is_empty());
|
||||
@@ -875,7 +935,7 @@ mod tests {
|
||||
"-A POSTROUTING -s 10.99.0.0/24 -m comment --comment {old_tag} -j MASQUERADE"
|
||||
),
|
||||
)
|
||||
// Only one of the three for the current range.
|
||||
// Only one rule for the current range.
|
||||
.with_rule(
|
||||
"filter",
|
||||
&format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"),
|
||||
@@ -897,7 +957,7 @@ mod tests {
|
||||
deleted.iter().all(|call| !call.contains("eth0")),
|
||||
"{deleted:?}"
|
||||
);
|
||||
assert_eq!(fake.verbs("-I").len(), 3);
|
||||
assert_eq!(fake.verbs("-I").len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -467,3 +467,214 @@ while True:
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
const CHAIN_TEST: &str = "overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit";
|
||||
|
||||
fn chain_namespace(role: &str) -> Namespace {
|
||||
let name = format!("tsng-chain-{role}-{}", std::process::id());
|
||||
ip(&["netns", "add", &name]);
|
||||
let guard = Namespace(name);
|
||||
ip(&["-n", &guard.0, "link", "set", "lo", "up"]);
|
||||
guard
|
||||
}
|
||||
|
||||
fn connect(a: &Namespace, left: &str, b: &Namespace, right: &str) {
|
||||
ip(&[
|
||||
"link", "add", left, "netns", &a.0, "type", "veth", "peer", "name", right, "netns", &b.0,
|
||||
]);
|
||||
ip(&["-n", &a.0, "link", "set", left, "up"]);
|
||||
ip(&["-n", &b.0, "link", "set", right, "up"]);
|
||||
}
|
||||
|
||||
fn python_in(namespace: &str) -> Command {
|
||||
let mut cmd = Command::new("ip");
|
||||
cmd.args(["netns", "exec", namespace, "python3"]);
|
||||
cmd
|
||||
}
|
||||
|
||||
fn chain_echo(namespace: &Namespace, name: &str) -> Echo {
|
||||
let code = r#"import socketserver, sys
|
||||
class Echo(socketserver.StreamRequestHandler):
|
||||
def handle(self):
|
||||
for line in self.rfile:
|
||||
self.wfile.write(f'{sys.argv[1]} {self.client_address[0]} '.encode() + line)
|
||||
with socketserver.ThreadingTCPServer(('198.51.100.2', 42100), Echo) as server:
|
||||
print('ready', flush=True)
|
||||
server.serve_forever()
|
||||
"#;
|
||||
let mut server = Echo(
|
||||
python_in(&namespace.0)
|
||||
.args(["-u", "-c", code, name])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let mut ready = String::new();
|
||||
BufReader::new(server.0.stdout.take().unwrap())
|
||||
.read_line(&mut ready)
|
||||
.unwrap();
|
||||
assert_eq!(ready.trim(), "ready");
|
||||
server
|
||||
}
|
||||
|
||||
fn short_chain_probe(mut cmd: Command, phase: &str, expected: &str) {
|
||||
let probe = r#"import socket
|
||||
with socket.create_connection(('198.51.100.2', 42100), timeout=3) as s:
|
||||
s.sendall(b'new\n')
|
||||
print(s.makefile('rb').readline().decode().strip())
|
||||
"#;
|
||||
let result = cmd.args(["-c", probe]).output().unwrap();
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"TCP probe {phase} expected {expected}: {}\n{}\n{}\n{}",
|
||||
String::from_utf8_lossy(&result.stderr),
|
||||
ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]),
|
||||
ip(&["-4", "rule", "show"]),
|
||||
ip(&["neigh", "show"]),
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), expected);
|
||||
}
|
||||
|
||||
fn chain_middle(a: &str) {
|
||||
use super::{BroadcastHostRules, ExitHostPlan, RuleOutcome};
|
||||
let range = "10.13.37.0/24".parse().unwrap();
|
||||
std::fs::write("/proc/sys/net/ipv4/ip_forward", "1").unwrap();
|
||||
// A root agent's UID bypass can also match a kernel reverse lookup.
|
||||
// Both the NAT reply from the uplink and the reply from C on tsun0 must
|
||||
// survive strict filtering when the remote Internet address is identical.
|
||||
for setting in ["rp_filter", "src_valid_mark"] {
|
||||
std::fs::write(format!("/proc/sys/net/ipv4/conf/all/{setting}"), "1").unwrap();
|
||||
}
|
||||
let filter: Vec<String> = [
|
||||
"-t",
|
||||
"mangle",
|
||||
"-A",
|
||||
"PREROUTING",
|
||||
"-m",
|
||||
"rpfilter",
|
||||
"--invert",
|
||||
"--validmark",
|
||||
"-j",
|
||||
"DROP",
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let rpf = run_firewall(false, &filter);
|
||||
assert!(
|
||||
matches!(rpf, super::linux::Ran::Exited { success: true, .. }),
|
||||
"{rpf:?}"
|
||||
);
|
||||
let provisioner = NetlinkProvisioner::new().unwrap();
|
||||
let host = provisioner.host_rules();
|
||||
let exit = host.exit_rules().unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let apply = |select| {
|
||||
let plan = ExitHostPlan {
|
||||
interface: "tsun0".into(),
|
||||
offer: vec![range],
|
||||
overlay: vec![range],
|
||||
client: select,
|
||||
client_source: select.then(|| "10.13.37.1".parse().unwrap()),
|
||||
..Default::default()
|
||||
};
|
||||
let result = runtime.block_on(exit.apply(&plan));
|
||||
assert_eq!(result.offer, [(range, RuleOutcome::Applied)]);
|
||||
assert_eq!(result.client, select.then_some(RuleOutcome::Applied));
|
||||
};
|
||||
apply(false);
|
||||
// The socket is created once and remains open across both reconciliations.
|
||||
let persistent = r#"import socket, sys
|
||||
with socket.create_connection(('198.51.100.2',42100), timeout=3) as s:
|
||||
out = s.makefile('rb')
|
||||
for line in sys.stdin.buffer:
|
||||
s.sendall(line)
|
||||
print(out.readline().decode().strip(), flush=True)
|
||||
"#;
|
||||
let mut stream = Echo(
|
||||
python_in(a)
|
||||
.args(["-u", "-c", persistent])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let mut input = stream.0.stdin.take().unwrap();
|
||||
let mut output = BufReader::new(stream.0.stdout.take().unwrap());
|
||||
for (change, phase, b_egress) in [
|
||||
(None, "before", "uplink 192.0.2.1 new"),
|
||||
(Some(true), "selected", "exit-c 10.13.37.1 new"),
|
||||
(Some(false), "cleared", "uplink 192.0.2.1 new"),
|
||||
] {
|
||||
if let Some(selected) = change {
|
||||
apply(selected);
|
||||
}
|
||||
writeln!(input, "{phase}").unwrap();
|
||||
let mut reply = String::new();
|
||||
output.read_line(&mut reply).unwrap();
|
||||
assert_eq!(
|
||||
reply.trim(),
|
||||
format!("uplink 192.0.2.1 {phase}"),
|
||||
"ongoing TCP stream from A"
|
||||
);
|
||||
short_chain_probe(python_in(a), phase, "uplink 192.0.2.1 new");
|
||||
// A regular application on B sends to exactly the same IP and port as A.
|
||||
let mut local = Command::new("python3");
|
||||
local.uid(991).gid(991);
|
||||
short_chain_probe(local, phase, b_egress);
|
||||
}
|
||||
runtime.block_on(exit.clear("tsun0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs Linux network namespaces, iproute2, iptables and Python"]
|
||||
fn serving_an_established_flow_while_switching_the_local_exit() {
|
||||
if let Ok(a) = std::env::var("TSUNAGI_EXIT_CHAIN_A") {
|
||||
chain_middle(&a);
|
||||
return;
|
||||
}
|
||||
let a = chain_namespace("a");
|
||||
let b = chain_namespace("b");
|
||||
let c = chain_namespace("c");
|
||||
let uplink = chain_namespace("wan");
|
||||
// Emulate the one overlay interface on B. The bridge is a separate
|
||||
// namespace so that A, B and C see only packets on their own veth.
|
||||
let mesh = chain_namespace("lan");
|
||||
ip(&["-n", &mesh.0, "link", "add", "mesh", "type", "bridge"]);
|
||||
ip(&["-n", &mesh.0, "link", "set", "mesh", "up"]);
|
||||
for (ns, port, address) in [
|
||||
(&a, "to-a", "10.13.37.2/24"),
|
||||
(&b, "to-b", "10.13.37.1/24"),
|
||||
(&c, "to-c", "10.13.37.3/24"),
|
||||
] {
|
||||
connect(ns, "tsun0", &mesh, port);
|
||||
ip(&["-n", &mesh.0, "link", "set", port, "master", "mesh"]);
|
||||
ip(&["-n", &ns.0, "addr", "add", address, "dev", "tsun0"]);
|
||||
}
|
||||
connect(&b, "wan-b", &uplink, "wan");
|
||||
ip(&["-n", &b.0, "addr", "add", "192.0.2.1/24", "dev", "wan-b"]);
|
||||
ip(&["-n", &uplink.0, "addr", "add", "192.0.2.2/24", "dev", "wan"]);
|
||||
ip(&["-n", &a.0, "route", "add", "default", "via", "10.13.37.1"]);
|
||||
ip(&["-n", &b.0, "route", "add", "default", "via", "192.0.2.2"]);
|
||||
for ns in [&uplink, &c] {
|
||||
ip(&["-n", &ns.0, "addr", "add", "198.51.100.2/32", "dev", "lo"]);
|
||||
}
|
||||
let _physical = chain_echo(&uplink, "uplink");
|
||||
let _exit = chain_echo(&c, "exit-c");
|
||||
let result = Command::new("ip")
|
||||
.args(["netns", "exec", &b.0])
|
||||
.arg(std::env::current_exe().unwrap())
|
||||
.args(["--ignored", "--exact", CHAIN_TEST, "--nocapture"])
|
||||
.env("TSUNAGI_EXIT_CHAIN_A", &a.0)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&result.stdout),
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
}
|
||||
@@ -8,8 +8,10 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
/// Outside Tailscale's 0xff0000 mask and ordinary low-bit WireGuard marks.
|
||||
pub(crate) const UNDERLAY_MARK: u32 = 0x4000_0000;
|
||||
pub(crate) const UNDERLAY_MASK: u32 = UNDERLAY_MARK;
|
||||
const MARK: &str = "0x40000000/0x40000000";
|
||||
pub(super) const MARK: &str = "0x40000000/0x40000000";
|
||||
const MASK: &str = "0x40000000";
|
||||
/// An authenticated return packet from this host’s own upstream exit.
|
||||
pub(crate) const EXIT_REPLY_MARK: u32 = 0x2000_0000;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) struct Listener {
|
||||
@@ -141,11 +143,11 @@ fn words(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|s| (*s).into()).collect()
|
||||
}
|
||||
|
||||
fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||
fn rules(interface: &str, uid: u32, ipv6: bool) -> Vec<(&'static str, Vec<String>)> {
|
||||
let tag = tag(interface);
|
||||
let uid = uid.to_string();
|
||||
let owner = uid.to_string();
|
||||
// Insert at position one in this order: final OUTPUT order is MARK, SAVE.
|
||||
vec![
|
||||
let mut rules = vec![
|
||||
(
|
||||
"PREROUTING",
|
||||
words(&[
|
||||
@@ -175,7 +177,7 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||
"-m",
|
||||
"owner",
|
||||
"--uid-owner",
|
||||
&uid,
|
||||
&owner,
|
||||
"-m",
|
||||
"mark",
|
||||
"--mark",
|
||||
@@ -199,7 +201,7 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||
"-m",
|
||||
"owner",
|
||||
"--uid-owner",
|
||||
&uid,
|
||||
&owner,
|
||||
"-m",
|
||||
"comment",
|
||||
"--comment",
|
||||
@@ -210,7 +212,40 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||
MARK,
|
||||
]),
|
||||
),
|
||||
]
|
||||
];
|
||||
if !ipv6 && uid == 0 {
|
||||
// Both xt_rpfilter and the kernel's strict rp_filter perform the
|
||||
// reverse lookup as UID 0. For an established local application's
|
||||
// reply from our upstream, the /0 must point back to this interface,
|
||||
// ahead of the root daemon's UID bypass. The actual packet's LOCAL
|
||||
// destination still uses routing table local at priority zero.
|
||||
rules.push((
|
||||
"PREROUTING",
|
||||
words(&[
|
||||
"-i",
|
||||
interface,
|
||||
"-m",
|
||||
"addrtype",
|
||||
"--dst-type",
|
||||
"LOCAL",
|
||||
"-m",
|
||||
"conntrack",
|
||||
"--ctdir",
|
||||
"REPLY",
|
||||
"--ctstate",
|
||||
"ESTABLISHED,RELATED",
|
||||
"-m",
|
||||
"comment",
|
||||
"--comment",
|
||||
&tag,
|
||||
"-j",
|
||||
"MARK",
|
||||
"--set-xmark",
|
||||
"0x20000000/0x20000000",
|
||||
]),
|
||||
));
|
||||
}
|
||||
rules
|
||||
}
|
||||
|
||||
fn execute(run: RunFamily<'_>, v6: bool, args: Vec<String>) -> Result<String, String> {
|
||||
@@ -295,7 +330,7 @@ fn install_with_listeners(
|
||||
clear(run, interface, v6)?;
|
||||
let result = (|| {
|
||||
for family in [false, true].into_iter().filter(|family| !family || v6) {
|
||||
for (chain, spec) in rules(interface, uid) {
|
||||
for (chain, spec) in rules(interface, uid, family) {
|
||||
let args = words(&["-t", "mangle", "-I", chain, "1"])
|
||||
.into_iter()
|
||||
.chain(spec)
|
||||
@@ -409,6 +444,25 @@ mod tests {
|
||||
assert_eq!(UNDERLAY_MASK & 0x00ff_0000, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_root_daemons_mark_local_ipv4_replies_from_their_own_exit() {
|
||||
for (uid, v6) in [(990, false), (0, true), (0, false)] {
|
||||
let rules = rules("tsun0", uid, v6);
|
||||
let marked: Vec<_> = rules
|
||||
.iter()
|
||||
.filter(|(_, args)| args.contains(&"0x20000000/0x20000000".to_string()))
|
||||
.collect();
|
||||
if uid == 0 && !v6 {
|
||||
assert_eq!(marked.len(), 1);
|
||||
assert_eq!(marked[0].0, "PREROUTING");
|
||||
let text = marked[0].1.join(" ");
|
||||
assert!(text.contains("-i tsun0 -m addrtype --dst-type LOCAL -m conntrack --ctdir REPLY --ctstate ESTABLISHED,RELATED"));
|
||||
} else {
|
||||
assert!(marked.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_retains_other_interfaces_and_rolls_back_partial_ipv6_installation() {
|
||||
let calls = RefCell::new(Vec::new());
|
||||
|
||||
@@ -19,10 +19,10 @@
|
||||
|
||||
use crate::BoxFuture;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
|
||||
use super::macos_exit::{apply_plan, clear_all, run_tool};
|
||||
use super::macos_exit::{HostState, apply_plan, clear_all, refresh_client, run_tool};
|
||||
use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome};
|
||||
|
||||
/// The limited-broadcast destination routed through the overlay interface.
|
||||
@@ -68,17 +68,25 @@ fn firewall_todo(plan: &BroadcastRulesPlan) -> String {
|
||||
/// `pf` plus `route` for exit nodes (see [`super::macos_exit`]).
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MacosHostRules {
|
||||
/// The reference `pfctl -E` handed out, held while exit-node rules need
|
||||
/// `pf` on and released when they are removed.
|
||||
pub(super) pf_token: Arc<Mutex<Option<String>>>,
|
||||
/// The PF reference and the physical routes owned by this agent.
|
||||
state: Arc<HostState>,
|
||||
}
|
||||
|
||||
impl MacosHostRules {
|
||||
/// Creates the host rules.
|
||||
/// Creates host rules with process-lifetime ownership. System services
|
||||
/// use [`Self::with_state_dir`] for recovery after abrupt termination.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Tie crash recovery to this agent's state directory, even when macOS
|
||||
/// assigns its utun a different number on the next run.
|
||||
pub fn with_state_dir(dir: &std::path::Path) -> Self {
|
||||
Self {
|
||||
state: Arc::new(HostState::with_state_dir(dir)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the route, replacing one this agent added earlier so the call
|
||||
/// can be repeated. The delete is best effort: a route that is not there
|
||||
/// is the state the add then reaches anyway.
|
||||
@@ -95,7 +103,7 @@ impl ExitHostRules for MacosHostRules {
|
||||
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||
Box::pin(async move {
|
||||
let job_plan = plan.clone();
|
||||
let token = Arc::clone(&self.pf_token);
|
||||
let token = Arc::clone(&self.state);
|
||||
tokio::task::spawn_blocking(move || apply_plan(&run_tool, &token, &job_plan))
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
@@ -113,10 +121,23 @@ impl ExitHostRules for MacosHostRules {
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
|
||||
Box::pin(async move {
|
||||
if !plan.client {
|
||||
return None;
|
||||
}
|
||||
let state = Arc::clone(&self.state);
|
||||
let plan = plan.clone();
|
||||
tokio::task::spawn_blocking(move || refresh_client(&run_tool, &state, &plan))
|
||||
.await
|
||||
.unwrap_or_else(|err| Some(RuleOutcome::Failed(err.to_string())))
|
||||
})
|
||||
}
|
||||
|
||||
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let name = interface.to_string();
|
||||
let token = Arc::clone(&self.pf_token);
|
||||
let token = Arc::clone(&self.state);
|
||||
let _ = tokio::task::spawn_blocking(move || clear_all(&run_tool, &token, &name)).await;
|
||||
})
|
||||
}
|
||||
|
||||
@@ -9,16 +9,17 @@
|
||||
//!
|
||||
//! ```text
|
||||
//! nat on <egress> inet from <range> to any -> (<egress>)
|
||||
//! pass in quick on <if> inet from <range> to ! <range>
|
||||
//! pass in quick on <if> inet from <range> to ! <range> tag <forwarded> no state
|
||||
//! pass out quick on <if> route-to (<egress> <gateway>) inet from <range> to any tagged <forwarded> no state
|
||||
//! pass out quick on <egress> inet from any to any flags any tagged <forwarded> keep state (if-bound)
|
||||
//! ```
|
||||
//!
|
||||
//! The anchor lives under `com.apple/` on purpose: the stock `/etc/pf.conf`
|
||||
//! evaluates `nat-anchor "com.apple/*"` and `anchor "com.apple/*"`, so the
|
||||
//! rules take effect without editing the user's ruleset. `pf` cannot say
|
||||
//! "every interface but one" in a translation address, so the egress is the
|
||||
//! interface of the default route **when the rules are applied**; after the
|
||||
//! default route moves (Wi-Fi to Ethernet) the rules are re-applied by
|
||||
//! switching the exit node off and on, or restarting the agent.
|
||||
//! interface of the physical default route. An active exit client refreshes
|
||||
//! the rules when this egress changes.
|
||||
//!
|
||||
//! The kernel's `net.inet.ip.forwarding` is only read, never written: it
|
||||
//! changes how the whole host behaves, which is the owner's decision.
|
||||
@@ -29,21 +30,32 @@
|
||||
//! Linux scheme does not carry over. Instead:
|
||||
//!
|
||||
//! ```text
|
||||
//! route add -net 0.0.0.0/1 <gateway> -ifscope <egress>
|
||||
//! route add -net 128.0.0.0/1 <gateway> -ifscope <egress>
|
||||
//! route add -net 0.0.0.0/1 -interface <if> -ifa <selected overlay address>
|
||||
//! route add -net 128.0.0.0/1 -interface <if> -ifa <selected overlay address>
|
||||
//! pass out quick on <if> route-to (<egress> <gateway>) inet proto { tcp udp }
|
||||
//! from any to ! <overlay ranges> user <agent uid>
|
||||
//! nat on <egress> inet from (<if>) to any -> (<egress>)
|
||||
//! from any to ! <overlay ranges> user <agent uid> tag <underlay> no state
|
||||
//! nat on <egress> inet from (<if>) to any tagged <underlay> -> (<egress>) static-port
|
||||
//! pass out quick on <egress> reply-to (lo0 127.0.0.1) inet proto { tcp udp }
|
||||
//! from any to any flags any tagged <underlay> keep state (if-bound)
|
||||
//! ```
|
||||
//!
|
||||
//! The two halves outrank the default route without replacing it, and every
|
||||
//! more specific route (LAN, another VPN) keeps working. The `route-to` rule
|
||||
//! The scoped routes preserve the physical path for sockets that already
|
||||
//! use its source address. The unscoped halves capture ordinary internet
|
||||
//! traffic. More specific routes (LAN and active meshes) keep working. The `route-to` rule
|
||||
//! sends the *agent's own* traffic — QUIC, relay, DHT, which would otherwise
|
||||
//! loop into the tunnel it carries — back out the physical interface, and the
|
||||
//! translation gives it that interface's address, since an unbound socket
|
||||
//! picked the overlay address when the route pointed at the overlay. Like the
|
||||
//! Linux exemption this is by user id, so anything else running as root also
|
||||
//! bypasses the tunnel.
|
||||
//! picked the overlay address when the route pointed at the overlay. The
|
||||
//! first pass is stateless: a floating `route-to` state would match again
|
||||
//! on physical egress before PF could apply the translation. Only the egress
|
||||
//! pass tracks the connection and reverses NAT on replies there. Once NAT
|
||||
//! restores the socket's utun address, macOS's default hybrid end-system
|
||||
//! model would discard the reply arriving over the physical interface.
|
||||
//! `reply-to` delivers that state's replies locally through loopback. Like
|
||||
//! the Linux exemption this is by user id, so anything else running as root
|
||||
//! also bypasses the tunnel.
|
||||
//!
|
||||
//! IPv6 is blocked while an exit node is in use, as on Linux: `::/1` and
|
||||
//! `8000::/1` are rejecting routes, so applications fall back to IPv4 at once
|
||||
@@ -60,6 +72,13 @@ use crate::state::Ipv4Range;
|
||||
use super::RuleOutcome;
|
||||
use super::exit::{ExitHostPlan, ExitHostReport};
|
||||
|
||||
#[cfg(all(test, target_os = "macos", feature = "tun-device"))]
|
||||
#[path = "macos_exit_kernel.rs"]
|
||||
mod kernel;
|
||||
#[path = "macos_scoped.rs"]
|
||||
mod scoped;
|
||||
use scoped::ScopedRoutes;
|
||||
|
||||
/// The programs this module runs, always by absolute path.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Tool {
|
||||
@@ -163,12 +182,27 @@ fn anchor_name(interface: &str) -> Result<String, String> {
|
||||
}
|
||||
|
||||
/// The default route as `route -n get default` reports it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(super) struct DefaultRoute {
|
||||
pub interface: String,
|
||||
pub gateway: Option<Ipv4Addr>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct HostState {
|
||||
token: Mutex<Option<String>>,
|
||||
routes: Mutex<ScopedRoutes>,
|
||||
}
|
||||
|
||||
impl HostState {
|
||||
pub(super) fn with_state_dir(dir: &std::path::Path) -> Self {
|
||||
Self {
|
||||
routes: Mutex::new(ScopedRoutes::with_journal(dir.join("macos-exit-routes"))),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `interface:` and `gateway:` out of `route -n get default`.
|
||||
fn parse_default_route(text: &str) -> Option<DefaultRoute> {
|
||||
let field = |name: &str| {
|
||||
@@ -277,16 +311,15 @@ fn pf_rules(
|
||||
let out = &egress.interface;
|
||||
let mut nat = Vec::new();
|
||||
let mut filter = Vec::new();
|
||||
for range in offer {
|
||||
nat.push(format!("nat on {out} inet from {range} to any -> ({out})"));
|
||||
filter.push(format!(
|
||||
"pass in quick on {interface} inet from {range} to ! {range}"
|
||||
));
|
||||
}
|
||||
let mut tables = Vec::new();
|
||||
let via = match egress.gateway {
|
||||
Some(gateway) => format!("({out} {gateway})"),
|
||||
None => out.clone(),
|
||||
};
|
||||
if let Some(client) = client {
|
||||
let tag = format!("tsng_underlay_{interface}");
|
||||
nat.push(format!(
|
||||
"nat on {out} inet from ({interface}) to any -> ({out})"
|
||||
"nat on {out} inet from ({interface}) to any tagged {tag} -> ({out}) static-port"
|
||||
));
|
||||
let target = if client.overlay.is_empty() {
|
||||
"any".to_string()
|
||||
@@ -300,15 +333,41 @@ fn pf_rules(
|
||||
));
|
||||
format!("! <tsunagi_overlay_{interface}>")
|
||||
};
|
||||
let via = match egress.gateway {
|
||||
Some(gateway) => format!("({out} {gateway})"),
|
||||
None => out.clone(),
|
||||
};
|
||||
filter.push(format!(
|
||||
"pass out quick on {interface} route-to {via} inet proto {{ tcp udp }} \
|
||||
from any to {target} user {}",
|
||||
from any to {target} user {} tag {tag} no state",
|
||||
client.uid
|
||||
));
|
||||
// A relay TCP stream may already be established when exit routing changes.
|
||||
// Only responses to tagged underlay traffic get local loopback delivery.
|
||||
filter.push(format!(
|
||||
"pass out quick on {out} reply-to (lo0 127.0.0.1) inet proto {{ tcp udp }} \
|
||||
from any to any flags any tagged {tag} keep state (if-bound)"
|
||||
));
|
||||
}
|
||||
for range in offer {
|
||||
// PF takes the first matching NAT rule. Preserve the transport's source
|
||||
// port even when its overlay source falls inside one of our own offers.
|
||||
nat.push(format!("nat on {out} inet from {range} to any -> ({out})"));
|
||||
let tag = format!("tsng_forward_{interface}");
|
||||
// Classify at authenticated overlay ingress. Only packets the host
|
||||
// actually forwards AND its routes send back to our utun need steering.
|
||||
// Local services, connected LANs and the owner's forwarding switch
|
||||
// retain their native kernel behavior.
|
||||
filter.push(format!(
|
||||
"pass in quick on {interface} inet from {range} to ! {range} tag {tag} no state"
|
||||
));
|
||||
}
|
||||
if !offer.is_empty() {
|
||||
let tag = format!("tsng_forward_{interface}");
|
||||
filter.insert(0, format!(
|
||||
"pass out quick on {interface} route-to {via} inet from any to any tagged {tag} no state"
|
||||
));
|
||||
// Keep the outbound NAT state on the physical interface. A floating
|
||||
// state could consume packets on the utun before the reroute rule runs.
|
||||
filter.push(format!(
|
||||
"pass out quick on {out} inet from any to any flags any tagged {tag} keep state (if-bound)"
|
||||
));
|
||||
}
|
||||
tables
|
||||
.into_iter()
|
||||
@@ -368,10 +427,6 @@ fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn flush_args(anchor: &str) -> Vec<String> {
|
||||
owned(&["-q", "-a", anchor, "-F", "all"])
|
||||
}
|
||||
|
||||
fn load_args(anchor: &str) -> Vec<String> {
|
||||
owned(&["-q", "-a", anchor, "-f", "-"])
|
||||
}
|
||||
@@ -381,6 +436,22 @@ const HALVES: [&str; 2] = ["0.0.0.0/1", "128.0.0.0/1"];
|
||||
/// The IPv6 halves, made unreachable.
|
||||
const HALVES_V6: [&str; 2] = ["::/1", "8000::/1"];
|
||||
|
||||
/// A scoped route is available to sockets already using this egress. It
|
||||
/// coexists with the unscoped route for ordinary applications.
|
||||
fn scoped_args(action: &str, prefix: &str, egress: &DefaultRoute) -> Vec<String> {
|
||||
let mut args = owned(&["-q", "-n", action, "-net", prefix]);
|
||||
if let Some(gateway) = egress.gateway {
|
||||
args.push(gateway.to_string());
|
||||
} else {
|
||||
args.extend(owned(&["-interface", &egress.interface]));
|
||||
}
|
||||
args.extend(owned(&["-ifscope", &egress.interface]));
|
||||
if action != "delete" {
|
||||
args.push("-proto2".into());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
fn route_set_args(
|
||||
action: &str,
|
||||
half: &str,
|
||||
@@ -406,15 +477,56 @@ fn route_del_v6_args(half: &str) -> Vec<String> {
|
||||
owned(&["-q", "-n", "delete", "-inet6", "-net", half, "::1"])
|
||||
}
|
||||
|
||||
fn captures_half(run: Run<'_>, half: &str, interface: &str) -> bool {
|
||||
run_ok(run, Tool::Route, &owned(&["-n", "get", "-net", half]), None).is_ok_and(|text| {
|
||||
scoped::field(&text, "mask") == Some("128.0.0.0")
|
||||
&& scoped::field(&text, "interface") == Some(interface)
|
||||
&& !scoped::flag(&text, "IFSCOPE")
|
||||
})
|
||||
}
|
||||
|
||||
/// Takes away the overlay default routes. Best effort: what is not there is
|
||||
/// the state wanted.
|
||||
fn clear_routes(run: Run<'_>, interface: &str) {
|
||||
for half in HALVES {
|
||||
let _ = run(Tool::Route, &route_del_args(half, interface), None);
|
||||
if captures_half(run, half, interface) {
|
||||
let _ = run(Tool::Route, &route_del_args(half, interface), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ipv6_reject(run: Run<'_>, half: &str) -> Result<Option<String>, String> {
|
||||
let args = owned(&["-n", "get", "-inet6", "-net", half]);
|
||||
match run_ok(run, Tool::Route, &args, None) {
|
||||
Ok(text)
|
||||
if scoped::flag(&text, "REJECT") && scoped::field(&text, "gateway") == Some("::1") =>
|
||||
{
|
||||
Ok(Some(text))
|
||||
}
|
||||
Ok(_) => Ok(None),
|
||||
Err(why)
|
||||
if why.contains("not in table")
|
||||
|| why.contains("No such process")
|
||||
|| why.contains("Address family not supported") =>
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
Err(why) => Err(why),
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_v6(run: Run<'_>, scoped: &mut ScopedRoutes) -> Result<(), String> {
|
||||
let Some(marker) = scoped.ipv6_marker() else {
|
||||
return Ok(());
|
||||
};
|
||||
for half in HALVES_V6 {
|
||||
let _ = run(Tool::Route, &route_del_v6_args(half), None);
|
||||
if ipv6_reject(run, half)?.is_some_and(|text| {
|
||||
scoped::flag(&text, "PROTO2") && scoped::marker(&text) == Some(marker)
|
||||
}) {
|
||||
run_ok(run, Tool::Route, &route_del_v6_args(half), None)?;
|
||||
}
|
||||
}
|
||||
scoped.record_ipv6(false).map(|_| ())
|
||||
}
|
||||
|
||||
/// Installs a split default, or changes its source in place when the route
|
||||
@@ -431,17 +543,12 @@ fn set_half(
|
||||
&route_set_args("add", half, interface, source),
|
||||
None,
|
||||
) {
|
||||
Ok(_) => Ok(true),
|
||||
Ok(_) if captures_half(run, half, interface) => Ok(true),
|
||||
Ok(_) => Err(format!(
|
||||
"the unscoped route for {half} does not use {interface}"
|
||||
)),
|
||||
Err(why) if why.contains("File exists") => {
|
||||
let lookup = run_ok(run, Tool::Route, &owned(&["-n", "get", "-net", half]), None)
|
||||
.map_err(|inspect| format!("{why}; {inspect}"))?;
|
||||
let field = |key: &str| {
|
||||
lookup
|
||||
.lines()
|
||||
.filter_map(|line| line.trim().split_once(':'))
|
||||
.find_map(|(name, value)| (name == key).then(|| value.trim()))
|
||||
};
|
||||
if field("mask") != Some("128.0.0.0") || field("interface") != Some(interface) {
|
||||
if !captures_half(run, half, interface) {
|
||||
return Err(why);
|
||||
}
|
||||
run_ok(
|
||||
@@ -456,7 +563,14 @@ fn set_half(
|
||||
}
|
||||
}
|
||||
|
||||
fn set_routes(run: Run<'_>, interface: &str, source: Option<Ipv4Addr>) -> Result<(), String> {
|
||||
fn set_routes(
|
||||
run: Run<'_>,
|
||||
interface: &str,
|
||||
source: Option<Ipv4Addr>,
|
||||
scoped: &mut ScopedRoutes,
|
||||
) -> Result<(), String> {
|
||||
let already_using_v6 = scoped.ipv6_marker().is_some();
|
||||
let marker = scoped.record_ipv6(true)?;
|
||||
let mut added = Vec::new();
|
||||
for half in HALVES {
|
||||
match set_half(run, half, interface, source) {
|
||||
@@ -466,31 +580,43 @@ fn set_routes(run: Run<'_>, interface: &str, source: Option<Ipv4Addr>) -> Result
|
||||
for half in added {
|
||||
let _ = run(Tool::Route, &route_del_args(half, interface), None);
|
||||
}
|
||||
if !already_using_v6 {
|
||||
scoped.record_ipv6(false)?;
|
||||
}
|
||||
return Err(why);
|
||||
}
|
||||
}
|
||||
}
|
||||
for half in HALVES_V6 {
|
||||
// A host without IPv6 has nothing to block; not a failure.
|
||||
if let Err(why) = run_ok(run, Tool::Route, &route_add_v6_args(half), None) {
|
||||
tracing::debug!(%why, "cannot block IPv6 for the exit node");
|
||||
let mut args = route_add_v6_args(half);
|
||||
args.extend(["-proto2".into(), "-hopcount".into(), marker.to_string()]);
|
||||
if let Err(why) = run_ok(run, Tool::Route, &args, None) {
|
||||
if why.contains("Address family not supported")
|
||||
|| (why.contains("File exists")
|
||||
&& ipv6_reject(run, half).is_ok_and(|route| route.is_some()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for half in added {
|
||||
let _ = run(Tool::Route, &route_del_args(half, interface), None);
|
||||
}
|
||||
if !already_using_v6 {
|
||||
clear_v6(run, scoped)?;
|
||||
}
|
||||
return Err(why);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Makes the host match the plan.
|
||||
pub(super) fn apply_plan(
|
||||
run: Run<'_>,
|
||||
token: &Mutex<Option<String>>,
|
||||
plan: &ExitHostPlan,
|
||||
) -> ExitHostReport {
|
||||
pub(super) fn apply_plan(run: Run<'_>, state: &HostState, plan: &ExitHostPlan) -> ExitHostReport {
|
||||
let forwarding = if plan.offer.is_empty() {
|
||||
None
|
||||
} else {
|
||||
forwarding_state(run)
|
||||
};
|
||||
let outcome = apply_rules(run, token, plan);
|
||||
let outcome = apply_rules(run, state, plan, None);
|
||||
let verdict = |ok: bool, why: &str| {
|
||||
if ok {
|
||||
RuleOutcome::Applied
|
||||
@@ -522,12 +648,16 @@ pub(super) fn apply_plan(
|
||||
|
||||
fn apply_rules(
|
||||
run: Run<'_>,
|
||||
token: &Mutex<Option<String>>,
|
||||
state: &HostState,
|
||||
plan: &ExitHostPlan,
|
||||
checked_egress: Option<DefaultRoute>,
|
||||
) -> Result<(), String> {
|
||||
let interface = plan.interface.as_str();
|
||||
let anchor = anchor_name(interface)?;
|
||||
let egress = default_route(run, interface)?;
|
||||
let egress = match checked_egress {
|
||||
Some(egress) => egress,
|
||||
None => default_route(run, interface)?,
|
||||
};
|
||||
let uid = if plan.client {
|
||||
Some(agent_uid(run)?)
|
||||
} else {
|
||||
@@ -539,30 +669,99 @@ fn apply_rules(
|
||||
});
|
||||
let rules = pf_rules(interface, &egress, &plan.offer, client.as_ref());
|
||||
|
||||
acquire_pf(run, token)?;
|
||||
let mut scoped = lock(&state.routes);
|
||||
scoped.load()?;
|
||||
acquire_pf(run, &state.token)?;
|
||||
run_ok(run, Tool::Pfctl, &load_args(&anchor), Some(&rules))
|
||||
.map_err(|why| format!("cannot load the pf rules: {why}"))?;
|
||||
// The routes come after the rules that keep the agent's own traffic off
|
||||
// them: the other order would loop for as long as it takes.
|
||||
if plan.client {
|
||||
set_routes(run, interface, plan.client_source)?;
|
||||
let previous = scoped.previous();
|
||||
let wanted = ScopedRoutes::desired(&egress);
|
||||
let result = scoped
|
||||
.ensure(run, &wanted)
|
||||
.and_then(|()| set_routes(run, interface, plan.client_source, &mut scoped));
|
||||
if let Err(reason) = result {
|
||||
// A same-interface gateway change may already have updated one
|
||||
// scoped route. Restore the former gateway before dropping new adds.
|
||||
if let Err(cleanup) = scoped
|
||||
.ensure(run, &previous)
|
||||
.and_then(|()| scoped.retain(run, &previous))
|
||||
{
|
||||
return Err(format!(
|
||||
"{reason}; restoring prior scoped routes failed: {cleanup}"
|
||||
));
|
||||
}
|
||||
return Err(reason);
|
||||
}
|
||||
scoped.retain(run, &wanted)?;
|
||||
scoped.active = Some(egress);
|
||||
} else {
|
||||
clear_routes(run, interface);
|
||||
clear_v6(run, &mut scoped)?;
|
||||
scoped.retain(run, &[])?;
|
||||
scoped.active = None;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes everything this agent put there for the interface.
|
||||
pub(super) fn clear_all(run: Run<'_>, token: &Mutex<Option<String>>, interface: &str) {
|
||||
pub(super) fn clear_all(run: Run<'_>, state: &HostState, interface: &str) {
|
||||
let mut scoped = lock(&state.routes);
|
||||
clear_routes(run, interface);
|
||||
if let Err(why) = scoped
|
||||
.load()
|
||||
.and_then(|()| clear_v6(run, &mut scoped))
|
||||
.and_then(|()| scoped.retain(run, &[]))
|
||||
{
|
||||
tracing::warn!(%why, "cannot remove scoped exit routes");
|
||||
}
|
||||
scoped.active = None;
|
||||
if let Ok(anchor) = anchor_name(interface) {
|
||||
// Flushing an anchor nothing was ever loaded into is not an error
|
||||
// worth reporting.
|
||||
if let Err(why) = run_ok(run, Tool::Pfctl, &flush_args(&anchor), None) {
|
||||
if let Err(why) = run_ok(run, Tool::Pfctl, &load_args(&anchor), Some("")) {
|
||||
tracing::debug!(%why, "cannot flush the exit node pf anchor");
|
||||
}
|
||||
}
|
||||
release_pf(run, token);
|
||||
release_pf(run, &state.token);
|
||||
}
|
||||
|
||||
/// The logical plan can be unchanged while Wi-Fi changes gateway or moves
|
||||
/// to Ethernet. Rebuild both PF and physical scope against that new egress.
|
||||
pub(super) fn refresh_client(
|
||||
run: Run<'_>,
|
||||
state: &HostState,
|
||||
plan: &ExitHostPlan,
|
||||
) -> Option<RuleOutcome> {
|
||||
if !plan.client || !lock(&state.routes).check_due(std::time::Instant::now()) {
|
||||
return None;
|
||||
}
|
||||
let egress = match default_route(run, &plan.interface) {
|
||||
Ok(egress) => egress,
|
||||
Err(reason) => return Some(RuleOutcome::Failed(reason)),
|
||||
};
|
||||
{
|
||||
let mut routes = lock(&state.routes);
|
||||
if routes.active.as_ref() == Some(&egress) {
|
||||
// A physical link may reconnect with the same name and gateway
|
||||
// after the kernel has discarded that interface's scoped routes.
|
||||
if let Err(reason) = routes.ensure(run, &ScopedRoutes::desired(&egress)) {
|
||||
return Some(RuleOutcome::Failed(reason));
|
||||
}
|
||||
if HALVES
|
||||
.iter()
|
||||
.all(|half| captures_half(run, half, &plan.interface))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(match apply_rules(run, state, plan, Some(egress)) {
|
||||
Ok(()) => RuleOutcome::Applied,
|
||||
Err(reason) => RuleOutcome::Failed(reason),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -601,6 +800,9 @@ destination: default\n\
|
||||
pf_load_fails: bool,
|
||||
route_add_fails: bool,
|
||||
half_interface: Option<&'static str>,
|
||||
v6: RefCell<std::collections::BTreeMap<String, u32>>,
|
||||
capture: RefCell<std::collections::BTreeMap<String, String>>,
|
||||
scoped: RefCell<std::collections::BTreeMap<(String, String), String>>,
|
||||
pf_enable_output: &'static str,
|
||||
}
|
||||
|
||||
@@ -615,6 +817,9 @@ destination: default\n\
|
||||
pf_load_fails: false,
|
||||
route_add_fails: false,
|
||||
half_interface: None,
|
||||
v6: RefCell::default(),
|
||||
capture: RefCell::default(),
|
||||
scoped: RefCell::default(),
|
||||
pf_enable_output: "pf enabled\nToken : 4242\n",
|
||||
}
|
||||
}
|
||||
@@ -638,11 +843,64 @@ destination: default\n\
|
||||
match tool {
|
||||
Tool::Id => ok("0\n", ""),
|
||||
Tool::Sysctl => ok(self.forwarding, ""),
|
||||
Tool::Route if args.iter().any(|a| a == "-inet6") => {
|
||||
let half = args[args.iter().position(|a| a == "-net").unwrap() + 1].clone();
|
||||
let mut table = self.v6.borrow_mut();
|
||||
if args.iter().any(|a| a == "get") {
|
||||
return table.get(&half).map_or_else(|| fail("not in table"),|marker|
|
||||
ok(&format!("gateway: ::1\nflags: <UP,REJECT,PROTO2>\nhopcount mtu\n{marker} 16384\n"),""));
|
||||
}
|
||||
if args.iter().any(|a| a == "delete") {
|
||||
table.remove(&half);
|
||||
} else if let std::collections::btree_map::Entry::Vacant(entry) =
|
||||
table.entry(half)
|
||||
{
|
||||
entry.insert(args.last().unwrap().parse().unwrap());
|
||||
} else {
|
||||
return fail("File exists");
|
||||
}
|
||||
ok("", "")
|
||||
}
|
||||
Tool::Route if args.iter().any(|a| a == "-ifscope") => {
|
||||
let after = |name: &str| {
|
||||
args.iter()
|
||||
.position(|a| a == name)
|
||||
.map(|i| args[i + 1].clone())
|
||||
};
|
||||
let scope = after("-ifscope").unwrap();
|
||||
let prefix = after("-net").unwrap();
|
||||
let key = (scope.clone(), prefix.clone());
|
||||
let mut table = self.scoped.borrow_mut();
|
||||
if args.iter().any(|a| a == "get") {
|
||||
return table
|
||||
.get(&key)
|
||||
.map_or_else(|| fail("not in table"), |text| ok(text, ""));
|
||||
}
|
||||
if args.iter().any(|a| a == "delete") {
|
||||
table.remove(&key);
|
||||
} else {
|
||||
let gateway = args
|
||||
.iter()
|
||||
.find(|a| a.parse::<Ipv4Addr>().is_ok())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let marker = after("-hopcount").unwrap();
|
||||
table.insert(key, format!("destination: {}\nmask: 128.0.0.0\ninterface: {scope}\ngateway: {gateway}\nflags: <UP,PROTO2,IFSCOPE>\nhopcount mtu\n{marker} 1500\n", prefix.split('/').next().unwrap()));
|
||||
}
|
||||
ok("", "")
|
||||
}
|
||||
Tool::Route
|
||||
if args.iter().any(|arg| arg == "get")
|
||||
&& args.iter().any(|arg| arg == "-net") =>
|
||||
{
|
||||
match self.half_interface {
|
||||
let half = args.last().unwrap();
|
||||
match self
|
||||
.capture
|
||||
.borrow()
|
||||
.get(half)
|
||||
.map(String::as_str)
|
||||
.or(self.half_interface)
|
||||
{
|
||||
Some(name) => ok(&format!("mask: 128.0.0.0\ninterface: {name}\n"), ""),
|
||||
None => fail("not in table"),
|
||||
}
|
||||
@@ -656,12 +914,31 @@ destination: default\n\
|
||||
Tool::Route
|
||||
if args.contains(&"add".to_string())
|
||||
&& ((self.route_add_fails && args.iter().any(|a| a == HALVES[1]))
|
||||
|| args.iter().any(|a| self.capture.borrow().contains_key(a))
|
||||
|| (self.half_interface.is_some()
|
||||
&& HALVES.iter().any(|half| args.iter().any(|a| a == half)))) =>
|
||||
{
|
||||
// Darwin route can return success after a routing-socket write failed.
|
||||
ok("", "route: writing to routing socket: File exists")
|
||||
}
|
||||
Tool::Route if args.iter().any(|a| a == "-interface") => {
|
||||
let half = args
|
||||
.iter()
|
||||
.position(|a| a == "-net")
|
||||
.map(|i| args[i + 1].clone())
|
||||
.unwrap();
|
||||
let iface = args
|
||||
.iter()
|
||||
.position(|a| a == "-interface")
|
||||
.map(|i| args[i + 1].clone())
|
||||
.unwrap();
|
||||
if args.iter().any(|a| a == "delete") {
|
||||
self.capture.borrow_mut().remove(&half);
|
||||
} else {
|
||||
self.capture.borrow_mut().insert(half, iface);
|
||||
}
|
||||
ok("", "")
|
||||
}
|
||||
Tool::Route => ok("", ""),
|
||||
Tool::Pfctl if self.pf_missing => Ran::Missing,
|
||||
Tool::Pfctl if args == ["-E"] => ok("", self.pf_enable_output),
|
||||
@@ -734,14 +1011,36 @@ destination: default\n\
|
||||
assert_eq!(
|
||||
text,
|
||||
"nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\n"
|
||||
pass out quick on utun5 route-to (en0 192.168.1.1) inet from any to any tagged tsng_forward_utun5 no state\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
|
||||
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
|
||||
);
|
||||
// Translation precedes filtering, as pf requires.
|
||||
assert!(text.find("nat on").unwrap() < text.find("pass in").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn using_sends_the_agents_own_traffic_back_out_the_physical_interface() {
|
||||
fn the_agents_tagged_nat_precedes_any_general_masquerade_for_offered_ranges() {
|
||||
let ranges = [range()];
|
||||
let client = ClientRules {
|
||||
uid: 0,
|
||||
overlay: &ranges,
|
||||
};
|
||||
let text = pf_rules("utun5", &egress(), &ranges, Some(&client));
|
||||
let mut nat = text.lines().filter(|line| line.starts_with("nat "));
|
||||
assert!(
|
||||
nat.next()
|
||||
.unwrap()
|
||||
.ends_with("tagged tsng_underlay_utun5 -> (en0) static-port")
|
||||
);
|
||||
assert_eq!(
|
||||
nat.next(),
|
||||
Some("nat on en0 inet from 10.13.37.0/24 to any -> (en0)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn using_keeps_the_reroute_and_the_physical_nat_in_separate_pf_passes() {
|
||||
let other: Ipv4Range = "10.99.0.0/16".parse().unwrap();
|
||||
let overlay = [range(), other];
|
||||
let client = ClientRules {
|
||||
@@ -755,19 +1054,17 @@ destination: default\n\
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains("nat on en0 inet from (utun5) to any -> (en0)\n"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains(
|
||||
let rules: Vec<_> = text.lines().skip(1).collect();
|
||||
assert_eq!(
|
||||
rules,
|
||||
[
|
||||
"nat on en0 inet from (utun5) to any tagged tsng_underlay_utun5 -> (en0) static-port",
|
||||
"pass out quick on utun5 route-to (en0 192.168.1.1) inet proto { tcp udp } \
|
||||
from any to ! <tsunagi_overlay_utun5> user 0\n"
|
||||
),
|
||||
"{text}"
|
||||
from any to ! <tsunagi_overlay_utun5> user 0 tag tsng_underlay_utun5 no state",
|
||||
"pass out quick on en0 reply-to (lo0 127.0.0.1) inet proto { tcp udp } from any to any flags any \
|
||||
tagged tsng_underlay_utun5 keep state (if-bound)",
|
||||
]
|
||||
);
|
||||
// Only the agent's user, and only what is not the overlay.
|
||||
assert!(!text.contains("from any to any"));
|
||||
|
||||
let direct = DefaultRoute {
|
||||
interface: "ppp0".into(),
|
||||
@@ -789,6 +1086,10 @@ destination: default\n\
|
||||
|
||||
#[test]
|
||||
fn the_overlay_default_routes_are_halves_and_ipv6_is_rejected() {
|
||||
assert_eq!(
|
||||
scoped_args("add", "128.0.0.0/1", &egress()).join(" "),
|
||||
"-q -n add -net 128.0.0.0/1 192.168.1.1 -ifscope en0 -proto2"
|
||||
);
|
||||
assert_eq!(
|
||||
route_set_args("add", "0.0.0.0/1", "utun5", None).join(" "),
|
||||
"-q -n add -net 0.0.0.0/1 -interface utun5"
|
||||
@@ -818,7 +1119,7 @@ destination: default\n\
|
||||
#[test]
|
||||
fn offering_loads_the_anchor_and_reads_but_never_writes_forwarding() {
|
||||
let fake = Fake::new();
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
|
||||
assert_eq!(report.forwarding, Some(true));
|
||||
@@ -833,7 +1134,9 @@ destination: default\n\
|
||||
assert_eq!(
|
||||
fake.stdins.borrow()[0],
|
||||
"nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\n"
|
||||
pass out quick on utun5 route-to (en0 192.168.1.1) inet from any to any tagged tsng_forward_utun5 no state\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
|
||||
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
|
||||
);
|
||||
// sysctl is only ever asked, never told.
|
||||
assert!(
|
||||
@@ -845,14 +1148,14 @@ destination: default\n\
|
||||
);
|
||||
// No client routes were added for an offer alone.
|
||||
assert_eq!(fake.count(" add "), 0);
|
||||
assert_eq!(token.lock().unwrap().as_deref(), Some("4242"));
|
||||
assert_eq!(token.token.lock().unwrap().as_deref(), Some("4242"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarding_off_is_reported_and_unreadable_is_none() {
|
||||
let mut fake = Fake::new();
|
||||
fake.forwarding = "0\n";
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
assert_eq!(report.forwarding, Some(false));
|
||||
fake.forwarding = "junk";
|
||||
@@ -863,12 +1166,18 @@ destination: default\n\
|
||||
#[test]
|
||||
fn the_client_rules_are_loaded_before_the_routes_that_need_them() {
|
||||
let fake = Fake::new();
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true));
|
||||
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||
assert!(report.offer.is_empty());
|
||||
let load = fake.position("-f -").unwrap();
|
||||
let add = fake.position(" add -net 0.0.0.0/1").unwrap();
|
||||
let scoped = fake
|
||||
.position(" add -net 128.0.0.0/1 192.168.1.1 -ifscope en0")
|
||||
.unwrap();
|
||||
let add = fake
|
||||
.position(" add -net 0.0.0.0/1 -interface utun5")
|
||||
.unwrap();
|
||||
assert!(load < scoped && scoped < add);
|
||||
assert!(load < add, "{:?}", fake.calls());
|
||||
assert!(fake.position("add -net 128.0.0.0/1").is_some());
|
||||
assert!(fake.position("-inet6 -net ::/1 ::1 -reject").is_some());
|
||||
@@ -880,17 +1189,19 @@ destination: default\n\
|
||||
#[test]
|
||||
fn both_exit_halves_use_the_selected_networks_address_on_a_shared_utun() {
|
||||
let fake = Fake::new();
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let mut selected = plan(false, true);
|
||||
selected.overlay.push("10.99.0.0/24".parse().unwrap());
|
||||
for source in ["10.99.0.17", "10.13.37.34"] {
|
||||
for (action, source) in [("add", "10.99.0.17"), ("change", "10.13.37.34")] {
|
||||
selected.client_source = Some(source.parse().unwrap());
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &selected);
|
||||
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||
for half in HALVES {
|
||||
assert!(
|
||||
fake.position(&format!("add -net {half} -interface utun5 -ifa {source}"))
|
||||
.is_some()
|
||||
fake.position(&format!(
|
||||
"{action} -net {half} -interface utun5 -ifa {source}"
|
||||
))
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -902,7 +1213,11 @@ destination: default\n\
|
||||
selected.client_source = Some("10.99.0.17".parse().unwrap());
|
||||
let mut fake = Fake::new();
|
||||
fake.half_interface = Some("utun5");
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &Mutex::new(None), &selected);
|
||||
let report = apply_plan(
|
||||
&|t, a, s| fake.run(t, a, s),
|
||||
&HostState::default(),
|
||||
&selected,
|
||||
);
|
||||
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||
for half in HALVES {
|
||||
assert!(
|
||||
@@ -918,19 +1233,104 @@ destination: default\n\
|
||||
foreign.half_interface = Some("utun9");
|
||||
let report = apply_plan(
|
||||
&|t, a, s| foreign.run(t, a, s),
|
||||
&Mutex::new(None),
|
||||
&HostState::default(),
|
||||
&selected,
|
||||
);
|
||||
assert!(matches!(report.client, Some(RuleOutcome::Failed(_))));
|
||||
assert_eq!(foreign.count(" change "), 0);
|
||||
assert_eq!(foreign.count(" delete "), 0);
|
||||
assert!(
|
||||
foreign.scoped.borrow().is_empty(),
|
||||
"new scoped routes were rolled back"
|
||||
);
|
||||
assert_eq!(foreign.count("delete -net 0.0.0.0/1 -interface utun9"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_cleans_scoped_routes_by_journal_and_kernel_marker_even_on_a_new_utun() {
|
||||
let fake = Fake::new();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||
let state = HostState::with_state_dir(dir.path());
|
||||
assert_eq!(
|
||||
apply_plan(&run, &state, &plan(false, true)).client,
|
||||
Some(RuleOutcome::Applied)
|
||||
);
|
||||
assert_eq!(fake.scoped.borrow().len(), 2);
|
||||
// An administrator replaces one of the two routes before we restart.
|
||||
for ((_, half), listing) in fake.scoped.borrow_mut().iter_mut() {
|
||||
if half == HALVES[0] {
|
||||
*listing = listing.replace("PROTO2", "STATIC");
|
||||
}
|
||||
}
|
||||
drop(state);
|
||||
clear_all(&run, &HostState::with_state_dir(dir.path()), "utun9");
|
||||
assert_eq!(fake.scoped.borrow().len(), 1);
|
||||
assert!(
|
||||
fake.scoped
|
||||
.borrow()
|
||||
.contains_key(&("en0".into(), HALVES[0].into()))
|
||||
);
|
||||
assert!(!dir.path().join("macos-exit-routes").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_preserves_an_ipv6_reject_installed_by_another_owner() {
|
||||
let fake = Fake::new();
|
||||
fake.v6.borrow_mut().insert("::/1".into(), 0);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let state = HostState::with_state_dir(dir.path());
|
||||
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||
assert_eq!(
|
||||
apply_plan(&run, &state, &plan(false, true)).client,
|
||||
Some(RuleOutcome::Applied)
|
||||
);
|
||||
assert_eq!(fake.v6.borrow().len(), 2);
|
||||
clear_all(&run, &HostState::with_state_dir(dir.path()), "utun9");
|
||||
assert_eq!(
|
||||
fake.v6.borrow().keys().cloned().collect::<Vec<_>>(),
|
||||
["::/1"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_a_changed_gateway_updates_pf_and_replaces_only_our_previous_scope() {
|
||||
let mut fake = Fake::new();
|
||||
let state = HostState::default();
|
||||
let plan = plan(false, true);
|
||||
assert_eq!(
|
||||
apply_plan(&|t, a, s| fake.run(t, a, s), &state, &plan).client,
|
||||
Some(RuleOutcome::Applied)
|
||||
);
|
||||
fake.default_route = Some(
|
||||
DEFAULT_ROUTE
|
||||
.replace("en0", "en1")
|
||||
.replace("192.168.1.1", "10.0.0.1"),
|
||||
);
|
||||
assert_eq!(
|
||||
refresh_client(&|t, a, s| fake.run(t, a, s), &state, &plan),
|
||||
Some(RuleOutcome::Applied)
|
||||
);
|
||||
assert_eq!(fake.scoped.borrow().len(), 2);
|
||||
assert!(
|
||||
fake.scoped
|
||||
.borrow()
|
||||
.keys()
|
||||
.all(|(interface, _)| interface == "en1")
|
||||
);
|
||||
assert!(
|
||||
fake.stdins
|
||||
.borrow()
|
||||
.last()
|
||||
.unwrap()
|
||||
.contains("route-to (en1 10.0.0.1)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_routes_are_added_when_the_rules_did_not_load() {
|
||||
let mut fake = Fake::new();
|
||||
fake.pf_load_fails = true;
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true));
|
||||
let Some(RuleOutcome::Failed(why)) = report.client else {
|
||||
panic!("{report:?}");
|
||||
@@ -947,7 +1347,7 @@ destination: default\n\
|
||||
fn a_failing_route_is_a_failure_and_leaves_nothing_behind() {
|
||||
let mut fake = Fake::new();
|
||||
fake.route_add_fails = true;
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(false, true));
|
||||
let Some(RuleOutcome::Failed(why)) = report.client else {
|
||||
panic!("{report:?}");
|
||||
@@ -970,7 +1370,7 @@ destination: default\n\
|
||||
fn a_missing_pfctl_or_default_route_says_what_is_wrong() {
|
||||
let mut fake = Fake::new();
|
||||
fake.pf_missing = true;
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
|
||||
panic!("{report:?}");
|
||||
@@ -991,7 +1391,7 @@ destination: default\n\
|
||||
fn a_default_route_through_the_overlay_is_refused() {
|
||||
let mut fake = Fake::new();
|
||||
fake.default_route = Some("gateway: 10.13.37.1\ninterface: utun5\n".into());
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
|
||||
panic!("{report:?}");
|
||||
@@ -1002,7 +1402,7 @@ destination: default\n\
|
||||
#[test]
|
||||
fn pf_is_enabled_once_and_released_once_on_clear() {
|
||||
let fake = Fake::new();
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||
apply_plan(&run, &token, &plan(true, false));
|
||||
apply_plan(&run, &token, &plan(true, true));
|
||||
@@ -1010,15 +1410,12 @@ destination: default\n\
|
||||
|
||||
clear_all(&run, &token, "utun5");
|
||||
assert_eq!(fake.count("Pfctl -X 4242"), 1);
|
||||
assert!(
|
||||
fake.position("-a com.apple/tsunagi-exit-utun5 -F all")
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(fake.stdins.borrow().last().map(String::as_str), Some(""));
|
||||
assert!(
|
||||
fake.position("delete -net 0.0.0.0/1 -interface utun5")
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(*token.lock().unwrap(), None);
|
||||
assert_eq!(*token.token.lock().unwrap(), None);
|
||||
// A second clear has nothing to release and still succeeds.
|
||||
clear_all(&run, &token, "utun5");
|
||||
assert_eq!(fake.count("Pfctl -X"), 1);
|
||||
@@ -1027,10 +1424,15 @@ destination: default\n\
|
||||
#[test]
|
||||
fn dropping_the_client_removes_its_routes() {
|
||||
let fake = Fake::new();
|
||||
let token = Mutex::new(None);
|
||||
let token = HostState::default();
|
||||
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||
assert_eq!(
|
||||
apply_plan(&run, &token, &plan(false, true)).client,
|
||||
Some(RuleOutcome::Applied)
|
||||
);
|
||||
let adds = fake.count(" add ");
|
||||
apply_plan(&run, &token, &plan(true, false));
|
||||
assert!(fake.position("delete -net 0.0.0.0/1").is_some());
|
||||
assert_eq!(fake.count(" add "), 0);
|
||||
assert_eq!(fake.count(" add "), adds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
//! Privileged macOS regression. Both ends are throwaway utuns; only a /30
|
||||
//! inside the simulated uplink is captured when switching the exit on.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use smoltcp::wire::{IpProtocol, Ipv4Packet, Ipv4Repr, TcpPacket, TcpSeqNumber, UdpPacket};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpStream, UdpSocket};
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::*;
|
||||
use crate::overlay::Cidr;
|
||||
use crate::overlay::provision::{InterfacePlan, InterfaceProvisioner, UtunProvisioner};
|
||||
use crate::overlay::tun::TunDevice;
|
||||
|
||||
const UPLINK: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 1);
|
||||
const REMOTE: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 6);
|
||||
const CAPTURE: &str = "192.0.2.4/30";
|
||||
const FIRST: Ipv4Addr = Ipv4Addr::new(198, 18, 222, 1);
|
||||
const SECOND: Ipv4Addr = Ipv4Addr::new(198, 19, 222, 1);
|
||||
const WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
async fn utun(addresses: &[Ipv4Addr]) -> Arc<dyn TunDevice> {
|
||||
let cidrs = addresses
|
||||
.iter()
|
||||
.map(|ip| Cidr::new((*ip).into(), 28).unwrap())
|
||||
.collect();
|
||||
UtunProvisioner::new()
|
||||
.unwrap()
|
||||
.reconcile(&InterfacePlan::new("test", 1280, cidrs))
|
||||
.await
|
||||
.unwrap()
|
||||
.device
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
struct Capture<'a> {
|
||||
overlay: &'a str,
|
||||
uplink: DefaultRoute,
|
||||
anchor: String,
|
||||
token: Mutex<Option<String>>,
|
||||
added_route: bool,
|
||||
added_scoped: bool,
|
||||
}
|
||||
|
||||
impl Drop for Capture<'_> {
|
||||
fn drop(&mut self) {
|
||||
if self.added_route {
|
||||
let _ = run_tool(Tool::Route, &route_del_args(CAPTURE, self.overlay), None);
|
||||
}
|
||||
if self.added_scoped {
|
||||
let _ = run_tool(
|
||||
Tool::Route,
|
||||
&scoped_args("delete", CAPTURE, &self.uplink),
|
||||
None,
|
||||
);
|
||||
}
|
||||
// Loading an empty ruleset removes just this temporary anchor's rules.
|
||||
let _ = run_tool(Tool::Pfctl, &load_args(&self.anchor), Some(""));
|
||||
release_pf(&run_tool, &self.token);
|
||||
}
|
||||
}
|
||||
|
||||
impl Capture<'_> {
|
||||
fn offer(&self, use_upstream: bool) {
|
||||
let ranges = [FIRST, SECOND]
|
||||
.map(|ip| Ipv4Range::new(Ipv4Addr::from(u32::from(ip) & !0xf), 28).unwrap());
|
||||
let rules = pf_rules(
|
||||
self.overlay,
|
||||
&self.uplink,
|
||||
&ranges[..1],
|
||||
use_upstream.then_some(&ClientRules {
|
||||
uid: 0,
|
||||
overlay: &ranges,
|
||||
}),
|
||||
);
|
||||
acquire_pf(&run_tool, &self.token).unwrap();
|
||||
run_ok(
|
||||
&run_tool,
|
||||
Tool::Pfctl,
|
||||
&load_args(&self.anchor),
|
||||
Some(&rules),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
fn enable(&mut self) {
|
||||
self.offer(true);
|
||||
run_ok(
|
||||
&run_tool,
|
||||
Tool::Route,
|
||||
&scoped::marked_args("add", CAPTURE, &self.uplink, 114275),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
self.added_scoped = true;
|
||||
run_ok(
|
||||
&run_tool,
|
||||
Tool::Route,
|
||||
&route_set_args("add", CAPTURE, self.overlay, Some(SECOND)),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
self.added_route = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ignore interface housekeeping and pure TCP ACKs while waiting for our packet.
|
||||
async fn packet(
|
||||
device: &dyn TunDevice,
|
||||
destination: Ipv4Addr,
|
||||
protocol: IpProtocol,
|
||||
port: u16,
|
||||
payload: &[u8],
|
||||
) -> Bytes {
|
||||
timeout(WAIT, async {
|
||||
loop {
|
||||
let raw = device.recv().await.expect("utun closed");
|
||||
let Ok(ip) = Ipv4Packet::new_checked(&raw[..]) else {
|
||||
continue;
|
||||
};
|
||||
if ip.version() != 4 || ip.dst_addr() != destination || ip.next_header() != protocol {
|
||||
continue;
|
||||
}
|
||||
let matches = match protocol {
|
||||
IpProtocol::Udp => UdpPacket::new_checked(ip.payload())
|
||||
.is_ok_and(|udp| udp.dst_port() == port && udp.payload() == payload),
|
||||
IpProtocol::Tcp => TcpPacket::new_checked(ip.payload()).is_ok_and(|tcp| {
|
||||
tcp.dst_port() == port
|
||||
&& tcp.payload() == payload
|
||||
&& (tcp.syn() || !payload.is_empty())
|
||||
}),
|
||||
_ => false,
|
||||
};
|
||||
if matches {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| {
|
||||
panic!(
|
||||
"no {protocol} packet for {destination}:{port} on {}",
|
||||
device.name()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn reply(request: &[u8]) -> Bytes {
|
||||
let ip = Ipv4Packet::new_checked(request).unwrap();
|
||||
let tcp_request = (ip.next_header() == IpProtocol::Tcp)
|
||||
.then(|| TcpPacket::new_checked(ip.payload()).unwrap());
|
||||
// Acknowledge TCP SYNs and echo data so the test observes return traffic
|
||||
// on the very socket that originated each flow.
|
||||
let reply_ip = Ipv4Repr {
|
||||
src_addr: ip.dst_addr(),
|
||||
dst_addr: ip.src_addr(),
|
||||
next_header: ip.next_header(),
|
||||
payload_len: tcp_request
|
||||
.as_ref()
|
||||
.map_or(ip.payload().len(), |tcp| 20 + tcp.payload().len()),
|
||||
hop_limit: 64,
|
||||
};
|
||||
let mut bytes = vec![0; reply_ip.buffer_len() + reply_ip.payload_len];
|
||||
let mut out = Ipv4Packet::new_unchecked(&mut bytes[..]);
|
||||
reply_ip.emit(&mut out, &Default::default());
|
||||
let src = reply_ip.src_addr.into();
|
||||
let dst = reply_ip.dst_addr.into();
|
||||
if let Some(incoming) = tcp_request {
|
||||
let mut tcp = TcpPacket::new_unchecked(out.payload_mut());
|
||||
tcp.set_header_len(20);
|
||||
tcp.set_src_port(incoming.dst_port());
|
||||
tcp.set_dst_port(incoming.src_port());
|
||||
tcp.set_syn(incoming.syn());
|
||||
tcp.set_ack(true);
|
||||
tcp.set_seq_number(if incoming.syn() {
|
||||
TcpSeqNumber(100)
|
||||
} else {
|
||||
incoming.ack_number()
|
||||
});
|
||||
tcp.set_ack_number(incoming.seq_number() + incoming.segment_len());
|
||||
tcp.set_window_len(8192);
|
||||
tcp.payload_mut().copy_from_slice(incoming.payload());
|
||||
tcp.fill_checksum(&src, &dst);
|
||||
} else {
|
||||
out.payload_mut().copy_from_slice(ip.payload());
|
||||
let mut udp = UdpPacket::new_unchecked(out.payload_mut());
|
||||
let (src_port, dst_port) = (udp.dst_port(), udp.src_port());
|
||||
udp.set_src_port(src_port);
|
||||
udp.set_dst_port(dst_port);
|
||||
udp.fill_checksum(&src, &dst);
|
||||
}
|
||||
bytes.into()
|
||||
}
|
||||
|
||||
async fn open_tcp(uplink: &dyn TunDevice, port: u16) -> TcpStream {
|
||||
let connect = TcpStream::connect((REMOTE, port));
|
||||
let peer = async {
|
||||
let syn = packet(uplink, REMOTE, IpProtocol::Tcp, port, &[]).await;
|
||||
assert_eq!(
|
||||
Ipv4Packet::new_checked(&syn[..]).unwrap().src_addr(),
|
||||
UPLINK
|
||||
);
|
||||
uplink.send(reply(&syn)).await.unwrap();
|
||||
};
|
||||
let (stream, ()) = tokio::join!(timeout(WAIT, connect), peer);
|
||||
stream.expect("SYN-ACK did not reach socket").unwrap()
|
||||
}
|
||||
|
||||
fn check_capture_routes(overlay: &str, uplink: &str) {
|
||||
for (scope, expected) in [(vec![], overlay), (owned(&["-ifscope", uplink]), uplink)] {
|
||||
let mut args = owned(&["-n", "get"]);
|
||||
args.extend(scope);
|
||||
args.extend(owned(&["-net", CAPTURE]));
|
||||
let output = run_ok(&run_tool, Tool::Route, &args, None).unwrap();
|
||||
eprintln!("route {}:\n{output}", args.join(" "));
|
||||
let actual = output
|
||||
.lines()
|
||||
.find_map(|line| line.trim().strip_prefix("interface: "));
|
||||
assert_eq!(actual, Some(expected));
|
||||
assert_eq!(output.contains("PROTO2"), expected == uplink);
|
||||
assert_eq!(output.contains("IFSCOPE"), expected == uplink);
|
||||
assert_eq!(
|
||||
output.split_whitespace().any(|s| s == "114275"),
|
||||
expected == uplink
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fn udp_round_trip(uplink: &dyn TunDevice, socket: &UdpSocket, stage: &str) {
|
||||
let port = socket.peer_addr().unwrap().port();
|
||||
eprintln!("{stage}: UDP {}", socket.local_addr().unwrap());
|
||||
socket
|
||||
.send(b"QUIC path")
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{stage}: sending UDP: {e}"));
|
||||
let raw = packet(uplink, REMOTE, IpProtocol::Udp, port, b"QUIC path").await;
|
||||
let ip = Ipv4Packet::new_checked(&raw[..]).unwrap();
|
||||
assert_eq!(ip.src_addr(), UPLINK);
|
||||
assert_eq!(
|
||||
UdpPacket::new_checked(ip.payload()).unwrap().src_port(),
|
||||
socket.local_addr().unwrap().port()
|
||||
);
|
||||
uplink.send(reply(&raw)).await.unwrap();
|
||||
let mut buf = [0; 64];
|
||||
let len = timeout(WAIT, socket.recv(&mut buf))
|
||||
.await
|
||||
.expect("UDP reply did not reach socket")
|
||||
.unwrap();
|
||||
assert_eq!(&buf[..len], b"QUIC path");
|
||||
}
|
||||
|
||||
async fn member_round_trip(
|
||||
overlay: &dyn TunDevice,
|
||||
uplink: &dyn TunDevice,
|
||||
port: u16,
|
||||
data: &[u8],
|
||||
) -> u16 {
|
||||
let member = Ipv4Addr::from(u32::from(FIRST) + 2);
|
||||
let ip = Ipv4Repr {
|
||||
src_addr: member,
|
||||
dst_addr: REMOTE,
|
||||
next_header: IpProtocol::Udp,
|
||||
payload_len: 8 + data.len(),
|
||||
hop_limit: 64,
|
||||
};
|
||||
let mut raw = vec![0; ip.buffer_len() + ip.payload_len];
|
||||
let mut out = Ipv4Packet::new_unchecked(&mut raw[..]);
|
||||
ip.emit(&mut out, &Default::default());
|
||||
let mut udp = UdpPacket::new_unchecked(out.payload_mut());
|
||||
udp.set_len(ip.payload_len as u16);
|
||||
udp.set_src_port(port);
|
||||
udp.set_dst_port(8020);
|
||||
udp.payload_mut().copy_from_slice(data);
|
||||
udp.fill_checksum(&member.into(), &REMOTE.into());
|
||||
overlay.send(raw.into()).await.unwrap();
|
||||
let outbound = packet(uplink, REMOTE, IpProtocol::Udp, 8020, data).await;
|
||||
let physical = Ipv4Packet::new_checked(&outbound[..]).unwrap();
|
||||
assert_eq!(physical.src_addr(), UPLINK);
|
||||
let translated = UdpPacket::new_checked(physical.payload())
|
||||
.unwrap()
|
||||
.src_port();
|
||||
uplink.send(reply(&outbound)).await.unwrap();
|
||||
let inbound = packet(overlay, member, IpProtocol::Udp, port, data).await;
|
||||
assert_eq!(
|
||||
Ipv4Packet::new_checked(&inbound[..]).unwrap().src_addr(),
|
||||
REMOTE
|
||||
);
|
||||
translated
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires root, the stock Apple PF anchor, and a disposable macOS runner"]
|
||||
async fn exit_preserves_underlay_and_both_meshes() {
|
||||
assert_eq!(agent_uid(&run_tool).unwrap(), 0);
|
||||
let uplink = utun(&[UPLINK]).await;
|
||||
let overlay = utun(&[FIRST, SECOND]).await;
|
||||
|
||||
let mut relay = open_tcp(&*uplink, 8001).await;
|
||||
let existing_quic = UdpSocket::bind((UPLINK, 0)).await.unwrap();
|
||||
existing_quic.connect((REMOTE, 8006)).await.unwrap();
|
||||
udp_round_trip(&*uplink, &existing_quic, "before exit").await;
|
||||
let mut capture = Capture {
|
||||
overlay: overlay.name(),
|
||||
uplink: DefaultRoute {
|
||||
interface: uplink.name().to_owned(),
|
||||
gateway: Some(Ipv4Addr::new(192, 0, 2, 2)),
|
||||
},
|
||||
anchor: anchor_name(overlay.name()).unwrap(),
|
||||
token: Mutex::new(None),
|
||||
added_route: false,
|
||||
added_scoped: false,
|
||||
};
|
||||
// The disposable runner enables kernel forwarding. A keeps the same
|
||||
// translated address and port when B installs an upstream route to this IP.
|
||||
capture.offer(false);
|
||||
let port = member_round_trip(&*overlay, &*uplink, 43001, b"member before").await;
|
||||
capture.enable();
|
||||
assert_eq!(
|
||||
member_round_trip(&*overlay, &*uplink, 43001, b"member during").await,
|
||||
port
|
||||
);
|
||||
member_round_trip(&*overlay, &*uplink, 43002, b"new member flow").await;
|
||||
check_capture_routes(overlay.name(), uplink.name());
|
||||
udp_round_trip(&*uplink, &existing_quic, "existing socket after exit").await;
|
||||
|
||||
// An already established relay must preserve its address and port.
|
||||
relay.write_all(b"established relay").await.unwrap();
|
||||
let established = packet(
|
||||
&*uplink,
|
||||
REMOTE,
|
||||
IpProtocol::Tcp,
|
||||
8001,
|
||||
b"established relay",
|
||||
)
|
||||
.await;
|
||||
let ip = Ipv4Packet::new_checked(&established[..]).unwrap();
|
||||
let tcp = TcpPacket::new_checked(ip.payload()).unwrap();
|
||||
assert_eq!(ip.src_addr(), UPLINK);
|
||||
assert_eq!(tcp.src_port(), relay.local_addr().unwrap().port());
|
||||
uplink.send(reply(&established)).await.unwrap();
|
||||
let mut echo = [0; b"established relay".len()];
|
||||
timeout(WAIT, relay.read_exact(&mut echo))
|
||||
.await
|
||||
.expect("established TCP reply did not reach socket")
|
||||
.unwrap();
|
||||
assert_eq!(&echo, b"established relay");
|
||||
|
||||
// The kernel selects the overlay source on new wildcard sockets. Real
|
||||
// replies to the translated address must reach those same sockets.
|
||||
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
|
||||
socket.connect((REMOTE, 8002)).await.unwrap();
|
||||
assert_eq!(socket.local_addr().unwrap().ip(), SECOND);
|
||||
udp_round_trip(&*uplink, &socket, "new socket after exit").await;
|
||||
let new_relay = open_tcp(&*uplink, 8003).await;
|
||||
assert_eq!(new_relay.local_addr().unwrap().ip(), SECOND);
|
||||
|
||||
// Same destination, ordinary UID: external traffic must enter the exit.
|
||||
let program = "import socket, sys\nsocket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b'ordinary', (sys.argv[1], 8004))";
|
||||
let mut child = tokio::process::Command::new("/usr/bin/python3");
|
||||
child
|
||||
.uid(65534)
|
||||
.gid(65534)
|
||||
.args(["-I", "-c", program, &REMOTE.to_string()])
|
||||
.kill_on_drop(true);
|
||||
assert!(
|
||||
timeout(WAIT, child.status())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
let ordinary = packet(&*overlay, REMOTE, IpProtocol::Udp, 8004, b"ordinary").await;
|
||||
assert_eq!(
|
||||
Ipv4Packet::new_checked(&ordinary[..]).unwrap().src_addr(),
|
||||
SECOND
|
||||
);
|
||||
|
||||
// Root traffic to either mesh also stays on the overlay with its own alias.
|
||||
let mesh = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
|
||||
for local in [FIRST, SECOND] {
|
||||
let peer = Ipv4Addr::from(u32::from(local) + 1);
|
||||
mesh.send_to(b"mesh", (peer, 8005)).await.unwrap();
|
||||
let raw = packet(&*overlay, peer, IpProtocol::Udp, 8005, b"mesh").await;
|
||||
assert_eq!(Ipv4Packet::new_checked(&raw[..]).unwrap().src_addr(), local);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Route ownership survives the process that installed the scoped physical
|
||||
//! routes. A pre-existing compatible route may be used, never adopted.
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(super) struct ScopedHalf {
|
||||
half: u8,
|
||||
egress: DefaultRoute,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
struct Journal {
|
||||
marker: u32,
|
||||
routes: Vec<ScopedHalf>,
|
||||
ipv6: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct ScopedRoutes {
|
||||
journal: Option<PathBuf>,
|
||||
loaded: bool,
|
||||
owned: Journal,
|
||||
pub(super) active: Option<DefaultRoute>,
|
||||
checked: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Default for ScopedRoutes {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
journal: None,
|
||||
loaded: false,
|
||||
owned: Journal {
|
||||
marker: rand::random_range(1..i32::MAX as u32),
|
||||
routes: Vec::new(),
|
||||
ipv6: false,
|
||||
},
|
||||
active: None,
|
||||
checked: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn marked_args(
|
||||
action: &str,
|
||||
prefix: &str,
|
||||
egress: &DefaultRoute,
|
||||
marker: u32,
|
||||
) -> Vec<String> {
|
||||
let mut args = scoped_args(action, prefix, egress);
|
||||
// Darwin exposes this otherwise unused route metric through RTM_GET.
|
||||
// The nonce separates routes made by independent agents on the same uplink.
|
||||
args.extend(["-hopcount".into(), marker.to_string()]);
|
||||
args
|
||||
}
|
||||
|
||||
pub(super) fn field<'a>(text: &'a str, key: &str) -> Option<&'a str> {
|
||||
text.lines()
|
||||
.filter_map(|l| l.trim().split_once(':'))
|
||||
.find_map(|(k, v)| (k == key).then(|| v.trim()))
|
||||
}
|
||||
|
||||
pub(super) fn flag(text: &str, name: &str) -> bool {
|
||||
field(text, "flags").is_some_and(|v| v.trim_matches(['<', '>']).split(',').any(|f| f == name))
|
||||
}
|
||||
|
||||
pub(super) fn marker(text: &str) -> Option<u32> {
|
||||
let mut lines = text.lines();
|
||||
while let Some(line) = lines.next() {
|
||||
if let Some(i) = line.split_whitespace().position(|v| v == "hopcount") {
|
||||
return lines.next()?.split_whitespace().nth(i)?.parse().ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A scoped lookup can return an unscoped LAN route or a default. Only an
|
||||
/// exact scoped /1 on the requested interface can be ours.
|
||||
fn inspect(
|
||||
run: Run<'_>,
|
||||
route: &ScopedHalf,
|
||||
) -> Result<Option<(DefaultRoute, Option<u32>)>, String> {
|
||||
let args = owned(&[
|
||||
"-n",
|
||||
"get",
|
||||
"-ifscope",
|
||||
&route.egress.interface,
|
||||
"-net",
|
||||
HALVES[route.half as usize],
|
||||
]);
|
||||
let text = match run_ok(run, Tool::Route, &args, None) {
|
||||
Ok(text) => text,
|
||||
Err(err)
|
||||
if err.contains("not in table")
|
||||
|| err.contains("No such process")
|
||||
|| err.contains("bad interface name") =>
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let destination = field(&text, "destination");
|
||||
let correct_half = match route.half {
|
||||
0 => matches!(destination, Some("default" | "0.0.0.0")),
|
||||
_ => destination == Some("128.0.0.0"),
|
||||
};
|
||||
if !correct_half || field(&text, "mask") != Some("128.0.0.0") || !flag(&text, "IFSCOPE") {
|
||||
return Ok(None);
|
||||
}
|
||||
let actual = parse_default_route(&text).ok_or("could not read scoped route interface")?;
|
||||
if actual.interface != route.egress.interface {
|
||||
return Ok(None);
|
||||
}
|
||||
let mark = flag(&text, "PROTO2").then(|| marker(&text)).flatten();
|
||||
Ok(Some((actual, mark)))
|
||||
}
|
||||
|
||||
impl ScopedRoutes {
|
||||
pub(super) fn with_journal(path: PathBuf) -> Self {
|
||||
Self {
|
||||
journal: Some(path),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn load(&mut self) -> Result<(), String> {
|
||||
if self.loaded {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(path) = &self.journal {
|
||||
match fs::File::open(path) {
|
||||
Ok(file) => {
|
||||
let mut bytes = Vec::new();
|
||||
file.take(4097)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if bytes.len() > 4096 {
|
||||
return Err("oversized macOS exit route journal".into());
|
||||
}
|
||||
let data: Journal = postcard::from_bytes(&bytes)
|
||||
.map_err(|e| format!("invalid macOS exit route journal: {e}"))?;
|
||||
if data.marker == 0
|
||||
|| data.routes.len() > 8
|
||||
|| data
|
||||
.routes
|
||||
.iter()
|
||||
.any(|r| r.half > 1 || !safe_name(&r.egress.interface))
|
||||
{
|
||||
return Err("invalid macOS exit route ownership".into());
|
||||
}
|
||||
self.owned = data;
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.to_string()),
|
||||
}
|
||||
}
|
||||
self.loaded = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save(&self) -> Result<(), String> {
|
||||
let Some(path) = &self.journal else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.owned.routes.is_empty() && !self.owned.ipv6 {
|
||||
return match fs::remove_file(path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
};
|
||||
}
|
||||
let tmp = path.with_extension(format!("{}.tmp", rand::random::<u64>()));
|
||||
let mut options = fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
let bytes = postcard::to_allocvec(&self.owned).map_err(|err| err.to_string())?;
|
||||
let mut file = options.open(&tmp).map_err(|err| err.to_string())?;
|
||||
let result = file.write_all(&bytes).and_then(|()| fs::rename(&tmp, path));
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(tmp);
|
||||
}
|
||||
result.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub(super) fn previous(&self) -> Vec<ScopedHalf> {
|
||||
self.owned.routes.clone()
|
||||
}
|
||||
|
||||
pub(super) fn ipv6_marker(&self) -> Option<u32> {
|
||||
self.owned.ipv6.then_some(self.owned.marker)
|
||||
}
|
||||
|
||||
pub(super) fn record_ipv6(&mut self, active: bool) -> Result<u32, String> {
|
||||
if self.owned.ipv6 != active {
|
||||
self.owned.ipv6 = active;
|
||||
if let Err(why) = self.save() {
|
||||
self.owned.ipv6 = !active;
|
||||
return Err(why);
|
||||
}
|
||||
}
|
||||
Ok(self.owned.marker)
|
||||
}
|
||||
|
||||
pub(super) fn desired(egress: &DefaultRoute) -> Vec<ScopedHalf> {
|
||||
[0, 1]
|
||||
.map(|half| ScopedHalf {
|
||||
half,
|
||||
egress: egress.clone(),
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
pub(super) fn check_due(&mut self, now: Instant) -> bool {
|
||||
if self
|
||||
.checked
|
||||
.is_some_and(|last| now.duration_since(last) < Duration::from_secs(15))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.checked = Some(now);
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn ensure(&mut self, run: Run<'_>, wanted: &[ScopedHalf]) -> Result<(), String> {
|
||||
for route in wanted {
|
||||
let current = inspect(run, route)?;
|
||||
let action = match current {
|
||||
Some((actual, tag))
|
||||
if actual == route.egress
|
||||
&& (tag.is_none()
|
||||
|| tag == Some(self.owned.marker)
|
||||
&& self.owned.routes.contains(route)) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Some((actual, Some(tag)))
|
||||
if tag == self.owned.marker
|
||||
&& self.owned.routes.contains(&ScopedHalf {
|
||||
half: route.half,
|
||||
egress: actual.clone(),
|
||||
}) =>
|
||||
{
|
||||
"change"
|
||||
}
|
||||
Some(_) => {
|
||||
return Err(format!(
|
||||
"scoped route {} on {} already belongs to another route owner",
|
||||
HALVES[route.half as usize], route.egress.interface
|
||||
));
|
||||
}
|
||||
None => "add",
|
||||
};
|
||||
if !self.owned.routes.contains(route) {
|
||||
if self.owned.routes.len() >= 8 {
|
||||
return Err("too many unreconciled scoped exit routes".into());
|
||||
}
|
||||
self.owned.routes.push(route.clone());
|
||||
if let Err(reason) = self.save() {
|
||||
self.owned.routes.pop();
|
||||
return Err(reason);
|
||||
}
|
||||
}
|
||||
run_ok(
|
||||
run,
|
||||
Tool::Route,
|
||||
&marked_args(
|
||||
action,
|
||||
HALVES[route.half as usize],
|
||||
&route.egress,
|
||||
self.owned.marker,
|
||||
),
|
||||
None,
|
||||
)?;
|
||||
if inspect(run, route)? != Some((route.egress.clone(), Some(self.owned.marker))) {
|
||||
return Err(format!(
|
||||
"the scoped route for {} on {} failed ownership verification",
|
||||
HALVES[route.half as usize], route.egress.interface
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn retain(&mut self, run: Run<'_>, keep: &[ScopedHalf]) -> Result<(), String> {
|
||||
for route in self.previous() {
|
||||
if keep.contains(&route) {
|
||||
continue;
|
||||
}
|
||||
if inspect(run, &route)? == Some((route.egress.clone(), Some(self.owned.marker))) {
|
||||
run_ok(
|
||||
run,
|
||||
Tool::Route,
|
||||
&scoped_args("delete", HALVES[route.half as usize], &route.egress),
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
self.owned.routes.retain(|r| r != &route);
|
||||
if let Err(reason) = self.save() {
|
||||
self.owned.routes.push(route);
|
||||
return Err(reason);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,10 @@
|
||||
#![cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
|
||||
use crate::BoxFuture;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
|
||||
use super::windows_exit;
|
||||
@@ -119,7 +123,7 @@ fn run_powershell(script: &str) -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// Runs a script and returns what it printed, or what it said on failure.
|
||||
fn run_powershell_output(script: &str) -> Result<String, String> {
|
||||
pub(super) fn run_powershell_output(script: &str) -> Result<String, String> {
|
||||
let output = std::process::Command::new(powershell_path())
|
||||
.args([
|
||||
"-NoProfile",
|
||||
@@ -153,12 +157,74 @@ async fn step(what: &'static str, script: String) -> RuleOutcome {
|
||||
|
||||
/// The Windows implementation, through PowerShell.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WindowsHostRules;
|
||||
pub struct WindowsHostRules {
|
||||
relay_cache: Arc<Mutex<RelayCache>>,
|
||||
uplink: Arc<Mutex<Option<(u32, Ipv4Addr)>>>,
|
||||
}
|
||||
|
||||
/// A temporary inventory failure cannot revoke existing sockets. A positive
|
||||
/// withdrawal of the last offer releases their uplink.
|
||||
fn remember_uplink(
|
||||
cache: &Mutex<Option<(u32, Ipv4Addr)>>,
|
||||
offering: bool,
|
||||
observed: Option<(u32, Ipv4Addr)>,
|
||||
) {
|
||||
if !offering || observed.is_some() {
|
||||
*cache.lock().unwrap_or_else(|e| e.into_inner()) = observed;
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowsHostRules {
|
||||
/// Creates it. Nothing is run until [`BroadcastHostRules::apply`].
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_secs(30);
|
||||
const DNS_GRACE: Duration = Duration::from_secs(120);
|
||||
const MAX_RELAY_ADDRESSES: usize = 16;
|
||||
|
||||
/// DNS may rotate while the old relay connection is still carrying packets.
|
||||
/// Keep recent answers for the relays still in use, with a fixed expiry and cap.
|
||||
#[derive(Debug, Default)]
|
||||
struct RelayCache {
|
||||
hosts: HashMap<String, BTreeMap<Ipv4Addr, Instant>>,
|
||||
last_refresh: Option<Instant>,
|
||||
}
|
||||
|
||||
impl RelayCache {
|
||||
fn lookup(
|
||||
&mut self,
|
||||
hosts: &[String],
|
||||
now: Instant,
|
||||
resolve: windows_exit::Resolve<'_>,
|
||||
) -> HashMap<String, Vec<Ipv4Addr>> {
|
||||
self.hosts.retain(|host, _| hosts.contains(host));
|
||||
let due = self
|
||||
.last_refresh
|
||||
.is_none_or(|last| now.duration_since(last) >= REFRESH_INTERVAL);
|
||||
for host in hosts {
|
||||
let known = self.hosts.entry(host.clone()).or_default();
|
||||
known.retain(|_, seen| now.duration_since(*seen) < DNS_GRACE);
|
||||
if due || known.is_empty() {
|
||||
for address in resolve(host).into_iter().take(MAX_RELAY_ADDRESSES) {
|
||||
known.insert(address, now);
|
||||
}
|
||||
while known.len() > MAX_RELAY_ADDRESSES {
|
||||
if let Some((&oldest, _)) = known.iter().min_by_key(|(_, seen)| **seen) {
|
||||
known.remove(&oldest);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if due {
|
||||
self.last_refresh = Some(now);
|
||||
}
|
||||
self.hosts
|
||||
.iter()
|
||||
.map(|(host, addresses)| (host.clone(), addresses.keys().copied().collect()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,12 +239,17 @@ fn resolve_host(host: &str) -> Vec<std::net::Ipv4Addr> {
|
||||
IpAddr::V4(ip) => Some(ip),
|
||||
IpAddr::V6(_) => None,
|
||||
})
|
||||
.take(MAX_RELAY_ADDRESSES)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
impl ExitHostRules for WindowsHostRules {
|
||||
fn forwarded_uplink(&self) -> Option<(u32, Ipv4Addr)> {
|
||||
*self.uplink.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn needs_bypass(&self) -> bool {
|
||||
true
|
||||
}
|
||||
@@ -186,12 +257,21 @@ impl ExitHostRules for WindowsHostRules {
|
||||
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||
Box::pin(async move {
|
||||
let job = plan.clone();
|
||||
let cache = Arc::clone(&self.relay_cache);
|
||||
let uplink = Arc::clone(&self.uplink);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
windows_exit::apply_plan(
|
||||
&|script| run_powershell_output(script),
|
||||
let hosts = cache.lock().unwrap_or_else(|p| p.into_inner()).lookup(
|
||||
&job.bypass_hosts,
|
||||
Instant::now(),
|
||||
&resolve_host,
|
||||
);
|
||||
let (report, physical) = windows_exit::reconcile(
|
||||
&|script| run_powershell_output(script),
|
||||
&|host| hosts.get(host).cloned().unwrap_or_default(),
|
||||
&job,
|
||||
)
|
||||
);
|
||||
remember_uplink(&uplink, !job.offer.is_empty(), physical);
|
||||
report
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
@@ -209,10 +289,59 @@ impl ExitHostRules for WindowsHostRules {
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
|
||||
Box::pin(async move {
|
||||
if !plan.client && plan.offer.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let job = plan.clone();
|
||||
let cache = Arc::clone(&self.relay_cache);
|
||||
let uplink = Arc::clone(&self.uplink);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let now = Instant::now();
|
||||
let mut cache = cache.lock().unwrap_or_else(|p| p.into_inner());
|
||||
if cache
|
||||
.last_refresh
|
||||
.is_some_and(|last| now.duration_since(last) < REFRESH_INTERVAL)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let hosts = cache.lookup(&job.bypass_hosts, now, &resolve_host);
|
||||
drop(cache);
|
||||
if !job.offer.is_empty() {
|
||||
remember_uplink(
|
||||
&uplink,
|
||||
true,
|
||||
windows_exit::uplink(&run_powershell_output, &job.interface).ok(),
|
||||
);
|
||||
}
|
||||
if !job.client {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
match windows_exit::refresh_bypass(
|
||||
&run_powershell_output,
|
||||
&|host| hosts.get(host).cloned().unwrap_or_default(),
|
||||
&job,
|
||||
) {
|
||||
Ok(()) => RuleOutcome::Applied,
|
||||
Err(reason) => RuleOutcome::Failed(reason),
|
||||
},
|
||||
)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|err| Some(RuleOutcome::Failed(format!("the task failed: {err}"))))
|
||||
})
|
||||
}
|
||||
|
||||
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let name = interface.to_string();
|
||||
let cache = Arc::clone(&self.relay_cache);
|
||||
let uplink = Arc::clone(&self.uplink);
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
*uplink.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
*cache.lock().unwrap_or_else(|p| p.into_inner()) = RelayCache::default();
|
||||
windows_exit::clear_all(&|script| run_powershell_output(script), &name)
|
||||
})
|
||||
.await;
|
||||
@@ -258,6 +387,45 @@ mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn transient_uplink_lookup_failure_preserves_the_live_forwarding_address() {
|
||||
let cache = Mutex::new(None);
|
||||
let old = (4, Ipv4Addr::new(192, 0, 2, 5));
|
||||
let new = (7, Ipv4Addr::new(198, 51, 100, 3));
|
||||
for (offering, observed, expected) in [
|
||||
(true, Some(old), Some(old)),
|
||||
(true, None, Some(old)),
|
||||
(true, Some(new), Some(new)),
|
||||
(false, None, None),
|
||||
] {
|
||||
remember_uplink(&cache, offering, observed);
|
||||
assert_eq!(*cache.lock().unwrap(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_dns_survives_a_transient_failure_and_retires_rotated_addresses() {
|
||||
use std::time::{Duration, Instant};
|
||||
let mut cache = RelayCache::default();
|
||||
let hosts = vec!["relay.example".into()];
|
||||
let old = [192, 0, 2, 1].into();
|
||||
let new = [192, 0, 2, 2].into();
|
||||
let now = Instant::now();
|
||||
assert_eq!(cache.lookup(&hosts, now, &|_| vec![old])[&hosts[0]], [old]);
|
||||
let later = |secs| now + Duration::from_secs(secs);
|
||||
assert_eq!(
|
||||
cache.lookup(&hosts, later(32), &|_| Vec::new())[&hosts[0]],
|
||||
[old]
|
||||
);
|
||||
let rotated = cache.lookup(&hosts, later(64), &|_| vec![new]);
|
||||
assert!(rotated[&hosts[0]].contains(&old) && rotated[&hosts[0]].contains(&new));
|
||||
assert_eq!(
|
||||
cache.lookup(&hosts, later(121), &|_| vec![new])[&hosts[0]],
|
||||
[new]
|
||||
);
|
||||
assert!(cache.lookup(&[], later(122), &|_| Vec::new()).is_empty());
|
||||
}
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
fn plan() -> BroadcastRulesPlan {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Exit-node host rules on Windows: WinNAT through PowerShell.
|
||||
//! Physical exit socket selection and client routes on Windows, through PowerShell.
|
||||
//!
|
||||
//! Compiled on every platform so the scripts and the plan logic are tested
|
||||
//! everywhere; only `WindowsHostRules` runs them, and only on Windows. It
|
||||
@@ -6,20 +6,10 @@
|
||||
//!
|
||||
//! # Offering
|
||||
//!
|
||||
//! One NAT object per offered range, named with the usual tag
|
||||
//! `tsunagi-exit:<if>:<range>`:
|
||||
//!
|
||||
//! ```text
|
||||
//! New-NetNat -Name <tag> -InternalIPInterfaceAddressPrefix <range>
|
||||
//! ```
|
||||
//!
|
||||
//! WinNAT translates that range out of whichever interface the traffic leaves
|
||||
//! by, which is the Windows counterpart of the Linux masquerade. Windows
|
||||
//! forwards per interface, and the egress is not known here, so forwarding is
|
||||
//! only *read* for the overlay interface; turning it on for the interfaces
|
||||
//! involved is the owner's decision (`Set-NetIPInterface -Forwarding Enabled`).
|
||||
//! Some Windows versions allow a single NAT per host: a second offered range
|
||||
//! then reports its own failure.
|
||||
//! Forwarded TCP/UDP and ICMP echo use sockets pinned to the physical
|
||||
//! interface and address. This keeps a member's traffic independent of local
|
||||
//! split routes even for the same destination. The userspace gateway owns the
|
||||
//! flows; changing a local upstream does not recreate them.
|
||||
//!
|
||||
//! # Using
|
||||
//!
|
||||
@@ -51,7 +41,7 @@
|
||||
use super::RuleOutcome;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, exit_tag, exit_tag_prefix};
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, exit_tag_prefix};
|
||||
use crate::state::Ipv4Range;
|
||||
|
||||
/// The route metric that marks a bypass route as this agent's.
|
||||
@@ -68,60 +58,67 @@ fn ps_literal(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
/// Creates the NAT of one range, replacing one this agent made before.
|
||||
fn nat_script(interface: &str, range: &Ipv4Range) -> String {
|
||||
let name = ps_literal(&exit_tag(interface, range));
|
||||
let prefix = ps_literal(&range.to_string());
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
$name = {name}\n\
|
||||
Get-NetNat -Name $name -ErrorAction SilentlyContinue | \
|
||||
Remove-NetNat -Confirm:$false -ErrorAction SilentlyContinue\n\
|
||||
New-NetNat -Name $name -InternalIPInterfaceAddressPrefix {prefix} | Out-Null\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes this interface's NAT objects except those named in `keep`.
|
||||
fn prune_script(interface: &str, keep: &[Ipv4Range]) -> String {
|
||||
/// Remove only obsolete WinNAT objects created by older Tsunagi releases.
|
||||
fn legacy_nat_cleanup(interface: &str) -> String {
|
||||
let prefix = ps_literal(&exit_tag_prefix(interface));
|
||||
let keep: Vec<String> = keep
|
||||
.iter()
|
||||
.map(|range| ps_literal(&exit_tag(interface, range)))
|
||||
.collect();
|
||||
format!(
|
||||
"$ErrorActionPreference = 'SilentlyContinue'\n\
|
||||
$prefix = {prefix}\n\
|
||||
$keep = @({})\n\
|
||||
Get-NetNat | Where-Object {{ $_.Name.StartsWith($prefix) -and \
|
||||
($keep -notcontains $_.Name) }} | Remove-NetNat -Confirm:$false\n\
|
||||
exit 0\n",
|
||||
keep.join(", ")
|
||||
$prefix = {prefix}\n\
|
||||
Get-NetNat | Where-Object {{ $_.Name.StartsWith($prefix) }} | Remove-NetNat -Confirm:$false\n\
|
||||
exit 0"
|
||||
)
|
||||
}
|
||||
|
||||
/// Prints `Enabled` or `Disabled` for the interface's IPv4 forwarding.
|
||||
fn forwarding_script(interface: &str) -> String {
|
||||
/// Both client bypasses and forwarded sockets use the winning /0 outside Wintun.
|
||||
fn select_gateway(interface: &str) -> String {
|
||||
let alias = ps_literal(interface);
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
(Get-NetIPInterface -InterfaceAlias {alias} -AddressFamily IPv4).Forwarding\n"
|
||||
$alias = {alias}\n\
|
||||
$best = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 \
|
||||
-PolicyStore ActiveStore | Where-Object {{ $_.InterfaceAlias -ne $alias -and \
|
||||
$_.NextHop -ne '0.0.0.0' -and $_.State -ne 'Dead' }} | Sort-Object {{ $_.RouteMetric + \
|
||||
(Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \
|
||||
Select-Object -First 1\n\
|
||||
if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Prints `<interface index> <next hop>` of the best default route that is
|
||||
/// not through the overlay interface.
|
||||
/// Read a usable source on the selected physical interface, even while the two
|
||||
/// client /1 routes point at Wintun. Never ask the default via the test target.
|
||||
fn uplink_script(interface: &str) -> String {
|
||||
format!(
|
||||
"{}$source = Get-NetIPAddress -InterfaceIndex $best.InterfaceIndex -AddressFamily IPv4 \
|
||||
-AddressState Preferred | Where-Object {{ -not $_.SkipAsSource }} | Select-Object -First 1\n\
|
||||
if (-not $source) {{ throw 'the physical interface has no usable IPv4 address' }}\n\
|
||||
\"$($best.InterfaceIndex) $($source.IPAddress)\"",
|
||||
select_gateway(interface)
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn uplink(run: RunScript<'_>, interface: &str) -> Result<(u32, Ipv4Addr), String> {
|
||||
let text = run(&uplink_script(interface))?;
|
||||
parse_gateway(&text)
|
||||
.filter(|(i, ip)| {
|
||||
*i != 0
|
||||
&& !ip.is_unspecified()
|
||||
&& !ip.is_multicast()
|
||||
&& !ip.is_loopback()
|
||||
&& !ip.is_broadcast()
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
"cannot determine the physical interface and IPv4 source for forwarding".into()
|
||||
})
|
||||
}
|
||||
|
||||
fn gateway_script(interface: &str) -> String {
|
||||
let alias = ps_literal(interface);
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
$alias = {alias}\n\
|
||||
$best = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 \
|
||||
-PolicyStore ActiveStore | Where-Object {{ $_.InterfaceAlias -ne $alias -and \
|
||||
$_.NextHop -ne '0.0.0.0' }} | Sort-Object {{ $_.RouteMetric + \
|
||||
(Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \
|
||||
Select-Object -First 1\n\
|
||||
if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n\
|
||||
\"$($best.InterfaceIndex) $($best.NextHop)\"\n"
|
||||
"{}\"$($best.InterfaceIndex) $($best.NextHop)\"\n\
|
||||
Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{ \
|
||||
$_.InterfaceAlias -ne $alias -and $_.State -ne 'Dead' -and \
|
||||
-not ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32')) }} | \
|
||||
Select-Object -ExpandProperty DestinationPrefix\n",
|
||||
select_gateway(interface)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -220,17 +217,42 @@ fn bypass_addresses(
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn apply_client(
|
||||
pub(super) fn refresh_bypass(
|
||||
run: RunScript<'_>,
|
||||
resolve: Resolve<'_>,
|
||||
plan: &ExitHostPlan,
|
||||
) -> Result<(), String> {
|
||||
let interface = plan.interface.as_str();
|
||||
let gateway = run(&gateway_script(interface))?;
|
||||
let (index, hop) = parse_gateway(&gateway)
|
||||
.ok_or_else(|| format!("cannot read the default gateway from `{}`", gateway.trim()))?;
|
||||
let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay);
|
||||
run(&bypass_script(index, hop, &addresses))?;
|
||||
let mut lines = gateway.lines();
|
||||
let first = lines.next().unwrap_or_default();
|
||||
let (index, hop) = parse_gateway(first)
|
||||
.ok_or_else(|| format!("cannot read the default gateway from `{first}`"))?;
|
||||
let mut addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay);
|
||||
for line in lines {
|
||||
let prefix = line.trim();
|
||||
let (network, bits) = prefix
|
||||
.split_once('/')
|
||||
.and_then(|(address, bits)| {
|
||||
Some((address.parse::<Ipv4Addr>().ok()?, bits.parse::<u8>().ok()?))
|
||||
})
|
||||
.filter(|(_, bits)| *bits <= 32)
|
||||
.ok_or_else(|| format!("cannot read physical route prefix `{prefix}`"))?;
|
||||
if bits > 1 {
|
||||
let mask = u32::MAX << (32 - bits);
|
||||
addresses.retain(|addr| u32::from(*addr) & mask != u32::from(network) & mask);
|
||||
}
|
||||
}
|
||||
run(&bypass_script(index, hop, &addresses)).map(|_| ())
|
||||
}
|
||||
|
||||
fn apply_client(
|
||||
run: RunScript<'_>,
|
||||
resolve: Resolve<'_>,
|
||||
plan: &ExitHostPlan,
|
||||
) -> Result<(), String> {
|
||||
refresh_bypass(run, resolve, plan)?;
|
||||
let interface = &plan.interface;
|
||||
if let Err(why) = run(&halves_script(interface)) {
|
||||
// Do not leave a half-installed set: bypass routes alone are harmless
|
||||
// but the next apply starts clean.
|
||||
@@ -240,35 +262,25 @@ fn apply_client(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_forwarding(text: &str) -> Option<bool> {
|
||||
match text.trim().to_ascii_lowercase().as_str() {
|
||||
"enabled" | "1" => Some(true),
|
||||
"disabled" | "0" => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the host match the plan.
|
||||
pub(super) fn apply_plan(
|
||||
/// Decide the egress for all offered memberships, then reconcile the separate
|
||||
/// destination routes used by this device's applications.
|
||||
pub(super) fn reconcile(
|
||||
run: RunScript<'_>,
|
||||
resolve: Resolve<'_>,
|
||||
plan: &ExitHostPlan,
|
||||
) -> ExitHostReport {
|
||||
) -> (ExitHostReport, Option<(u32, Ipv4Addr)>) {
|
||||
let interface = plan.interface.as_str();
|
||||
// What an earlier plan left and this one no longer wants.
|
||||
let pruned = run(&prune_script(interface, &plan.offer));
|
||||
let physical = (!plan.offer.is_empty()).then(|| uplink(run, interface));
|
||||
let offer = plan
|
||||
.offer
|
||||
.iter()
|
||||
.map(|range| {
|
||||
let outcome = match &pruned {
|
||||
Err(why) => RuleOutcome::Failed(why.clone()),
|
||||
Ok(_) => match run(&nat_script(interface, range)) {
|
||||
Ok(_) => RuleOutcome::Applied,
|
||||
Err(why) => RuleOutcome::Failed(why),
|
||||
},
|
||||
let result = match &physical {
|
||||
Some(Ok(_)) => RuleOutcome::Applied,
|
||||
Some(Err(why)) => RuleOutcome::Failed(why.clone()),
|
||||
None => RuleOutcome::Failed("no exit offer".into()),
|
||||
};
|
||||
(*range, outcome)
|
||||
(*range, result)
|
||||
})
|
||||
.collect();
|
||||
let client = if plan.client {
|
||||
@@ -281,23 +293,19 @@ pub(super) fn apply_plan(
|
||||
let _ = run(&remove_client_script(interface));
|
||||
None
|
||||
};
|
||||
let forwarding = if plan.offer.is_empty() {
|
||||
None
|
||||
} else {
|
||||
run(&forwarding_script(interface))
|
||||
.ok()
|
||||
.and_then(|text| parse_forwarding(&text))
|
||||
};
|
||||
ExitHostReport {
|
||||
offer,
|
||||
forwarding,
|
||||
client,
|
||||
}
|
||||
(
|
||||
ExitHostReport {
|
||||
offer,
|
||||
forwarding: None,
|
||||
client,
|
||||
},
|
||||
physical.and_then(Result::ok),
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes every NAT object of this agent's for the interface.
|
||||
pub(super) fn clear_all(run: RunScript<'_>, interface: &str) {
|
||||
if let Err(why) = run(&prune_script(interface, &[])) {
|
||||
if let Err(why) = run(&legacy_nat_cleanup(interface)) {
|
||||
tracing::warn!(interface, "cannot remove the exit node NAT: {why}");
|
||||
}
|
||||
if let Err(why) = run(&remove_client_script(interface)) {
|
||||
@@ -328,90 +336,109 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nat_is_named_with_the_tag_and_replaces_its_own() {
|
||||
let script = nat_script("tsun0", &range());
|
||||
assert!(
|
||||
script.contains("$name = 'tsunagi-exit:tsun0:10.13.37.0/24'"),
|
||||
"{script}"
|
||||
);
|
||||
assert!(script.contains("-InternalIPInterfaceAddressPrefix '10.13.37.0/24'"));
|
||||
assert!(
|
||||
script.find("Remove-NetNat").unwrap() < script.find("New-NetNat").unwrap(),
|
||||
"{script}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quote_in_a_value_cannot_escape_the_literal() {
|
||||
let script = nat_script("x'; Remove-Item C:\\ #", &range());
|
||||
assert!(script.contains("'tsunagi-exit:x''; Remove-Item C:\\ #:10.13.37.0/24'"));
|
||||
assert!(prune_script("x'y", &[]).contains("'tsunagi-exit:x''y:'"));
|
||||
assert!(forwarding_script("x'y").contains("'x''y'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pruning_keeps_wanted_ranges_and_only_selects_this_interfaces_nats() {
|
||||
let script = prune_script("tsun0", &[range()]);
|
||||
assert!(script.contains("$prefix = 'tsunagi-exit:tsun0:'"));
|
||||
assert!(script.contains("$keep = @('tsunagi-exit:tsun0:10.13.37.0/24')"));
|
||||
assert!(script.contains("StartsWith($prefix)"));
|
||||
assert!(script.contains("exit 0"));
|
||||
assert!(prune_script("tsun0", &[]).contains("$keep = @()"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarding_text_is_read_never_written() {
|
||||
assert_eq!(parse_forwarding("Enabled\r\n"), Some(true));
|
||||
assert_eq!(parse_forwarding("Disabled"), Some(false));
|
||||
assert_eq!(parse_forwarding("what"), None);
|
||||
let script = forwarding_script("tsun0");
|
||||
assert!(script.contains("Get-NetIPInterface"));
|
||||
assert!(!script.contains("Set-NetIPInterface"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offering_prunes_then_creates_and_reads_forwarding() {
|
||||
fn selecting_an_upstream_never_recreates_a_forwarded_session_or_installs_a_destination_exception()
|
||||
{
|
||||
let calls = RefCell::new(Vec::new());
|
||||
let run = |script: &str| -> Result<String, String> {
|
||||
calls.borrow_mut().push(script.to_string());
|
||||
Ok(if script.contains("Get-NetIPInterface") {
|
||||
"Disabled\n".to_string()
|
||||
Ok(if script.contains("Get-NetIPAddress") {
|
||||
"7 192.0.2.15".into()
|
||||
} else if script.contains("Select-Object -ExpandProperty DestinationPrefix") {
|
||||
"7 192.0.2.1".into()
|
||||
} else {
|
||||
String::new()
|
||||
})
|
||||
};
|
||||
let report = apply_plan(&run, &no_names, &plan(false));
|
||||
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
|
||||
assert_eq!(report.forwarding, Some(false));
|
||||
assert_eq!(report.client, None);
|
||||
let calls = calls.borrow();
|
||||
assert!(calls[0].contains("StartsWith"), "{calls:?}");
|
||||
assert!(calls[1].contains("New-NetNat"), "{calls:?}");
|
||||
// Without a client, the routes of an earlier plan are taken away.
|
||||
assert!(calls[2].contains("RouteMetric -eq 7373"), "{calls:?}");
|
||||
assert!(calls[3].contains("Get-NetIPInterface"), "{calls:?}");
|
||||
for client in [false, true, false] {
|
||||
let (report, physical) = reconcile(&run, &no_names, &plan(client));
|
||||
assert_eq!(physical, Some((7, "192.0.2.15".parse().unwrap())));
|
||||
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
|
||||
assert_eq!(report.forwarding, None);
|
||||
}
|
||||
assert!(
|
||||
!calls
|
||||
.borrow()
|
||||
.iter()
|
||||
.any(|s| s.contains("NetNat") || s.contains("Set-NetIPInterface"))
|
||||
);
|
||||
assert!(uplink_script("x'y").contains("'x''y'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_nat_is_that_ranges_failure() {
|
||||
let run = |script: &str| -> Result<String, String> {
|
||||
if script.contains("New-NetNat") {
|
||||
Err("A NAT with this prefix already exists".into())
|
||||
} else {
|
||||
Ok(String::new())
|
||||
}
|
||||
};
|
||||
let report = apply_plan(&run, &no_names, &plan(false));
|
||||
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
|
||||
panic!("{report:?}");
|
||||
};
|
||||
assert!(why.contains("already exists"), "{why}");
|
||||
fn failure_to_find_a_physical_source_never_advertises_a_working_exit() {
|
||||
for line in [
|
||||
"",
|
||||
"0 198.51.100.3",
|
||||
"5 0.0.0.0",
|
||||
"5 127.0.0.1",
|
||||
"3 10.0.0.1 extra",
|
||||
] {
|
||||
let (report, physical) = reconcile(&|_| Ok(line.into()), &no_names, &plan(false));
|
||||
assert_eq!(physical, None);
|
||||
assert!(matches!(&report.offer[0].1, RuleOutcome::Failed(_)));
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_plan(run: RunScript<'_>, resolve: Resolve<'_>, plan: &ExitHostPlan) -> ExitHostReport {
|
||||
reconcile(run, resolve, plan).0
|
||||
}
|
||||
|
||||
fn no_names(_: &str) -> Vec<Ipv4Addr> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Run the real refresh against the Windows ActiveStore. The fixture
|
||||
/// only permits its TEST-NET /32 and refuses to prune pre-existing routes.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
#[ignore = "requires an elevated disposable Windows runner with a physical default gateway"]
|
||||
fn windows_refresh_installs_only_the_external_test_address() {
|
||||
use super::super::windows::run_powershell_output;
|
||||
|
||||
let target = Ipv4Addr::new(198, 51, 100, 207);
|
||||
let inventory = run_powershell_output(&gateway_script("tsng-native-test")).unwrap();
|
||||
let (index, gateway) = parse_gateway(inventory.lines().next().unwrap()).unwrap();
|
||||
let plan = ExitHostPlan {
|
||||
interface: "tsng-native-test".into(),
|
||||
bypass: vec![gateway, target],
|
||||
client: true,
|
||||
..Default::default()
|
||||
};
|
||||
let run = |script: &str| {
|
||||
if script == gateway_script(&plan.interface) {
|
||||
return Ok(inventory.clone());
|
||||
}
|
||||
// Catch a failure to recognize the gateway's connected LAN before
|
||||
// executing a script which might create a route to the gateway.
|
||||
assert!(script.contains(&format!("$keep = @(@('{target}') |")));
|
||||
let guarded = format!(
|
||||
r#"$ErrorActionPreference = 'Stop'
|
||||
$prefix = '{target}/32'
|
||||
$before = @(Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{
|
||||
$_.DestinationPrefix -eq $prefix -or ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32'))
|
||||
}})
|
||||
if ($before.Count) {{ throw 'fixture requires an unused test prefix and no pre-existing bypass routes' }}
|
||||
try {{
|
||||
{script}
|
||||
$actual = @(Get-NetRoute -DestinationPrefix $prefix -PolicyStore ActiveStore -ErrorAction Stop)
|
||||
if ($actual.Count -ne 1 -or $actual[0].InterfaceIndex -ne {index} -or
|
||||
$actual[0].NextHop -ne '{gateway}' -or $actual[0].RouteMetric -ne {BYPASS_METRIC}) {{
|
||||
throw 'unexpected physical bypass route'
|
||||
}}
|
||||
}} finally {{
|
||||
Get-NetRoute -DestinationPrefix $prefix -InterfaceIndex {index} -NextHop '{gateway}' -PolicyStore ActiveStore -ErrorAction SilentlyContinue |
|
||||
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} }} | Remove-NetRoute -Confirm:$false
|
||||
}}
|
||||
if (Get-NetRoute -DestinationPrefix $prefix -PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{
|
||||
throw 'test route still present after cleanup'
|
||||
}}
|
||||
exit 0"#
|
||||
);
|
||||
run_powershell_output(&guarded)
|
||||
};
|
||||
refresh_bypass(&run, &no_names, &plan).unwrap();
|
||||
}
|
||||
|
||||
fn client_plan() -> ExitHostPlan {
|
||||
ExitHostPlan {
|
||||
interface: "tsun0".into(),
|
||||
@@ -549,6 +576,47 @@ mod tests {
|
||||
assert!(!bypass.contains("'10.13.37.4'") && !bypass.contains("'10.99.0.6'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connected_lan_and_an_existing_host_route_stay_on_their_own_paths() {
|
||||
let mut plan = client_plan();
|
||||
for addr in ["192.168.1.11", "198.51.100.7", "198.51.100.9"] {
|
||||
plan.bypass.push(addr.parse().unwrap());
|
||||
}
|
||||
let calls = RefCell::new(Vec::new());
|
||||
let run = |script: &str| {
|
||||
calls.borrow_mut().push(script.to_string());
|
||||
Ok("12 192.168.1.1\n192.168.1.0/24\n198.51.100.7/32\n".into())
|
||||
};
|
||||
apply_client(&run, &no_names, &plan).unwrap();
|
||||
let calls = calls.borrow();
|
||||
let bypass = calls.iter().find(|s| s.contains("New-NetRoute")).unwrap();
|
||||
assert!(!bypass.contains("'192.168.1.11'"));
|
||||
assert!(!bypass.contains("'198.51.100.7'"));
|
||||
assert!(bypass.contains("'198.51.100.9'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_uses_the_new_physical_gateway_without_touching_the_exit_routes() {
|
||||
let plan = client_plan();
|
||||
let routes = RefCell::new(Vec::new());
|
||||
for gateway in ["12 192.168.1.1", "17 10.0.0.1"] {
|
||||
let run = |script: &str| {
|
||||
if script.contains("Select-Object -First 1") {
|
||||
Ok(gateway.into())
|
||||
} else {
|
||||
routes.borrow_mut().push(script.to_owned());
|
||||
Ok(String::new())
|
||||
}
|
||||
};
|
||||
refresh_bypass(&run, &no_names, &plan).unwrap();
|
||||
}
|
||||
let routes = routes.into_inner();
|
||||
assert_eq!(routes.len(), 2);
|
||||
assert!(routes[0].contains("-InterfaceIndex 12 -NextHop '192.168.1.1'"));
|
||||
assert!(routes[1].contains("-InterfaceIndex 17 -NextHop '10.0.0.1'"));
|
||||
assert!(routes.iter().all(|s| !s.contains("'0.0.0.0/1'")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_goes_through_the_overlay_when_the_bypass_cannot_be_written() {
|
||||
let run = |script: &str| -> Result<String, String> {
|
||||
@@ -642,7 +710,7 @@ mod tests {
|
||||
};
|
||||
clear_all(&run, "tsun0");
|
||||
let seen = seen.borrow();
|
||||
assert!(seen[0].contains("$keep = @()"));
|
||||
assert!(seen[0].contains("StartsWith($prefix)"));
|
||||
assert!(seen[0].contains("'tsunagi-exit:tsun0:'"));
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ use iroh::EndpointId;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::identity::NetworkId;
|
||||
use crate::traffic::{Direction, Role};
|
||||
|
||||
use super::exit::{ExitRulesReport, RuleSetReport};
|
||||
use super::hostrules::{
|
||||
@@ -147,6 +148,8 @@ impl Tally {
|
||||
/// The overlay interface.
|
||||
pub struct Interface {
|
||||
device: Arc<dyn TunDevice>,
|
||||
#[cfg(windows)]
|
||||
forwarding: Option<super::egress::Gateway>,
|
||||
factory: Arc<dyn TunFactory>,
|
||||
name: String,
|
||||
mtu: u32,
|
||||
@@ -235,6 +238,34 @@ impl Interface {
|
||||
let name = device.name().to_string();
|
||||
let tally = Arc::new(Tally::default());
|
||||
|
||||
#[cfg(windows)]
|
||||
let forwarding = factory.on_host().then(|| {
|
||||
let routes = routes.clone();
|
||||
let carrier = carrier.clone();
|
||||
super::egress::Gateway::new(mtu, move |route, packet| {
|
||||
if let Some(IpHeader::V4 {
|
||||
source,
|
||||
destination,
|
||||
}) = IpHeader::parse(&packet)
|
||||
&& routes.accepts_exit_traffic(route.network, source)
|
||||
&& matches!(
|
||||
routes.packet_source(route.network, route.peer, destination),
|
||||
Some(PacketSource::Member)
|
||||
)
|
||||
{
|
||||
let obs = routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| Role::ServeExit,
|
||||
);
|
||||
if carrier.carry(route, packet) {
|
||||
obs.record();
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
let vip_task = {
|
||||
let factory = Arc::clone(&factory);
|
||||
let routes = Arc::clone(&routes);
|
||||
@@ -247,7 +278,10 @@ impl Interface {
|
||||
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 (route,packet) in probes {
|
||||
let obs = routes.traffic.packet(route.network,route.peer,Direction::Tx,&packet,||Role::Vip);
|
||||
if carrier.carry(route,packet) {obs.record();}
|
||||
}
|
||||
for job in jobs {
|
||||
let factory = Arc::clone(&factory);
|
||||
checks.spawn(job.run(move |socket, source| factory.bind_overlay_socket(socket, source)));
|
||||
@@ -273,8 +307,14 @@ impl Interface {
|
||||
};
|
||||
match routes.vips.outgoing(packet.clone()) {
|
||||
crate::vip::router::Decision::Send(route, packet) => {
|
||||
let obs =
|
||||
routes
|
||||
.vips
|
||||
.observe_outgoing(&routes.traffic, Some(route), &packet);
|
||||
for part in crate::vip::packet::fragments(packet, mtu) {
|
||||
let len = part.len();
|
||||
if carrier.carry(route, part) {
|
||||
obs.record_fragment(len);
|
||||
tally.sent.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -282,13 +322,22 @@ impl Interface {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
crate::vip::router::Decision::Local(packet) => {
|
||||
for part in crate::vip::packet::fragments(packet, mtu) {
|
||||
let _ = device.send(part).await;
|
||||
crate::vip::router::Decision::Local(translated)
|
||||
| crate::vip::router::Decision::Reassembled(translated) => {
|
||||
let obs =
|
||||
routes
|
||||
.vips
|
||||
.observe_outgoing(&routes.traffic, None, &translated);
|
||||
for part in crate::vip::packet::fragments(translated, mtu) {
|
||||
let len = part.len();
|
||||
if device.send(part).await.is_ok() {
|
||||
obs.record_fragment(len);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
crate::vip::router::Decision::Drop => continue,
|
||||
crate::vip::router::Decision::Drop
|
||||
| crate::vip::router::Decision::ProbeReceived => continue,
|
||||
crate::vip::router::Decision::Pass => {}
|
||||
}
|
||||
let destination = header.destination();
|
||||
@@ -301,7 +350,15 @@ impl Interface {
|
||||
.flatten();
|
||||
if let Some(recipients) = recipients {
|
||||
for &route in recipients.iter() {
|
||||
let obs = routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| Role::Broadcast,
|
||||
);
|
||||
if carrier.carry(route, packet.clone()) {
|
||||
obs.record();
|
||||
tally.sent.fetch_add(1, Ordering::Relaxed);
|
||||
tally.broadcast_sent.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
@@ -320,11 +377,39 @@ impl Interface {
|
||||
tally.multicast.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
let Some(route) = routes.route_v4(destination) else {
|
||||
let selected = match (header.source(), destination) {
|
||||
(IpAddr::V4(source), IpAddr::V4(address)) => {
|
||||
routes.packet_route(Some(source), address)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let Some((route, exit)) = selected else {
|
||||
tally.note_unroutable(destination);
|
||||
continue;
|
||||
};
|
||||
let len = packet.len() as u64;
|
||||
let obs = routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| {
|
||||
if exit.is_some() {
|
||||
Role::ViaExit
|
||||
} else if let IpAddr::V4(src) = header.source()
|
||||
&& routes.accepts_exit_traffic(route.network, src)
|
||||
{
|
||||
Role::ServeExit
|
||||
} else {
|
||||
Role::Mesh
|
||||
}
|
||||
},
|
||||
);
|
||||
if carrier.carry(route, packet) {
|
||||
obs.record();
|
||||
if let Some(exit) = exit {
|
||||
exit.tx_bytes.fetch_add(len, Ordering::Relaxed);
|
||||
}
|
||||
tally.sent.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -334,6 +419,8 @@ impl Interface {
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
#[cfg(windows)]
|
||||
forwarding,
|
||||
device,
|
||||
factory,
|
||||
name,
|
||||
@@ -456,6 +543,10 @@ impl Interface {
|
||||
(state.plan.clone(), state.is_ok())
|
||||
};
|
||||
if wanted.is_empty() {
|
||||
#[cfg(windows)]
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(Vec::new());
|
||||
}
|
||||
if planned.is_some() {
|
||||
exit.clear(&self.name).await;
|
||||
let mut state = self.exit_state();
|
||||
@@ -474,9 +565,13 @@ impl Interface {
|
||||
report.client = Some(outcome);
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
self.configure_forwarding(exit.forwarded_uplink());
|
||||
return;
|
||||
}
|
||||
let report = exit.apply(&wanted).await;
|
||||
#[cfg(windows)]
|
||||
self.configure_forwarding(exit.forwarded_uplink());
|
||||
for (range, outcome) in &report.offer {
|
||||
match outcome {
|
||||
RuleOutcome::Applied => tracing::info!(
|
||||
@@ -524,6 +619,22 @@ impl Interface {
|
||||
state.report = Some(report);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn configure_forwarding(&self, physical: Option<(u32, std::net::Ipv4Addr)>) {
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(
|
||||
self.routes
|
||||
.exit_offers()
|
||||
.into_iter()
|
||||
.filter_map(|(network, _)| {
|
||||
let (index, address) = physical?;
|
||||
Some((network, super::egress::Physical { index, address }))
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the host routes its own transport by destination.
|
||||
pub(crate) fn needs_underlay_targets(&self) -> bool {
|
||||
self.host_rules
|
||||
@@ -773,6 +884,10 @@ impl Interface {
|
||||
|
||||
/// Removes the interface from the host.
|
||||
pub async fn remove(&self) {
|
||||
#[cfg(windows)]
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(Vec::new());
|
||||
}
|
||||
// The route goes with the interface; the firewall rule does not, so
|
||||
// it is taken out explicitly while the interface is still known.
|
||||
if let Some(rules) = &self.host_rules {
|
||||
@@ -840,12 +955,14 @@ impl Interface {
|
||||
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(Rejected::WrongSource);
|
||||
};
|
||||
let broadcast = match (origin, header.destination()) {
|
||||
(PacketSource::ExitReply { local: Some(local) }, IpAddr::V4(destination))
|
||||
if destination == local =>
|
||||
{
|
||||
false
|
||||
}
|
||||
let (broadcast, exit, forwarded) = match (origin, header.destination()) {
|
||||
(
|
||||
PacketSource::ExitReply {
|
||||
local: Some(local),
|
||||
exit,
|
||||
},
|
||||
IpAddr::V4(destination),
|
||||
) if destination == local => (false, Some(exit), false),
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.is_broadcast(destination) =>
|
||||
{
|
||||
@@ -855,13 +972,17 @@ impl Interface {
|
||||
self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(Rejected::BroadcastDenied);
|
||||
}
|
||||
true
|
||||
(true, None, false)
|
||||
}
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.is_local_destination(network, destination)
|
||||
|| self.routes.accepts_exit_traffic(network, destination) =>
|
||||
if self.routes.is_local_destination(network, destination) =>
|
||||
{
|
||||
false
|
||||
(false, None, false)
|
||||
}
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.accepts_exit_traffic(network, destination) =>
|
||||
{
|
||||
(false, None, true)
|
||||
}
|
||||
_ => {
|
||||
self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -870,24 +991,104 @@ impl Interface {
|
||||
};
|
||||
// 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) => {
|
||||
crate::vip::router::Decision::Send(route, reply) => {
|
||||
self.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &packet, || Role::Vip)
|
||||
.record();
|
||||
let packet = reply;
|
||||
// Probe replies use the ordinary peer carrier, never the TUN.
|
||||
self.carrier.carry(route, packet);
|
||||
let tx = self.routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| Role::Vip,
|
||||
);
|
||||
if self.carrier.carry(route, packet) {
|
||||
tx.record();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::Local(packet) => {
|
||||
for part in crate::vip::packet::fragments(packet, self.mtu) {
|
||||
crate::vip::router::Decision::Local(translated) => {
|
||||
let obs =
|
||||
self.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &translated, || Role::Vip);
|
||||
for part in crate::vip::packet::fragments(translated, self.mtu) {
|
||||
let len = part.len();
|
||||
if self.device.send(part).await.is_ok() {
|
||||
obs.record_fragment(len);
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::Reassembled(reassembled) => {
|
||||
for part in crate::vip::packet::fragments(reassembled, self.mtu) {
|
||||
self.deliver_admitted(network, peer, part, broadcast, exit.as_ref(), forwarded)
|
||||
.await;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::ProbeReceived => {
|
||||
self.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &packet, || Role::Vip)
|
||||
.record();
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::Drop => return Ok(()),
|
||||
crate::vip::router::Decision::Pass => packet,
|
||||
};
|
||||
self.deliver_admitted(network, peer, packet, broadcast, exit.as_ref(), forwarded)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn deliver_admitted(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
packet: Bytes,
|
||||
broadcast: bool,
|
||||
exit: Option<&Arc<super::router::SelectedExit>>,
|
||||
forwarded: bool,
|
||||
) {
|
||||
let obs = self
|
||||
.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &packet, || {
|
||||
if forwarded {
|
||||
Role::ServeExit
|
||||
} else if exit.is_some() {
|
||||
Role::ViaExit
|
||||
} else if broadcast {
|
||||
Role::Broadcast
|
||||
} else {
|
||||
Role::Mesh
|
||||
}
|
||||
});
|
||||
// Only authenticated member traffic admitted by the exit policy can
|
||||
// open a physical socket. A rejected allocation never falls through
|
||||
// to Wintun, where the local upstream's split routes might recapture it.
|
||||
#[cfg(windows)]
|
||||
if forwarded && let Some(gateway) = &self.forwarding {
|
||||
if gateway.forward(Route { network, peer }, packet) {
|
||||
obs.record();
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.tally.undeliverable.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Remote broadcasts terminate here. Only local TUN ingress can fan out.
|
||||
let len = packet.len() as u64;
|
||||
if self.device.send(packet).await.is_ok() {
|
||||
obs.record();
|
||||
if let Some(exit) = exit {
|
||||
exit.rx_bytes.fetch_add(len, Ordering::Relaxed);
|
||||
}
|
||||
if broadcast {
|
||||
self.tally
|
||||
.broadcast_received
|
||||
@@ -895,7 +1096,6 @@ impl Interface {
|
||||
}
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The addresses the interface should be carrying, from the table.
|
||||
@@ -926,18 +1126,6 @@ impl Drop for Interface {
|
||||
}
|
||||
}
|
||||
|
||||
impl RoutingTable {
|
||||
/// The route for a destination, when it is one the overlay carries.
|
||||
fn route_v4(&self, destination: IpAddr) -> Option<Route> {
|
||||
match destination {
|
||||
IpAddr::V4(address) => self.route(address),
|
||||
// The overlay is IPv4. An IPv6 packet has no owner here, and
|
||||
// counting it as unroutable is the truth rather than a fault.
|
||||
IpAddr::V6(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an address is one the overlay has nowhere to send.
|
||||
fn is_multicast_or_broadcast(address: IpAddr) -> bool {
|
||||
match address {
|
||||
@@ -1530,6 +1718,57 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exit_totals_count_only_accepted_internet_packets_for_the_current_choice() {
|
||||
let (interface, device, routes, _, id) = interface(false).await;
|
||||
let totals = |p| {
|
||||
routes
|
||||
.exit_traffic(id, peer(p))
|
||||
.map(|t| (t.tx_bytes, t.rx_bytes))
|
||||
};
|
||||
assert_eq!(totals(2), None);
|
||||
routes.set_exit(id, using(peer(2)));
|
||||
let outgoing = ipv4(addr(1), INTERNET, b"request");
|
||||
device.push_from_os(outgoing.clone());
|
||||
device.push_from_os(ipv4(addr(1), addr(2), b"ordinary mesh traffic"));
|
||||
wait_for(&interface, |c| c.sent.saturating_sub(1)).await;
|
||||
let incoming = ipv4(INTERNET, addr(1), b"reply");
|
||||
interface
|
||||
.deliver(id, peer(2), incoming.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
interface
|
||||
.deliver(id, peer(2), ipv4(addr(2), addr(1), b"mesh"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
interface
|
||||
.deliver(id, peer(3), incoming.clone())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
interface
|
||||
.deliver(id, peer(2), ipv4(INTERNET, addr(3), b"wrong host"))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
routes.set_exit(id, using(peer(2)));
|
||||
assert_eq!(
|
||||
totals(2),
|
||||
Some((outgoing.len() as u64, incoming.len() as u64))
|
||||
);
|
||||
routes.set_exit(id, using(peer(3)));
|
||||
assert_eq!(totals(2), None);
|
||||
assert_eq!(totals(3), Some((0, 0)));
|
||||
routes.set_exit(id, ExitPolicy::default());
|
||||
assert_eq!(totals(3), None);
|
||||
routes.set_exit(id, using(peer(2)));
|
||||
assert_eq!(totals(2), Some((0, 0)));
|
||||
interface.remove().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn internet_traffic_goes_to_the_exit_node_and_only_once_one_is_chosen() {
|
||||
let (interface, device, routes, carrier, id) = interface(false).await;
|
||||
|
||||
@@ -40,6 +40,8 @@ pub enum OverlayError {
|
||||
|
||||
pub mod broadcast;
|
||||
pub mod config;
|
||||
#[cfg(any(windows, test))]
|
||||
mod egress;
|
||||
pub mod exit;
|
||||
pub mod hostrules;
|
||||
pub mod interface;
|
||||
|
||||
@@ -55,7 +55,7 @@ use crate::BoxFuture;
|
||||
use crate::overlay::OverlayError;
|
||||
|
||||
use super::super::config::Cidr;
|
||||
use super::super::hostrules::linux_exit_mark::{UNDERLAY_MARK, UNDERLAY_MASK};
|
||||
use super::super::hostrules::linux_exit_mark::{EXIT_REPLY_MARK, UNDERLAY_MARK, UNDERLAY_MASK};
|
||||
use super::super::tun::{TunDevice, TunRequest};
|
||||
use super::privilege::{NetAdmin, Privilege, probe_net_admin};
|
||||
use super::{
|
||||
@@ -671,6 +671,7 @@ const EXIT_TABLE: u32 = 0x7473;
|
||||
/// The main table.
|
||||
const MAIN_TABLE: u32 = 254;
|
||||
/// Protect marked underlay and initial socket routing before Tailscale's rules.
|
||||
const EXIT_REPLY_PRIORITY: u32 = 5204;
|
||||
const EXIT_MARK_PRIORITY: u32 = 5205;
|
||||
const EXIT_BYPASS_PRIORITY: u32 = 5206;
|
||||
const LEGACY_EXIT_BYPASS_PRIORITY: u32 = 5280;
|
||||
@@ -704,6 +705,15 @@ fn rule_priority(rule: &RuleMessage) -> Option<u32> {
|
||||
fn is_exit_rule(rule: &RuleMessage) -> bool {
|
||||
let table = rule_table(rule);
|
||||
match rule_priority(rule) {
|
||||
Some(EXIT_REPLY_PRIORITY) => {
|
||||
table == EXIT_TABLE
|
||||
&& rule
|
||||
.attributes
|
||||
.contains(&RuleAttribute::FwMark(EXIT_REPLY_MARK))
|
||||
&& rule
|
||||
.attributes
|
||||
.contains(&RuleAttribute::FwMask(EXIT_REPLY_MARK))
|
||||
}
|
||||
Some(EXIT_MARK_PRIORITY) => {
|
||||
table == MAIN_TABLE
|
||||
&& rule
|
||||
@@ -865,11 +875,11 @@ async fn replace_exit_default(
|
||||
/// ip rule add priority 5205 fwmark 0x40000000/0x40000000 lookup main
|
||||
/// ip rule add priority 5206 uidrange <uid>-<uid> lookup main
|
||||
/// ip rule add priority 5290 lookup main suppress_prefixlength 0
|
||||
/// ip rule add priority 5300 lookup 0x7473
|
||||
/// ip rule add priority 5300 iif lo lookup 0x7473
|
||||
/// ```
|
||||
///
|
||||
/// and the same for IPv6 with `ip -6 route replace unreachable default table
|
||||
/// 0x7473`, so that IPv6 is refused instead of leaving the ordinary way.
|
||||
/// 0x7473` and no interface selector, so IPv6 is refused.
|
||||
///
|
||||
/// What an earlier call left is removed first, so repeating it is safe, and
|
||||
/// the rules go in last, so a failure part way never leaves a rule that
|
||||
@@ -886,7 +896,24 @@ async fn set_exit_client(
|
||||
};
|
||||
replace_exit_default(&handle, name, source).await?;
|
||||
|
||||
add_mark_bypass(&handle, false).await?;
|
||||
if uid == 0 {
|
||||
add_mark_rule(
|
||||
&handle,
|
||||
false,
|
||||
EXIT_TABLE,
|
||||
EXIT_REPLY_PRIORITY,
|
||||
EXIT_REPLY_MARK,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
add_mark_rule(
|
||||
&handle,
|
||||
false,
|
||||
MAIN_TABLE,
|
||||
EXIT_MARK_PRIORITY,
|
||||
UNDERLAY_MARK,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut bypass = handle
|
||||
.rule()
|
||||
@@ -930,6 +957,7 @@ async fn set_exit_client(
|
||||
.table_id(EXIT_TABLE)
|
||||
.action(RuleAction::ToTable)
|
||||
.priority(EXIT_DEFAULT_PRIORITY)
|
||||
.input_interface("lo")
|
||||
.execute()
|
||||
.await
|
||||
.map_err(|err| fail("rule for the default route", err))?;
|
||||
@@ -960,7 +988,7 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O
|
||||
};
|
||||
}
|
||||
|
||||
add_mark_bypass(handle, true).await?;
|
||||
add_mark_rule(handle, true, MAIN_TABLE, EXIT_MARK_PRIORITY, UNDERLAY_MARK).await?;
|
||||
let mut bypass = handle
|
||||
.rule()
|
||||
.add()
|
||||
@@ -1008,14 +1036,20 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O
|
||||
.map_err(|err| fail("rule for the default route", err))
|
||||
}
|
||||
|
||||
async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), OverlayError> {
|
||||
async fn add_mark_rule(
|
||||
handle: &rtnetlink::Handle,
|
||||
v6: bool,
|
||||
table: u32,
|
||||
priority: u32,
|
||||
bit: u32,
|
||||
) -> Result<(), OverlayError> {
|
||||
let mut rule = handle
|
||||
.rule()
|
||||
.add()
|
||||
.table_id(MAIN_TABLE)
|
||||
.table_id(table)
|
||||
.action(RuleAction::ToTable)
|
||||
.priority(EXIT_MARK_PRIORITY)
|
||||
.fw_mark(UNDERLAY_MARK);
|
||||
.priority(priority)
|
||||
.fw_mark(bit);
|
||||
rule.message_mut().header.family = if v6 {
|
||||
rtnetlink::packet_route::AddressFamily::Inet6
|
||||
} else {
|
||||
@@ -1023,9 +1057,11 @@ async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), Ove
|
||||
};
|
||||
rule.message_mut()
|
||||
.attributes
|
||||
.push(RuleAttribute::FwMask(UNDERLAY_MASK));
|
||||
.push(RuleAttribute::FwMask(bit));
|
||||
rule.execute().await.map_err(|err| {
|
||||
OverlayError::Unavailable(format!("cannot protect marked underlay traffic: {err}"))
|
||||
OverlayError::Unavailable(format!(
|
||||
"cannot add exit routing rule {priority} for mark {bit:#x}: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -21,9 +21,11 @@
|
||||
//! one is in use.
|
||||
|
||||
use super::broadcast::{BroadcastPolicy, BroadcastTable};
|
||||
use arc_swap::ArcSwap;
|
||||
use super::exit::ExitTraffic;
|
||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||
use std::collections::HashMap;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use iroh::EndpointId;
|
||||
@@ -43,7 +45,19 @@ pub struct Route {
|
||||
/// An internet source is valid only for a reply to our address in the exit's network.
|
||||
pub(super) enum PacketSource {
|
||||
Member,
|
||||
ExitReply { local: Option<Ipv4Addr> },
|
||||
ExitReply {
|
||||
local: Option<Ipv4Addr>,
|
||||
exit: Arc<SelectedExit>,
|
||||
},
|
||||
}
|
||||
|
||||
/// A packet holds its selection until delivery finishes, even if the operator
|
||||
/// switches to another exit in the meantime.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct SelectedExit {
|
||||
route: Route,
|
||||
pub(super) tx_bytes: AtomicU64,
|
||||
pub(super) rx_bytes: AtomicU64,
|
||||
}
|
||||
|
||||
/// A network's exit-node settings, as far as packets are concerned.
|
||||
@@ -71,6 +85,44 @@ pub struct NetworkRoutes {
|
||||
pub peers: Vec<(Ipv4Addr, EndpointId)>,
|
||||
}
|
||||
|
||||
impl NetworkRoutes {
|
||||
fn address_pair(&self, peer: EndpointId) -> Option<(Ipv4Addr, Ipv4Addr)> {
|
||||
let local = self.local?;
|
||||
let (remote, _) = self.peers.iter().find(|(_, owner)| *owner == peer)?;
|
||||
Some((local, *remote))
|
||||
}
|
||||
}
|
||||
|
||||
/// The signed addresses negotiated for one running diagnostic. A new allocation can
|
||||
/// invalidate either end, so an active probe must recheck them when ownership changes.
|
||||
pub(crate) struct DiagnosticPeer {
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
pub(crate) local: Ipv4Addr,
|
||||
pub(crate) remote: Ipv4Addr,
|
||||
// Even revision of the checked routing table, plus one if both addresses matched.
|
||||
checked: AtomicU64,
|
||||
}
|
||||
|
||||
impl DiagnosticPeer {
|
||||
pub(crate) fn is_current(&self, table: &RoutingTable) -> bool {
|
||||
let revision = table.address_revision.load(Ordering::Acquire);
|
||||
let checked = self.checked.load(Ordering::Relaxed);
|
||||
if checked & !1 == revision {
|
||||
return checked & 1 != 0;
|
||||
}
|
||||
let networks = table.read();
|
||||
let pair = networks
|
||||
.get(&self.network)
|
||||
.and_then(|n| n.address_pair(self.peer));
|
||||
let valid = pair == Some((self.local, self.remote));
|
||||
let revision = table.address_revision.load(Ordering::Relaxed);
|
||||
self.checked
|
||||
.store(revision | u64::from(valid), Ordering::Relaxed);
|
||||
valid
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a network cannot be added to the table.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum RouteError {
|
||||
@@ -95,9 +147,13 @@ pub enum RouteError {
|
||||
/// Address ownership across every network this agent is in.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct RoutingTable {
|
||||
pub(crate) traffic: Arc<crate::traffic::TrafficMonitor>,
|
||||
pub(crate) vips: Arc<crate::vip::VipRouter>,
|
||||
broadcast: ArcSwap<BroadcastTable>,
|
||||
selected_exit: ArcSwapOption<SelectedExit>,
|
||||
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
|
||||
/// Advanced by two under the routing write lock when signed address ownership changes.
|
||||
address_revision: AtomicU64,
|
||||
}
|
||||
|
||||
impl RoutingTable {
|
||||
@@ -106,6 +162,23 @@ impl RoutingTable {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Exact local and signed remote addresses for a mesh diagnostic. Exit routes do not qualify.
|
||||
pub(crate) fn diagnostic_peer(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
) -> Option<DiagnosticPeer> {
|
||||
let networks = self.read();
|
||||
let (local, remote) = networks.get(&network)?.address_pair(peer)?;
|
||||
Some(DiagnosticPeer {
|
||||
network,
|
||||
peer,
|
||||
local,
|
||||
remote,
|
||||
checked: AtomicU64::new(self.address_revision.load(Ordering::Relaxed) | 1),
|
||||
})
|
||||
}
|
||||
|
||||
fn read(&self) -> std::sync::RwLockReadGuard<'_, HashMap<NetworkId, NetworkRoutes>> {
|
||||
match self.networks.read() {
|
||||
Ok(guard) => guard,
|
||||
@@ -170,7 +243,14 @@ impl RoutingTable {
|
||||
if routes.exit.via.is_some() {
|
||||
clear_other_exits(networks, network);
|
||||
}
|
||||
let ownership_changed = networks
|
||||
.get(&network)
|
||||
.is_none_or(|old| old.local != routes.local || old.peers != routes.peers);
|
||||
networks.insert(network, routes);
|
||||
if ownership_changed {
|
||||
self.address_revision.fetch_add(2, Ordering::Release);
|
||||
}
|
||||
self.refresh_exit(networks);
|
||||
self.broadcast
|
||||
.store(Arc::new(BroadcastTable::build(networks)));
|
||||
Ok(())
|
||||
@@ -180,7 +260,10 @@ impl RoutingTable {
|
||||
pub fn remove_network(&self, network: NetworkId) {
|
||||
self.vips.remove_network(network);
|
||||
let mut networks = self.write();
|
||||
networks.remove(&network);
|
||||
if networks.remove(&network).is_some() {
|
||||
self.address_revision.fetch_add(2, Ordering::Release);
|
||||
}
|
||||
self.refresh_exit(&networks);
|
||||
self.broadcast
|
||||
.store(Arc::new(BroadcastTable::build(&networks)));
|
||||
}
|
||||
@@ -213,9 +296,35 @@ impl RoutingTable {
|
||||
if routes.exit.via.is_some() {
|
||||
clear_other_exits(&mut networks, network);
|
||||
}
|
||||
self.refresh_exit(&networks);
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish the current choice under the same write lock as the route edits.
|
||||
fn refresh_exit(&self, networks: &HashMap<NetworkId, NetworkRoutes>) {
|
||||
let route = exit_via(networks).map(|(network, peer)| Route { network, peer });
|
||||
if self.selected_exit.load().as_ref().map(|exit| exit.route) != route {
|
||||
self.selected_exit.store(route.map(|route| {
|
||||
Arc::new(SelectedExit {
|
||||
route,
|
||||
tx_bytes: AtomicU64::default(),
|
||||
rx_bytes: AtomicU64::default(),
|
||||
})
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn exit_traffic(&self, network: NetworkId, peer: EndpointId) -> Option<ExitTraffic> {
|
||||
let current = self.selected_exit.load();
|
||||
let exit = current
|
||||
.as_ref()
|
||||
.filter(|e| e.route == Route { network, peer })?;
|
||||
Some(ExitTraffic {
|
||||
tx_bytes: exit.tx_bytes.load(Ordering::Relaxed),
|
||||
rx_bytes: exit.rx_bytes.load(Ordering::Relaxed),
|
||||
})
|
||||
}
|
||||
|
||||
/// Recognizes limited and configured subnet broadcasts before unicast lookup.
|
||||
pub fn is_broadcast(&self, destination: Ipv4Addr) -> bool {
|
||||
self.broadcast.load().is_destination(destination)
|
||||
@@ -249,6 +358,14 @@ impl RoutingTable {
|
||||
/// unicast destination, goes to this device's exit node when it has one:
|
||||
/// that is what sending *all* traffic through a member means.
|
||||
pub fn route(&self, destination: Ipv4Addr) -> Option<Route> {
|
||||
self.packet_route(None, destination).map(|(route, _)| route)
|
||||
}
|
||||
|
||||
pub(super) fn packet_route(
|
||||
&self,
|
||||
source: Option<Ipv4Addr>,
|
||||
destination: Ipv4Addr,
|
||||
) -> Option<(Route, Option<Arc<SelectedExit>>)> {
|
||||
let networks = self.read();
|
||||
for (network, routes) in networks.iter() {
|
||||
if routes.local == Some(destination) {
|
||||
@@ -259,10 +376,13 @@ impl RoutingTable {
|
||||
.iter()
|
||||
.find(|(address, _)| *address == destination)
|
||||
{
|
||||
return Some(Route {
|
||||
network: *network,
|
||||
peer: *peer,
|
||||
});
|
||||
return Some((
|
||||
Route {
|
||||
network: *network,
|
||||
peer: *peer,
|
||||
},
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
// Inside an overlay range, an unowned address is nobody's, not the
|
||||
@@ -270,7 +390,16 @@ impl RoutingTable {
|
||||
if !is_internet_destination(destination) || in_any_range(&networks, destination) {
|
||||
return None;
|
||||
}
|
||||
exit_via(&networks).map(|(network, peer)| Route { network, peer })
|
||||
let exit = self.selected_exit.load_full()?;
|
||||
// The host's default route may hand a forwarded packet back to the TUN.
|
||||
// Only this device can originate traffic for its own upstream. Replies
|
||||
// to a member above still route by destination with their internet source.
|
||||
if let Some(source) = source
|
||||
&& networks.get(&exit.route.network)?.local != Some(source)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((exit.route, Some(exit)))
|
||||
}
|
||||
|
||||
/// Whether a peer may send from a source address.
|
||||
@@ -298,11 +427,14 @@ impl RoutingTable {
|
||||
{
|
||||
return Some(PacketSource::Member);
|
||||
}
|
||||
(exit_via(&networks) == Some((network, peer))
|
||||
let current = self.selected_exit.load();
|
||||
let exit = current.as_ref()?;
|
||||
(exit.route == Route { network, peer }
|
||||
&& is_internet_destination(source)
|
||||
&& !in_any_range(&networks, source))
|
||||
.then_some(PacketSource::ExitReply {
|
||||
.then(|| PacketSource::ExitReply {
|
||||
local: routes.local,
|
||||
exit: Arc::clone(exit),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -326,7 +458,10 @@ impl RoutingTable {
|
||||
///
|
||||
/// Choosing another exit replaces the previous one under the table's write lock.
|
||||
pub fn exit_via(&self) -> Option<(NetworkId, EndpointId)> {
|
||||
exit_via(&self.read())
|
||||
self.selected_exit
|
||||
.load()
|
||||
.as_ref()
|
||||
.map(|exit| (exit.route.network, exit.route.peer))
|
||||
}
|
||||
|
||||
/// Whether a default route is selected and the local source valid in that network.
|
||||
@@ -527,6 +662,60 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_running_diagnostic_tracks_signed_ownership_across_route_changes() {
|
||||
let table = RoutingTable::new();
|
||||
let id = network("diagnostic");
|
||||
let other = network("other");
|
||||
table.set_network(id, routes()).unwrap();
|
||||
let bound = table.diagnostic_peer(id, peer(2)).unwrap();
|
||||
assert_eq!((bound.local, bound.remote), (addr(1), addr(2)));
|
||||
assert!(bound.is_current(&table));
|
||||
assert!(table.diagnostic_peer(id, peer(9)).is_none());
|
||||
assert!(table.set_network(other, routes()).is_err());
|
||||
table.set_exit(
|
||||
id,
|
||||
ExitPolicy {
|
||||
offer: true,
|
||||
via: Some(peer(3)),
|
||||
},
|
||||
);
|
||||
assert!(bound.is_current(&table));
|
||||
|
||||
let mut changed = routes();
|
||||
changed.peers[1].0 = addr(9);
|
||||
table.update_allocations(id, changed.clone()).unwrap();
|
||||
assert!(bound.is_current(&table), "another member moved");
|
||||
changed.peers[0].0 = addr(7);
|
||||
table.update_allocations(id, changed).unwrap();
|
||||
assert!(
|
||||
!bound.is_current(&table),
|
||||
"the old peer address is no longer owned"
|
||||
);
|
||||
assert!(!bound.is_current(&table));
|
||||
let moved = table.diagnostic_peer(id, peer(2)).unwrap();
|
||||
assert!(moved.is_current(&table));
|
||||
table
|
||||
.update_allocations(
|
||||
id,
|
||||
NetworkRoutes {
|
||||
local: None,
|
||||
..routes()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!moved.is_current(&table));
|
||||
assert!(table.diagnostic_peer(id, peer(2)).is_none());
|
||||
table.update_allocations(id, routes()).unwrap();
|
||||
assert!(bound.is_current(&table));
|
||||
table.remove_network(id);
|
||||
table.set_network(other, routes()).unwrap();
|
||||
assert!(
|
||||
!bound.is_current(&table),
|
||||
"same member and IPs in a different network"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packet_goes_to_the_member_that_holds_its_destination() {
|
||||
let table = RoutingTable::new();
|
||||
@@ -800,6 +989,32 @@ mod tests {
|
||||
|
||||
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
|
||||
|
||||
#[test]
|
||||
fn tunnel_warming_follows_the_selected_membership_on_restore_switch_and_off() {
|
||||
let table = Arc::new(RoutingTable::new());
|
||||
let (tx, _rx) = tokio::sync::mpsc::channel(1);
|
||||
let context = crate::dataplane::PluginContext::new(tx, peer(1), None, &table);
|
||||
let (a, b) = (network("left"), network("right"));
|
||||
let exit = peer(2);
|
||||
table.set_network(a, with_exit(false, Some(exit))).unwrap();
|
||||
table.set_network(b, NetworkRoutes::default()).unwrap();
|
||||
assert_eq!(context.warm_peer(a), Some(exit));
|
||||
assert_eq!(context.warm_peer(b), None);
|
||||
let select = |via| ExitPolicy { offer: true, via };
|
||||
table.set_exit(b, select(Some(exit)));
|
||||
assert_eq!(context.warm_peer(a), None);
|
||||
assert_eq!(context.warm_peer(b), Some(exit));
|
||||
table.set_exit(b, select(None));
|
||||
assert_eq!(
|
||||
context.warm_peer(b),
|
||||
None,
|
||||
"offering an exit does not select one"
|
||||
);
|
||||
table.set_exit(a, select(Some(exit)));
|
||||
table.remove_network(a);
|
||||
assert_eq!(context.warm_peer(a), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() {
|
||||
let table = RoutingTable::new();
|
||||
|
||||
@@ -90,6 +90,23 @@ pub struct Announcement {
|
||||
pub hostname: String,
|
||||
/// Announced IP plugin capabilities. Opaque to the core.
|
||||
pub capabilities: Vec<PluginCapability>,
|
||||
/// Software release reported by this peer for display after authentication.
|
||||
/// Keep this trailer last: original v8 readers stop after the capabilities.
|
||||
#[serde(default, deserialize_with = "read_agent_version")]
|
||||
pub agent_version: Option<String>,
|
||||
}
|
||||
|
||||
fn read_agent_version<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
// A frame contains exactly one envelope. EOF here is a legacy announcement.
|
||||
// An unreadable display hint can also be discarded without losing the
|
||||
// hostname or capabilities. Borrow the frame until the label is bounded.
|
||||
let version = Option::<&str>::deserialize(d).ok().flatten().filter(|s| {
|
||||
!s.is_empty()
|
||||
&& s.len() <= crate::config::MAX_AGENT_VERSION_LEN
|
||||
&& s.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-'))
|
||||
});
|
||||
Ok(version.map(str::to_owned))
|
||||
}
|
||||
|
||||
/// Opens a data channel, sent by the initiator right after the membership
|
||||
@@ -395,3 +412,41 @@ pub fn kind(message: &ControlMessage) -> &'static str {
|
||||
ControlMessage::Bye { .. } => "bye",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn v8_announcements_interoperate_with_and_without_a_software_version() {
|
||||
// The original v8 frame ends with the capability list. Decode the
|
||||
// new frame using exactly those fields as an older receiver would.
|
||||
type OldFrame = ([u8; 32], u8, bool, bool, String, Vec<PluginCapability>);
|
||||
let old: OldFrame = ([7; 32], 1, true, false, "lab".into(), vec![]);
|
||||
let legacy = encode(&old).unwrap();
|
||||
assert!(decode::<Envelope>(&legacy[..legacy.len() - 1]).is_err());
|
||||
let read = |bytes: &[u8]| match decode::<Envelope>(bytes).unwrap().message {
|
||||
ControlMessage::Announce(a) => a,
|
||||
_ => panic!("expected announcement"),
|
||||
};
|
||||
let mut a = read(&legacy);
|
||||
assert_eq!(a.agent_version, None);
|
||||
a.agent_version = Some("2.1.0-rc.2+android".into());
|
||||
let wire = encode(&Envelope {
|
||||
network_id: old.0,
|
||||
message: ControlMessage::Announce(a.clone()),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(decode::<OldFrame>(&wire).unwrap(), old);
|
||||
assert_eq!(read(&wire), a);
|
||||
|
||||
for invalid in ["", "1.2.3\nforged", &"1".repeat(256)] {
|
||||
let mut wire = legacy.clone();
|
||||
wire.extend(encode(&Some(invalid)).unwrap());
|
||||
let a = read(&wire);
|
||||
assert_eq!(a.agent_version, None);
|
||||
assert_eq!(a.hostname, "lab");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
//! Window-scoped, local observations. Each reader owns just its current interval.
|
||||
//! The first branch on the packet path skips all monitor work when nobody is watching.
|
||||
use arc_swap::ArcSwap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{
|
||||
Arc, Mutex, Weak,
|
||||
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
NetworkId,
|
||||
config::{MAX_INTERVAL_FLOWS, MAX_TRAFFIC_READERS},
|
||||
iroh_types::EndpointId,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
/// How the local agent handled the observed traffic.
|
||||
pub enum Role {
|
||||
/// Ordinary authenticated overlay traffic.
|
||||
Mesh,
|
||||
/// Local internet traffic carried by the selected exit peer.
|
||||
ViaExit,
|
||||
/// Internet traffic forwarded for a remote exit client.
|
||||
ServeExit,
|
||||
/// Traffic translated or probed by the virtual service router.
|
||||
Vip,
|
||||
/// One accepted overlay broadcast copy.
|
||||
Broadcast,
|
||||
/// A sample from an admitted mesh throughput test.
|
||||
SpeedTest,
|
||||
/// Messages on an authenticated control session.
|
||||
Control,
|
||||
/// Opaque datagrams forwarded between other mesh members.
|
||||
Relay,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
/// Whether this role counts transport data rather than locally visible IP packets.
|
||||
pub fn transport(self) -> bool {
|
||||
matches!(self, Self::Control | Self::Relay)
|
||||
}
|
||||
}
|
||||
|
||||
/// Addresses on the side of this agent and on the side of its authenticated peer.
|
||||
/// For encrypted transit the two endpoint IDs are ordered, with TX from the first.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
pub struct FlowKey {
|
||||
/// Public network identity.
|
||||
pub network: [u8; 32],
|
||||
/// Authenticated peer, or first endpoint of an opaque relay pair.
|
||||
pub peer: [u8; 32],
|
||||
/// Local forwarding or transport role.
|
||||
pub role: Role,
|
||||
/// Admitted header metadata used for aggregation.
|
||||
pub flow: Flow,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
/// One bidirectional IP conversation, control session, or opaque relay pair.
|
||||
pub enum Flow {
|
||||
/// IPv4 endpoints from the agent-facing and peer-facing sides.
|
||||
Ip {
|
||||
/// Source when sending, destination when receiving.
|
||||
near: [u8; 4],
|
||||
/// Destination when sending, source when receiving.
|
||||
far: [u8; 4],
|
||||
/// IPv4 protocol number.
|
||||
protocol: u8,
|
||||
/// Transport header fields available in this packet.
|
||||
detail: IpDetail,
|
||||
},
|
||||
/// Aggregated authenticated control envelopes.
|
||||
Control,
|
||||
/// An end-to-end mesh envelope passing through this device.
|
||||
Relay {
|
||||
/// The second endpoint, ordered by public key.
|
||||
other: [u8; 32],
|
||||
/// Opaque plugin protocol tag carried by the relay header.
|
||||
wire_protocol: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
/// Transport fields read from an IPv4 header and its bounded prefix.
|
||||
pub enum IpDetail {
|
||||
/// TCP/UDP ports in near/far order.
|
||||
Ports(u16, u16),
|
||||
/// ICMP echo requests and replies for the address pair.
|
||||
Echo,
|
||||
/// Another ICMP type and code.
|
||||
Icmp(u8, u8),
|
||||
/// Noninitial fragment with no transport header.
|
||||
Fragment,
|
||||
/// Protocol has no recognised, readable transport prefix.
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum Direction {
|
||||
Tx,
|
||||
Rx,
|
||||
}
|
||||
|
||||
impl Flow {
|
||||
pub(crate) fn ip(packet: &[u8], dir: Direction) -> Option<Self> {
|
||||
let header = packet.get(..20)?;
|
||||
let offset = usize::from(header[0] & 15) * 4;
|
||||
let total = usize::from(u16::from_be_bytes([header[2], header[3]]));
|
||||
if header[0] >> 4 != 4 || offset < 20 {
|
||||
return None;
|
||||
}
|
||||
let body = packet.get(..total)?.get(offset..)?;
|
||||
let protocol = header[9];
|
||||
let a: [u8; 4] = header[12..16].try_into().ok()?;
|
||||
let b: [u8; 4] = header[16..20].try_into().ok()?;
|
||||
let (near, far) = match dir {
|
||||
Direction::Tx => (a, b),
|
||||
Direction::Rx => (b, a),
|
||||
};
|
||||
let detail = if (u16::from_be_bytes([header[6], header[7]]) & 0x1fff) != 0 {
|
||||
IpDetail::Fragment
|
||||
} else {
|
||||
match (protocol, body) {
|
||||
(6 | 17, [a, b, c, d, ..]) => {
|
||||
let (src, dst) = (u16::from_be_bytes([*a, *b]), u16::from_be_bytes([*c, *d]));
|
||||
match dir {
|
||||
Direction::Tx => IpDetail::Ports(src, dst),
|
||||
Direction::Rx => IpDetail::Ports(dst, src),
|
||||
}
|
||||
}
|
||||
(1, [0 | 8, 0, ..]) => IpDetail::Echo,
|
||||
(1, [kind, code, ..]) => IpDetail::Icmp(*kind, *code),
|
||||
_ => IpDetail::Other,
|
||||
}
|
||||
};
|
||||
Some(Self::Ip {
|
||||
near,
|
||||
far,
|
||||
protocol,
|
||||
detail,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
/// Counters added during one observation interval.
|
||||
pub struct FlowDelta {
|
||||
/// Stable bidirectional identity of this flow.
|
||||
pub key: FlowKey,
|
||||
/// Bytes sent in this interval.
|
||||
pub tx_bytes: u64,
|
||||
/// Bytes received in this interval.
|
||||
pub rx_bytes: u64,
|
||||
/// Packets or transport messages sent.
|
||||
pub tx_packets: u64,
|
||||
/// Packets or transport messages received.
|
||||
pub rx_packets: u64,
|
||||
/// Age of the most recent observation when the interval was drained.
|
||||
pub age_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Serialize, Deserialize)]
|
||||
/// An interval delta for one local subscriber.
|
||||
pub struct TrafficSnapshot {
|
||||
/// Flows observed since the previous drain.
|
||||
pub flows: Vec<FlowDelta>,
|
||||
/// Elapsed monotonic milliseconds since opening or the preceding drain.
|
||||
pub interval_ms: u64,
|
||||
/// Packets/messages that could not be counted during this interval.
|
||||
pub omitted: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Counts {
|
||||
tx: u64,
|
||||
rx: u64,
|
||||
ntx: u64,
|
||||
nrx: u64,
|
||||
last: Instant,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Bucket {
|
||||
// Concurrent writers can spill into a different lane, including the reverse
|
||||
// direction of the same flow. The window merges these after the drain.
|
||||
lanes: [Mutex<HashMap<FlowKey, Counts>>; 4],
|
||||
since: Mutex<Instant>,
|
||||
entries: AtomicUsize,
|
||||
omitted: AtomicU64,
|
||||
}
|
||||
|
||||
fn millis(d: Duration) -> u64 {
|
||||
u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
impl Bucket {
|
||||
fn add(&self, key: FlowKey, dir: Direction, len: u64, now: Instant) {
|
||||
for lane in &self.lanes {
|
||||
let Ok(mut flows) = lane.try_lock() else {
|
||||
continue;
|
||||
};
|
||||
let counts = match flows.entry(key) {
|
||||
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
|
||||
std::collections::hash_map::Entry::Vacant(e) => {
|
||||
if self.entries.fetch_add(1, Ordering::Relaxed) >= MAX_INTERVAL_FLOWS {
|
||||
self.entries.fetch_sub(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
e.insert(Counts {
|
||||
tx: 0,
|
||||
rx: 0,
|
||||
ntx: 0,
|
||||
nrx: 0,
|
||||
last: now,
|
||||
})
|
||||
}
|
||||
};
|
||||
counts.last = counts.last.max(now);
|
||||
let (bytes, packets) = match dir {
|
||||
Direction::Tx => (&mut counts.tx, &mut counts.ntx),
|
||||
Direction::Rx => (&mut counts.rx, &mut counts.nrx),
|
||||
};
|
||||
*bytes = bytes.saturating_add(len);
|
||||
*packets = packets.saturating_add(1);
|
||||
return;
|
||||
}
|
||||
self.omitted.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(crate) struct TrafficMonitor {
|
||||
active: AtomicBool,
|
||||
readers: ArcSwap<Vec<Weak<Bucket>>>,
|
||||
// Only registration/unregistration use this lock.
|
||||
registration: Mutex<()>,
|
||||
}
|
||||
|
||||
impl TrafficMonitor {
|
||||
pub(crate) fn subscribe(self: &Arc<Self>) -> Result<TrafficSubscription, String> {
|
||||
let _edit = self.registration.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut readers = (**self.readers.load()).clone();
|
||||
if readers.len() >= MAX_TRAFFIC_READERS {
|
||||
return Err("Too many traffic monitor windows are open".into());
|
||||
}
|
||||
let bucket = Arc::new(Bucket {
|
||||
lanes: Default::default(),
|
||||
since: Mutex::new(Instant::now()),
|
||||
entries: AtomicUsize::new(0),
|
||||
omitted: AtomicU64::new(0),
|
||||
});
|
||||
readers.push(Arc::downgrade(&bucket));
|
||||
self.readers.store(Arc::new(readers));
|
||||
self.active.store(true, Ordering::Release);
|
||||
Ok(TrafficSubscription {
|
||||
owner: Arc::downgrade(self),
|
||||
bucket,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(
|
||||
&self,
|
||||
make: impl FnOnce() -> Option<(FlowKey, Direction, u64)>,
|
||||
) -> Observation {
|
||||
if !self.active.load(Ordering::Acquire) {
|
||||
return Observation(None);
|
||||
}
|
||||
let readers = self.readers.load_full();
|
||||
Observation(make().map(|(key, dir, len)| Pending {
|
||||
readers,
|
||||
key,
|
||||
dir,
|
||||
len,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn packet(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
dir: Direction,
|
||||
packet: &[u8],
|
||||
role: impl FnOnce() -> Role,
|
||||
) -> Observation {
|
||||
self.prepare(|| {
|
||||
Some((
|
||||
FlowKey {
|
||||
network: *network.as_bytes(),
|
||||
peer: *peer.as_bytes(),
|
||||
role: role(),
|
||||
flow: Flow::ip(packet, dir)?,
|
||||
},
|
||||
dir,
|
||||
packet.len() as u64,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn control(&self, network: NetworkId, peer: EndpointId, dir: Direction, len: u64) {
|
||||
self.prepare(|| {
|
||||
Some((
|
||||
FlowKey {
|
||||
network: *network.as_bytes(),
|
||||
peer: *peer.as_bytes(),
|
||||
role: Role::Control,
|
||||
flow: Flow::Control,
|
||||
},
|
||||
dir,
|
||||
len,
|
||||
))
|
||||
})
|
||||
.record();
|
||||
}
|
||||
|
||||
pub(crate) fn relay(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
source: [u8; 32],
|
||||
dest: [u8; 32],
|
||||
wire_protocol: u64,
|
||||
len: usize,
|
||||
) {
|
||||
self.prepare(|| {
|
||||
let (peer, other, dir) = if source <= dest {
|
||||
(source, dest, Direction::Tx)
|
||||
} else {
|
||||
(dest, source, Direction::Rx)
|
||||
};
|
||||
Some((
|
||||
FlowKey {
|
||||
network: *network.as_bytes(),
|
||||
peer,
|
||||
role: Role::Relay,
|
||||
flow: Flow::Relay {
|
||||
other,
|
||||
wire_protocol,
|
||||
},
|
||||
},
|
||||
dir,
|
||||
len as u64,
|
||||
))
|
||||
})
|
||||
.record();
|
||||
}
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
readers: Arc<Vec<Weak<Bucket>>>,
|
||||
key: FlowKey,
|
||||
dir: Direction,
|
||||
len: u64,
|
||||
}
|
||||
pub(crate) struct Observation(Option<Pending>);
|
||||
impl Pending {
|
||||
fn count(&self, len: u64) {
|
||||
let now = Instant::now();
|
||||
for reader in self.readers.iter().filter_map(Weak::upgrade) {
|
||||
reader.add(self.key, self.dir, len, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Observation {
|
||||
pub(crate) fn record(self) {
|
||||
if let Some(pending) = self.0 {
|
||||
pending.count(pending.len);
|
||||
}
|
||||
}
|
||||
pub(crate) fn record_fragment(&self, len: usize) {
|
||||
if let Some(pending) = &self.0 {
|
||||
pending.count(len as u64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the reader and turns off observation when the last window disconnects.
|
||||
#[derive(Debug)]
|
||||
pub struct TrafficSubscription {
|
||||
owner: Weak<TrafficMonitor>,
|
||||
bucket: Arc<Bucket>,
|
||||
}
|
||||
|
||||
impl TrafficSubscription {
|
||||
/// Atomically start a fresh interval; serialisation never holds the collector lock.
|
||||
pub fn snapshot(&self) -> TrafficSnapshot {
|
||||
let (now, previous, lanes, omitted) = {
|
||||
let mut since = self.bucket.since.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let locks = self
|
||||
.bucket
|
||||
.lanes
|
||||
.each_ref()
|
||||
.map(|lane| lane.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let now = Instant::now();
|
||||
self.bucket.entries.store(0, Ordering::Relaxed);
|
||||
let lanes = locks.map(|mut lock| std::mem::take(&mut *lock));
|
||||
(
|
||||
now,
|
||||
std::mem::replace(&mut *since, now),
|
||||
lanes,
|
||||
self.bucket.omitted.swap(0, Ordering::Relaxed),
|
||||
)
|
||||
};
|
||||
let [mut flows, second, third, fourth] = lanes;
|
||||
for (key, c) in [second, third, fourth].into_iter().flatten() {
|
||||
flows
|
||||
.entry(key)
|
||||
.and_modify(|a| {
|
||||
a.tx = a.tx.saturating_add(c.tx);
|
||||
a.rx = a.rx.saturating_add(c.rx);
|
||||
a.ntx = a.ntx.saturating_add(c.ntx);
|
||||
a.nrx = a.nrx.saturating_add(c.nrx);
|
||||
a.last = a.last.max(c.last)
|
||||
})
|
||||
.or_insert(c);
|
||||
}
|
||||
TrafficSnapshot {
|
||||
interval_ms: millis(now.saturating_duration_since(previous)),
|
||||
omitted,
|
||||
flows: flows
|
||||
.into_iter()
|
||||
.map(|(key, c)| FlowDelta {
|
||||
key,
|
||||
tx_bytes: c.tx,
|
||||
rx_bytes: c.rx,
|
||||
tx_packets: c.ntx,
|
||||
rx_packets: c.nrx,
|
||||
age_ms: millis(now.saturating_duration_since(c.last)),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TrafficSubscription {
|
||||
fn drop(&mut self) {
|
||||
if let Some(monitor) = self.owner.upgrade() {
|
||||
let _edit = monitor
|
||||
.registration
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let bucket = Arc::downgrade(&self.bucket);
|
||||
let remaining: Vec<_> = monitor
|
||||
.readers
|
||||
.load()
|
||||
.iter()
|
||||
.filter(|r| !Weak::ptr_eq(r, &bucket))
|
||||
.cloned()
|
||||
.collect();
|
||||
let active = !remaining.is_empty();
|
||||
monitor.readers.store(Arc::new(remaining));
|
||||
monitor.active.store(active, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,147 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
|
||||
fn ip(proto: u8, reply: bool) -> Vec<u8> {
|
||||
let mut p = vec![0; 32];
|
||||
p[0] = 0x45;
|
||||
p[2..4].copy_from_slice(&32u16.to_be_bytes());
|
||||
p[9] = proto;
|
||||
let (a, b, x, y) = if reply {
|
||||
(2, 1, 443u16, 49152u16)
|
||||
} else {
|
||||
(1, 2, 49152, 443)
|
||||
};
|
||||
p[12..16].copy_from_slice(&[10, 0, 0, a]);
|
||||
p[16..20].copy_from_slice(&[10, 0, 0, b]);
|
||||
p[20..22].copy_from_slice(&x.to_be_bytes());
|
||||
p[22..24].copy_from_slice(&y.to_be_bytes());
|
||||
if proto == 1 {
|
||||
p[20] = if reply { 0 } else { 8 };
|
||||
p[21] = 0;
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dormant_monitor_and_independent_window_lifetimes() {
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let submit = || {
|
||||
monitor
|
||||
.prepare(|| Some((control(), Direction::Tx, 100)))
|
||||
.record()
|
||||
};
|
||||
fn control() -> FlowKey {
|
||||
FlowKey {
|
||||
network: [1; 32],
|
||||
peer: [2; 32],
|
||||
role: Role::Control,
|
||||
flow: Flow::Control,
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
monitor
|
||||
.prepare(|| panic!("observer ran while closed"))
|
||||
.0
|
||||
.is_none()
|
||||
);
|
||||
let a = monitor.subscribe().unwrap();
|
||||
assert!(a.snapshot().flows.is_empty());
|
||||
submit();
|
||||
let pending = monitor.prepare(|| Some((control(), Direction::Rx, 50)));
|
||||
let b = monitor.subscribe().unwrap();
|
||||
pending.record();
|
||||
submit();
|
||||
let a_sample = a.snapshot();
|
||||
assert_eq!(a_sample.flows[0].tx_bytes, 200);
|
||||
assert_eq!(a_sample.flows[0].rx_bytes, 50);
|
||||
assert_eq!(b.snapshot().flows[0].tx_bytes, 100);
|
||||
assert!(a.snapshot().flows.is_empty());
|
||||
drop((a, b));
|
||||
assert!(
|
||||
monitor
|
||||
.prepare(|| panic!("observer left active"))
|
||||
.0
|
||||
.is_none()
|
||||
);
|
||||
assert!(monitor.subscribe().unwrap().snapshot().flows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tuple_and_echo_replies_have_the_same_key_and_fragments_never_invent_ports() {
|
||||
for protocol in [6, 17, 1] {
|
||||
let key = Flow::ip(&ip(protocol, false), Direction::Tx).unwrap();
|
||||
assert_eq!(Some(key), Flow::ip(&ip(protocol, true), Direction::Rx));
|
||||
}
|
||||
let mut packet = ip(17, false);
|
||||
packet[7] = 1;
|
||||
assert!(matches!(
|
||||
Flow::ip(&packet, Direction::Tx),
|
||||
Some(Flow::Ip {
|
||||
detail: IpDetail::Fragment,
|
||||
..
|
||||
})
|
||||
));
|
||||
packet[0] = 0x4f;
|
||||
assert!(Flow::ip(&packet, Direction::Tx).is_none());
|
||||
assert!(Flow::ip(&[], Direction::Rx).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_interval_reports_overflow_and_preserves_known_counters() {
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let sub = monitor.subscribe().unwrap();
|
||||
for i in 0..=MAX_INTERVAL_FLOWS {
|
||||
let mut peer = [0; 32];
|
||||
peer[..8].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
monitor
|
||||
.prepare(|| {
|
||||
Some((
|
||||
FlowKey {
|
||||
network: [0; 32],
|
||||
peer,
|
||||
role: Role::Control,
|
||||
flow: Flow::Control,
|
||||
},
|
||||
Direction::Tx,
|
||||
20,
|
||||
))
|
||||
})
|
||||
.record();
|
||||
}
|
||||
let sample = sub.snapshot();
|
||||
assert_eq!(sample.flows.len(), MAX_INTERVAL_FLOWS);
|
||||
assert_eq!(sample.omitted, 1);
|
||||
assert!(postcard::to_stdvec(&sample).unwrap().len() < (1 << 20));
|
||||
assert_eq!(sub.snapshot().omitted, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_writers_share_the_flow_without_waiting_and_closed_windows_release_inflight_buffers() {
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let sub = monitor.subscribe().unwrap();
|
||||
let key = FlowKey {
|
||||
network: [1; 32],
|
||||
peer: [2; 32],
|
||||
role: Role::Control,
|
||||
flow: Flow::Control,
|
||||
};
|
||||
monitor.prepare(|| Some((key, Direction::Tx, 20))).record();
|
||||
let held = sub.bucket.lanes[0].lock().unwrap();
|
||||
monitor.prepare(|| Some((key, Direction::Rx, 30))).record();
|
||||
drop(held);
|
||||
let result = sub.snapshot();
|
||||
assert_eq!(result.flows.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
result.flows[0].tx_bytes,
|
||||
result.flows[0].rx_bytes,
|
||||
result.omitted
|
||||
),
|
||||
(20, 30, 0)
|
||||
);
|
||||
let pending = monitor.prepare(|| Some((key, Direction::Rx, 10)));
|
||||
let bucket = Arc::downgrade(&sub.bucket);
|
||||
drop(sub);
|
||||
assert!(bucket.upgrade().is_none());
|
||||
pending.record();
|
||||
}
|
||||
@@ -15,6 +15,8 @@ pub(crate) enum Decision {
|
||||
Pass,
|
||||
Send(Route, Bytes),
|
||||
Local(Bytes),
|
||||
Reassembled(Bytes),
|
||||
ProbeReceived,
|
||||
Drop,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
@@ -452,6 +454,69 @@ impl VipRouter {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Identify an outgoing VIP datagram on the client-facing side of NAT. Called
|
||||
/// once on the reassembled datagram; only accepted fragments contribute bytes.
|
||||
pub(crate) fn observe_outgoing(
|
||||
&self,
|
||||
monitor: &crate::traffic::TrafficMonitor,
|
||||
route: Option<Route>,
|
||||
bytes: &[u8],
|
||||
) -> crate::traffic::Observation {
|
||||
use crate::traffic::{Direction, Flow as ObservedFlow, FlowKey, IpDetail, Role};
|
||||
monitor.prepare(|| {
|
||||
let state = self.lock();
|
||||
let reverse = packet::tuple(bytes).map(Tuple::reverse);
|
||||
let (route, dir, client) = if let Some(route) = route {
|
||||
let original = reverse
|
||||
.and_then(|t| state.reverse.get(&(route.network, route.peer, t)))
|
||||
.copied();
|
||||
(route, Direction::Tx, original)
|
||||
} else {
|
||||
// A local backend both receives requests and returns replies through this TUN.
|
||||
let source = packet::addresses(bytes)?.0;
|
||||
state.networks.iter().find_map(|(id, n)| {
|
||||
let route = Route {
|
||||
network: *id,
|
||||
peer: n.local,
|
||||
};
|
||||
if let Some(t) = reverse.and_then(|t| state.reverse.get(&(*id, n.local, t))) {
|
||||
return Some((route, Direction::Tx, Some(*t)));
|
||||
}
|
||||
let reply = reverse
|
||||
.and_then(|t| state.flows.get(&t))
|
||||
.is_some_and(|f| f.local && f.key.network == *id);
|
||||
(reply || n.vips.iter().any(|v| v.address == Some(source))).then_some((
|
||||
route,
|
||||
Direction::Rx,
|
||||
None,
|
||||
))
|
||||
})?
|
||||
};
|
||||
let flow = match client {
|
||||
Some(t) => ObservedFlow::Ip {
|
||||
near: t.src.octets(),
|
||||
far: t.dst.octets(),
|
||||
protocol: match t.protocol {
|
||||
Protocol::Tcp => 6,
|
||||
Protocol::Udp => 17,
|
||||
},
|
||||
detail: IpDetail::Ports(t.sport, t.dport),
|
||||
},
|
||||
None => ObservedFlow::ip(bytes, dir)?,
|
||||
};
|
||||
Some((
|
||||
FlowKey {
|
||||
network: *route.network.as_bytes(),
|
||||
peer: *route.peer.as_bytes(),
|
||||
role: Role::Vip,
|
||||
flow,
|
||||
},
|
||||
dir,
|
||||
bytes.len() as u64,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn outgoing(&self, packet: Bytes) -> Decision {
|
||||
let mut s = self.lock();
|
||||
let Some((src, dst)) = packet::addresses(&packet) else {
|
||||
@@ -716,6 +781,7 @@ impl VipRouter {
|
||||
p.heard = Some(Instant::now());
|
||||
p.pending = None;
|
||||
p.misses = 0;
|
||||
return Decision::ProbeReceived;
|
||||
}
|
||||
return Decision::Drop;
|
||||
}
|
||||
@@ -763,7 +829,7 @@ impl VipRouter {
|
||||
return packet::rewrite_icmp(&packet, original).map_or(Decision::Drop, Decision::Local);
|
||||
}
|
||||
if was_fragmented {
|
||||
Decision::Local(packet)
|
||||
Decision::Reassembled(packet)
|
||||
} else {
|
||||
Decision::Pass
|
||||
}
|
||||
@@ -1021,6 +1087,9 @@ mod tests {
|
||||
};
|
||||
assert_eq!(route.peer, a);
|
||||
let wire = packet::tuple(&out).unwrap();
|
||||
let monitor = std::sync::Arc::new(crate::traffic::TrafficMonitor::default());
|
||||
let capture = monitor.subscribe().unwrap();
|
||||
r.observe_outgoing(&monitor, Some(route), &out).record();
|
||||
assert_eq!(wire.dport, 6443);
|
||||
assert_ne!(wire.sport, t.sport);
|
||||
let reply = packet(wire.reverse(), 0x12);
|
||||
@@ -1028,6 +1097,17 @@ mod tests {
|
||||
panic!("reverse NAT expected")
|
||||
};
|
||||
assert_eq!(packet::tuple(&reply), Some(t.reverse()));
|
||||
monitor
|
||||
.packet(n, a, crate::traffic::Direction::Rx, &reply, || {
|
||||
crate::traffic::Role::Vip
|
||||
})
|
||||
.record();
|
||||
let sample = capture.snapshot();
|
||||
assert_eq!(sample.flows.len(), 1);
|
||||
assert_eq!(
|
||||
(sample.flows[0].tx_packets, sample.flows[0].rx_packets),
|
||||
(1, 1)
|
||||
);
|
||||
assert_eq!(packet::checksum(&reply[..20]), 0);
|
||||
{
|
||||
r.lock().networks.get_mut(&n).unwrap().vips.clear();
|
||||
@@ -1073,6 +1153,9 @@ mod tests {
|
||||
let Decision::Local(out) = r.outgoing(packet(t, 0)) else {
|
||||
panic!("local delivery expected")
|
||||
};
|
||||
let monitor = std::sync::Arc::new(crate::traffic::TrafficMonitor::default());
|
||||
let capture = monitor.subscribe().unwrap();
|
||||
r.observe_outgoing(&monitor, None, &out).record();
|
||||
let wire = packet::tuple(&out).unwrap();
|
||||
assert_eq!(wire.src, t.dst);
|
||||
assert_eq!(wire.dst, t.src);
|
||||
@@ -1080,6 +1163,13 @@ mod tests {
|
||||
let Decision::Local(reply) = r.outgoing(packet(wire.reverse(), 0)) else {
|
||||
panic!("local reverse NAT expected")
|
||||
};
|
||||
r.observe_outgoing(&monitor, None, &reply).record();
|
||||
let sample = capture.snapshot();
|
||||
assert_eq!(sample.flows.len(), 1);
|
||||
assert_eq!(
|
||||
(sample.flows[0].tx_packets, sample.flows[0].rx_packets),
|
||||
(1, 1)
|
||||
);
|
||||
assert_eq!(packet::tuple(&reply), Some(t.reverse()));
|
||||
}
|
||||
#[tokio::test]
|
||||
|
||||
@@ -47,6 +47,79 @@ async fn open_control_stream(
|
||||
|
||||
const LIMIT: usize = 64 * 1024;
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_authenticated_disconnect_reports_the_quic_close_code() {
|
||||
let agent = TestAgent::spawn(&SharedMemoryDiscovery::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let (name, secret) = network("disconnect-diagnostics");
|
||||
let id = agent.agent.join_network(&name, &secret).await.unwrap();
|
||||
let member = raw_endpoint().await;
|
||||
let (conn, mut send, mut recv) = open_control_stream(&member, agent.agent.local_addr()).await;
|
||||
let mut events = agent.agent.subscribe();
|
||||
tsunagi::proto::handshake::initiate(
|
||||
&conn,
|
||||
&mut send,
|
||||
&mut recv,
|
||||
member.id(),
|
||||
&NetworkKeys::derive(&name, &secret),
|
||||
&tsunagi::Limits::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let message = ControlMessage::Announce(tsunagi::proto::message::Announcement {
|
||||
broadcast: true,
|
||||
exit_node: false,
|
||||
hostname: "returning-peer".into(),
|
||||
capabilities: Vec::new(),
|
||||
agent_version: None,
|
||||
});
|
||||
write_frame(
|
||||
&mut send,
|
||||
&encode(&Envelope {
|
||||
network_id: *id.as_bytes(),
|
||||
message,
|
||||
})
|
||||
.unwrap(),
|
||||
LIMIT,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
tsunagi::testing::wait_until("peer hostname is known", || async {
|
||||
agent
|
||||
.agent
|
||||
.network_status(id)
|
||||
.await
|
||||
.ok()?
|
||||
.peers
|
||||
.into_iter()
|
||||
.find(|p| {
|
||||
p.endpoint_id == member.id() && p.hostname.as_deref() == Some("returning-peer")
|
||||
})
|
||||
})
|
||||
.await;
|
||||
conn.close(42u32.into(), b"private remote text\nsecond line");
|
||||
let (reported_network, hostname, reason) = wait_event(&mut events, |event| match event {
|
||||
Event::PeerDisconnected {
|
||||
network,
|
||||
network_name,
|
||||
peer,
|
||||
hostname,
|
||||
reason,
|
||||
} if *network == id && *peer == member.id() => {
|
||||
Some((network_name.clone(), hostname.clone(), reason.clone()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(reported_network, name);
|
||||
assert_eq!(hostname.as_deref(), Some("returning-peer"));
|
||||
assert!(reason.contains("application code 42"), "{reason}");
|
||||
assert!(!reason.contains("private remote text"));
|
||||
member.close().await;
|
||||
agent.agent.shutdown().await;
|
||||
}
|
||||
|
||||
/// Sends `Hello` and reads the responder's `HelloAck`.
|
||||
async fn exchange_hellos(
|
||||
send: &mut SendStream,
|
||||
|
||||
@@ -148,13 +148,21 @@ async fn being_told_about_one_member_is_enough_to_meet_them_all() {
|
||||
|
||||
// Three that already know each other, and nothing that resolves by
|
||||
// network: no shared discovery here, only what members pass on.
|
||||
// A single introduction fits each frame, including when three members
|
||||
// already know the same bootstrap. No peer may get stuck behind the first.
|
||||
let small_frames = |dir: &std::path::Path| {
|
||||
let mut config = local_config(dir);
|
||||
config.limits.max_state_records = 1;
|
||||
config.limits.session_send_queue = 2;
|
||||
config
|
||||
};
|
||||
let first_dir = tempfile::TempDir::new().unwrap();
|
||||
let first = Agent::spawn(local_config(first_dir.path())).await.unwrap();
|
||||
let first = Agent::spawn(small_frames(first_dir.path())).await.unwrap();
|
||||
let network_id = first.join_network(&name, &secret).await.unwrap();
|
||||
|
||||
let second_dir = tempfile::TempDir::new().unwrap();
|
||||
let second = Agent::spawn(
|
||||
local_config(second_dir.path())
|
||||
small_frames(second_dir.path())
|
||||
.with_discovery(Arc::new(StaticBootstrap::new([first.local_addr()]))),
|
||||
)
|
||||
.await
|
||||
@@ -164,7 +172,7 @@ async fn being_told_about_one_member_is_enough_to_meet_them_all() {
|
||||
|
||||
let third_dir = tempfile::TempDir::new().unwrap();
|
||||
let third = Agent::spawn(
|
||||
local_config(third_dir.path())
|
||||
small_frames(third_dir.path())
|
||||
.with_discovery(Arc::new(StaticBootstrap::new([first.local_addr()]))),
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -43,15 +43,19 @@ async fn four_agents_form_a_mesh_and_exchange_distinguishable_messages() {
|
||||
// A peer counts as connected as soon as its session is authenticated, which
|
||||
// can be a round before its announcement carrying the hostname arrives, so
|
||||
// this waits for the hostnames rather than reading them straight away.
|
||||
let hostnames: HashSet<String> = wait_until("three distinct peer hostnames", || async {
|
||||
let status = agents[0].agent.network_status(network_id).await.ok()?;
|
||||
let hostnames: HashSet<String> = status
|
||||
.peers
|
||||
.iter()
|
||||
.filter_map(|peer| peer.hostname.clone())
|
||||
.collect();
|
||||
(hostnames.len() >= 3).then_some(hostnames)
|
||||
})
|
||||
let hostnames: HashSet<String> = wait_until(
|
||||
"three peers announce their hostname and release",
|
||||
|| async {
|
||||
let status = agents[0].agent.network_status(network_id).await.ok()?;
|
||||
let hostnames: HashSet<String> = status
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|peer| peer.agent_version.as_deref() == Some(env!("CARGO_PKG_VERSION")))
|
||||
.filter_map(|peer| peer.hostname.clone())
|
||||
.collect();
|
||||
(hostnames.len() >= 3).then_some(hostnames)
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
hostnames.len(),
|
||||
|
||||
@@ -16,6 +16,97 @@ async fn view(agent: &Agent, network: NetworkId, id: &str) -> VipStatus {
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_local_storage_failure_is_repaired_from_the_peer_after_reconnect() {
|
||||
use tsunagi::{StoragePaths, agent::Event, testing::wait_event};
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let a = TestAgent::spawn(&discovery).await.unwrap();
|
||||
let b = TestAgent::spawn(&discovery).await.unwrap();
|
||||
let (name, secret) = network("retry-signed-update");
|
||||
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||
b.agent.join_network(&name, &secret).await.unwrap();
|
||||
wait_for_peers(&a.agent, id, 1).await;
|
||||
let path = StoragePaths::under(b.dir.path()).state_db();
|
||||
let trigger = |sql: &'static str| {
|
||||
let path = path.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
rusqlite::Connection::open(path)
|
||||
.unwrap()
|
||||
.execute_batch(sql)
|
||||
.unwrap()
|
||||
})
|
||||
};
|
||||
trigger("CREATE TRIGGER reject_vip BEFORE INSERT ON vip_fields BEGIN SELECT RAISE(ABORT, 'test write failure'); END;").await.unwrap();
|
||||
let mut events = b.agent.subscribe();
|
||||
let vip = VipConfig::new("recover");
|
||||
a.agent
|
||||
.save_vip(id, vip.clone(), None, false)
|
||||
.await
|
||||
.unwrap();
|
||||
wait_event(&mut events, |e| matches!(e, Event::PluginError { protocol, reason, .. } if protocol == "state" && reason.contains("test write failure")).then_some(())).await;
|
||||
trigger("DROP TRIGGER reject_vip").await.unwrap();
|
||||
assert_eq!(view(&b.agent, id, &vip.id).await.config, vip);
|
||||
a.stop().await;
|
||||
b.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn idle_maintenance_does_not_republish_acknowledged_mesh_state() {
|
||||
use tsunagi::{agent::Event, proto::ControlMessage};
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let a = TestAgent::spawn(&discovery).await.unwrap();
|
||||
let b = TestAgent::spawn(&discovery).await.unwrap();
|
||||
let (name, secret) = network("quiet-mesh");
|
||||
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||
b.agent.join_network(&name, &secret).await.unwrap();
|
||||
wait_for_peers(&a.agent, id, 1).await;
|
||||
let vip = VipConfig::new("web");
|
||||
a.agent
|
||||
.save_vip(id, vip.clone(), None, false)
|
||||
.await
|
||||
.unwrap();
|
||||
view(&b.agent, id, &vip.id).await;
|
||||
let mut events = b.agent.subscribe();
|
||||
// Mark the end of each round on the same ordered control stream.
|
||||
let last_hints = std::cell::RefCell::new(None);
|
||||
for round in 0..4 {
|
||||
a.agent.recheck_network(id).await.unwrap();
|
||||
a.agent
|
||||
.send(
|
||||
id,
|
||||
b.agent.endpoint_id(),
|
||||
ControlMessage::Ping {
|
||||
seq: round,
|
||||
payload: vec![],
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
tsunagi::testing::wait_event(&mut events, |event| {
|
||||
if let Event::MessageReceived { message, .. } = event {
|
||||
match message {
|
||||
ControlMessage::Ping { seq, .. } if *seq == round => return Some(()),
|
||||
ControlMessage::Vips { .. } | ControlMessage::Reachable { .. } if round > 0 => {
|
||||
panic!("republished unchanged state on maintenance round {round}")
|
||||
}
|
||||
ControlMessage::Peers { peers } => {
|
||||
assert_ne!(
|
||||
last_hints.replace(Some(peers.clone())).as_ref(),
|
||||
Some(peers),
|
||||
"unchanged introductions"
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await;
|
||||
}
|
||||
a.stop().await;
|
||||
b.stop().await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn any_member_can_edit_services_and_an_offline_creator_is_not_required() {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
description = "Built-in mesh transports and status reporting for native tsunagi agents."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -8,11 +8,11 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.2" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.2" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.2" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.2" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.8" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.8" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.8" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.8" }
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ pub fn networks(
|
||||
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())),
|
||||
idle: tunnel.is_some_and(|t| t.health.idle),
|
||||
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),
|
||||
@@ -86,6 +87,7 @@ pub fn networks(
|
||||
};
|
||||
|
||||
NetworkReport {
|
||||
speed: network.speed.clone(),
|
||||
vips: network.vips.clone(),
|
||||
protocols: network.protocols.clone(),
|
||||
auto_start: network.auto_start,
|
||||
@@ -102,6 +104,7 @@ pub fn networks(
|
||||
.peers
|
||||
.iter()
|
||||
.map(|peer| PeerReport {
|
||||
agent_version: peer.agent_version.clone(),
|
||||
data_error: peer.data_error.clone(),
|
||||
endpoint_id: peer.endpoint_id.to_string(),
|
||||
hostname: peer.hostname.clone(),
|
||||
@@ -193,6 +196,7 @@ fn exit_report(network: &tsunagi::agent::NetworkStatus) -> tsunagi::ipc::ExitRep
|
||||
})
|
||||
};
|
||||
tsunagi::ipc::ExitReport {
|
||||
traffic: network.exit_traffic,
|
||||
offering: network.exit_offer,
|
||||
offer_rules: rules(&network.exit_rules.offer),
|
||||
forwarding: network.exit_rules.forwarding,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "tsunagi-speedtest"
|
||||
version = "0.1.0"
|
||||
description = "Bounded, adaptive goodput measurements over an authenticated mesh tunnel"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bytes.workspace = true
|
||||
postcard.workspace = true
|
||||
serde.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,477 @@
|
||||
use crate::measurement::{Pacer, Receiver, Search};
|
||||
use crate::packet::{MAX_MTU, MIN_MTU, PacketBuilder};
|
||||
use crate::{
|
||||
Control, Datagram, Direction, Feedback, NORMAL_BYTES, Progress, Quality, Reading, Start, State,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use std::future::Future;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until, timeout_at};
|
||||
|
||||
const TOTAL_TIME: Duration = Duration::from_secs(5);
|
||||
const DIRECTION_TIME: Duration = Duration::from_millis(1900);
|
||||
const FEEDBACK_TICK: Duration = Duration::from_millis(25);
|
||||
const PACE_TICK: Duration = Duration::from_millis(1);
|
||||
|
||||
/// Parameters for one locally admitted, authenticated peer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Config {
|
||||
/// Fresh random identifier for the exchange. A responder uses the identifier from the request.
|
||||
pub id: u64,
|
||||
/// Local overlay IPv4 address on this network.
|
||||
pub local: Ipv4Addr,
|
||||
/// Authenticated peer's overlay address on this network.
|
||||
pub remote: Ipv4Addr,
|
||||
/// Maximum complete diagnostic datagram size supported by this route.
|
||||
pub mtu: u16,
|
||||
/// Local policy's maximum diagnostic IPv4 bytes in each direction.
|
||||
pub byte_limit: u32,
|
||||
/// Recent peer RTT, used to select the feedback interval and bound the final drain.
|
||||
pub rtt: Duration,
|
||||
}
|
||||
|
||||
/// Delivery for exactly one network and peer. The host uses its usual network
|
||||
/// authentication for control and its ordinary encrypted packet path for probes.
|
||||
pub trait Io: Send + Sync {
|
||||
/// Enqueue or send one reliable authenticated control record.
|
||||
fn control(&self, message: Control) -> impl Future<Output = bool> + Send;
|
||||
/// Attempt to send one packet without blocking the tunnel or buffering unbounded data.
|
||||
fn packet(&self, packet: Bytes) -> bool;
|
||||
/// Publish a live observation or terminal state.
|
||||
fn progress(&self, update: Progress);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Ingress(Mutex<Option<Receiver>>);
|
||||
|
||||
impl Ingress {
|
||||
fn with<T>(&self, f: impl FnOnce(&mut Option<Receiver>) -> T) -> T {
|
||||
let mut guard = self.0.lock().unwrap_or_else(|poison| poison.into_inner());
|
||||
f(&mut guard)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloneable, nonblocking ingress for a single test. Data is counted in place;
|
||||
/// it is never put on the reliable message queue.
|
||||
#[derive(Clone)]
|
||||
pub struct Handle {
|
||||
id: u64,
|
||||
local: Ipv4Addr,
|
||||
remote: Ipv4Addr,
|
||||
events: mpsc::Sender<Control>,
|
||||
cancel: watch::Sender<bool>,
|
||||
ingress: Arc<Ingress>,
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
/// Deliver an authenticated control record for an existing test.
|
||||
pub fn control(&self, message: Control) {
|
||||
if message.id() == self.id && message.valid() {
|
||||
if matches!(message, Control::Cancel { .. }) {
|
||||
self.cancel();
|
||||
} else {
|
||||
let _ = self.events.try_send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Count a validated probe from the bound peer in the current receiving direction.
|
||||
pub fn data(&self, packet: Datagram) {
|
||||
if packet.id == self.id && packet.source == self.remote && packet.destination == self.local
|
||||
{
|
||||
self.ingress.with(|rx| {
|
||||
if let Some(rx) = rx {
|
||||
rx.put(packet, Instant::now());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt local work, including outstanding control sends.
|
||||
pub fn cancel(&self) {
|
||||
self.cancel.send_replace(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// A single, bounded two-direction exchange. Nothing runs until the host calls `run`.
|
||||
pub struct Session {
|
||||
cfg: Config,
|
||||
request: Option<Start>,
|
||||
events: mpsc::Receiver<Control>,
|
||||
cancel: watch::Receiver<bool>,
|
||||
ingress: Arc<Ingress>,
|
||||
progress: Progress,
|
||||
}
|
||||
|
||||
/// Prepare an outgoing session. The test begins when its runner sends its Start record.
|
||||
pub fn initiate(config: Config) -> (Handle, Session) {
|
||||
new_session(config, None)
|
||||
}
|
||||
|
||||
/// Prepare the response to a verified Start. Local and requested traffic limits are intersected.
|
||||
pub fn respond(mut config: Config, request: Start) -> (Handle, Session) {
|
||||
config.id = request.id;
|
||||
new_session(config, Some(request))
|
||||
}
|
||||
|
||||
fn new_session(config: Config, request: Option<Start>) -> (Handle, Session) {
|
||||
let (tx, events) = mpsc::channel(32);
|
||||
let (cancel_tx, cancel) = watch::channel(false);
|
||||
let ingress = Arc::new(Ingress::default());
|
||||
let handle = Handle {
|
||||
id: config.id,
|
||||
local: config.local,
|
||||
remote: config.remote,
|
||||
events: tx,
|
||||
cancel: cancel_tx,
|
||||
ingress: ingress.clone(),
|
||||
};
|
||||
let session = Session {
|
||||
cfg: config,
|
||||
request,
|
||||
events,
|
||||
cancel,
|
||||
ingress,
|
||||
progress: Progress::default(),
|
||||
};
|
||||
(handle, session)
|
||||
}
|
||||
|
||||
fn open_control(control: Option<Control>) -> Result<Control, State> {
|
||||
match control {
|
||||
Some(Control::Busy { .. }) => Err(State::Busy),
|
||||
Some(Control::Cancel { .. }) => Err(State::Cancelled),
|
||||
Some(control) => Ok(control),
|
||||
None => Err(State::Cancelled),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(io: &impl Io, message: Control) -> Result<(), State> {
|
||||
if io.control(message).await {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(State::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run both directions under one five-second deadline and return the same final
|
||||
/// snapshot that is published to the host. Dropping the future stops packet generation.
|
||||
pub async fn run(mut self, io: impl Io) -> Progress {
|
||||
let deadline = Instant::now() + TOTAL_TIME;
|
||||
let mut cancellation = self.cancel.clone();
|
||||
io.progress(self.progress);
|
||||
let state = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.wait_for(|v| *v) => State::Cancelled,
|
||||
result = timeout_at(deadline, self.exchange(&io, deadline)) => {
|
||||
match result { Ok(Ok(())) => State::Complete, Ok(Err(state)) => state, Err(_) => State::TimedOut }
|
||||
}
|
||||
};
|
||||
self.ingress.with(|rx| *rx = None);
|
||||
self.progress.state = state;
|
||||
io.progress(self.progress);
|
||||
if matches!(state, State::Cancelled | State::Failed | State::TimedOut) {
|
||||
// A blocked control stream must never delay local release or shutdown.
|
||||
let _ = timeout_at(
|
||||
deadline.min(Instant::now() + Duration::from_millis(20)),
|
||||
io.control(Control::Cancel { id: self.cfg.id }),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
self.progress
|
||||
}
|
||||
|
||||
async fn exchange(&mut self, io: &impl Io, deadline: Instant) -> Result<(), State> {
|
||||
let id = self.cfg.id;
|
||||
self.cfg.byte_limit = self.cfg.byte_limit.min(NORMAL_BYTES);
|
||||
self.cfg.mtu = self.cfg.mtu.min(MAX_MTU);
|
||||
if self.cfg.mtu < MIN_MTU || self.cfg.byte_limit == 0 || self.cfg.local == self.cfg.remote {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
if let Some(start) = self.request {
|
||||
if !Control::Start(start).valid() {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
self.cfg.mtu = self.cfg.mtu.min(start.mtu);
|
||||
self.cfg.byte_limit = self.cfg.byte_limit.min(start.byte_limit);
|
||||
send(
|
||||
io,
|
||||
Control::Accepted {
|
||||
id,
|
||||
mtu: self.cfg.mtu,
|
||||
byte_limit: self.cfg.byte_limit,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
send(
|
||||
io,
|
||||
Control::Start(Start {
|
||||
id,
|
||||
mtu: self.cfg.mtu,
|
||||
byte_limit: self.cfg.byte_limit,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
if let Control::Accepted {
|
||||
mtu, byte_limit, ..
|
||||
} = open_control(self.events.recv().await)?
|
||||
{
|
||||
if mtu > self.cfg.mtu || byte_limit > self.cfg.byte_limit {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
self.cfg.mtu = mtu;
|
||||
self.cfg.byte_limit = byte_limit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for direction in [Direction::Download, Direction::Upload] {
|
||||
self.progress.state = match direction {
|
||||
Direction::Download => State::Download,
|
||||
Direction::Upload => State::Upload,
|
||||
};
|
||||
io.progress(self.progress);
|
||||
let sender = (direction == Direction::Download) == self.request.is_some();
|
||||
let result = if sender {
|
||||
self.send_probes(io, direction, deadline).await?
|
||||
} else {
|
||||
self.receive_probes(io, direction).await?
|
||||
};
|
||||
*self.progress.at(direction) = result;
|
||||
io.progress(self.progress);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_probes(
|
||||
&mut self,
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
deadline: Instant,
|
||||
) -> Result<Reading, State> {
|
||||
loop {
|
||||
if matches!(open_control(self.events.recv().await)?, Control::Ready { direction: d, .. } if d == direction)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
let start = Instant::now();
|
||||
// Leave room for the opposite direction and the final reliable report.
|
||||
let remaining = deadline
|
||||
.saturating_duration_since(start)
|
||||
.saturating_sub(Duration::from_millis(200));
|
||||
let phase = if direction == Direction::Download {
|
||||
remaining / 2
|
||||
} else {
|
||||
remaining
|
||||
};
|
||||
let end = start + phase.min(DIRECTION_TIME);
|
||||
let mut tick = interval_at(start + PACE_TICK, PACE_TICK);
|
||||
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let mut search = Search::default();
|
||||
let mut pacer = Pacer::new(start, self.cfg.mtu);
|
||||
let builder = PacketBuilder::new(
|
||||
self.cfg.local,
|
||||
self.cfg.remote,
|
||||
self.cfg.id,
|
||||
direction,
|
||||
self.cfg.mtu,
|
||||
);
|
||||
let limit = self.cfg.byte_limit / u32::from(self.cfg.mtu);
|
||||
let mut packets = 0;
|
||||
let mut last_bytes = 0;
|
||||
let mut last_feedback = start;
|
||||
let max_silence = (self
|
||||
.cfg
|
||||
.rtt
|
||||
.saturating_mul(3)
|
||||
.saturating_add(Duration::from_millis(200)))
|
||||
.clamp(Duration::from_millis(700), Duration::from_millis(950));
|
||||
while packets < limit && !search.done() && Instant::now() < end {
|
||||
tokio::select! {
|
||||
control = self.events.recv() => {
|
||||
if let Control::Feedback { direction: d, sample, .. } = open_control(control)?
|
||||
&& d == direction && sample.bytes >= last_bytes && sample.bytes <= self.cfg.byte_limit
|
||||
{
|
||||
if sample.bytes > last_bytes {
|
||||
last_feedback = Instant::now();
|
||||
last_bytes = sample.bytes;
|
||||
}
|
||||
if sample.bps > 0 {
|
||||
*self.progress.at(direction) = Reading { bps: Some(sample.bps), bytes: last_bytes, quality: Quality::Measuring };
|
||||
io.progress(self.progress);
|
||||
}
|
||||
search.observe(sample, start.elapsed().as_micros() as u32);
|
||||
}
|
||||
}
|
||||
_ = tick.tick() => {
|
||||
let now = Instant::now();
|
||||
let silence = if last_bytes == 0 { max_silence.max(Duration::from_millis(1100)) } else { max_silence };
|
||||
if now.duration_since(last_feedback) > silence {
|
||||
break;
|
||||
}
|
||||
let emit = pacer.packets(now, search.target).min(limit - packets);
|
||||
for index in 0..emit {
|
||||
if index > 0 && index.is_multiple_of(64) {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let elapsed_us = start.elapsed().as_micros() as u32;
|
||||
let packet = builder.packet(search.stage, packets, elapsed_us);
|
||||
// A tunnel waiting for a handshake can retain a submitted
|
||||
// packet. Charge that attempt, then release the unissued
|
||||
// part of this batch for a later tick if the tunnel is full.
|
||||
packets += 1;
|
||||
if !io.packet(packet) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
send(
|
||||
io,
|
||||
Control::End {
|
||||
id: self.cfg.id,
|
||||
direction,
|
||||
packets,
|
||||
reading: search.result(last_bytes),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
if let Control::Report {
|
||||
direction: d,
|
||||
reading,
|
||||
..
|
||||
} = open_control(self.events.recv().await)?
|
||||
&& d == direction
|
||||
{
|
||||
if reading.bytes > packets * u32::from(self.cfg.mtu - crate::packet::HEADER) {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
return Ok(reading);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn receive_probes(
|
||||
&mut self,
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
) -> Result<Reading, State> {
|
||||
let id = self.cfg.id;
|
||||
self.ingress
|
||||
.with(|rx| *rx = Some(Receiver::new(direction, self.cfg.mtu, self.cfg.byte_limit)));
|
||||
send(io, Control::Ready { id, direction }).await?;
|
||||
let mut tick = interval_at(Instant::now() + FEEDBACK_TICK, FEEDBACK_TICK);
|
||||
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let window = self
|
||||
.cfg
|
||||
.rtt
|
||||
.clamp(Duration::from_millis(100), Duration::from_millis(220));
|
||||
let (packets, estimate) = loop {
|
||||
tokio::select! {
|
||||
control = self.events.recv() => {
|
||||
if let Control::End { direction: d, packets, reading, .. } = open_control(control)?
|
||||
&& d == direction
|
||||
{
|
||||
if packets > self.cfg.byte_limit / u32::from(self.cfg.mtu) { return Err(State::Failed); }
|
||||
break (packets, reading);
|
||||
}
|
||||
}
|
||||
_ = tick.tick() => {
|
||||
let sample = self.ingress.with(|rx| rx.as_mut().and_then(|r| r.sample(Instant::now(), window)));
|
||||
if let Some(sample) = sample {
|
||||
self.update_receiver(io, direction, sample);
|
||||
send(io, Control::Feedback { id, direction, sample }).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let received = self.ingress.with(|rx| rx.as_ref().map_or(0, |r| r.count));
|
||||
if received < packets {
|
||||
// Reliable End and encrypted probes may take different paths.
|
||||
let drain = self
|
||||
.cfg
|
||||
.rtt
|
||||
.clamp(Duration::from_millis(25), Duration::from_millis(120));
|
||||
sleep_until(Instant::now() + drain).await;
|
||||
}
|
||||
let rx = self.ingress.with(Option::take).ok_or(State::Failed)?;
|
||||
if rx.count > packets {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
let reading = rx.finish(estimate);
|
||||
send(
|
||||
io,
|
||||
Control::Report {
|
||||
id,
|
||||
direction,
|
||||
reading,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(reading)
|
||||
}
|
||||
|
||||
fn update_receiver(&mut self, io: &impl Io, direction: Direction, sample: Feedback) {
|
||||
let reading = self.progress.at(direction);
|
||||
reading.bytes = sample.bytes;
|
||||
if sample.bps > 0 {
|
||||
reading.bps = Some(sample.bps);
|
||||
}
|
||||
io.progress(self.progress);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_ingress_is_bound_to_the_session_id_and_both_assigned_addresses() {
|
||||
let local = Ipv4Addr::new(10, 1, 2, 3);
|
||||
let remote = Ipv4Addr::new(10, 1, 2, 4);
|
||||
let conf = Config {
|
||||
id: 42,
|
||||
local,
|
||||
remote,
|
||||
mtu: 1280,
|
||||
byte_limit: 32_000,
|
||||
rtt: Duration::ZERO,
|
||||
};
|
||||
let (handle, _) = initiate(conf);
|
||||
handle.ingress.with(|rx| {
|
||||
*rx = Some(Receiver::new(
|
||||
Direction::Download,
|
||||
conf.mtu,
|
||||
conf.byte_limit,
|
||||
))
|
||||
});
|
||||
let make = |src, dst, id, seq| {
|
||||
let raw = PacketBuilder::new(src, dst, id, Direction::Download, 1280).packet(0, seq, 7);
|
||||
crate::decode_packet(&raw).unwrap()
|
||||
};
|
||||
for (ipfrom, ipto, id, seq) in [
|
||||
(remote, local, 41, 0),
|
||||
(local, remote, 42, 1),
|
||||
(Ipv4Addr::LOCALHOST, local, 42, 2),
|
||||
(remote, Ipv4Addr::LOCALHOST, 42, 3),
|
||||
(remote, local, 42, 4),
|
||||
] {
|
||||
handle.data(make(ipfrom, ipto, id, seq));
|
||||
}
|
||||
assert_eq!(
|
||||
handle.ingress.with(|rx| rx.as_ref().map(|r| r.count)),
|
||||
Some(1)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Directional goodput measurements for an authenticated peer on its existing IPv4 tunnel.
|
||||
//!
|
||||
//! The host advertises and negotiates this crate's wire version, admits at most one
|
||||
//! test at a time, and delivers control messages over its reliable authenticated
|
||||
//! channel. Probe packets take the same encrypted IPv4 path as application traffic.
|
||||
|
||||
mod engine;
|
||||
mod measurement;
|
||||
mod packet;
|
||||
mod wire;
|
||||
|
||||
pub use engine::{Config, Handle, Io, Session, initiate, respond};
|
||||
pub use packet::{Datagram, decode_packet, is_test_packet};
|
||||
pub use wire::{Control, Direction, Feedback, Progress, Quality, Reading, Start, State};
|
||||
|
||||
/// Capability negotiated by peers for this protocol.
|
||||
pub const PROTOCOL: &str = "speedtest";
|
||||
/// Wire version of the control records and IPv4 payload, independent of software versions.
|
||||
pub const VERSION: u16 = 1;
|
||||
/// Absolute per-direction diagnostic IPv4 traffic budget.
|
||||
pub const NORMAL_BYTES: u32 = 96 * 1024 * 1024;
|
||||
/// Suggested per-direction budget on metered paths.
|
||||
pub const METERED_BYTES: u32 = 8 * 1024 * 1024;
|
||||
@@ -0,0 +1,483 @@
|
||||
use crate::packet::HEADER;
|
||||
use crate::wire::MAX_BPS;
|
||||
use crate::{Datagram, Direction, Feedback, Quality, Reading};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
const INITIAL_BPS: u64 = 8_000_000;
|
||||
// A tail shorter than a regular feedback period may still contain a sustained
|
||||
// train. Require both clocks to span this interval and multiple arrival groups.
|
||||
const MIN_TRAIN: Duration = Duration::from_millis(60);
|
||||
const MIN_BPS: u64 = 32_000;
|
||||
|
||||
pub(crate) struct Receiver {
|
||||
pub(crate) direction: Direction,
|
||||
mtu: u16,
|
||||
packets: u32,
|
||||
seen: Vec<u64>,
|
||||
stage: u8,
|
||||
window: Option<Window>,
|
||||
pub(crate) count: u32,
|
||||
best: u64,
|
||||
}
|
||||
|
||||
struct Window {
|
||||
received: u32,
|
||||
opening_group: u32,
|
||||
arrival_groups: u8,
|
||||
last_group: Instant,
|
||||
first_arrival: Instant,
|
||||
last_arrival: Instant,
|
||||
first: u32,
|
||||
highest: u32,
|
||||
first_send_us: u32,
|
||||
last_send_us: u32,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
fn new(probe: Datagram, now: Instant) -> Self {
|
||||
Self {
|
||||
received: 1,
|
||||
opening_group: 1,
|
||||
arrival_groups: 1,
|
||||
last_group: now,
|
||||
first_arrival: now,
|
||||
last_arrival: now,
|
||||
first: probe.sequence,
|
||||
highest: probe.sequence,
|
||||
first_send_us: probe.sent_us,
|
||||
last_send_us: probe.sent_us,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, probe: Datagram, now: Instant) {
|
||||
if self.arrival_groups < 3
|
||||
&& now.duration_since(self.last_group) >= Duration::from_millis(20)
|
||||
{
|
||||
self.arrival_groups += 1;
|
||||
self.last_group = now;
|
||||
}
|
||||
self.first = self.first.min(probe.sequence);
|
||||
self.highest = self.highest.max(probe.sequence);
|
||||
self.first_send_us = self.first_send_us.min(probe.sent_us);
|
||||
self.last_send_us = self.last_send_us.max(probe.sent_us);
|
||||
// Packets already in the first arrival batch did not traverse the measured interval.
|
||||
if now.duration_since(self.first_arrival) < Duration::from_millis(1) {
|
||||
self.opening_group += 1;
|
||||
}
|
||||
self.received += 1;
|
||||
self.last_arrival = now;
|
||||
}
|
||||
|
||||
fn rate(&self, mtu: u16) -> Option<u64> {
|
||||
let arrivals = self.last_arrival.duration_since(self.first_arrival);
|
||||
let sends = Duration::from_micros(u64::from(self.last_send_us - self.first_send_us));
|
||||
let packets = self.received.saturating_sub(self.opening_group);
|
||||
if packets < 3 || self.arrival_groups < 3 || arrivals < MIN_TRAIN || sends < MIN_TRAIN {
|
||||
return None;
|
||||
}
|
||||
// Feedback and End may arrive late, or queued packets may arrive together.
|
||||
// Use the slower of the sender's and receiver's independent train clocks.
|
||||
let elapsed = arrivals.max(sends).as_micros() as u64;
|
||||
Some((u64::from(packets) * u64::from(mtu - HEADER) * 8_000_000 / elapsed).min(MAX_BPS))
|
||||
}
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
pub(crate) fn new(direction: Direction, mtu: u16, budget: u32) -> Self {
|
||||
let packets = budget / u32::from(mtu);
|
||||
Self {
|
||||
direction,
|
||||
mtu,
|
||||
packets,
|
||||
seen: vec![0; packets.div_ceil(64) as usize],
|
||||
stage: 0,
|
||||
window: None,
|
||||
count: 0,
|
||||
best: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn put(&mut self, probe: Datagram, now: Instant) {
|
||||
if probe.direction != self.direction
|
||||
|| probe.size != self.mtu
|
||||
|| probe.sequence >= self.packets
|
||||
{
|
||||
return;
|
||||
}
|
||||
let word = &mut self.seen[(probe.sequence / 64) as usize];
|
||||
let bit = 1u64 << (probe.sequence % 64);
|
||||
if *word & bit != 0 {
|
||||
return;
|
||||
}
|
||||
*word |= bit;
|
||||
self.count += 1;
|
||||
if probe.stage < self.stage {
|
||||
return;
|
||||
}
|
||||
if probe.stage > self.stage {
|
||||
self.finish_window();
|
||||
self.stage = probe.stage;
|
||||
}
|
||||
match &mut self.window {
|
||||
Some(window) => window.push(probe, now),
|
||||
None => self.window = Some(Window::new(probe, now)),
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_window(&mut self) {
|
||||
if let Some(rate) = self.window.take().and_then(|w| w.rate(self.mtu)) {
|
||||
self.best = self.best.max(rate);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish(mut self, estimate: Reading) -> Reading {
|
||||
self.finish_window();
|
||||
// Final delivery belongs to the receiver. A sender may have stopped on its
|
||||
// byte limit before receiving feedback for a faster, fully observed train.
|
||||
if self.best == 0 {
|
||||
return Reading {
|
||||
bps: None,
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::Insufficient,
|
||||
};
|
||||
}
|
||||
if estimate.quality == Quality::Measured
|
||||
&& let Some(rate) = estimate.bps
|
||||
&& self.best.abs_diff(rate) <= rate / 5
|
||||
{
|
||||
return Reading {
|
||||
bps: Some(rate.min(self.best)),
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::Measured,
|
||||
};
|
||||
}
|
||||
Reading {
|
||||
bps: Some(self.best),
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::AtLeast,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&self) -> u32 {
|
||||
self.count * u32::from(self.mtu - HEADER)
|
||||
}
|
||||
|
||||
// A rate needs observations spread over a real interval. A queued burst
|
||||
// followed by silence must never turn into a capacity estimate.
|
||||
pub(crate) fn sample(&mut self, now: Instant, minimum: Duration) -> Option<Feedback> {
|
||||
let bytes = self.bytes();
|
||||
let w = self.window.as_ref()?;
|
||||
let elapsed = now.duration_since(w.first_arrival);
|
||||
if elapsed < minimum {
|
||||
return None;
|
||||
}
|
||||
let span = w.highest - w.first + 1;
|
||||
let loss = (u64::from(span.saturating_sub(w.received)) * 1000 / u64::from(span)) as u16;
|
||||
let rate = w.rate(self.mtu);
|
||||
if rate.is_none() && elapsed < Duration::from_millis(600) {
|
||||
return None;
|
||||
}
|
||||
let bps = rate.unwrap_or(0);
|
||||
let feedback = Feedback {
|
||||
stage: self.stage,
|
||||
bps,
|
||||
lost_per_mille: loss,
|
||||
bytes,
|
||||
echo_us: w.last_send_us,
|
||||
};
|
||||
self.window = None;
|
||||
self.best = self.best.max(bps);
|
||||
Some(feedback)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Phase {
|
||||
Ramp,
|
||||
// A rate backed off from congestion needs another, higher offer to test it.
|
||||
Settle { verified: bool },
|
||||
Challenge { previous_rate: u64 },
|
||||
}
|
||||
|
||||
pub(crate) struct Search {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) target: u64,
|
||||
best: u64,
|
||||
baseline_delay: Option<u32>,
|
||||
initial_loss: Option<u16>,
|
||||
last_echo: Option<u32>,
|
||||
phase: Phase,
|
||||
previous: Option<u64>,
|
||||
measured: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for Search {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
stage: 0,
|
||||
target: INITIAL_BPS,
|
||||
best: 0,
|
||||
baseline_delay: None,
|
||||
initial_loss: None,
|
||||
last_echo: None,
|
||||
phase: Phase::Ramp,
|
||||
previous: None,
|
||||
measured: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Search {
|
||||
pub(crate) fn observe(&mut self, sample: Feedback, elapsed_us: u32) {
|
||||
if sample.stage != self.stage
|
||||
|| self.measured.is_some()
|
||||
|| sample.echo_us > elapsed_us
|
||||
|| self.last_echo.is_some_and(|echo| echo >= sample.echo_us)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.last_echo = Some(sample.echo_us);
|
||||
let bps = sample.bps;
|
||||
self.best = self.best.max(bps);
|
||||
let delay = elapsed_us - sample.echo_us;
|
||||
let base = *self.baseline_delay.get_or_insert(delay);
|
||||
self.baseline_delay = Some(base.min(delay));
|
||||
let queuing = delay > base.saturating_add(45_000).max(base.saturating_mul(2));
|
||||
// Loss present at the first offer also reduces the payload rate that
|
||||
// can arrive at higher offers. Look for additional loss or queuing.
|
||||
// A very lossy first sample may already be an overloaded slow path.
|
||||
let baseline_loss = *self
|
||||
.initial_loss
|
||||
.get_or_insert(sample.lost_per_mille.min(400));
|
||||
let expected = self.target * u64::from(1000 - baseline_loss) / 1000;
|
||||
let congested =
|
||||
sample.lost_per_mille > baseline_loss + 30 || bps < expected * 4 / 5 || queuing;
|
||||
if congested {
|
||||
let verified = match self.phase {
|
||||
Phase::Challenge { previous_rate } => {
|
||||
bps.abs_diff(previous_rate) <= previous_rate / 5
|
||||
}
|
||||
Phase::Settle { verified } => verified && bps >= self.target * 4 / 5,
|
||||
Phase::Ramp => false,
|
||||
};
|
||||
self.phase = Phase::Settle { verified };
|
||||
self.previous = None;
|
||||
self.offer(if bps == 0 {
|
||||
self.target / 2
|
||||
} else {
|
||||
bps * 97 / 100
|
||||
});
|
||||
} else if let Phase::Settle { verified } = self.phase {
|
||||
if sample.lost_per_mille > 100 {
|
||||
self.previous = None;
|
||||
return;
|
||||
}
|
||||
if let Some(prev) = self.previous.replace(bps)
|
||||
&& prev.abs_diff(bps) <= bps / 6
|
||||
{
|
||||
let steady = (prev + bps) / 2;
|
||||
if verified {
|
||||
self.measured = Some(steady);
|
||||
} else if elapsed_us >= 850_000 {
|
||||
// A cold tunnel or one busy scheduler slice can look like a bottleneck.
|
||||
// Two samples at our own reduced rate prove only that we can sustain it.
|
||||
self.phase = Phase::Challenge {
|
||||
previous_rate: steady,
|
||||
};
|
||||
self.offer(steady * 2);
|
||||
self.previous = None;
|
||||
}
|
||||
}
|
||||
} else if self.target < MAX_BPS {
|
||||
self.phase = Phase::Ramp;
|
||||
self.offer(self.target.saturating_mul(4));
|
||||
}
|
||||
}
|
||||
|
||||
fn offer(&mut self, bps: u64) {
|
||||
self.target = bps.clamp(MIN_BPS, MAX_BPS);
|
||||
self.stage = self.stage.saturating_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn done(&self) -> bool {
|
||||
self.measured.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn result(&self, bytes: u32) -> Reading {
|
||||
if let Some(bps) = self.measured {
|
||||
Reading {
|
||||
bps: Some(bps),
|
||||
bytes,
|
||||
quality: Quality::Measured,
|
||||
}
|
||||
} else if self.best > 0 {
|
||||
Reading {
|
||||
bps: Some(self.best),
|
||||
bytes,
|
||||
quality: Quality::AtLeast,
|
||||
}
|
||||
} else {
|
||||
Reading {
|
||||
bps: None,
|
||||
bytes,
|
||||
quality: Quality::Insufficient,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Pacer {
|
||||
last_tick: Instant,
|
||||
// Fractional packet credit in payload bit-nanoseconds.
|
||||
credit: u64,
|
||||
cost: u64,
|
||||
}
|
||||
|
||||
impl Pacer {
|
||||
pub(crate) fn new(start: Instant, mtu: u16) -> Self {
|
||||
Self {
|
||||
last_tick: start,
|
||||
credit: 0,
|
||||
cost: u64::from(mtu - HEADER) * 8_000_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn packets(&mut self, now: Instant, bps: u64) -> u32 {
|
||||
// The event loop may have been descheduled. Never catch up with a long burst.
|
||||
let elapsed = now
|
||||
.duration_since(self.last_tick)
|
||||
.as_nanos()
|
||||
.min(12_000_000) as u64;
|
||||
self.last_tick = now;
|
||||
self.credit += elapsed * bps;
|
||||
let packets = self.credit / self.cost;
|
||||
self.credit %= self.cost;
|
||||
packets.min(512) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
fn packet(sequence: u32, stage: u8, sent_us: u32) -> Datagram {
|
||||
Datagram {
|
||||
id: 7,
|
||||
source: Ipv4Addr::LOCALHOST,
|
||||
destination: Ipv4Addr::BROADCAST,
|
||||
direction: Direction::Download,
|
||||
stage,
|
||||
sequence,
|
||||
sent_us,
|
||||
size: 1280,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_reordered_packets_are_counted_once_and_do_not_reopen_earlier_stages() {
|
||||
let t = Instant::now();
|
||||
let mut rx = Receiver::new(Direction::Download, 1280, 1280 * 8);
|
||||
for (i, s) in [(7, 1), (1, 0), (3, 1), (3, 1), (8, 1), (u32::MAX, 1)] {
|
||||
rx.put(packet(i, s, 0), t);
|
||||
}
|
||||
rx.put(
|
||||
Datagram {
|
||||
direction: Direction::Upload,
|
||||
..packet(4, 1, 0)
|
||||
},
|
||||
t,
|
||||
);
|
||||
rx.put(
|
||||
Datagram {
|
||||
size: 1500,
|
||||
..packet(5, 1, 0)
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert_eq!(rx.count, 3);
|
||||
assert_eq!(rx.bytes(), 3 * u32::from(1280 - HEADER));
|
||||
assert_eq!(rx.stage, 1);
|
||||
assert!(rx.window.as_ref().is_some_and(|w| w.received == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_burst_or_compressed_catchup_cannot_establish_throughput() {
|
||||
let start = Instant::now();
|
||||
let mut receiver = Receiver::new(Direction::Download, 1280, NORMAL_BYTES_FOR_TEST);
|
||||
for i in 0..500 {
|
||||
receiver.put(packet(i, 0, i), start);
|
||||
}
|
||||
let window = Duration::from_millis(120);
|
||||
for i in 500..520 {
|
||||
receiver.put(packet(i, 0, i), start + window);
|
||||
}
|
||||
assert!(receiver.sample(start + window, window).is_none());
|
||||
let feedback = receiver
|
||||
.sample(start + Duration::from_millis(650), window)
|
||||
.unwrap();
|
||||
assert_eq!(feedback.bps, 0);
|
||||
assert_eq!(receiver.best, 0);
|
||||
}
|
||||
|
||||
const NORMAL_BYTES_FOR_TEST: u32 = 1024 * 1024;
|
||||
|
||||
#[test]
|
||||
fn final_rate_uses_delivered_payload_even_when_end_overtakes_feedback() {
|
||||
let start = Instant::now();
|
||||
let mut rx = Receiver::new(Direction::Download, 1280, NORMAL_BYTES_FOR_TEST);
|
||||
// The first train takes twice as long to arrive as to send. The faster
|
||||
// second train ends before the next feedback tick.
|
||||
for i in 0..=100 {
|
||||
rx.put(
|
||||
packet(i, 0, i * 1_000),
|
||||
start + Duration::from_millis(u64::from(i) * 2),
|
||||
);
|
||||
}
|
||||
let tick = Duration::from_millis(220);
|
||||
let initial = rx.sample(start + tick, tick).unwrap();
|
||||
let payload_bits = u64::from(1280 - HEADER) * 8;
|
||||
assert_eq!(initial.bps, payload_bits * 500);
|
||||
for i in 0..=100 {
|
||||
rx.put(
|
||||
packet(101 + i, 1, 250_000 + i * 1_000),
|
||||
start + Duration::from_millis(250 + u64::from(i)),
|
||||
);
|
||||
}
|
||||
let result = rx.finish(Reading {
|
||||
bytes: initial.bytes,
|
||||
bps: Some(initial.bps),
|
||||
quality: Quality::AtLeast,
|
||||
});
|
||||
assert_eq!(result.bps, Some(payload_bits * 1000));
|
||||
assert_eq!(result.quality, Quality::AtLeast);
|
||||
assert_eq!(result.bytes, 202 * u32::from(1280 - HEADER));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retransmitted_feedback_does_not_supply_two_confirmation_windows() {
|
||||
let mut search = Search::default();
|
||||
let f = |stage, bps, lost_per_mille, bytes, echo_us| Feedback {
|
||||
stage,
|
||||
bps,
|
||||
lost_per_mille,
|
||||
bytes,
|
||||
echo_us,
|
||||
};
|
||||
search.observe(f(0, 1_000_000, 700, 15000, 120_000), 121_000);
|
||||
let observed = f(1, 970_000, 0, 30000, 241_000);
|
||||
search.observe(observed, 242_000);
|
||||
search.observe(observed, 243_000);
|
||||
assert!(!search.done());
|
||||
search.observe(f(1, 970_000, 0, 45000, 360_000), 361_000);
|
||||
assert!(!search.done());
|
||||
search.observe(f(1, 970_000, 0, 100_000, 900_000), 901_000);
|
||||
assert_eq!(search.stage, 2);
|
||||
search.observe(f(2, 1_000_000, 450, 120_000, 1_060_000), 1_061_000);
|
||||
search.observe(f(3, 970_000, 0, 150_000, 1_220_000), 1_221_000);
|
||||
search.observe(f(3, 970_000, 0, 180_000, 1_380_000), 1_381_000);
|
||||
assert!(search.done());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
use crate::Direction;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub(crate) const MIN_MTU: u16 = 576;
|
||||
pub(crate) const MAX_MTU: u16 = 1500;
|
||||
pub(crate) const HEADER: u16 = 46;
|
||||
const MAGIC: &[u8; 8] = b"TSNGSP01";
|
||||
const IP_PROTOCOL: u8 = 253; // RFC 3692 local experiment, disambiguated by MAGIC.
|
||||
|
||||
/// Fields from a validated version-one diagnostic IPv4 packet. Probes carry no arbitrary stream data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Datagram {
|
||||
/// Measurement identifier from the authenticated control exchange.
|
||||
pub id: u64,
|
||||
/// Source address of the inner IPv4 datagram.
|
||||
pub source: Ipv4Addr,
|
||||
/// Destination address of the inner IPv4 datagram.
|
||||
pub destination: Ipv4Addr,
|
||||
pub(crate) direction: Direction,
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) sequence: u32,
|
||||
pub(crate) sent_us: u32,
|
||||
pub(crate) size: u16,
|
||||
}
|
||||
|
||||
impl Datagram {
|
||||
/// Number of delivered diagnostic payload bytes, excluding both headers.
|
||||
pub fn payload_len(self) -> u16 {
|
||||
self.size - HEADER
|
||||
}
|
||||
}
|
||||
|
||||
/// Identify this crate's reserved IPv4 payload, including malformed records that should be dropped.
|
||||
pub fn is_test_packet(bytes: &[u8]) -> bool {
|
||||
if bytes.len() < 20 || bytes[0] >> 4 != 4 || bytes[9] != IP_PROTOCOL {
|
||||
return false;
|
||||
}
|
||||
let offset = usize::from(bytes[0] & 0x0f) * 4;
|
||||
offset >= 20 && bytes.get(offset..offset + MAGIC.len()) == Some(MAGIC)
|
||||
}
|
||||
|
||||
/// Validate an entire diagnostic datagram before handing its fixed-size metadata to the receiver.
|
||||
pub fn decode_packet(bytes: &[u8]) -> Option<Datagram> {
|
||||
let size = u16::try_from(bytes.len()).ok()?;
|
||||
if !(MIN_MTU..=MAX_MTU).contains(&size)
|
||||
|| bytes[0] != 0x45
|
||||
|| bytes[9] != IP_PROTOCOL
|
||||
|| bytes[20..28] != *MAGIC
|
||||
|| u16::from_be_bytes([bytes[2], bytes[3]]) != size
|
||||
|| u16::from_be_bytes([bytes[6], bytes[7]]) & !0x4000 != 0
|
||||
|| checksum(&bytes[..20]) != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let direction = match bytes[36] {
|
||||
0 => Direction::Download,
|
||||
1 => Direction::Upload,
|
||||
_ => return None,
|
||||
};
|
||||
let sent_us = u32::from_be_bytes(bytes[42..46].try_into().ok()?);
|
||||
if sent_us > 5_000_000 {
|
||||
return None;
|
||||
}
|
||||
Some(Datagram {
|
||||
source: Ipv4Addr::from(<[u8; 4]>::try_from(&bytes[12..16]).ok()?),
|
||||
destination: Ipv4Addr::from(<[u8; 4]>::try_from(&bytes[16..20]).ok()?),
|
||||
id: u64::from_be_bytes(bytes[28..36].try_into().ok()?),
|
||||
direction,
|
||||
stage: bytes[37],
|
||||
sequence: u32::from_be_bytes(bytes[38..42].try_into().ok()?),
|
||||
sent_us,
|
||||
size,
|
||||
})
|
||||
}
|
||||
|
||||
// Build the immutable header and deterministic padding once per direction. The
|
||||
// underlying data tunnel encrypts the packet before it goes on the wire.
|
||||
pub(crate) struct PacketBuilder(Bytes);
|
||||
|
||||
impl PacketBuilder {
|
||||
pub(crate) fn new(
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
id: u64,
|
||||
direction: Direction,
|
||||
mtu: u16,
|
||||
) -> Self {
|
||||
let mut bytes = BytesMut::zeroed(usize::from(mtu));
|
||||
bytes[0] = 0x45;
|
||||
bytes[2..4].copy_from_slice(&mtu.to_be_bytes());
|
||||
bytes[6] = 0x40;
|
||||
bytes[8] = 64;
|
||||
bytes[9] = IP_PROTOCOL;
|
||||
bytes[12..16].copy_from_slice(&source.octets());
|
||||
bytes[16..20].copy_from_slice(&destination.octets());
|
||||
let check = checksum(&bytes[..20]);
|
||||
bytes[10..12].copy_from_slice(&check.to_be_bytes());
|
||||
bytes[20..28].copy_from_slice(MAGIC);
|
||||
bytes[28..36].copy_from_slice(&id.to_be_bytes());
|
||||
bytes[36] = match direction {
|
||||
Direction::Download => 0,
|
||||
Direction::Upload => 1,
|
||||
};
|
||||
Self(bytes.freeze())
|
||||
}
|
||||
|
||||
pub(crate) fn packet(&self, stage: u8, sequence: u32, sent_us: u32) -> Bytes {
|
||||
let mut bytes = BytesMut::from(self.0.as_ref());
|
||||
bytes[37] = stage;
|
||||
bytes[38..42].copy_from_slice(&sequence.to_be_bytes());
|
||||
bytes[42..46].copy_from_slice(&sent_us.to_be_bytes());
|
||||
bytes.freeze()
|
||||
}
|
||||
}
|
||||
|
||||
fn checksum(bytes: &[u8]) -> u16 {
|
||||
let mut sum: u32 = bytes
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|&word| u32::from(u16::from_be_bytes(word)))
|
||||
.sum();
|
||||
while sum > u32::from(u16::MAX) {
|
||||
sum = (sum & 0xffff) + (sum >> 16);
|
||||
}
|
||||
!(sum as u16)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
fn probe() -> Bytes {
|
||||
PacketBuilder::new(
|
||||
Ipv4Addr::new(10, 1, 10, 1),
|
||||
Ipv4Addr::new(10, 1, 10, 2),
|
||||
42,
|
||||
Direction::Upload,
|
||||
1280,
|
||||
)
|
||||
.packet(3, 908, 12_000)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routeable_ip_header_and_test_metadata_round_trip() {
|
||||
let bytes = probe();
|
||||
assert!(is_test_packet(&bytes));
|
||||
let data = decode_packet(&bytes).unwrap();
|
||||
assert_eq!(data.source, Ipv4Addr::new(10, 1, 10, 1));
|
||||
assert_eq!(data.destination, Ipv4Addr::new(10, 1, 10, 2));
|
||||
assert_eq!(
|
||||
(
|
||||
data.id,
|
||||
data.direction,
|
||||
data.stage,
|
||||
data.sequence,
|
||||
data.sent_us
|
||||
),
|
||||
(42, Direction::Upload, 3, 908, 12_000)
|
||||
);
|
||||
assert_eq!(data.payload_len(), 1280 - HEADER);
|
||||
for n in [0, 1, 19, 27, 45, 100, 1279] {
|
||||
assert!(decode_packet(&bytes[..n]).is_none());
|
||||
}
|
||||
for (byte, value) in [
|
||||
(0, 0x65),
|
||||
(2, 0x04),
|
||||
(6, 0x20),
|
||||
(9, 17),
|
||||
(10, 0),
|
||||
(20, b'z'),
|
||||
(36, 3),
|
||||
(42, 255),
|
||||
] {
|
||||
let mut bad = bytes.to_vec();
|
||||
bad[byte] = value;
|
||||
assert!(decode_packet(&bad).is_none(), "corrupted {byte}");
|
||||
}
|
||||
let mut broken = bytes.to_vec();
|
||||
broken[36] = 123;
|
||||
assert!(is_test_packet(&broken));
|
||||
broken[20] = 0;
|
||||
assert!(!is_test_packet(&broken));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use crate::NORMAL_BYTES;
|
||||
use crate::packet::{MAX_MTU, MIN_MTU};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Both endpoints name directions from the initiating user's point of view.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Direction {
|
||||
/// From the responding peer to the initiator.
|
||||
Download,
|
||||
/// From the initiator to the responding peer.
|
||||
Upload,
|
||||
}
|
||||
|
||||
/// What the received samples establish about the path.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Quality {
|
||||
/// Measurement in progress.
|
||||
#[default]
|
||||
Measuring,
|
||||
/// The receiver confirmed a stable rate after the probe reached the path's limit.
|
||||
Measured,
|
||||
/// Sustained delivery at this rate was established before the time or byte budget ended.
|
||||
AtLeast,
|
||||
/// No full observation window was available.
|
||||
Insufficient,
|
||||
}
|
||||
|
||||
/// Useful probe payload received in one direction.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Reading {
|
||||
/// Delivered bits per second, if there was enough evidence to calculate a rate.
|
||||
pub bps: Option<u64>,
|
||||
/// Unique, received probe payload bytes, excluding IPv4 and diagnostic headers.
|
||||
pub bytes: u32,
|
||||
/// Meaning of the reported rate.
|
||||
pub quality: Quality,
|
||||
}
|
||||
|
||||
/// Lifecycle of a single bidirectional test.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum State {
|
||||
/// Negotiating a test.
|
||||
#[default]
|
||||
Starting,
|
||||
/// Receiving from the peer.
|
||||
Download,
|
||||
/// Sending to the peer.
|
||||
Upload,
|
||||
/// Both direction reports were exchanged.
|
||||
Complete,
|
||||
/// A participant cancelled this test.
|
||||
Cancelled,
|
||||
/// The other endpoint is already testing.
|
||||
Busy,
|
||||
/// A participant failed to finish before the deadline.
|
||||
TimedOut,
|
||||
/// The transport failed, configuration was invalid, or a peer sent inconsistent results.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A snapshot suitable for status or a live display.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Progress {
|
||||
/// Current phase or final outcome.
|
||||
pub state: State,
|
||||
/// Peer to initiator.
|
||||
pub down: Reading,
|
||||
/// Initiator to peer.
|
||||
pub up: Reading,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
pub(crate) fn at(&mut self, direction: Direction) -> &mut Reading {
|
||||
match direction {
|
||||
Direction::Download => &mut self.down,
|
||||
Direction::Upload => &mut self.up,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Request to start one measurement under both peers' local limits.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Start {
|
||||
/// Fresh random identifier selected by the initiator.
|
||||
pub id: u64,
|
||||
/// Maximum diagnostic IPv4 bytes to send per direction.
|
||||
pub byte_limit: u32,
|
||||
/// Maximum complete IPv4 datagram size supported by the initiating endpoint.
|
||||
pub mtu: u16,
|
||||
}
|
||||
|
||||
/// Receiver-clock observation at one offered rate.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Feedback {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) bps: u64,
|
||||
pub(crate) lost_per_mille: u16,
|
||||
pub(crate) bytes: u32,
|
||||
pub(crate) echo_us: u32,
|
||||
}
|
||||
|
||||
/// Bounded records carried by the authenticated, reliable control connection.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Control {
|
||||
/// Request a test between these two peers.
|
||||
Start(Start),
|
||||
/// Negotiated maximum datagram size and per-direction budget.
|
||||
Accepted {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Per-direction budget in IPv4 bytes.
|
||||
byte_limit: u32,
|
||||
/// Size of every probe datagram.
|
||||
mtu: u16,
|
||||
},
|
||||
/// The responder already has an active test.
|
||||
Busy {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
},
|
||||
/// Receiver has installed its data sink before the sender begins.
|
||||
Ready {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction about to start.
|
||||
direction: Direction,
|
||||
},
|
||||
/// Observed goodput and loss over a full interval of the receiver's clock.
|
||||
Feedback {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction being measured.
|
||||
direction: Direction,
|
||||
/// Receiver's observation.
|
||||
sample: Feedback,
|
||||
},
|
||||
/// The sender has stopped issuing probes and shares the result of its rate search.
|
||||
End {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction ending.
|
||||
direction: Direction,
|
||||
/// Number of IPv4 datagrams issued by the sender.
|
||||
packets: u32,
|
||||
/// Rate search result based on receiver feedback.
|
||||
reading: Reading,
|
||||
},
|
||||
/// Final delivery numbers after draining late probes.
|
||||
Report {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction completed.
|
||||
direction: Direction,
|
||||
/// Agreed result for this direction.
|
||||
reading: Reading,
|
||||
},
|
||||
/// End the exchange early in either direction.
|
||||
Cancel {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) const MAX_BPS: u64 = 8_000_000_000;
|
||||
const MAX_RECORD: usize = 64;
|
||||
|
||||
impl Control {
|
||||
/// Identifier used to bind the record to an already authenticated peer and session.
|
||||
pub fn id(&self) -> u64 {
|
||||
match *self {
|
||||
Self::Start(start) => start.id,
|
||||
Self::Accepted { id, .. }
|
||||
| Self::Busy { id }
|
||||
| Self::Ready { id, .. }
|
||||
| Self::Feedback { id, .. }
|
||||
| Self::End { id, .. }
|
||||
| Self::Report { id, .. }
|
||||
| Self::Cancel { id } => id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a control record into its compact version-one representation.
|
||||
pub fn encode(&self) -> Result<Vec<u8>, postcard::Error> {
|
||||
postcard::to_stdvec(self)
|
||||
}
|
||||
|
||||
/// Parse exactly one version-one record. Trailing bytes and values outside the protocol limits are rejected.
|
||||
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||
if bytes.len() > MAX_RECORD {
|
||||
return None;
|
||||
}
|
||||
let (control, rest) = postcard::take_from_bytes::<Self>(bytes).ok()?;
|
||||
(rest.is_empty() && control.valid()).then_some(control)
|
||||
}
|
||||
|
||||
pub(crate) fn valid(self) -> bool {
|
||||
match self {
|
||||
Self::Start(Start {
|
||||
byte_limit, mtu, ..
|
||||
})
|
||||
| Self::Accepted {
|
||||
byte_limit, mtu, ..
|
||||
} => (1..=NORMAL_BYTES).contains(&byte_limit) && (MIN_MTU..=MAX_MTU).contains(&mtu),
|
||||
Self::Feedback { sample, .. } => {
|
||||
sample.bps <= MAX_BPS
|
||||
&& sample.lost_per_mille <= 1000
|
||||
&& sample.bytes <= NORMAL_BYTES
|
||||
&& sample.echo_us <= 5_000_000
|
||||
}
|
||||
Self::End {
|
||||
packets, reading, ..
|
||||
} => packets <= NORMAL_BYTES / u32::from(MIN_MTU) && valid_result(reading),
|
||||
Self::Report { reading, .. } => valid_result(reading),
|
||||
Self::Busy { .. } | Self::Ready { .. } | Self::Cancel { .. } => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_result(reading: Reading) -> bool {
|
||||
reading.bytes <= NORMAL_BYTES
|
||||
&& match reading.quality {
|
||||
Quality::Insufficient => reading.bps.is_none(),
|
||||
Quality::Measured | Quality::AtLeast => {
|
||||
reading.bytes > 0 && reading.bps.is_some_and(|v| (1..=MAX_BPS).contains(&v))
|
||||
}
|
||||
Quality::Measuring => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
//! Independently clocked sessions exchange real control records and shaped IPv4 probes.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use bytes::Bytes;
|
||||
use std::future::Future;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
use tsunagi_speedtest::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Link {
|
||||
remote: Handle,
|
||||
start: Instant,
|
||||
rate: u64,
|
||||
warmup: Option<(Duration, u64)>,
|
||||
control_delay: Duration,
|
||||
drop_every: u32,
|
||||
state: Arc<Mutex<Delivery>>,
|
||||
samples: Arc<Mutex<Vec<Progress>>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Delivery {
|
||||
// Tokens represent one millisecond of useful payload on this shaped path.
|
||||
tick: u64,
|
||||
credit: u64,
|
||||
bytes: u64,
|
||||
packets: u32,
|
||||
}
|
||||
|
||||
impl Io for Link {
|
||||
async fn control(&self, message: Control) -> bool {
|
||||
// The harness creates the responding session with the real Start record.
|
||||
if !matches!(message, Control::Start(_)) {
|
||||
if !self.control_delay.is_zero() {
|
||||
tokio::time::sleep(self.control_delay).await;
|
||||
}
|
||||
self.remote
|
||||
.control(Control::decode(&message.encode().unwrap()).unwrap());
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
let probe = decode_packet(&packet).unwrap();
|
||||
let tick = self.start.elapsed().as_millis() as u64;
|
||||
let rate = self
|
||||
.warmup
|
||||
.filter(|(until, _)| self.start.elapsed() < *until)
|
||||
.map_or(self.rate, |(_, rate)| rate);
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state.tick != tick {
|
||||
let elapsed = tick - state.tick;
|
||||
state.credit = (state.credit + rate * elapsed / 8000).min(rate * 4 / 8000 + 1300);
|
||||
state.tick = tick;
|
||||
}
|
||||
state.bytes += packet.len() as u64;
|
||||
if state.credit >= probe.payload_len() as u64 {
|
||||
state.credit -= probe.payload_len() as u64;
|
||||
state.packets += 1;
|
||||
if self.drop_every != 0 && state.packets.is_multiple_of(self.drop_every) {
|
||||
return true;
|
||||
}
|
||||
self.remote.data(probe);
|
||||
// Duplicates must never add more bytes or improve the reported rate.
|
||||
self.remote.data(probe);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn progress(&self, update: Progress) {
|
||||
self.samples.lock().unwrap().push(update);
|
||||
}
|
||||
}
|
||||
|
||||
fn config(local: u8, remote: u8, bytes: u32) -> Config {
|
||||
Config {
|
||||
id: 7,
|
||||
local: Ipv4Addr::new(10, 11, 12, local),
|
||||
remote: Ipv4Addr::new(10, 11, 12, remote),
|
||||
mtu: 1280,
|
||||
byte_limit: bytes,
|
||||
rtt: Duration::from_millis(20),
|
||||
}
|
||||
}
|
||||
|
||||
async fn measure(down: u64, up: u64, budget: u32) -> (Progress, Progress, Link, Link) {
|
||||
shaped(down, up, budget, Duration::ZERO, 0, None).await
|
||||
}
|
||||
|
||||
async fn shaped(
|
||||
down: u64,
|
||||
up: u64,
|
||||
budget: u32,
|
||||
control_delay: Duration,
|
||||
drop_every: u32,
|
||||
warmup: Option<(Duration, u64)>,
|
||||
) -> (Progress, Progress, Link, Link) {
|
||||
let cfg = |a, b| Config {
|
||||
rtt: control_delay.max(Duration::from_millis(20)),
|
||||
..config(a, b, budget)
|
||||
};
|
||||
let (a, initiator) = initiate(cfg(1, 2));
|
||||
let start = Start {
|
||||
id: 7,
|
||||
byte_limit: budget,
|
||||
mtu: 1280,
|
||||
};
|
||||
let (b, responder) = respond(cfg(2, 1), start);
|
||||
let now = Instant::now();
|
||||
let link = |remote, rate, warmup| Link {
|
||||
warmup,
|
||||
remote,
|
||||
start: now,
|
||||
rate,
|
||||
control_delay,
|
||||
drop_every,
|
||||
state: Default::default(),
|
||||
samples: Default::default(),
|
||||
};
|
||||
let ab = link(b, up, None);
|
||||
let ba = link(a, down, warmup);
|
||||
let (a, b) = tokio::join!(initiator.run(ab.clone()), responder.run(ba.clone()));
|
||||
println!(
|
||||
"Shaped path {down}/{up} bit/s, receiver readings {:?}/{:?}",
|
||||
a.down.bps, a.up.bps
|
||||
);
|
||||
assert!(now.elapsed() <= Duration::from_secs(5));
|
||||
assert!(ab.state.lock().unwrap().bytes <= u64::from(budget));
|
||||
assert!(ba.state.lock().unwrap().bytes <= u64::from(budget));
|
||||
(a, b, ab, ba)
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn both_directions_measure_delivery_and_show_it_before_completion() {
|
||||
let (a, b, ab, _) = measure(10_000_000, 40_000_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (sample, expected) in [(a.down, 10_000_000), (a.up, 40_000_000)] {
|
||||
let bps = sample.bps.unwrap();
|
||||
assert!(
|
||||
(expected * 8 / 10..=expected * 12 / 10).contains(&bps),
|
||||
"{sample:?}"
|
||||
);
|
||||
assert_eq!(sample.quality, Quality::Measured, "{sample:?}");
|
||||
}
|
||||
let updates = ab.samples.lock().unwrap();
|
||||
assert!(
|
||||
updates
|
||||
.iter()
|
||||
.any(|p| p.state == State::Download && p.down.bps.is_some())
|
||||
);
|
||||
assert!(
|
||||
updates
|
||||
.iter()
|
||||
.any(|p| p.state == State::Upload && p.up.bps.is_some())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_fast_path_extends_the_probe_but_never_turns_a_short_burst_into_a_peak() {
|
||||
let (a, _, _, _) = measure(1_000_000_000, 1_000_000_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
assert!(a.down.bytes > 16 * 1024 * 1024);
|
||||
assert!(
|
||||
a.down
|
||||
.bps
|
||||
.is_some_and(|v| (700_000_000..=1_150_000_000).contains(&v)),
|
||||
"{a:?}"
|
||||
);
|
||||
let (short, _, _, _) = measure(1_000_000_000, 1_000_000_000, 4096).await;
|
||||
assert_eq!(short.down.quality, Quality::Insufficient);
|
||||
assert_eq!(short.down.bps, None);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn persistent_random_loss_does_not_masquerade_as_a_slow_link() {
|
||||
let (a, _, _, _) = shaped(
|
||||
20_000_000,
|
||||
45_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(45),
|
||||
20,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (reading, rate) in [(a.down, 20_000_000), (a.up, 45_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|v| (rate * 7 / 10..=rate * 11 / 10).contains(&v)),
|
||||
"{a:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn fast_metered_path_returns_a_sustained_lower_bound_within_its_budget() {
|
||||
let (a, _, _, _) = measure(4_000_000_000, 4_000_000_000, METERED_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for reading in [a.down, a.up] {
|
||||
assert_eq!(reading.quality, Quality::AtLeast);
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|v| (50_000_000..1_000_000_000).contains(&v))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn unreachable_data_path_cannot_synthesize_a_rate_or_keep_the_exchange_open() {
|
||||
let (a, _, _, _) = measure(0, 0, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for reading in [a.down, a.up] {
|
||||
assert_eq!(reading.quality, Quality::Insufficient);
|
||||
assert_eq!(reading.bps, None);
|
||||
}
|
||||
}
|
||||
|
||||
struct Silent;
|
||||
impl Io for Silent {
|
||||
fn control(&self, _: Control) -> impl Future<Output = bool> + Send {
|
||||
std::future::pending()
|
||||
}
|
||||
fn packet(&self, _: Bytes) -> bool {
|
||||
false
|
||||
}
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_blocked_control_stream_cannot_hold_up_cancellation_or_the_deadline() {
|
||||
let (handle, runner) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
let task = tokio::spawn(runner.run(Silent));
|
||||
tokio::task::yield_now().await;
|
||||
handle.cancel();
|
||||
let before = Instant::now();
|
||||
assert_eq!(task.await.unwrap().state, State::Cancelled);
|
||||
assert!(before.elapsed() <= Duration::from_millis(25));
|
||||
|
||||
let (_keep_ingress, runner) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
let before = Instant::now();
|
||||
assert_eq!(runner.run(Silent).await.state, State::TimedOut);
|
||||
assert!(before.elapsed() <= Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_records_have_finite_limits_and_exact_framing() {
|
||||
let message = Control::Start(Start {
|
||||
id: 42,
|
||||
byte_limit: NORMAL_BYTES,
|
||||
mtu: 1280,
|
||||
});
|
||||
let mut wire = message.encode().unwrap();
|
||||
assert_eq!(Control::decode(&wire), Some(message));
|
||||
for n in 0..wire.len() {
|
||||
assert_eq!(Control::decode(&wire[..n]), None);
|
||||
}
|
||||
wire.push(0);
|
||||
assert_eq!(Control::decode(&wire), None);
|
||||
assert_eq!(Control::decode(&[255; 65]), None);
|
||||
for (byte_limit, mtu) in [
|
||||
(0, 1280),
|
||||
(NORMAL_BYTES + 1, 1280),
|
||||
(1000, 4),
|
||||
(1000, u16::MAX),
|
||||
] {
|
||||
let wire = Control::Start(Start {
|
||||
id: 1,
|
||||
byte_limit,
|
||||
mtu,
|
||||
})
|
||||
.encode()
|
||||
.unwrap();
|
||||
assert_eq!(Control::decode(&wire), None);
|
||||
}
|
||||
}
|
||||
|
||||
struct OpenControl;
|
||||
impl Io for OpenControl {
|
||||
fn control(&self, _: Control) -> impl Future<Output = bool> + Send {
|
||||
std::future::ready(true)
|
||||
}
|
||||
fn packet(&self, _: Bytes) -> bool {
|
||||
false
|
||||
}
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn an_unrelated_busy_reply_does_not_cancel_the_active_request() {
|
||||
let (handle, session) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
handle.control(Control::Busy { id: 8 });
|
||||
let task = tokio::spawn(session.run(OpenControl));
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!task.is_finished());
|
||||
handle.control(Control::Busy { id: 7 });
|
||||
assert_eq!(task.await.unwrap().state, State::Busy);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn slower_control_feedback_leaves_time_for_both_directions() {
|
||||
let (a, b, _, _) = shaped(
|
||||
12_000_000,
|
||||
25_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(130),
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a.state, State::Complete);
|
||||
assert!(
|
||||
a.down
|
||||
.bps
|
||||
.is_some_and(|v| (9_000_000..=14_000_000).contains(&v))
|
||||
);
|
||||
assert!(
|
||||
a.up.bps
|
||||
.is_some_and(|v| (17_000_000..=28_000_000).contains(&v))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn slow_links_accumulate_enough_arrivals_for_a_rate() {
|
||||
let (a, _, _, _) = measure(100_000, 256_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (r, rate) in [(a.down, 100_000), (a.up, 256_000)] {
|
||||
assert!(
|
||||
r.bps
|
||||
.is_some_and(|v| (rate * 65 / 100..=rate * 125 / 100).contains(&v)),
|
||||
"{r:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn persistent_heavy_loss_reports_only_sustained_lower_bounds() {
|
||||
let (a, _, _, _) = shaped(
|
||||
50_000_000,
|
||||
50_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::ZERO,
|
||||
3,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
for r in [a.down, a.up] {
|
||||
assert_eq!(r.quality, Quality::AtLeast, "{r:?}");
|
||||
assert!(
|
||||
r.bps
|
||||
.is_some_and(|v| (28_000_000..=36_000_000).contains(&v)),
|
||||
"{r:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_rate_requires_evidence_of_delivered_payload() {
|
||||
for quality in [Quality::AtLeast, Quality::Measured] {
|
||||
let message = Control::Report {
|
||||
id: 1,
|
||||
direction: Direction::Download,
|
||||
reading: Reading {
|
||||
bps: Some(8_000_000_000),
|
||||
bytes: 0,
|
||||
quality,
|
||||
},
|
||||
};
|
||||
assert!(Control::decode(&message.encode().unwrap()).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_cold_download_reprobes_after_the_path_warms_up() {
|
||||
let (result, _, _, _) = shaped(
|
||||
300_000_000,
|
||||
250_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::ZERO,
|
||||
0,
|
||||
Some((Duration::from_millis(850), 60_000_000)),
|
||||
)
|
||||
.await;
|
||||
for (reading, expected) in [(result.down, 300_000_000), (result.up, 250_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|rate| (expected * 8 / 10..=expected * 11 / 10).contains(&rate)),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delayed_feedback_does_not_hide_the_metered_receivers_last_sustained_rate() {
|
||||
let (result, _, _, _) = shaped(
|
||||
350_000_000,
|
||||
200_000_000,
|
||||
METERED_BYTES,
|
||||
Duration::from_millis(95),
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
for (reading, expected) in [(result.down, 350_000_000), (result.up, 200_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|rate| (expected * 75 / 100..=expected * 11 / 10).contains(&rate)),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_full_tunnel_charges_only_packets_actually_submitted_to_it() {
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
|
||||
struct BusyQueue {
|
||||
other: Handle,
|
||||
start: Instant,
|
||||
stalled: AtomicBool,
|
||||
submitted: AtomicU32,
|
||||
}
|
||||
|
||||
impl Io for BusyQueue {
|
||||
async fn control(&self, message: Control) -> bool {
|
||||
if let Control::End { packets, .. } = message {
|
||||
assert!(self.stalled.load(Ordering::Relaxed));
|
||||
assert_eq!(packets, self.submitted.load(Ordering::Relaxed));
|
||||
}
|
||||
if !matches!(message, Control::Start(_)) {
|
||||
self.other.control(message);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
let count = self.submitted.fetch_add(1, Ordering::Relaxed);
|
||||
let full = self.start.elapsed() > Duration::from_millis(180) && count.is_multiple_of(3);
|
||||
if full {
|
||||
self.stalled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
// A backpressured tunnel may drop the packet or retain it for a
|
||||
// pending handshake. Either outcome must respect the byte budget.
|
||||
if !full || count.is_multiple_of(2) {
|
||||
self.other.data(decode_packet(&packet).unwrap());
|
||||
}
|
||||
!full
|
||||
}
|
||||
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
let budget = 2 * 1024 * 1024;
|
||||
let (a, outgoing) = initiate(config(1, 2, budget));
|
||||
let (b, incoming) = respond(
|
||||
config(2, 1, budget),
|
||||
Start {
|
||||
id: 7,
|
||||
byte_limit: budget,
|
||||
mtu: 1280,
|
||||
},
|
||||
);
|
||||
let queue = |other| BusyQueue {
|
||||
other,
|
||||
start: Instant::now(),
|
||||
stalled: AtomicBool::new(false),
|
||||
submitted: AtomicU32::new(0),
|
||||
};
|
||||
let (initiator, responder) = tokio::join!(
|
||||
outgoing.run(queue(b.clone())),
|
||||
incoming.run(queue(a.clone()))
|
||||
);
|
||||
assert_eq!(initiator.state, State::Complete);
|
||||
assert_eq!(initiator, responder);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -8,7 +8,7 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
||||
rustls = "0.23"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
description = "Tray application to manage a running tsunagi agent."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -16,7 +16,7 @@ tsunagi-ui = { path = "../tsunagi-ui" }
|
||||
# The agent control client and the report types: the GUI is a thin client over
|
||||
# the same local control interface the CLI uses, so it reuses these directly
|
||||
# and never re-implements the protocol.
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.2" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8" }
|
||||
# Native, lightweight GUI — no web engine. eframe re-exports egui.
|
||||
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
|
||||
# Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
|
||||
|
||||
@@ -9,16 +9,13 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Instant;
|
||||
|
||||
use eframe::egui;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use tsunagi::ipc;
|
||||
|
||||
/// How often the worker refreshes status while idle.
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(2);
|
||||
|
||||
use tsunagi_ui::client::Client;
|
||||
pub(crate) use tsunagi_ui::client::{Command, Snapshot, VipSaveResult};
|
||||
|
||||
@@ -32,6 +29,7 @@ impl Client for AgentClient {
|
||||
}
|
||||
|
||||
/// Handle the UI holds: send commands, read the latest snapshot.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AgentClient {
|
||||
tx: mpsc::UnboundedSender<Command>,
|
||||
shared: Arc<Mutex<Snapshot>>,
|
||||
@@ -105,12 +103,19 @@ async fn worker(
|
||||
ctx: egui::Context,
|
||||
) {
|
||||
refresh(&shared, &ctx).await;
|
||||
let mut tick = tokio::time::interval(POLL_INTERVAL);
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
|
||||
loop {
|
||||
let interval = {
|
||||
let snapshot = lock(&shared);
|
||||
tsunagi_ui::client::status_poll_interval(
|
||||
snapshot
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s.as_ref().ok())
|
||||
.map(Arc::as_ref),
|
||||
)
|
||||
};
|
||||
tokio::select! {
|
||||
_ = tick.tick() => {
|
||||
_ = tokio::time::sleep(interval) => {
|
||||
refresh(&shared, &ctx).await;
|
||||
}
|
||||
command = rx.recv() => {
|
||||
@@ -118,7 +123,7 @@ async fn worker(
|
||||
run(&resolve_socket(), command, &shared, &pending_copy, &ctx).await;
|
||||
refresh(&shared, &ctx).await;
|
||||
lock(&shared).busy = false;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,7 +146,7 @@ async fn refresh(shared: &Arc<Mutex<Snapshot>>, ctx: &egui::Context) {
|
||||
guard.at = Some(Instant::now());
|
||||
guard.socket = socket;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
|
||||
/// Runs one command and records its outcome.
|
||||
@@ -153,7 +158,7 @@ async fn run(
|
||||
ctx: &egui::Context,
|
||||
) {
|
||||
lock(shared).busy = true;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
|
||||
let outcome: Result<String, String> = match command {
|
||||
Command::SaveVip {
|
||||
@@ -245,6 +250,16 @@ async fn run(
|
||||
})
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
Command::StartSpeedTest { network_id, peer } => {
|
||||
ipc::start_speed_test(socket, &network_id, peer.as_deref(), false)
|
||||
.await
|
||||
.map(|_| String::new())
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
Command::StopSpeedTest { network_id } => ipc::stop_speed_test(socket, &network_id)
|
||||
.await
|
||||
.map(|_| String::new())
|
||||
.map_err(|err| err.to_string()),
|
||||
Command::Join { name, secret } => ipc::join_network(socket, &name, &secret)
|
||||
.await
|
||||
.map(|report| {
|
||||
@@ -288,7 +303,7 @@ async fn run(
|
||||
Some(outcome)
|
||||
};
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
|
||||
/// Where the GUI looks for the agent: `TSUNAGI_CONTROL_SOCKET` if set, else the
|
||||
|
||||
+146
-54
@@ -5,7 +5,7 @@
|
||||
//! and gone when the window is closed. The tray, which has to outlive the
|
||||
//! window, lives in the other process; see [`crate::tray`].
|
||||
|
||||
use std::time::Duration;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
@@ -17,12 +17,19 @@ use crate::ui::{self, UiState};
|
||||
|
||||
use tsunagi_ui::app_fonts;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Views {
|
||||
state: UiState,
|
||||
traffic: Traffic,
|
||||
}
|
||||
|
||||
/// The window's state.
|
||||
pub(crate) struct App {
|
||||
agent: AgentClient,
|
||||
state: UiState,
|
||||
/// Traffic rates derived from successive snapshots.
|
||||
traffic: Traffic,
|
||||
runtime: tokio::runtime::Handle,
|
||||
monitor: Option<crate::monitor::Monitor>,
|
||||
views: Arc<Mutex<Views>>,
|
||||
device_revision: Option<(u64, tsunagi_ui::stats::Unit, bool)>,
|
||||
/// The snapshot generation last folded into `traffic`.
|
||||
sampled: u64,
|
||||
}
|
||||
@@ -41,8 +48,10 @@ impl App {
|
||||
let agent = AgentClient::spawn(&runtime, ctx);
|
||||
Ok(Self {
|
||||
agent,
|
||||
state: UiState::default(),
|
||||
traffic: Traffic::default(),
|
||||
runtime,
|
||||
monitor: None,
|
||||
views: Default::default(),
|
||||
device_revision: None,
|
||||
sampled: 0,
|
||||
})
|
||||
}
|
||||
@@ -51,41 +60,64 @@ impl App {
|
||||
impl eframe::App for App {
|
||||
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
let snapshot = self.agent.snapshot();
|
||||
let mut views = self.views.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Views { state, traffic } = &mut *views;
|
||||
if snapshot.generation != self.sampled
|
||||
&& let (Some(Ok(report)), Some(at)) = (&snapshot.status, snapshot.at)
|
||||
{
|
||||
self.traffic.observe(report, at);
|
||||
traffic.observe(report, at);
|
||||
self.sampled = snapshot.generation;
|
||||
}
|
||||
|
||||
ui::draw(ctx, &self.agent, &mut self.state, &snapshot, &self.traffic);
|
||||
self.show_devices_windows(ctx, &snapshot);
|
||||
self.show_vip_windows(ctx, &snapshot);
|
||||
self.show_about_window(ctx, &snapshot);
|
||||
ui::draw(ctx, &self.agent, state, &snapshot, traffic);
|
||||
if state.monitor_open {
|
||||
let monitor = self.monitor.get_or_insert_with(|| {
|
||||
crate::monitor::Monitor::new(&self.runtime, self.agent.socket())
|
||||
});
|
||||
if !monitor.show(ctx, &snapshot) {
|
||||
self.monitor = None;
|
||||
state.monitor_open = false;
|
||||
}
|
||||
}
|
||||
Self::show_vip_windows(ctx, &self.agent, state, &snapshot);
|
||||
Self::show_about_window(ctx, &self.agent, state, &snapshot);
|
||||
let revision = (snapshot.generation, state.unit, snapshot.busy);
|
||||
let refresh = self.device_revision != Some(revision);
|
||||
self.device_revision = Some(revision);
|
||||
if let Some(Ok(report)) = &snapshot.status {
|
||||
state
|
||||
.open_devices
|
||||
.retain(|id| report.networks.iter().any(|n| n.network_id == *id));
|
||||
let open: Vec<_> = state.open_devices.iter().cloned().collect();
|
||||
// The embedded fallback can run the child callback immediately.
|
||||
drop(views);
|
||||
self.show_devices_windows(ctx, report, &open, refresh);
|
||||
}
|
||||
|
||||
// A secret the worker fetched for the clipboard: copy it here, on the
|
||||
// UI thread that owns the clipboard, exactly once.
|
||||
if let Some(secret) = self.agent.take_pending_copy() {
|
||||
ctx.copy_text(secret);
|
||||
}
|
||||
|
||||
// Keep ticking so fresh status is picked up.
|
||||
ctx.request_repaint_after(Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn show_vip_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
||||
fn show_vip_windows(
|
||||
ctx: &egui::Context,
|
||||
agent: &AgentClient,
|
||||
state: &mut UiState,
|
||||
snapshot: &crate::agent::Snapshot,
|
||||
) {
|
||||
let Some(Ok(report)) = &snapshot.status else {
|
||||
return;
|
||||
};
|
||||
let ids: Vec<_> = self.state.vip_windows.keys().cloned().collect();
|
||||
let ids: Vec<_> = 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);
|
||||
state.vip_windows.remove(&id);
|
||||
continue;
|
||||
};
|
||||
let Some(state) = self.state.vip_windows.get_mut(&id) else {
|
||||
let Some(editor) = state.vip_windows.get_mut(&id) else {
|
||||
continue;
|
||||
};
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
@@ -98,13 +130,13 @@ impl App {
|
||||
egui::ViewportId::from_hash_of(("vip", &id)),
|
||||
builder,
|
||||
|vctx, _| {
|
||||
let close = crate::vip::show(vctx, &self.agent, state, network, snapshot);
|
||||
let close = crate::vip::show(vctx, agent, editor, network, snapshot);
|
||||
if close {
|
||||
return false;
|
||||
}
|
||||
if vctx.input(|i| i.viewport().close_requested()) {
|
||||
if state.dirty() {
|
||||
state.request_close();
|
||||
if editor.dirty() {
|
||||
editor.request_close();
|
||||
vctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
true
|
||||
} else {
|
||||
@@ -116,13 +148,18 @@ impl App {
|
||||
},
|
||||
);
|
||||
if !keep {
|
||||
self.state.vip_windows.remove(&id);
|
||||
state.vip_windows.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Renders the About window while it is open.
|
||||
fn show_about_window(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
||||
if !self.state.about_open {
|
||||
fn show_about_window(
|
||||
ctx: &egui::Context,
|
||||
agent: &AgentClient,
|
||||
state: &mut UiState,
|
||||
snapshot: &crate::agent::Snapshot,
|
||||
) {
|
||||
if !state.about_open {
|
||||
return;
|
||||
}
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
@@ -131,7 +168,7 @@ impl App {
|
||||
.with_icon(crate::icon::window())
|
||||
.with_inner_size([560.0, 520.0])
|
||||
.with_min_inner_size([380.0, 280.0]);
|
||||
let socket = self.agent.socket();
|
||||
let socket = agent.socket();
|
||||
let keep = ctx.show_viewport_immediate(
|
||||
egui::ViewportId::from_hash_of("about"),
|
||||
builder,
|
||||
@@ -141,50 +178,57 @@ impl App {
|
||||
},
|
||||
);
|
||||
if !keep {
|
||||
self.state.about_open = false;
|
||||
state.about_open = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders one separate window per open network-devices view.
|
||||
fn show_devices_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
||||
let Some(Ok(report)) = &snapshot.status else {
|
||||
return;
|
||||
};
|
||||
let open: Vec<String> = self.state.open_devices.iter().cloned().collect();
|
||||
fn show_devices_windows(
|
||||
&self,
|
||||
ctx: &egui::Context,
|
||||
report: &Arc<tsunagi::ipc::StatusReport>,
|
||||
open: &[String],
|
||||
refresh: bool,
|
||||
) {
|
||||
for id in open {
|
||||
let Some(network) = report.networks.iter().find(|n| n.network_id == id) else {
|
||||
// The network is gone (left/forgotten); close its window.
|
||||
self.state.open_devices.remove(&id);
|
||||
let Some(index) = report.networks.iter().position(|n| n.network_id == *id) else {
|
||||
continue;
|
||||
};
|
||||
let viewport_id = egui::ViewportId::from_hash_of(("devices", &id));
|
||||
let viewport = egui::ViewportId::from_hash_of(("devices", id));
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
.with_title(devices::title(network))
|
||||
.with_title(devices::title(&report.networks[index]))
|
||||
.with_app_id(crate::icon::APP_ID)
|
||||
.with_icon(crate::icon::window())
|
||||
.with_inner_size([1440.0, 640.0])
|
||||
.with_min_inner_size([800.0, 400.0]);
|
||||
let agent = &self.agent;
|
||||
let traffic = &self.traffic;
|
||||
// The window shares the single unit setting, so its toggle and the
|
||||
// main window's stay in step.
|
||||
let unit = &mut self.state.unit;
|
||||
let confirm = &mut self.state.exit_confirm;
|
||||
let forget_confirm = &mut self.state.forget_confirm;
|
||||
let keep = ctx.show_viewport_immediate(viewport_id, builder, |vctx, _class| {
|
||||
.with_inner_size([1000., 640.])
|
||||
.with_min_inner_size([560., 400.]);
|
||||
let views = self.views.clone();
|
||||
let agent = self.agent.clone();
|
||||
let report = report.clone();
|
||||
ctx.show_viewport_deferred(viewport, builder, move |ctx, _| {
|
||||
let mut views = views.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Views { state, traffic } = &mut *views;
|
||||
let network = &report.networks[index];
|
||||
if ctx.input(|i| i.viewport().close_requested()) {
|
||||
state.open_devices.remove(&network.network_id);
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
return;
|
||||
}
|
||||
let old_unit = state.unit;
|
||||
devices::show(
|
||||
vctx,
|
||||
agent,
|
||||
unit,
|
||||
(confirm, forget_confirm),
|
||||
ctx,
|
||||
&agent,
|
||||
&mut state.unit,
|
||||
(&mut state.exit_confirm, &mut state.forget_confirm),
|
||||
network,
|
||||
&report.endpoint_id,
|
||||
traffic,
|
||||
);
|
||||
!vctx.input(|i| i.viewport().close_requested())
|
||||
if old_unit != state.unit {
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
});
|
||||
if !keep {
|
||||
self.state.open_devices.remove(&id);
|
||||
if refresh {
|
||||
ctx.request_repaint_of(viewport);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,8 +236,56 @@ impl App {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn device_frames_are_scheduled_independently_of_the_main_window() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_embed_viewports(false);
|
||||
let agent = AgentClient::spawn(runtime.handle(), ctx.clone());
|
||||
let app = App {
|
||||
agent,
|
||||
runtime: runtime.handle().clone(),
|
||||
monitor: None,
|
||||
views: Default::default(),
|
||||
sampled: 0,
|
||||
device_revision: None,
|
||||
};
|
||||
let report = Arc::new(tsunagi::ipc::StatusReport {
|
||||
networks: vec![tsunagi::ipc::NetworkReport {
|
||||
network_id: "test-id".into(),
|
||||
name: "lab".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
});
|
||||
let id = egui::ViewportId::from_hash_of(("devices", "test-id"));
|
||||
let open = ["test-id".to_string()].into_iter().collect();
|
||||
app.views.lock().unwrap().state.open_devices = open;
|
||||
let out = ctx.run(Default::default(), |ctx| {
|
||||
app.show_devices_windows(ctx, &report, &["test-id".to_string()], true);
|
||||
});
|
||||
assert!(out.viewport_output[&id].class == egui::ViewportClass::Deferred);
|
||||
let draw = out.viewport_output[&id].viewport_ui_cb.as_ref().unwrap();
|
||||
let mut input = egui::RawInput {
|
||||
viewport_id: id,
|
||||
..Default::default()
|
||||
};
|
||||
input
|
||||
.viewports
|
||||
.entry(id)
|
||||
.or_default()
|
||||
.events
|
||||
.push(egui::ViewportEvent::Close);
|
||||
let _ = ctx.run(input, |ctx| draw(ctx));
|
||||
assert!(app.views.lock().unwrap().state.open_devices.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_icons_have_an_embedded_font_in_the_app() {
|
||||
let fonts = app_fonts();
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! It is the same shape as `dist/linux/tsunagi.svg` (a disc, a ring, a dot).
|
||||
|
||||
use crate::watch::Health;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
/// Normal operation. The colour of the logo itself.
|
||||
const BLUE: [u8; 3] = [0x2f, 0x80, 0xd8];
|
||||
@@ -89,12 +90,17 @@ pub(crate) fn tray(health: Health) -> Option<tray_icon::Icon> {
|
||||
}
|
||||
|
||||
/// The icon of the application's windows.
|
||||
pub(crate) fn window() -> eframe::egui::IconData {
|
||||
eframe::egui::IconData {
|
||||
rgba: rgba(BLUE),
|
||||
width: SIZE,
|
||||
height: SIZE,
|
||||
}
|
||||
pub(crate) fn window() -> Arc<eframe::egui::IconData> {
|
||||
// egui compares viewport icons by Arc identity. Reuse both the pixels and
|
||||
// their allocation so animating a row does not update a native window icon.
|
||||
static ICON: LazyLock<Arc<eframe::egui::IconData>> = LazyLock::new(|| {
|
||||
Arc::new(eframe::egui::IconData {
|
||||
rgba: rgba(BLUE),
|
||||
width: SIZE,
|
||||
height: SIZE,
|
||||
})
|
||||
});
|
||||
Arc::clone(&ICON)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -122,6 +128,13 @@ mod tests {
|
||||
assert_eq!(body, [GREEN[0], GREEN[1], GREEN[2], 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repainting_a_devices_viewport_does_not_ask_the_os_to_replace_its_icon() {
|
||||
let viewport = || eframe::egui::ViewportBuilder::default().with_icon(window());
|
||||
let (commands, recreate) = viewport().patch(viewport());
|
||||
assert!(!recreate && commands.is_empty(), "{commands:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_state_has_its_own_colour() {
|
||||
let colours = [
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
use tsunagi_ui::about;
|
||||
mod agent;
|
||||
mod app;
|
||||
mod monitor;
|
||||
use tsunagi_ui::devices;
|
||||
mod icon;
|
||||
use tsunagi_ui::stats;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! The local IPC subscription lives exactly as long as its viewport.
|
||||
use eframe::egui;
|
||||
use std::{path::PathBuf, time::Duration};
|
||||
use tsunagi::ipc::TrafficStream;
|
||||
use tsunagi_ui::monitor::Window;
|
||||
|
||||
pub(super) struct Monitor {
|
||||
view: Window,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Monitor {
|
||||
pub fn new(runtime: &tokio::runtime::Handle, socket: PathBuf) -> Self {
|
||||
let view = Window::new(None);
|
||||
let feed = view.feed();
|
||||
let task = runtime.spawn(async move {
|
||||
let capture = async {
|
||||
let mut stream = TrafficStream::open(&socket).await?;
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
if !feed.sample(stream.snapshot().await?) {
|
||||
return Ok::<_, tsunagi::Error>(());
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Err(e) = capture.await {
|
||||
feed.error(format!("Capture stopped · {e}"));
|
||||
}
|
||||
});
|
||||
Self { view, task }
|
||||
}
|
||||
pub fn show(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) -> bool {
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
.with_title("tsunagi · Traffic monitor")
|
||||
.with_app_id(crate::icon::APP_ID)
|
||||
.with_icon(crate::icon::window())
|
||||
.with_inner_size([920., 580.])
|
||||
.with_min_inner_size([340., 320.]);
|
||||
ctx.show_viewport_immediate(
|
||||
egui::ViewportId::from_hash_of("traffic-monitor"),
|
||||
builder,
|
||||
|ctx, _| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
self.view.show(
|
||||
ui,
|
||||
snapshot.status.as_ref().and_then(|r| r.as_deref().ok()),
|
||||
snapshot.generation,
|
||||
);
|
||||
});
|
||||
!ctx.input(|i| i.viewport().close_requested())
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Drop for Monitor {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
@@ -38,9 +38,15 @@ pub(crate) fn draw(
|
||||
.weak(),
|
||||
);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(icon::INFO).on_hover_text("About").clicked() {
|
||||
if tsunagi_ui::widgets::icon_button(ui, icon::INFO, "About Tsunagi").clicked() {
|
||||
state.about_open = true;
|
||||
}
|
||||
if matches!(&snapshot.status, Some(Ok(_)))
|
||||
&& tsunagi_ui::widgets::icon_button(ui, icon::PULSE, "Traffic monitor")
|
||||
.clicked()
|
||||
{
|
||||
state.monitor_open = true;
|
||||
}
|
||||
if snapshot.busy {
|
||||
ui.add(egui::Spinner::new());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.2"
|
||||
version = "1.0.8"
|
||||
description = "Shared egui widgets for the tray and Android clients."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -9,6 +9,9 @@ repository.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
postcard.workspace = true
|
||||
rusqlite = { version = "0.40", features = ["bundled", "functions"] }
|
||||
tempfile.workspace = true
|
||||
egui = "0.31"
|
||||
egui-phosphor = "0.9"
|
||||
zeroize = "1.9"
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
Source Sans Pro Bold
|
||||
Copyright 2010, 2012, 2014 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name ‘Source’.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License,
|
||||
Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font
|
||||
creation efforts of academic and linguistic communities, and to
|
||||
provide a free and open framework in which fonts may be shared and
|
||||
improved in partnership with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply to
|
||||
any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software
|
||||
components as distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to,
|
||||
deleting, or substituting -- in part or in whole -- any of the
|
||||
components of the Original Version, by changing formats or by porting
|
||||
the Font Software to a new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed,
|
||||
modify, redistribute, and sell modified and unmodified copies of the
|
||||
Font Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components, in
|
||||
Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the
|
||||
corresponding Copyright Holder. This restriction only applies to the
|
||||
primary font name as presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created using
|
||||
the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
@@ -7,7 +7,8 @@
|
||||
use tsunagi::ipc::{PrivilegeReport, StatusReport};
|
||||
|
||||
use crate::client::Snapshot;
|
||||
use crate::format;
|
||||
use crate::{format, widgets};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
|
||||
const AUTHOR: &str = "AB <tsunagi@hexor.cy>";
|
||||
@@ -141,7 +142,7 @@ fn agent_table(ui: &mut egui::Ui, socket: Option<&str>, report: &StatusReport) {
|
||||
ui.label(if socket.is_some() {
|
||||
"can be managed (CAP_NET_ADMIN)"
|
||||
} else {
|
||||
"Android VPN service"
|
||||
"Android foreground service"
|
||||
});
|
||||
}
|
||||
PrivilegeReport::Missing(_) => {
|
||||
@@ -177,7 +178,21 @@ fn grid(ui: &mut egui::Ui, id: &str, add: impl FnOnce(&mut egui::Ui)) {
|
||||
|
||||
/// One label/value line of a table.
|
||||
fn row(ui: &mut egui::Ui, label: &str, value: impl FnOnce(&mut egui::Ui)) {
|
||||
ui.weak(label);
|
||||
match label {
|
||||
"repository" => widgets::field(ui, icon::GITHUB_LOGO, "", "Source code repository"),
|
||||
"license" => widgets::field(ui, icon::SCALES, "", "Software license"),
|
||||
"build" => widgets::field(
|
||||
ui,
|
||||
icon::CPU,
|
||||
"Build",
|
||||
"Platform, architecture and build profile",
|
||||
),
|
||||
"version" => widgets::field(ui, icon::TAG, "Version", "Tsunagi Agent software version"),
|
||||
"endpoint id" => widgets::field(ui, icon::FINGERPRINT, "", "Device endpoint ID"),
|
||||
_ => {
|
||||
ui.weak(label);
|
||||
}
|
||||
}
|
||||
value(ui);
|
||||
ui.end_row();
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Commands and observations shared by both graphical clients.
|
||||
use std::{path::PathBuf, time::Instant};
|
||||
use tsunagi::ipc::StatusReport;
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tsunagi::ipc::{SpeedPhase, SpeedReport, StatusReport};
|
||||
|
||||
/// A request from the UI to the agent.
|
||||
pub enum Command {
|
||||
@@ -62,6 +65,18 @@ pub enum Command {
|
||||
/// Selected member identity.
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Measure one peer, or all compatible online exits in sequence.
|
||||
StartSpeedTest {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Exact peer identity, or all exits when absent.
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Cancel this network's current test and any queued exits.
|
||||
StopSpeedTest {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
},
|
||||
/// Join a network, or start one already configured.
|
||||
Join {
|
||||
/// Network name.
|
||||
@@ -119,3 +134,25 @@ pub trait Client {
|
||||
/// An earlier action is waiting for an acknowledgement.
|
||||
fn busy(&self) -> bool;
|
||||
}
|
||||
|
||||
pub(crate) fn speed_running(report: &SpeedReport) -> bool {
|
||||
report.batch.is_some()
|
||||
|| report.peers.values().any(|peer| {
|
||||
matches!(
|
||||
peer.phase,
|
||||
SpeedPhase::Queued
|
||||
| SpeedPhase::Preparing
|
||||
| SpeedPhase::Download
|
||||
| SpeedPhase::Upload
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Poll more frequently while showing a short, live speed measurement.
|
||||
pub fn status_poll_interval(report: Option<&StatusReport>) -> Duration {
|
||||
if report.is_some_and(|r| r.networks.iter().any(|n| speed_running(&n.speed))) {
|
||||
Duration::from_millis(250)
|
||||
} else {
|
||||
Duration::from_secs(2)
|
||||
}
|
||||
}
|
||||
+469
-228
File diff suppressed because it is too large.
Load diff
@@ -1,60 +1,219 @@
|
||||
//! One line per member and one expanded detail block, with no horizontal scroller.
|
||||
//! A width-constrained device table for touch. Optional columns move into the
|
||||
//! expanded row before any essential columns run out of space.
|
||||
use super::{
|
||||
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text,
|
||||
devices, exit, forget_button, format, icon, rtt_text, tunnel_cell,
|
||||
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text, exit,
|
||||
forget_button, format, icon, rtt_text, speed, traffic_pair, tunnel_cell,
|
||||
};
|
||||
use crate::widgets;
|
||||
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, Vec2, pos2, vec2};
|
||||
|
||||
pub(super) fn roster(
|
||||
ui: &mut egui::Ui,
|
||||
network: &NetworkReport,
|
||||
own_id: &str,
|
||||
traffic: &Traffic,
|
||||
#[derive(Clone, Copy)]
|
||||
enum Column {
|
||||
Device,
|
||||
Speed,
|
||||
State,
|
||||
Address,
|
||||
Rtt,
|
||||
Traffic,
|
||||
Version,
|
||||
Path,
|
||||
Plot,
|
||||
}
|
||||
|
||||
impl Column {
|
||||
fn title(self, unit: Unit) -> &'static str {
|
||||
match self {
|
||||
Self::Device => "device",
|
||||
Self::Speed => speed::HEADER,
|
||||
Self::State => "State",
|
||||
Self::Address => "IPv4",
|
||||
Self::Rtt => "Data RTT",
|
||||
Self::Traffic if unit == Unit::Bytes => "bytes (TX / RX)",
|
||||
Self::Traffic => "pkts (TX / RX)",
|
||||
Self::Version => "Version",
|
||||
Self::Path => "Data path",
|
||||
Self::Plot => "Traffic / s",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn columns(
|
||||
ui: &Ui,
|
||||
width: f32,
|
||||
landscape: bool,
|
||||
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();
|
||||
members: &[Device<'_>],
|
||||
) -> Vec<(Column, f32)> {
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let measure = |s: &str| {
|
||||
let text_width = |s: &str| {
|
||||
ui.painter()
|
||||
.layout_no_wrap(s.to_owned(), font.clone(), ui.visuals().text_color())
|
||||
.layout_no_wrap(s.into(), font.clone(), Color32::WHITE)
|
||||
.size()
|
||||
.x
|
||||
};
|
||||
let rtt_x = width - (measure("9999 ms") + 18.0).min(width * 0.25);
|
||||
let ip_x = rtt_x - (measure("255.255.255.255") + 14.0).min(width * 0.40);
|
||||
let offsets = [16.0, ip_x, rtt_x];
|
||||
let size = egui::vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 8.0);
|
||||
ui.spacing_mut().item_spacing.y = 1.0;
|
||||
let (header, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "Data RTT"]) {
|
||||
ui.painter().text(
|
||||
header.left_center() + egui::vec2(x, 0.),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
title,
|
||||
font.clone(),
|
||||
ui.visuals().weak_text_color(),
|
||||
);
|
||||
let measure = |s: &str| text_width(s) + 10.;
|
||||
let disclosure = text_width(icon::CARET_RIGHT) + 3.;
|
||||
let name = 20. + text_width("device") + 3.;
|
||||
let available = width - name - disclosure;
|
||||
let small_speed = speed::PORTRAIT_WIDTH.min(width * 0.18);
|
||||
let address = measure("255.255.255.255").min(width * if landscape { 0.27 } else { 0.35 });
|
||||
let rtt = measure("Data RTT")
|
||||
.max(measure("9999 ms"))
|
||||
.min(width * if landscape { 0.15 } else { 0.22 });
|
||||
let traffic = (landscape && width >= 420.)
|
||||
.then(|| {
|
||||
// Account for both rounded values (up to 1024.0) and the unit
|
||||
// suffixes in the actual body font, independently of the live bytes.
|
||||
let digit = ui.fonts(|fonts| {
|
||||
('0'..='9')
|
||||
.max_by(|a, b| {
|
||||
fonts
|
||||
.glyph_width(&font, *a)
|
||||
.total_cmp(&fonts.glyph_width(&font, *b))
|
||||
})
|
||||
.unwrap_or('0')
|
||||
});
|
||||
let number = format!("{digit}{digit}{digit}{digit}.{digit}");
|
||||
let bytes_width = format::BYTE_UNITS.iter().fold(0.0_f32, |w, suffix| {
|
||||
w.max(measure(&format!("{number} {suffix} / {number} {suffix}")))
|
||||
});
|
||||
let floor = bytes_width.max(measure(Column::Traffic.title(unit)));
|
||||
match unit {
|
||||
Unit::Bytes => floor,
|
||||
Unit::Packets => members
|
||||
.iter()
|
||||
.filter(|m| m.online)
|
||||
.filter_map(|m| m.overlay)
|
||||
.fold(floor, |w, p| {
|
||||
w.max(measure(&traffic_pair(p.tx_packets, p.rx_packets, unit)))
|
||||
}),
|
||||
}
|
||||
})
|
||||
// An unusually long packet count can use the end of the device name,
|
||||
// but always leave room for its status icon and disclosure.
|
||||
.filter(|w| w + small_speed + 20. + text_width("…") + 3. + disclosure <= width);
|
||||
let mut spare = available - traffic.unwrap_or_default();
|
||||
let state = (landscape && width >= 510.).then(|| measure("Control only"));
|
||||
let speed = if landscape && speed::WIDTH + address + rtt + state.unwrap_or_default() <= spare {
|
||||
speed::WIDTH
|
||||
} else {
|
||||
small_speed
|
||||
};
|
||||
spare -= speed;
|
||||
let mut cols = vec![(Column::Device, 0.), (Column::Speed, speed)];
|
||||
for (column, want) in [(Column::Address, address), (Column::Rtt, rtt)] {
|
||||
if spare >= want {
|
||||
cols.push((column, want));
|
||||
spare -= want;
|
||||
}
|
||||
}
|
||||
if let Some(w) = state.filter(|w| *w <= spare) {
|
||||
cols.insert(2, (Column::State, w));
|
||||
spare -= w;
|
||||
}
|
||||
if let Some(w) = traffic {
|
||||
cols.push((Column::Traffic, w));
|
||||
for (column, desire) in [
|
||||
(Column::Version, measure("v1.0.4-rc.1")),
|
||||
(Column::Path, measure("tcp-tls direct")),
|
||||
(Column::Plot, 110.),
|
||||
] {
|
||||
if spare < desire {
|
||||
break;
|
||||
}
|
||||
cols.push((column, desire));
|
||||
spare -= desire;
|
||||
}
|
||||
}
|
||||
let other: f32 = cols.iter().map(|c| c.1).sum();
|
||||
// Reserve the disclosure arrow at the end, including on small split screens.
|
||||
cols[0].1 = (width - other - disclosure).max(0.);
|
||||
cols
|
||||
}
|
||||
|
||||
fn text_cell(ui: &Ui, rect: Rect, text: &str, font: &FontId, color: Color32) {
|
||||
let mut job = egui::text::LayoutJob::simple_singleline(text.into(), font.clone(), color);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.max_width = (rect.width() - 3.).max(0.);
|
||||
job.wrap.break_anywhere = true;
|
||||
let galley = ui.painter().layout_job(job);
|
||||
let pos = pos2(rect.left(), rect.center().y - galley.size().y / 2.);
|
||||
ui.painter_at(rect).galley(pos, galley, color);
|
||||
}
|
||||
|
||||
pub(super) fn roster(
|
||||
ui: &mut Ui,
|
||||
network: &NetworkReport,
|
||||
members: &[Device<'_>],
|
||||
traffic: &Traffic,
|
||||
unit: Unit,
|
||||
(exit, forget): (&mut Option<ExitConfirm>, &mut Option<ForgetConfirm>),
|
||||
speed: &speed::Controls<'_>,
|
||||
) {
|
||||
// An Android rotation changes the surrounding scroll area but not the selected peer.
|
||||
let id = egui::Id::new(("expanded device", &network.network_id));
|
||||
let mut selected = ui.data(|d| d.get_temp::<String>(id));
|
||||
let width = ui.available_width();
|
||||
let columns = columns(ui, width, widgets::landscape(ui.ctx()), unit, members);
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let size = vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 9.);
|
||||
ui.spacing_mut().item_spacing.y = 1.;
|
||||
let (header, _) = ui.allocate_exact_size(size, Sense::hover());
|
||||
let mut x = header.left();
|
||||
for &(column, w) in &columns {
|
||||
let mut rect = Rect::from_min_size(pos2(x, header.top()), vec2(w, size.y));
|
||||
if matches!(column, Column::Device) {
|
||||
rect.min.x += 20.;
|
||||
}
|
||||
if matches!(column, Column::Speed) {
|
||||
ui.painter_at(rect).text(
|
||||
rect.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
column.title(unit),
|
||||
font.clone(),
|
||||
ui.visuals().text_color(),
|
||||
);
|
||||
let r = ui.interact(rect, id.with("speed units"), Sense::click());
|
||||
widgets::hint(r, speed::HEADER_HINT);
|
||||
} else {
|
||||
text_cell(
|
||||
ui,
|
||||
rect,
|
||||
column.title(unit),
|
||||
&font,
|
||||
ui.visuals().text_color(),
|
||||
);
|
||||
}
|
||||
x += w;
|
||||
}
|
||||
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() {
|
||||
let (row, _) = ui.allocate_exact_size(size, Sense::hover());
|
||||
let response = ui.interact(row, id.with(member.id), Sense::click());
|
||||
let clicked = response.clicked();
|
||||
let exit_hint = if member.in_use {
|
||||
" · Selected internet exit"
|
||||
} else if member.exit_node {
|
||||
" · Offers an exit node"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let description = format!("{} · {}{exit_hint}", member.name(), member.channel_hint());
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(
|
||||
egui::WidgetType::SelectableLabel,
|
||||
response.enabled(),
|
||||
&description,
|
||||
)
|
||||
});
|
||||
widgets::hint(response, &description);
|
||||
if 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,
|
||||
2.,
|
||||
if open {
|
||||
ui.visuals().widgets.hovered.weak_bg_fill
|
||||
} else {
|
||||
@@ -62,52 +221,92 @@ pub(super) fn roster(
|
||||
},
|
||||
);
|
||||
}
|
||||
let dot = row.left_center() + egui::vec2(6., 0.);
|
||||
if member.online {
|
||||
ui.painter().circle_filled(dot, 3., exit::GOOD);
|
||||
} else {
|
||||
ui.painter().circle_stroke(
|
||||
dot,
|
||||
3.,
|
||||
egui::Stroke::new(1.0_f32, ui.visuals().weak_text_color()),
|
||||
);
|
||||
}
|
||||
let name = member.name();
|
||||
let rtt = rtt_text(member.data_rtt_ms);
|
||||
let labels = [
|
||||
name.as_str(),
|
||||
member.address.as_deref().unwrap_or("—"),
|
||||
rtt.as_str(),
|
||||
];
|
||||
let color = if member.online {
|
||||
let channel = member.channel();
|
||||
let normal = if member.online {
|
||||
ui.visuals().text_color()
|
||||
} else {
|
||||
ui.visuals().weak_text_color()
|
||||
channel.color(ui)
|
||||
};
|
||||
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);
|
||||
let mut x = row.left();
|
||||
for &(column, w) in &columns {
|
||||
let mut rect = Rect::from_min_size(pos2(x, row.top()), vec2(w, row.height()));
|
||||
x += w;
|
||||
let text = match column {
|
||||
Column::Speed => {
|
||||
speed.cell(ui, rect, member);
|
||||
continue;
|
||||
}
|
||||
Column::Device => {
|
||||
channel.paint(
|
||||
ui,
|
||||
Rect::from_center_size(rect.left_center() + vec2(9., 0.), Vec2::splat(16.)),
|
||||
);
|
||||
rect.min.x += 20.;
|
||||
if member.in_use || member.exit_node {
|
||||
ui.painter_at(rect).text(
|
||||
rect.right_center(),
|
||||
Align2::RIGHT_CENTER,
|
||||
icon::SIGN_OUT,
|
||||
font.clone(),
|
||||
if member.in_use { exit::GOOD } else { normal },
|
||||
);
|
||||
rect.max.x -= font.size + 3.;
|
||||
}
|
||||
member.name()
|
||||
}
|
||||
Column::State => channel.label().into(),
|
||||
Column::Address => member.address.as_deref().unwrap_or("—").into(),
|
||||
Column::Rtt => rtt_text(member.data_rtt_ms),
|
||||
Column::Version => member.version_label(),
|
||||
Column::Path => {
|
||||
data_path_text(member.path, member.via_name.as_deref(), member.online)
|
||||
}
|
||||
Column::Traffic => member.overlay.filter(|_| member.online).map_or_else(
|
||||
|| "—".into(),
|
||||
|peer| {
|
||||
let (tx, rx) = unit.counters(peer);
|
||||
traffic_pair(tx, rx, unit)
|
||||
},
|
||||
),
|
||||
Column::Plot => {
|
||||
if let Some(peer) = member.overlay.filter(|_| member.online) {
|
||||
let mut plot = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(rect.shrink2(vec2(2., 2.)))
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
format::sparkline(
|
||||
&mut plot,
|
||||
traffic.peer(&network.network_id, &peer.public_key),
|
||||
unit,
|
||||
rect.height() - 4.,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
text_cell(
|
||||
ui,
|
||||
rect,
|
||||
&text,
|
||||
&font,
|
||||
if matches!(column, Column::State) {
|
||||
channel.color(ui)
|
||||
} else {
|
||||
normal
|
||||
},
|
||||
);
|
||||
}
|
||||
ui.painter().text(
|
||||
row.right_center(),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
Align2::RIGHT_CENTER,
|
||||
if open {
|
||||
icon::CARET_DOWN
|
||||
} else {
|
||||
icon::CARET_RIGHT
|
||||
},
|
||||
font.clone(),
|
||||
ui.visuals().weak_text_color(),
|
||||
ui.visuals().text_color(),
|
||||
);
|
||||
if open {
|
||||
ui.push_id(member.id, |ui| {
|
||||
@@ -130,74 +329,101 @@ fn details(
|
||||
exit: &mut Option<ExitConfirm>,
|
||||
forget: &mut Option<ForgetConfirm>,
|
||||
) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak(if member.online { "online" } else { "offline" });
|
||||
if let Some(name) = &member.copy {
|
||||
format::copy_field(ui, &member.name(), name);
|
||||
}
|
||||
if let Some(address) = &member.address {
|
||||
format::copy_field(ui, address, address);
|
||||
}
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak("Endpoint ID");
|
||||
format::copy_field(ui, &format::short(member.id), member.id);
|
||||
});
|
||||
let (path, _) = data_path_text(member.path, member.via_name.as_deref(), member.online);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(path);
|
||||
tunnel_cell(ui, member);
|
||||
});
|
||||
if member.online {
|
||||
if let Some(path) = member.data_transport_detail {
|
||||
ui.label(path);
|
||||
}
|
||||
ui.label(format!(
|
||||
"Data RTT {} · Control RTT {}",
|
||||
rtt_text(member.data_rtt_ms),
|
||||
rtt_text(member.control_rtt_ms)
|
||||
));
|
||||
}
|
||||
if let Some(error) = member.data_error {
|
||||
ui.colored_label(AMBER, error);
|
||||
}
|
||||
if let Some((taken, holder)) = &member.name_taken {
|
||||
ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}."));
|
||||
}
|
||||
if let Some(peer) = member.overlay {
|
||||
let series = traffic.peer(&network.network_id, &peer.public_key);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(format!(
|
||||
"TX {} · {} pkts",
|
||||
format::bytes(peer.tx_bytes as f64),
|
||||
peer.tx_packets
|
||||
));
|
||||
ui.label(format!(
|
||||
"RX {} · {} pkts",
|
||||
format::bytes(peer.rx_bytes as f64),
|
||||
peer.rx_packets
|
||||
));
|
||||
ui.weak(format::series_rate(series, unit));
|
||||
egui::Frame::new()
|
||||
.fill(ui.visuals().faint_bg_color)
|
||||
.inner_margin(egui::Margin::symmetric(10, 8))
|
||||
.show(ui, |ui| {
|
||||
ui.set_min_width(ui.available_width());
|
||||
ui.spacing_mut().item_spacing.y = 4.0;
|
||||
ui.columns(2, |cols| {
|
||||
cols[0].small("Data path");
|
||||
let path = data_path_text(member.path, member.via_name.as_deref(), member.online);
|
||||
cols[0].horizontal_wrapped(|ui| {
|
||||
ui.label(path);
|
||||
if member.online {
|
||||
tunnel_cell(ui, member);
|
||||
}
|
||||
});
|
||||
cols[1].small("Tsunagi version");
|
||||
cols[1].label(member.agent_version.unwrap_or("Unknown"));
|
||||
});
|
||||
if let Some(path) = member.data_transport_detail {
|
||||
ui.add(egui::Label::new(path).wrap());
|
||||
}
|
||||
if member.online {
|
||||
ui.columns(2, |cols| {
|
||||
cols[0].small("Data RTT");
|
||||
cols[0].label(rtt_text(member.data_rtt_ms));
|
||||
cols[1].small("Control RTT");
|
||||
cols[1].label(rtt_text(member.control_rtt_ms));
|
||||
});
|
||||
}
|
||||
if let Some(peer) = member.overlay.filter(|_| member.online) {
|
||||
ui.separator();
|
||||
let (tx, rx) = unit.counters(peer);
|
||||
let sent_color = ui.visuals().hyperlink_color;
|
||||
ui.columns(2, |cols| {
|
||||
for (col, arrow, caption, count, color) in [
|
||||
(0, icon::ARROW_UP, "Sent", tx, sent_color),
|
||||
(1, icon::ARROW_DOWN, "Received", rx, exit::GOOD),
|
||||
] {
|
||||
cols[col].horizontal(|ui| {
|
||||
ui.colored_label(color, arrow);
|
||||
ui.label(caption);
|
||||
});
|
||||
let value = format::amount(count, unit);
|
||||
let value = match unit {
|
||||
Unit::Packets => format!("{value} pkts"),
|
||||
Unit::Bytes => value,
|
||||
};
|
||||
let size = cols[col].text_style_height(&egui::TextStyle::Body) + 2.0;
|
||||
cols[col].label(egui::RichText::new(value).size(size).strong());
|
||||
}
|
||||
});
|
||||
format::sparkline(
|
||||
ui,
|
||||
traffic.peer(&network.network_id, &peer.public_key),
|
||||
unit,
|
||||
28.0,
|
||||
);
|
||||
}
|
||||
ui.separator();
|
||||
ui.columns(2, |cols| {
|
||||
cols[0].small("Endpoint ID");
|
||||
format::copy_field(&mut cols[0], &format::short(member.id), member.id);
|
||||
cols[1].small("IPv4");
|
||||
if let Some(address) = &member.address {
|
||||
format::copy_field(&mut cols[1], address, address);
|
||||
} else {
|
||||
cols[1].weak("—");
|
||||
}
|
||||
});
|
||||
if let Some(name) = &member.copy {
|
||||
format::copy_field(ui, name, name);
|
||||
}
|
||||
if let Some(error) = member.data_error {
|
||||
ui.colored_label(member.channel().color(ui), error);
|
||||
}
|
||||
if let Some((taken, holder)) = &member.name_taken {
|
||||
ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}."));
|
||||
}
|
||||
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);
|
||||
});
|
||||
format::sparkline(ui, series, unit, 22.);
|
||||
}
|
||||
if (member.exit_node || member.in_use)
|
||||
&& ui
|
||||
.button(if member.in_use {
|
||||
"Stop using exit node"
|
||||
} else {
|
||||
"Use exit node"
|
||||
})
|
||||
.clicked()
|
||||
{
|
||||
*exit = Some(ExitConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: member.id.into(),
|
||||
name: member.name(),
|
||||
stop: member.in_use,
|
||||
main: false,
|
||||
});
|
||||
}
|
||||
forget_button(ui, member, network, forget);
|
||||
ui.separator();
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
//! The same speed control occupies one fixed cell throughout a measurement.
|
||||
use super::{Client, Command, Device, NetworkReport, format, icon, widgets};
|
||||
use crate::client::speed_running;
|
||||
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, pos2, vec2};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tsunagi::ipc::{SpeedPeerReport, SpeedPhase, SpeedRate};
|
||||
|
||||
pub(super) const WIDTH: f32 = 108.;
|
||||
pub(super) const PORTRAIT_WIDTH: f32 = 56.;
|
||||
pub(super) const HEADER: &str = "Mbit/s";
|
||||
pub(super) const HEADER_HINT: &str = "Peer speed test · download / upload in megabits per second";
|
||||
|
||||
pub(super) struct Controls<'a> {
|
||||
network: &'a NetworkReport,
|
||||
client: &'a dyn Client,
|
||||
running: bool,
|
||||
}
|
||||
|
||||
impl<'a> Controls<'a> {
|
||||
pub(super) fn new(network: &'a NetworkReport, client: &'a dyn Client) -> Self {
|
||||
Self {
|
||||
network,
|
||||
client,
|
||||
running: speed_running(&network.speed),
|
||||
}
|
||||
}
|
||||
|
||||
fn capable(&self, id: &str) -> bool {
|
||||
self.network.speed.capable.iter().any(|peer| peer == id)
|
||||
}
|
||||
|
||||
pub(super) fn toolbar(&self, ui: &mut Ui) {
|
||||
let (label, help, available) = if self.running {
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(250));
|
||||
let label = self.network.speed.batch.map_or_else(
|
||||
|| format!("{} Stop test", icon::STOP_CIRCLE),
|
||||
|batch| {
|
||||
format!(
|
||||
"{} Stop {}/{}",
|
||||
icon::STOP_CIRCLE,
|
||||
batch.done,
|
||||
batch.total
|
||||
)
|
||||
},
|
||||
);
|
||||
(
|
||||
label,
|
||||
"Stop this speed test and skip any queued exits.",
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
let available = self.network.active
|
||||
&& self
|
||||
.network
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.exit_node && self.capable(&p.endpoint_id));
|
||||
(
|
||||
format!("{} Test exits", icon::GAUGE),
|
||||
if available {
|
||||
"Test each compatible online exit node in this network, one at a time."
|
||||
} else {
|
||||
"No online exit in this network supports peer speed tests."
|
||||
},
|
||||
available,
|
||||
)
|
||||
};
|
||||
// Leave room for the batch count before starting. A wrapping toolbar
|
||||
// must keep the same height when the button becomes Stop.
|
||||
let width = ui
|
||||
.painter()
|
||||
.layout_no_wrap(
|
||||
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
|
||||
egui::TextStyle::Button.resolve(ui.style()),
|
||||
ui.visuals().text_color(),
|
||||
)
|
||||
.size()
|
||||
.x
|
||||
+ 2. * ui.spacing().button_padding.x;
|
||||
let button = ui.add_enabled(
|
||||
available && !self.client.busy(),
|
||||
egui::Button::new(label).min_size(vec2(width, 0.)),
|
||||
);
|
||||
if widgets::hint(button, help).clicked() {
|
||||
let network_id = self.network.network_id.clone();
|
||||
let command = if self.running {
|
||||
Command::StopSpeedTest { network_id }
|
||||
} else {
|
||||
Command::StartSpeedTest {
|
||||
network_id,
|
||||
peer: None,
|
||||
}
|
||||
};
|
||||
self.client.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cell(&self, ui: &mut Ui, rect: Rect, peer: &Device<'_>) {
|
||||
if !ui.is_rect_visible(rect) {
|
||||
return;
|
||||
}
|
||||
let reading = self.network.speed.peers.get(peer.id);
|
||||
let supported = self.capable(peer.id);
|
||||
let ready = self.network.active && peer.online && supported;
|
||||
let can_start = ready && !self.running && !self.client.busy();
|
||||
let id = ui.make_persistent_id(("test peer speed", &self.network.network_id, peer.id));
|
||||
let r = ui.interact(rect, id, Sense::click());
|
||||
let r = if can_start {
|
||||
r.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
} else {
|
||||
r
|
||||
};
|
||||
let v = ui.visuals();
|
||||
let color = if ready {
|
||||
v.hyperlink_color
|
||||
} else {
|
||||
v.weak_text_color()
|
||||
};
|
||||
if can_start && (r.hovered() || r.has_focus()) {
|
||||
ui.painter()
|
||||
.rect_filled(rect.shrink(1.), 3., v.widgets.hovered.weak_bg_fill);
|
||||
}
|
||||
paint_reading(ui, rect, reading, ready, color);
|
||||
let hint = tooltip(peer, reading, supported, self.running);
|
||||
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, can_start, &hint));
|
||||
if widgets::hint(r, &hint).clicked() && can_start {
|
||||
self.client.send(Command::StartSpeedTest {
|
||||
network_id: self.network.network_id.clone(),
|
||||
peer: Some(peer.id.into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_reading(
|
||||
ui: &Ui,
|
||||
rect: Rect,
|
||||
reading: Option<&SpeedPeerReport>,
|
||||
ready: bool,
|
||||
color: Color32,
|
||||
) {
|
||||
let painter = ui.painter_at(rect);
|
||||
let Some(test) = reading else {
|
||||
let glyph = if ready { icon::GAUGE } else { "—" };
|
||||
painter.text(
|
||||
rect.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
glyph,
|
||||
FontId::proportional(16.),
|
||||
color,
|
||||
);
|
||||
return;
|
||||
};
|
||||
let v = ui.visuals();
|
||||
let small = egui::TextStyle::Small.resolve(ui.style());
|
||||
let label = |s: &str, ink: Color32| {
|
||||
painter.text(rect.center(), Align2::CENTER_CENTER, s, small.clone(), ink);
|
||||
};
|
||||
match test.phase {
|
||||
SpeedPhase::Queued => label("Queued", v.weak_text_color()),
|
||||
SpeedPhase::Preparing => {
|
||||
label("Starting", color);
|
||||
activity(ui, rect, color);
|
||||
}
|
||||
SpeedPhase::Failed(_) => label(&format!("{} Retry", icon::WARNING), v.error_fg_color),
|
||||
SpeedPhase::Cancelled => label(&format!("{} Retry", icon::ARROW_CLOCKWISE), color),
|
||||
SpeedPhase::Download | SpeedPhase::Upload | SpeedPhase::Done => {
|
||||
// Reserve the same two slots for idle, live and completed readings.
|
||||
let inline = rect.width() >= WIDTH - 1.;
|
||||
let font = if inline {
|
||||
small.clone()
|
||||
} else {
|
||||
FontId::proportional(small.size.min(rect.height() * 0.46))
|
||||
};
|
||||
for (offset, arrow, rate, phase) in [
|
||||
(-0.23, icon::ARROW_DOWN, test.down, SpeedPhase::Download),
|
||||
(0.23, icon::ARROW_UP, test.up, SpeedPhase::Upload),
|
||||
] {
|
||||
let measuring = test.phase == phase;
|
||||
let value = rate.map_or_else(
|
||||
|| if measuring { "…" } else { "—" }.to_owned(),
|
||||
compact_rate,
|
||||
);
|
||||
let ink = if measuring {
|
||||
v.hyperlink_color
|
||||
} else if rate.is_some() {
|
||||
v.text_color()
|
||||
} else {
|
||||
v.weak_text_color()
|
||||
};
|
||||
painter.text(
|
||||
rect.center()
|
||||
+ if inline {
|
||||
vec2(rect.width() * offset, 0.)
|
||||
} else {
|
||||
vec2(0., rect.height() * offset)
|
||||
},
|
||||
Align2::CENTER_CENTER,
|
||||
format!("{arrow} {value}"),
|
||||
font.clone(),
|
||||
ink,
|
||||
);
|
||||
}
|
||||
if test.phase != SpeedPhase::Done {
|
||||
activity(ui, rect, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A moving mark indicates an active phase even before the first receiver
|
||||
// report arrives. Repaint only visible, active cells.
|
||||
fn activity(ui: &Ui, rect: Rect, color: Color32) {
|
||||
let bar = rect.shrink2(vec2(4., 1.));
|
||||
let width = bar.width() * 0.24;
|
||||
let t = ui.input(|i| (i.time % 1.) as f32);
|
||||
let x = bar.left() + (bar.width() - width) * (t * std::f32::consts::PI).sin().powi(2);
|
||||
ui.painter_at(rect).line_segment(
|
||||
[pos2(x, bar.bottom()), pos2(x + width, bar.bottom())],
|
||||
(1., color),
|
||||
);
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(80));
|
||||
}
|
||||
|
||||
// Round positive lower bounds down so the displayed minimum is supported by
|
||||
// the measurement, including near a precision or unit boundary.
|
||||
fn detailed_rate(rate: SpeedRate, divisor: f64) -> String {
|
||||
let value = rate.bps as f64 / divisor;
|
||||
if rate.lower_bound {
|
||||
format!("at least {:.2}", (value * 100.).floor() / 100.)
|
||||
} else {
|
||||
format!("{value:.2}")
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_rate(rate: SpeedRate) -> String {
|
||||
let (unit, precision, suffix) = match rate.bps {
|
||||
0 => return "0".into(),
|
||||
1..10_000 => return "<0.01".into(),
|
||||
10_000..1_000_000 => (1e6, 2, ""),
|
||||
1_000_000..10_000_000 => (1e6, 1, ""),
|
||||
10_000_000..10_000_000_000 => (1e6, 0, ""),
|
||||
_ => (1e9, 0, "k"),
|
||||
};
|
||||
format!("{:.precision$}{suffix}", rate.bps as f64 / unit)
|
||||
}
|
||||
|
||||
fn tooltip(
|
||||
peer: &Device<'_>,
|
||||
test: Option<&SpeedPeerReport>,
|
||||
supported: bool,
|
||||
running: bool,
|
||||
) -> String {
|
||||
let mut hint = format!("Speed to {}", peer.name());
|
||||
if let Some(test) = test {
|
||||
let phase = match &test.phase {
|
||||
SpeedPhase::Queued => "Waiting for the previous exit",
|
||||
SpeedPhase::Preparing => "Opening the data channel",
|
||||
SpeedPhase::Download => "Measuring download",
|
||||
SpeedPhase::Upload => "Measuring upload",
|
||||
SpeedPhase::Done => "Completed",
|
||||
SpeedPhase::Failed(error) => error.as_str(),
|
||||
SpeedPhase::Cancelled => "Stopped",
|
||||
};
|
||||
hint.push_str(&format!("\n{phase}"));
|
||||
for (label, rate) in [("Download", test.down), ("Upload", test.up)] {
|
||||
if let Some(rate) = rate {
|
||||
let (divisor, suffix) = if rate.bps < 1_000_000 {
|
||||
(1000., "kbit/s")
|
||||
} else {
|
||||
(1e6, "Mbit/s")
|
||||
};
|
||||
hint.push_str(&format!(
|
||||
"\n{label} {} {suffix}",
|
||||
detailed_rate(rate, divisor)
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(path) = &test.path {
|
||||
hint.push_str(&format!("\nPath at start {path}"));
|
||||
}
|
||||
if test.elapsed_ms > 0 || test.bytes > 0 {
|
||||
hint.push_str(&format!(
|
||||
"\n{} transferred in {:.1} s",
|
||||
format::bytes(test.bytes as f64),
|
||||
f64::from(test.elapsed_ms) / 1000.
|
||||
));
|
||||
}
|
||||
if test.measured_at_unix_secs > 0
|
||||
&& matches!(
|
||||
test.phase,
|
||||
SpeedPhase::Done | SpeedPhase::Failed(_) | SpeedPhase::Cancelled
|
||||
)
|
||||
&& let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH)
|
||||
{
|
||||
let age = now.as_secs().saturating_sub(test.measured_at_unix_secs);
|
||||
let age = if age < 60 {
|
||||
format!("{age} s")
|
||||
} else if age < 3600 {
|
||||
format!("{} min", age / 60)
|
||||
} else {
|
||||
format!("{} h", age / 3600)
|
||||
};
|
||||
hint.push_str(&format!("\nMeasured {age} ago"));
|
||||
}
|
||||
}
|
||||
if !peer.online {
|
||||
hint.push_str("\nPeer is offline.");
|
||||
} else if !supported {
|
||||
hint.push_str("\nNo compatible speed-test session with this peer.");
|
||||
} else if !running {
|
||||
hint.push_str(if test.is_some() {
|
||||
"\nTap to test again."
|
||||
} else {
|
||||
"\nTap to test download and upload."
|
||||
});
|
||||
}
|
||||
hint
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
use tsunagi::ipc::{PeerReport, SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate};
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClientLog(RefCell<Vec<Command>>);
|
||||
|
||||
impl Client for ClientLog {
|
||||
fn send(&self, cmd: Command) {
|
||||
self.0.borrow_mut().push(cmd);
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn network() -> NetworkReport {
|
||||
let mut n = NetworkReport {
|
||||
active: true,
|
||||
name: "mesh".into(),
|
||||
network_id: "network".into(),
|
||||
..Default::default()
|
||||
};
|
||||
for (id, offers_exit) in [("alice", true), ("ben", false), ("older", true)] {
|
||||
n.peers.push(PeerReport {
|
||||
endpoint_id: id.into(),
|
||||
hostname: Some(id.into()),
|
||||
exit_node: offers_exit,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
n.speed.capable = vec!["alice".into(), "ben".into()];
|
||||
n
|
||||
}
|
||||
|
||||
fn reading(phase: SpeedPhase) -> SpeedPeerReport {
|
||||
SpeedPeerReport {
|
||||
phase,
|
||||
down: Some(SpeedRate {
|
||||
bps: 125_000_000,
|
||||
lower_bound: false,
|
||||
}),
|
||||
up: Some(SpeedRate {
|
||||
bps: 35_995_000,
|
||||
lower_bound: true,
|
||||
}),
|
||||
bytes: 1_900_000,
|
||||
elapsed_ms: 600,
|
||||
path: Some("wg direct".into()),
|
||||
measured_at_unix_secs: 0,
|
||||
}
|
||||
}
|
||||
|
||||
struct Screen {
|
||||
ctx: egui::Context,
|
||||
width: f32,
|
||||
log: ClientLog,
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
fn new(width: f32, mobile: bool) -> Self {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
if mobile {
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
}
|
||||
Self {
|
||||
ctx,
|
||||
width,
|
||||
log: ClientLog::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(&self, n: &NetworkReport, events: Vec<egui::Event>) -> egui::FullOutput {
|
||||
self.frame_at(n, None, events)
|
||||
}
|
||||
|
||||
fn frame_at(
|
||||
&self,
|
||||
n: &NetworkReport,
|
||||
time: Option<f64>,
|
||||
events: Vec<egui::Event>,
|
||||
) -> egui::FullOutput {
|
||||
self.ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(self.width, 650.),
|
||||
)),
|
||||
events,
|
||||
time,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
show(
|
||||
ctx,
|
||||
&self.log,
|
||||
&mut Unit::Bytes,
|
||||
(&mut None, &mut None),
|
||||
n,
|
||||
"self",
|
||||
&Traffic::default(),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn click(&self, n: &NetworkReport, pos: egui::Pos2) {
|
||||
for pressed in [true, false] {
|
||||
self.frame(
|
||||
n,
|
||||
vec![
|
||||
egui::Event::PointerMoved(pos),
|
||||
egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn positions(out: &egui::FullOutput, find: impl Fn(&str) -> bool) -> Vec<egui::Pos2> {
|
||||
out.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if find(t.galley.text()) => {
|
||||
Some(t.pos + t.galley.rect.center().to_vec2())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_and_completed_readings_keep_the_same_row_and_tapping_retests_a_non_exit_peer() {
|
||||
for (width, mobile) in [(320., true), (860., true), (1440., false)] {
|
||||
let mut n = network();
|
||||
let s = Screen::new(width, mobile);
|
||||
s.frame(&n, vec![]);
|
||||
let idle = s.frame(&n, vec![]);
|
||||
let gauges = positions(&idle, |s| s == icon::GAUGE);
|
||||
assert_eq!(gauges.len(), 2, "capable peers only");
|
||||
let button = gauges[1];
|
||||
let peer_pos = positions(&idle, |s| s == "ben")[0];
|
||||
let after = positions(&idle, |s| s == "older")[0];
|
||||
s.click(&n, button);
|
||||
for phase in [
|
||||
SpeedPhase::Preparing,
|
||||
SpeedPhase::Download,
|
||||
SpeedPhase::Upload,
|
||||
SpeedPhase::Done,
|
||||
] {
|
||||
let live_down = phase == SpeedPhase::Download;
|
||||
let mut report = reading(phase);
|
||||
if live_down {
|
||||
report.down = Some(SpeedRate {
|
||||
bps: 19_900_000,
|
||||
lower_bound: false,
|
||||
});
|
||||
report.up = None;
|
||||
}
|
||||
n.speed.peers.insert("ben".into(), report);
|
||||
let out = s.frame(&n, vec![]);
|
||||
if live_down {
|
||||
assert!(!positions(&out, |s| s == format!("{} 20", icon::ARROW_DOWN)).is_empty());
|
||||
assert!(!positions(&out, |s| s == format!("{} —", icon::ARROW_UP)).is_empty());
|
||||
}
|
||||
assert_eq!(positions(&out, |s| s == "ben"), [peer_pos]);
|
||||
assert_eq!(positions(&out, |s| s == "older"), [after]);
|
||||
assert!(
|
||||
positions(&out, |s| s == "Endpoint ID").is_empty(),
|
||||
"speed tap expanded a row"
|
||||
);
|
||||
}
|
||||
let done = s.frame(&n, vec![]);
|
||||
let down_text = format!("{} 125", icon::ARROW_DOWN);
|
||||
let up_text = format!("{} 36", icon::ARROW_UP);
|
||||
for value in [&down_text, &up_text] {
|
||||
let lines = positions(&done, |s| s == value);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!((lines[0].x - button.x).abs() < 31.);
|
||||
assert!((lines[0].y - button.y).abs() < 12.);
|
||||
assert!(lines[0].x < width);
|
||||
}
|
||||
let down = positions(&done, |s| s == down_text)[0];
|
||||
let up = positions(&done, |s| s == up_text)[0];
|
||||
if width > 650. {
|
||||
assert!(
|
||||
(down.y - up.y).abs() < 1. && down.x < up.x,
|
||||
"wide screens show both rates on one line"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
(down.x - up.x).abs() < 1. && down.y < up.y,
|
||||
"portrait shows a rate on each line"
|
||||
);
|
||||
}
|
||||
s.click(&n, button);
|
||||
let log = s.log.0.borrow();
|
||||
assert_eq!(log.len(), 2);
|
||||
assert!(log.iter().all(|cmd| matches!(cmd, Command::StartSpeedTest { network_id, peer: Some(peer) } if network_id == "network" && peer == "ben")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_press_explains_a_partial_result_without_requesting_another_test() {
|
||||
let s = Screen::new(360., true);
|
||||
let mut n = network();
|
||||
n.speed.peers.insert(
|
||||
"ben".into(),
|
||||
reading(SpeedPhase::Failed("Peer timed out".into())),
|
||||
);
|
||||
let draw = |time, events| s.frame_at(&n, Some(time), events);
|
||||
draw(0., vec![]);
|
||||
let pos = positions(&draw(0.1, vec![]), |s| s.contains("Retry"))[0];
|
||||
let touch = |phase| egui::Event::Touch {
|
||||
device_id: egui::TouchDeviceId(0),
|
||||
id: egui::TouchId(1),
|
||||
phase,
|
||||
pos,
|
||||
force: None,
|
||||
};
|
||||
let pointer = |pressed| egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
};
|
||||
draw(
|
||||
0.2,
|
||||
vec![
|
||||
touch(egui::TouchPhase::Start),
|
||||
egui::Event::PointerMoved(pos),
|
||||
pointer(true),
|
||||
],
|
||||
);
|
||||
draw(1.2, vec![]);
|
||||
let held = draw(1.3, vec![]);
|
||||
let tips = positions(&held, |text| {
|
||||
text.contains("Peer timed out")
|
||||
&& text.contains("at least 35.99 Mbit/s")
|
||||
&& text.contains("Path at start wg direct")
|
||||
});
|
||||
assert_eq!(tips.len(), 1);
|
||||
draw(
|
||||
1.4,
|
||||
vec![
|
||||
touch(egui::TouchPhase::End),
|
||||
pointer(false),
|
||||
egui::Event::PointerGone,
|
||||
],
|
||||
);
|
||||
assert!(s.log.0.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_batch_requires_an_online_capable_exit_and_stops_in_its_own_network() {
|
||||
let mut n = network();
|
||||
let s = Screen::new(360., true);
|
||||
s.frame(&n, vec![]);
|
||||
let start = positions(&s.frame(&n, vec![]), |s| s.contains("Test exits"))[0];
|
||||
n.peers[0].exit_node = false;
|
||||
s.frame(&n, vec![]);
|
||||
s.click(&n, start);
|
||||
assert!(s.log.0.borrow().is_empty());
|
||||
n.peers[0].exit_node = true;
|
||||
s.frame(&n, vec![]);
|
||||
s.click(&n, start);
|
||||
n.speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
|
||||
let batch = s.frame(&n, vec![]);
|
||||
assert!(!positions(&batch, |s| s == format!("{} Stop 0/1", icon::STOP_CIRCLE)).is_empty());
|
||||
let font = egui::TextStyle::Button.resolve(&s.ctx.style());
|
||||
assert!(s.ctx.fonts(|f| f.has_glyphs(&font, icon::STOP_CIRCLE)));
|
||||
s.click(&n, positions(&batch, |s| s.contains("Stop"))[0]);
|
||||
assert!(matches!(s.log.0.borrow().as_slice(), [
|
||||
Command::StartSpeedTest { network_id, peer: None },
|
||||
Command::StopSpeedTest { network_id: stopped },
|
||||
] if network_id == "network" && stopped == network_id));
|
||||
}
|
||||
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user