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.
302 lines
10 KiB
Rust
302 lines
10 KiB
Rust
//! The client side: a background worker that talks to the agent over the local
|
|
//! control socket, off the UI thread.
|
|
//!
|
|
//! The UI never blocks on IO. A worker on a tokio runtime polls the agent for
|
|
//! status on an interval and runs the commands the UI sends (join, leave,
|
|
//! activate, broadcast), writing the latest snapshot into shared state and
|
|
//! asking egui to repaint. The whole thing is a thin layer over
|
|
//! [`tsunagi::ipc`]; no protocol is re-implemented here.
|
|
|
|
use std::path::PathBuf;
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, Instant};
|
|
|
|
use eframe::egui;
|
|
use tokio::sync::mpsc;
|
|
|
|
use tsunagi::ipc;
|
|
|
|
/// How often the worker refreshes status while idle.
|
|
const POLL_INTERVAL: Duration = Duration::from_secs(2);
|
|
|
|
use tsunagi_ui::client::Client;
|
|
pub(crate) use tsunagi_ui::client::{Command, Snapshot, VipSaveResult};
|
|
|
|
impl Client for AgentClient {
|
|
fn send(&self, command: Command) {
|
|
self.send(command);
|
|
}
|
|
fn busy(&self) -> bool {
|
|
lock(&self.shared).busy
|
|
}
|
|
}
|
|
|
|
/// Handle the UI holds: send commands, read the latest snapshot.
|
|
pub(crate) struct AgentClient {
|
|
tx: mpsc::UnboundedSender<Command>,
|
|
shared: Arc<Mutex<Snapshot>>,
|
|
/// A secret fetched for the clipboard, taken by the UI thread which owns
|
|
/// the clipboard; kept out of [`Snapshot`] so it is copied once, not every
|
|
/// frame, and never travels in the cloned snapshot.
|
|
pending_copy: Arc<Mutex<Option<String>>>,
|
|
}
|
|
|
|
impl AgentClient {
|
|
/// Starts the worker on `runtime`, reporting to `ctx` (for repaints).
|
|
pub(crate) fn spawn(runtime: &tokio::runtime::Handle, ctx: egui::Context) -> Self {
|
|
let (tx, rx) = mpsc::unbounded_channel();
|
|
let shared = Arc::new(Mutex::new(Snapshot {
|
|
socket: resolve_socket(),
|
|
..Snapshot::default()
|
|
}));
|
|
let pending_copy = Arc::new(Mutex::new(None));
|
|
runtime.spawn(worker(
|
|
rx,
|
|
Arc::clone(&shared),
|
|
Arc::clone(&pending_copy),
|
|
ctx,
|
|
));
|
|
Self {
|
|
tx,
|
|
shared,
|
|
pending_copy,
|
|
}
|
|
}
|
|
|
|
/// Takes any secret the worker fetched for the clipboard.
|
|
pub(crate) fn take_pending_copy(&self) -> Option<String> {
|
|
lock(&self.pending_copy).take()
|
|
}
|
|
|
|
/// The control socket this client talks to, as last resolved.
|
|
pub(crate) fn socket(&self) -> PathBuf {
|
|
lock(&self.shared).socket.clone()
|
|
}
|
|
|
|
/// Sends a command; a dropped worker simply means nothing happens.
|
|
pub(crate) fn send(&self, command: Command) {
|
|
// Disable protocol editing until the refreshed snapshot arrives;
|
|
// otherwise a second checkbox click could replace the first edit
|
|
// using the same stale network selection.
|
|
lock(&self.shared).busy = true;
|
|
if self.tx.send(command).is_err() {
|
|
lock(&self.shared).busy = false;
|
|
}
|
|
}
|
|
|
|
/// A copy of the latest snapshot.
|
|
pub(crate) fn snapshot(&self) -> Snapshot {
|
|
lock(&self.shared).clone()
|
|
}
|
|
}
|
|
|
|
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
|
match mutex.lock() {
|
|
Ok(guard) => guard,
|
|
Err(poisoned) => poisoned.into_inner(),
|
|
}
|
|
}
|
|
|
|
/// The worker loop: refresh on an interval and whenever a command runs.
|
|
async fn worker(
|
|
mut rx: mpsc::UnboundedReceiver<Command>,
|
|
shared: Arc<Mutex<Snapshot>>,
|
|
pending_copy: Arc<Mutex<Option<String>>>,
|
|
ctx: egui::Context,
|
|
) {
|
|
refresh(&shared, &ctx).await;
|
|
let mut tick = tokio::time::interval(POLL_INTERVAL);
|
|
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
|
|
|
loop {
|
|
tokio::select! {
|
|
_ = tick.tick() => {
|
|
refresh(&shared, &ctx).await;
|
|
}
|
|
command = rx.recv() => {
|
|
let Some(command) = command else { return };
|
|
run(&resolve_socket(), command, &shared, &pending_copy, &ctx).await;
|
|
refresh(&shared, &ctx).await;
|
|
lock(&shared).busy = false;
|
|
ctx.request_repaint();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Reads status and stores it, mapping any failure to a human string.
|
|
///
|
|
/// The socket is looked for again each time: a window opened before the agent
|
|
/// was started would otherwise keep asking the per-user path for ever, while
|
|
/// the service came up at the system one.
|
|
async fn refresh(shared: &Arc<Mutex<Snapshot>>, ctx: &egui::Context) {
|
|
let socket = resolve_socket();
|
|
let status = ipc::request_status(&socket)
|
|
.await
|
|
.map_err(|err| err.to_string());
|
|
{
|
|
let mut guard = lock(shared);
|
|
guard.status = Some(status.map(Arc::new));
|
|
guard.generation = guard.generation.wrapping_add(1);
|
|
guard.at = Some(Instant::now());
|
|
guard.socket = socket;
|
|
}
|
|
ctx.request_repaint();
|
|
}
|
|
|
|
/// Runs one command and records its outcome.
|
|
async fn run(
|
|
socket: &std::path::Path,
|
|
command: Command,
|
|
shared: &Arc<Mutex<Snapshot>>,
|
|
pending_copy: &Arc<Mutex<Option<String>>>,
|
|
ctx: &egui::Context,
|
|
) {
|
|
lock(shared).busy = true;
|
|
ctx.request_repaint();
|
|
|
|
let outcome: Result<String, String> = match command {
|
|
Command::SaveVip {
|
|
token,
|
|
network_id,
|
|
config,
|
|
expected,
|
|
delete,
|
|
} => {
|
|
let result = ipc::save_vip(socket, &network_id, config, expected, delete)
|
|
.await
|
|
.map_err(|e| e.to_string());
|
|
lock(shared).vip_result = Some(VipSaveResult {
|
|
token,
|
|
result: result.clone(),
|
|
});
|
|
result.map(|_| "VIP configuration saved".into())
|
|
}
|
|
Command::ForgetNode {
|
|
network_id,
|
|
peer,
|
|
expected_version,
|
|
} => ipc::forget_node(socket, &network_id, &peer, expected_version)
|
|
.await
|
|
.map(|report| {
|
|
format!(
|
|
"forgot node claim v{}; cleanup queued to {} peers",
|
|
report.record_version, report.peers_told
|
|
)
|
|
})
|
|
.map_err(|err| err.to_string()),
|
|
Command::SetProtocols {
|
|
network_id,
|
|
protocols,
|
|
} => ipc::set_protocols(socket, &network_id, protocols)
|
|
.await
|
|
.map(|names| {
|
|
format!(
|
|
"protocols: {}",
|
|
if names.is_empty() {
|
|
"none".into()
|
|
} else {
|
|
names.join(", ")
|
|
}
|
|
)
|
|
})
|
|
.map_err(|err| err.to_string()),
|
|
Command::SetActive { network_id, active } => ipc::set_active(socket, &network_id, active)
|
|
.await
|
|
.map(|report| {
|
|
let state = if report.active { "started" } else { "stopped" };
|
|
if report.suspended.is_empty() {
|
|
format!("{} {}", state, report.name)
|
|
} else {
|
|
format!(
|
|
"{} {}; suspended {} until it stops",
|
|
state,
|
|
report.name,
|
|
report
|
|
.suspended
|
|
.iter()
|
|
.map(|n| format!("{} ({})", n.name, n.network_id))
|
|
.collect::<Vec<_>>()
|
|
.join(", ")
|
|
)
|
|
}
|
|
})
|
|
.map_err(|err| err.to_string()),
|
|
Command::SetBroadcast {
|
|
network_id,
|
|
enabled,
|
|
} => ipc::set_broadcast(socket, &network_id, enabled)
|
|
.await
|
|
.map(|on| format!("broadcast {}", if on { "on" } else { "off" }))
|
|
.map_err(|err| err.to_string()),
|
|
Command::SetExitOffer {
|
|
network_id,
|
|
enabled,
|
|
} => ipc::set_exit_offer(socket, &network_id, enabled)
|
|
.await
|
|
.map(|on| format!("exit node {}", if on { "on" } else { "off" }))
|
|
.map_err(|err| err.to_string()),
|
|
Command::SetExitNode { network_id, peer } => {
|
|
ipc::set_exit_node(socket, &network_id, peer.as_deref())
|
|
.await
|
|
.map(|peer| match peer {
|
|
Some(_) => "now using the exit node".to_string(),
|
|
None => "stopped using an exit node".to_string(),
|
|
})
|
|
.map_err(|err| err.to_string())
|
|
}
|
|
Command::Join { name, secret } => ipc::join_network(socket, &name, &secret)
|
|
.await
|
|
.map(|report| {
|
|
format!(
|
|
"{} {}",
|
|
if report.active {
|
|
"joined"
|
|
} else {
|
|
"configured; stopped by range conflict:"
|
|
},
|
|
report.name
|
|
)
|
|
})
|
|
.map_err(|err| err.to_string()),
|
|
Command::Leave { network_id } => ipc::leave_network(socket, &network_id)
|
|
.await
|
|
.map(|report| format!("left {}", report.name))
|
|
.map_err(|err| err.to_string()),
|
|
Command::SetHostname(name) => ipc::set_hostname(socket, &name)
|
|
.await
|
|
.map(|accepted| format!("hostname: {accepted}"))
|
|
.map_err(|err| err.to_string()),
|
|
Command::CopySecret { network_id } => {
|
|
match ipc::network_secret(socket, &network_id).await {
|
|
// The secret goes only to the clipboard slot, never into the
|
|
// banner text or any log line.
|
|
Ok(secret) => {
|
|
*lock(pending_copy) = Some(secret);
|
|
Ok("secret copied to clipboard".to_string())
|
|
}
|
|
Err(err) => Err(err.to_string()),
|
|
}
|
|
}
|
|
};
|
|
|
|
{
|
|
let mut guard = lock(shared);
|
|
guard.last_action = if matches!(&outcome, Ok(message) if message.is_empty()) {
|
|
None
|
|
} else {
|
|
Some(outcome)
|
|
};
|
|
}
|
|
ctx.request_repaint();
|
|
}
|
|
|
|
/// Where the GUI looks for the agent: `TSUNAGI_CONTROL_SOCKET` if set, else the
|
|
/// platform default (the system service's path).
|
|
pub(crate) fn resolve_socket() -> PathBuf {
|
|
if let Some(path) = std::env::var_os("TSUNAGI_CONTROL_SOCKET") {
|
|
return PathBuf::from(path);
|
|
}
|
|
ipc::default_control_socket_path()
|
|
}
|