//! 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::{self, StatusReport}; /// How often the worker refreshes status while idle. const POLL_INTERVAL: Duration = Duration::from_secs(2); /// A request from the UI to the agent. pub(crate) enum Command { SaveVip { token: String, network_id: String, config: tsunagi::vip::VipConfig, expected: Option, delete: bool, }, /// Retire the exact offline-node claim selected in the devices window. ForgetNode { network_id: String, peer: String, expected_version: u64, }, /// Replace the network's enabled protocols in preference order. SetProtocols { network_id: String, protocols: Vec, }, /// Stop serving a network, or start serving it again. SetActive { network_id: String, active: bool }, /// Turn local broadcast participation on or off for a network. SetBroadcast { network_id: String, enabled: bool }, /// Offer this device as an exit node in a network, or stop. SetExitOffer { network_id: String, enabled: bool }, /// Send all this device's internet traffic through a member of a /// network, or (`None`) back the ordinary way. SetExitNode { network_id: String, peer: Option, }, /// Join a network, or start one already configured. Join { name: String, secret: String }, /// Leave a network entirely. Leave { network_id: String }, /// Change the hostname this device announces. SetHostname(String), /// Fetch a network's shared secret and place it on the clipboard. CopySecret { network_id: String }, } /// The latest the worker knows, read by the UI each frame. #[derive(Clone)] pub(crate) struct VipSaveResult { pub token: String, pub result: Result, String>, } #[derive(Clone, Default)] pub(crate) struct Snapshot { pub vip_result: Option, /// The last status, or the reason it could not be read (agent down, no /// permission on the socket, …). pub status: Option>, /// The outcome of the most recent command, for a transient banner. pub last_action: Option>, /// Whether a command is currently being executed. pub busy: bool, /// Bumped each time `status` is refreshed, so the UI can tell new data from /// a repaint of the same data and sample traffic rates only on change. pub generation: u64, /// When this status was read, for computing rates between refreshes. pub at: Option, /// The socket the last request went to. pub socket: PathBuf, } /// Handle the UI holds: send commands, read the latest snapshot. pub(crate) struct AgentClient { tx: mpsc::UnboundedSender, shared: Arc>, /// 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>>, } impl AgentClient { #[cfg(test)] pub(crate) fn test_client() -> (Self, mpsc::UnboundedReceiver) { let (tx, rx) = mpsc::unbounded_channel(); ( Self { tx, shared: Arc::new(Mutex::new(Snapshot::default())), pending_copy: Arc::new(Mutex::new(None)), }, rx, ) } /// 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 { 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(mutex: &Mutex) -> 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, shared: Arc>, pending_copy: Arc>>, 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>, 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); 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>, pending_copy: &Arc>>, ctx: &egui::Context, ) { lock(shared).busy = true; ctx.request_repaint(); let outcome: Result = 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::>() .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() }