Add a Rust Android mesh client with shared tray views

Run one agent for all joined networks behind Android's VPN service. Share
transport registration and reporting with the CLI, and move the tray's
egui forms into a Rust UI crate. Phones use compact device rows and a
full-width exit picker with RTT and data path. All four transports retain
their per-network selection and priority. The phone consumes remote IPv4
exits and keeps the existing desktop identity and wire protocols.

Send discovery and transport traffic over the physical network and bind
VIP TCP health checks to the mesh. Build local DNS zones from the same
signed membership and VIP records on desktop and Android. Answer UDP and
TCP queries on the VPN, keep unknown mesh names local, and resolve public
names through Android's underlying resolver, including with an exit.

Show an ongoing notification for the selected exit. Guard its disconnect
action against a stale selection and keep mesh routing and DNS alive when
it removes the default route. Remove the app notification in mesh-only
mode. Document Android 14's unlocked-device swipe behavior.

Checked formatting and ran locked all-target workspace Clippy with
warnings denied and tests on macOS (547 passed, 2 ignored). Built the
arm64 debug APK. A physical Pixel resolved a mesh member and a Kubernetes
VIP, answered UDP and TCP DNS, and reached the API over TLS (HTTP 401
without credentials). On a separate Android emulator the notification
action removed the default route and notice while mesh DNS still worked.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-24 17:28:23 +02:00
1 parent 9dec056349
commit ef67e1c0ae
70 files changed
+6199 -1181

No files matched your search

