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.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 14:33:50 +02:00
1 parent f9f67f88b1
commit 8c4c2fa34e
39 files changed
+1144 -412

No files matched your search

+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 Exact network names, full ids and unique id prefixes work here. The choice is
local to this device, saved per network and applied immediately; an offline local to this device, saved per network and applied immediately; an offline
change applies on the next start. In the tray, expand **data transports** on a network change applies on the next start. In the tray or on Android, click the network
tile to enable transports and set their initial preference order. Adjacent peers need a common external transport at the same wire version. 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 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. 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 `tsng status` and the tray show the direct data link's measured RTT separately
+2 -2
View File
@@ -16,7 +16,7 @@ cd android
adb install -r app/build/outputs/apk/debug/app-debug.apk 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. **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. 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,7 @@ 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. 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) 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)
## Check two networks on an emulator ## Check two networks on an emulator
@@ -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()
}
}
}
@@ -9,6 +9,9 @@ import android.view.WindowInsets
import android.widget.FrameLayout import android.widget.FrameLayout
class MainActivity : Activity() { class MainActivity : Activity() {
private val settings by lazy { getSharedPreferences("agent", MODE_PRIVATE) }
private var checkedAutoStart = false
private var consentPending = false
private var askedForNotifications = false private var askedForNotifications = false
internal fun requestExitNotifications() { internal fun requestExitNotifications() {
if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications && if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications &&
@@ -20,6 +23,7 @@ class MainActivity : Activity() {
private lateinit var surface: MeshSurface private lateinit var surface: MeshSurface
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
consentPending = savedInstanceState?.getBoolean("consent_pending") == true
surface = MeshSurface(this) surface = MeshSurface(this)
val root = FrameLayout(this) val root = FrameLayout(this)
if (Build.VERSION.SDK_INT >= 30) { if (Build.VERSION.SDK_INT >= 30) {
@@ -33,17 +37,43 @@ class MainActivity : Activity() {
root.addView(surface) root.addView(surface)
setContentView(root) setContentView(root)
} }
internal fun requestVpn() { override fun onPostResume() {
super.onPostResume()
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)
}
internal fun requestAgent() {
if (consentPending) return
val consent = VpnService.prepare(this) val consent = VpnService.prepare(this)
if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java)) if (consent == null) startAgent() else {
else startActivityForResult(consent, 1) consentPending = true
startActivityForResult(consent, 1)
}
}
private fun startAgent() {
settings.edit().putBoolean("auto_start", true).apply()
val service = Intent(this, MeshVpn::class.java)
// 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") @Deprecated("Platform consent result")
override fun onActivityResult(request: Int, result: Int, data: Intent?) { override fun onActivityResult(request: Int, result: Int, data: Intent?) {
super.onActivityResult(request, result, data) super.onActivityResult(request, result, data)
if (request == 1) { if (request == 1) {
if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java)) consentPending = false
else surface.input(5, "VPN permission was declined") if (result == RESULT_OK) startAgent() else {
settings.edit().putBoolean("auto_start", false).apply()
surface.input(5, "Android VPN permission was declined")
}
} }
} }
@Deprecated("Forward system Back to the current Rust view") @Deprecated("Forward system Back to the current Rust view")
@@ -34,7 +34,7 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface() override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h } override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
override fun onDrawFrame(gl: GL10?) { override fun onDrawFrame(gl: GL10?) {
val delay = Native.draw(this, widthPx, heightPx, density) val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started)
removeCallbacks(repaint) removeCallbacks(repaint)
postDelayed(repaint, delay.coerceAtLeast(16)) postDelayed(repaint, delay.coerceAtLeast(16))
} }
@@ -58,8 +58,8 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
return true return true
} }
fun startVpn() { post { activity.requestVpn() } } fun startAgent() { post { activity.requestAgent() } }
fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } } fun stopAgent() { post { activity.stopAgent() } }
fun requestExitNotifications() { post { activity.requestExitNotifications() } } fun requestExitNotifications() { post { activity.requestExitNotifications() } }
fun closeScreen() { post { activity.finish() } } fun closeScreen() { post { activity.finish() } }
fun openUrl(url: String) { post { fun openUrl(url: String) { post {
@@ -27,6 +27,8 @@ class MeshVpn : VpnService() {
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT" private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
private const val NOTIFICATION_ID = 1 private const val NOTIFICATION_ID = 1
private const val EXIT_CHANNEL = "exit-node" private const val EXIT_CHANNEL = "exit-node"
@Volatile var started = false
private set
} }
private val main = Handler(Looper.getMainLooper()) private val main = Handler(Looper.getMainLooper())
private val notifications by lazy { getSystemService(NotificationManager::class.java) } private val notifications by lazy { getSystemService(NotificationManager::class.java) }
@@ -34,7 +36,6 @@ class MeshVpn : VpnService() {
private var closed = false private var closed = false
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) } private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
@Volatile private var upstream: Network? = null @Volatile private var upstream: Network? = null
private var watching = false
private val changes = object : ConnectivityManager.NetworkCallback() { private val changes = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) = useUnderlay(network) override fun onAvailable(network: Network) = useUnderlay(network)
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) { override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
@@ -77,15 +78,15 @@ class MeshVpn : VpnService() {
STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY } STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY }
DISCONNECT_EXIT -> { DISCONNECT_EXIT -> {
val ids = intent.data?.pathSegments.orEmpty() 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])) { 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() 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 return START_NOT_STICKY
} }
} }
if (watching) { if (started) {
if (Native.failed(instance)) { if (Native.failed(instance)) {
Native.stop(instance) Native.stop(instance)
instance = 0 instance = 0
@@ -93,12 +94,13 @@ class MeshVpn : VpnService() {
} }
return START_NOT_STICKY 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)) 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) if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
startForeground(NOTIFICATION_ID, startup.build()) startForeground(NOTIFICATION_ID, startup.build())
watching = true started = true
connectivity.requestNetwork(NetworkRequest.Builder() connectivity.requestNetwork(NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper())) .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper()))
@@ -189,8 +191,12 @@ class MeshVpn : VpnService() {
@Synchronized private fun shutdown() { @Synchronized private fun shutdown() {
if (closed) return if (closed) return
closed = true closed = true
if (watching) connectivity.unregisterNetworkCallback(changes) if (started) connectivity.unregisterNetworkCallback(changes)
started = false
if (instance != 0L) Native.stop(instance) if (instance != 0L) Native.stop(instance)
instance = 0L
upstream = null
physicalAddresses = ""
connectivity.bindProcessToNetwork(null) connectivity.bindProcessToNetwork(null)
stopForeground(STOP_FOREGROUND_REMOVE) stopForeground(STOP_FOREGROUND_REMOVE)
} }
@@ -13,7 +13,7 @@ internal object Native {
external fun networkChanged(instance: Long, addresses: String) external fun networkChanged(instance: Long, addresses: String)
external fun surface() 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): Long
external fun touch(action: Int, id: Int, x: Float, y: Float) external fun touch(action: Int, id: Int, x: Float, y: Float)
external fun input(kind: Int, value: String) external fun input(kind: Int, value: String)
external fun key(key: Int) external fun key(key: Int)
@@ -7,7 +7,7 @@ use egui_glow::{Painter, glow};
use jni::{ use jni::{
JNIEnv, JNIEnv,
objects::{JObject, JString, JValue}, objects::{JObject, JString, JValue},
sys::{jfloat, jint, jlong}, sys::{jboolean, jfloat, jint, jlong},
}; };
use std::{ use std::{
cell::RefCell, cell::RefCell,
@@ -75,6 +75,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
w: jint, w: jint,
h: jint, h: jint,
scale: jfloat, scale: jfloat,
service_started: jboolean,
) -> jlong { ) -> jlong {
with_display(|d| { with_display(|d| {
let size = egui::vec2(w as f32, h as f32) / scale; let size = egui::vec2(w as f32, h as f32) / scale;
@@ -88,19 +89,22 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
info.native_pixels_per_point = Some(scale); info.native_pixels_per_point = Some(scale);
} }
let mut action = None; 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())); 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 { if exit_active && !d.exit_active {
let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]); let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]);
} }
d.exit_active = exit_active; d.exit_active = exit_active;
let output = d.ctx.run(input, |ctx| { 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 { if let Some(action) = action {
let method = match action { let method = match action {
SystemAction::Start => "startVpn", SystemAction::Start => "startAgent",
SystemAction::Stop => "stopVpn", SystemAction::Stop => "stopAgent",
SystemAction::PasteSecret => "pasteSecret", SystemAction::PasteSecret => "pasteSecret",
SystemAction::Finish => "closeScreen", SystemAction::Finish => "closeScreen",
}; };
+2 -2
View File
@@ -48,10 +48,10 @@ fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
let (reply, result) = oneshot::channel(); let (reply, result) = oneshot::channel();
current() current()
.as_ref() .as_ref()
.ok_or("VPN service stopped")? .ok_or("Tsunagi Agent stopped")?
.commands .commands
.try_send((Request::Action(cmd), reply)) .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) Ok(result)
} }
+85 -19
View File
@@ -480,7 +480,7 @@ async fn tun_reader_survives_address_changes_failed_establish_and_last_network_l
} }
#[tokio::test] #[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::{ use crate::{
service::{State, report}, service::{State, report},
view::{Phone, configure}, view::{Phone, configure},
@@ -500,37 +500,102 @@ async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() {
address: Some("10.1.2.3".into()), address: Some("10.1.2.3".into()),
..Default::default() ..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 state = State::Ready(Arc::new(sample), Instant::now());
let ctx = egui::Context::default(); let ctx = egui::Context::default();
configure(&ctx); configure(&ctx);
let mut phone = Phone::default(); let mut phone = Phone::default();
let frame = ctx.run( let mut frame = |events| {
egui::RawInput { ctx.run(
screen_rect: Some(egui::Rect::from_min_size( egui::RawInput {
egui::Pos2::ZERO, screen_rect: Some(egui::Rect::from_min_size(
egui::vec2(360., 720.), egui::Pos2::ZERO,
)), egui::vec2(360., 720.),
..Default::default() )),
}, events,
|ctx| { ..Default::default()
phone.draw(ctx, &state, |_| { },
panic!("drawing the overview issued a command") |ctx| {
}); phone.draw(ctx, &state, |_| {
}, panic!("drawing the overview issued a command")
); });
let y = |label: &str| { },
)
};
let positions = |frame: &egui::FullOutput, label: &str| {
frame frame
.shapes .shapes
.iter() .iter()
.find_map(|shape| match &shape.shape { .filter_map(|shape| match &shape.shape {
Shape::Text(text) if text.galley.text() == label => Some(text.pos.y), Shape::Text(text) if text.galley.text() == label => {
Some(text.pos + text.galley.rect.center().to_vec2())
}
_ => None, _ => None,
}) })
.unwrap_or_else(|| panic!("missing label {label}")) .collect::<Vec<_>>()
}; };
frame(vec![]);
let closed = frame(vec![]);
let titles = positions(&closed, name.as_str());
assert_eq!(titles.len(), 2);
assert!(positions(&closed, "Show devices").is_empty());
use egui_phosphor::regular::{ARROW_DOWN, ARROW_UP};
let font = egui::TextStyle::Body.resolve(&ctx.style());
for icon in [ARROW_UP, ARROW_DOWN] {
assert!(ctx.fonts(|fonts| fonts.has_glyphs(&font, icon)));
}
for label in [
"Exit via gateway".to_owned(),
format!("{ARROW_UP} 2.0 kB"),
format!("{ARROW_DOWN} 512 B"),
] {
assert_eq!(positions(&closed, &label).len(), 1, "missing {label}");
}
let mut click = |pos| {
for pressed in [true, false] {
frame(vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
},
]);
}
frame(vec![])
};
let opened = click(titles[0]);
assert_eq!(positions(&opened, "Show devices").len(), 1);
let y = |label| positions(&opened, label)[0].y;
assert!((0.0..=26.0).contains(&(y("host") - y("device")))); 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("range") - y("id"))));
assert!((0.0..=26.0).contains(&(y("peers") - y("addr")))); assert!((0.0..=26.0).contains(&(y("peers") - y("addr"))));
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; agent.shutdown().await;
} }
@@ -631,6 +696,7 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
} }
frame(vec![]) frame(vec![])
}; };
click("lab");
let live = click("VIP"); let live = click("VIP");
for label in ["Overview", "Configuration", "Next new flow", "node:8080"] { for label in ["Overview", "Configuration", "Next new flow", "node:8080"] {
let p = position(&live, label); let p = position(&live, label);
+6 -5
View File
@@ -162,7 +162,7 @@ impl Phone {
let outcome = match pending.result.try_recv() { let outcome = match pending.result.try_recv() {
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return, Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return,
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => { Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
Err("VPN service stopped".to_owned()) Err("Tsunagi Agent stopped".to_owned())
} }
Ok(v) => v, Ok(v) => v,
}; };
@@ -239,8 +239,9 @@ impl Phone {
}); });
} else if self.page == Page::About } else if self.page == Page::About
&& !matches!(state, State::Off) && !matches!(state, State::Off)
&& ui.button("Stop VPN").clicked() && ui.button("Stop Tsunagi Agent").clicked()
{ {
self.home();
system = Some(SystemAction::Stop); system = Some(SystemAction::Stop);
} }
}); });
@@ -278,10 +279,10 @@ impl Phone {
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
let Some(report) = report else { let Some(report) = report else {
match state { 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 let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("Tsunagi Agent is stopped");}
if ui.button("Start VPN").clicked() {system = Some(SystemAction::Start);} if ui.button("Start Tsunagi Agent").clicked() {self.error = None; system = Some(SystemAction::Start);}
} }
} }
return; return;
+1
View File
@@ -1309,6 +1309,7 @@ impl Agent {
.exit_via .exit_via
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok()), .and_then(|bytes| EndpointId::from_bytes(&bytes).ok()),
exit_via_online: false, exit_via_online: false,
exit_traffic: None,
exit_rules: Default::default(), exit_rules: Default::default(),
descriptor: keys.descriptor(), descriptor: keys.descriptor(),
name: stored.name, name: stored.name,
+11
View File
@@ -2810,6 +2810,7 @@ impl Runtime {
exit_node, exit_node,
hostname: self.params.hostname.clone(), hostname: self.params.hostname.clone(),
capabilities, capabilities,
agent_version: Some(env!("CARGO_PKG_VERSION").to_owned()),
} }
} }
@@ -2999,6 +3000,9 @@ impl Runtime {
} }
if let Some(session) = self.sessions.get_mut(&peer) { if let Some(session) = self.sessions.get_mut(&peer) {
session.hostname = Some(announcement.hostname.clone()); session.hostname = Some(announcement.hostname.clone());
session
.agent_version
.clone_from(&announcement.agent_version);
session.broadcast = announcement.broadcast; session.broadcast = announcement.broadcast;
session.exit_node = announcement.exit_node; session.exit_node = announcement.exit_node;
session.capabilities = capabilities.clone(); session.capabilities = capabilities.clone();
@@ -3260,6 +3264,7 @@ impl Runtime {
exit_node: session.exit_node, exit_node: session.exit_node,
endpoint_id: session.peer, endpoint_id: session.peer,
role: session.role, role: session.role,
agent_version: session.agent_version.clone(),
hostname: session hostname: session
.hostname .hostname
.clone() .clone()
@@ -3348,6 +3353,12 @@ impl Runtime {
exit_offer: exit.offer, exit_offer: exit.offer,
exit_via: exit.via, exit_via: exit.via,
exit_via_online: exit.via.is_some_and(|via| self.exit_node_online(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 exit_rules: self
.params .params
.interface .interface
+2
View File
@@ -72,6 +72,7 @@ pub(crate) struct Session {
/// number of control bytes it queues. /// number of control bytes it queues.
pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>, pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>,
pub(crate) hostname: Option<String>, pub(crate) hostname: Option<String>,
pub(crate) agent_version: Option<String>,
pub(crate) capabilities: Vec<PluginCapability>, pub(crate) capabilities: Vec<PluginCapability>,
pub(crate) broadcast: bool, pub(crate) broadcast: bool,
/// The peer offers itself as an exit node in this network. /// The peer offers itself as an exit node in this network.
@@ -228,6 +229,7 @@ pub(crate) fn spawn(
conn, conn,
outbound: outbound_tx, outbound: outbound_tx,
hostname: None, hostname: None,
agent_version: None,
capabilities: Vec::new(), capabilities: Vec::new(),
broadcast: false, broadcast: false,
exit_node: false, exit_node: false,
+4
View File
@@ -152,6 +152,8 @@ pub struct PeerStatus {
/// ///
/// A mutable binding, not an identity. /// A mutable binding, not an identity.
pub hostname: Option<String>, 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 /// Protocols agreed with this peer: both sides have them at the same
/// version. /// version.
/// ///
@@ -247,6 +249,8 @@ pub struct NetworkStatus {
pub exit_via: Option<EndpointId>, pub exit_via: Option<EndpointId>,
/// Whether that member is connected and still offering to be one. /// Whether that member is connected and still offering to be one.
pub exit_via_online: bool, 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. /// What the host rules for the exit settings are doing.
pub exit_rules: crate::overlay::ExitRulesReport, pub exit_rules: crate::overlay::ExitRulesReport,
/// Immutable deterministic description of the network space. /// 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))] #[cfg_attr(target_os = "macos", allow(dead_code))]
const APP_NAME: &str = "tsunagi"; 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. /// Rendezvous slots per network; this bounds a discovery sample, not membership.
pub const DHT_SLOTS: u8 = 16; pub const DHT_SLOTS: u8 = 16;
/// BEP44 permits 1000 bencoded bytes; a 996-byte string has a four-byte prefix. /// BEP44 permits 1000 bencoded bytes; a 996-byte string has a four-byte prefix.
+5 -1
View File
@@ -830,6 +830,8 @@ pub struct MemberReport {
/// One control plane peer. /// One control plane peer.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerReport { pub struct PeerReport {
/// 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. /// Actionable carrier failure or policy mismatch; absent for a usable route.
pub data_error: Option<String>, pub data_error: Option<String>,
/// The peer's endpoint id. /// The peer's endpoint id.
@@ -893,6 +895,8 @@ pub struct RuleSetReport {
/// One network's exit-node settings and what they are doing. /// One network's exit-node settings and what they are doing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExitReport { 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. /// This agent offers itself as an exit node in this network.
pub offering: bool, pub offering: bool,
/// Masquerading and forwarding rules for members' traffic, when offering. /// Masquerading and forwarding rules for members' traffic, when offering.
@@ -1141,7 +1145,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
/// ///
/// Bump it whenever [`Request`], [`Response`] or anything they contain /// Bump it whenever [`Request`], [`Response`] or anything they contain
/// changes shape. /// changes shape.
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 24]); pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 25]);
/// Reads one request off an accepted stream, answers it, writes the response. /// 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 //! system sees. It is kept apart from the broadcast rules, which have a
//! different lifetime and different tags. //! 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. /// How one set of host rules went.
#[derive(Debug, Clone, Default, PartialEq, Eq)] #[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleSetReport { pub struct RuleSetReport {
+74 -21
View File
@@ -320,11 +320,19 @@ impl Interface {
tally.multicast.fetch_add(1, Ordering::Relaxed); tally.multicast.fetch_add(1, Ordering::Relaxed);
continue; 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); tally.note_unroutable(destination);
continue; continue;
}; };
let len = packet.len() as u64;
if carrier.carry(route, packet) { 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); tally.sent.fetch_add(1, Ordering::Relaxed);
} else { } else {
tally.undeliverable.fetch_add(1, Ordering::Relaxed); tally.undeliverable.fetch_add(1, Ordering::Relaxed);
@@ -840,12 +848,14 @@ impl Interface {
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed); self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongSource); return Err(Rejected::WrongSource);
}; };
let broadcast = match (origin, header.destination()) { let (broadcast, exit) = match (origin, header.destination()) {
(PacketSource::ExitReply { local: Some(local) }, IpAddr::V4(destination)) (
if destination == local => PacketSource::ExitReply {
{ local: Some(local),
false exit,
} },
IpAddr::V4(destination),
) if destination == local => (false, Some(exit)),
(PacketSource::Member, IpAddr::V4(destination)) (PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_broadcast(destination) => if self.routes.is_broadcast(destination) =>
{ {
@@ -855,13 +865,13 @@ impl Interface {
self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed); self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::BroadcastDenied); return Err(Rejected::BroadcastDenied);
} }
true (true, None)
} }
(PacketSource::Member, IpAddr::V4(destination)) (PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_local_destination(network, destination) if self.routes.is_local_destination(network, destination)
|| self.routes.accepts_exit_traffic(network, destination) => || self.routes.accepts_exit_traffic(network, destination) =>
{ {
false (false, None)
} }
_ => { _ => {
self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed); self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed);
@@ -887,7 +897,11 @@ impl Interface {
crate::vip::router::Decision::Pass => packet, crate::vip::router::Decision::Pass => packet,
}; };
// Remote broadcasts terminate here. Only local TUN ingress can fan out. // Remote broadcasts terminate here. Only local TUN ingress can fan out.
let len = packet.len() as u64;
if self.device.send(packet).await.is_ok() { if self.device.send(packet).await.is_ok() {
if let Some(exit) = exit {
exit.rx_bytes.fetch_add(len, Ordering::Relaxed);
}
if broadcast { if broadcast {
self.tally self.tally
.broadcast_received .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. /// Whether an address is one the overlay has nowhere to send.
fn is_multicast_or_broadcast(address: IpAddr) -> bool { fn is_multicast_or_broadcast(address: IpAddr) -> bool {
match address { 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] #[tokio::test]
async fn internet_traffic_goes_to_the_exit_node_and_only_once_one_is_chosen() { async fn internet_traffic_goes_to_the_exit_node_and_only_once_one_is_chosen() {
let (interface, device, routes, carrier, id) = interface(false).await; let (interface, device, routes, carrier, id) = interface(false).await;
+66 -9
View File
@@ -21,9 +21,11 @@
//! one is in use. //! one is in use.
use super::broadcast::{BroadcastPolicy, BroadcastTable}; use super::broadcast::{BroadcastPolicy, BroadcastTable};
use arc_swap::ArcSwap; use super::exit::ExitTraffic;
use arc_swap::{ArcSwap, ArcSwapOption};
use std::collections::HashMap; use std::collections::HashMap;
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use iroh::EndpointId; 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. /// An internet source is valid only for a reply to our address in the exit's network.
pub(super) enum PacketSource { pub(super) enum PacketSource {
Member, 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. /// A network's exit-node settings, as far as packets are concerned.
@@ -97,6 +111,7 @@ pub enum RouteError {
pub struct RoutingTable { pub struct RoutingTable {
pub(crate) vips: Arc<crate::vip::VipRouter>, pub(crate) vips: Arc<crate::vip::VipRouter>,
broadcast: ArcSwap<BroadcastTable>, broadcast: ArcSwap<BroadcastTable>,
selected_exit: ArcSwapOption<SelectedExit>,
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>, networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
} }
@@ -171,6 +186,7 @@ impl RoutingTable {
clear_other_exits(networks, network); clear_other_exits(networks, network);
} }
networks.insert(network, routes); networks.insert(network, routes);
self.refresh_exit(networks);
self.broadcast self.broadcast
.store(Arc::new(BroadcastTable::build(networks))); .store(Arc::new(BroadcastTable::build(networks)));
Ok(()) Ok(())
@@ -181,6 +197,7 @@ impl RoutingTable {
self.vips.remove_network(network); self.vips.remove_network(network);
let mut networks = self.write(); let mut networks = self.write();
networks.remove(&network); networks.remove(&network);
self.refresh_exit(&networks);
self.broadcast self.broadcast
.store(Arc::new(BroadcastTable::build(&networks))); .store(Arc::new(BroadcastTable::build(&networks)));
} }
@@ -213,9 +230,35 @@ impl RoutingTable {
if routes.exit.via.is_some() { if routes.exit.via.is_some() {
clear_other_exits(&mut networks, network); 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. /// Recognizes limited and configured subnet broadcasts before unicast lookup.
pub fn is_broadcast(&self, destination: Ipv4Addr) -> bool { pub fn is_broadcast(&self, destination: Ipv4Addr) -> bool {
self.broadcast.load().is_destination(destination) 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: /// unicast destination, goes to this device's exit node when it has one:
/// that is what sending *all* traffic through a member means. /// that is what sending *all* traffic through a member means.
pub fn route(&self, destination: Ipv4Addr) -> Option<Route> { 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(); let networks = self.read();
for (network, routes) in networks.iter() { for (network, routes) in networks.iter() {
if routes.local == Some(destination) { if routes.local == Some(destination) {
@@ -259,10 +309,13 @@ impl RoutingTable {
.iter() .iter()
.find(|(address, _)| *address == destination) .find(|(address, _)| *address == destination)
{ {
return Some(Route { return Some((
network: *network, Route {
peer: *peer, network: *network,
}); peer: *peer,
},
None,
));
} }
} }
// Inside an overlay range, an unowned address is nobody's, not the // 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) { if !is_internet_destination(destination) || in_any_range(&networks, destination) {
return None; 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. /// Whether a peer may send from a source address.
@@ -298,11 +352,14 @@ impl RoutingTable {
{ {
return Some(PacketSource::Member); 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) && is_internet_destination(source)
&& !in_any_range(&networks, source)) && !in_any_range(&networks, source))
.then_some(PacketSource::ExitReply { .then(|| PacketSource::ExitReply {
local: routes.local, local: routes.local,
exit: Arc::clone(exit),
}) })
} }
+55
View File
@@ -90,6 +90,23 @@ pub struct Announcement {
pub hostname: String, pub hostname: String,
/// Announced IP plugin capabilities. Opaque to the core. /// Announced IP plugin capabilities. Opaque to the core.
pub capabilities: Vec<PluginCapability>, 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 /// 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", 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");
}
}
}
+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 // 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 // can be a round before its announcement carrying the hostname arrives, so
// this waits for the hostnames rather than reading them straight away. // this waits for the hostnames rather than reading them straight away.
let hostnames: HashSet<String> = wait_until("three distinct peer hostnames", || async { let hostnames: HashSet<String> = wait_until(
let status = agents[0].agent.network_status(network_id).await.ok()?; "three peers announce their hostname and release",
let hostnames: HashSet<String> = status || async {
.peers let status = agents[0].agent.network_status(network_id).await.ok()?;
.iter() let hostnames: HashSet<String> = status
.filter_map(|peer| peer.hostname.clone()) .peers
.collect(); .iter()
(hostnames.len() >= 3).then_some(hostnames) .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; .await;
assert_eq!( assert_eq!(
hostnames.len(), hostnames.len(),
+2
View File
@@ -102,6 +102,7 @@ pub fn networks(
.peers .peers
.iter() .iter()
.map(|peer| PeerReport { .map(|peer| PeerReport {
agent_version: peer.agent_version.clone(),
data_error: peer.data_error.clone(), data_error: peer.data_error.clone(),
endpoint_id: peer.endpoint_id.to_string(), endpoint_id: peer.endpoint_id.to_string(),
hostname: peer.hostname.clone(), hostname: peer.hostname.clone(),
@@ -193,6 +194,7 @@ fn exit_report(network: &tsunagi::agent::NetworkStatus) -> tsunagi::ipc::ExitRep
}) })
}; };
tsunagi::ipc::ExitReport { tsunagi::ipc::ExitReport {
traffic: network.exit_traffic,
offering: network.exit_offer, offering: network.exit_offer,
offer_rules: rules(&network.exit_rules.offer), offer_rules: rules(&network.exit_rules.offer),
forwarding: network.exit_rules.forwarding, forwarding: network.exit_rules.forwarding,
+2 -2
View File
@@ -162,8 +162,8 @@ impl App {
.with_title(devices::title(network)) .with_title(devices::title(network))
.with_app_id(crate::icon::APP_ID) .with_app_id(crate::icon::APP_ID)
.with_icon(crate::icon::window()) .with_icon(crate::icon::window())
.with_inner_size([1440.0, 640.0]) .with_inner_size([1000.0, 640.0])
.with_min_inner_size([800.0, 400.0]); .with_min_inner_size([560.0, 400.0]);
let agent = &self.agent; let agent = &self.agent;
let traffic = &self.traffic; let traffic = &self.traffic;
// The window shares the single unit setting, so its toggle and the // The window shares the single unit setting, so its toggle and the
+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.
+1 -1
View File
@@ -141,7 +141,7 @@ fn agent_table(ui: &mut egui::Ui, socket: Option<&str>, report: &StatusReport) {
ui.label(if socket.is_some() { ui.label(if socket.is_some() {
"can be managed (CAP_NET_ADMIN)" "can be managed (CAP_NET_ADMIN)"
} else { } else {
"Android VPN service" "Android foreground service"
}); });
} }
PrivilegeReport::Missing(_) => { PrivilegeReport::Missing(_) => {
+199 -121
View File
@@ -44,6 +44,7 @@ struct Device<'a> {
name_taken: Option<(&'a str, String)>, name_taken: Option<(&'a str, String)>,
/// The last hostname seen for it, kept while it is offline. /// The last hostname seen for it, kept while it is offline.
hostname: Option<&'a str>, hostname: Option<&'a str>,
agent_version: Option<&'a str>,
/// What clicking the hostname copies: `hostname.network`, so it resolves. /// What clicking the hostname copies: `hostname.network`, so it resolves.
copy: Option<String>, copy: Option<String>,
/// The full endpoint id, which clicking the short form copies. /// The full endpoint id, which clicking the short form copies.
@@ -104,6 +105,11 @@ impl Device<'_> {
fn sort_key(&self) -> String { fn sort_key(&self) -> String {
self.hostname.unwrap_or(self.id).to_lowercase() 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. /// The first characters of an endpoint id, enough to tell devices apart.
@@ -122,6 +128,11 @@ fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
} }
_ => format::copy_field(ui, &short_id(device.id), device.id), _ => 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 { if let Some((name, holder)) = &device.name_taken {
ui.label(egui::RichText::new(egui_phosphor::regular::WARNING).color(AMBER)) ui.label(egui::RichText::new(egui_phosphor::regular::WARNING).color(AMBER))
.on_hover_text(format!( .on_hover_text(format!(
@@ -170,23 +181,23 @@ pub fn show(
}); });
return; 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 devices = devices(network, own_id);
let online = devices.iter().filter(|d| d.online).count(); let online = devices.iter().filter(|d| d.online).count();
ui.label( ui.columns(2, |columns| {
egui::RichText::new(format!( columns[0].strong(format!(
"devices ({} online / {} known)", "devices ({online} online / {} known)",
online,
devices.len() 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() egui::ScrollArea::both()
.auto_shrink([false, false]) .auto_shrink([false, false])
.show(ui, |ui| { .show(ui, |ui| {
@@ -335,7 +346,9 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) {
.spacing([12.0, 3.0]) .spacing([12.0, 3.0])
.show(ui, |ui| { .show(ui, |ui| {
ui.weak("id"); ui.weak("id");
let id = if ui.ctx().os() == egui::os::OperatingSystem::Android { let id = if ui.ctx().os() == egui::os::OperatingSystem::Android
|| ui.available_width() < 440.0
{
format::short(&network.network_id) format::short(&network.network_id)
} else { } else {
network.network_id.clone() network.network_id.clone()
@@ -460,6 +473,7 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
via_name, via_name,
name_taken, name_taken,
hostname, hostname,
agent_version: peer.and_then(|p| p.agent_version.as_deref()),
copy: hostname.map(|h| format!("{h}.{}", network.name)), copy: hostname.map(|h| format!("{h}.{}", network.name)),
id, id,
data_error: peer.and_then(|p| p.data_error.as_deref()), data_error: peer.and_then(|p| p.data_error.as_deref()),
@@ -484,44 +498,55 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
devices devices
} }
const COLUMN_HEADERS: [&str; 10] = [ fn column_headers(unit: Unit) -> [&'static str; 9] {
"device", [
"exit", "device",
"data", "exit",
"RTT data / control", "data",
"address", "RTT data / control",
"data path", "address",
"pkts", "data path",
"bytes", match unit {
"rate", Unit::Bytes => "bytes (TX / RX)",
"plot", Unit::Packets => "pkts (TX / RX)",
]; },
"rate",
"plot",
]
}
/// Initial column floors; actual headers, values and totals can grow them. /// Initial column floors; actual headers, values and totals can grow them.
const COLUMN_SAMPLES: [&str; 10] = [ const COLUMN_SAMPLES: [&str; 9] = [
"device", "device",
"exit", "exit",
"data", "data",
"9999 ms", "9999 ms",
"255.255.255.255", "255.255.255.255",
"data path", "data path",
"99999/99999",
"1023.9 MB / 1023.9 MB", "1023.9 MB / 1023.9 MB",
"1023.9 kB/s", "1023.9 kB/s",
"plot", "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. /// Column widths that only ever grow, kept across frames.
/// ///
/// Live values can change width between frames. A value that /// 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 /// 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 /// column in and push every cell after it. Remembering the widest seen keeps
/// the table where it is. /// the table where it is.
fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 10] { fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 9] {
let stored: Option<[f32; 10]> = ui.memory(|m| m.data.get_temp(id)); let stored: Option<[f32; 9]> = ui.memory(|m| m.data.get_temp(id));
stored.unwrap_or_else(|| { stored.unwrap_or_else(|| {
let font = egui::FontSelection::Default.resolve(ui.style()); 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) { for (width, sample) in widths.iter_mut().zip(COLUMN_SAMPLES) {
if !sample.is_empty() { if !sample.is_empty() {
*width = ui.fonts(|fonts| { *width = ui.fonts(|fonts| {
@@ -536,10 +561,9 @@ fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 10] {
}) })
} }
fn stretch_columns(mut widths: [f32; 10], available: f32) -> [f32; 10] { fn stretch_columns(mut widths: [f32; 9], available: f32) -> [f32; 9] {
let gaps = 10.0 * (widths.len() - 1) as f32; let gaps = crate::table::GAP * (widths.len() - 1) as f32;
widths[9] = widths[9].max(100.0); widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(100.0, 180.0);
widths[9] += (available - gaps - widths.iter().sum::<f32>()).max(0.0);
widths widths
} }
@@ -618,16 +642,17 @@ fn device_table(
.x .x
}) })
}; };
for (column, header) in COLUMN_HEADERS.into_iter().enumerate() { let headers = column_headers(unit);
widths[column] = widths[column].max(measure(header.to_owned())); 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) = let (mut tx_total, mut rx_total) = (0_u64, 0_u64);
(0, 0, 0, 0);
for device in devices { for device in devices {
let name = format!( let name = format!(
"{} ({}){}", "{} ({}) {}{}",
device.name(), device.name(),
short_id(device.id), short_id(device.id),
device.version_label(),
if !device.online { " Forget" } else { "" } if !device.online { " Forget" } else { "" }
); );
widths[0] = widths[0].max(measure(name) + 24.0); widths[0] = widths[0].max(measure(name) + 24.0);
@@ -641,59 +666,36 @@ fn device_table(
widths[column] = widths[column].max(measure(text)); widths[column] = widths[column].max(measure(text));
} }
if let Some(peer) = device.overlay { if let Some(peer) = device.overlay {
tx_packets = tx_packets.saturating_add(peer.tx_packets); let (tx, rx) = unit.counters(peer);
rx_packets = rx_packets.saturating_add(peer.rx_packets); tx_total = tx_total.saturating_add(tx);
tx_bytes = tx_bytes.saturating_add(peer.tx_bytes); rx_total = rx_total.saturating_add(rx);
rx_bytes = rx_bytes.saturating_add(peer.rx_bytes); widths[6] = widths[6].max(measure(traffic_pair(tx, rx, unit)));
for (column, text) in [ widths[7] = widths[7].max(measure(format::series_rate(
(6, format!("{}/{}", peer.tx_packets, peer.rx_packets)), traffic.peer(network_id, &peer.public_key),
( unit,
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));
}
} }
} }
for (column, text) in [ let total = traffic_pair(tx_total, rx_total, unit);
(6, format!("{tx_packets}/{rx_packets}")), let rate = format::series_rate(traffic.network(network_id), unit);
( widths[6] = widths[6].max(measure(total.clone()));
7, widths[7] = widths[7].max(measure(rate.clone()));
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));
}
if widths != previous_widths { if widths != previous_widths {
ui.ctx().request_repaint(); ui.ctx().request_repaint();
} }
ui.memory_mut(|m| m.data.insert_temp(widths_id, widths)); ui.memory_mut(|m| m.data.insert_temp(widths_id, widths));
let widths = stretch_columns(widths, ui.available_width()); let widths = stretch_columns(widths, ui.available_width());
crate::table::row(ui, "device headers", &widths, false, |column, ui| { 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 { match column {
2 => { 2 => {
response.on_hover_text("Encrypted data channel readiness."); response.on_hover_text("Encrypted data channel readiness.");
} }
3 => { 3 => {
response.on_hover_text("Control-connection round-trip time."); response.on_hover_text("Data-link and control-connection round-trip times.");
} }
7 => { 6 => {
response.on_hover_text("Plaintext IP bytes accepted by the encrypted channel in this counter lifetime; excludes relay transit, transport overhead and delivery probes."); response.on_hover_text("Sent / received IP traffic in the selected unit. Excludes relay transit and transport overhead.");
} }
5 => { 5 => {
response.on_hover_text("External data transport or relay route."); response.on_hover_text("External data transport or relay route.");
@@ -731,16 +733,10 @@ fn device_table(
let series = traffic.peer(network_id, &peer.public_key); let series = traffic.peer(network_id, &peer.public_key);
match column { match column {
6 => { 6 => {
ui.label(format!("{}/{}", peer.tx_packets, peer.rx_packets)); let (tx, rx) = unit.counters(peer);
ui.label(traffic_pair(tx, rx, unit));
} }
7 => { 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)); ui.label(format::series_rate(series, unit));
} }
_ => format::sparkline(ui, series, unit, 24.0), _ => format::sparkline(ui, series, unit, 24.0),
@@ -762,17 +758,10 @@ fn device_table(
ui.strong("total"); ui.strong("total");
} }
6 => { 6 => {
ui.strong(format!("{tx_packets}/{rx_packets}")); ui.strong(&total);
} }
7 => { 7 => {
ui.strong(format!( ui.strong(&rate);
"{} / {}",
format::bytes(tx_bytes as f64),
format::bytes(rx_bytes as f64)
));
}
8 => {
ui.strong(format::series_rate(traffic.network(network_id), unit));
} }
_ => {} _ => {}
}, },
@@ -903,17 +892,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] #[test]
fn phone_roster_fits_each_width_and_expands_only_the_tapped_member() { 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 { let mut network = NetworkReport {
network_id: "a".repeat(60), network_id: "a".repeat(60),
name: "lab".into(), name: "lab".into(),
@@ -933,9 +923,24 @@ mod tests {
m.overlay_address_v4 = Some(format!("192.168.254.{}", 240 + i)); m.overlay_address_v4 = Some(format!("192.168.254.{}", 240 + i));
network.members.push(m); 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] { for width in [320.0, 360.0, 430.0, 870.0] {
let ctx = egui::Context::default(); let ctx = egui::Context::default();
ctx.set_os(egui::os::OperatingSystem::Android); ctx.set_os(egui::os::OperatingSystem::Android);
ctx.set_fonts(crate::app_fonts());
let frame = |events| { let frame = |events| {
ctx.run( ctx.run(
egui::RawInput { egui::RawInput {
@@ -950,7 +955,7 @@ mod tests {
show( show(
ctx, ctx,
&ReadOnly, &ReadOnly,
&mut Unit::Packets, &mut Unit::Bytes,
(&mut None, &mut None), (&mut None, &mut None),
&network, &network,
"self", "self",
@@ -999,8 +1004,22 @@ mod tests {
}; };
let expanded = click(a); let expanded = click(a);
assert_eq!(positions(&expanded, "Endpoint ID").len(), 1); 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]); let switched = click(positions(&expanded, "bravo")[0]);
assert_eq!(positions(&switched, "Endpoint ID").len(), 1); assert_eq!(positions(&switched, "Endpoint ID").len(), 1);
assert_eq!(positions(&switched, "Unknown").len(), 1);
let closed = click(positions(&switched, "bravo")[0]); let closed = click(positions(&switched, "bravo")[0]);
assert!(positions(&closed, "Endpoint ID").is_empty()); assert!(positions(&closed, "Endpoint ID").is_empty());
} }
@@ -1133,11 +1152,11 @@ mod tests {
} }
#[test] #[test]
fn resized_table_fills_the_window_without_growing_fixed_columns() { fn wider_windows_keep_a_compact_plot_and_narrow_windows_preserve_column_floors() {
let minimum = [100.0; 10]; let minimum = [100.0; 9];
let wide = stretch_columns(minimum, 1440.0); let wide = stretch_columns(minimum, 1440.0);
assert!((wide.iter().sum::<f32>() + 90.0 - 1440.0).abs() < 0.1); assert!((100.0..=190.0).contains(&wide[8]));
assert_eq!(&wide[..9], &minimum[..9]); assert_eq!(&wide[..8], &minimum[..8]);
let narrow = stretch_columns(minimum, 800.0); let narrow = stretch_columns(minimum, 800.0);
assert_eq!( assert_eq!(
narrow, minimum, narrow, minimum,
@@ -1148,6 +1167,39 @@ mod tests {
wide, wide,
"a resize does not accumulate padding" "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] #[test]
@@ -1168,18 +1220,19 @@ mod tests {
} }
let context = egui::Context::default(); let context = egui::Context::default();
for (width, packets, age) in [ for (width, packets, age, unit) in [
(1600.0, 1569, 56), (1600.0, 1569, 56, crate::home::UiState::default().unit),
(1600.0, 55_555, 172_800), (1600.0, 55_555, 172_800, Unit::Packets),
(1600.0, 137_245, 172_800), (1600.0, 137_245, 172_800, Unit::Bytes),
(900.0, 9_876_543_210, 172_800), (900.0, 9_876_543_210, 172_800, Unit::Packets),
(1600.0, 42, 56), (1600.0, 42, 56, Unit::Bytes),
] { ] {
let network = NetworkReport { let network = NetworkReport {
network_id: "network".into(), network_id: "network".into(),
peers: ["peer", "other"] peers: ["peer", "other"]
.into_iter() .into_iter()
.map(|id| PeerReport { .map(|id| PeerReport {
agent_version: (id == "peer").then(|| "2.0.0-rc.1".into()),
data_error: None, data_error: None,
endpoint_id: id.into(), endpoint_id: id.into(),
rtt_ms: Some(12_345), rtt_ms: Some(12_345),
@@ -1220,7 +1273,7 @@ mod tests {
ui.allocate_ui(egui::vec2(width, 480.0), |ui| { ui.allocate_ui(egui::vec2(width, 480.0), |ui| {
device_table( device_table(
ui, ui,
Unit::Packets, unit,
&network, &network,
&rows, &rows,
&Traffic::default(), &Traffic::default(),
@@ -1234,11 +1287,36 @@ mod tests {
let shapes: Vec<_> = output.shapes.into_iter().map(|s| s.shape).collect(); let shapes: Vec<_> = output.shapes.into_iter().map(|s| s.shape).collect();
let mut texts = Vec::new(); let mut texts = Vec::new();
collect_text(&shapes, &mut texts); 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 [ for (label, next_column) in [
("RTT data / control".to_string(), "address"), ("RTT data / control".to_string(), "address"),
(rtt_pair(&rows[0]), "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 let right = texts
.iter() .iter()
@@ -1403,7 +1481,7 @@ mod tests {
&mut None, &mut None,
&mut None, &mut None,
); );
let stored: [f32; 10] = ui let stored: [f32; 9] = ui
.memory(|memory| { .memory(|memory| {
memory memory
.data .data
+97 -69
View File
@@ -130,74 +130,102 @@ fn details(
exit: &mut Option<ExitConfirm>, exit: &mut Option<ExitConfirm>,
forget: &mut Option<ForgetConfirm>, forget: &mut Option<ForgetConfirm>,
) { ) {
ui.horizontal_wrapped(|ui| { egui::Frame::new()
ui.weak(if member.online { "online" } else { "offline" }); .fill(ui.visuals().faint_bg_color)
if let Some(name) = &member.copy { .inner_margin(egui::Margin::symmetric(10, 8))
format::copy_field(ui, &member.name(), name); .show(ui, |ui| {
} ui.set_min_width(ui.available_width());
if let Some(address) = &member.address { ui.spacing_mut().item_spacing.y = 4.0;
format::copy_field(ui, address, address); ui.columns(2, |cols| {
} cols[0].small("Data path");
}); let (path, _) =
ui.horizontal_wrapped(|ui| { data_path_text(member.path, member.via_name.as_deref(), member.online);
ui.weak("Endpoint ID"); cols[0].horizontal_wrapped(|ui| {
format::copy_field(ui, &format::short(member.id), member.id); ui.label(path);
}); if member.online {
let (path, _) = data_path_text(member.path, member.via_name.as_deref(), member.online); tunnel_cell(ui, member);
ui.horizontal_wrapped(|ui| { }
ui.label(path); });
tunnel_cell(ui, member); cols[1].small("Tsunagi version");
}); cols[1].label(member.agent_version.unwrap_or("Unknown"));
if member.online { });
if let Some(path) = member.data_transport_detail { if let Some(path) = member.data_transport_detail {
ui.label(path); ui.add(egui::Label::new(path).wrap());
} }
ui.label(format!( if member.online {
"Data RTT {} · Control RTT {}", ui.columns(2, |cols| {
rtt_text(member.data_rtt_ms), cols[0].small("Data RTT");
rtt_text(member.control_rtt_ms) 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(error) = member.data_error { });
ui.colored_label(AMBER, error); }
} if let Some(peer) = member.overlay.filter(|_| member.online) {
if let Some((taken, holder)) = &member.name_taken { ui.separator();
ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}.")); let (tx, rx) = unit.counters(peer);
} let sent_color = ui.visuals().hyperlink_color;
if let Some(peer) = member.overlay { ui.columns(2, |cols| {
let series = traffic.peer(&network.network_id, &peer.public_key); for (col, arrow, caption, count, color) in [
ui.horizontal_wrapped(|ui| { (0, icon::ARROW_UP, "Sent", tx, sent_color),
ui.label(format!( (1, icon::ARROW_DOWN, "Received", rx, exit::GOOD),
"TX {} · {} pkts", ] {
format::bytes(peer.tx_bytes as f64), cols[col].horizontal(|ui| {
peer.tx_packets ui.colored_label(color, arrow);
)); ui.label(caption);
ui.label(format!( });
"RX {} · {} pkts", let value = format::amount(count, unit);
format::bytes(peer.rx_bytes as f64), let value = match unit {
peer.rx_packets Unit::Packets => format!("{value} pkts"),
)); Unit::Bytes => value,
ui.weak(format::series_rate(series, unit)); };
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(AMBER, 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();
} }
+8
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. /// A rate in the chosen unit, per second.
pub fn rate(value: f32, unit: Unit) -> String { pub fn rate(value: f32, unit: Unit) -> String {
match unit { match unit {
+234 -120
View File
@@ -28,6 +28,8 @@ pub struct UiState {
pub join: JoinForm, pub join: JoinForm,
/// Whether rates and sparklines are shown in packets or bytes. /// Whether rates and sparklines are shown in packets or bytes.
pub unit: Unit, pub unit: Unit,
/// Network details opened during this run, keyed by identity even for namesakes.
expanded_networks: BTreeSet<String>,
/// An in-progress hostname edit (`None` when not editing). /// An in-progress hostname edit (`None` when not editing).
pub host_edit: Option<String>, pub host_edit: Option<String>,
/// Network ids whose devices window is open. /// Network ids whose devices window is open.
@@ -46,7 +48,8 @@ impl Default for UiState {
fn default() -> Self { fn default() -> Self {
Self { Self {
join: JoinForm::default(), join: JoinForm::default(),
unit: Unit::Packets, unit: Unit::Bytes,
expanded_networks: BTreeSet::new(),
host_edit: None, host_edit: None,
open_devices: BTreeSet::new(), open_devices: BTreeSet::new(),
vip_windows: Default::default(), vip_windows: Default::default(),
@@ -121,97 +124,153 @@ pub fn draw_network(
offer_exit: bool, offer_exit: bool,
) -> bool { ) -> bool {
let mut pick_exit = false; let mut pick_exit = false;
ui.add_space(6.0); ui.add_space(5.0);
egui::Frame::group(ui.style()).show(ui, |ui| { ui.push_id(&network.network_id, |ui| {
ui.horizontal(|ui| { egui::Frame::group(ui.style()).show(ui, |ui| {
format::copy_field(ui, network.name.as_str(), &network.name); ui.set_min_width(ui.available_width());
if ui.button("VIP").clicked(){state.vip_windows.entry(network.network_id.clone()).or_default();} let mut open = state.expanded_networks.contains(&network.network_id);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let status = if network.active {
let leave = format!(
egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE)) "{} online",
.fill(LEAVE_RED); devices::online_count(network, &report.endpoint_id)
if ui.add(leave).clicked() { )
agent.send(Command::Leave { } else {
"Stopped".to_owned()
};
if network_header(ui, &network.name, &status, open).clicked() {
open = !open;
if open {
state.expanded_networks.insert(network.network_id.clone());
} else {
state.expanded_networks.remove(&network.network_id);
}
}
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");
}
if !open {
return;
}
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);
pick_exit = network_settings(ui, agent, network, offer_exit);
ui.separator();
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(), network_id: network.network_id.clone(),
}); });
} }
if ui.button("Show devices").clicked() {
state.open_devices.insert(network.network_id.clone());
}
if ui.button("VIP").clicked() {
state
.vip_windows
.entry(network.network_id.clone())
.or_default();
}
}); });
}); });
});
pick_exit
}
let address = network.overlay.as_ref().and_then(|o| o.address.as_ref()); fn draw_metadata(ui: &mut egui::Ui, network: &NetworkReport, own_id: &str) {
let series = traffic.network(&network.network_id); egui::Grid::new(ui.id().with("metadata"))
.num_columns(2)
egui::Grid::new(("net", &network.network_id)) .spacing([10.0, 3.0])
.num_columns(2) .show(ui, |ui| {
.spacing([10.0, 3.0]) ui.weak("name");
.show(ui, |ui| { format::copy_field(ui, &network.name, &network.name);
ui.weak("id"); ui.end_row();
format::copy_field(ui, &format::short(&network.network_id), &network.network_id); 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(); ui.end_row();
if let Some(range) = &network.range {
ui.weak("range");
format::copy_field(ui, range, range);
ui.end_row();
}
if let Some(address) = address {
ui.weak("addr");
format::copy_field(ui, address, address);
ui.end_row();
}
ui.weak("peers");
ui.label(format!(
"{} online · {} known",
devices::online_count(network, &report.endpoint_id),
devices::known_count(network, &report.endpoint_id)
));
ui.end_row();
});
draw_protocols(ui, agent, network, &report.available_protocols);
format::sparkline(ui, series, state.unit, 34.0);
if !network.range_conflicts.is_empty() {
ui.colored_label(BAD, "Stopped: overlapping network ranges");
for conflict in &network.range_conflicts {
ui.label(format!("{} ({}) uses {}", conflict.name, conflict.network_id, conflict.range));
} }
ui.label("Switching suspends these networks until this network stops, then resumes them automatically."); if let Some(address) = network.overlay.as_ref().and_then(|o| o.address.as_ref()) {
if network.auto_start { ui.weak("This network will resume automatically when its range is free."); } ui.weak("addr");
format::copy_field(ui, address, address);
ui.end_row();
}
ui.weak("peers");
ui.label(format!("{} known", 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.horizontal_wrapped(|ui| { ui.label("Switching suspends these networks until this network stops, then resumes them automatically.");
if !network.active && !network.range_conflicts.is_empty() { if network.auto_start {
if ui.button("Switch to this network").clicked() { ui.weak("This network will resume automatically when its range is free.");
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: true }); }
} }
if network.auto_start && ui.button("Keep stopped").clicked() { ui.horizontal_wrapped(|ui| {
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: false }); if !network.active && !network.range_conflicts.is_empty() {
} if ui.button("Switch to this network").clicked() {
} else { agent.send(Command::SetActive {
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(), 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; let mut offering = network.exit.offering;
if offer_exit && ui if ui
.checkbox(&mut offering, "exit node") .checkbox(&mut offering, "exit node")
.on_hover_text( .on_hover_text("Let members send all their internet traffic through this device, which can see it.")
"let other members send all their internet traffic through this \
device, which can see it",
)
.changed() .changed()
{ {
agent.send(Command::SetExitOffer { agent.send(Command::SetExitOffer {
@@ -219,54 +278,109 @@ pub fn draw_network(
enabled: offering, enabled: offering,
}); });
} }
}); } else {
ui.horizontal(|ui| { pick_exit = ui.button("Exit node…").clicked();
// In the bottom left corner while this device sends its traffic through }
// somebody: green while that works, red while it does not. let leave = egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE))
if let Some(via) = &network.exit.via { .fill(LEAVE_RED);
let color = if network.exit.via_online { if ui.add(leave).clicked() {
exit::GOOD agent.send(Command::Leave {
} else { network_id: network.network_id.clone(),
exit::LOUD
};
let response = ui
.add(
egui::Label::new(
egui::RichText::new(icon::SIGN_OUT).size(18.0).color(color),
)
.sense(egui::Sense::click()),
)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(format!(
"exit node: {} — click to stop",
exit::name_of(network, via)
));
if response.clicked() {
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
}
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Show devices").clicked() {
state.open_devices.insert(network.network_id.clone());
}
if ui
.button(format!("{} Copy secret", icon::COPY))
.on_hover_text("copy this network's secret to the clipboard")
.clicked()
{
agent.send(Command::CopySecret {
network_id: network.network_id.clone(),
});
}
}); });
});
for warning in exit::warnings(network) {
draw_exit_warning(ui, &warning);
} }
}); });
pick_exit 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(),
);
response
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(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 clicked = ui
.add(egui::Button::new(egui::RichText::new(icon::SIGN_OUT).color(color)).frame(false))
.on_hover_text("Stop using this exit node")
.clicked();
if ui
.link(format!("Exit via {name}"))
.on_hover_text("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 {
ui.label(format!(
"{} {}",
icon::ARROW_UP,
format::bytes(t.tx_bytes as f64)
))
.on_hover_text("Sent through this exit");
ui.label(format!(
"{} {}",
icon::ARROW_DOWN,
format::bytes(t.rx_bytes as f64)
))
.on_hover_text("Received through this exit");
}
});
}
fn draw_protocols( fn draw_protocols(
ui: &mut egui::Ui, ui: &mut egui::Ui,
agent: &dyn Client, agent: &dyn Client,
+10 -1
View File
@@ -11,9 +11,18 @@ mod table;
pub mod vip; pub mod vip;
mod vip_status; mod vip_status;
/// 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 { pub fn app_fonts() -> egui::FontDefinitions {
let mut fonts = egui::FontDefinitions::default(); let mut fonts = egui::FontDefinitions::default();
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); 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 fonts
} }
+9
View File
@@ -23,6 +23,15 @@ pub enum Unit {
Bytes, 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. /// One series' rolling packet and byte rates.
#[derive(Default)] #[derive(Default)]
pub struct Series { pub struct Series {
@@ -359,6 +359,15 @@ async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
let reply = ipv4_packet(INTERNET, chosen.client_addr, b"reply"); let reply = ipv4_packet(INTERNET, chosen.client_addr, b"reply");
chosen.peer_tun.push_from_os(reply.clone()); chosen.peer_tun.push_from_os(reply.clone());
assert_eq!(next(&tun).await, reply); 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; peer.agent.shutdown().await;
client.agent.shutdown().await; client.agent.shutdown().await;
@@ -37,6 +37,7 @@ fn source(agent: Agent, plugin: Arc<WireguardPlugin>) -> Arc<dyn tsunagi::ipc::R
.peers .peers
.iter() .iter()
.map(|peer| tsunagi::ipc::PeerReport { .map(|peer| tsunagi::ipc::PeerReport {
agent_version: peer.agent_version.clone(),
data_error: None, data_error: None,
endpoint_id: peer.endpoint_id.to_string(), endpoint_id: peer.endpoint_id.to_string(),
hostname: peer.hostname.clone(), hostname: peer.hostname.clone(),
+1
View File
@@ -5206,6 +5206,7 @@ mod status_tests {
relay_sent_via: 0, relay_sent_via: 0,
relay_received_via: 0, relay_received_via: 0,
peers: vec![PeerReport { peers: vec![PeerReport {
agent_version: None,
data_error: None, data_error: None,
endpoint_id: ONLINE.into(), endpoint_id: ONLINE.into(),
hostname: Some("music".into()), hostname: Some("music".into()),
+1 -1
View File
@@ -123,7 +123,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 `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 `tsunagi/ctrl/8`, discovery, membership and signed state are unchanged. The data
ALPN is `tsunagi/data/6`; the relay envelope format is unchanged. Automatic 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 so agent, CLI and tray must match. Historical `wg-quic/wireguard.sqlite` is the
canonical internal key store. Missing keys are imported transactionally from canonical internal key store. Missing keys are imported transactionally from
`wg` then `awg`, without replacing an existing canonical key or modifying a `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 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. 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 An agent uses **one exit node across all active networks**. Choosing another
replaces the previous selection and survives restart. Internet packets use replaces the previous selection and survives restart. Internet packets use
+15 -5
View File
@@ -15,10 +15,12 @@ Upgrading the crate or bumping the control protocol must never change an
existing `NetworkId`. existing `NetworkId`.
Control version 8 adds signed, multi-writer VIP field snapshots to version 7's 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 node retirements. The transition from control v7 to v8 requires updating all
together. Network ids, derivation labels, handshake encoding and existing record members together. Members already on v8 can adopt the optional software version
signatures are unchanged. Local CLI/tray IPC is version 23; restart the agent field independently. Data ALPN is `tsunagi/data/6` for the single internal
with matching clients. SQLite schema 10 adds `vip_fields`, preserving identity, 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. network configuration, signed node records and retirement proofs.
See [virtual services](vip.md), [state sync](sync-model.md) and [AWG](amnezia.md). See [virtual services](vip.md), [state sync](sync-model.md) and [AWG](amnezia.md).
@@ -248,7 +250,7 @@ not affect other networks.
| message | meaning | | 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 | | `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 | | `Ping { seq, payload }` | small request used to verify the exchange |
| `Pong { seq, payload }` | the echoed reply | | `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 | | `Reachable { links }` | sender's current direct data links, by kind of transport |
| `Bye { reason }` | graceful goodbye; not a revocation of anything | | `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 `broadcast` is a per-network local opt-in, enabled by default and treated as
false until an authenticated announcement arrives. It governs IP broadcast false until an authenticated announcement arrives. It governs IP broadcast
fanout and local admission; encrypted transit still uses the existing envelope. fanout and local admission; encrypted transit still uses the existing envelope.