Provide named VIPs with independent protocol/port listeners and node/port backends so applications can use one DNS endpoint without a separate load balancer. Every authenticated member may create, edit or delete any service. Client agents select the eligible backend with the lowest measured encrypted data-plane RTT, including relayed paths, and pin existing flows. UDP recovers on another backend after failure; established TCP is never replayed or moved. An unanswered empty TCP SYN may retry another backend before establishment. Keep signed multi-writer field registers in state/vip.rs. Independent backend edits merge, same-field conflicts use Lamport/author/canonical ordering, and listener generations prevent old backend entries returning on port recreation. Permanent service tombstones protect replay while allowing obsolete fields to be compacted. Active-service and deletion-history limits are separate. Commit complete snapshots and the author's durable counter atomically before local routing changes or publication. Restore counters from newer genuine author updates learned from replicas after an old backup is restored. Implement bounded client-side address/port NAT at overlay ingress and reverse translation only after authenticated source/destination admission. Reserve OS source ports to avoid direct-flow collisions and quarantine retired ports for late replies. Handle a backend on the client itself, scoped fragment assembly, checksums, re-fragmentation and quoted ICMP/PMTU headers. Plugins and encrypted transit retain their existing contracts. Data-path probes measure RTT; bounded fair TCP connect checks are enabled by default and configurable per listener. Arbitrary UDP application readiness remains unknown; path checks and explicit port errors drive eligibility without protocol-specific probe payloads. Expose the shared draft API through local IPC, simple vip/listener/backend CLI commands, JSON, editor-based atomic updates and watch output. Add a VIP button on each network tile and a separate tray editor. Edits and removals stay local until Save; stale revisions retain the draft, and closing a dirty window offers explicit discard. Report local routing choices, health reasons, RTT age, active and draining bindings, IP counters, rates, drops and UDP failovers. Extend DNS with service names; keep numeric addresses secondary and preserve existing bindings while VIP addresses or listeners change. This changes control wire ALPN/version to tsunagi/ctrl/8 and local IPC to 22; all members and local clients must upgrade together. Data ALPN remains 5. SQLite schema 10 migrates existing mandatory state without changing identity, secrets, network ids, derivation labels, handshake encoding or node records. Crate versions and release tags are unchanged. No installed agent or tray was replaced. Commands, limits and operational semantics are in docs/vip.md. Checks on Linux in nix develop: - cargo fmt --all -- --check - cargo clippy --locked --workspace --all-targets -- -D warnings - cargo test --locked --workspace --all-targets: 559 passed, 3 ignored - git diff --cached --check The full suite includes real encrypted TCP/UDP VIP traffic, backend-stop UDP failover, real loopback TCP check recovery, source admission, signed merges, stale/deleted state, SQLite migration and rollback, restart/author recovery, network isolation, actual CLI/DNS processes, and headless text-entry/Save-button interaction. Discovery and memory TUNs are the existing test substitutions; authentication, transport, encryption and SQLite remain real. Initial checks outside Nix failed for missing GTK pkg-config metadata, and an initial CLI test inherited TSUNAGI_CONTROL_SOCKET. Final checks use the Nix environment with that variable unset so tests address their temporary sockets. Root/internet-dependent tests remain ignored. No live host TUN, native desktop session, macOS or Windows validation was performed.
369 lines
13 KiB
Rust
369 lines
13 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::{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<String>,
|
|
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<String>,
|
|
},
|
|
/// 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<String>,
|
|
},
|
|
/// 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<Vec<tsunagi::vip::VipStatus>, String>,
|
|
}
|
|
#[derive(Clone, Default)]
|
|
pub(crate) struct Snapshot {
|
|
pub vip_result: Option<VipSaveResult>,
|
|
/// The last status, or the reason it could not be read (agent down, no
|
|
/// permission on the socket, …).
|
|
pub status: Option<Result<StatusReport, String>>,
|
|
/// The outcome of the most recent command, for a transient banner.
|
|
pub last_action: Option<Result<String, String>>,
|
|
/// 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<Instant>,
|
|
/// 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<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 {
|
|
#[cfg(test)]
|
|
pub(crate) fn test_client() -> (Self, mpsc::UnboundedReceiver<Command>) {
|
|
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<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);
|
|
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()
|
|
}
|