+190
View File
@@ -0,0 +1,190 @@
//! Construct the native data transports in one place for both the CLI and Android.
//! The embedding application supplies the Tokio runtime, TUN and discovery policy.
use std::{
net::{IpAddr, Ipv4Addr},
sync::Arc,
};
use tokio::{sync::watch, task::JoinSet};
use tsunagi::{
Agent, AgentConfig, TransportPolicy, dataplane::transport::iroh_link::IrohCarrier,
iroh_types::EndpointAddr,
};
use tsunagi_awg::{AWG_PROTOCOL, AWG_WIRE_VERSION, AwgPlugin, AwgTransport};
use tsunagi_tcp_tls::{TCP_TLS_PROTOCOL, TcpTlsCarrier, TcpTlsConfig, TcpTlsTransport};
use tsunagi_wireguard::WG_PROTOCOL;
pub mod report;
/// What a protocol is called, what it speaks, and what it takes.
///
/// A registry rather than a lookup on the plugins themselves, because
/// `tsng protocols` has to answer before anything is constructed, and
/// because this is the list `--protocol` resolves against.
pub struct ProtocolSpec {
/// The name on the wire, which is what peers compare.
pub name: &'static str,
/// The wire version. Not the software version: two peers on different
/// builds carry traffic for each other as long as this matches.
pub version: u16,
/// One line about what it is.
pub summary: &'static str,
/// The settings it accepts.
pub options: &'static [tsunagi::dataplane::ProtocolOption],
}
const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::ProtocolOption {
key: "port",
value: "PORT",
help: "preferred local UDP port; additional pairs use dynamic ports",
default: Some("51820"),
}];
/// Every protocol this build has.
pub const PROTOCOLS: &[ProtocolSpec] = &[
ProtocolSpec {
name: WG_PROTOCOL,
version: tsunagi_wireguard::WG_WIRE_VERSION,
summary: "Pure WireGuard direct UDP transport",
options: WG_OPTIONS,
},
ProtocolSpec {
name: AWG_PROTOCOL,
version: AWG_WIRE_VERSION,
summary: "Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt",
options: AwgPlugin::OPTIONS,
},
ProtocolSpec {
name: "wg-quic",
version: 1,
summary: "iroh QUIC datagram carrier with NAT traversal and relays",
options: &[],
},
ProtocolSpec {
name: TCP_TLS_PROTOCOL,
version: tsunagi_tcp_tls::TCP_TLS_VERSION,
summary: "TCP TLS 1.3 carrier",
options: TcpTlsConfig::OPTIONS,
},
];
/// Incoming direct connections to attach after the agent has acquired its identity.
pub struct Carriers {
udp: [Arc<AwgTransport>; 2],
tls: Arc<TcpTlsTransport>,
}
impl Carriers {
/// Register the complete catalog. CLI options and phone defaults use the same
/// constructors and wire versions. Android supplies the addresses of its selected
/// physical network; desktop discovers addresses on its host interfaces.
pub async fn configure(
mut config: AgentConfig,
bootstrap: &[EndpointAddr],
underlay: Option<watch::Receiver<Vec<IpAddr>>>,
options: impl Fn(&ProtocolSpec) -> Vec<(String, String)>,
) -> Result<(AgentConfig, Self), Box<dyn std::error::Error>> {
let options_for = |name| {
PROTOCOLS
.iter()
.find(|p| p.name == name)
.map(&options)
.unwrap_or_default()
};
let wg_opts = options_for(WG_PROTOCOL);
let port = wg_opts
.iter()
.find(|(k, _)| k == "port")
.map(|(_, v)| v.parse::<u16>())
.transpose()?
.unwrap_or(51820);
let awg_opts = options_for(AWG_PROTOCOL);
const STUN: &str = "stun.l.google.com:19302";
let server = awg_opts
.iter()
.find(|(key, _)| key == "stun")
.map_or(STUN, |(_, value)| value.as_str());
if server.len() > 255 || (server != "off" && !server.contains(':')) {
return Err("awg:stun must be HOST:PORT or off".into());
}
let public = config.transport != TransportPolicy::LocalOnly;
let db = config.paths.state_db();
let identity = tokio::task::spawn_blocking(move || {
tsunagi::storage::StateStore::open(db)?.load_or_create_device_identity()
})
.await??;
let bind = Ipv4Addr::UNSPECIFIED;
let udp = [
AwgTransport::wireguard_with_port(
identity.endpoint_id(),
bind,
public.then(|| STUN.into()),
port,
),
AwgTransport::new_with_stun(
identity.endpoint_id(),
bind,
(public && server != "off").then(|| server.into()),
),
];
for transport in &udp {
transport.exclude_interface(config.interface_name.clone());
if let Some(source) = &underlay {
transport.set_underlay(source.clone());
}
config = config
.with_carrier(AwgPlugin::new(transport.clone()))
.with_custom_transport(transport.protocol_id(), transport.clone());
}
let settings =
TcpTlsConfig::configure(TcpTlsConfig::new(), &options_for(TCP_TLS_PROTOCOL))?;
let tls = Arc::new(
TcpTlsTransport::bind(&identity, settings.port, settings.sni)
.await
.map_err(|error| -> Box<dyn std::error::Error> { error })?,
);
for address in bootstrap {
for ip in address.ip_addrs() {
tls.set_peer_addr(address.id, *ip);
}
}
let carrier = TcpTlsCarrier::with_interface(tls.clone(), config.interface_name.clone());
if let Some(source) = underlay {
carrier.set_underlay(source);
}
config = config
.with_carrier(Arc::new(IrohCarrier))
.with_carrier(carrier)
.with_custom_transport(TCP_TLS_PROTOCOL, tls.clone());
Ok((config, Self { udp, tls }))
}
/// Accept incoming authenticated links until the caller drops the returned task set.
#[must_use = "keep the listeners alive for the lifetime of this agent"]
pub fn listen(self, agent: &Agent) -> JoinSet<()> {
let mut tasks = JoinSet::new();
for transport in self.udp {
let agent = agent.clone();
tasks.spawn(async move {
while let Some(inbound) = transport.next_inbound().await {
if let Err(error) = agent.install_inbound_link(inbound).await {
tracing::debug!(%error, protocol=transport.protocol_id(), "inbound link rejected");
}
}
});
}
let agent = agent.clone();
tasks.spawn(async move {
self.tls
.accept_loop(move |inbound| {
let agent = agent.clone();
tokio::spawn(async move {
if let Err(error) = agent.install_inbound_link(inbound).await {
tracing::debug!(%error, "inbound tcp-tls link rejected");
}
});
})
.await;
});
tasks
}
}
+201
View File
@@ -0,0 +1,201 @@
//! Combine the core snapshot and live WireGuard observations for local clients.
use tsunagi::ipc::{MemberReport, NetworkReport, OverlayPeerReport, OverlayReport, PeerReport};
use tsunagi::{AgentStatus, agent::OverlayStatus};
use tsunagi_wg_quic::WireguardPlugin;
/// Build the same per-network view for an in-process client and the CLI's IPC server.
pub fn networks(
status: &AgentStatus,
overlay: Option<&OverlayStatus>,
wireguard: Option<&WireguardPlugin>,
) -> Vec<NetworkReport> {
status
.networks
.iter()
.map(|network| {
let wg_view = wireguard.and_then(|plugin| plugin.overview(network.network_id));
let wg_overlay_addr = wg_view.as_ref().and_then(|v| v.overlay_address_v4);
let wg_prefix_len = wg_view
.as_ref()
.and_then(|v| v.ipv4_range)
.map_or(0, |r| r.prefix_len);
let has_any_plugin = wg_view.is_some();
let overlay = if has_any_plugin && overlay.is_some() {
let mut peers: Vec<OverlayPeerReport> = Vec::new();
if let Some(view) = &wg_view {
for peer in &view.peers {
let tunnel = peer.tunnel.as_ref();
peers.push(OverlayPeerReport {
counter_epoch: tunnel.map_or(0, |t| t.stats.counter_epoch),
endpoint_id: peer.endpoint_id.to_string(),
protocol: String::new(),
public_key: peer.public_key.to_string(),
address: peer.overlay_address_v4.map(|a| a.to_string()),
handshake_secs_ago: tunnel
.and_then(|t| t.health.since_handshake.map(|s| s.as_secs())),
tx_packets: tunnel.map_or(0, |t| t.stats.tx_packets),
rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets),
tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes),
rx_bytes: tunnel.map_or(0, |t| t.stats.rx_bytes),
dropped: tunnel.map_or(0, |t| {
t.stats.dropped_wrong_source + t.stats.dropped_oversize
}),
protocol_errors: tunnel.map_or(0, |t| t.stats.protocol_errors),
path: tunnel.map_or_else(|| "no data path".into(), |t| t.path.clone()),
});
}
}
let (address, prefix_len) = if wg_overlay_addr.is_some() {
(wg_overlay_addr.map(|addr| addr.to_string()), wg_prefix_len)
} else {
(
network
.members
.iter()
.find(|m| m.endpoint_id == status.endpoint_id)
.and_then(|m| m.overlay_address_v4)
.map(|a| a.to_string()),
network.range.map_or(0, |r| r.prefix_len),
)
};
Some(OverlayReport {
interface: overlay.map_or_else(String::new, |o| o.interface.clone()),
on_host: overlay.is_some_and(|o| o.on_host),
mtu: overlay.map_or(0, |o| o.mtu),
address,
prefix_len,
peers,
unroutable_packets: overlay.map_or(0, |o| o.counters.unroutable),
multicast_packets: overlay.map_or(0, |o| o.counters.multicast),
unroutable_sample: overlay
.and_then(|o| o.counters.unroutable_sample.map(|a| a.to_string())),
broadcast_rules: overlay.and_then(|o| o.broadcast_rules.as_ref()).map(
|rules| tsunagi::ipc::HostRulesReport {
ok: rules.is_ok(),
detail: rules.summary(),
source: rules.plan.source.to_string(),
},
),
})
} else {
None
};
NetworkReport {
vips: network.vips.clone(),
protocols: network.protocols.clone(),
auto_start: network.auto_start,
exit: exit_report(network),
broadcast: network.broadcast,
name: network.name.to_string(),
network_id: network.network_id.to_string(),
active: matches!(network.state, tsunagi::agent::NetworkState::Active),
candidates: network.candidates.len() as u32,
relay_forwarded: network.relay.forwarded,
relay_sent_via: network.relay.sent_via,
relay_received_via: network.relay.received_via,
peers: network
.peers
.iter()
.map(|peer| PeerReport {
data_error: peer.data_error.clone(),
endpoint_id: peer.endpoint_id.to_string(),
hostname: peer.hostname.clone(),
transport: peer.transport.to_string(),
rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64),
exit_node: peer.exit_node,
path: data_path_report(&peer.data_path),
})
.collect(),
members: network
.members
.iter()
.map(|member| MemberReport {
record_version: member.record_version,
endpoint_id: member.endpoint_id.to_string(),
overlay_address_v4: member.overlay_address_v4.map(|addr| addr.to_string()),
// What this agent is currently experiencing trying to
// reach it, so a dial-failure count can be attributed
// to the member it belongs to instead of floating
// free as a network-wide number.
failed_dials: network
.candidates
.iter()
.find(|candidate| candidate.endpoint_id == member.endpoint_id)
.map_or(0, |candidate| candidate.consecutive_failures),
hostname: member
.last_hostname
.clone()
.or_else(|| member.hostname.clone()),
online: member.online,
path: data_path_report(&member.data_path),
hostname_conflict: member.hostname_conflict.as_ref().map(conflict_report),
})
.collect(),
range: network.range.map(|range| range.to_string()),
range_conflict: network.range_conflict.map(|range| range.to_string()),
range_conflicts: network
.range_conflicts
.iter()
.map(|c| tsunagi::ipc::RangeConflictReport {
network_id: c.network_id.to_string(),
name: c.name.to_string(),
range: c.range.to_string(),
})
.collect(),
dial_failures: network.metrics.dial_failures,
handshake_failures: network.metrics.handshake_failures,
control_messages: (
network.metrics.control_messages_sent,
network.metrics.control_messages_received,
),
overlay,
hostname_conflict: network.hostname_conflict.as_ref().map(conflict_report),
}
})
.collect()
}
fn data_path_report(path: &tsunagi::agent::DataPath) -> tsunagi::ipc::DataPathReport {
match path {
tsunagi::agent::DataPath::None => tsunagi::ipc::DataPathReport::None,
tsunagi::agent::DataPath::Direct { transport } => tsunagi::ipc::DataPathReport::Direct {
transport: transport.clone(),
},
tsunagi::agent::DataPath::Relayed { hops, via } => tsunagi::ipc::DataPathReport::Relayed {
hops: *hops,
via: via.to_string(),
},
}
}
fn conflict_report(
conflict: &tsunagi::agent::HostnameConflict,
) -> tsunagi::ipc::HostnameConflictReport {
tsunagi::ipc::HostnameConflictReport {
name: conflict.name.clone(),
holder: conflict.holder.to_string(),
}
}
/// One network's exit-node settings, as the control interface reports them.
fn exit_report(network: &tsunagi::agent::NetworkStatus) -> tsunagi::ipc::ExitReport {
let rules = |report: &Option<tsunagi::overlay::RuleSetReport>| {
report.as_ref().map(|report| tsunagi::ipc::RuleSetReport {
ok: report.ok,
detail: report.detail.clone(),
})
};
tsunagi::ipc::ExitReport {
offering: network.exit_offer,
offer_rules: rules(&network.exit_rules.offer),
forwarding: network.exit_rules.forwarding,
via: network.exit_via.map(|peer| peer.to_string()),
via_online: network.exit_via_online,
client_rules: rules(&network.exit_rules.client),
}
}