diff --git a/README.md b/README.md index 940120c..a847573 100644 --- a/README.md +++ b/README.md @@ -141,8 +141,11 @@ tsng protocols home none # control plane only Exact network names, full ids and unique id prefixes work here. The choice is local to this device, saved per network and applied immediately; an offline -change applies on the next start. In the tray, expand **data transports** on a network -tile to enable transports and set their initial preference order. Adjacent peers need a common external transport at the same wire version. +change applies on the next start. In the tray or on Android, click the network +name to expand its card. Open **data transports** to enable transports and set +their initial preference order. **Show devices** lists peers and their reported +Tsunagi versions. On Android, tap a device to see its version and traffic. +Adjacent peers need a common external transport at the same wire version. Peers that both support link comparison probe another mutually enabled transport while traffic continues on the current one. They can switch to a faster healthy link. `tsng status` and the tray show the direct data link's measured RTT separately diff --git a/android/README.md b/android/README.md index c7c6907..81256a3 100644 --- a/android/README.md +++ b/android/README.md @@ -16,7 +16,7 @@ cd android adb install -r app/build/outputs/apk/debug/app-debug.apk ``` -Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join with the existing network name and secret. Android keeps the established VPN service bound when the activity closes. **About → Stop VPN** disconnects it. The app-private state directory holds the device identity and its saved networks. +Open **tsunagi** to start the agent. On first launch, accept Android’s VPN permission prompt so the agent can create its mesh interface. Join with the existing network name and secret. The service continues when the activity closes. **About → Stop Tsunagi Agent** keeps it stopped across launches. After stopping or declining consent, tap **Start Tsunagi Agent** to enable automatic startup again. The app-private state directory holds the device identity and its saved networks. The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic. @@ -26,7 +26,7 @@ Applications using Android’s system resolver can connect to `.= 33 && !askedForNotifications && @@ -20,6 +23,7 @@ class MainActivity : Activity() { private lateinit var surface: MeshSurface override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + consentPending = savedInstanceState?.getBoolean("consent_pending") == true surface = MeshSurface(this) val root = FrameLayout(this) if (Build.VERSION.SDK_INT >= 30) { @@ -33,17 +37,43 @@ class MainActivity : Activity() { root.addView(surface) 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) - if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java)) - else startActivityForResult(consent, 1) + if (consent == null) startAgent() else { + consentPending = true + startActivityForResult(consent, 1) + } + } + private fun startAgent() { + settings.edit().putBoolean("auto_start", true).apply() + val service = Intent(this, MeshVpn::class.java) + // A retry of an existing service may already have left foreground mode. + if (MeshVpn.started) startService(service) else startForegroundService(service) + } + internal fun stopAgent() { + settings.edit().putBoolean("auto_start", false).apply() + startService(Intent(this, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } @Deprecated("Platform consent result") override fun onActivityResult(request: Int, result: Int, data: Intent?) { super.onActivityResult(request, result, data) if (request == 1) { - if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java)) - else surface.input(5, "VPN permission was declined") + consentPending = false + if (result == RESULT_OK) startAgent() else { + settings.edit().putBoolean("auto_start", false).apply() + surface.input(5, "Android VPN permission was declined") + } } } @Deprecated("Forward system Back to the current Rust view") diff --git a/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt b/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt index 5cd630d..337b154 100644 --- a/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt +++ b/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt @@ -34,7 +34,7 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface() override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h } override fun onDrawFrame(gl: GL10?) { - val delay = Native.draw(this, widthPx, heightPx, density) + val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started) removeCallbacks(repaint) postDelayed(repaint, delay.coerceAtLeast(16)) } @@ -58,8 +58,8 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), return true } - fun startVpn() { post { activity.requestVpn() } } - fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } } + fun startAgent() { post { activity.requestAgent() } } + fun stopAgent() { post { activity.stopAgent() } } fun requestExitNotifications() { post { activity.requestExitNotifications() } } fun closeScreen() { post { activity.finish() } } fun openUrl(url: String) { post { diff --git a/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt b/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt index 4b50e67..b1cc919 100644 --- a/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt +++ b/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt @@ -27,6 +27,8 @@ class MeshVpn : VpnService() { private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT" private const val NOTIFICATION_ID = 1 private const val EXIT_CHANNEL = "exit-node" + @Volatile var started = false + private set } private val main = Handler(Looper.getMainLooper()) private val notifications by lazy { getSystemService(NotificationManager::class.java) } @@ -34,7 +36,6 @@ class MeshVpn : VpnService() { private var closed = false private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) } @Volatile private var upstream: Network? = null - private var watching = false private val changes = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) = useUnderlay(network) override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) { @@ -77,15 +78,15 @@ class MeshVpn : VpnService() { STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY } DISCONNECT_EXIT -> { val ids = intent.data?.pathSegments.orEmpty() - if (watching && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) { + if (started && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) { if (!Native.disconnectExit(instance, ids[0], ids[1])) { android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show() } - } else if (!watching) stopSelf(startId) + } else if (!started) stopSelf(startId) return START_NOT_STICKY } } - if (watching) { + if (started) { if (Native.failed(instance)) { Native.stop(instance) instance = 0 @@ -93,12 +94,13 @@ class MeshVpn : VpnService() { } return START_NOT_STICKY } - notifications.createNotificationChannel(NotificationChannel("vpn", "VPN", NotificationManager.IMPORTANCE_LOW)) + closed = false + notifications.createNotificationChannel(NotificationChannel("vpn", "Tsunagi Agent", NotificationManager.IMPORTANCE_LOW)) notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW)) - val startup = notification("vpn").setContentTitle("Starting mesh VPN") + val startup = notification("vpn").setContentTitle("Starting Tsunagi Agent") if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED) startForeground(NOTIFICATION_ID, startup.build()) - watching = true + started = true connectivity.requestNetwork(NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper())) @@ -189,8 +191,12 @@ class MeshVpn : VpnService() { @Synchronized private fun shutdown() { if (closed) return closed = true - if (watching) connectivity.unregisterNetworkCallback(changes) + if (started) connectivity.unregisterNetworkCallback(changes) + started = false if (instance != 0L) Native.stop(instance) + instance = 0L + upstream = null + physicalAddresses = "" connectivity.bindProcessToNetwork(null) stopForeground(STOP_FOREGROUND_REMOVE) } diff --git a/android/app/src/main/java/cy/hexor/tsunagi/Native.kt b/android/app/src/main/java/cy/hexor/tsunagi/Native.kt index 3c5e994..3d0a479 100644 --- a/android/app/src/main/java/cy/hexor/tsunagi/Native.kt +++ b/android/app/src/main/java/cy/hexor/tsunagi/Native.kt @@ -13,7 +13,7 @@ internal object Native { external fun networkChanged(instance: Long, addresses: String) external fun surface() - external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long + external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean): Long external fun touch(action: Int, id: Int, x: Float, y: Float) external fun input(kind: Int, value: String) external fun key(key: Int) diff --git a/crates/tsunagi-android/src/android/display.rs b/crates/tsunagi-android/src/android/display.rs index fcd3e2f..b7372a3 100644 --- a/crates/tsunagi-android/src/android/display.rs +++ b/crates/tsunagi-android/src/android/display.rs @@ -7,7 +7,7 @@ use egui_glow::{Painter, glow}; use jni::{ JNIEnv, objects::{JObject, JString, JValue}, - sys::{jfloat, jint, jlong}, + sys::{jboolean, jfloat, jint, jlong}, }; use std::{ cell::RefCell, @@ -75,6 +75,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw( w: jint, h: jint, scale: jfloat, + service_started: jboolean, ) -> jlong { with_display(|d| { 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); } let mut action = None; - let state = super::status(); + let state = match super::status() { + crate::service::State::Off if service_started != 0 => crate::service::State::Starting, + state => state, + }; let exit_active = matches!(&state, crate::service::State::Ready(report, _) if report.networks.iter().any(|n| n.active && n.exit.via.is_some())); if exit_active && !d.exit_active { let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]); } d.exit_active = exit_active; let output = d.ctx.run(input, |ctx| { - action = d.ui.draw(ctx, &state, super::send); + action = d.ui.draw(ctx, &state, super::send).or(action); }); if let Some(action) = action { let method = match action { - SystemAction::Start => "startVpn", - SystemAction::Stop => "stopVpn", + SystemAction::Start => "startAgent", + SystemAction::Stop => "stopAgent", SystemAction::PasteSecret => "pasteSecret", SystemAction::Finish => "closeScreen", }; diff --git a/crates/tsunagi-android/src/android/mod.rs b/crates/tsunagi-android/src/android/mod.rs index 6fd8c3f..ac61aea 100644 --- a/crates/tsunagi-android/src/android/mod.rs +++ b/crates/tsunagi-android/src/android/mod.rs @@ -48,10 +48,10 @@ fn send(cmd: tsunagi_ui::client::Command) -> Result { let (reply, result) = oneshot::channel(); current() .as_ref() - .ok_or("VPN service stopped")? + .ok_or("Tsunagi Agent stopped")? .commands .try_send((Request::Action(cmd), reply)) - .map_err(|_| "VPN service is busy or stopped".to_owned())?; + .map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?; Ok(result) } diff --git a/crates/tsunagi-android/src/tests.rs b/crates/tsunagi-android/src/tests.rs index 46e4855..f270d61 100644 --- a/crates/tsunagi-android/src/tests.rs +++ b/crates/tsunagi-android/src/tests.rs @@ -480,7 +480,7 @@ async fn tun_reader_survives_address_changes_failed_establish_and_last_network_l } #[tokio::test] -async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() { +async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded() { use crate::{ service::{State, report}, view::{Phone, configure}, @@ -500,37 +500,102 @@ async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() { address: Some("10.1.2.3".into()), ..Default::default() }); + let mut other = sample.networks[0].clone(); + other.network_id = "another-network".into(); + sample.networks.push(other); + sample.networks[0].peers.push(tsunagi::ipc::PeerReport { + endpoint_id: "exit-endpoint-id".into(), + hostname: Some("gateway".into()), + ..Default::default() + }); + sample.networks[0].exit = tsunagi::ipc::ExitReport { + via: Some("exit-endpoint-id".into()), + via_online: true, + traffic: Some(tsunagi::overlay::exit::ExitTraffic { + tx_bytes: 2048, + rx_bytes: 512, + }), + client_rules: Some(tsunagi::ipc::RuleSetReport { + ok: true, + detail: String::new(), + }), + ..Default::default() + }; let state = State::Ready(Arc::new(sample), Instant::now()); let ctx = egui::Context::default(); configure(&ctx); let mut phone = Phone::default(); - let frame = ctx.run( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(360., 720.), - )), - ..Default::default() - }, - |ctx| { - phone.draw(ctx, &state, |_| { - panic!("drawing the overview issued a command") - }); - }, - ); - let y = |label: &str| { + let mut frame = |events| { + ctx.run( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(360., 720.), + )), + events, + ..Default::default() + }, + |ctx| { + phone.draw(ctx, &state, |_| { + panic!("drawing the overview issued a command") + }); + }, + ) + }; + let positions = |frame: &egui::FullOutput, label: &str| { frame .shapes .iter() - .find_map(|shape| match &shape.shape { - Shape::Text(text) if text.galley.text() == label => Some(text.pos.y), + .filter_map(|shape| match &shape.shape { + Shape::Text(text) if text.galley.text() == label => { + Some(text.pos + text.galley.rect.center().to_vec2()) + } _ => None, }) - .unwrap_or_else(|| panic!("missing label {label}")) + .collect::>() }; + 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("range") - y("id")))); 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; } @@ -631,6 +696,7 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() { } frame(vec![]) }; + click("lab"); let live = click("VIP"); for label in ["Overview", "Configuration", "Next new flow", "node:8080"] { let p = position(&live, label); diff --git a/crates/tsunagi-android/src/view.rs b/crates/tsunagi-android/src/view.rs index 5e229a4..38615e6 100644 --- a/crates/tsunagi-android/src/view.rs +++ b/crates/tsunagi-android/src/view.rs @@ -162,7 +162,7 @@ impl Phone { let outcome = match pending.result.try_recv() { Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return, Err(tokio::sync::oneshot::error::TryRecvError::Closed) => { - Err("VPN service stopped".to_owned()) + Err("Tsunagi Agent stopped".to_owned()) } Ok(v) => v, }; @@ -239,8 +239,9 @@ impl Phone { }); } else if self.page == Page::About && !matches!(state, State::Off) - && ui.button("Stop VPN").clicked() + && ui.button("Stop Tsunagi Agent").clicked() { + self.home(); system = Some(SystemAction::Stop); } }); @@ -278,10 +279,10 @@ impl Phone { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { let Some(report) = report else { match state { - State::Starting => {ui.spinner(); ui.label("Starting VPN…");} + State::Starting => {ui.spinner(); ui.label("Starting Tsunagi Agent…");} _ => { - if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("VPN is stopped");} - if ui.button("Start VPN").clicked() {system = Some(SystemAction::Start);} + if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("Tsunagi Agent is stopped");} + if ui.button("Start Tsunagi Agent").clicked() {self.error = None; system = Some(SystemAction::Start);} } } return; diff --git a/crates/tsunagi-core/src/agent/mod.rs b/crates/tsunagi-core/src/agent/mod.rs index 55ae934..19c7c6a 100644 --- a/crates/tsunagi-core/src/agent/mod.rs +++ b/crates/tsunagi-core/src/agent/mod.rs @@ -1309,6 +1309,7 @@ impl Agent { .exit_via .and_then(|bytes| EndpointId::from_bytes(&bytes).ok()), exit_via_online: false, + exit_traffic: None, exit_rules: Default::default(), descriptor: keys.descriptor(), name: stored.name, diff --git a/crates/tsunagi-core/src/agent/network.rs b/crates/tsunagi-core/src/agent/network.rs index e4fece7..ed5b6d2 100644 --- a/crates/tsunagi-core/src/agent/network.rs +++ b/crates/tsunagi-core/src/agent/network.rs @@ -2810,6 +2810,7 @@ impl Runtime { exit_node, hostname: self.params.hostname.clone(), 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) { session.hostname = Some(announcement.hostname.clone()); + session + .agent_version + .clone_from(&announcement.agent_version); session.broadcast = announcement.broadcast; session.exit_node = announcement.exit_node; session.capabilities = capabilities.clone(); @@ -3260,6 +3264,7 @@ impl Runtime { exit_node: session.exit_node, endpoint_id: session.peer, role: session.role, + agent_version: session.agent_version.clone(), hostname: session .hostname .clone() @@ -3348,6 +3353,12 @@ impl Runtime { exit_offer: exit.offer, exit_via: exit.via, exit_via_online: exit.via.is_some_and(|via| self.exit_node_online(via)), + exit_traffic: self + .params + .interface + .as_ref() + .and(exit.via) + .and_then(|peer| self.params.routes.exit_traffic(self.network_id, peer)), exit_rules: self .params .interface diff --git a/crates/tsunagi-core/src/agent/session.rs b/crates/tsunagi-core/src/agent/session.rs index 79ebe0f..3010770 100644 --- a/crates/tsunagi-core/src/agent/session.rs +++ b/crates/tsunagi-core/src/agent/session.rs @@ -72,6 +72,7 @@ pub(crate) struct Session { /// number of control bytes it queues. pub(crate) outbound: mpsc::Sender>>, pub(crate) hostname: Option, + pub(crate) agent_version: Option, pub(crate) capabilities: Vec, pub(crate) broadcast: bool, /// The peer offers itself as an exit node in this network. @@ -228,6 +229,7 @@ pub(crate) fn spawn( conn, outbound: outbound_tx, hostname: None, + agent_version: None, capabilities: Vec::new(), broadcast: false, exit_node: false, diff --git a/crates/tsunagi-core/src/agent/status.rs b/crates/tsunagi-core/src/agent/status.rs index 4f6fad8..808ac9c 100644 --- a/crates/tsunagi-core/src/agent/status.rs +++ b/crates/tsunagi-core/src/agent/status.rs @@ -152,6 +152,8 @@ pub struct PeerStatus { /// /// A mutable binding, not an identity. pub hostname: Option, + /// Software version in the peer's latest authenticated announcement. + pub agent_version: Option, /// Protocols agreed with this peer: both sides have them at the same /// version. /// @@ -247,6 +249,8 @@ pub struct NetworkStatus { pub exit_via: Option, /// Whether that member is connected and still offering to be one. pub exit_via_online: bool, + /// IP byte totals since this exit route was selected. + pub exit_traffic: Option, /// What the host rules for the exit settings are doing. pub exit_rules: crate::overlay::ExitRulesReport, /// Immutable deterministic description of the network space. diff --git a/crates/tsunagi-core/src/config.rs b/crates/tsunagi-core/src/config.rs index 7981593..ea3c1c6 100644 --- a/crates/tsunagi-core/src/config.rs +++ b/crates/tsunagi-core/src/config.rs @@ -21,6 +21,9 @@ use crate::error::Result; #[cfg_attr(target_os = "macos", allow(dead_code))] const APP_NAME: &str = "tsunagi"; +/// Maximum length of the optional software release label in a peer announcement. +pub const MAX_AGENT_VERSION_LEN: usize = 64; + /// Rendezvous slots per network; this bounds a discovery sample, not membership. pub const DHT_SLOTS: u8 = 16; /// BEP44 permits 1000 bencoded bytes; a 996-byte string has a four-byte prefix. diff --git a/crates/tsunagi-core/src/ipc/mod.rs b/crates/tsunagi-core/src/ipc/mod.rs index 40c683d..72afa6e 100644 --- a/crates/tsunagi-core/src/ipc/mod.rs +++ b/crates/tsunagi-core/src/ipc/mod.rs @@ -830,6 +830,8 @@ pub struct MemberReport { /// One control plane peer. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct PeerReport { + /// The software version reported by this authenticated peer, when available. + pub agent_version: Option, /// Actionable carrier failure or policy mismatch; absent for a usable route. pub data_error: Option, /// The peer's endpoint id. @@ -893,6 +895,8 @@ pub struct RuleSetReport { /// One network's exit-node settings and what they are doing. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ExitReport { + /// IP bytes carried through this exit since selection, when locally observed. + pub traffic: Option, /// This agent offers itself as an exit node in this network. pub offering: bool, /// 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 /// 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. /// diff --git a/crates/tsunagi-core/src/overlay/exit.rs b/crates/tsunagi-core/src/overlay/exit.rs index 97ccd34..1b35c90 100644 --- a/crates/tsunagi-core/src/overlay/exit.rs +++ b/crates/tsunagi-core/src/overlay/exit.rs @@ -5,6 +5,15 @@ //! system sees. It is kept apart from the broadcast rules, which have a //! different lifetime and different tags. +/// Plaintext IP bytes carried through the client's currently selected internet exit. +#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ExitTraffic { + /// Bytes accepted by the carrier for off-mesh destinations. + pub tx_bytes: u64, + /// Internet reply bytes delivered to the local interface. + pub rx_bytes: u64, +} + /// How one set of host rules went. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RuleSetReport { diff --git a/crates/tsunagi-core/src/overlay/interface.rs b/crates/tsunagi-core/src/overlay/interface.rs index 2f7ed0d..f9168c8 100644 --- a/crates/tsunagi-core/src/overlay/interface.rs +++ b/crates/tsunagi-core/src/overlay/interface.rs @@ -320,11 +320,19 @@ impl Interface { tally.multicast.fetch_add(1, Ordering::Relaxed); continue; } - let Some(route) = routes.route_v4(destination) else { + let selected = match destination { + IpAddr::V4(address) => routes.packet_route(address), + IpAddr::V6(_) => None, + }; + let Some((route, exit)) = selected else { tally.note_unroutable(destination); continue; }; + let len = packet.len() as u64; if carrier.carry(route, packet) { + if let Some(exit) = exit { + exit.tx_bytes.fetch_add(len, Ordering::Relaxed); + } tally.sent.fetch_add(1, Ordering::Relaxed); } else { tally.undeliverable.fetch_add(1, Ordering::Relaxed); @@ -840,12 +848,14 @@ impl Interface { self.tally.wrong_source.fetch_add(1, Ordering::Relaxed); return Err(Rejected::WrongSource); }; - let broadcast = match (origin, header.destination()) { - (PacketSource::ExitReply { local: Some(local) }, IpAddr::V4(destination)) - if destination == local => - { - false - } + let (broadcast, exit) = match (origin, header.destination()) { + ( + PacketSource::ExitReply { + local: Some(local), + exit, + }, + IpAddr::V4(destination), + ) if destination == local => (false, Some(exit)), (PacketSource::Member, IpAddr::V4(destination)) if self.routes.is_broadcast(destination) => { @@ -855,13 +865,13 @@ impl Interface { self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed); return Err(Rejected::BroadcastDenied); } - true + (true, None) } (PacketSource::Member, IpAddr::V4(destination)) if self.routes.is_local_destination(network, destination) || self.routes.accepts_exit_traffic(network, destination) => { - false + (false, None) } _ => { self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed); @@ -887,7 +897,11 @@ impl Interface { crate::vip::router::Decision::Pass => packet, }; // Remote broadcasts terminate here. Only local TUN ingress can fan out. + let len = packet.len() as u64; if self.device.send(packet).await.is_ok() { + if let Some(exit) = exit { + exit.rx_bytes.fetch_add(len, Ordering::Relaxed); + } if broadcast { self.tally .broadcast_received @@ -926,18 +940,6 @@ impl Drop for Interface { } } -impl RoutingTable { - /// The route for a destination, when it is one the overlay carries. - fn route_v4(&self, destination: IpAddr) -> Option { - match destination { - IpAddr::V4(address) => self.route(address), - // The overlay is IPv4. An IPv6 packet has no owner here, and - // counting it as unroutable is the truth rather than a fault. - IpAddr::V6(_) => None, - } - } -} - /// Whether an address is one the overlay has nowhere to send. fn is_multicast_or_broadcast(address: IpAddr) -> bool { match address { @@ -1530,6 +1532,57 @@ mod tests { } } + #[tokio::test] + async fn exit_totals_count_only_accepted_internet_packets_for_the_current_choice() { + let (interface, device, routes, _, id) = interface(false).await; + let totals = |p| { + routes + .exit_traffic(id, peer(p)) + .map(|t| (t.tx_bytes, t.rx_bytes)) + }; + assert_eq!(totals(2), None); + routes.set_exit(id, using(peer(2))); + let outgoing = ipv4(addr(1), INTERNET, b"request"); + device.push_from_os(outgoing.clone()); + device.push_from_os(ipv4(addr(1), addr(2), b"ordinary mesh traffic")); + wait_for(&interface, |c| c.sent.saturating_sub(1)).await; + let incoming = ipv4(INTERNET, addr(1), b"reply"); + interface + .deliver(id, peer(2), incoming.clone()) + .await + .unwrap(); + interface + .deliver(id, peer(2), ipv4(addr(2), addr(1), b"mesh")) + .await + .unwrap(); + assert!( + interface + .deliver(id, peer(3), incoming.clone()) + .await + .is_err() + ); + assert!( + interface + .deliver(id, peer(2), ipv4(INTERNET, addr(3), b"wrong host")) + .await + .is_err() + ); + + routes.set_exit(id, using(peer(2))); + assert_eq!( + totals(2), + Some((outgoing.len() as u64, incoming.len() as u64)) + ); + routes.set_exit(id, using(peer(3))); + assert_eq!(totals(2), None); + assert_eq!(totals(3), Some((0, 0))); + routes.set_exit(id, ExitPolicy::default()); + assert_eq!(totals(3), None); + routes.set_exit(id, using(peer(2))); + assert_eq!(totals(2), Some((0, 0))); + interface.remove().await; + } + #[tokio::test] async fn internet_traffic_goes_to_the_exit_node_and_only_once_one_is_chosen() { let (interface, device, routes, carrier, id) = interface(false).await; diff --git a/crates/tsunagi-core/src/overlay/router.rs b/crates/tsunagi-core/src/overlay/router.rs index e74bb38..7a22aea 100644 --- a/crates/tsunagi-core/src/overlay/router.rs +++ b/crates/tsunagi-core/src/overlay/router.rs @@ -21,9 +21,11 @@ //! one is in use. use super::broadcast::{BroadcastPolicy, BroadcastTable}; -use arc_swap::ArcSwap; +use super::exit::ExitTraffic; +use arc_swap::{ArcSwap, ArcSwapOption}; use std::collections::HashMap; use std::net::Ipv4Addr; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, RwLock}; use iroh::EndpointId; @@ -43,7 +45,19 @@ pub struct Route { /// An internet source is valid only for a reply to our address in the exit's network. pub(super) enum PacketSource { Member, - ExitReply { local: Option }, + ExitReply { + local: Option, + exit: Arc, + }, +} + +/// A packet holds its selection until delivery finishes, even if the operator +/// switches to another exit in the meantime. +#[derive(Debug)] +pub(super) struct SelectedExit { + route: Route, + pub(super) tx_bytes: AtomicU64, + pub(super) rx_bytes: AtomicU64, } /// A network's exit-node settings, as far as packets are concerned. @@ -97,6 +111,7 @@ pub enum RouteError { pub struct RoutingTable { pub(crate) vips: Arc, broadcast: ArcSwap, + selected_exit: ArcSwapOption, networks: RwLock>, } @@ -171,6 +186,7 @@ impl RoutingTable { clear_other_exits(networks, network); } networks.insert(network, routes); + self.refresh_exit(networks); self.broadcast .store(Arc::new(BroadcastTable::build(networks))); Ok(()) @@ -181,6 +197,7 @@ impl RoutingTable { self.vips.remove_network(network); let mut networks = self.write(); networks.remove(&network); + self.refresh_exit(&networks); self.broadcast .store(Arc::new(BroadcastTable::build(&networks))); } @@ -213,9 +230,35 @@ impl RoutingTable { if routes.exit.via.is_some() { clear_other_exits(&mut networks, network); } + self.refresh_exit(&networks); } } + /// Publish the current choice under the same write lock as the route edits. + fn refresh_exit(&self, networks: &HashMap) { + 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 { + let current = self.selected_exit.load(); + let exit = current + .as_ref() + .filter(|e| e.route == Route { network, peer })?; + Some(ExitTraffic { + tx_bytes: exit.tx_bytes.load(Ordering::Relaxed), + rx_bytes: exit.rx_bytes.load(Ordering::Relaxed), + }) + } + /// Recognizes limited and configured subnet broadcasts before unicast lookup. pub fn is_broadcast(&self, destination: Ipv4Addr) -> bool { self.broadcast.load().is_destination(destination) @@ -249,6 +292,13 @@ impl RoutingTable { /// unicast destination, goes to this device's exit node when it has one: /// that is what sending *all* traffic through a member means. pub fn route(&self, destination: Ipv4Addr) -> Option { + self.packet_route(destination).map(|(route, _)| route) + } + + pub(super) fn packet_route( + &self, + destination: Ipv4Addr, + ) -> Option<(Route, Option>)> { let networks = self.read(); for (network, routes) in networks.iter() { if routes.local == Some(destination) { @@ -259,10 +309,13 @@ impl RoutingTable { .iter() .find(|(address, _)| *address == destination) { - return Some(Route { - network: *network, - peer: *peer, - }); + return Some(( + Route { + network: *network, + peer: *peer, + }, + None, + )); } } // Inside an overlay range, an unowned address is nobody's, not the @@ -270,7 +323,8 @@ impl RoutingTable { if !is_internet_destination(destination) || in_any_range(&networks, destination) { return None; } - exit_via(&networks).map(|(network, peer)| Route { network, peer }) + let exit = self.selected_exit.load_full()?; + Some((exit.route, Some(exit))) } /// Whether a peer may send from a source address. @@ -298,11 +352,14 @@ impl RoutingTable { { return Some(PacketSource::Member); } - (exit_via(&networks) == Some((network, peer)) + let current = self.selected_exit.load(); + let exit = current.as_ref()?; + (exit.route == Route { network, peer } && is_internet_destination(source) && !in_any_range(&networks, source)) - .then_some(PacketSource::ExitReply { + .then(|| PacketSource::ExitReply { local: routes.local, + exit: Arc::clone(exit), }) } diff --git a/crates/tsunagi-core/src/proto/message.rs b/crates/tsunagi-core/src/proto/message.rs index 9cd983c..7582d01 100644 --- a/crates/tsunagi-core/src/proto/message.rs +++ b/crates/tsunagi-core/src/proto/message.rs @@ -90,6 +90,23 @@ pub struct Announcement { pub hostname: String, /// Announced IP plugin capabilities. Opaque to the core. pub capabilities: Vec, + /// 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, +} + +fn read_agent_version<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + // A frame contains exactly one envelope. EOF here is a legacy announcement. + // An unreadable display hint can also be discarded without losing the + // hostname or capabilities. Borrow the frame until the label is bounded. + let version = Option::<&str>::deserialize(d).ok().flatten().filter(|s| { + !s.is_empty() + && s.len() <= crate::config::MAX_AGENT_VERSION_LEN + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-')) + }); + Ok(version.map(str::to_owned)) } /// Opens a data channel, sent by the initiator right after the membership @@ -395,3 +412,41 @@ pub fn kind(message: &ControlMessage) -> &'static str { ControlMessage::Bye { .. } => "bye", } } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::panic)] + use super::*; + + #[test] + fn v8_announcements_interoperate_with_and_without_a_software_version() { + // The original v8 frame ends with the capability list. Decode the + // new frame using exactly those fields as an older receiver would. + type OldFrame = ([u8; 32], u8, bool, bool, String, Vec); + let old: OldFrame = ([7; 32], 1, true, false, "lab".into(), vec![]); + let legacy = encode(&old).unwrap(); + assert!(decode::(&legacy[..legacy.len() - 1]).is_err()); + let read = |bytes: &[u8]| match decode::(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::(&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"); + } + } +} diff --git a/crates/tsunagi-core/tests/multi_peer.rs b/crates/tsunagi-core/tests/multi_peer.rs index 3175b23..fae598c 100644 --- a/crates/tsunagi-core/tests/multi_peer.rs +++ b/crates/tsunagi-core/tests/multi_peer.rs @@ -43,15 +43,19 @@ async fn four_agents_form_a_mesh_and_exchange_distinguishable_messages() { // A peer counts as connected as soon as its session is authenticated, which // can be a round before its announcement carrying the hostname arrives, so // this waits for the hostnames rather than reading them straight away. - let hostnames: HashSet = wait_until("three distinct peer hostnames", || async { - let status = agents[0].agent.network_status(network_id).await.ok()?; - let hostnames: HashSet = status - .peers - .iter() - .filter_map(|peer| peer.hostname.clone()) - .collect(); - (hostnames.len() >= 3).then_some(hostnames) - }) + let hostnames: HashSet = wait_until( + "three peers announce their hostname and release", + || async { + let status = agents[0].agent.network_status(network_id).await.ok()?; + let hostnames: HashSet = status + .peers + .iter() + .filter(|peer| peer.agent_version.as_deref() == Some(env!("CARGO_PKG_VERSION"))) + .filter_map(|peer| peer.hostname.clone()) + .collect(); + (hostnames.len() >= 3).then_some(hostnames) + }, + ) .await; assert_eq!( hostnames.len(), diff --git a/crates/tsunagi-runtime/src/report.rs b/crates/tsunagi-runtime/src/report.rs index 19849a1..0050b44 100644 --- a/crates/tsunagi-runtime/src/report.rs +++ b/crates/tsunagi-runtime/src/report.rs @@ -102,6 +102,7 @@ pub fn networks( .peers .iter() .map(|peer| PeerReport { + agent_version: peer.agent_version.clone(), data_error: peer.data_error.clone(), endpoint_id: peer.endpoint_id.to_string(), hostname: peer.hostname.clone(), @@ -193,6 +194,7 @@ fn exit_report(network: &tsunagi::agent::NetworkStatus) -> tsunagi::ipc::ExitRep }) }; tsunagi::ipc::ExitReport { + traffic: network.exit_traffic, offering: network.exit_offer, offer_rules: rules(&network.exit_rules.offer), forwarding: network.exit_rules.forwarding, diff --git a/crates/tsunagi-tray/src/app.rs b/crates/tsunagi-tray/src/app.rs index 1789f35..a2bfa75 100644 --- a/crates/tsunagi-tray/src/app.rs +++ b/crates/tsunagi-tray/src/app.rs @@ -162,8 +162,8 @@ impl App { .with_title(devices::title(network)) .with_app_id(crate::icon::APP_ID) .with_icon(crate::icon::window()) - .with_inner_size([1440.0, 640.0]) - .with_min_inner_size([800.0, 400.0]); + .with_inner_size([1000.0, 640.0]) + .with_min_inner_size([560.0, 400.0]); let agent = &self.agent; let traffic = &self.traffic; // The window shares the single unit setting, so its toggle and the diff --git a/crates/tsunagi-ui/fonts/OFL.txt b/crates/tsunagi-ui/fonts/OFL.txt new file mode 100644 index 0000000..19ddde7 --- /dev/null +++ b/crates/tsunagi-ui/fonts/OFL.txt @@ -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. diff --git a/crates/tsunagi-ui/fonts/SourceSansPro-Bold.ttf b/crates/tsunagi-ui/fonts/SourceSansPro-Bold.ttf new file mode 100644 index 0000000..f698646 Binary files /dev/null and b/crates/tsunagi-ui/fonts/SourceSansPro-Bold.ttf differ diff --git a/crates/tsunagi-ui/src/about.rs b/crates/tsunagi-ui/src/about.rs index 2a4026c..b8fd218 100644 --- a/crates/tsunagi-ui/src/about.rs +++ b/crates/tsunagi-ui/src/about.rs @@ -141,7 +141,7 @@ fn agent_table(ui: &mut egui::Ui, socket: Option<&str>, report: &StatusReport) { ui.label(if socket.is_some() { "can be managed (CAP_NET_ADMIN)" } else { - "Android VPN service" + "Android foreground service" }); } PrivilegeReport::Missing(_) => { diff --git a/crates/tsunagi-ui/src/devices.rs b/crates/tsunagi-ui/src/devices.rs index d14d74a..cb9898d 100644 --- a/crates/tsunagi-ui/src/devices.rs +++ b/crates/tsunagi-ui/src/devices.rs @@ -44,6 +44,7 @@ struct Device<'a> { name_taken: Option<(&'a str, String)>, /// The last hostname seen for it, kept while it is offline. hostname: Option<&'a str>, + agent_version: Option<&'a str>, /// What clicking the hostname copies: `hostname.network`, so it resolves. copy: Option, /// The full endpoint id, which clicking the short form copies. @@ -104,6 +105,11 @@ impl Device<'_> { fn sort_key(&self) -> String { self.hostname.unwrap_or(self.id).to_lowercase() } + + fn version_label(&self) -> String { + self.agent_version + .map_or_else(|| "v?".into(), |v| format!("v{}", format::short(v))) + } } /// The first characters of an endpoint id, enough to tell devices apart. @@ -122,6 +128,11 @@ fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) { } _ => format::copy_field(ui, &short_id(device.id), device.id), } + ui.label(egui::RichText::new(device.version_label()).small().weak()) + .on_hover_text(format!( + "Tsunagi {}", + device.agent_version.unwrap_or("version unknown") + )); if let Some((name, holder)) = &device.name_taken { ui.label(egui::RichText::new(egui_phosphor::regular::WARNING).color(AMBER)) .on_hover_text(format!( @@ -170,23 +181,23 @@ pub fn show( }); return; } - summary(ui, network); - ui.add_space(6.0); - - ui.label(egui::RichText::new("traffic").strong()); - format::sparkline(ui, traffic.network(&network.network_id), unit, 48.0); - ui.add_space(8.0); - let devices = devices(network, own_id); let online = devices.iter().filter(|d| d.online).count(); - ui.label( - egui::RichText::new(format!( - "devices ({} online / {} known)", - online, + ui.columns(2, |columns| { + columns[0].strong(format!( + "devices ({online} online / {} known)", devices.len() - )) - .strong(), - ); + )); + columns[0].collapsing("Network details", |ui| summary(ui, network)); + let plot = &mut columns[1]; + plot.label("Network traffic"); + let width = plot.available_width().min(440.0); + plot.scope(|ui| { + ui.set_max_width(width); + format::sparkline(ui, traffic.network(&network.network_id), unit, 48.0); + }); + }); + ui.add_space(8.0); egui::ScrollArea::both() .auto_shrink([false, false]) .show(ui, |ui| { @@ -335,7 +346,9 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) { .spacing([12.0, 3.0]) .show(ui, |ui| { 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) } else { network.network_id.clone() @@ -460,6 +473,7 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec> { via_name, name_taken, hostname, + agent_version: peer.and_then(|p| p.agent_version.as_deref()), copy: hostname.map(|h| format!("{h}.{}", network.name)), id, data_error: peer.and_then(|p| p.data_error.as_deref()), @@ -484,44 +498,55 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec> { devices } -const COLUMN_HEADERS: [&str; 10] = [ - "device", - "exit", - "data", - "RTT data / control", - "address", - "data path", - "pkts", - "bytes", - "rate", - "plot", -]; +fn column_headers(unit: Unit) -> [&'static str; 9] { + [ + "device", + "exit", + "data", + "RTT data / control", + "address", + "data path", + match unit { + Unit::Bytes => "bytes (TX / RX)", + Unit::Packets => "pkts (TX / RX)", + }, + "rate", + "plot", + ] +} /// Initial column floors; actual headers, values and totals can grow them. -const COLUMN_SAMPLES: [&str; 10] = [ +const COLUMN_SAMPLES: [&str; 9] = [ "device", "exit", "data", "9999 ms", "255.255.255.255", "data path", - "99999/99999", "1023.9 MB / 1023.9 MB", "1023.9 kB/s", "plot", ]; +fn traffic_pair(tx: u64, rx: u64, unit: Unit) -> String { + format!( + "{} / {}", + format::amount(tx, unit), + format::amount(rx, unit) + ) +} + /// Column widths that only ever grow, kept across frames. /// /// Live values can change width between frames. A value that /// gets shorter — `14.4 MB/s` giving way to `382 pkt/s` — would pull the /// column in and push every cell after it. Remembering the widest seen keeps /// the table where it is. -fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 10] { - let stored: Option<[f32; 10]> = ui.memory(|m| m.data.get_temp(id)); +fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 9] { + let stored: Option<[f32; 9]> = ui.memory(|m| m.data.get_temp(id)); stored.unwrap_or_else(|| { let font = egui::FontSelection::Default.resolve(ui.style()); - let mut widths = [0.0; 10]; + let mut widths = [0.0; 9]; for (width, sample) in widths.iter_mut().zip(COLUMN_SAMPLES) { if !sample.is_empty() { *width = ui.fonts(|fonts| { @@ -536,10 +561,9 @@ fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 10] { }) } -fn stretch_columns(mut widths: [f32; 10], available: f32) -> [f32; 10] { - let gaps = 10.0 * (widths.len() - 1) as f32; - widths[9] = widths[9].max(100.0); - widths[9] += (available - gaps - widths.iter().sum::()).max(0.0); +fn stretch_columns(mut widths: [f32; 9], available: f32) -> [f32; 9] { + let gaps = crate::table::GAP * (widths.len() - 1) as f32; + widths[8] = (available - gaps - widths[..8].iter().sum::()).clamp(100.0, 180.0); widths } @@ -618,16 +642,17 @@ fn device_table( .x }) }; - for (column, header) in COLUMN_HEADERS.into_iter().enumerate() { - widths[column] = widths[column].max(measure(header.to_owned())); + let headers = column_headers(unit); + for (column, header) in headers.iter().enumerate() { + widths[column] = widths[column].max(measure((*header).to_owned())); } - let (mut tx_packets, mut rx_packets, mut tx_bytes, mut rx_bytes): (u64, u64, u64, u64) = - (0, 0, 0, 0); + let (mut tx_total, mut rx_total) = (0_u64, 0_u64); for device in devices { let name = format!( - "{} ({}){}", + "{} ({}) {}{}", device.name(), short_id(device.id), + device.version_label(), if !device.online { " Forget" } else { "" } ); widths[0] = widths[0].max(measure(name) + 24.0); @@ -641,59 +666,36 @@ fn device_table( widths[column] = widths[column].max(measure(text)); } if let Some(peer) = device.overlay { - tx_packets = tx_packets.saturating_add(peer.tx_packets); - rx_packets = rx_packets.saturating_add(peer.rx_packets); - tx_bytes = tx_bytes.saturating_add(peer.tx_bytes); - rx_bytes = rx_bytes.saturating_add(peer.rx_bytes); - for (column, text) in [ - (6, format!("{}/{}", peer.tx_packets, peer.rx_packets)), - ( - 7, - format!( - "{} / {}", - format::bytes(peer.tx_bytes as f64), - format::bytes(peer.rx_bytes as f64) - ), - ), - ( - 8, - format::series_rate(traffic.peer(network_id, &peer.public_key), unit), - ), - ] { - widths[column] = widths[column].max(measure(text)); - } + let (tx, rx) = unit.counters(peer); + tx_total = tx_total.saturating_add(tx); + rx_total = rx_total.saturating_add(rx); + widths[6] = widths[6].max(measure(traffic_pair(tx, rx, unit))); + widths[7] = widths[7].max(measure(format::series_rate( + traffic.peer(network_id, &peer.public_key), + unit, + ))); } } - for (column, text) in [ - (6, format!("{tx_packets}/{rx_packets}")), - ( - 7, - format!( - "{} / {}", - format::bytes(tx_bytes as f64), - format::bytes(rx_bytes as f64) - ), - ), - (8, format::series_rate(traffic.network(network_id), unit)), - ] { - widths[column] = widths[column].max(measure(text)); - } + let total = traffic_pair(tx_total, rx_total, unit); + let rate = format::series_rate(traffic.network(network_id), unit); + widths[6] = widths[6].max(measure(total.clone())); + widths[7] = widths[7].max(measure(rate.clone())); if widths != previous_widths { ui.ctx().request_repaint(); } ui.memory_mut(|m| m.data.insert_temp(widths_id, widths)); let widths = stretch_columns(widths, ui.available_width()); crate::table::row(ui, "device headers", &widths, false, |column, ui| { - let response = ui.weak(COLUMN_HEADERS[column]); + let response = ui.weak(headers[column]); match column { 2 => { response.on_hover_text("Encrypted data channel readiness."); } 3 => { - response.on_hover_text("Control-connection round-trip time."); + response.on_hover_text("Data-link and control-connection round-trip times."); } - 7 => { - response.on_hover_text("Plaintext IP bytes accepted by the encrypted channel in this counter lifetime; excludes relay transit, transport overhead and delivery probes."); + 6 => { + response.on_hover_text("Sent / received IP traffic in the selected unit. Excludes relay transit and transport overhead."); } 5 => { response.on_hover_text("External data transport or relay route."); @@ -731,16 +733,10 @@ fn device_table( let series = traffic.peer(network_id, &peer.public_key); match column { 6 => { - ui.label(format!("{}/{}", peer.tx_packets, peer.rx_packets)); + let (tx, rx) = unit.counters(peer); + ui.label(traffic_pair(tx, rx, unit)); } 7 => { - ui.label(format!( - "{} / {}", - format::bytes(peer.tx_bytes as f64), - format::bytes(peer.rx_bytes as f64) - )); - } - 8 => { ui.label(format::series_rate(series, unit)); } _ => format::sparkline(ui, series, unit, 24.0), @@ -762,17 +758,10 @@ fn device_table( ui.strong("total"); } 6 => { - ui.strong(format!("{tx_packets}/{rx_packets}")); + ui.strong(&total); } 7 => { - ui.strong(format!( - "{} / {}", - format::bytes(tx_bytes as f64), - format::bytes(rx_bytes as f64) - )); - } - 8 => { - ui.strong(format::series_rate(traffic.network(network_id), unit)); + ui.strong(&rate); } _ => {} }, @@ -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] fn phone_roster_fits_each_width_and_expands_only_the_tapped_member() { - struct ReadOnly; - impl Client for ReadOnly { - fn send(&self, _: Command) { - panic!("reading a row issued an action"); - } - fn busy(&self) -> bool { - false - } - } let mut network = NetworkReport { network_id: "a".repeat(60), name: "lab".into(), @@ -933,9 +923,24 @@ mod tests { m.overlay_address_v4 = Some(format!("192.168.254.{}", 240 + i)); network.members.push(m); } + network.peers.push(tsunagi::ipc::PeerReport { + endpoint_id: "alpha".into(), + agent_version: Some("2.0.0-rc.1".into()), + ..Default::default() + }); + network.overlay = Some(tsunagi::ipc::OverlayReport { + peers: vec![OverlayPeerReport { + endpoint_id: "alpha".into(), + tx_bytes: 1024, + rx_bytes: 512, + ..Default::default() + }], + ..Default::default() + }); for width in [320.0, 360.0, 430.0, 870.0] { let ctx = egui::Context::default(); ctx.set_os(egui::os::OperatingSystem::Android); + ctx.set_fonts(crate::app_fonts()); let frame = |events| { ctx.run( egui::RawInput { @@ -950,7 +955,7 @@ mod tests { show( ctx, &ReadOnly, - &mut Unit::Packets, + &mut Unit::Bytes, (&mut None, &mut None), &network, "self", @@ -999,8 +1004,22 @@ mod tests { }; let expanded = click(a); assert_eq!(positions(&expanded, "Endpoint ID").len(), 1); + assert_eq!(positions(&expanded, "2.0.0-rc.1").len(), 1); + let up = positions(&expanded, "1.0 kB")[0]; + let down = positions(&expanded, "512 B")[0]; + assert!(down.x - up.x > width * 0.25 && (up.y - down.y).abs() < 2.0); + for (arrow, caption, value) in [ + (icon::ARROW_UP, "Sent", up), + (icon::ARROW_DOWN, "Received", down), + ] { + let arrow = positions(&expanded, arrow)[0]; + let caption = positions(&expanded, caption)[0]; + assert!(arrow.x < caption.x && arrow.y < value.y); + assert!((arrow.x - value.x).abs() < 35.0); + } let switched = click(positions(&expanded, "bravo")[0]); assert_eq!(positions(&switched, "Endpoint ID").len(), 1); + assert_eq!(positions(&switched, "Unknown").len(), 1); let closed = click(positions(&switched, "bravo")[0]); assert!(positions(&closed, "Endpoint ID").is_empty()); } @@ -1133,11 +1152,11 @@ mod tests { } #[test] - fn resized_table_fills_the_window_without_growing_fixed_columns() { - let minimum = [100.0; 10]; + fn wider_windows_keep_a_compact_plot_and_narrow_windows_preserve_column_floors() { + let minimum = [100.0; 9]; let wide = stretch_columns(minimum, 1440.0); - assert!((wide.iter().sum::() + 90.0 - 1440.0).abs() < 0.1); - assert_eq!(&wide[..9], &minimum[..9]); + assert!((100.0..=190.0).contains(&wide[8])); + assert_eq!(&wide[..8], &minimum[..8]); let narrow = stretch_columns(minimum, 800.0); assert_eq!( narrow, minimum, @@ -1148,6 +1167,39 @@ mod tests { wide, "a resize does not accumulate padding" ); + + let ctx = egui::Context::default(); + for window_width in [800.0, 1000.0, 1440.0] { + let frame = ctx.run( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(window_width, 640.0), + )), + ..Default::default() + }, + |ctx| { + show( + ctx, + &ReadOnly, + &mut Unit::Bytes, + (&mut None, &mut None), + &NetworkReport::default(), + "self", + &Traffic::default(), + ); + }, + ); + let chart = frame + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Rect(r) if r.rect.height() == 48.0 => Some(r.rect), + _ => None, + }) + .expect("network traffic chart"); + assert!((300.0..=440.0).contains(&chart.width()), "{chart:?}"); + } } #[test] @@ -1168,18 +1220,19 @@ mod tests { } let context = egui::Context::default(); - for (width, packets, age) in [ - (1600.0, 1569, 56), - (1600.0, 55_555, 172_800), - (1600.0, 137_245, 172_800), - (900.0, 9_876_543_210, 172_800), - (1600.0, 42, 56), + for (width, packets, age, unit) in [ + (1600.0, 1569, 56, crate::home::UiState::default().unit), + (1600.0, 55_555, 172_800, Unit::Packets), + (1600.0, 137_245, 172_800, Unit::Bytes), + (900.0, 9_876_543_210, 172_800, Unit::Packets), + (1600.0, 42, 56, Unit::Bytes), ] { let network = NetworkReport { network_id: "network".into(), peers: ["peer", "other"] .into_iter() .map(|id| PeerReport { + agent_version: (id == "peer").then(|| "2.0.0-rc.1".into()), data_error: None, endpoint_id: id.into(), rtt_ms: Some(12_345), @@ -1220,7 +1273,7 @@ mod tests { ui.allocate_ui(egui::vec2(width, 480.0), |ui| { device_table( ui, - Unit::Packets, + unit, &network, &rows, &Traffic::default(), @@ -1234,11 +1287,36 @@ mod tests { let shapes: Vec<_> = output.shapes.into_iter().map(|s| s.shape).collect(); let mut texts = Vec::new(); collect_text(&shapes, &mut texts); + let visible = |value: &str| texts.iter().any(|t| t.galley.text() == value); + assert!(visible("v2.0.0-rc.1")); + assert!(visible("v?")); + let packet_counts = format!("{packets} / {}", packets + 1); + let byte_counts = "117.7 MB / 941.9 MB"; + if packets == 1569 { + assert!(visible("bytes (TX / RX)")); + assert!(visible(byte_counts)); + } + assert_eq!(visible(&packet_counts), unit == Unit::Packets); + assert_eq!(visible(byte_counts), unit == Unit::Bytes); for (label, next_column) in [ ("RTT data / control".to_string(), "address"), (rtt_pair(&rows[0]), "address"), - (format!("{packets}/{}", packets + 1), "bytes"), - (format!("{}/{}", packets * 2, (packets + 1) * 2), "bytes"), + ( + if unit == Unit::Packets { + packet_counts + } else { + byte_counts.into() + }, + "rate", + ), + ( + if unit == Unit::Packets { + format!("{} / {}", packets * 2, (packets + 1) * 2) + } else { + "235.5 MB / 1.8 GB".into() + }, + "rate", + ), ] { let right = texts .iter() @@ -1403,7 +1481,7 @@ mod tests { &mut None, &mut None, ); - let stored: [f32; 10] = ui + let stored: [f32; 9] = ui .memory(|memory| { memory .data diff --git a/crates/tsunagi-ui/src/devices/compact.rs b/crates/tsunagi-ui/src/devices/compact.rs index 3745ba1..7217e4b 100644 --- a/crates/tsunagi-ui/src/devices/compact.rs +++ b/crates/tsunagi-ui/src/devices/compact.rs @@ -130,74 +130,102 @@ fn details( exit: &mut Option, forget: &mut Option, ) { - ui.horizontal_wrapped(|ui| { - ui.weak(if member.online { "online" } else { "offline" }); - if let Some(name) = &member.copy { - format::copy_field(ui, &member.name(), name); - } - if let Some(address) = &member.address { - format::copy_field(ui, address, address); - } - }); - ui.horizontal_wrapped(|ui| { - ui.weak("Endpoint ID"); - format::copy_field(ui, &format::short(member.id), member.id); - }); - let (path, _) = data_path_text(member.path, member.via_name.as_deref(), member.online); - ui.horizontal_wrapped(|ui| { - ui.label(path); - tunnel_cell(ui, member); - }); - if member.online { - if let Some(path) = member.data_transport_detail { - ui.label(path); - } - ui.label(format!( - "Data RTT {} · Control RTT {}", - rtt_text(member.data_rtt_ms), - rtt_text(member.control_rtt_ms) - )); - } - if let Some(error) = member.data_error { - ui.colored_label(AMBER, error); - } - if let Some((taken, holder)) = &member.name_taken { - ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}.")); - } - if let Some(peer) = member.overlay { - let series = traffic.peer(&network.network_id, &peer.public_key); - ui.horizontal_wrapped(|ui| { - ui.label(format!( - "TX {} · {} pkts", - format::bytes(peer.tx_bytes as f64), - peer.tx_packets - )); - ui.label(format!( - "RX {} · {} pkts", - format::bytes(peer.rx_bytes as f64), - peer.rx_packets - )); - ui.weak(format::series_rate(series, unit)); + egui::Frame::new() + .fill(ui.visuals().faint_bg_color) + .inner_margin(egui::Margin::symmetric(10, 8)) + .show(ui, |ui| { + ui.set_min_width(ui.available_width()); + ui.spacing_mut().item_spacing.y = 4.0; + ui.columns(2, |cols| { + cols[0].small("Data path"); + let (path, _) = + data_path_text(member.path, member.via_name.as_deref(), member.online); + cols[0].horizontal_wrapped(|ui| { + ui.label(path); + if member.online { + tunnel_cell(ui, member); + } + }); + cols[1].small("Tsunagi version"); + cols[1].label(member.agent_version.unwrap_or("Unknown")); + }); + if let Some(path) = member.data_transport_detail { + ui.add(egui::Label::new(path).wrap()); + } + if member.online { + ui.columns(2, |cols| { + cols[0].small("Data RTT"); + cols[0].label(rtt_text(member.data_rtt_ms)); + cols[1].small("Control RTT"); + cols[1].label(rtt_text(member.control_rtt_ms)); + }); + } + if let Some(peer) = member.overlay.filter(|_| member.online) { + ui.separator(); + let (tx, rx) = unit.counters(peer); + let sent_color = ui.visuals().hyperlink_color; + ui.columns(2, |cols| { + for (col, arrow, caption, count, color) in [ + (0, icon::ARROW_UP, "Sent", tx, sent_color), + (1, icon::ARROW_DOWN, "Received", rx, exit::GOOD), + ] { + cols[col].horizontal(|ui| { + ui.colored_label(color, arrow); + ui.label(caption); + }); + let value = format::amount(count, unit); + let value = match unit { + Unit::Packets => format!("{value} pkts"), + Unit::Bytes => value, + }; + let size = cols[col].text_style_height(&egui::TextStyle::Body) + 2.0; + cols[col].label(egui::RichText::new(value).size(size).strong()); + } + }); + format::sparkline( + ui, + traffic.peer(&network.network_id, &peer.public_key), + unit, + 28.0, + ); + } + ui.separator(); + ui.columns(2, |cols| { + cols[0].small("Endpoint ID"); + format::copy_field(&mut cols[0], &format::short(member.id), member.id); + cols[1].small("IPv4"); + if let Some(address) = &member.address { + format::copy_field(&mut cols[1], address, address); + } else { + cols[1].weak("—"); + } + }); + if let Some(name) = &member.copy { + format::copy_field(ui, name, name); + } + if let Some(error) = member.data_error { + ui.colored_label(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(); } diff --git a/crates/tsunagi-ui/src/format.rs b/crates/tsunagi-ui/src/format.rs index cdcf8e5..a2731dc 100644 --- a/crates/tsunagi-ui/src/format.rs +++ b/crates/tsunagi-ui/src/format.rs @@ -38,6 +38,14 @@ pub fn bytes(n: f64) -> String { } } +/// A cumulative amount in the selected unit. +pub(crate) fn amount(value: u64, unit: Unit) -> String { + match unit { + Unit::Bytes => bytes(value as f64), + Unit::Packets => value.to_string(), + } +} + /// A rate in the chosen unit, per second. pub fn rate(value: f32, unit: Unit) -> String { match unit { diff --git a/crates/tsunagi-ui/src/home.rs b/crates/tsunagi-ui/src/home.rs index 834ed6a..54c28e5 100644 --- a/crates/tsunagi-ui/src/home.rs +++ b/crates/tsunagi-ui/src/home.rs @@ -28,6 +28,8 @@ pub struct UiState { pub join: JoinForm, /// Whether rates and sparklines are shown in packets or bytes. pub unit: Unit, + /// Network details opened during this run, keyed by identity even for namesakes. + expanded_networks: BTreeSet, /// An in-progress hostname edit (`None` when not editing). pub host_edit: Option, /// Network ids whose devices window is open. @@ -46,7 +48,8 @@ impl Default for UiState { fn default() -> Self { Self { join: JoinForm::default(), - unit: Unit::Packets, + unit: Unit::Bytes, + expanded_networks: BTreeSet::new(), host_edit: None, open_devices: BTreeSet::new(), vip_windows: Default::default(), @@ -121,97 +124,153 @@ pub fn draw_network( offer_exit: bool, ) -> bool { let mut pick_exit = false; - ui.add_space(6.0); - egui::Frame::group(ui.style()).show(ui, |ui| { - ui.horizontal(|ui| { - format::copy_field(ui, network.name.as_str(), &network.name); - if ui.button("VIP").clicked(){state.vip_windows.entry(network.network_id.clone()).or_default();} - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let leave = - egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE)) - .fill(LEAVE_RED); - if ui.add(leave).clicked() { - agent.send(Command::Leave { + ui.add_space(5.0); + ui.push_id(&network.network_id, |ui| { + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + let mut open = state.expanded_networks.contains(&network.network_id); + let status = if network.active { + format!( + "{} online", + devices::online_count(network, &report.endpoint_id) + ) + } 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(), }); } + 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()); - let series = traffic.network(&network.network_id); - - egui::Grid::new(("net", &network.network_id)) - .num_columns(2) - .spacing([10.0, 3.0]) - .show(ui, |ui| { - ui.weak("id"); - format::copy_field(ui, &format::short(&network.network_id), &network.network_id); +fn draw_metadata(ui: &mut egui::Ui, network: &NetworkReport, own_id: &str) { + egui::Grid::new(ui.id().with("metadata")) + .num_columns(2) + .spacing([10.0, 3.0]) + .show(ui, |ui| { + ui.weak("name"); + format::copy_field(ui, &network.name, &network.name); + ui.end_row(); + ui.weak("id"); + format::copy_field(ui, &format::short(&network.network_id), &network.network_id); + ui.end_row(); + if let Some(range) = &network.range { + ui.weak("range"); + format::copy_field(ui, range, range); ui.end_row(); - - if let Some(range) = &network.range { - ui.weak("range"); - format::copy_field(ui, range, range); - ui.end_row(); - } - if let Some(address) = address { - ui.weak("addr"); - format::copy_field(ui, address, address); - ui.end_row(); - } - ui.weak("peers"); - ui.label(format!( - "{} online · {} known", - devices::online_count(network, &report.endpoint_id), - devices::known_count(network, &report.endpoint_id) - )); - ui.end_row(); - }); - - draw_protocols(ui, agent, network, &report.available_protocols); - - format::sparkline(ui, series, state.unit, 34.0); - - if !network.range_conflicts.is_empty() { - ui.colored_label(BAD, "Stopped: overlapping network ranges"); - for conflict in &network.range_conflicts { - ui.label(format!("{} ({}) uses {}", conflict.name, conflict.network_id, conflict.range)); } - ui.label("Switching suspends these networks until this network stops, then resumes them automatically."); - if network.auto_start { ui.weak("This network will resume automatically when its range is free."); } + if let Some(address) = network.overlay.as_ref().and_then(|o| o.address.as_ref()) { + 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| { - if !network.active && !network.range_conflicts.is_empty() { - if ui.button("Switch to this network").clicked() { - agent.send(Command::SetActive { network_id: network.network_id.clone(), active: true }); - } - if network.auto_start && ui.button("Keep stopped").clicked() { - agent.send(Command::SetActive { network_id: network.network_id.clone(), active: false }); - } - } else { - let mut active = network.active; - if ui.checkbox(&mut active, "active").changed() { - agent.send(Command::SetActive { - network_id: network.network_id.clone(), - active, - }); - } - } - let mut broadcast = network.broadcast; - if ui.checkbox(&mut broadcast, "broadcast").changed() { - agent.send(Command::SetBroadcast { + ui.label("Switching suspends these networks until this network stops, then resumes them automatically."); + if network.auto_start { + ui.weak("This network will resume automatically when its range is free."); + } + } + ui.horizontal_wrapped(|ui| { + if !network.active && !network.range_conflicts.is_empty() { + if ui.button("Switch to this network").clicked() { + agent.send(Command::SetActive { network_id: network.network_id.clone(), - enabled: broadcast, + active: true, }); } - if !offer_exit && ui.button("Exit node…").clicked() { pick_exit = true; } + if network.auto_start && ui.button("Keep stopped").clicked() { + agent.send(Command::SetActive { + network_id: network.network_id.clone(), + active: false, + }); + } + } else { + let mut active = network.active; + if ui.checkbox(&mut active, "active").changed() { + agent.send(Command::SetActive { + network_id: network.network_id.clone(), + active, + }); + } + } + let mut broadcast = network.broadcast; + if ui.checkbox(&mut broadcast, "broadcast").changed() { + agent.send(Command::SetBroadcast { + network_id: network.network_id.clone(), + enabled: broadcast, + }); + } + if offer_exit { let mut offering = network.exit.offering; - if offer_exit && ui + if ui .checkbox(&mut offering, "exit node") - .on_hover_text( - "let other members send all their internet traffic through this \ - device, which can see it", - ) + .on_hover_text("Let members send all their internet traffic through this device, which can see it.") .changed() { agent.send(Command::SetExitOffer { @@ -219,54 +278,109 @@ pub fn draw_network( enabled: offering, }); } - }); - ui.horizontal(|ui| { - // In the bottom left corner while this device sends its traffic through - // somebody: green while that works, red while it does not. - if let Some(via) = &network.exit.via { - let color = if network.exit.via_online { - exit::GOOD - } else { - exit::LOUD - }; - let response = ui - .add( - egui::Label::new( - egui::RichText::new(icon::SIGN_OUT).size(18.0).color(color), - ) - .sense(egui::Sense::click()), - ) - .on_hover_cursor(egui::CursorIcon::PointingHand) - .on_hover_text(format!( - "exit node: {} — click to stop", - exit::name_of(network, via) - )); - if response.clicked() { - state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via)); - } - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button("Show devices").clicked() { - state.open_devices.insert(network.network_id.clone()); - } - if ui - .button(format!("{} Copy secret", icon::COPY)) - .on_hover_text("copy this network's secret to the clipboard") - .clicked() - { - agent.send(Command::CopySecret { - network_id: network.network_id.clone(), - }); - } + } else { + pick_exit = ui.button("Exit node…").clicked(); + } + let leave = egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE)) + .fill(LEAVE_RED); + if ui.add(leave).clicked() { + agent.send(Command::Leave { + network_id: network.network_id.clone(), }); - }); - for warning in exit::warnings(network) { - draw_exit_warning(ui, &warning); } }); pick_exit } +fn network_header(ui: &mut egui::Ui, name: &str, status: &str, open: bool) -> egui::Response { + let height = ui.text_style_height(&egui::TextStyle::Heading).max(30.0); + let (rect, response) = ui.allocate_exact_size( + egui::vec2(ui.available_width(), height), + egui::Sense::click(), + ); + response.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::CollapsingHeader, ui.is_enabled(), name) + }); + let visuals = ui.style().interact(&response); + if response.hovered() || response.has_focus() { + ui.painter().rect_filled(rect, 3.0, visuals.weak_bg_fill); + } + let font = egui::TextStyle::Body.resolve(ui.style()); + ui.painter().text( + rect.left_center(), + egui::Align2::LEFT_CENTER, + if open { + icon::CARET_DOWN + } else { + icon::CARET_RIGHT + }, + font.clone(), + visuals.text_color(), + ); + let end = ui.painter().text( + rect.right_center(), + egui::Align2::RIGHT_CENTER, + status, + font.clone(), + ui.visuals().text_color(), + ); + let left = rect.left() + font.size + 6.0; + let mut job = egui::text::LayoutJob::simple_singleline( + name.into(), + egui::FontId::new(font.size + 4.0, egui::FontFamily::Name("Bold".into())), + ui.visuals().strong_text_color(), + ); + job.wrap.max_width = (end.left() - left - 8.0).max(0.0); + job.wrap.max_rows = 1; + job.wrap.break_anywhere = true; + let title = ui.painter().layout_job(job); + ui.painter().galley( + egui::pos2(left, rect.center().y - title.size().y / 2.0), + title, + visuals.text_color(), + ); + 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( ui: &mut egui::Ui, agent: &dyn Client, diff --git a/crates/tsunagi-ui/src/lib.rs b/crates/tsunagi-ui/src/lib.rs index 3c58f0e..20838e0 100644 --- a/crates/tsunagi-ui/src/lib.rs +++ b/crates/tsunagi-ui/src/lib.rs @@ -11,9 +11,18 @@ mod table; pub mod vip; 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 { let mut fonts = egui::FontDefinitions::default(); egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); + let mut bold = fonts.families[&egui::FontFamily::Proportional].clone(); + bold.insert(0, "Source Sans Pro Bold".into()); + fonts.font_data.insert( + "Source Sans Pro Bold".into(), + egui::FontData::from_static(include_bytes!("../fonts/SourceSansPro-Bold.ttf")).into(), + ); + fonts + .families + .insert(egui::FontFamily::Name("Bold".into()), bold); fonts } diff --git a/crates/tsunagi-ui/src/stats.rs b/crates/tsunagi-ui/src/stats.rs index 49eaf5f..07f6bf8 100644 --- a/crates/tsunagi-ui/src/stats.rs +++ b/crates/tsunagi-ui/src/stats.rs @@ -23,6 +23,15 @@ pub enum Unit { Bytes, } +impl Unit { + pub(crate) fn counters(self, peer: &OverlayPeerReport) -> (u64, u64) { + match self { + Self::Packets => (peer.tx_packets, peer.rx_packets), + Self::Bytes => (peer.tx_bytes, peer.rx_bytes), + } + } +} + /// One series' rolling packet and byte rates. #[derive(Default)] pub struct Series { diff --git a/crates/tsunagi-wg-quic/tests/exit_node.rs b/crates/tsunagi-wg-quic/tests/exit_node.rs index 5168b67..84b9da1 100644 --- a/crates/tsunagi-wg-quic/tests/exit_node.rs +++ b/crates/tsunagi-wg-quic/tests/exit_node.rs @@ -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"); chosen.peer_tun.push_from_os(reply.clone()); assert_eq!(next(&tun).await, reply); + let expected = tsunagi::overlay::exit::ExitTraffic { + tx_bytes: request.len() as u64, + rx_bytes: reply.len() as u64, + }; + wait_until("exit totals for the selected membership", || async { + (client.status(chosen.id).await.exit_traffic == Some(expected)).then_some(()) + }) + .await; + assert_eq!(client.status(other.id).await.exit_traffic, None); } peer.agent.shutdown().await; client.agent.shutdown().await; diff --git a/crates/tsunagi-wg-quic/tests/local_control.rs b/crates/tsunagi-wg-quic/tests/local_control.rs index e22bd6d..915f1c2 100644 --- a/crates/tsunagi-wg-quic/tests/local_control.rs +++ b/crates/tsunagi-wg-quic/tests/local_control.rs @@ -37,6 +37,7 @@ fn source(agent: Agent, plugin: Arc) -> Arc