Compare commits

...
5 Commits
Author SHA1 Message Date
Aleksandr Bogomiakov 6a0a87e76c Keep the selected exit ready and report idle tunnels in 1.0.5
Read the exit network and endpoint from the published routing choice.
Start a normal WireGuard exchange at 120 seconds for that tunnel even
when idle. BoringTun keeps the current key usable during the exchange
and owns retry and expiry. Switching or clearing the route also moves
or removes the renewal policy.

Show Idle in the tray, on Android and in CLI status after 30 seconds
without IP traffic on a previously established tunnel. Keep key changes
and keepalives out of activity, and keep waiting packets, missing paths
and transport errors visible. Preserve queued flow tags when a native
keepalive occupies a slot and drain pending IP on key confirmation.

Bump the local status IPC to 26 and update the workspace, Android and
Nix versions. Upgrade the daemon and desktop clients together. Mesh
protocols, key lifetimes and persistent storage remain compatible.

On macOS arm64 the initial workspace run passed 602 tests. A separate
181-second two-agent test observed renewal only in the selected mesh
and delivered its first internet packet after idle. Formatting and
strict workspace Clippy passed on the release sources. The maintainer
requested publication without waiting for another full test run.
2026-11-25 16:57:10 +02:00
Aleksandr Bogomiakov e3e6089d0b Adapt mesh views to phone rotation and toggle the exit from Quick Settings
Use the available width for the Android device table, keeping individual
peers expandable and their full details reachable in both orientations.
Show network selection and settings side by side in landscape and reuse
the VIP editor with a compact toolbar and width-aware backend columns.
Retain the selected network, expanded peer, traffic unit and VIP draft
across rotation.

Show data-channel readiness consistently in the tray and on Android.
Distinguish an establishing channel, a disabled data plane, an offline
peer and a transport failure. Use an animated arc for visible waiting
peers. Explain Phosphor controls on hover, focus and long press, and
provide a masked-by-default reveal button in the shared secret field.

Store the last confirmed exit network and endpoint in Android's private
preferences. A Quick Settings tap disconnects that selection or restores
the exact peer through the existing agent. First use opens the chooser.
On a cold start, wait for an authenticated exit offer outside the command
loop. Check the current selection again before changing the route. Only
changed exit offers wake roster subscribers. Wire formats, software
version and mesh identity storage remain compatible.

On macOS arm64, cargo fmt and strict workspace Clippy passed. The locked
workspace suite passed 598 tests with four opt-in tests ignored. Built the
tray, the ARM64 debug APK and its test APK. All three instrumentation tests
passed on an Android API 37 emulator. Opened the chooser from the actual
Quick Settings tile, rotated the activity and inspected rendered device
lists with ready, waiting, failed and offline peers. Physical phones and
native Linux and Windows builds were not exercised.
2026-11-25 15:38:10 +02:00
Aleksandr Bogomiakov 50c0ecea45 Reduce idle mesh traffic and Android background work for 1.0.4
A phone keeping its mesh online was paying for two data-path probe exchanges
per WG or AWG link, repeated control snapshots, and a full Android status
and DNS rebuild every two seconds while the activity was closed.

Let a timely, authenticated reply of the requested size on the physical
carrier satisfy its native delivery check. Keep the full-sized probe, RTT
window, loss thresholds, roaming, and independent silence detection. Resume
native probes when shared confirmations go stale and answer both probe
formats throughout the lifetime of the pair.

Index the latest signed objects once per network. Each reliable session
sends a full snapshot on connect and advances its cursor only when a frame
enters its send queue. Reopen the affected stream if a replica cannot
persist a received update. Send canonical peer hints in bounded batches,
publish changed edges immediately, and refresh reachability ahead of its
90-second expiry. The scheduling revisions live in memory and peers use
the existing wire formats and database schema.

Drive Android DNS and selected-exit notifications from coalesced roster
changes. The visible activity requests fresh counters, reusing the current
DNS zones. Set the workspace, Android, and Nix package versions to 1.0.4.

Formatting and strict workspace Clippy passed on macOS arm64. The locked
workspace suite passed 594 tests with four opt-in checks ignored. Both
Android instrumentation tests passed on an API 37 arm64 emulator. Tested
mixed 1.0.3/1.0.4 pairs on WG and AWG. In a 30-second idle WG comparison,
one endpoint's combined UDP bytes fell from 220950 to 138596 and its
control messages from 24 to 2. Physical phone discharge and native Linux
and Windows runs remain unverified.
2026-11-25 15:04:07 +02:00
Aleksandr Bogomiakov 8c4c2fa34e Fold network cards and show which peer carries exit traffic
Start the tray and Android overviews with each network folded under its
bold name. Keep the selected exit, its host name and its sent and received
byte totals visible. Put VIP beside Copy secret and Show devices.

Default to bytes and make the unit switch update the desktop traffic
column, totals, rates and plots together. Open the devices window at
1000 points wide and bound the network and per-peer plots. Use both sides
of the phone detail view for transport, latency, version and traffic.

Attach counters to the current network and exit peer. Count off-mesh IP
bytes after carrier acceptance and replies after local interface delivery.
Changing the selection starts new totals. Ordinary mesh traffic to the
same peer and rejected packets stay out of the exit counters.

Advertise the agent release as an optional bounded trailer on an
authenticated control v8 announcement. Older readers can ignore it and
older peers display an unknown version. Release labels live for the
session and do not participate in authentication or wire negotiation.
The new status fields require local IPC v25, so update the daemon, CLI
and tray together. Existing mesh identities and databases need no migration.

On Android, request system interface consent on the first app launch.
Respect an explicit stop or declined consent across launches. Start
Tsunagi Agent re-enables automatic startup.

Checked formatting and strict workspace Clippy on macOS arm64. The full
locked workspace suite passed 588 tests with four opt-in tests ignored.
Built the tray and Android debug APKs. Both instrumentation tests passed
on an Android 37 arm64 emulator, including app startup, stop and restart.
Checked the first-run permission prompt and the rendered phone and desktop
layouts. Native Linux and Windows tests were not run on this host.
2026-11-25 14:33:50 +02:00
Aleksandr Bogomiakov f9f67f88b1 Prepare the 1.0.3 release
Promote the confirmed release candidate to 1.0.3 across the workspace packages, internal dependency requirements, lockfile, Android app and Nix package. The change is limited to release metadata. Tests were skipped at the maintainer's request.
2026-11-25 04:22:24 +02:00
78 changed files with 3975 additions and 1016 deletions

No files matched your search

