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

@@ -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",
};
+2 -2
View File
@@ -48,10 +48,10 @@ fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
let (reply, result) = oneshot::channel();
current()
.as_ref()
.ok_or("VPN service stopped")?
.ok_or("Tsunagi Agent stopped")?
.commands
.try_send((Request::Action(cmd), reply))
.map_err(|_| "VPN service is busy or stopped".to_owned())?;
.map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?;
Ok(result)
}
+85 -19
View File
@@ -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::<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("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);
+6 -5
View File
@@ -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;
+1
View File
@@ -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,
+11
View File
@@ -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
+2
View File
@@ -72,6 +72,7 @@ pub(crate) struct Session {
/// number of control bytes it queues.
pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>,
pub(crate) hostname: Option<String>,
pub(crate) agent_version: Option<String>,
pub(crate) capabilities: Vec<PluginCapability>,
pub(crate) broadcast: bool,
/// The peer offers itself as an exit node in this network.
@@ -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,
+4
View File
@@ -152,6 +152,8 @@ pub struct PeerStatus {
///
/// A mutable binding, not an identity.
pub hostname: Option<String>,
/// Software version in the peer's latest authenticated announcement.
pub agent_version: Option<String>,
/// Protocols agreed with this peer: both sides have them at the same
/// version.
///
@@ -247,6 +249,8 @@ pub struct NetworkStatus {
pub exit_via: Option<EndpointId>,
/// Whether that member is connected and still offering to be one.
pub exit_via_online: bool,
/// IP byte totals since this exit route was selected.
pub exit_traffic: Option<crate::overlay::exit::ExitTraffic>,
/// What the host rules for the exit settings are doing.
pub exit_rules: crate::overlay::ExitRulesReport,
/// Immutable deterministic description of the network space.
+3
View File
@@ -21,6 +21,9 @@ use crate::error::Result;
#[cfg_attr(target_os = "macos", allow(dead_code))]
const APP_NAME: &str = "tsunagi";
/// Maximum length of the optional software release label in a peer announcement.
pub const MAX_AGENT_VERSION_LEN: usize = 64;
/// Rendezvous slots per network; this bounds a discovery sample, not membership.
pub const DHT_SLOTS: u8 = 16;
/// BEP44 permits 1000 bencoded bytes; a 996-byte string has a four-byte prefix.
+5 -1
View File
@@ -830,6 +830,8 @@ pub struct MemberReport {
/// One control plane peer.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerReport {
/// The software version reported by this authenticated peer, when available.
pub agent_version: Option<String>,
/// Actionable carrier failure or policy mismatch; absent for a usable route.
pub data_error: Option<String>,
/// The peer's endpoint id.
@@ -893,6 +895,8 @@ pub struct RuleSetReport {
/// One network's exit-node settings and what they are doing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExitReport {
/// IP bytes carried through this exit since selection, when locally observed.
pub traffic: Option<crate::overlay::exit::ExitTraffic>,
/// This agent offers itself as an exit node in this network.
pub offering: bool,
/// Masquerading and forwarding rules for members' traffic, when offering.
@@ -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.
///
+9
View File
@@ -5,6 +5,15 @@
//! system sees. It is kept apart from the broadcast rules, which have a
//! different lifetime and different tags.
/// Plaintext IP bytes carried through the client's currently selected internet exit.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ExitTraffic {
/// Bytes accepted by the carrier for off-mesh destinations.
pub tx_bytes: u64,
/// Internet reply bytes delivered to the local interface.
pub rx_bytes: u64,
}
/// How one set of host rules went.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleSetReport {
+74 -21
View File
@@ -320,11 +320,19 @@ impl Interface {
tally.multicast.fetch_add(1, Ordering::Relaxed);
continue;
}
let Some(route) = routes.route_v4(destination) else {
let selected = match destination {
IpAddr::V4(address) => routes.packet_route(address),
IpAddr::V6(_) => None,
};
let Some((route, exit)) = selected else {
tally.note_unroutable(destination);
continue;
};
let len = packet.len() as u64;
if carrier.carry(route, packet) {
if let Some(exit) = exit {
exit.tx_bytes.fetch_add(len, Ordering::Relaxed);
}
tally.sent.fetch_add(1, Ordering::Relaxed);
} else {
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
@@ -840,12 +848,14 @@ impl Interface {
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongSource);
};
let broadcast = match (origin, header.destination()) {
(PacketSource::ExitReply { local: Some(local) }, IpAddr::V4(destination))
if destination == local =>
{
false
}
let (broadcast, exit) = match (origin, header.destination()) {
(
PacketSource::ExitReply {
local: Some(local),
exit,
},
IpAddr::V4(destination),
) if destination == local => (false, Some(exit)),
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_broadcast(destination) =>
{
@@ -855,13 +865,13 @@ impl Interface {
self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::BroadcastDenied);
}
true
(true, None)
}
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_local_destination(network, destination)
|| self.routes.accepts_exit_traffic(network, destination) =>
{
false
(false, None)
}
_ => {
self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed);
@@ -887,7 +897,11 @@ impl Interface {
crate::vip::router::Decision::Pass => packet,
};
// Remote broadcasts terminate here. Only local TUN ingress can fan out.
let len = packet.len() as u64;
if self.device.send(packet).await.is_ok() {
if let Some(exit) = exit {
exit.rx_bytes.fetch_add(len, Ordering::Relaxed);
}
if broadcast {
self.tally
.broadcast_received
@@ -926,18 +940,6 @@ impl Drop for Interface {
}
}
impl RoutingTable {
/// The route for a destination, when it is one the overlay carries.
fn route_v4(&self, destination: IpAddr) -> Option<Route> {
match destination {
IpAddr::V4(address) => self.route(address),
// The overlay is IPv4. An IPv6 packet has no owner here, and
// counting it as unroutable is the truth rather than a fault.
IpAddr::V6(_) => None,
}
}
}
/// Whether an address is one the overlay has nowhere to send.
fn is_multicast_or_broadcast(address: IpAddr) -> bool {
match address {
@@ -1530,6 +1532,57 @@ mod tests {
}
}
#[tokio::test]
async fn exit_totals_count_only_accepted_internet_packets_for_the_current_choice() {
let (interface, device, routes, _, id) = interface(false).await;
let totals = |p| {
routes
.exit_traffic(id, peer(p))
.map(|t| (t.tx_bytes, t.rx_bytes))
};
assert_eq!(totals(2), None);
routes.set_exit(id, using(peer(2)));
let outgoing = ipv4(addr(1), INTERNET, b"request");
device.push_from_os(outgoing.clone());
device.push_from_os(ipv4(addr(1), addr(2), b"ordinary mesh traffic"));
wait_for(&interface, |c| c.sent.saturating_sub(1)).await;
let incoming = ipv4(INTERNET, addr(1), b"reply");
interface
.deliver(id, peer(2), incoming.clone())
.await
.unwrap();
interface
.deliver(id, peer(2), ipv4(addr(2), addr(1), b"mesh"))
.await
.unwrap();
assert!(
interface
.deliver(id, peer(3), incoming.clone())
.await
.is_err()
);
assert!(
interface
.deliver(id, peer(2), ipv4(INTERNET, addr(3), b"wrong host"))
.await
.is_err()
);
routes.set_exit(id, using(peer(2)));
assert_eq!(
totals(2),
Some((outgoing.len() as u64, incoming.len() as u64))
);
routes.set_exit(id, using(peer(3)));
assert_eq!(totals(2), None);
assert_eq!(totals(3), Some((0, 0)));
routes.set_exit(id, ExitPolicy::default());
assert_eq!(totals(3), None);
routes.set_exit(id, using(peer(2)));
assert_eq!(totals(2), Some((0, 0)));
interface.remove().await;
}
#[tokio::test]
async fn internet_traffic_goes_to_the_exit_node_and_only_once_one_is_chosen() {
let (interface, device, routes, carrier, id) = interface(false).await;
+66 -9
View File
@@ -21,9 +21,11 @@
//! one is in use.
use super::broadcast::{BroadcastPolicy, BroadcastTable};
use arc_swap::ArcSwap;
use super::exit::ExitTraffic;
use arc_swap::{ArcSwap, ArcSwapOption};
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use iroh::EndpointId;
@@ -43,7 +45,19 @@ pub struct Route {
/// An internet source is valid only for a reply to our address in the exit's network.
pub(super) enum PacketSource {
Member,
ExitReply { local: Option<Ipv4Addr> },
ExitReply {
local: Option<Ipv4Addr>,
exit: Arc<SelectedExit>,
},
}
/// A packet holds its selection until delivery finishes, even if the operator
/// switches to another exit in the meantime.
#[derive(Debug)]
pub(super) struct SelectedExit {
route: Route,
pub(super) tx_bytes: AtomicU64,
pub(super) rx_bytes: AtomicU64,
}
/// A network's exit-node settings, as far as packets are concerned.
@@ -97,6 +111,7 @@ pub enum RouteError {
pub struct RoutingTable {
pub(crate) vips: Arc<crate::vip::VipRouter>,
broadcast: ArcSwap<BroadcastTable>,
selected_exit: ArcSwapOption<SelectedExit>,
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
}
@@ -171,6 +186,7 @@ impl RoutingTable {
clear_other_exits(networks, network);
}
networks.insert(network, routes);
self.refresh_exit(networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(networks)));
Ok(())
@@ -181,6 +197,7 @@ impl RoutingTable {
self.vips.remove_network(network);
let mut networks = self.write();
networks.remove(&network);
self.refresh_exit(&networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
}
@@ -213,9 +230,35 @@ impl RoutingTable {
if routes.exit.via.is_some() {
clear_other_exits(&mut networks, network);
}
self.refresh_exit(&networks);
}
}
/// Publish the current choice under the same write lock as the route edits.
fn refresh_exit(&self, networks: &HashMap<NetworkId, NetworkRoutes>) {
let route = exit_via(networks).map(|(network, peer)| Route { network, peer });
if self.selected_exit.load().as_ref().map(|exit| exit.route) != route {
self.selected_exit.store(route.map(|route| {
Arc::new(SelectedExit {
route,
tx_bytes: AtomicU64::default(),
rx_bytes: AtomicU64::default(),
})
}));
}
}
pub(crate) fn exit_traffic(&self, network: NetworkId, peer: EndpointId) -> Option<ExitTraffic> {
let current = self.selected_exit.load();
let exit = current
.as_ref()
.filter(|e| e.route == Route { network, peer })?;
Some(ExitTraffic {
tx_bytes: exit.tx_bytes.load(Ordering::Relaxed),
rx_bytes: exit.rx_bytes.load(Ordering::Relaxed),
})
}
/// Recognizes limited and configured subnet broadcasts before unicast lookup.
pub fn is_broadcast(&self, destination: Ipv4Addr) -> bool {
self.broadcast.load().is_destination(destination)
@@ -249,6 +292,13 @@ impl RoutingTable {
/// unicast destination, goes to this device's exit node when it has one:
/// that is what sending *all* traffic through a member means.
pub fn route(&self, destination: Ipv4Addr) -> Option<Route> {
self.packet_route(destination).map(|(route, _)| route)
}
pub(super) fn packet_route(
&self,
destination: Ipv4Addr,
) -> Option<(Route, Option<Arc<SelectedExit>>)> {
let networks = self.read();
for (network, routes) in networks.iter() {
if routes.local == Some(destination) {
@@ -259,10 +309,13 @@ impl RoutingTable {
.iter()
.find(|(address, _)| *address == destination)
{
return Some(Route {
network: *network,
peer: *peer,
});
return Some((
Route {
network: *network,
peer: *peer,
},
None,
));
}
}
// Inside an overlay range, an unowned address is nobody's, not the
@@ -270,7 +323,8 @@ impl RoutingTable {
if !is_internet_destination(destination) || in_any_range(&networks, destination) {
return None;
}
exit_via(&networks).map(|(network, peer)| Route { network, peer })
let exit = self.selected_exit.load_full()?;
Some((exit.route, Some(exit)))
}
/// Whether a peer may send from a source address.
@@ -298,11 +352,14 @@ impl RoutingTable {
{
return Some(PacketSource::Member);
}
(exit_via(&networks) == Some((network, peer))
let current = self.selected_exit.load();
let exit = current.as_ref()?;
(exit.route == Route { network, peer }
&& is_internet_destination(source)
&& !in_any_range(&networks, source))
.then_some(PacketSource::ExitReply {
.then(|| PacketSource::ExitReply {
local: routes.local,
exit: Arc::clone(exit),
})
}
+55
View File
@@ -90,6 +90,23 @@ pub struct Announcement {
pub hostname: String,
/// Announced IP plugin capabilities. Opaque to the core.
pub capabilities: Vec<PluginCapability>,
/// Software release reported by this peer for display after authentication.
/// Keep this trailer last: original v8 readers stop after the capabilities.
#[serde(default, deserialize_with = "read_agent_version")]
pub agent_version: Option<String>,
}
fn read_agent_version<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
// A frame contains exactly one envelope. EOF here is a legacy announcement.
// An unreadable display hint can also be discarded without losing the
// hostname or capabilities. Borrow the frame until the label is bounded.
let version = Option::<&str>::deserialize(d).ok().flatten().filter(|s| {
!s.is_empty()
&& s.len() <= crate::config::MAX_AGENT_VERSION_LEN
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-'))
});
Ok(version.map(str::to_owned))
}
/// Opens a data channel, sent by the initiator right after the membership
@@ -395,3 +412,41 @@ pub fn kind(message: &ControlMessage) -> &'static str {
ControlMessage::Bye { .. } => "bye",
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::panic)]
use super::*;
#[test]
fn v8_announcements_interoperate_with_and_without_a_software_version() {
// The original v8 frame ends with the capability list. Decode the
// new frame using exactly those fields as an older receiver would.
type OldFrame = ([u8; 32], u8, bool, bool, String, Vec<PluginCapability>);
let old: OldFrame = ([7; 32], 1, true, false, "lab".into(), vec![]);
let legacy = encode(&old).unwrap();
assert!(decode::<Envelope>(&legacy[..legacy.len() - 1]).is_err());
let read = |bytes: &[u8]| match decode::<Envelope>(bytes).unwrap().message {
ControlMessage::Announce(a) => a,
_ => panic!("expected announcement"),
};
let mut a = read(&legacy);
assert_eq!(a.agent_version, None);
a.agent_version = Some("2.1.0-rc.2+android".into());
let wire = encode(&Envelope {
network_id: old.0,
message: ControlMessage::Announce(a.clone()),
})
.unwrap();
assert_eq!(decode::<OldFrame>(&wire).unwrap(), old);
assert_eq!(read(&wire), a);
for invalid in ["", "1.2.3\nforged", &"1".repeat(256)] {
let mut wire = legacy.clone();
wire.extend(encode(&Some(invalid)).unwrap());
let a = read(&wire);
assert_eq!(a.agent_version, None);
assert_eq!(a.hostname, "lab");
}
}
}
+13 -9
View File
@@ -43,15 +43,19 @@ async fn four_agents_form_a_mesh_and_exchange_distinguishable_messages() {
// A peer counts as connected as soon as its session is authenticated, which
// can be a round before its announcement carrying the hostname arrives, so
// this waits for the hostnames rather than reading them straight away.
let hostnames: HashSet<String> = wait_until("three distinct peer hostnames", || async {
let status = agents[0].agent.network_status(network_id).await.ok()?;
let hostnames: HashSet<String> = status
.peers
.iter()
.filter_map(|peer| peer.hostname.clone())
.collect();
(hostnames.len() >= 3).then_some(hostnames)
})
let hostnames: HashSet<String> = wait_until(
"three peers announce their hostname and release",
|| async {
let status = agents[0].agent.network_status(network_id).await.ok()?;
let hostnames: HashSet<String> = status
.peers
.iter()
.filter(|peer| peer.agent_version.as_deref() == Some(env!("CARGO_PKG_VERSION")))
.filter_map(|peer| peer.hostname.clone())
.collect();
(hostnames.len() >= 3).then_some(hostnames)
},
)
.await;
assert_eq!(
hostnames.len(),
+2
View File
@@ -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,
+2 -2
View File
@@ -162,8 +162,8 @@ impl App {
.with_title(devices::title(network))
.with_app_id(crate::icon::APP_ID)
.with_icon(crate::icon::window())
.with_inner_size([1440.0, 640.0])
.with_min_inner_size([800.0, 400.0]);
.with_inner_size([1000.0, 640.0])
.with_min_inner_size([560.0, 400.0]);
let agent = &self.agent;
let traffic = &self.traffic;
// The window shares the single unit setting, so its toggle and the
+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() {
"can be managed (CAP_NET_ADMIN)"
} else {
"Android VPN service"
"Android foreground service"
});
}
PrivilegeReport::Missing(_) => {
+199 -121
View File
@@ -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<String>,
/// 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<Device<'a>> {
via_name,
name_taken,
hostname,
agent_version: peer.and_then(|p| p.agent_version.as_deref()),
copy: hostname.map(|h| format!("{h}.{}", network.name)),
id,
data_error: peer.and_then(|p| p.data_error.as_deref()),
@@ -484,44 +498,55 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
devices
}
const COLUMN_HEADERS: [&str; 10] = [
"device",
"exit",
"data",
"RTT data / control",
"address",
"data path",
"pkts",
"bytes",
"rate",
"plot",
];
fn column_headers(unit: Unit) -> [&'static str; 9] {
[
"device",
"exit",
"data",
"RTT data / control",
"address",
"data path",
match unit {
Unit::Bytes => "bytes (TX / RX)",
Unit::Packets => "pkts (TX / RX)",
},
"rate",
"plot",
]
}
/// Initial column floors; actual headers, values and totals can grow them.
const COLUMN_SAMPLES: [&str; 10] = [
const COLUMN_SAMPLES: [&str; 9] = [
"device",
"exit",
"data",
"9999 ms",
"255.255.255.255",
"data path",
"99999/99999",
"1023.9 MB / 1023.9 MB",
"1023.9 kB/s",
"plot",
];
fn traffic_pair(tx: u64, rx: u64, unit: Unit) -> String {
format!(
"{} / {}",
format::amount(tx, unit),
format::amount(rx, unit)
)
}
/// Column widths that only ever grow, kept across frames.
///
/// Live values can change width between frames. A value that
/// gets shorter — `14.4 MB/s` giving way to `382 pkt/s` — would pull the
/// column in and push every cell after it. Remembering the widest seen keeps
/// the table where it is.
fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 10] {
let stored: Option<[f32; 10]> = ui.memory(|m| m.data.get_temp(id));
fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 9] {
let stored: Option<[f32; 9]> = ui.memory(|m| m.data.get_temp(id));
stored.unwrap_or_else(|| {
let font = egui::FontSelection::Default.resolve(ui.style());
let mut widths = [0.0; 10];
let mut widths = [0.0; 9];
for (width, sample) in widths.iter_mut().zip(COLUMN_SAMPLES) {
if !sample.is_empty() {
*width = ui.fonts(|fonts| {
@@ -536,10 +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::<f32>()).max(0.0);
fn stretch_columns(mut widths: [f32; 9], available: f32) -> [f32; 9] {
let gaps = crate::table::GAP * (widths.len() - 1) as f32;
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(100.0, 180.0);
widths
}
@@ -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::<f32>() + 90.0 - 1440.0).abs() < 0.1);
assert_eq!(&wide[..9], &minimum[..9]);
assert!((100.0..=190.0).contains(&wide[8]));
assert_eq!(&wide[..8], &minimum[..8]);
let narrow = stretch_columns(minimum, 800.0);
assert_eq!(
narrow, minimum,
@@ -1148,6 +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
+97 -69
View File
@@ -130,74 +130,102 @@ fn details(
exit: &mut Option<ExitConfirm>,
forget: &mut Option<ForgetConfirm>,
) {
ui.horizontal_wrapped(|ui| {
ui.weak(if member.online { "online" } else { "offline" });
if let Some(name) = &member.copy {
format::copy_field(ui, &member.name(), name);
}
if let Some(address) = &member.address {
format::copy_field(ui, address, address);
}
});
ui.horizontal_wrapped(|ui| {
ui.weak("Endpoint ID");
format::copy_field(ui, &format::short(member.id), member.id);
});
let (path, _) = data_path_text(member.path, member.via_name.as_deref(), member.online);
ui.horizontal_wrapped(|ui| {
ui.label(path);
tunnel_cell(ui, member);
});
if member.online {
if let Some(path) = member.data_transport_detail {
ui.label(path);
}
ui.label(format!(
"Data RTT {} · Control RTT {}",
rtt_text(member.data_rtt_ms),
rtt_text(member.control_rtt_ms)
));
}
if let Some(error) = member.data_error {
ui.colored_label(AMBER, error);
}
if let Some((taken, holder)) = &member.name_taken {
ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}."));
}
if let Some(peer) = member.overlay {
let series = traffic.peer(&network.network_id, &peer.public_key);
ui.horizontal_wrapped(|ui| {
ui.label(format!(
"TX {} · {} pkts",
format::bytes(peer.tx_bytes as f64),
peer.tx_packets
));
ui.label(format!(
"RX {} · {} pkts",
format::bytes(peer.rx_bytes as f64),
peer.rx_packets
));
ui.weak(format::series_rate(series, unit));
egui::Frame::new()
.fill(ui.visuals().faint_bg_color)
.inner_margin(egui::Margin::symmetric(10, 8))
.show(ui, |ui| {
ui.set_min_width(ui.available_width());
ui.spacing_mut().item_spacing.y = 4.0;
ui.columns(2, |cols| {
cols[0].small("Data path");
let (path, _) =
data_path_text(member.path, member.via_name.as_deref(), member.online);
cols[0].horizontal_wrapped(|ui| {
ui.label(path);
if member.online {
tunnel_cell(ui, member);
}
});
cols[1].small("Tsunagi version");
cols[1].label(member.agent_version.unwrap_or("Unknown"));
});
if let Some(path) = member.data_transport_detail {
ui.add(egui::Label::new(path).wrap());
}
if member.online {
ui.columns(2, |cols| {
cols[0].small("Data RTT");
cols[0].label(rtt_text(member.data_rtt_ms));
cols[1].small("Control RTT");
cols[1].label(rtt_text(member.control_rtt_ms));
});
}
if let Some(peer) = member.overlay.filter(|_| member.online) {
ui.separator();
let (tx, rx) = unit.counters(peer);
let sent_color = ui.visuals().hyperlink_color;
ui.columns(2, |cols| {
for (col, arrow, caption, count, color) in [
(0, icon::ARROW_UP, "Sent", tx, sent_color),
(1, icon::ARROW_DOWN, "Received", rx, exit::GOOD),
] {
cols[col].horizontal(|ui| {
ui.colored_label(color, arrow);
ui.label(caption);
});
let value = format::amount(count, unit);
let value = match unit {
Unit::Packets => format!("{value} pkts"),
Unit::Bytes => value,
};
let size = cols[col].text_style_height(&egui::TextStyle::Body) + 2.0;
cols[col].label(egui::RichText::new(value).size(size).strong());
}
});
format::sparkline(
ui,
traffic.peer(&network.network_id, &peer.public_key),
unit,
28.0,
);
}
ui.separator();
ui.columns(2, |cols| {
cols[0].small("Endpoint ID");
format::copy_field(&mut cols[0], &format::short(member.id), member.id);
cols[1].small("IPv4");
if let Some(address) = &member.address {
format::copy_field(&mut cols[1], address, address);
} else {
cols[1].weak("—");
}
});
if let Some(name) = &member.copy {
format::copy_field(ui, name, name);
}
if let Some(error) = member.data_error {
ui.colored_label(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.
pub fn rate(value: f32, unit: Unit) -> String {
match unit {
+234 -120
View File
@@ -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<String>,
/// An in-progress hostname edit (`None` when not editing).
pub host_edit: Option<String>,
/// 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,
+10 -1
View File
@@ -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
}
+9
View File
@@ -23,6 +23,15 @@ pub enum Unit {
Bytes,
}
impl Unit {
pub(crate) fn counters(self, peer: &OverlayPeerReport) -> (u64, u64) {
match self {
Self::Packets => (peer.tx_packets, peer.rx_packets),
Self::Bytes => (peer.tx_bytes, peer.rx_bytes),
}
}
}
/// One series' rolling packet and byte rates.
#[derive(Default)]
pub struct Series {
@@ -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;
@@ -37,6 +37,7 @@ fn source(agent: Agent, plugin: Arc<WireguardPlugin>) -> Arc<dyn tsunagi::ipc::R
.peers
.iter()
.map(|peer| tsunagi::ipc::PeerReport {
agent_version: peer.agent_version.clone(),
data_error: None,
endpoint_id: peer.endpoint_id.to_string(),
hostname: peer.hostname.clone(),
+1
View File
@@ -5206,6 +5206,7 @@ mod status_tests {
relay_sent_via: 0,
relay_received_via: 0,
peers: vec![PeerReport {
agent_version: None,
data_error: None,
endpoint_id: ONLINE.into(),
hostname: Some("music".into()),