Generated
+10 -10
View File
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tsunagi"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"anstream",
"anstyle",
@@ -6320,7 +6320,7 @@ dependencies = [
[[package]]
name = "tsunagi-android"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"bytes",
"egui",
@@ -6344,7 +6344,7 @@ dependencies = [
[[package]]
name = "tsunagi-awg"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"bytes",
"iroh",
@@ -6359,7 +6359,7 @@ dependencies = [
[[package]]
name = "tsunagi-core"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"arc-swap",
"bytes",
@@ -6402,7 +6402,7 @@ dependencies = [
[[package]]
name = "tsunagi-runtime"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"tokio",
"tracing",
@@ -6415,7 +6415,7 @@ dependencies = [
[[package]]
name = "tsunagi-tcp-tls"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"bytes",
"caps",
@@ -6435,7 +6435,7 @@ dependencies = [
[[package]]
name = "tsunagi-tray"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"eframe",
"egui-phosphor",
@@ -6451,7 +6451,7 @@ dependencies = [
[[package]]
name = "tsunagi-ui"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"egui",
"egui-phosphor",
@@ -6461,7 +6461,7 @@ dependencies = [
[[package]]
name = "tsunagi-wg-quic"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"boringtun",
"bytes",
@@ -6488,7 +6488,7 @@ dependencies = [
[[package]]
name = "tsunagi-wireguard"
version = "1.0.3-rc1"
version = "1.0.5"
dependencies = [
"boringtun",
"bytes",
+5 -2
View File
@@ -141,8 +141,11 @@ 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.
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
+6 -2
View File
@@ -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
+1 -1
View File
@@ -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.3-rc1')
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.5')
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()
}
}
}
+8
View File
@@ -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")
@@ -23,6 +23,8 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
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
@@ -34,7 +36,9 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
override fun onDrawFrame(gl: GL10?) {
val delay = Native.draw(this, widthPx, heightPx, density)
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))
}
@@ -58,8 +62,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,17 +24,20 @@ 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 onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
@@ -75,17 +78,21 @@ class MeshVpn : VpnService() {
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 +100,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 +124,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 +200,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)
}
@@ -10,10 +10,11 @@ internal object Native {
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 surface()
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long
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>
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-android"
version = "1.0.3-rc1"
version = "1.0.5"
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.3-rc1" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.5" }
tsunagi-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
+22 -6
View File
@@ -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,
@@ -54,7 +54,16 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj
crate::view::configure(&ctx);
DISPLAY.with_borrow_mut(|d| {
// If Android discarded the old EGL context, its GPU resources are already gone.
let ui = d.take().map(|old| old.ui).unwrap_or_default();
let 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();
*d = Some(Display {
painter,
ctx,
@@ -75,8 +84,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 +100,22 @@ 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);
});
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 +242,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(),
_ => {}
});
}
+71 -8
View File
@@ -25,6 +25,7 @@ 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>>,
@@ -39,19 +40,30 @@ 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;
};
if session
.last_refresh
.is_none_or(|last| last.elapsed() >= std::time::Duration::from_secs(2))
&& session
.commands
.try_send((Request::Refresh, oneshot::channel().0))
.is_ok()
{
session.last_refresh = Some(std::time::Instant::now());
}
session.state.borrow().clone()
}
fn send(cmd: tsunagi_ui::client::Command) -> 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())?;
.map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?;
Ok(result)
}
@@ -227,6 +239,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
})?;
*slot = Some(Session {
id,
last_refresh: None,
commands,
state: state_rx,
underlay,
@@ -252,9 +265,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 +291,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 +337,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,
+11 -4
View File
@@ -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 {
+119 -18
View File
@@ -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;
@@ -14,6 +14,8 @@ use zeroize::Zeroizing;
pub enum Request {
/// 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 +25,13 @@ 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,
},
}
/// A configured default route stays visible if its remote peer goes offline.
@@ -70,6 +79,66 @@ 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 {
/// The agent has applied the action.
@@ -176,13 +245,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
@@ -218,16 +296,20 @@ pub async fn serve(
mut stop: watch::Receiver<bool>,
mut publish_exit: impl FnMut(Option<&ExitNotice>),
) {
let mut poll = tokio::time::interval(std::time::Duration::from_secs(2));
poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut 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;
loop {
let reply = tokio::select! {
let (reply, mut refresh_zones) = tokio::select! {
biased;
_ = stop.wait_for(|stopped| *stopped) => break,
_ = async { drop(stop.wait_for(|stopped| *stopped).await) } => break,
command = commands.recv() => {
let Some((request, reply)) = command else { break };
let refresh_zones = !matches!(request, Request::Refresh);
let result = match request {
Request::Refresh => Ok(Outcome::Applied),
Request::Action(cmd) => {
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
dns.replace(None);
@@ -241,22 +323,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(&notice) {
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(&notice) {
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);
}
+321 -43
View File
@@ -8,9 +8,79 @@ 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(false);
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(..)));
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_replace(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 +113,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(false);
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, &notice.network, &notice.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, &notice.network, &notice.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 +213,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, &notice.network, &notice.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_replace(true);
task.await.unwrap();
}
#[tokio::test]
@@ -480,7 +631,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 +651,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 +818,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 +858,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 +899,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);
}
}
+158 -12
View File
@@ -24,6 +24,7 @@ enum Page {
Devices(String),
Vips(String),
Exit(String),
ExitNetworks,
Leave(String),
}
impl Page {
@@ -40,7 +41,7 @@ impl Page {
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",
}
}
@@ -90,10 +91,14 @@ pub struct Phone {
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;
@@ -104,11 +109,15 @@ pub fn configure(ctx: &Context) {
impl Phone {
fn home(&mut self) {
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 +136,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 +161,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 +266,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 +295,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,6 +310,25 @@ 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 {
@@ -222,14 +346,18 @@ 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() {
@@ -239,8 +367,9 @@ impl Phone {
});
} 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);
}
});
@@ -275,13 +404,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 +426,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 +437,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 +449,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 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-awg"
version = "1.0.3-rc1"
version = "1.0.5"
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true
rust-version.workspace = true
+3
View File
@@ -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 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-core"
version = "1.0.3-rc1"
version = "1.0.5"
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"]
+20 -3
View File
@@ -26,8 +26,9 @@ 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;
@@ -106,6 +107,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<()>>>,
@@ -452,6 +454,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 +511,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 +694,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 +711,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
@@ -1019,6 +1031,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 +1043,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,
});
@@ -1097,6 +1111,7 @@ impl Agent {
interface.sync_broadcast_rules().await;
interface.sync_exit_rules().await;
}
self.inner.roster_changed.send_replace(());
Ok(())
}
@@ -1111,6 +1126,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);
}
@@ -1309,6 +1325,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,
+180 -174
View File
@@ -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)]
@@ -205,6 +207,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>>,
}
@@ -429,10 +432,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
@@ -521,8 +523,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,
@@ -545,10 +547,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();
@@ -787,7 +793,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.
@@ -894,12 +899,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();
@@ -1210,6 +1214,7 @@ impl Runtime {
}
}
self.index_stored_state();
self.ensure_own_claim().await;
self.publish_allocations().await;
}
@@ -1425,14 +1430,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,
@@ -1440,40 +1438,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(
@@ -1495,11 +1461,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;
@@ -1511,14 +1473,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);
}
}
@@ -1565,7 +1529,7 @@ impl Runtime {
return;
}
}
self.broadcast_state();
self.share_changes([SyncKey::Claim(self.local_id)]);
}
fn update_vips(&self) {
@@ -1654,25 +1618,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(());
};
@@ -1694,14 +1654,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<()> {
@@ -1719,33 +1686,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");
}
@@ -1759,29 +1703,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 {
@@ -1790,43 +1738,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 {
@@ -1863,6 +1798,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(())
}
@@ -1907,6 +1843,7 @@ impl Runtime {
return;
}
self.exit_via_was_online = online;
self.params.roster_changed.send_replace(());
if online {
tracing::info!(
network = %self.network_id,
@@ -1979,6 +1916,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(());
}
@@ -2312,9 +2250,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
@@ -2363,21 +2304,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
@@ -2390,18 +2358,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());
}
}
}
@@ -2626,8 +2609,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);
@@ -2747,8 +2728,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,
@@ -2810,6 +2794,7 @@ impl Runtime {
exit_node,
hostname: self.params.hostname.clone(),
capabilities,
agent_version: Some(env!("CARGO_PKG_VERSION").to_owned()),
}
}
@@ -2897,6 +2882,7 @@ 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,
peer,
@@ -2920,6 +2906,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();
@@ -2999,8 +2986,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);
@@ -3020,7 +3013,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()));
}
@@ -3034,6 +3027,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
@@ -3187,7 +3181,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(
@@ -3235,7 +3234,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 {
@@ -3260,6 +3259,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()
@@ -3348,6 +3348,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
@@ -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);
}
}
+11 -2
View File
@@ -68,10 +68,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 +232,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,
+9
View File
@@ -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.
///
@@ -247,6 +254,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.
+3
View File
@@ -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.
+14 -3
View File
@@ -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()
}
}
@@ -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.
+10 -4
View File
@@ -830,6 +830,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 +895,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 +940,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.
@@ -1141,7 +1147,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
///
/// Bump it whenever [`Request`], [`Response`] or anything they contain
/// changes shape.
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 24]);
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 26]);
/// Reads one request off an accepted stream, answers it, writes the response.
///
+9
View File
@@ -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 {
+74 -21
View File
@@ -320,11 +320,19 @@ impl Interface {
tally.multicast.fetch_add(1, Ordering::Relaxed);
continue;
}
let Some(route) = routes.route_v4(destination) else {
let selected = match destination {
IpAddr::V4(address) => routes.packet_route(address),
IpAddr::V6(_) => None,
};
let Some((route, exit)) = selected else {
tally.note_unroutable(destination);
continue;
};
let len = packet.len() as u64;
if carrier.carry(route, packet) {
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);
@@ -840,12 +848,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) = match (origin, header.destination()) {
(
PacketSource::ExitReply {
local: Some(local),
exit,
},
IpAddr::V4(destination),
) if destination == local => (false, Some(exit)),
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_broadcast(destination) =>
{
@@ -855,13 +865,13 @@ impl Interface {
self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::BroadcastDenied);
}
true
(true, None)
}
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_local_destination(network, destination)
|| self.routes.accepts_exit_traffic(network, destination) =>
{
false
(false, None)
}
_ => {
self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed);
@@ -887,7 +897,11 @@ impl Interface {
crate::vip::router::Decision::Pass => packet,
};
// 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() {
if let Some(exit) = exit {
exit.rx_bytes.fetch_add(len, Ordering::Relaxed);
}
if broadcast {
self.tally
.broadcast_received
@@ -926,18 +940,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 +1532,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;
+96 -10
View File
@@ -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.
@@ -97,6 +111,7 @@ pub enum RouteError {
pub struct RoutingTable {
pub(crate) vips: Arc<crate::vip::VipRouter>,
broadcast: ArcSwap<BroadcastTable>,
selected_exit: ArcSwapOption<SelectedExit>,
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
}
@@ -171,6 +186,7 @@ impl RoutingTable {
clear_other_exits(networks, network);
}
networks.insert(network, routes);
self.refresh_exit(networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(networks)));
Ok(())
@@ -181,6 +197,7 @@ impl RoutingTable {
self.vips.remove_network(network);
let mut networks = self.write();
networks.remove(&network);
self.refresh_exit(&networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
}
@@ -213,9 +230,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 +292,13 @@ 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(destination).map(|(route, _)| route)
}
pub(super) fn packet_route(
&self,
destination: Ipv4Addr,
) -> Option<(Route, Option<Arc<SelectedExit>>)> {
let networks = self.read();
for (network, routes) in networks.iter() {
if routes.local == Some(destination) {
@@ -259,10 +309,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 +323,8 @@ 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()?;
Some((exit.route, Some(exit)))
}
/// Whether a peer may send from a source address.
@@ -298,11 +352,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 +383,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.
@@ -800,6 +860,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();
+55
View File
@@ -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");
}
}
}
+11 -3
View File
@@ -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
+13 -9
View File
@@ -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(),
+91
View File
@@ -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();
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-runtime"
version = "1.0.3-rc1"
version = "1.0.5"
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.3-rc1" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3-rc1" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3-rc1" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.3-rc1" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3-rc1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.5" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.5" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.5" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.5" }
tokio.workspace = true
tracing.workspace = true
+3
View File
@@ -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),
@@ -102,6 +103,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 +195,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,
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tcp-tls"
version = "1.0.3-rc1"
version = "1.0.5"
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.3-rc1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
rustls = "0.23"
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tray"
version = "1.0.3-rc1"
version = "1.0.5"
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.3-rc1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
# 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).
+2 -2
View File
@@ -162,8 +162,8 @@ impl App {
.with_title(devices::title(network))
.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]);
.with_inner_size([1000.0, 640.0])
.with_min_inner_size([560.0, 400.0]);
let agent = &self.agent;
let traffic = &self.traffic;
// The window shares the single unit setting, so its toggle and the
+1 -1
View File
@@ -38,7 +38,7 @@ 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 snapshot.busy {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-ui"
version = "1.0.3-rc1"
version = "1.0.5"
description = "Shared egui widgets for the tray and Android clients."
edition.workspace = true
rust-version.workspace = true
+95
View File
@@ -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.
+18 -3
View File
@@ -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();
}
+296 -200
View File
@@ -8,6 +8,7 @@
use std::collections::HashMap;
mod compact;
mod exit_picker;
mod status;
pub use crate::exit::name_of;
pub use exit_picker::choose_exit;
@@ -19,9 +20,9 @@ use crate::client::{Client, Command};
use crate::exit;
use crate::format;
use crate::stats::{Traffic, Unit};
use crate::widgets;
/// A device that works but not as well as it could: reached through others,
/// or with a name somebody else holds.
/// A hostname that another peer already holds.
const AMBER: egui::Color32 = egui::Color32::from_rgb(0xd9, 0xa4, 0x2c);
/// A readable title for a network's window.
@@ -44,6 +45,7 @@ struct Device<'a> {
name_taken: Option<(&'a str, String)>,
/// The last hostname seen for it, kept while it is offline.
hostname: Option<&'a str>,
agent_version: Option<&'a str>,
/// What clicking the hostname copies: `hostname.network`, so it resolves.
copy: Option<String>,
/// The full endpoint id, which clicking the short form copies.
@@ -104,6 +106,11 @@ impl Device<'_> {
fn sort_key(&self) -> String {
self.hostname.unwrap_or(self.id).to_lowercase()
}
fn version_label(&self) -> String {
self.agent_version
.map_or_else(|| "v?".into(), |v| format!("v{}", format::short(v)))
}
}
/// The first characters of an endpoint id, enough to tell devices apart.
@@ -115,6 +122,9 @@ fn short_id(id: &str) -> String {
/// Clicking either copies its own full value.
fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
ui.spacing_mut().item_spacing.x = 4.0;
let (rect, r) = ui.allocate_exact_size(egui::Vec2::splat(16.), egui::Sense::click());
device.channel().paint(ui, rect);
widgets::hint(r, device.channel_hint());
match (device.hostname, &device.copy) {
(Some(hostname), Some(copy)) => {
format::copy_field(ui, hostname, copy);
@@ -122,11 +132,20 @@ fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
}
_ => format::copy_field(ui, &short_id(device.id), device.id),
}
ui.label(egui::RichText::new(device.version_label()).small().weak())
.on_hover_text(format!(
"Tsunagi {}",
device.agent_version.unwrap_or("version unknown")
));
if let Some((name, holder)) = &device.name_taken {
ui.label(egui::RichText::new(egui_phosphor::regular::WARNING).color(AMBER))
.on_hover_text(format!(
"Name `{name}` belongs to {holder}. Use this device's address."
));
let warning = ui.add(
egui::Label::new(egui::RichText::new(icon::WARNING).color(AMBER))
.sense(egui::Sense::click()),
);
widgets::hint(
warning,
&format!("Name `{name}` belongs to {holder}. Use this device's address."),
);
}
}
@@ -143,11 +162,16 @@ pub fn show(
let (confirm, forget_confirm) = confirmations;
egui::CentralPanel::default().show(ctx, |ui| {
ui.horizontal(|ui| {
ui.heading(&network.name);
// Reserve the unit switch even when a network name fills the viewport.
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.selectable_value(unit, Unit::Bytes, "bytes");
ui.selectable_value(unit, Unit::Packets, "pkts");
ui.label("show:");
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.add(
egui::Label::new(egui::RichText::new(&network.name).heading()).truncate(),
);
});
});
});
// A copy of the chosen unit for the read-only rendering below.
@@ -158,7 +182,13 @@ pub fn show(
.auto_shrink([false, false])
.show(ui, |ui| {
ui.collapsing("Network details", |ui| summary(ui, network));
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0);
if widgets::landscape(ctx) {
ui.collapsing("Network traffic", |ui| {
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0)
});
} else {
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0);
}
compact::roster(
ui,
network,
@@ -170,23 +200,23 @@ pub fn show(
});
return;
}
summary(ui, network);
ui.add_space(6.0);
ui.label(egui::RichText::new("traffic").strong());
format::sparkline(ui, traffic.network(&network.network_id), unit, 48.0);
ui.add_space(8.0);
let devices = devices(network, own_id);
let online = devices.iter().filter(|d| d.online).count();
ui.label(
egui::RichText::new(format!(
"devices ({} online / {} known)",
online,
ui.columns(2, |columns| {
columns[0].strong(format!(
"devices ({online} online / {} known)",
devices.len()
))
.strong(),
);
));
columns[0].collapsing("Network details", |ui| summary(ui, network));
let plot = &mut columns[1];
plot.label("Network traffic");
let width = plot.available_width().min(440.0);
plot.scope(|ui| {
ui.set_max_width(width);
format::sparkline(ui, traffic.network(&network.network_id), unit, 48.0);
});
});
ui.add_space(8.0);
egui::ScrollArea::both()
.auto_shrink([false, false])
.show(ui, |ui| {
@@ -334,8 +364,10 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) {
.num_columns(2)
.spacing([12.0, 3.0])
.show(ui, |ui| {
ui.weak("id");
let id = if ui.ctx().os() == egui::os::OperatingSystem::Android {
widgets::network_id(ui);
let id = if ui.ctx().os() == egui::os::OperatingSystem::Android
|| ui.available_width() < 440.0
{
format::short(&network.network_id)
} else {
network.network_id.clone()
@@ -343,33 +375,53 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) {
format::copy_field(ui, &id, &network.network_id);
ui.end_row();
ui.weak("active");
widgets::field(ui, icon::POWER, "Active", "Network active on this device");
ui.label(yes_no(network.active));
ui.end_row();
ui.weak("broadcast");
widgets::field(
ui,
icon::BROADCAST,
"Broadcast",
"Local broadcast participation",
);
ui.label(yes_no(network.broadcast));
ui.end_row();
if let Some(range) = &network.range {
ui.weak("range");
widgets::range(ui);
format::copy_field(ui, range, range);
ui.end_row();
}
if let Some(address) = network.overlay.as_ref().and_then(|o| o.address.as_ref()) {
ui.weak("this device");
widgets::device_address(ui);
format::copy_field(ui, address, address);
ui.end_row();
}
ui.weak("candidates");
widgets::field(
ui,
icon::MAGNIFYING_GLASS,
"Candidates",
"Unverified discovery candidates",
);
ui.label(network.candidates.to_string());
ui.end_row();
ui.weak("relay fwd/via/recv");
widgets::field(
ui,
icon::FLOW_ARROW,
"Relay fwd / via / recv",
"Datagrams forwarded / sent via relay / received via relay",
);
ui.label(format!(
"{} / {} / {}",
network.relay_forwarded, network.relay_sent_via, network.relay_received_via
));
ui.end_row();
ui.weak("dial/handshake fails");
widgets::field(
ui,
icon::WARNING,
"Dial / handshake failures",
"Failed connection attempts / failed membership handshakes",
);
ui.label(format!(
"{} / {}",
network.dial_failures, network.handshake_failures
@@ -460,6 +512,7 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
via_name,
name_taken,
hostname,
agent_version: peer.and_then(|p| p.agent_version.as_deref()),
copy: hostname.map(|h| format!("{h}.{}", network.name)),
id,
data_error: peer.and_then(|p| p.data_error.as_deref()),
@@ -484,44 +537,55 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
devices
}
const COLUMN_HEADERS: [&str; 10] = [
"device",
"exit",
"data",
"RTT data / control",
"address",
"data path",
"pkts",
"bytes",
"rate",
"plot",
];
fn column_headers(unit: Unit) -> [&'static str; 9] {
[
"device",
"exit",
"data",
"RTT data / control",
"address",
"data path",
match unit {
Unit::Bytes => "bytes (TX / RX)",
Unit::Packets => "pkts (TX / RX)",
},
"rate",
"plot",
]
}
/// Initial column floors; actual headers, values and totals can grow them.
const COLUMN_SAMPLES: [&str; 10] = [
const COLUMN_SAMPLES: [&str; 9] = [
"device",
"exit",
"data",
"9999 ms",
"255.255.255.255",
"data path",
"99999/99999",
"1023.9 MB / 1023.9 MB",
"1023.9 kB/s",
"plot",
];
fn traffic_pair(tx: u64, rx: u64, unit: Unit) -> String {
format!(
"{} / {}",
format::amount(tx, unit),
format::amount(rx, unit)
)
}
/// Column widths that only ever grow, kept across frames.
///
/// Live values can change width between frames. A value that
/// gets shorter — `14.4 MB/s` giving way to `382 pkt/s` — would pull the
/// column in and push every cell after it. Remembering the widest seen keeps
/// the table where it is.
fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 10] {
let stored: Option<[f32; 10]> = ui.memory(|m| m.data.get_temp(id));
fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 9] {
let stored: Option<[f32; 9]> = ui.memory(|m| m.data.get_temp(id));
stored.unwrap_or_else(|| {
let font = egui::FontSelection::Default.resolve(ui.style());
let mut widths = [0.0; 10];
let mut widths = [0.0; 9];
for (width, sample) in widths.iter_mut().zip(COLUMN_SAMPLES) {
if !sample.is_empty() {
*width = ui.fonts(|fonts| {
@@ -536,10 +600,9 @@ fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 10] {
})
}
fn stretch_columns(mut widths: [f32; 10], available: f32) -> [f32; 10] {
let gaps = 10.0 * (widths.len() - 1) as f32;
widths[9] = widths[9].max(100.0);
widths[9] += (available - gaps - widths.iter().sum::<f32>()).max(0.0);
fn stretch_columns(mut widths: [f32; 9], available: f32) -> [f32; 9] {
let gaps = crate::table::GAP * (widths.len() - 1) as f32;
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(100.0, 180.0);
widths
}
@@ -577,9 +640,8 @@ fn exit_cell(
)
.sense(egui::Sense::click()),
)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(hint);
if response.clicked() {
.on_hover_cursor(egui::CursorIcon::PointingHand);
if widgets::hint(response, hint).clicked() {
*confirm = Some(ExitConfirm {
network_id: network_id.to_string(),
peer_id: device.id.to_string(),
@@ -618,22 +680,23 @@ fn device_table(
.x
})
};
for (column, header) in COLUMN_HEADERS.into_iter().enumerate() {
widths[column] = widths[column].max(measure(header.to_owned()));
let headers = column_headers(unit);
for (column, header) in headers.iter().enumerate() {
widths[column] = widths[column].max(measure((*header).to_owned()));
}
let (mut tx_packets, mut rx_packets, mut tx_bytes, mut rx_bytes): (u64, u64, u64, u64) =
(0, 0, 0, 0);
let (mut tx_total, mut rx_total) = (0_u64, 0_u64);
for device in devices {
let name = format!(
"{} ({}){}",
"{} ({}) {}{}",
device.name(),
short_id(device.id),
device.version_label(),
if !device.online { " Forget" } else { "" }
);
widths[0] = widths[0].max(measure(name) + 24.0);
let (path, _) = data_path_text(device.path, device.via_name.as_deref(), device.online);
widths[0] = widths[0].max(measure(name) + 44.0);
let path = data_path_text(device.path, device.via_name.as_deref(), device.online);
for (column, text) in [
(2, "waiting".to_owned()),
(2, device.channel().label().to_owned()),
(3, rtt_pair(device)),
(4, device.address.clone().unwrap_or_default()),
(5, path),
@@ -641,59 +704,36 @@ fn device_table(
widths[column] = widths[column].max(measure(text));
}
if let Some(peer) = device.overlay {
tx_packets = tx_packets.saturating_add(peer.tx_packets);
rx_packets = rx_packets.saturating_add(peer.rx_packets);
tx_bytes = tx_bytes.saturating_add(peer.tx_bytes);
rx_bytes = rx_bytes.saturating_add(peer.rx_bytes);
for (column, text) in [
(6, format!("{}/{}", peer.tx_packets, peer.rx_packets)),
(
7,
format!(
"{} / {}",
format::bytes(peer.tx_bytes as f64),
format::bytes(peer.rx_bytes as f64)
),
),
(
8,
format::series_rate(traffic.peer(network_id, &peer.public_key), unit),
),
] {
widths[column] = widths[column].max(measure(text));
}
let (tx, rx) = unit.counters(peer);
tx_total = tx_total.saturating_add(tx);
rx_total = rx_total.saturating_add(rx);
widths[6] = widths[6].max(measure(traffic_pair(tx, rx, unit)));
widths[7] = widths[7].max(measure(format::series_rate(
traffic.peer(network_id, &peer.public_key),
unit,
)));
}
}
for (column, text) in [
(6, format!("{tx_packets}/{rx_packets}")),
(
7,
format!(
"{} / {}",
format::bytes(tx_bytes as f64),
format::bytes(rx_bytes as f64)
),
),
(8, format::series_rate(traffic.network(network_id), unit)),
] {
widths[column] = widths[column].max(measure(text));
}
let total = traffic_pair(tx_total, rx_total, unit);
let rate = format::series_rate(traffic.network(network_id), unit);
widths[6] = widths[6].max(measure(total.clone()));
widths[7] = widths[7].max(measure(rate.clone()));
if widths != previous_widths {
ui.ctx().request_repaint();
}
ui.memory_mut(|m| m.data.insert_temp(widths_id, widths));
let widths = stretch_columns(widths, ui.available_width());
crate::table::row(ui, "device headers", &widths, false, |column, ui| {
let response = ui.weak(COLUMN_HEADERS[column]);
let response = ui.weak(headers[column]);
match column {
2 => {
response.on_hover_text("Encrypted data channel readiness.");
}
3 => {
response.on_hover_text("Control-connection round-trip time.");
response.on_hover_text("Data-link and control-connection round-trip times.");
}
7 => {
response.on_hover_text("Plaintext IP bytes accepted by the encrypted channel in this counter lifetime; excludes relay transit, transport overhead and delivery probes.");
6 => {
response.on_hover_text("Sent / received IP traffic in the selected unit. Excludes relay transit and transport overhead.");
}
5 => {
response.on_hover_text("External data transport or relay route.");
@@ -731,16 +771,10 @@ fn device_table(
let series = traffic.peer(network_id, &peer.public_key);
match column {
6 => {
ui.label(format!("{}/{}", peer.tx_packets, peer.rx_packets));
let (tx, rx) = unit.counters(peer);
ui.label(traffic_pair(tx, rx, unit));
}
7 => {
ui.label(format!(
"{} / {}",
format::bytes(peer.tx_bytes as f64),
format::bytes(peer.rx_bytes as f64)
));
}
8 => {
ui.label(format::series_rate(series, unit));
}
_ => format::sparkline(ui, series, unit, 24.0),
@@ -762,17 +796,10 @@ fn device_table(
ui.strong("total");
}
6 => {
ui.strong(format!("{tx_packets}/{rx_packets}"));
ui.strong(&total);
}
7 => {
ui.strong(format!(
"{} / {}",
format::bytes(tx_bytes as f64),
format::bytes(rx_bytes as f64)
));
}
8 => {
ui.strong(format::series_rate(traffic.network(network_id), unit));
ui.strong(&rate);
}
_ => {}
},
@@ -792,71 +819,51 @@ fn rtt_pair(device: &Device<'_>) -> String {
}
fn tunnel_cell(ui: &mut egui::Ui, device: &Device<'_>) {
let ready = device.overlay.is_some_and(|peer| peer.is_up())
&& !matches!(device.path, None | Some(DataPathReport::None));
let text = if !device.online {
"—"
} else if ready {
"ready"
} else {
"waiting"
};
let error = device.data_error.unwrap_or({
if ready {
"Encrypted data channel ready"
} else {
"Encrypted data channel is not ready"
}
});
ui.label(text).on_hover_text(error);
let state = device.channel();
let r = ui.add(
egui::Label::new(egui::RichText::new(state.label()).color(state.color(ui)))
.sense(egui::Sense::click()),
);
widgets::hint(r, device.channel_hint());
}
/// Compact route label and whether that route is the preferred direct form.
/// Compact route label for either client.
/// The icon font is embedded by egui-phosphor and installed in `App::new`.
fn data_path_text(
path: Option<&DataPathReport>,
via_name: Option<&str>,
online: bool,
) -> (String, bool) {
fn data_path_text(path: Option<&DataPathReport>, via_name: Option<&str>, online: bool) -> String {
if !online {
return ("offline".into(), false);
return "offline".into();
}
match path {
Some(DataPathReport::Direct { transport }) => (format!("{} {transport}", icon::LINK), true),
Some(DataPathReport::Relayed { hops, .. }) => (
format!(
"{} {} · {hops} hops",
icon::SHARE_NETWORK,
via_name.unwrap_or("another device")
),
false,
Some(DataPathReport::Direct { transport }) => format!("{} {transport}", icon::LINK),
Some(DataPathReport::Relayed { hops, .. }) => format!(
"{} {} · {hops} hops",
icon::SHARE_NETWORK,
via_name.unwrap_or("another device")
),
Some(DataPathReport::None) | None => ("no data path yet".into(), false),
Some(DataPathReport::None) | None => "no data path yet".into(),
}
}
/// How a device is reached right now.
///
/// A device reached through others is online, over a longer path, and says
/// so: the colour is the only difference in how it is treated.
fn data_path_cell(ui: &mut egui::Ui, device: &Device<'_>) {
let (text, good) = data_path_text(device.path, device.via_name.as_deref(), device.online);
let response = if good {
ui.add(egui::Label::new(text).wrap_mode(egui::TextWrapMode::Extend))
} else {
ui.add(
egui::Label::new(egui::RichText::new(text).color(AMBER))
.wrap_mode(egui::TextWrapMode::Extend),
)
};
response.on_hover_text(match device.path {
Some(DataPathReport::Direct { .. }) => device
.data_transport_detail
.unwrap_or("Direct link to this member."),
Some(DataPathReport::Relayed { .. }) => "Traffic forwarded through another device.",
_ if device.online => "Control connected; data transport unavailable.",
_ => "Unreachable.",
});
let text = data_path_text(device.path, device.via_name.as_deref(), device.online);
let mut text = egui::RichText::new(text);
if !device.online {
text = text.weak();
}
let response = ui.add(egui::Label::new(text).extend().sense(egui::Sense::click()));
widgets::hint(
response,
match device.path {
Some(DataPathReport::Direct { .. }) => device
.data_transport_detail
.unwrap_or("Direct link to this member."),
Some(DataPathReport::Relayed { .. }) => "Traffic forwarded through another device.",
_ if device.online => "Control connected; data transport unavailable.",
_ => "Unreachable.",
},
);
}
fn forget_button(
@@ -903,17 +910,18 @@ mod tests {
}
}
struct ReadOnly;
impl Client for ReadOnly {
fn send(&self, _: Command) {
panic!("reading the devices view issued an action");
}
fn busy(&self) -> bool {
false
}
}
#[test]
fn phone_roster_fits_each_width_and_expands_only_the_tapped_member() {
struct ReadOnly;
impl Client for ReadOnly {
fn send(&self, _: Command) {
panic!("reading a row issued an action");
}
fn busy(&self) -> bool {
false
}
}
let mut network = NetworkReport {
network_id: "a".repeat(60),
name: "lab".into(),
@@ -933,9 +941,24 @@ mod tests {
m.overlay_address_v4 = Some(format!("192.168.254.{}", 240 + i));
network.members.push(m);
}
network.peers.push(tsunagi::ipc::PeerReport {
endpoint_id: "alpha".into(),
agent_version: Some("2.0.0-rc.1".into()),
..Default::default()
});
network.overlay = Some(tsunagi::ipc::OverlayReport {
peers: vec![OverlayPeerReport {
endpoint_id: "alpha".into(),
tx_bytes: 1024,
rx_bytes: 512,
..Default::default()
}],
..Default::default()
});
for width in [320.0, 360.0, 430.0, 870.0] {
let ctx = egui::Context::default();
ctx.set_os(egui::os::OperatingSystem::Android);
ctx.set_fonts(crate::app_fonts());
let frame = |events| {
ctx.run(
egui::RawInput {
@@ -950,7 +973,7 @@ mod tests {
show(
ctx,
&ReadOnly,
&mut Unit::Packets,
&mut Unit::Bytes,
(&mut None, &mut None),
&network,
"self",
@@ -999,8 +1022,22 @@ mod tests {
};
let expanded = click(a);
assert_eq!(positions(&expanded, "Endpoint ID").len(), 1);
assert_eq!(positions(&expanded, "2.0.0-rc.1").len(), 1);
let up = positions(&expanded, "1.0 kB")[0];
let down = positions(&expanded, "512 B")[0];
assert!(down.x - up.x > width * 0.25 && (up.y - down.y).abs() < 2.0);
for (arrow, caption, value) in [
(icon::ARROW_UP, "Sent", up),
(icon::ARROW_DOWN, "Received", down),
] {
let arrow = positions(&expanded, arrow)[0];
let caption = positions(&expanded, caption)[0];
assert!(arrow.x < caption.x && arrow.y < value.y);
assert!((arrow.x - value.x).abs() < 35.0);
}
let switched = click(positions(&expanded, "bravo")[0]);
assert_eq!(positions(&switched, "Endpoint ID").len(), 1);
assert_eq!(positions(&switched, "Unknown").len(), 1);
let closed = click(positions(&switched, "bravo")[0]);
assert!(positions(&closed, "Endpoint ID").is_empty());
}
@@ -1074,7 +1111,7 @@ mod tests {
None,
true,
),
(format!("{} tcp-tls", icon::LINK), true)
format!("{} tcp-tls", icon::LINK)
);
}
@@ -1090,13 +1127,13 @@ mod tests {
Some("iris"),
true,
),
(format!("{} iris · 2 hops", icon::SHARE_NETWORK), false)
format!("{} iris · 2 hops", icon::SHARE_NETWORK)
);
assert_eq!(
data_path_text(Some(&DataPathReport::None), None, true),
("no data path yet".into(), false)
"no data path yet"
);
assert_eq!(data_path_text(None, None, false), ("offline".into(), false));
assert_eq!(data_path_text(None, None, false), "offline");
}
#[test]
@@ -1133,11 +1170,11 @@ mod tests {
}
#[test]
fn resized_table_fills_the_window_without_growing_fixed_columns() {
let minimum = [100.0; 10];
fn wider_windows_keep_a_compact_plot_and_narrow_windows_preserve_column_floors() {
let minimum = [100.0; 9];
let wide = stretch_columns(minimum, 1440.0);
assert!((wide.iter().sum::<f32>() + 90.0 - 1440.0).abs() < 0.1);
assert_eq!(&wide[..9], &minimum[..9]);
assert!((100.0..=190.0).contains(&wide[8]));
assert_eq!(&wide[..8], &minimum[..8]);
let narrow = stretch_columns(minimum, 800.0);
assert_eq!(
narrow, minimum,
@@ -1148,6 +1185,39 @@ mod tests {
wide,
"a resize does not accumulate padding"
);
let ctx = egui::Context::default();
for window_width in [800.0, 1000.0, 1440.0] {
let frame = ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(window_width, 640.0),
)),
..Default::default()
},
|ctx| {
show(
ctx,
&ReadOnly,
&mut Unit::Bytes,
(&mut None, &mut None),
&NetworkReport::default(),
"self",
&Traffic::default(),
);
},
);
let chart = frame
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Rect(r) if r.rect.height() == 48.0 => Some(r.rect),
_ => None,
})
.expect("network traffic chart");
assert!((300.0..=440.0).contains(&chart.width()), "{chart:?}");
}
}
#[test]
@@ -1168,18 +1238,19 @@ mod tests {
}
let context = egui::Context::default();
for (width, packets, age) in [
(1600.0, 1569, 56),
(1600.0, 55_555, 172_800),
(1600.0, 137_245, 172_800),
(900.0, 9_876_543_210, 172_800),
(1600.0, 42, 56),
for (width, packets, age, unit) in [
(1600.0, 1569, 56, crate::home::UiState::default().unit),
(1600.0, 55_555, 172_800, Unit::Packets),
(1600.0, 137_245, 172_800, Unit::Bytes),
(900.0, 9_876_543_210, 172_800, Unit::Packets),
(1600.0, 42, 56, Unit::Bytes),
] {
let network = NetworkReport {
network_id: "network".into(),
peers: ["peer", "other"]
.into_iter()
.map(|id| PeerReport {
agent_version: (id == "peer").then(|| "2.0.0-rc.1".into()),
data_error: None,
endpoint_id: id.into(),
rtt_ms: Some(12_345),
@@ -1220,7 +1291,7 @@ mod tests {
ui.allocate_ui(egui::vec2(width, 480.0), |ui| {
device_table(
ui,
Unit::Packets,
unit,
&network,
&rows,
&Traffic::default(),
@@ -1234,11 +1305,36 @@ mod tests {
let shapes: Vec<_> = output.shapes.into_iter().map(|s| s.shape).collect();
let mut texts = Vec::new();
collect_text(&shapes, &mut texts);
let visible = |value: &str| texts.iter().any(|t| t.galley.text() == value);
assert!(visible("v2.0.0-rc.1"));
assert!(visible("v?"));
let packet_counts = format!("{packets} / {}", packets + 1);
let byte_counts = "117.7 MB / 941.9 MB";
if packets == 1569 {
assert!(visible("bytes (TX / RX)"));
assert!(visible(byte_counts));
}
assert_eq!(visible(&packet_counts), unit == Unit::Packets);
assert_eq!(visible(byte_counts), unit == Unit::Bytes);
for (label, next_column) in [
("RTT data / control".to_string(), "address"),
(rtt_pair(&rows[0]), "address"),
(format!("{packets}/{}", packets + 1), "bytes"),
(format!("{}/{}", packets * 2, (packets + 1) * 2), "bytes"),
(
if unit == Unit::Packets {
packet_counts
} else {
byte_counts.into()
},
"rate",
),
(
if unit == Unit::Packets {
format!("{} / {}", packets * 2, (packets + 1) * 2)
} else {
"235.5 MB / 1.8 GB".into()
},
"rate",
),
] {
let right = texts
.iter()
@@ -1387,7 +1483,7 @@ mod tests {
};
let rows = devices(&network, "own");
let far = rows.iter().find(|device| device.id == "far").unwrap();
let (label, _) = data_path_text(far.path, far.via_name.as_deref(), far.online);
let label = data_path_text(far.path, far.via_name.as_deref(), far.online);
let context = egui::Context::default();
let mut fonts = egui::FontDefinitions::default();
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
@@ -1403,7 +1499,7 @@ mod tests {
&mut None,
&mut None,
);
let stored: [f32; 10] = ui
let stored: [f32; 9] = ui
.memory(|memory| {
memory
.data
+298 -132
View File
@@ -1,11 +1,99 @@
//! 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,
devices, exit, forget_button, format, icon, rtt_text, traffic_pair, tunnel_cell,
};
use crate::widgets;
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, Vec2, pos2, vec2};
#[derive(Clone, Copy)]
enum Column {
Device,
State,
Address,
Rtt,
Traffic,
Version,
Path,
Plot,
}
impl Column {
fn title(self, unit: Unit) -> &'static str {
match self {
Self::Device => "device",
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) -> Vec<(Column, f32)> {
let font = egui::TextStyle::Body.resolve(ui.style());
let measure = |s: &str| {
ui.painter()
.layout_no_wrap(s.into(), font.clone(), Color32::WHITE)
.size()
.x
+ 10.
};
let mut cols = vec![(Column::Device, 0.)];
if landscape && width >= 510. {
cols.push((Column::State, measure("Control only").min(width * 0.16)));
}
cols.push((
Column::Address,
measure("255.255.255.255").min(width * if landscape { 0.27 } else { 0.35 }),
));
cols.push((
Column::Rtt,
measure("9999 ms").min(width * if landscape { 0.15 } else { 0.22 }),
));
if landscape {
cols.push((
Column::Traffic,
measure(Column::Traffic.title(unit))
.max(measure("999 MB / 999 MB"))
.min(width * 0.29),
));
let mut spare = width - cols.iter().map(|c| c.1).sum::<f32>() - 122.;
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 - 16.).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 egui::Ui,
ui: &mut Ui,
network: &NetworkReport,
own_id: &str,
traffic: &Traffic,
@@ -15,46 +103,61 @@ pub(super) fn roster(
let members = devices(network, own_id);
let online = members.iter().filter(|m| m.online).count();
ui.strong(format!(
"devices ({} online / {} known)",
online,
"devices ({online} online / {} known)",
members.len()
));
let id = ui.make_persistent_id(("expanded device", &network.network_id));
// 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);
let font = egui::TextStyle::Body.resolve(ui.style());
let measure = |s: &str| {
ui.painter()
.layout_no_wrap(s.to_owned(), font.clone(), ui.visuals().text_color())
.size()
.x
};
let rtt_x = width - (measure("9999 ms") + 18.0).min(width * 0.25);
let ip_x = rtt_x - (measure("255.255.255.255") + 14.0).min(width * 0.40);
let offsets = [16.0, ip_x, rtt_x];
let size = egui::vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 8.0);
ui.spacing_mut().item_spacing.y = 1.0;
let (header, _) = ui.allocate_exact_size(size, egui::Sense::hover());
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "Data RTT"]) {
ui.painter().text(
header.left_center() + egui::vec2(x, 0.),
egui::Align2::LEFT_CENTER,
title,
font.clone(),
ui.visuals().weak_text_color(),
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.;
}
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 +165,88 @@ 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::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.left_center(),
Align2::LEFT_CENTER,
icon::SIGN_OUT,
font.clone(),
if member.in_use { exit::GOOD } else { normal },
);
rect.min.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 +269,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();
}
+102
View File
@@ -0,0 +1,102 @@
use super::{DataPathReport, Device, icon};
use tsunagi::agent::{DATA_CONNECTING, DATA_DISABLED};
#[derive(Copy, Clone, PartialEq, Eq)]
pub(super) enum Channel {
Ready,
Idle,
Waiting,
Error,
Offline,
Disabled,
}
impl Device<'_> {
pub(super) fn channel(&self) -> Channel {
if !self.online {
return Channel::Offline;
}
match self.data_error {
Some(DATA_DISABLED) => Channel::Disabled,
Some(DATA_CONNECTING) => Channel::Waiting,
Some(_) => Channel::Error,
None if matches!(self.path, None | Some(DataPathReport::None)) => Channel::Waiting,
None if self.overlay.is_some_and(|p| p.idle) => Channel::Idle,
None if self.overlay.is_some_and(|p| p.is_up()) => Channel::Ready,
None => Channel::Waiting,
}
}
pub(super) fn channel_hint(&self) -> &str {
match self.channel() {
Channel::Offline => "Offline · peer unreachable",
Channel::Ready => "Ready · encrypted data channel available",
Channel::Idle => "Idle · online, no recent IP traffic",
Channel::Waiting => "Waiting for the encrypted data channel",
Channel::Disabled => "Control only · data transports disabled locally",
Channel::Error => self.data_error.unwrap_or("Data channel error"),
}
}
}
impl Channel {
pub(super) fn label(self) -> &'static str {
match self {
Self::Ready => "Ready",
Self::Idle => "Idle",
Self::Waiting => "Waiting",
Self::Error => "Error",
Self::Offline => "Offline",
Self::Disabled => "Control only",
}
}
pub(super) fn color(self, ui: &egui::Ui) -> egui::Color32 {
use egui::Color32;
match (self, ui.visuals().dark_mode) {
(Self::Ready, true) => Color32::from_rgb(100, 210, 136),
(Self::Ready, false) => Color32::from_rgb(25, 120, 61),
(Self::Idle, true) => Color32::from_rgb(145, 176, 200),
(Self::Idle, false) => Color32::from_rgb(64, 99, 125),
(Self::Waiting, true) => Color32::from_rgb(244, 190, 85),
(Self::Waiting, false) => Color32::from_rgb(150, 94, 8),
(Self::Error, true) => Color32::from_rgb(255, 129, 116),
(Self::Error, false) => Color32::from_rgb(179, 52, 44),
(Self::Offline | Self::Disabled, true) => Color32::from_rgb(136, 139, 145),
(Self::Offline | Self::Disabled, false) => Color32::from_rgb(98, 102, 108),
}
}
pub(super) fn paint(self, ui: &egui::Ui, rect: egui::Rect) {
if !ui.is_rect_visible(rect) {
return;
}
let color = self.color(ui);
let glyph = match self {
Self::Ready => icon::CHECK_CIRCLE,
Self::Idle => icon::MOON,
Self::Error => icon::WARNING,
Self::Offline => icon::MINUS_CIRCLE,
Self::Disabled => icon::PAUSE_CIRCLE,
Self::Waiting => {
let start = ui.input(|i| (i.time % 1.2) as f32) * std::f32::consts::TAU / 1.2;
let radius = rect.height() * 0.34;
let points = (0..=12)
.map(|i| {
rect.center()
+ egui::Vec2::angled(start + std::f32::consts::PI * i as f32 / 12.)
* radius
})
.collect();
ui.painter()
.add(egui::Shape::line(points, egui::Stroke::new(1.8_f32, color)));
ui.ctx()
.request_repaint_after(std::time::Duration::from_millis(65));
return;
}
};
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
glyph,
egui::FontId::proportional(rect.height()),
color,
);
}
}
+10 -3
View File
@@ -38,6 +38,14 @@ pub fn bytes(n: f64) -> String {
}
}
/// A cumulative amount in the selected unit.
pub(crate) fn amount(value: u64, unit: Unit) -> String {
match unit {
Unit::Bytes => bytes(value as f64),
Unit::Packets => value.to_string(),
}
}
/// A rate in the chosen unit, per second.
pub fn rate(value: f32, unit: Unit) -> String {
match unit {
@@ -79,9 +87,8 @@ pub fn copy_field(ui: &mut egui::Ui, display: &str, value: &str) {
};
let response = ui
.add(egui::Label::new(text).sense(egui::Sense::click()))
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text("click to copy");
if response.clicked() {
.on_hover_cursor(egui::CursorIcon::PointingHand);
if crate::widgets::hint(response, "Copy to clipboard").clicked() {
ui.ctx().copy_text(value.to_owned());
ui.memory_mut(|memory| memory.data.insert_temp(id, Instant::now()));
}
+362 -152
View File
@@ -3,6 +3,7 @@ use crate::{
client::{Client, Command},
devices, exit, format,
stats::{Traffic, Unit},
widgets,
};
use egui_phosphor::regular as icon;
use std::collections::BTreeSet;
@@ -20,6 +21,7 @@ pub struct JoinForm {
pub name: String,
/// User-entered network secret.
pub secret: Zeroizing<String>,
revealed: bool,
}
/// Local UI state kept across frames.
@@ -28,6 +30,10 @@ pub struct UiState {
pub join: JoinForm,
/// Whether rates and sparklines are shown in packets or bytes.
pub unit: Unit,
/// Network details opened during this run, keyed by identity even for namesakes.
expanded_networks: BTreeSet<String>,
/// The network whose settings occupy the detail pane on a landscape phone.
pub selected_network: Option<String>,
/// An in-progress hostname edit (`None` when not editing).
pub host_edit: Option<String>,
/// Network ids whose devices window is open.
@@ -46,7 +52,9 @@ impl Default for UiState {
fn default() -> Self {
Self {
join: JoinForm::default(),
unit: Unit::Packets,
unit: Unit::Bytes,
expanded_networks: BTreeSet::new(),
selected_network: None,
host_edit: None,
open_devices: BTreeSet::new(),
vip_windows: Default::default(),
@@ -66,21 +74,17 @@ pub fn draw_header(
) {
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.weak("device");
widgets::field(ui, icon::FINGERPRINT, "", "Device endpoint ID");
// Clicking the shortened id copies the full one.
format::copy_field(ui, &format::short(&report.endpoint_id), &report.endpoint_id);
});
ui.horizontal(|ui| {
ui.weak("host");
widgets::field(ui, icon::DESKTOP_TOWER, "", "Device hostname");
match &mut state.host_edit {
None => {
ui.label(&report.hostname);
if ui
.small_button(icon::PENCIL_SIMPLE)
.on_hover_text("rename")
.clicked()
{
if widgets::icon_button(ui, icon::PENCIL_SIMPLE, "Rename this device").clicked() {
state.host_edit = Some(report.hostname.clone());
}
}
@@ -88,11 +92,11 @@ pub fn draw_header(
let response = ui.add(egui::TextEdit::singleline(buffer).desired_width(150.0));
let submit = (response.lost_focus()
&& ui.input(|i| i.key_pressed(egui::Key::Enter)))
|| ui.small_button(icon::CHECK).on_hover_text("save").clicked();
|| widgets::icon_button(ui, icon::CHECK, "Save hostname").clicked();
if submit {
agent.send(Command::SetHostname(buffer.trim().to_string()));
state.host_edit = None;
} else if ui.small_button(icon::X).on_hover_text("cancel").clicked() {
} else if widgets::icon_button(ui, icon::X, "Cancel hostname edit").clicked() {
state.host_edit = None;
}
}
@@ -121,97 +125,224 @@ pub fn draw_network(
offer_exit: bool,
) -> bool {
let mut pick_exit = false;
ui.add_space(6.0);
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.horizontal(|ui| {
format::copy_field(ui, network.name.as_str(), &network.name);
if ui.button("VIP").clicked(){state.vip_windows.entry(network.network_id.clone()).or_default();}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let leave =
egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE))
.fill(LEAVE_RED);
if ui.add(leave).clicked() {
agent.send(Command::Leave {
network_id: network.network_id.clone(),
});
}
});
ui.add_space(5.0);
ui.push_id(&network.network_id, |ui| {
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.set_min_width(ui.available_width());
let open = state.expanded_networks.contains(&network.network_id);
if overview(ui, network, report, state, open) {
state.toggle_network(&network.network_id, !open);
}
if state.expanded_networks.contains(&network.network_id) {
ui.separator();
pick_exit =
draw_network_details(ui, agent, state, traffic, network, report, offer_exit);
}
});
});
pick_exit
}
let address = network.overlay.as_ref().and_then(|o| o.address.as_ref());
let series = traffic.network(&network.network_id);
egui::Grid::new(("net", &network.network_id))
.num_columns(2)
.spacing([10.0, 3.0])
.show(ui, |ui| {
ui.weak("id");
format::copy_field(ui, &format::short(&network.network_id), &network.network_id);
ui.end_row();
if let Some(range) = &network.range {
ui.weak("range");
format::copy_field(ui, range, range);
ui.end_row();
}
if let Some(address) = address {
ui.weak("addr");
format::copy_field(ui, address, address);
ui.end_row();
}
ui.weak("peers");
ui.label(format!(
"{} online · {} known",
devices::online_count(network, &report.endpoint_id),
devices::known_count(network, &report.endpoint_id)
));
ui.end_row();
});
draw_protocols(ui, agent, network, &report.available_protocols);
format::sparkline(ui, series, state.unit, 34.0);
if !network.range_conflicts.is_empty() {
ui.colored_label(BAD, "Stopped: overlapping network ranges");
for conflict in &network.range_conflicts {
ui.label(format!("{} ({}) uses {}", conflict.name, conflict.network_id, conflict.range));
impl UiState {
fn toggle_network(&mut self, id: &str, open: bool) {
if open {
self.expanded_networks.insert(id.to_owned());
self.selected_network = Some(id.to_owned());
} else {
self.expanded_networks.remove(id);
if self.selected_network.as_deref() == Some(id) {
self.selected_network = None;
}
ui.label("Switching suspends these networks until this network stops, then resumes them automatically.");
if network.auto_start { ui.weak("This network will resume automatically when its range is free."); }
}
ui.horizontal_wrapped(|ui| {
if !network.active && !network.range_conflicts.is_empty() {
if ui.button("Switch to this network").clicked() {
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: true });
}
if network.auto_start && ui.button("Keep stopped").clicked() {
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: false });
}
} else {
let mut active = network.active;
if ui.checkbox(&mut active, "active").changed() {
agent.send(Command::SetActive {
network_id: network.network_id.clone(),
active,
});
}
}
/// Close the landscape detail pane and fold that card when rotated back.
pub fn close_selection(&mut self) -> bool {
if let Some(id) = self.selected_network.take() {
self.expanded_networks.remove(&id);
return true;
}
false
}
}
fn overview(
ui: &mut egui::Ui,
network: &NetworkReport,
report: &StatusReport,
state: &mut UiState,
open: bool,
) -> bool {
let status = if network.active {
format!(
"{} online",
devices::online_count(network, &report.endpoint_id)
)
} else {
"Stopped".into()
};
let clicked = network_header(ui, &network.name, &status, open).clicked();
if let Some(via) = &network.exit.via {
draw_selected_exit(ui, network, via, state);
}
for warning in exit::warnings(network) {
draw_exit_warning(ui, &warning);
}
if !network.range_conflicts.is_empty() {
ui.colored_label(BAD, "Stopped: overlapping network ranges");
}
clicked
}
/// One network in the landscape selector. Exit status stays visible beside its network.
pub fn draw_network_selector(
ui: &mut egui::Ui,
network: &NetworkReport,
report: &StatusReport,
state: &mut UiState,
) {
let open = state.selected_network.as_deref() == Some(&network.network_id);
ui.push_id(&network.network_id, |ui| {
let mut frame = egui::Frame::group(ui.style());
if open {
frame = frame.stroke(ui.visuals().selection.stroke);
}
frame.show(ui, |ui| {
ui.set_min_width(ui.available_width());
if overview(ui, network, report, state, open) {
state.toggle_network(&network.network_id, !open);
}
let mut broadcast = network.broadcast;
if ui.checkbox(&mut broadcast, "broadcast").changed() {
agent.send(Command::SetBroadcast {
});
});
}
/// Actions and settings shared by a folded card and the landscape detail pane.
pub fn draw_network_details(
ui: &mut egui::Ui,
agent: &dyn Client,
state: &mut UiState,
traffic: &Traffic,
network: &NetworkReport,
report: &StatusReport,
offer_exit: bool,
) -> bool {
ui.horizontal_wrapped(|ui| {
if ui
.button(format!("{} Copy secret", icon::COPY))
.on_hover_text("Copy this network's secret to the clipboard")
.clicked()
{
agent.send(Command::CopySecret {
network_id: network.network_id.clone(),
});
}
if ui.button("Show devices").clicked() {
state.open_devices.insert(network.network_id.clone());
}
if widgets::hint(
ui.button(format!("{} VIP", icon::NETWORK)),
"Manage virtual IP services",
)
.clicked()
{
state
.vip_windows
.entry(network.network_id.clone())
.or_default();
}
});
ui.separator();
draw_metadata(ui, network, &report.endpoint_id);
draw_protocols(ui, agent, network, &report.available_protocols);
format::sparkline(ui, traffic.network(&network.network_id), state.unit, 34.0);
network_settings(ui, agent, network, offer_exit)
}
fn draw_metadata(ui: &mut egui::Ui, network: &NetworkReport, own_id: &str) {
egui::Grid::new(ui.id().with("metadata"))
.num_columns(2)
.spacing([10.0, 3.0])
.show(ui, |ui| {
widgets::field(ui, icon::TAG, "", "Network name");
format::copy_field(ui, &network.name, &network.name);
ui.end_row();
widgets::network_id(ui);
format::copy_field(ui, &format::short(&network.network_id), &network.network_id);
ui.end_row();
if let Some(range) = &network.range {
widgets::range(ui);
format::copy_field(ui, range, range);
ui.end_row();
}
if let Some(address) = network.overlay.as_ref().and_then(|o| o.address.as_ref()) {
widgets::device_address(ui);
format::copy_field(ui, address, address);
ui.end_row();
}
widgets::field(ui, icon::DEVICES, "", "Online and known peers");
ui.label(format!(
"{} online · {} known",
devices::online_count(network, own_id),
devices::known_count(network, own_id)
));
ui.end_row();
});
}
fn network_settings(
ui: &mut egui::Ui,
agent: &dyn Client,
network: &NetworkReport,
offer_exit: bool,
) -> bool {
let mut pick_exit = false;
if !network.range_conflicts.is_empty() {
for conflict in &network.range_conflicts {
ui.label(format!(
"{} ({}) uses {}",
conflict.name, conflict.network_id, conflict.range
));
}
ui.label("Switching suspends these networks until this network stops, then resumes them automatically.");
if network.auto_start {
ui.weak("This network will resume automatically when its range is free.");
}
}
ui.horizontal_wrapped(|ui| {
if !network.active && !network.range_conflicts.is_empty() {
if ui.button("Switch to this network").clicked() {
agent.send(Command::SetActive {
network_id: network.network_id.clone(),
enabled: broadcast,
active: true,
});
}
if !offer_exit && ui.button("Exit node…").clicked() { pick_exit = true; }
if network.auto_start && ui.button("Keep stopped").clicked() {
agent.send(Command::SetActive {
network_id: network.network_id.clone(),
active: false,
});
}
} else {
let mut active = network.active;
if ui.checkbox(&mut active, "active").changed() {
agent.send(Command::SetActive {
network_id: network.network_id.clone(),
active,
});
}
}
let mut broadcast = network.broadcast;
if ui.checkbox(&mut broadcast, "broadcast").changed() {
agent.send(Command::SetBroadcast {
network_id: network.network_id.clone(),
enabled: broadcast,
});
}
if offer_exit {
let mut offering = network.exit.offering;
if offer_exit && ui
if ui
.checkbox(&mut offering, "exit node")
.on_hover_text(
"let other members send all their internet traffic through this \
device, which can see it",
)
.on_hover_text("Let members send all their internet traffic through this device, which can see it.")
.changed()
{
agent.send(Command::SetExitOffer {
@@ -219,54 +350,108 @@ pub fn draw_network(
enabled: offering,
});
}
});
ui.horizontal(|ui| {
// In the bottom left corner while this device sends its traffic through
// somebody: green while that works, red while it does not.
if let Some(via) = &network.exit.via {
let color = if network.exit.via_online {
exit::GOOD
} else {
exit::LOUD
};
let response = ui
.add(
egui::Label::new(
egui::RichText::new(icon::SIGN_OUT).size(18.0).color(color),
)
.sense(egui::Sense::click()),
)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(format!(
"exit node: {} — click to stop",
exit::name_of(network, via)
));
if response.clicked() {
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
}
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Show devices").clicked() {
state.open_devices.insert(network.network_id.clone());
}
if ui
.button(format!("{} Copy secret", icon::COPY))
.on_hover_text("copy this network's secret to the clipboard")
.clicked()
{
agent.send(Command::CopySecret {
network_id: network.network_id.clone(),
});
}
} else {
pick_exit = ui.button("Exit node…").clicked();
}
let leave = egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE))
.fill(LEAVE_RED);
if ui.add(leave).clicked() {
agent.send(Command::Leave {
network_id: network.network_id.clone(),
});
});
for warning in exit::warnings(network) {
draw_exit_warning(ui, &warning);
}
});
pick_exit
}
fn network_header(ui: &mut egui::Ui, name: &str, status: &str, open: bool) -> egui::Response {
let height = ui.text_style_height(&egui::TextStyle::Heading).max(30.0);
let (rect, response) = ui.allocate_exact_size(
egui::vec2(ui.available_width(), height),
egui::Sense::click(),
);
response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::CollapsingHeader, ui.is_enabled(), name)
});
let visuals = ui.style().interact(&response);
if response.hovered() || response.has_focus() {
ui.painter().rect_filled(rect, 3.0, visuals.weak_bg_fill);
}
let font = egui::TextStyle::Body.resolve(ui.style());
ui.painter().text(
rect.left_center(),
egui::Align2::LEFT_CENTER,
if open {
icon::CARET_DOWN
} else {
icon::CARET_RIGHT
},
font.clone(),
visuals.text_color(),
);
let end = ui.painter().text(
rect.right_center(),
egui::Align2::RIGHT_CENTER,
status,
font.clone(),
ui.visuals().text_color(),
);
let left = rect.left() + font.size + 6.0;
let mut job = egui::text::LayoutJob::simple_singleline(
name.into(),
egui::FontId::new(font.size + 4.0, egui::FontFamily::Name("Bold".into())),
ui.visuals().strong_text_color(),
);
job.wrap.max_width = (end.left() - left - 8.0).max(0.0);
job.wrap.max_rows = 1;
job.wrap.break_anywhere = true;
let title = ui.painter().layout_job(job);
ui.painter().galley(
egui::pos2(left, rect.center().y - title.size().y / 2.0),
title,
visuals.text_color(),
);
widgets::hint(
response.on_hover_cursor(egui::CursorIcon::PointingHand),
name,
)
}
fn draw_selected_exit(ui: &mut egui::Ui, network: &NetworkReport, via: &str, state: &mut UiState) {
ui.horizontal_wrapped(|ui| {
let color = if network.exit.via_online {
exit::GOOD
} else {
exit::LOUD
};
let name = exit::name_of(network, via);
let button = ui
.add(egui::Button::new(egui::RichText::new(icon::SIGN_OUT).color(color)).frame(false));
let clicked = widgets::hint(button, "Stop using this exit node").clicked();
if widgets::hint(
ui.link(format!("Exit via {name}")),
"Stop using this exit node",
)
.clicked()
|| clicked
{
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
}
if let Some(t) = network.exit.traffic {
for (glyph, bytes, hint) in [
(icon::ARROW_UP, t.tx_bytes, "Sent through this exit"),
(icon::ARROW_DOWN, t.rx_bytes, "Received through this exit"),
] {
let text = format!("{glyph} {}", format::bytes(bytes as f64));
widgets::hint(
ui.add(egui::Label::new(text).sense(egui::Sense::click())),
hint,
);
}
}
});
}
fn draw_protocols(
ui: &mut egui::Ui,
agent: &dyn Client,
@@ -309,21 +494,16 @@ fn draw_protocols(
changed = true;
}
if let Some(index) = selected.iter().position(|p| p == &protocol.name) {
if ui
.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP))
.on_hover_text("prefer earlier")
.clicked()
if widgets::hint(ui.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP)),
"Move transport up in preference order").clicked()
{
selected.swap(index, index - 1);
changed = true;
}
if ui
.add_enabled(
if widgets::hint(ui.add_enabled(
index + 1 < selected.len(),
egui::Button::new(icon::ARROW_DOWN),
)
.on_hover_text("prefer later")
.clicked()
), "Move transport down in preference order").clicked()
{
selected.swap(index, index + 1);
changed = true;
@@ -384,18 +564,47 @@ pub fn draw_join(ui: &mut egui::Ui, agent: &dyn Client, join: &mut JoinForm) {
ui.label("secret");
ui.horizontal(|ui| {
ui.add(
egui::TextEdit::singleline(&mut *join.secret)
.id("join-secret".into())
.desired_width(INPUT_WIDTH - 26.0)
.password(true),
);
if ui
.button(icon::SHUFFLE)
.on_hover_text("Generate a new random secret")
.clicked()
let visuals = ui.visuals().widgets.inactive;
egui::Frame::new()
.fill(ui.visuals().extreme_bg_color)
.stroke(visuals.bg_stroke)
.corner_radius(visuals.corner_radius)
.inner_margin(egui::Margin::symmetric(3, 1))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
let input = ui.add(
egui::TextEdit::singleline(&mut *join.secret)
.id("join-secret".into())
.frame(false)
.desired_width(INPUT_WIDTH - 65.0)
.password(!join.revealed),
);
let (glyph, label) = if join.revealed {
(icon::EYE_SLASH, "Hide secret")
} else {
(icon::EYE, "Show secret")
};
let eye = ui.add(egui::Button::new(glyph).frame(false));
eye.widget_info(|| {
egui::WidgetInfo::labeled(
egui::WidgetType::Button,
eye.enabled(),
label,
)
});
if widgets::hint(eye, label).clicked() {
join.revealed = !join.revealed;
if input.lost_focus() {
input.request_focus();
}
}
});
});
if widgets::icon_button(ui, icon::SHUFFLE, "Generate a new random secret").clicked()
{
join.secret = tsunagi::identity::NetworkSecret::generate().encode();
join.revealed = false;
}
});
ui.end_row();
@@ -411,5 +620,6 @@ pub fn draw_join(ui: &mut egui::Ui, agent: &dyn Client, join: &mut JoinForm) {
secret: Zeroizing::new(join.secret.trim().to_owned()),
});
join.secret.zeroize();
join.revealed = false;
}
}
+13 -1
View File
@@ -6,14 +6,26 @@ mod exit;
pub mod format;
pub mod home;
pub mod listeners;
#[cfg(test)]
mod presentation_tests;
pub mod stats;
mod table;
pub mod vip;
mod vip_status;
pub mod widgets;
/// Install the tray's regular Phosphor glyphs alongside egui's standard fonts.
/// Install the Phosphor icons and bold network title face for both egui clients.
pub fn app_fonts() -> egui::FontDefinitions {
let mut fonts = egui::FontDefinitions::default();
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
let mut bold = fonts.families[&egui::FontFamily::Proportional].clone();
bold.insert(0, "Source Sans Pro Bold".into());
fonts.font_data.insert(
"Source Sans Pro Bold".into(),
egui::FontData::from_static(include_bytes!("../fonts/SourceSansPro-Bold.ttf")).into(),
);
fonts
.families
.insert(egui::FontFamily::Name("Bold".into()), bold);
fonts
}
+262
View File
@@ -0,0 +1,262 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use crate::{
client::{Client, Command},
devices, home,
stats::{Traffic, Unit},
};
use egui::{Context, Event, FullOutput, Pos2, Rect, Vec2};
use egui_phosphor::regular as icon;
use tsunagi::ipc::{
DataPathReport, MemberReport, NetworkReport, OverlayPeerReport, OverlayReport, PeerReport,
};
#[test]
fn keyboard_focus_explains_an_icon_and_the_shared_font_contains_the_status_glyphs() {
let ctx = Context::default();
ctx.set_fonts(crate::app_fonts());
let draw = |time| {
frame(&ctx, egui::vec2(360., 500.), time, vec![], |ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
let r = crate::widgets::icon_button(ui, icon::EYE, "Show secret");
r.request_focus();
let font = egui::TextStyle::Body.resolve(ui.style());
for glyph in [
icon::EYE,
icon::EYE_SLASH,
icon::NETWORK,
icon::CHECK_CIRCLE,
icon::WARNING,
icon::MINUS_CIRCLE,
icon::PAUSE_CIRCLE,
icon::MOON,
icon::SIGN_OUT,
icon::FINGERPRINT,
icon::HASH,
icon::TREE_STRUCTURE,
icon::DEVICE_MOBILE,
icon::DEVICES,
icon::BROADCAST,
icon::FLOW_ARROW,
icon::GITHUB_LOGO,
icon::SCALES,
] {
assert!(
ui.fonts(|f| f.has_glyphs(&font, glyph)),
"missing glyph {glyph}"
);
}
});
})
};
draw(0.);
draw(0.1);
assert!(label(&draw(0.2), "Show secret").is_some());
}
struct ReadOnly;
impl Client for ReadOnly {
fn busy(&self) -> bool {
false
}
fn send(&self, _: Command) {
panic!("reading the UI issued a command");
}
}
fn frame(
ctx: &Context,
size: Vec2,
time: f64,
events: Vec<Event>,
draw: impl FnMut(&Context),
) -> FullOutput {
ctx.run(
egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)),
time: Some(time),
events,
..Default::default()
},
draw,
)
}
fn label(frame: &FullOutput, value: &str) -> Option<Rect> {
frame.shapes.iter().find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == value => Some(t.visual_bounding_rect()),
_ => None,
})
}
fn press(pos: Pos2, pressed: bool) -> Event {
Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
}
}
#[test]
fn secret_eye_masks_by_default_and_long_touch_explains_without_revealing() {
let ctx = Context::default();
ctx.set_fonts(crate::app_fonts());
ctx.set_os(egui::os::OperatingSystem::Android);
let mut form = home::JoinForm::default();
form.secret.push_str("test-only-value");
let mut draw = |time, events| {
frame(&ctx, egui::vec2(360., 720.), time, events, |ctx| {
egui::CentralPanel::default().show(ctx, |ui| home::draw_join(ui, &ReadOnly, &mut form));
})
};
draw(0., vec![]);
let masked = draw(0.1, vec![]);
assert!(label(&masked, "test-only-value").is_none());
let eye = label(&masked, icon::EYE)
.expect("show secret button")
.center();
let touch = |phase| Event::Touch {
device_id: egui::TouchDeviceId(0),
id: egui::TouchId(1),
phase,
pos: eye,
force: None,
};
draw(
0.2,
vec![
touch(egui::TouchPhase::Start),
Event::PointerMoved(eye),
press(eye, true),
],
);
draw(1.2, vec![]);
let held = draw(1.3, vec![]);
assert!(label(&held, "Show secret").is_some());
draw(
1.4,
vec![
touch(egui::TouchPhase::End),
press(eye, false),
Event::PointerGone,
],
);
assert!(label(&draw(1.5, vec![]), "test-only-value").is_none());
for (time, visible) in [(2., true), (3., false)] {
draw(time, vec![Event::PointerMoved(eye), press(eye, true)]);
draw(time + 0.1, vec![press(eye, false)]);
let out = draw(time + 0.2, vec![]);
assert_eq!(label(&out, "test-only-value").is_some(), visible);
assert!(label(&out, if visible { icon::EYE_SLASH } else { icon::EYE }).is_some());
}
}
#[test]
fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_screen() {
let ctx = Context::default();
ctx.set_os(egui::os::OperatingSystem::Android);
ctx.set_fonts(crate::app_fonts());
let mut net = NetworkReport {
name: "lab".into(),
network_id: "network".into(),
..Default::default()
};
for (id, state) in [
("alpha", "ready"),
("bravo", "waiting"),
("charlie", "error"),
("delta", "offline"),
("echo", "control only"),
("foxtrot", "idle"),
] {
net.members.push(MemberReport {
endpoint_id: id.into(),
hostname: Some(id.into()),
online: state != "offline",
overlay_address_v4: Some("192.168.254.251".into()),
..Default::default()
});
if state != "offline" {
net.peers.push(PeerReport {
endpoint_id: id.into(),
path: DataPathReport::Relayed {
hops: 2,
via: "another".into(),
},
data_error: match state {
"waiting" => Some(tsunagi::agent::DATA_CONNECTING.into()),
"error" => Some("Carrier unavailable".into()),
"control only" => Some(tsunagi::agent::DATA_DISABLED.into()),
_ => None,
},
agent_version: Some("1.0.4".into()),
..Default::default()
});
}
}
let mut overlay_peers = vec![OverlayPeerReport {
endpoint_id: "alpha".into(),
handshake_secs_ago: Some(2),
tx_bytes: 2048,
rx_bytes: 512,
..Default::default()
}];
// Only the reachable peer with a healthy path may show Idle. A problem
// or an offline observation takes precedence over quiet IP counters.
overlay_peers.extend(["bravo", "charlie", "delta", "echo", "foxtrot"].map(|id| {
OverlayPeerReport {
endpoint_id: id.into(),
idle: true,
..Default::default()
}
}));
net.overlay = Some(OverlayReport {
peers: overlay_peers,
..Default::default()
});
let draw = |size, time, events| {
frame(&ctx, size, time, events, |ctx| {
devices::show(
ctx,
&ReadOnly,
&mut Unit::Bytes,
(&mut None, &mut None),
&net,
"self",
&Traffic::default(),
)
})
};
let portrait = egui::vec2(360., 740.);
draw(portrait, 0., vec![]);
let pos = label(&draw(portrait, 0.1, vec![]), "alpha")
.unwrap()
.center();
draw(
portrait,
0.2,
vec![Event::PointerMoved(pos), press(pos, true)],
);
draw(portrait, 0.3, vec![press(pos, false)]);
for (index, width) in [580., 740., 960.].into_iter().enumerate() {
let size = egui::vec2(width, 360.);
let time = 1. + index as f64;
draw(size, time, vec![]);
let out = draw(size, time + 0.1, vec![]);
for text in [
"bytes (TX / RX)",
"2.0 kB / 512 B",
"Ready",
"Idle",
"Waiting",
"Error",
"Offline",
"Control only",
"Endpoint ID",
] {
let rect = label(&out, text).unwrap_or_else(|| panic!("missing {text} at {width}"));
assert!(
rect.left() >= 0. && rect.right() <= width,
"{text} exceeds {width}: {rect:?}"
);
}
}
assert!(label(&draw(portrait, 4., vec![]), "Endpoint ID").is_some());
}
+9
View File
@@ -23,6 +23,15 @@ pub enum Unit {
Bytes,
}
impl Unit {
pub(crate) fn counters(self, peer: &OverlayPeerReport) -> (u64, u64) {
match self {
Self::Packets => (peer.tx_packets, peer.rx_packets),
Self::Bytes => (peer.tx_bytes, peer.rx_bytes),
}
}
}
/// One series' rolling packet and byte rates.
#[derive(Default)]
pub struct Series {
+21 -6
View File
@@ -93,8 +93,16 @@ pub fn show(
let mut close = state.close_after_save && !state.dirty();
let mut discard_new = false;
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading(format!("VIP · {}", n.name));
ui.weak("Configuration is shared with every member. Changes take effect only after Save.");
let wide = ui.available_width() >= 580.;
ui.horizontal_wrapped(|ui| {
ui.heading(format!("VIP · {}", n.name));
crate::widgets::field(
ui,
egui_phosphor::regular::INFO,
"",
"Configuration is shared with every member. Changes take effect only after Save.",
);
});
if state.close_question {
ui.horizontal_wrapped(|ui| {
ui.label("Unsaved changes.");
@@ -176,7 +184,15 @@ pub fn show(
);
}
let busy = state.pending.is_some();
let tabs = |ui: &mut egui::Ui, configure: &mut bool| {
ui.selectable_value(configure, false, "Overview");
ui.selectable_value(configure, true, "Configuration");
};
ui.horizontal_wrapped(|ui| {
if wide {
tabs(ui, &mut state.configure);
ui.separator();
}
let valid = draft.config.validate(&tsunagi::Limits::default());
if !n.active {
ui.weak("Start the network to save changes.");
@@ -224,10 +240,9 @@ pub fn show(
}
});
ui.separator();
ui.horizontal(|ui| {
ui.selectable_value(&mut state.configure, false, "Overview");
ui.selectable_value(&mut state.configure, true, "Configuration");
});
if !wide {
ui.horizontal(|ui| tabs(ui, &mut state.configure));
}
egui::ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
+63 -19
View File
@@ -229,12 +229,15 @@ pub(crate) fn show(ui: &mut egui::Ui, v: &VipStatus, n: &NetworkReport, view: &m
ui.separator();
diagram(ui, v, l, n, view);
ui.add_space(6.0);
egui::ScrollArea::horizontal()
.id_salt("backend table scroll")
.auto_shrink([false, true])
.show(ui, |ui| {
backend_table(ui, v, l, n, view);
});
let phone = ui.ctx().os() == egui::os::OperatingSystem::Android;
if phone {
backend_table(ui, v, l, n, view, true);
} else {
egui::ScrollArea::horizontal()
.id_salt("backend table scroll")
.auto_shrink([false, true])
.show(ui, |ui| backend_table(ui, v, l, n, view, false));
}
if let Some(b) = l
.backends
.iter()
@@ -271,6 +274,23 @@ pub(crate) fn show(ui: &mut egui::Ui, v: &VipStatus, n: &NetworkReport, view: &m
format::copy_field(ui, address, address);
}
});
if phone {
let rates = view.backends.get(&key(v, l, &b.backend));
ui.horizontal_wrapped(|ui| {
metric(ui, "TX", &format::bytes(b.counters.tx_bytes as f64));
metric(ui, "RX", &format::bytes(b.counters.rx_bytes as f64));
metric(
ui,
"TX rate",
&format::series_rate(rates.map(|r| &r.tx), view.unit),
);
metric(
ui,
"RX rate",
&format::series_rate(rates.map(|r| &r.rx), view.unit),
);
});
}
});
}
});
@@ -307,6 +327,7 @@ fn backend_table(
l: &ListenerStatus,
n: &NetworkReport,
view: &mut View,
fit: bool,
) {
let headers = [
"Backend",
@@ -365,17 +386,40 @@ fn backend_table(
);
}
}
let widths_id = ui.id().with("backend column widths");
if let Some(previous) = ui.memory(|memory| memory.data.get_temp::<[f32; 8]>(widths_id)) {
for (width, previous) in widths.iter_mut().zip(previous) {
*width = width.max(previous);
let columns: Vec<usize> = if fit {
let mut columns = vec![0, 1, 3];
let free = ui.available_width();
// Keep health and RTT visible even on a portrait phone. Secondary values
// also live in the selected backend's details.
widths[1] = 90.0_f32.min(free * 0.30);
widths[3] = 65.0_f32.min(free * 0.21);
let mut reserved = widths[1] + widths[3] + 2. * table::GAP;
for column in [2, 4, 5, 6, 7] {
let next = reserved + widths[column] + table::GAP;
if free - next < 115. {
break;
}
columns.push(column);
reserved = next;
}
}
ui.memory_mut(|memory| memory.data.insert_temp(widths_id, widths));
let fixed = widths.iter().sum::<f32>() + table::GAP * 7.0;
widths[7] += (ui.available_width() - fixed).max(0.0);
table::row(ui, "backend headers", &widths, false, |column, ui| {
ui.weak(headers[column]);
widths[0] = (free - reserved).max(0.);
columns.sort_unstable();
columns
} else {
let widths_id = ui.id().with("backend column widths");
if let Some(previous) = ui.memory(|memory| memory.data.get_temp::<[f32; 8]>(widths_id)) {
for (width, previous) in widths.iter_mut().zip(previous) {
*width = width.max(previous);
}
}
ui.memory_mut(|memory| memory.data.insert_temp(widths_id, widths));
let fixed = widths.iter().sum::<f32>() + table::GAP * 7.0;
widths[7] += (ui.available_width() - fixed).max(0.0);
(0..widths.len()).collect()
};
let visible: Vec<_> = columns.iter().map(|&i| widths[i]).collect();
table::row(ui, "backend headers", &visible, false, |column, ui| {
ui.weak(headers[columns[column]]);
});
for (index, b) in l.backends.iter().enumerate() {
let key = key(v, l, &b.backend);
@@ -383,9 +427,9 @@ fn backend_table(
table::row(
ui,
&key,
&widths,
&visible,
index % 2 == 0,
|column, ui| match column {
|column, ui| match columns[column] {
0 => {
if ui
.selectable_label(view.selected.as_ref() == Some(&key), &values[index][0])
@@ -416,7 +460,7 @@ fn backend_table(
);
}
3..=6 => {
ui.label(&values[index][column]);
ui.label(&values[index][columns[column]]);
}
_ => format::sparkline(ui, rates.map(|r| &r.total), view.unit, 24.0),
},
+81
View File
@@ -0,0 +1,81 @@
//! Icons with the same meaning and input behavior across both clients.
use egui::{Response, Sense, Ui, WidgetInfo, WidgetType};
use egui_phosphor::regular as icon;
/// Supplied by Android so the soft keyboard never looks like an orientation change.
pub fn set_landscape(ctx: &egui::Context, landscape: bool) {
ctx.data_mut(|d| d.insert_temp(egui::Id::new("window landscape"), landscape));
}
/// Whether this viewport has a landscape layout.
pub fn landscape(ctx: &egui::Context) -> bool {
ctx.data(|d| d.get_temp(egui::Id::new("window landscape")))
.unwrap_or_else(|| ctx.screen_rect().width() > ctx.screen_rect().height())
}
/// A tooltip for mouse hover, keyboard focus or a deliberate long press.
pub fn hint(response: Response, description: &str) -> Response {
let ctx = &response.ctx;
let touch = ctx.os() == egui::os::OperatingSystem::Android;
let now = ctx.input(|i| i.time);
let key = egui::Id::new(("touch explanation", ctx.viewport_id()));
if response.long_touched() {
ctx.data_mut(|d| d.insert_temp(key, (response.id, now + 2.5)));
ctx.request_repaint();
}
let held = ctx
.data(|d| d.get_temp::<(egui::Id, f64)>(key))
.filter(|(id, until)| touch && *id == response.id && now < *until);
if held.is_some() || (!touch && response.has_focus()) {
egui::show_tooltip_for(ctx, response.layer_id, response.id, &response.rect, |ui| {
ui.set_max_width(
ui.spacing()
.tooltip_width
.min(ctx.screen_rect().width() - 16.),
);
ui.label(description);
});
if let Some((_, until)) = held {
ctx.request_repaint_after_secs((until - now) as f32);
}
response
} else {
response
.on_hover_text(description)
.on_disabled_hover_text(description)
}
}
/// A glyph-only button with its action exposed to assistive technology.
pub fn icon_button(ui: &mut Ui, glyph: &str, description: &str) -> Response {
let r = ui.button(glyph);
r.widget_info(|| WidgetInfo::labeled(WidgetType::Button, r.enabled(), description));
hint(r, description)
}
/// A field caption, or just its icon when the adjacent value is self-explanatory.
pub(crate) fn field(ui: &mut Ui, glyph: &str, caption: &str, description: &str) {
let label = if caption.is_empty() {
glyph.to_string()
} else {
format!("{glyph} {caption}")
};
let r = ui.add(egui::Label::new(egui::RichText::new(label).weak()).sense(Sense::click()));
r.widget_info(|| WidgetInfo::labeled(WidgetType::Label, r.enabled(), description));
hint(r, description);
}
pub(crate) fn network_id(ui: &mut Ui) {
field(ui, icon::HASH, "", "Network ID");
}
pub(crate) fn range(ui: &mut Ui) {
field(ui, icon::TREE_STRUCTURE, "", "Network range (CIDR)");
}
pub(crate) fn device_address(ui: &mut Ui) {
let glyph = if ui.ctx().os() == egui::os::OperatingSystem::Android {
icon::DEVICE_MOBILE
} else {
icon::LAPTOP
};
field(ui, glyph, "", "This device’s IPv4 address");
}
+2 -2
View File
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
# Its own version, and deliberately separate from the wire version it
# negotiates: a release here does not stop it talking to a peer on an older
# build, because what peers compare is `ANNOUNCEMENT_VERSION`.
version = "1.0.3-rc1"
version = "1.0.5"
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
edition.workspace = true
rust-version.workspace = true
@@ -11,7 +11,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true
tokio.workspace = true
serde.workspace = true
+240 -48
View File
@@ -32,7 +32,7 @@ use std::collections::{HashMap, VecDeque};
use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;
use std::time::{Duration, Instant};
use boringtun::noise::{Tunn, TunnResult};
use bytes::Bytes;
@@ -41,7 +41,7 @@ use tokio::task::JoinHandle;
use tsunagi::dataplane::routing::{FlowId, flow::ip_flow};
use tsunagi::dataplane::transport::{SharedLink, TransportError};
use tsunagi::dataplane::{PacketSink, PluginError};
use tsunagi::dataplane::{PacketSink, PluginContext, PluginError};
use tsunagi::identity::NetworkId;
use crate::keys::{WgPublicKey, WgSecretKey};
@@ -52,6 +52,11 @@ use crate::keys::{WgPublicKey, WgSecretKey};
/// drives handshakes, rekeying and keepalives.
const TIMER_INTERVAL: Duration = Duration::from_millis(250);
/// Start renewing the selected exit at WireGuard's normal rekey age. The
/// current key can still carry data for a minute while its successor is agreed.
const WARM_REKEY_AFTER: Duration = Duration::from_secs(120);
const IDLE_AFTER: Duration = Duration::from_secs(30);
/// Scratch space for one encapsulate or decapsulate call.
const SCRATCH: usize = 4096;
@@ -60,10 +65,13 @@ const SCRATCH: usize = 4096;
struct FlowTunnel {
tunn: Tunn,
queued: VecDeque<(FlowId, usize)>,
/// First usable session or most recent IP payload. Keepalives and later
/// handshakes leave this alone, including when the current key expires.
last_activity: Option<Instant>,
}
fn is_data(result: &TunnResult<'_>) -> bool {
matches!(result, TunnResult::WriteToNetwork(bytes) if bytes.starts_with(&[4, 0, 0, 0]))
fn carries_ip(frame: &[u8]) -> bool {
frame.len() > crate::plugin::WIREGUARD_OVERHEAD as usize && frame.starts_with(&[4, 0, 0, 0])
}
impl FlowTunnel {
@@ -74,7 +82,11 @@ impl FlowTunnel {
flow: FlowId,
) -> (TunnResult<'a>, FlowId) {
let result = self.tunn.encapsulate(packet, scratch);
if is_data(&result) {
if packet.is_empty() {
return (result, 0);
}
if matches!(&result, TunnResult::WriteToNetwork(out) if carries_ip(out)) {
self.last_activity = Some(Instant::now());
return (result, flow);
}
// MAX_QUEUE_DEPTH in boringtun 0.7: the newest packet is dropped at 256.
@@ -89,32 +101,83 @@ impl FlowTunnel {
packet: &[u8],
scratch: &'a mut [u8],
) -> (TunnResult<'a>, FlowId, Option<usize>) {
// Empty input asks BoringTun to drain its FIFO. Wait for a usable key
// so a failed drain cannot reorder IP packets among queued keepalives.
if packet.is_empty() && self.tunn.time_since_last_handshake().is_none() {
return (TunnResult::Done, 0, None);
}
let result = self.tunn.decapsulate(None, packet, scratch);
let (mut flow, mut plaintext_len) = (0, None);
if packet.is_empty() {
if is_data(&result) {
if let Some((tag, len)) = self.queued.pop_front() {
flow = tag;
plaintext_len = Some(len);
match &result {
TunnResult::WriteToNetwork(out) if carries_ip(out) => {
if let Some((tag, len)) = self.queued.pop_front() {
flow = tag;
plaintext_len = Some(len);
}
}
} else if let Some(pending) = self.queued.pop_front() {
// Without a session, draining pops the oldest IP packet and
// encapsulate queues it again at the back.
self.queued.push_back(pending);
// An internal keepalive may occupy a slot in the bounded
// FIFO. Discard tags for IP packets BoringTun could not queue.
TunnResult::Done => self.queued.clear(),
_ => {}
}
}
if matches!(
result,
TunnResult::WriteToTunnelV4(..) | TunnResult::WriteToTunnelV6(..)
) || plaintext_len.is_some()
|| (self.last_activity.is_none() && self.tunn.time_since_last_handshake().is_some())
{
self.last_activity = Some(Instant::now());
}
(result, flow, plaintext_len)
}
fn update_timers<'a>(&mut self, scratch: &'a mut [u8]) -> TunnResult<'a> {
let result = self.tunn.update_timers(scratch);
if matches!(
result,
TunnResult::Err(boringtun::noise::errors::WireGuardError::ConnectionExpired)
) {
self.queued.clear();
fn health(&self, now: Instant, keep_warm: bool) -> PeerHealth {
let since_handshake = self.tunn.time_since_last_handshake();
let idle = self.queued.is_empty()
&& (!keep_warm || since_handshake.is_some())
&& self
.last_activity
.is_some_and(|at| now.duration_since(at) >= IDLE_AFTER);
PeerHealth {
since_handshake,
idle,
}
}
fn update_timers(
&mut self,
scratch: &mut [u8],
refresh_after: Option<Duration>,
) -> Option<usize> {
match self.tunn.update_timers(scratch) {
TunnResult::WriteToNetwork(out) => return Some(out.len()),
TunnResult::Err(boringtun::noise::errors::WireGuardError::ConnectionExpired) => {
if !self.queued.is_empty() {
// BoringTun gave up on pending IP packets. Keep reporting
// a waiting tunnel until a new session actually succeeds.
self.last_activity = None;
self.queued.clear();
}
}
TunnResult::Err(err) => tracing::trace!(?err, "wireguard timer produced an error"),
_ => {}
}
let after = refresh_after?;
if self
.tunn
.time_since_last_handshake()
.is_some_and(|age| age < after)
{
return None;
}
// An in-flight exchange and its retries remain under BoringTun's
// timers. Asking without forcing never restarts one.
match self.tunn.format_handshake_initiation(scratch, false) {
TunnResult::WriteToNetwork(out) => Some(out.len()),
_ => None,
}
result
}
}
@@ -164,15 +227,14 @@ pub struct PeerStats {
/// Whether a peer's tunnel has completed a handshake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PeerHealth {
/// Time since the last successful WireGuard handshake.
///
/// `None` means no handshake has completed yet, so the tunnel is not
/// carrying traffic. This is reported as it is, never guessed.
/// Age of the last handshake while a usable WireGuard session exists.
pub since_handshake: Option<Duration>,
/// A previously established tunnel with no recent or queued IP traffic.
pub idle: bool,
}
impl PeerHealth {
/// Whether the tunnel has ever completed a handshake.
/// Whether the tunnel currently has a usable session key.
pub fn is_up(&self) -> bool {
self.since_handshake.is_some()
}
@@ -227,14 +289,12 @@ impl Peer {
}
}
fn health(&self) -> PeerHealth {
fn health(&self, keep_warm: bool) -> PeerHealth {
let guard = match self.tunn.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
PeerHealth {
since_handshake: guard.tunn.time_since_last_handshake(),
}
guard.health(Instant::now(), keep_warm)
}
}
@@ -259,6 +319,7 @@ pub struct PeerSummary {
struct Inner {
network: NetworkId,
context: PluginContext,
private_key: WgSecretKey,
peers: RwLock<HashMap<WgPublicKey, Arc<Peer>>>,
/// Where decrypted packets go.
@@ -292,11 +353,20 @@ impl WireguardDevice {
/// leave through the sink. Which address belongs to whom, and therefore
/// where a packet should go, is decided above this.
pub fn start(network: NetworkId, private_key: WgSecretKey, sink: Arc<dyn PacketSink>) -> Self {
Self::start_with_context(network, private_key, PluginContext::with_sink(sink))
}
pub(crate) fn start_with_context(
network: NetworkId,
private_key: WgSecretKey,
context: PluginContext,
) -> Self {
let inner = Arc::new(Inner {
network,
private_key,
peers: RwLock::new(HashMap::new()),
sink,
sink: context.packet_sink(),
context,
next_index: AtomicU32::new(1),
});
@@ -336,7 +406,7 @@ impl WireguardDevice {
let (result, selected_flow) = tunn.encapsulate(packet, &mut scratch, flow);
match result {
TunnResult::WriteToNetwork(out) => {
Some((out.len(), selected_flow, out.starts_with(&[4, 0, 0, 0])))
Some((out.len(), selected_flow, carries_ip(out)))
}
// No session yet, so nothing to send. Counted as dropped
// rather than reported: the handshake is in flight and the
@@ -394,6 +464,7 @@ impl WireguardDevice {
tunn: Mutex::new(FlowTunnel {
tunn,
queued: VecDeque::new(),
last_activity: None,
}),
link,
counters: Arc::new(PeerCounters {
@@ -442,6 +513,7 @@ impl WireguardDevice {
/// A snapshot of every peer.
pub fn peers(&self) -> Vec<PeerSummary> {
let warm_peer = self.inner.context.warm_peer(self.inner.network);
let mut peers: Vec<PeerSummary> = read_lock(&self.inner.peers)
.values()
.map(|peer| {
@@ -453,7 +525,7 @@ impl WireguardDevice {
endpoint_id: peer.endpoint_id,
public_key: peer.public_key,
overlay_address_v4: overlay_v4,
health: peer.health(),
health: peer.health(warm_peer == Some(peer.endpoint_id)),
stats: peer.stats(),
path: peer.link.path_description(),
max_datagram: peer.link.max_datagram_size(),
@@ -546,14 +618,14 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
// any packets that were queued while the session was coming up.
let mut input: Option<&[u8]> = Some(&datagram);
loop {
let outcome = {
let (outcome, drain_pending) = {
let mut tunn = match peer.tunn.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
let (result, flow, plaintext_len) =
tunn.decapsulate(input.unwrap_or(&[]), &mut scratch);
match result {
let outcome = match result {
TunnResult::WriteToNetwork(out) => {
Outcome::ToNetwork(out.len(), flow, plaintext_len)
}
@@ -567,7 +639,8 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
tracing::trace!(?err, "wireguard decapsulation failed");
Outcome::Failed
}
}
};
(outcome, input.is_some() && !tunn.queued.is_empty())
};
match outcome {
@@ -595,7 +668,6 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
peer.counters
.rx_bytes
.fetch_add(len as u64, Ordering::Relaxed);
break;
}
Outcome::Failed => {
peer.counters
@@ -603,8 +675,14 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
.fetch_add(1, Ordering::Relaxed);
break;
}
Outcome::Done => break,
Outcome::Done => {}
}
// A responder can first confirm its key on an incoming keepalive
// or IP packet. Flush waiting application traffic on that path too.
if !drain_pending {
break;
}
input = None;
}
}
}
@@ -620,24 +698,20 @@ enum Outcome {
async fn drive_timers(inner: Arc<Inner>) {
let mut ticker = tokio::time::interval(TIMER_INTERVAL);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut scratch = vec![0u8; SCRATCH];
loop {
ticker.tick().await;
let warm_peer = inner.context.warm_peer(inner.network);
let peers: Vec<Arc<Peer>> = read_lock(&inner.peers).values().cloned().collect();
for peer in peers {
let mut scratch = vec![0u8; SCRATCH];
let len = {
let mut tunn = match peer.tunn.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
match tunn.update_timers(&mut scratch) {
TunnResult::WriteToNetwork(out) => Some(out.len()),
TunnResult::Err(err) => {
tracing::trace!(?err, "wireguard timer produced an error");
None
}
_ => None,
}
let refresh_after =
(warm_peer == Some(peer.endpoint_id)).then_some(WARM_REKEY_AFTER);
tunn.update_timers(&mut scratch, refresh_after)
};
if let Some(len) = len {
send_to_peer(&peer, &scratch[..len]);
@@ -662,6 +736,7 @@ mod flow_tests {
None,
),
queued: VecDeque::new(),
last_activity: None,
}
}
fn wire(result: TunnResult<'_>) -> Vec<u8> {
@@ -671,6 +746,123 @@ mod flow_tests {
}
}
fn establish(a: &mut FlowTunnel, b: &mut FlowTunnel, scratch: &mut [u8]) {
let hello = wire(a.tunn.format_handshake_initiation(scratch, false));
let response = wire(b.decapsulate(&hello, scratch).0);
let confirmation = wire(a.decapsulate(&response, scratch).0);
let _ = b.decapsulate(&confirmation, scratch);
}
#[test]
fn only_a_due_warm_tunnel_rekeys_and_the_old_key_carries_data_during_the_exchange() {
let ak = WgSecretKey::from_bytes(&[1; 32]);
let bk = WgSecretKey::from_bytes(&[2; 32]);
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
let mut scratch = [0u8; SCRATCH];
establish(&mut a, &mut b, &mut scratch);
assert!(a.update_timers(&mut scratch, None).is_none());
assert!(
a.update_timers(&mut scratch, Some(WARM_REKEY_AFTER))
.is_none()
);
// Make the renewal due now, then withhold its response. BoringTun still
// owns both generations of keys and its normal retry timer.
let len = a.update_timers(&mut scratch, Some(Duration::ZERO)).unwrap();
let hello = scratch[..len].to_vec();
assert_eq!(&hello[..4], &[1, 0, 0, 0]);
assert!(
a.update_timers(&mut scratch, Some(Duration::ZERO))
.is_none()
);
let mut ip = [0u8; 20];
ip[0] = 0x45;
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
for generation in 0..2 {
ip[19] = generation;
let ciphertext = wire(a.encapsulate(&ip, &mut scratch, 7).0);
assert!(matches!(b.decapsulate(&ciphertext, &mut scratch).0,
TunnResult::WriteToTunnelV4(bytes, _) if bytes == ip));
if generation == 0 {
let reply = wire(b.decapsulate(&hello, &mut scratch).0);
let confirmation = wire(a.decapsulate(&reply, &mut scratch).0);
let _ = b.decapsulate(&confirmation, &mut scratch);
}
}
assert!(a.queued.is_empty());
}
#[test]
fn idle_survives_background_handshakes_but_never_hides_pending_ip_or_a_cold_exit() {
let ak = WgSecretKey::from_bytes(&[1; 32]);
let bk = WgSecretKey::from_bytes(&[2; 32]);
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
let mut scratch = [0u8; SCRATCH];
assert!(!a.health(Instant::now() + IDLE_AFTER, false).idle);
establish(&mut a, &mut b, &mut scratch);
assert!(!a.health(Instant::now(), false).idle);
let activity = (a.last_activity, b.last_activity);
let idle_at = Instant::now() + IDLE_AFTER;
assert!(a.health(idle_at, true).idle);
establish(&mut a, &mut b, &mut scratch);
assert_eq!((a.last_activity, b.last_activity), activity);
assert!(a.health(idle_at, true).idle);
assert!(b.health(idle_at, false).idle);
let mut ip = [0u8; 20];
ip[0] = 0x45;
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
let ciphertext = wire(a.encapsulate(&ip, &mut scratch, 7).0);
let _ = b.decapsulate(&ciphertext, &mut scratch);
assert!(!a.health(Instant::now(), false).idle);
assert!(!b.health(Instant::now(), false).idle);
assert!(a.last_activity > activity.0 && b.last_activity > activity.1);
// Discard BoringTun's session keys to exercise an idle tunnel with no
// usable key and the first IP packet that has to wait for a new one.
a.tunn
.set_static_private(ak.to_static_secret(), ak.public().into_x25519(), None);
let idle_at = Instant::now() + IDLE_AFTER;
assert!(a.health(idle_at, false).idle);
assert!(!a.health(idle_at, true).idle);
let _ = a.encapsulate(&ip, &mut scratch, 7);
assert!(!a.health(idle_at, false).idle);
}
#[test]
fn draining_a_queued_keepalive_preserves_ip_flow_tags_and_eventually_goes_idle() {
let ak = WgSecretKey::from_bytes(&[1; 32]);
let bk = WgSecretKey::from_bytes(&[2; 32]);
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
let mut scratch = [0u8; SCRATCH];
// This is what BoringTun's persistent keepalive timer does with no key.
let hello = wire(a.tunn.encapsulate(&[], &mut scratch));
let mut ip = [0u8; 20];
ip[0] = 0x45;
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
for flow in 1..=256 {
let _ = a.encapsulate(&ip, &mut scratch, flow);
}
let reply = wire(b.decapsulate(&hello, &mut scratch).0);
let _ = a.decapsulate(&reply, &mut scratch);
let (keepalive, flow, bytes) = a.decapsulate(&[], &mut scratch);
assert_eq!(
wire(keepalive).len(),
crate::plugin::WIREGUARD_OVERHEAD as usize
);
assert_eq!((flow, bytes), (0, None));
for expected in 1..=255 {
let (data, flow, bytes) = a.decapsulate(&[], &mut scratch);
assert!(carries_ip(&wire(data)));
assert_eq!((flow, bytes), (expected, Some(ip.len())));
}
assert!(matches!(
a.decapsulate(&[], &mut scratch).0,
TunnResult::Done
));
assert!(a.health(Instant::now() + IDLE_AFTER, false).idle);
}
#[test]
fn flow_tags_survive_pending_queue_overflow_handshake_and_encryption() {
let ak = WgSecretKey::from_bytes(&[1; 32]);
@@ -716,7 +908,7 @@ mod flow_tests {
TunnResult::Done
));
let (result, flow) = a.encapsulate(&packet, &mut scratch, 12345);
assert!(is_data(&result));
assert!(carries_ip(&wire(result)));
assert_eq!(flow, 12345);
}
}
+6 -12
View File
@@ -35,7 +35,6 @@ use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tsunagi::BoxFuture;
use tsunagi::dataplane::PacketSink;
use tsunagi::dataplane::transport::SharedLink;
use tsunagi::dataplane::{IpPlugin, PluginCapability, PluginContext, PluginError};
use tsunagi::identity::NetworkId;
@@ -213,8 +212,6 @@ struct Worker {
store: WgKeyStore,
shared: Mutex<Shared>,
context: OnceLock<PluginContext>,
/// Where decrypted packets go, once the agent has attached one.
sink: OnceLock<Arc<dyn PacketSink>>,
}
impl std::fmt::Debug for Worker {
@@ -315,7 +312,6 @@ impl WireguardPlugin {
store,
shared: Mutex::new(Shared::default()),
context: OnceLock::new(),
sink: OnceLock::new(),
});
let (commands, receiver) = mpsc::channel(64);
@@ -473,13 +469,12 @@ impl Worker {
}
};
let sink = match self.sink.get() {
Some(sink) => Arc::clone(sink),
// Not attached to an agent: the protocol still runs, and its
// packets have nowhere to go.
None => Arc::new(tsunagi::dataplane::DiscardPackets) as Arc<dyn PacketSink>,
};
let device = Arc::new(WireguardDevice::start(network, key, sink));
let context = self
.context
.get()
.cloned()
.unwrap_or_else(PluginContext::detached);
let device = Arc::new(WireguardDevice::start_with_context(network, key, context));
let mut shared = self.lock_shared();
if let Some(state) = shared.networks.get_mut(&network) {
@@ -668,7 +663,6 @@ impl IpPlugin for WireguardPlugin {
if let Some(local) = context.local_endpoint_id() {
let _ = self.worker.local_id.set(local);
}
let _ = self.worker.sink.set(context.packet_sink());
let _ = self.worker.context.set(context);
}
+99 -6
View File
@@ -310,22 +310,106 @@ async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() {
live.peer.agent.shutdown().await;
}
#[tokio::test]
async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
async fn shared_nodes() -> (Node, Node) {
let discovery = SharedMemoryDiscovery::new();
let client = Node::open(TempDir::new().unwrap(), &discovery, "client", None).await;
let dir = TempDir::new().unwrap();
let config = tsunagi::testing::config_with(dir.path(), &discovery);
let peer = Node::start(dir, "shared", config).await;
(client, peer)
}
async fn shared_networks<'a>(client: &Node, peer: &'a Node) -> [ExitNetwork<'a>; 2] {
// Fixed credentials keep the two automatically derived /24s distinct.
let mut meshes = Vec::new();
for (name, secret) in [("shared-left", [1; 32]), ("shared-right", [2; 32])] {
let join = |name, secret| {
let credentials = (
NetworkName::new(name).unwrap(),
NetworkSecret::from_bytes(secret).unwrap(),
);
meshes.push(ExitNetwork::join(&client, &peer, credentials).await);
}
ExitNetwork::join(client, peer, credentials)
};
[
join("shared-left", [1; 32]).await,
join("shared-right", [2; 32]).await,
]
}
#[tokio::test]
#[ignore = "observes a full 180-second WireGuard key lifetime on real clocks"]
async fn only_the_selected_exit_stays_keyed_through_idle_expiry() {
let (client, peer) = shared_nodes().await;
let [chosen, other] = shared_networks(&client, &peer).await;
client
.agent
.set_exit_via(chosen.id, Some(peer.id()))
.await
.unwrap();
let tunnel = |network| {
client
.plugin
.overview(network)
.unwrap()
.peers
.into_iter()
.find(|p| p.endpoint_id == peer.id())
.unwrap()
.tunnel
.unwrap()
};
let epoch = tunnel(chosen.id).stats.counter_epoch;
let mut old_key_seen = false;
tokio::time::timeout(Duration::from_secs(210), async {
let mut poll = tokio::time::interval(Duration::from_millis(500));
loop {
poll.tick().await;
let warm = tunnel(chosen.id);
let cold = tunnel(other.id);
assert_eq!(warm.stats.counter_epoch, epoch);
let warm_age = warm
.health
.since_handshake
.expect("usable exit key throughout idle");
assert_eq!((warm.stats.tx_bytes, warm.stats.rx_bytes), (0, 0));
assert_eq!((cold.stats.tx_bytes, cold.stats.rx_bytes), (0, 0));
if cold
.health
.since_handshake
.is_some_and(|age| age >= Duration::from_secs(150))
{
old_key_seen = true;
}
if old_key_seen && !cold.health.is_up() {
assert!(
warm_age < Duration::from_secs(90),
"exit key renewed before expiry"
);
assert!(warm.health.idle && cold.health.idle);
break;
}
}
})
.await
.expect("unselected peer's unused session expired");
let packet = ipv4_packet(chosen.client_addr, INTERNET, b"first IP packet after idle");
client.tun().await.push_from_os(packet.clone());
assert_eq!(next(&chosen.peer_tun).await, packet);
assert!(!tunnel(chosen.id).health.idle);
client
.agent
.set_exit_via(other.id, Some(peer.id()))
.await
.unwrap();
client.wait_for_tunnels(other.id, 1).await;
assert!(tunnel(other.id).health.idle, "warming sends no IP payload");
client.agent.shutdown().await;
peer.agent.shutdown().await;
}
#[tokio::test]
async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
let (client, peer) = shared_nodes().await;
let meshes = shared_networks(&client, &peer).await;
let tun = client.tun().await;
for (chosen, other) in [(&meshes[0], &meshes[1]), (&meshes[1], &meshes[0])] {
client
@@ -359,6 +443,15 @@ async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
let reply = ipv4_packet(INTERNET, chosen.client_addr, b"reply");
chosen.peer_tun.push_from_os(reply.clone());
assert_eq!(next(&tun).await, reply);
let expected = tsunagi::overlay::exit::ExitTraffic {
tx_bytes: request.len() as u64,
rx_bytes: reply.len() as u64,
};
wait_until("exit totals for the selected membership", || async {
(client.status(chosen.id).await.exit_traffic == Some(expected)).then_some(())
})
.await;
assert_eq!(client.status(other.id).await.exit_traffic, None);
}
peer.agent.shutdown().await;
client.agent.shutdown().await;
@@ -37,6 +37,7 @@ fn source(agent: Agent, plugin: Arc<WireguardPlugin>) -> Arc<dyn tsunagi::ipc::R
.peers
.iter()
.map(|peer| tsunagi::ipc::PeerReport {
agent_version: peer.agent_version.clone(),
data_error: None,
endpoint_id: peer.endpoint_id.to_string(),
hostname: peer.hostname.clone(),
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-wireguard"
version = "1.0.3-rc1"
version = "1.0.5"
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
serde.workspace = true
+64 -10
View File
@@ -18,6 +18,27 @@ pub(crate) const MAX_PAYLOAD: usize = tsunagi::config::MAX_DATA_DATAGRAM;
const CHUNK: usize = 700;
const QUEUE: usize = 64;
const WINDOW: Duration = Duration::from_secs(20);
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
#[derive(Default)]
struct DeliveryChecks {
replies: AtomicU64,
last_shared: Mutex<Option<Instant>>,
}
impl DeliveryChecks {
fn confirm_shared(&self, now: Instant) {
*self.last_shared.lock().unwrap_or_else(|e| e.into_inner()) = Some(now);
self.replies.fetch_add(1, Ordering::Relaxed);
}
fn needs_probe(&self, now: Instant) -> bool {
self.last_shared
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_none_or(|last| now.saturating_duration_since(last) >= PROBE_TIMEOUT)
}
}
pub(crate) struct PairLink {
network: NetworkId,
@@ -30,7 +51,7 @@ pub(crate) struct PairLink {
closed: AtomicBool,
remote: Mutex<Option<SocketAddr>>,
reason: Mutex<Option<String>>,
checks: Arc<AtomicU64>,
checks: Arc<DeliveryChecks>,
}
impl std::fmt::Debug for PairLink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -42,7 +63,7 @@ impl std::fmt::Debug for PairLink {
}
impl PairLink {
pub(crate) fn delivery_checks(&self) -> u64 {
self.checks.load(Ordering::Relaxed)
self.checks.replies.load(Ordering::Relaxed)
}
pub(crate) fn has_authenticated_path(&self) -> bool {
match self.remote.lock() {
@@ -99,6 +120,9 @@ impl PacketLink for PairLink {
fn close(&self) {
self.stop.send_replace(true);
}
fn confirm_delivery(&self) {
self.checks.confirm_shared(Instant::now());
}
fn failure_reason(&self) -> Option<String> {
match self.reason.lock() {
Ok(reason) => reason.clone(),
@@ -145,7 +169,7 @@ pub(crate) fn start(
closed: AtomicBool::new(false),
remote: Mutex::new(None),
reason: Mutex::new(None),
checks: Arc::new(AtomicU64::new(0)),
checks: Arc::default(),
});
let weak = Arc::downgrade(&link);
let checks = link.checks.clone();
@@ -198,7 +222,7 @@ struct Engine {
assemblies: HashMap<u64, Assembly>,
started: Instant,
last_authenticated: Instant,
checks: Arc<AtomicU64>,
checks: Arc<DeliveryChecks>,
}
enum ResultOwned {
Wire(Vec<u8>),
@@ -249,12 +273,23 @@ impl Engine {
_=timer.tick()=>{
let result=own(self.tunn.update_timers(&mut scratch));self.process(result,None).await;
if last_probe.elapsed()>=Duration::from_secs(1) {
last_probe=Instant::now();self.sequence=self.sequence.wrapping_add(1);
self.pending.push_back((self.sequence,Instant::now()));
let mut probe=vec![1];probe.extend_from_slice(&self.sequence.to_be_bytes());
probe.resize(713,0);rand::fill(&mut probe[9..]);self.encrypt(&probe).await;
last_probe = Instant::now();
if self.checks.needs_probe(last_probe) {
self.sequence = self.sequence.wrapping_add(1);
self.pending.push_back((self.sequence, last_probe));
let mut probe = vec![1];
probe.extend_from_slice(&self.sequence.to_be_bytes());
probe.resize(713, 0);
rand::fill(&mut probe[9..]);
self.encrypt(&probe).await;
} else {
// A full-sized round trip passed through fragmentation and
// reassembly. The outer monitor owns loss accounting now.
self.samples.clear();
self.pending.clear();
}
}
while self.pending.front().is_some_and(|(_,at)|at.elapsed()>=Duration::from_secs(3)) {
while self.pending.front().is_some_and(|(_,at)|at.elapsed()>=PROBE_TIMEOUT) {
self.pending.pop_front();self.samples.push_back(false);
}
while self.samples.len()>20 {self.samples.pop_front();}
@@ -363,7 +398,7 @@ impl Engine {
{
self.pending.remove(index);
self.samples.push_back(true);
self.checks.fetch_add(1, Ordering::Relaxed);
self.checks.replies.fetch_add(1, Ordering::Relaxed);
}
}
Some(3) => self.fragment(seq, payload),
@@ -412,3 +447,22 @@ impl Engine {
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn shared_delivery_replaces_native_probes_only_while_round_trips_succeed() {
let checks = DeliveryChecks::default();
let start = Instant::now();
assert!(checks.needs_probe(start));
checks.confirm_shared(start);
assert!(!checks.needs_probe(start + Duration::from_secs(2)));
assert!(checks.needs_probe(start + Duration::from_secs(3)));
checks.confirm_shared(start + Duration::from_secs(4));
assert!(!checks.needs_probe(start + Duration::from_secs(5)));
assert_eq!(checks.replies.load(Ordering::Relaxed), 2);
}
}
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi"
version = "1.0.3-rc1"
version = "1.0.5"
description = "The tsunagi command line agent."
edition.workspace = true
rust-version.workspace = true
@@ -12,11 +12,11 @@ name = "tsng"
path = "src/main.rs"
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.3-rc1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.3-rc1", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3-rc1" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3-rc1" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3-rc1" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.5" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.5" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.5" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.5" }
iroh.workspace = true
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
tracing.workspace = true
+43 -6
View File
@@ -3884,12 +3884,17 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
),
Some(DataPathReport::None) | None => ("connected · no data path yet".to_string(), false),
};
let idle = data_path_good && row.data_error.is_none() && row.tunnel.is_some_and(|t| t.idle);
let show_counters = tunnel_up || idle;
let mut detail = String::new();
if let Some(v4) = row.overlay_address_v4 {
detail.push_str(&format!("{v4:<15} "));
}
detail.push_str(&path);
if idle {
detail.push_str(" · idle");
}
if let Some(rtt) = row.data_rtt_ms {
detail.push_str(&format!(" data RTT {rtt}ms"));
}
@@ -3906,7 +3911,7 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
}
detail.extend(taken);
let health = if !data_path_good || row.data_error.is_some() || (has_overlay && !tunnel_up) {
let health = if !data_path_good || row.data_error.is_some() || (has_overlay && !show_counters) {
Health::Degraded
} else {
Health::Good
@@ -3916,12 +3921,12 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
if let Some(reason) = row.data_error {
out = out.with_note(reason.to_owned());
}
if !tunnel_up && let Some(path) = row.data_transport_detail {
if !show_counters && let Some(path) = row.data_transport_detail {
out = out.with_note(path.to_owned());
}
if let Some(tunnel) = row.tunnel {
out = out.with_note(match tunnel.handshake_secs_ago {
Some(_) => format!(
out = out.with_note(if show_counters {
format!(
"tx {} rx {} · IP bytes ↑{} ↓{}{} · {}",
tunnel.tx_packets,
tunnel.rx_packets,
@@ -3933,8 +3938,9 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
String::new()
},
row.data_transport_detail.unwrap_or(&tunnel.path)
),
None => "encrypted data channel is not ready yet".into(),
)
} else {
"encrypted data channel is not ready yet".into()
});
}
out
@@ -5206,6 +5212,7 @@ mod status_tests {
relay_sent_via: 0,
relay_received_via: 0,
peers: vec![PeerReport {
agent_version: None,
data_error: None,
endpoint_id: ONLINE.into(),
hostname: Some("music".into()),
@@ -5772,6 +5779,36 @@ mod status_tests {
);
}
#[test]
fn an_idle_peer_keeps_its_counters_and_a_missing_route_is_still_degraded() {
let mut network = network_after_a_peer_returned();
let mut quiet = tunnel(ONLINE, None);
quiet.idle = true;
network.overlay = Some(overlay(vec![quiet]));
for (path, health) in [
(
tsunagi::ipc::DataPathReport::Direct {
transport: "wg".into(),
},
Health::Good,
),
(tsunagi::ipc::DataPathReport::None, Health::Degraded),
] {
network.peers[0].path = path.clone();
network.members[1].path = path;
let mut report = report::Report::new();
report.push(network_section(&network, OWN, false));
let text = report.render(false);
assert_eq!(report.worst(), health, "{text}");
if health == Health::Good {
assert!(
text.contains("idle") && text.contains("tx 32 rx 887"),
"{text}"
);
}
}
}
#[test]
fn handshake_failures_with_nobody_connected_point_at_the_secret() {
// The classic symptom of one member being given a different secret.
+6 -2
View File
@@ -110,7 +110,11 @@ fresh private marker/key to the sender's endpoint id. Unanswered requests expire
after three seconds. After a 20-second warmup, at least 15 completed observations
and at least 60% loss in the last 20 observations retire a carrier. Probes are
consumed at the carrier boundary and never enter the TUN or user IP counters.
AWG additionally checks encrypted outer delivery throughout the pair lifetime.
Both WG and AWG start with native encrypted probes. A timely authenticated
round trip on the full-sized carrier check also proves outer delivery, so it
replaces the native probe. Native probes resume after three seconds without
such a confirmation. Each peer still answers both types of probe independently,
including requests from 1.0.3 peers.
Setup failure or persistent runtime loss advances to the next mutually supported
carrier in the initiator's order. Earlier expired cooldowns do not jump ahead of
@@ -123,7 +127,7 @@ The internal capability is `wireguard-e2e` v4; external `wg` and `awg` use v2,
`wg-quic` v1 and `tcp-tls` v2, as in 1.0.1. Control ALPN
`tsunagi/ctrl/8`, discovery, membership and signed state are unchanged. The data
ALPN is `tsunagi/data/6`; the relay envelope format is unchanged. Automatic
carrier comparisons are optional on the mesh wire. Local IPC is v24,
carrier comparisons are optional on the mesh wire. Local IPC is v25,
so agent, CLI and tray must match. Historical `wg-quic/wireguard.sqlite` is the
canonical internal key store. Missing keys are imported transactionally from
`wg` then `awg`, without replacing an existing canonical key or modifying a
+4
View File
@@ -30,6 +30,10 @@ tsng exit-node off
The tray does the same: a checkbox on the network tile to offer, and an icon on
each device in the devices window that offers one, with a confirmation.
The network card shows the selected peer even when folded. The up arrow counts
IP bytes sent through the exit and the down arrow counts reply bytes delivered
to this device. Traffic addressed to the peer within the mesh is counted only
in the devices window. The exit totals start over on a new selection or restart.
An agent uses **one exit node across all active networks**. Choosing another
replaces the previous selection and survives restart. Internet packets use
+17 -7
View File
@@ -15,10 +15,12 @@ Upgrading the crate or bumping the control protocol must never change an
existing `NetworkId`.
Control version 8 adds signed, multi-writer VIP field snapshots to version 7's
node retirements. Data ALPN is `tsunagi/data/6` for the single internal WireGuard channel. All members must upgrade
together. Network ids, derivation labels, handshake encoding and existing record
signatures are unchanged. Local CLI/tray IPC is version 23; restart the agent
with matching clients. SQLite schema 10 adds `vip_fields`, preserving identity,
node retirements. The transition from control v7 to v8 requires updating all
members together. Members already on v8 can adopt the optional software version
field independently. Data ALPN is `tsunagi/data/6` for the single internal
WireGuard channel. Network ids, derivation labels, handshake encoding and
existing record signatures are unchanged. Local CLI/tray IPC is version 25.
Restart the agent with matching clients. SQLite schema 10 adds `vip_fields`, preserving identity,
network configuration, signed node records and retirement proofs.
See [virtual services](vip.md), [state sync](sync-model.md) and [AWG](amnezia.md).
@@ -223,8 +225,8 @@ ignores it. Each row belongs to the authenticated sender and is replaced
atomically, expires after 90 seconds, and is withdrawn on session closure. Only
authenticated members enter the graph; local edges always come from actual
links.
Announcements refresh on the existing control maintenance interval and are
sent immediately on link changes. Topology stays volatile, outside signed state.
Each new session receives the current edges. Link changes trigger an immediate
update, and unchanged edges are due for refresh after 30 seconds. Topology stays volatile, outside signed state.
Version 5 also adds `hostname_since` to a signed hostname claim (signing domain
`tsunagi-signed-record-v3`): a name belongs to whoever claimed it first. Stored
@@ -248,7 +250,7 @@ not affect other networks.
| message | meaning |
|---|---|
| `Announce { hostname, capabilities, broadcast }` | this agent's hostname, IP-plugin capabilities and local broadcast participation |
| `Announce { broadcast, exit_node, hostname, capabilities, agent_version? }` | this agent’s hostname, capabilities, broadcast and exit settings, and optional software release |
| `Transport { protocol, payload }` | private, bounded per-peer transport negotiation; never state or a public message event |
| `Ping { seq, payload }` | small request used to verify the exchange |
| `Pong { seq, payload }` | the echoed reply |
@@ -258,6 +260,14 @@ not affect other networks.
| `Reachable { links }` | sender's current direct data links, by kind of transport |
| `Bye { reason }` | graceful goodbye; not a revocation of anything |
The final field of an authenticated announcement is an optional Tsunagi software
version. It is a display hint for the current session. Control v8 readers that
predate the field stop decoding after the capabilities. Updated readers accept a
frame ending there and show the version as unknown. A present label is limited
to 64 ASCII letters, digits, dots, plus signs and hyphens. An invalid hint is
ignored. Authentication, identity derivation and transport selection use their
own wire versions independently of this label.
`broadcast` is a per-network local opt-in, enabled by default and treated as
false until an authenticated announcement arrives. It governs IP broadcast
fanout and local admission; encrypted transit still uses the existing envelope.
+2 -2
View File
@@ -24,8 +24,8 @@ the selected link fails or its MTU is too small. The configured order
selects the initial link. Peers with automatic carrier selection can then
prefer a faster measured link for that neighbour. Every authenticated
member enters the graph; a member in the middle needs no protocol in common
with either end, only a link to each. A snapshot refreshes on the maintenance
interval, expires after 90 seconds, and is withdrawn when the session ends.
with either end, only a link to each. A snapshot is due for refresh after 30
seconds, expires after 90 seconds, and is withdrawn when the session ends.
Link arrival, closure and changed announcements rebuild routes immediately.
Unchanged announcements refresh their age without republishing the forwarding
snapshot.
+4 -3
View File
@@ -90,9 +90,10 @@ is not a permanent identity ban or a change of secret.
The marker and requester's own author counter commit in one SQLite transaction
before publication. Receivers persist a verified marker before applying it.
Invalid proofs are rejected individually. Periodic bounded marker batches
rotate through each peer's send queue, including when a queue fills, so a
replica that missed an update can catch up without the requester being online.
Invalid proofs are rejected individually. Each authenticated stream receives
the current claims, markers and VIPs, then their changes. A per-session cursor
advances when a bounded frame enters the send queue. The next maintenance
round retries pending revisions, and a new session starts from the beginning.
One strongest marker per target is retained, with a default limit of 1024 per
network and 1024 bytes per encoded marker. New targets beyond that limit are
+3 -2
View File
@@ -142,8 +142,9 @@ Missing snapshot fields are never deletion.
Saving validates the entire draft and checks the revision shown by the editor.
The merged snapshot and author's counter commit together in SQLite before local
routing changes or publication. Receivers verify and persist complete service
snapshots before exposing them. Periodic rotating snapshots repair queue loss
and returning replicas without requiring the creator online. Concurrent edits
snapshots before exposing them. Each session sends changed services and retries
when its send queue has room. Reconnecting replicas receive all retained
services and tombstones from any member. Concurrent edits
made before participants have seen each other can still merge after a save.
A merged configuration exceeding listener/backend limits is reported as an
error and excluded from routing rather than selected according to arrival order.
+9
View File
@@ -238,6 +238,15 @@ modifying the source files. Corrupt legacy databases are hard errors. Old
internal channel; contradictory values are rejected. Interface MTU is selected
once with `--mtu`, independent of carrier selection.
The client renews the selected exit peer's session key at 120 seconds, even
when no IP traffic is flowing. The current key can carry packets during the
exchange. Changing the exit moves this behavior to the new network and peer.
The device list shows **Idle** after an established tunnel has had 30 seconds
without IP traffic. Handshakes and keepalives do not restart this interval.
Pending IP packets, a missing path, or a selected exit waiting for a usable
key still show **Waiting**. A reported transport failure shows **Error**.
User traffic counters count original IP bytes once when the encrypted frame is
accepted by the logical transport, and once when decrypted on receipt. They do
not promise remote delivery. They exclude carrier overhead, handshakes,
+1 -1
View File
@@ -34,7 +34,7 @@ let
in
rustPlatform.buildRustPackage {
pname = if withTray then "tsunagi" else "tsunagi-cli";
version = "1.0.3-rc1";
version = "1.0.5";
src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock;