Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4dcdec662 | ||
|
|
69310108f4 | ||
|
|
e7dff34ec2 |
No files matched your search
+110
-17
@@ -838,6 +838,33 @@ enum Observed {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The directories the running agent uses, unless the user named some.
|
||||||
|
///
|
||||||
|
/// The control socket of a packaged service is found without flags, but the
|
||||||
|
/// state it keeps is not in this user's default directory — reading that
|
||||||
|
/// would report a device that has joined nothing next to an agent that has
|
||||||
|
/// joined a network. The agent knows where its state is, so it is asked.
|
||||||
|
async fn agent_paths(
|
||||||
|
paths: StoragePaths,
|
||||||
|
socket: &std::path::Path,
|
||||||
|
is_custom_state: bool,
|
||||||
|
) -> StoragePaths {
|
||||||
|
if is_custom_state || !tsunagi::ipc::is_serving(socket).await {
|
||||||
|
return paths;
|
||||||
|
}
|
||||||
|
match tsunagi::ipc::request_status(socket).await {
|
||||||
|
Ok(report) if !report.state_dir.is_empty() => {
|
||||||
|
let cache = if report.cache_dir.is_empty() {
|
||||||
|
paths.cache_dir
|
||||||
|
} else {
|
||||||
|
PathBuf::from(report.cache_dir)
|
||||||
|
};
|
||||||
|
StoragePaths::new(report.state_dir, cache)
|
||||||
|
}
|
||||||
|
_ => paths,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Asks the agent, and falls back to the state store.
|
/// Asks the agent, and falls back to the state store.
|
||||||
async fn observe(paths: &StoragePaths, socket: &std::path::Path) -> Observed {
|
async fn observe(paths: &StoragePaths, socket: &std::path::Path) -> Observed {
|
||||||
let socket_present = tsunagi::ipc::is_serving(socket).await;
|
let socket_present = tsunagi::ipc::is_serving(socket).await;
|
||||||
@@ -1374,6 +1401,7 @@ impl tsunagi::ipc::ReportSource for AgentControl {
|
|||||||
self.plugin.as_deref(),
|
self.plugin.as_deref(),
|
||||||
self.tcp_tls.as_deref(),
|
self.tcp_tls.as_deref(),
|
||||||
dns,
|
dns,
|
||||||
|
&self.paths,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
})
|
})
|
||||||
@@ -1667,6 +1695,7 @@ async fn network_command(args: NetworkArgs) -> Result<(), Box<dyn std::error::Er
|
|||||||
let paths = args.paths.resolve()?;
|
let paths = args.paths.resolve()?;
|
||||||
let is_custom_state = args.paths.state_dir.is_some();
|
let is_custom_state = args.paths.state_dir.is_some();
|
||||||
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
||||||
|
let paths = agent_paths(paths, &socket, is_custom_state).await;
|
||||||
match args.action {
|
match args.action {
|
||||||
None => show_networks(&paths, &socket).await,
|
None => show_networks(&paths, &socket).await,
|
||||||
Some(NetworkAction::Broadcast { network, choice }) => {
|
Some(NetworkAction::Broadcast { network, choice }) => {
|
||||||
@@ -1702,6 +1731,7 @@ async fn join_command(args: JoinArgs) -> Result<(), Box<dyn std::error::Error>>
|
|||||||
let paths = args.paths.resolve()?;
|
let paths = args.paths.resolve()?;
|
||||||
let is_custom_state = args.paths.state_dir.is_some();
|
let is_custom_state = args.paths.state_dir.is_some();
|
||||||
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
||||||
|
let paths = agent_paths(paths, &socket, is_custom_state).await;
|
||||||
let name = NetworkName::new(args.network)?;
|
let name = NetworkName::new(args.network)?;
|
||||||
// A name this device already has means that network; a name nobody
|
// A name this device already has means that network; a name nobody
|
||||||
// has means a new one, and no secret is needed to make a network with
|
// has means a new one, and no secret is needed to make a network with
|
||||||
@@ -1861,16 +1891,15 @@ async fn show_networks(
|
|||||||
use report::{Health, Report, Row, Section};
|
use report::{Health, Report, Row, Section};
|
||||||
|
|
||||||
let stored = stored_networks(paths);
|
let stored = stored_networks(paths);
|
||||||
if stored.is_empty() {
|
|
||||||
eprintln!("no network has been joined");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let observed = observe(paths, socket).await;
|
let observed = observe(paths, socket).await;
|
||||||
let live = match &observed {
|
let live = match &observed {
|
||||||
Observed::Agent(report) => report.networks.clone(),
|
Observed::Agent(report) => report.networks.clone(),
|
||||||
Observed::Stored { .. } => Vec::new(),
|
Observed::Stored { .. } => Vec::new(),
|
||||||
};
|
};
|
||||||
|
if stored.is_empty() && live.is_empty() {
|
||||||
|
eprintln!("no network has been joined");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
let mut out = Report::new();
|
let mut out = Report::new();
|
||||||
let mut section = Section::new("networks");
|
let mut section = Section::new("networks");
|
||||||
@@ -1921,6 +1950,20 @@ async fn show_networks(
|
|||||||
.with_note(note),
|
.with_note(note),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// What the agent runs but this process could not read from the store,
|
||||||
|
// for instance when the state is not readable by this user.
|
||||||
|
for network in live.iter().filter(|live| {
|
||||||
|
!stored
|
||||||
|
.iter()
|
||||||
|
.any(|n| n.network_id.to_string() == live.network_id)
|
||||||
|
}) {
|
||||||
|
let state = if network.active { "running" } else { "stopped" };
|
||||||
|
section.push(Row::new(
|
||||||
|
Health::Info,
|
||||||
|
network.name.clone(),
|
||||||
|
format!("{} · {state}", network.network_id),
|
||||||
|
));
|
||||||
|
}
|
||||||
out.push(section);
|
out.push(section);
|
||||||
print_report("tsunagi networks", &out)
|
print_report("tsunagi networks", &out)
|
||||||
}
|
}
|
||||||
@@ -2163,6 +2206,7 @@ async fn dns_command(args: DnsArgs) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let paths = args.paths.resolve()?;
|
let paths = args.paths.resolve()?;
|
||||||
let is_custom_state = args.paths.state_dir.is_some();
|
let is_custom_state = args.paths.state_dir.is_some();
|
||||||
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
||||||
|
let paths = agent_paths(paths, &socket, is_custom_state).await;
|
||||||
|
|
||||||
let enable = match args.action {
|
let enable = match args.action {
|
||||||
None => return show_dns(&paths, &socket).await,
|
None => return show_dns(&paths, &socket).await,
|
||||||
@@ -2256,6 +2300,7 @@ async fn id(args: IdArgs) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let paths = args.paths.resolve()?;
|
let paths = args.paths.resolve()?;
|
||||||
let is_custom_state = args.paths.state_dir.is_some();
|
let is_custom_state = args.paths.state_dir.is_some();
|
||||||
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
||||||
|
let paths = agent_paths(paths, &socket, is_custom_state).await;
|
||||||
|
|
||||||
match args.action {
|
match args.action {
|
||||||
None => show_identity(&paths, &socket).await,
|
None => show_identity(&paths, &socket).await,
|
||||||
@@ -2448,6 +2493,7 @@ async fn status(args: StatusArgs) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let paths = args.paths.resolve()?;
|
let paths = args.paths.resolve()?;
|
||||||
let is_custom_state = args.paths.state_dir.is_some();
|
let is_custom_state = args.paths.state_dir.is_some();
|
||||||
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
let socket = control_socket(&paths, args.control_socket.as_ref(), is_custom_state);
|
||||||
|
let paths = agent_paths(paths, &socket, is_custom_state).await;
|
||||||
let observed = observe(&paths, &socket).await;
|
let observed = observe(&paths, &socket).await;
|
||||||
|
|
||||||
let mut out = Report::new();
|
let mut out = Report::new();
|
||||||
@@ -2519,7 +2565,7 @@ async fn status(args: StatusArgs) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
out.push(host_section());
|
out.push(host_section(&observed));
|
||||||
out.push(addresses_section().await);
|
out.push(addresses_section().await);
|
||||||
print_report("tsunagi status", &out)
|
print_report("tsunagi status", &out)
|
||||||
}
|
}
|
||||||
@@ -2631,10 +2677,8 @@ impl MemberRow<'_> {
|
|||||||
self.transport.is_some()
|
self.transport.is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What to call it: the name it announced, or a short form of its id.
|
/// What to call it: the name it announced — the last one, when it is
|
||||||
///
|
/// away — or a short form of its id.
|
||||||
/// A member that is away has no hostname, because nothing durable records
|
|
||||||
/// one — only the signed claim survives, and that carries an address.
|
|
||||||
fn label(&self) -> String {
|
fn label(&self) -> String {
|
||||||
match self.hostname {
|
match self.hostname {
|
||||||
Some(hostname) => hostname.to_string(),
|
Some(hostname) => hostname.to_string(),
|
||||||
@@ -2667,10 +2711,11 @@ fn member_rows<'a>(network: &'a tsunagi::ipc::NetworkReport, own_id: &str) -> Ve
|
|||||||
let row = entry(&mut rows, &member.endpoint_id);
|
let row = entry(&mut rows, &member.endpoint_id);
|
||||||
row.overlay_address_v4 = member.overlay_address_v4.as_deref();
|
row.overlay_address_v4 = member.overlay_address_v4.as_deref();
|
||||||
row.failed_dials = member.failed_dials;
|
row.failed_dials = member.failed_dials;
|
||||||
|
row.hostname = member.hostname.as_deref();
|
||||||
}
|
}
|
||||||
for peer in &network.peers {
|
for peer in &network.peers {
|
||||||
let row = entry(&mut rows, &peer.endpoint_id);
|
let row = entry(&mut rows, &peer.endpoint_id);
|
||||||
row.hostname = peer.hostname.as_deref();
|
row.hostname = peer.hostname.as_deref().or(row.hostname);
|
||||||
row.transport = Some(&peer.transport);
|
row.transport = Some(&peer.transport);
|
||||||
row.rtt_ms = peer.rtt_ms;
|
row.rtt_ms = peer.rtt_ms;
|
||||||
}
|
}
|
||||||
@@ -3001,7 +3046,11 @@ fn short(text: &str, len: usize) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// What this host can and cannot do for the data plane.
|
/// What this host can and cannot do for the data plane.
|
||||||
fn host_section() -> report::Section {
|
///
|
||||||
|
/// The interface is created by the agent, so when one answered, its own
|
||||||
|
/// report of whether it may do that is the answer; what this process holds
|
||||||
|
/// says nothing about it.
|
||||||
|
fn host_section(observed: &Observed) -> report::Section {
|
||||||
use report::{Health, Row, Section};
|
use report::{Health, Row, Section};
|
||||||
|
|
||||||
let mut host = Section::new("host");
|
let mut host = Section::new("host");
|
||||||
@@ -3041,8 +3090,20 @@ fn host_section() -> report::Section {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
use tsunagi::ipc::PrivilegeReport;
|
||||||
use tsunagi::overlay::{Privilege, probe_net_admin};
|
use tsunagi::overlay::{Privilege, probe_net_admin};
|
||||||
match probe_net_admin() {
|
let (privilege, program) = match observed {
|
||||||
|
Observed::Agent(report) => match &report.privilege {
|
||||||
|
PrivilegeReport::Unknown => (probe_net_admin(), program_path()),
|
||||||
|
PrivilegeReport::Available => (Privilege::Available, report.program.clone()),
|
||||||
|
PrivilegeReport::Missing(reason) => {
|
||||||
|
(Privilege::Missing(reason.clone()), report.program.clone())
|
||||||
|
}
|
||||||
|
PrivilegeReport::Unsupported => (Privilege::Unsupported, report.program.clone()),
|
||||||
|
},
|
||||||
|
Observed::Stored { .. } => (probe_net_admin(), program_path()),
|
||||||
|
};
|
||||||
|
match privilege {
|
||||||
Privilege::Available => {
|
Privilege::Available => {
|
||||||
let held = if cfg!(target_os = "windows") {
|
let held = if cfg!(target_os = "windows") {
|
||||||
"assumes an elevated process; creation reports if not"
|
"assumes an elevated process; creation reports if not"
|
||||||
@@ -3062,10 +3123,7 @@ fn host_section() -> report::Section {
|
|||||||
// the eye is meant to scan.
|
// the eye is meant to scan.
|
||||||
host.push(
|
host.push(
|
||||||
Row::new(Health::Degraded, "privileges", "CAP_NET_ADMIN not held").with_note(
|
Row::new(Health::Degraded, "privileges", "CAP_NET_ADMIN not held").with_note(
|
||||||
format!(
|
format!("sudo setcap cap_net_admin,cap_net_bind_service+p {program}"),
|
||||||
"sudo setcap cap_net_admin,cap_net_bind_service+p {}",
|
|
||||||
program_path()
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
host.push(Row::new(
|
host.push(Row::new(
|
||||||
@@ -3990,6 +4048,7 @@ async fn build_report(
|
|||||||
wireguard: Option<&WireguardPlugin>,
|
wireguard: Option<&WireguardPlugin>,
|
||||||
tcp_tls: Option<&TcpTlsPlugin>,
|
tcp_tls: Option<&TcpTlsPlugin>,
|
||||||
dns: Option<DnsState>,
|
dns: Option<DnsState>,
|
||||||
|
paths: &StoragePaths,
|
||||||
) -> tsunagi::ipc::StatusReport {
|
) -> tsunagi::ipc::StatusReport {
|
||||||
use tsunagi::ipc::{
|
use tsunagi::ipc::{
|
||||||
MemberReport, NetworkReport, OverlayPeerReport, OverlayReport, PeerReport, StatusReport,
|
MemberReport, NetworkReport, OverlayPeerReport, OverlayReport, PeerReport, StatusReport,
|
||||||
@@ -4250,6 +4309,10 @@ async fn build_report(
|
|||||||
.iter()
|
.iter()
|
||||||
.find(|candidate| candidate.endpoint_id == member.endpoint_id)
|
.find(|candidate| candidate.endpoint_id == member.endpoint_id)
|
||||||
.map_or(0, |candidate| candidate.consecutive_failures),
|
.map_or(0, |candidate| candidate.consecutive_failures),
|
||||||
|
hostname: member
|
||||||
|
.last_hostname
|
||||||
|
.clone()
|
||||||
|
.or_else(|| member.hostname.clone()),
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
range: network.range.map(|range| range.to_string()),
|
range: network.range.map(|range| range.to_string()),
|
||||||
@@ -4276,6 +4339,16 @@ async fn build_report(
|
|||||||
cache_healthy: status.cache_healthy,
|
cache_healthy: status.cache_healthy,
|
||||||
networks,
|
networks,
|
||||||
dns,
|
dns,
|
||||||
|
state_dir: paths.state_dir.display().to_string(),
|
||||||
|
cache_dir: paths.cache_dir.display().to_string(),
|
||||||
|
program: program_path(),
|
||||||
|
privilege: match tsunagi::overlay::probe_net_admin() {
|
||||||
|
tsunagi::overlay::Privilege::Available => tsunagi::ipc::PrivilegeReport::Available,
|
||||||
|
tsunagi::overlay::Privilege::Missing(reason) => {
|
||||||
|
tsunagi::ipc::PrivilegeReport::Missing(reason)
|
||||||
|
}
|
||||||
|
tsunagi::overlay::Privilege::Unsupported => tsunagi::ipc::PrivilegeReport::Unsupported,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4577,11 +4650,13 @@ mod status_tests {
|
|||||||
endpoint_id: OWN.into(),
|
endpoint_id: OWN.into(),
|
||||||
overlay_address_v4: Some("10.13.37.69".into()),
|
overlay_address_v4: Some("10.13.37.69".into()),
|
||||||
failed_dials: 0,
|
failed_dials: 0,
|
||||||
|
hostname: None,
|
||||||
},
|
},
|
||||||
MemberReport {
|
MemberReport {
|
||||||
endpoint_id: ONLINE.into(),
|
endpoint_id: ONLINE.into(),
|
||||||
overlay_address_v4: Some("10.13.37.237".into()),
|
overlay_address_v4: Some("10.13.37.237".into()),
|
||||||
failed_dials: 0,
|
failed_dials: 0,
|
||||||
|
hostname: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
range: Some("10.13.37.0/24".into()),
|
range: Some("10.13.37.0/24".into()),
|
||||||
@@ -4822,6 +4897,7 @@ mod status_tests {
|
|||||||
endpoint_id: AWAY.into(),
|
endpoint_id: AWAY.into(),
|
||||||
overlay_address_v4: Some("10.13.37.99".into()),
|
overlay_address_v4: Some("10.13.37.99".into()),
|
||||||
failed_dials: 9,
|
failed_dials: 9,
|
||||||
|
hostname: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let rows = member_rows(&network, OWN);
|
let rows = member_rows(&network, OWN);
|
||||||
@@ -4831,6 +4907,22 @@ mod status_tests {
|
|||||||
assert_eq!(rows[1].endpoint_id, AWAY);
|
assert_eq!(rows[1].endpoint_id, AWAY);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_offline_member_keeps_the_last_name_it_announced() {
|
||||||
|
let mut network = network_after_a_peer_returned();
|
||||||
|
network.members.push(MemberReport {
|
||||||
|
endpoint_id: AWAY.into(),
|
||||||
|
overlay_address_v4: Some("10.13.37.99".into()),
|
||||||
|
failed_dials: 0,
|
||||||
|
hostname: Some("laptop".into()),
|
||||||
|
});
|
||||||
|
|
||||||
|
let rows = member_rows(&network, OWN);
|
||||||
|
let away = rows.iter().find(|row| row.endpoint_id == AWAY).unwrap();
|
||||||
|
assert!(!away.online());
|
||||||
|
assert_eq!(away.label(), "laptop");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_member_that_is_away_is_stated_rather_than_flagged() {
|
fn a_member_that_is_away_is_stated_rather_than_flagged() {
|
||||||
// In a mesh of laptops a member being away is the ordinary
|
// In a mesh of laptops a member being away is the ordinary
|
||||||
@@ -4842,6 +4934,7 @@ mod status_tests {
|
|||||||
endpoint_id: AWAY.into(),
|
endpoint_id: AWAY.into(),
|
||||||
overlay_address_v4: Some("10.13.37.99".into()),
|
overlay_address_v4: Some("10.13.37.99".into()),
|
||||||
failed_dials: 9,
|
failed_dials: 9,
|
||||||
|
hostname: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut out = report::Report::new();
|
let mut out = report::Report::new();
|
||||||
|
|||||||
@@ -27,13 +27,14 @@ tracing-subscriber.workspace = true
|
|||||||
egui-phosphor = "0.9"
|
egui-phosphor = "0.9"
|
||||||
|
|
||||||
# Linux only: tray-icon (already GTK-based there) needs the app to initialise
|
# Linux only: tray-icon (already GTK-based there) needs the app to initialise
|
||||||
# GTK and run its main loop, which eframe/winit do not do.
|
# GTK and run its main loop.
|
||||||
[target.'cfg(target_os = "linux")'.dependencies]
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
gtk = "0.18"
|
gtk = "0.18"
|
||||||
|
|
||||||
# macOS only: set the app's activation policy to Accessory so it lives in the
|
# Windows and macOS: the tray process has no GUI toolkit, only an event loop to
|
||||||
# menu bar with no Dock icon. Pinned to eframe's winit so the types unify.
|
# serve the icon (and, on macOS, the Accessory activation policy that keeps it
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
# out of the Dock). Pinned to eframe's winit so the types unify.
|
||||||
|
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]
|
||||||
winit = "0.30"
|
winit = "0.30"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
//! The eframe application: wires the tray, the main window, the per-network
|
//! The eframe application behind the window: the main view, the per-network
|
||||||
//! devices windows, and the agent worker.
|
//! devices windows, and the agent worker.
|
||||||
|
//!
|
||||||
|
//! It runs in its own process, started by the tray when the user chooses Open
|
||||||
|
//! and gone when the window is closed. The tray, which has to outlive the
|
||||||
|
//! window, lives in the other process; see [`crate::tray`].
|
||||||
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -8,24 +12,20 @@ use eframe::egui;
|
|||||||
use crate::agent::{AgentClient, resolve_socket};
|
use crate::agent::{AgentClient, resolve_socket};
|
||||||
use crate::devices;
|
use crate::devices;
|
||||||
use crate::stats::Traffic;
|
use crate::stats::Traffic;
|
||||||
use crate::tray::{Action, Tray};
|
|
||||||
use crate::ui::{self, UiState};
|
use crate::ui::{self, UiState};
|
||||||
|
|
||||||
/// The tray application state.
|
/// The window's state.
|
||||||
pub(crate) struct App {
|
pub(crate) struct App {
|
||||||
agent: AgentClient,
|
agent: AgentClient,
|
||||||
tray: Tray,
|
|
||||||
state: UiState,
|
state: UiState,
|
||||||
/// Traffic rates derived from successive snapshots.
|
/// Traffic rates derived from successive snapshots.
|
||||||
traffic: Traffic,
|
traffic: Traffic,
|
||||||
/// The snapshot generation last folded into `traffic`.
|
/// The snapshot generation last folded into `traffic`.
|
||||||
sampled: u64,
|
sampled: u64,
|
||||||
/// Set when the user chose Quit, so the next close exits rather than hides.
|
|
||||||
quitting: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
/// Builds the app: resolves the socket, starts the worker, creates the tray.
|
/// Builds the app: resolves the socket and starts the worker.
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
cc: &eframe::CreationContext<'_>,
|
cc: &eframe::CreationContext<'_>,
|
||||||
runtime: tokio::runtime::Handle,
|
runtime: tokio::runtime::Handle,
|
||||||
@@ -37,40 +37,18 @@ impl App {
|
|||||||
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
|
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
|
||||||
ctx.set_fonts(fonts);
|
ctx.set_fonts(fonts);
|
||||||
|
|
||||||
let agent = AgentClient::spawn(&runtime, ctx.clone(), resolve_socket());
|
let agent = AgentClient::spawn(&runtime, ctx, resolve_socket());
|
||||||
let tray = Tray::new(ctx)?;
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
agent,
|
agent,
|
||||||
tray,
|
|
||||||
state: UiState::default(),
|
state: UiState::default(),
|
||||||
traffic: Traffic::default(),
|
traffic: Traffic::default(),
|
||||||
sampled: 0,
|
sampled: 0,
|
||||||
quitting: false,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl eframe::App for App {
|
impl eframe::App for App {
|
||||||
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||||
for action in self.tray.poll() {
|
|
||||||
match action {
|
|
||||||
Action::Open => {
|
|
||||||
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
|
|
||||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
|
||||||
}
|
|
||||||
Action::Quit => {
|
|
||||||
self.quitting = true;
|
|
||||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Closing the main window hides it to the tray; only Quit truly exits.
|
|
||||||
if ctx.input(|i| i.viewport().close_requested()) && !self.quitting {
|
|
||||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
|
||||||
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
|
|
||||||
}
|
|
||||||
|
|
||||||
let snapshot = self.agent.snapshot();
|
let snapshot = self.agent.snapshot();
|
||||||
if snapshot.generation != self.sampled
|
if snapshot.generation != self.sampled
|
||||||
&& let (Some(Ok(report)), Some(at)) = (&snapshot.status, snapshot.at)
|
&& let (Some(Ok(report)), Some(at)) = (&snapshot.status, snapshot.at)
|
||||||
@@ -88,7 +66,7 @@ impl eframe::App for App {
|
|||||||
ctx.copy_text(secret);
|
ctx.copy_text(secret);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keep ticking so fresh status and tray actions are picked up.
|
// Keep ticking so fresh status is picked up.
|
||||||
ctx.request_repaint_after(Duration::from_millis(500));
|
ctx.request_repaint_after(Duration::from_millis(500));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -117,7 +95,7 @@ impl App {
|
|||||||
// main window's stay in step.
|
// main window's stay in step.
|
||||||
let unit = &mut self.state.unit;
|
let unit = &mut self.state.unit;
|
||||||
let keep = ctx.show_viewport_immediate(viewport_id, builder, |vctx, _class| {
|
let keep = ctx.show_viewport_immediate(viewport_id, builder, |vctx, _class| {
|
||||||
devices::show(vctx, agent, unit, network, traffic);
|
devices::show(vctx, agent, unit, network, &report.endpoint_id, traffic);
|
||||||
!vctx.input(|i| i.viewport().close_requested())
|
!vctx.input(|i| i.viewport().close_requested())
|
||||||
});
|
});
|
||||||
if !keep {
|
if !keep {
|
||||||
|
|||||||
@@ -23,22 +23,51 @@ pub(crate) fn title(network: &NetworkReport) -> String {
|
|||||||
/// One row of the device table, built from a tunnel and/or a signed member.
|
/// One row of the device table, built from a tunnel and/or a signed member.
|
||||||
struct Device<'a> {
|
struct Device<'a> {
|
||||||
online: bool,
|
online: bool,
|
||||||
name: String,
|
/// The last hostname seen for it, kept while it is offline.
|
||||||
/// What clicking the name copies: `hostname.network` so it resolves, or
|
hostname: Option<&'a str>,
|
||||||
/// the short id when there is no hostname.
|
/// What clicking the hostname copies: `hostname.network`, so it resolves.
|
||||||
copy: String,
|
copy: Option<String>,
|
||||||
|
/// The full endpoint id, which clicking the short form copies.
|
||||||
|
id: &'a str,
|
||||||
proto: &'a str,
|
proto: &'a str,
|
||||||
address: Option<String>,
|
address: Option<String>,
|
||||||
handshake_secs: Option<u64>,
|
handshake_secs: Option<u64>,
|
||||||
overlay: Option<&'a OverlayPeerReport>,
|
overlay: Option<&'a OverlayPeerReport>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Device<'_> {
|
||||||
|
fn sort_key(&self) -> String {
|
||||||
|
self.hostname.unwrap_or(self.id).to_lowercase()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first characters of an endpoint id, enough to tell devices apart.
|
||||||
|
fn short_id(id: &str) -> String {
|
||||||
|
id.chars().take(5).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The device cell: the hostname and, in brackets, the start of the id.
|
||||||
|
/// Clicking either copies its own full value.
|
||||||
|
fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = 4.0;
|
||||||
|
match (device.hostname, &device.copy) {
|
||||||
|
(Some(hostname), Some(copy)) => {
|
||||||
|
format::copy_field(ui, hostname, copy);
|
||||||
|
format::copy_field(ui, &format!("({})", short_id(device.id)), device.id);
|
||||||
|
}
|
||||||
|
_ => format::copy_field(ui, &short_id(device.id), device.id),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// Draws the window body into its viewport.
|
/// Draws the window body into its viewport.
|
||||||
pub(crate) fn show(
|
pub(crate) fn show(
|
||||||
ctx: &egui::Context,
|
ctx: &egui::Context,
|
||||||
_agent: &AgentClient,
|
_agent: &AgentClient,
|
||||||
unit: &mut Unit,
|
unit: &mut Unit,
|
||||||
network: &NetworkReport,
|
network: &NetworkReport,
|
||||||
|
own_id: &str,
|
||||||
traffic: &Traffic,
|
traffic: &Traffic,
|
||||||
) {
|
) {
|
||||||
egui::CentralPanel::default().show(ctx, |ui| {
|
egui::CentralPanel::default().show(ctx, |ui| {
|
||||||
@@ -60,7 +89,7 @@ pub(crate) fn show(
|
|||||||
format::sparkline(ui, traffic.network(&network.network_id), unit, 48.0);
|
format::sparkline(ui, traffic.network(&network.network_id), unit, 48.0);
|
||||||
ui.add_space(8.0);
|
ui.add_space(8.0);
|
||||||
|
|
||||||
let devices = devices(network);
|
let devices = devices(network, own_id);
|
||||||
let online = devices.iter().filter(|d| d.online).count();
|
let online = devices.iter().filter(|d| d.online).count();
|
||||||
ui.label(
|
ui.label(
|
||||||
egui::RichText::new(format!(
|
egui::RichText::new(format!(
|
||||||
@@ -123,31 +152,56 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Every other device this network knows of, from a live tunnel or the signed
|
||||||
|
/// membership. This device is in the roster too but is not one of the others.
|
||||||
|
fn known_ids<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<&'a str> {
|
||||||
|
let overlay_peers = network
|
||||||
|
.overlay
|
||||||
|
.as_ref()
|
||||||
|
.map(|o| o.peers.as_slice())
|
||||||
|
.unwrap_or(&[]);
|
||||||
|
let mut ids: Vec<&str> = Vec::new();
|
||||||
|
let candidates = overlay_peers
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.endpoint_id.as_str())
|
||||||
|
.chain(network.peers.iter().map(|p| p.endpoint_id.as_str()))
|
||||||
|
.chain(network.members.iter().map(|m| m.endpoint_id.as_str()));
|
||||||
|
for id in candidates {
|
||||||
|
if id != own_id && !ids.contains(&id) {
|
||||||
|
ids.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ids
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many other devices this network knows of, connected or not.
|
||||||
|
pub(crate) fn known_count(network: &NetworkReport, own_id: &str) -> usize {
|
||||||
|
known_ids(network, own_id).len()
|
||||||
|
}
|
||||||
|
|
||||||
/// Builds the device list: every endpoint known from a live tunnel or the
|
/// Builds the device list: every endpoint known from a live tunnel or the
|
||||||
/// signed membership, online ones first.
|
/// signed membership, online ones first.
|
||||||
fn devices(network: &NetworkReport) -> Vec<Device<'_>> {
|
fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
|
||||||
let hostnames: HashMap<&str, &str> = network
|
// The signed members carry the last name seen, so a device that is away
|
||||||
.peers
|
// is still called by it; a live announcement is fresher and wins.
|
||||||
|
let mut hostnames: HashMap<&str, &str> = network
|
||||||
|
.members
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|p| p.hostname.as_deref().map(|h| (p.endpoint_id.as_str(), h)))
|
.filter_map(|m| m.hostname.as_deref().map(|h| (m.endpoint_id.as_str(), h)))
|
||||||
.collect();
|
.collect();
|
||||||
|
hostnames.extend(
|
||||||
|
network
|
||||||
|
.peers
|
||||||
|
.iter()
|
||||||
|
.filter_map(|p| p.hostname.as_deref().map(|h| (p.endpoint_id.as_str(), h))),
|
||||||
|
);
|
||||||
let overlay_peers = network
|
let overlay_peers = network
|
||||||
.overlay
|
.overlay
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|o| o.peers.as_slice())
|
.map(|o| o.peers.as_slice())
|
||||||
.unwrap_or(&[]);
|
.unwrap_or(&[]);
|
||||||
|
|
||||||
let mut ids: Vec<&str> = Vec::new();
|
let ids = known_ids(network, own_id);
|
||||||
for peer in overlay_peers {
|
|
||||||
if !ids.contains(&peer.endpoint_id.as_str()) {
|
|
||||||
ids.push(&peer.endpoint_id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for member in &network.members {
|
|
||||||
if !ids.contains(&member.endpoint_id.as_str()) {
|
|
||||||
ids.push(&member.endpoint_id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut devices: Vec<Device> = ids
|
let mut devices: Vec<Device> = ids
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -156,15 +210,11 @@ fn devices(network: &NetworkReport) -> Vec<Device<'_>> {
|
|||||||
let member = network.members.iter().find(|m| m.endpoint_id == id);
|
let member = network.members.iter().find(|m| m.endpoint_id == id);
|
||||||
let online = overlay.is_some_and(|p| p.handshake_secs_ago.is_some());
|
let online = overlay.is_some_and(|p| p.handshake_secs_ago.is_some());
|
||||||
let hostname = hostnames.get(id).copied();
|
let hostname = hostnames.get(id).copied();
|
||||||
let name = hostname.map_or_else(
|
|
||||||
|| format::short(overlay.map_or(id, |p| p.public_key.as_str())),
|
|
||||||
str::to_string,
|
|
||||||
);
|
|
||||||
let copy = hostname.map_or_else(|| name.clone(), |h| format!("{h}.{}", network.name));
|
|
||||||
Device {
|
Device {
|
||||||
online,
|
online,
|
||||||
name,
|
hostname,
|
||||||
copy,
|
copy: hostname.map(|h| format!("{h}.{}", network.name)),
|
||||||
|
id,
|
||||||
proto: overlay.map_or("—", |p| p.protocol.as_str()),
|
proto: overlay.map_or("—", |p| p.protocol.as_str()),
|
||||||
address: overlay
|
address: overlay
|
||||||
.and_then(|p| p.address.clone())
|
.and_then(|p| p.address.clone())
|
||||||
@@ -178,7 +228,7 @@ fn devices(network: &NetworkReport) -> Vec<Device<'_>> {
|
|||||||
devices.sort_by(|a, b| {
|
devices.sort_by(|a, b| {
|
||||||
b.online
|
b.online
|
||||||
.cmp(&a.online)
|
.cmp(&a.online)
|
||||||
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
|
.then_with(|| a.sort_key().cmp(&b.sort_key()))
|
||||||
});
|
});
|
||||||
devices
|
devices
|
||||||
}
|
}
|
||||||
@@ -216,7 +266,7 @@ fn device_table(
|
|||||||
ui.end_row();
|
ui.end_row();
|
||||||
|
|
||||||
for device in devices {
|
for device in devices {
|
||||||
format::copy_field(ui, &device.name, &device.copy);
|
name_cell(ui, device);
|
||||||
ui.label(device.proto);
|
ui.label(device.proto);
|
||||||
match &device.address {
|
match &device.address {
|
||||||
Some(address) => format::copy_field(ui, address, address),
|
Some(address) => format::copy_field(ui, address, address),
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
//! Tray application for managing a running tsunagi agent.
|
//! Tray application for managing a running tsunagi agent.
|
||||||
//!
|
//!
|
||||||
//! A small window (networks, their peers and addresses, join/leave, per-network
|
//! A tray icon and menu (Open, Quit) that opens a small window (networks, their
|
||||||
//! active and broadcast switches) plus a tray menu (Open, Quit). It is a thin
|
//! peers and addresses, join/leave, per-network active and broadcast switches).
|
||||||
//! client over the agent's local control socket — the same interface the CLI
|
//! There is no window until Open, and closing it leaves the icon. The window
|
||||||
//! uses — and owns its own runtime, logger and event loop, like the CLI binary.
|
//! is a thin client over the agent's local control socket — the same interface
|
||||||
|
//! the CLI uses.
|
||||||
|
|
||||||
// The window is created hidden-to-tray on close rather than exiting; the binary
|
// Nothing here is a library.
|
||||||
// itself may exit on Quit. Nothing here is a library.
|
|
||||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
mod agent;
|
mod agent;
|
||||||
@@ -21,38 +21,42 @@ use eframe::egui;
|
|||||||
|
|
||||||
use crate::app::App;
|
use crate::app::App;
|
||||||
|
|
||||||
|
/// The argument that makes this binary the window rather than the tray.
|
||||||
|
const WINDOW_ARG: &str = "--window";
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));
|
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));
|
||||||
let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init();
|
let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init();
|
||||||
|
|
||||||
|
// Two processes from one binary. The tray is what stays; the window is
|
||||||
|
// started by it and ends when it is closed. A window that merely hides is
|
||||||
|
// not something every platform can do — Wayland has no such thing — and a
|
||||||
|
// hidden one that stays is worse than none.
|
||||||
|
if std::env::args().any(|arg| arg == WINDOW_ARG) {
|
||||||
|
window()
|
||||||
|
} else {
|
||||||
|
tray::run()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the window until it is closed.
|
||||||
|
fn window() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||||
.enable_all()
|
.enable_all()
|
||||||
.build()?;
|
.build()?;
|
||||||
let handle = runtime.handle().clone();
|
let handle = runtime.handle().clone();
|
||||||
|
|
||||||
#[cfg_attr(not(target_os = "macos"), expect(unused_mut))]
|
let options = eframe::NativeOptions {
|
||||||
let mut options = eframe::NativeOptions {
|
|
||||||
// A fixed, small window; the whole layout targets this size.
|
// A fixed, small window; the whole layout targets this size.
|
||||||
viewport: egui::ViewportBuilder::default()
|
viewport: egui::ViewportBuilder::default()
|
||||||
.with_title("tsunagi")
|
.with_title("tsunagi")
|
||||||
|
.with_app_id("tsunagi")
|
||||||
.with_inner_size([360.0, 600.0])
|
.with_inner_size([360.0, 600.0])
|
||||||
.with_resizable(false)
|
.with_resizable(false),
|
||||||
// Start hidden: the app lives in the tray and the window opens from
|
|
||||||
// the menu.
|
|
||||||
.with_visible(false),
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
// macOS: live in the menu bar with no Dock icon (tray-only).
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
{
|
|
||||||
options.event_loop_builder = Some(Box::new(|builder| {
|
|
||||||
use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
|
|
||||||
builder.with_activation_policy(ActivationPolicy::Accessory);
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
eframe::run_native(
|
eframe::run_native(
|
||||||
"tsunagi",
|
"tsunagi",
|
||||||
options,
|
options,
|
||||||
@@ -63,7 +67,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
}),
|
}),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// The window loop has ended (Quit); let the runtime wind down.
|
// The window loop has ended; let the runtime wind down.
|
||||||
drop(runtime);
|
drop(runtime);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
+123
-83
@@ -1,31 +1,55 @@
|
|||||||
//! The tray icon and its menu.
|
//! The tray: the icon, its menu, and starting the window.
|
||||||
//!
|
//!
|
||||||
//! The menu is just Open and Quit; everything else (per-network switches,
|
//! This is the process that stays. It holds no window and no GUI toolkit of
|
||||||
//! join/leave) lives in the window. Menu clicks are read on a background
|
//! its own; choosing Open starts this same binary again as the window, which
|
||||||
//! thread and turned into [`Action`]s, so they are handled even while the
|
//! is a perfectly ordinary program that ends when it is closed.
|
||||||
//! window is hidden and egui would otherwise not be repainting.
|
|
||||||
|
|
||||||
use std::sync::mpsc;
|
use std::process::{Child, Command};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use eframe::egui;
|
|
||||||
use tray_icon::menu::{Menu, MenuEvent, MenuId, MenuItem, PredefinedMenuItem};
|
use tray_icon::menu::{Menu, MenuEvent, MenuId, MenuItem, PredefinedMenuItem};
|
||||||
use tray_icon::{Icon, TrayIcon, TrayIconBuilder};
|
use tray_icon::{Icon, TrayIcon, TrayIconBuilder};
|
||||||
|
|
||||||
/// What the user picked from the tray menu.
|
/// The window process, when there is one.
|
||||||
pub(crate) enum Action {
|
struct Window {
|
||||||
/// Show (and focus) the window.
|
child: Mutex<Option<Child>>,
|
||||||
Open,
|
|
||||||
/// Quit the application.
|
|
||||||
Quit,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The live tray icon plus the channel of menu actions.
|
impl Window {
|
||||||
pub(crate) struct Tray {
|
/// Starts the window unless one is already open.
|
||||||
/// Kept alive for as long as the app runs; dropping it removes the icon.
|
///
|
||||||
/// On Linux the icon lives on the GTK thread instead (it is not `Send`).
|
/// Raising an existing one is not something a process can ask for on
|
||||||
#[cfg(not(target_os = "linux"))]
|
/// every platform, so choosing Open while it is open does nothing.
|
||||||
_icon: TrayIcon,
|
fn open(&self) {
|
||||||
actions: mpsc::Receiver<Action>,
|
let mut slot = self.child.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if let Some(child) = slot.as_mut() {
|
||||||
|
match child.try_wait() {
|
||||||
|
Ok(None) => return,
|
||||||
|
_ => *slot = None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let started = std::env::current_exe()
|
||||||
|
.map_err(|err| err.to_string())
|
||||||
|
.and_then(|exe| {
|
||||||
|
Command::new(exe)
|
||||||
|
.arg(crate::WINDOW_ARG)
|
||||||
|
.spawn()
|
||||||
|
.map_err(|err| err.to_string())
|
||||||
|
});
|
||||||
|
match started {
|
||||||
|
Ok(child) => *slot = Some(child),
|
||||||
|
Err(err) => eprintln!("cannot open the window: {err}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes the window if it is open.
|
||||||
|
fn close(&self) {
|
||||||
|
let mut slot = self.child.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if let Some(mut child) = slot.take() {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A built tray icon and the ids of its menu items.
|
/// A built tray icon and the ids of its menu items.
|
||||||
@@ -57,75 +81,91 @@ fn build() -> Result<Built, String> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Tray {
|
/// Acts on menu choices as the platform's loop delivers them.
|
||||||
/// Builds the tray and starts reading its menu events.
|
fn handle_menu(built: &Built, window: Arc<Window>) {
|
||||||
///
|
let (open, quit) = (built.open.clone(), built.quit.clone());
|
||||||
/// Created on the main thread on macOS and Windows (required on macOS). On
|
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
|
||||||
/// Linux the tray needs GTK, which eframe/winit never initialise, so it is
|
if event.id == open {
|
||||||
/// built on a dedicated thread that initialises GTK and runs its main loop.
|
window.open();
|
||||||
/// `ctx` is used to wake the UI when a menu item is chosen.
|
} else if event.id == quit {
|
||||||
pub(crate) fn new(ctx: egui::Context) -> Result<Self, String> {
|
window.close();
|
||||||
#[cfg(target_os = "linux")]
|
std::process::exit(0);
|
||||||
let (open_id, quit_id) = {
|
}
|
||||||
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
|
}));
|
||||||
std::thread::Builder::new()
|
}
|
||||||
.name("tray-gtk".into())
|
|
||||||
.spawn(move || {
|
|
||||||
if let Err(err) = gtk::init() {
|
|
||||||
let _ = ready_tx.send(Err(format!("cannot initialise GTK: {err}")));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
match build() {
|
|
||||||
Ok(built) => {
|
|
||||||
let _ = ready_tx.send(Ok((built.open, built.quit)));
|
|
||||||
gtk::main();
|
|
||||||
drop(built.icon);
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
let _ = ready_tx.send(Err(err));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.map_err(|err| err.to_string())?;
|
|
||||||
ready_rx
|
|
||||||
.recv()
|
|
||||||
.map_err(|_| "the tray thread exited before it was ready".to_string())??
|
|
||||||
};
|
|
||||||
#[cfg(not(target_os = "linux"))]
|
|
||||||
let (icon, open_id, quit_id) = {
|
|
||||||
let built = build()?;
|
|
||||||
(built.icon, built.open, built.quit)
|
|
||||||
};
|
|
||||||
|
|
||||||
let (tx, rx) = mpsc::channel();
|
/// Shows the icon and runs until Quit.
|
||||||
std::thread::spawn(move || {
|
///
|
||||||
// The global menu-event channel is fed by the OS event loop.
|
/// Linux: the tray needs GTK, which nothing else here initialises, so this
|
||||||
while let Ok(event) = MenuEvent::receiver().recv() {
|
/// thread does and runs its main loop.
|
||||||
let action = if event.id == open_id {
|
#[cfg(target_os = "linux")]
|
||||||
Action::Open
|
pub(crate) fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
} else if event.id == quit_id {
|
gtk::init().map_err(|err| format!("cannot initialise GTK: {err}"))?;
|
||||||
Action::Quit
|
let built = build()?;
|
||||||
} else {
|
handle_menu(
|
||||||
continue;
|
&built,
|
||||||
};
|
Arc::new(Window {
|
||||||
if tx.send(action).is_err() {
|
child: Mutex::new(None),
|
||||||
break;
|
}),
|
||||||
}
|
);
|
||||||
ctx.request_repaint();
|
gtk::main();
|
||||||
|
drop(built.icon);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows the icon and runs until Quit.
|
||||||
|
///
|
||||||
|
/// Windows and macOS: the icon needs an event loop on the main thread to be
|
||||||
|
/// served, and macOS wants it created once that loop is running. There are no
|
||||||
|
/// windows in it; it exists to be pumped.
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
pub(crate) fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::window::WindowId;
|
||||||
|
|
||||||
|
struct Pump {
|
||||||
|
window: Arc<Window>,
|
||||||
|
icon: Option<TrayIcon>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for Pump {
|
||||||
|
fn resumed(&mut self, _event_loop: &ActiveEventLoop) {
|
||||||
|
if self.icon.is_some() {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
});
|
match build() {
|
||||||
|
Ok(built) => {
|
||||||
|
handle_menu(&built, Arc::clone(&self.window));
|
||||||
|
self.icon = Some(built.icon);
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("cannot create the tray icon: {err}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(Self {
|
fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, _: WindowEvent) {}
|
||||||
#[cfg(not(target_os = "linux"))]
|
|
||||||
_icon: icon,
|
|
||||||
actions: rx,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The menu actions since the last call.
|
let mut builder = EventLoop::builder();
|
||||||
pub(crate) fn poll(&self) -> impl Iterator<Item = Action> + '_ {
|
// macOS: live in the menu bar with no Dock icon.
|
||||||
self.actions.try_iter()
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
|
||||||
|
builder.with_activation_policy(ActivationPolicy::Accessory);
|
||||||
}
|
}
|
||||||
|
let event_loop = builder.build()?;
|
||||||
|
let mut pump = Pump {
|
||||||
|
window: Arc::new(Window {
|
||||||
|
child: Mutex::new(None),
|
||||||
|
}),
|
||||||
|
icon: None,
|
||||||
|
};
|
||||||
|
event_loop.run_app(&mut pump)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A small round icon, drawn in code so there is no asset to ship yet.
|
/// A small round icon, drawn in code so there is no asset to ship yet.
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ use egui_phosphor::regular as icon;
|
|||||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||||
|
|
||||||
use crate::agent::{AgentClient, Command, Snapshot};
|
use crate::agent::{AgentClient, Command, Snapshot};
|
||||||
|
use crate::devices;
|
||||||
use crate::format;
|
use crate::format;
|
||||||
use crate::stats::{Traffic, Unit};
|
use crate::stats::{Traffic, Unit};
|
||||||
|
|
||||||
@@ -114,7 +115,7 @@ pub(crate) fn draw(
|
|||||||
ui.weak("No networks yet — join one below.");
|
ui.weak("No networks yet — join one below.");
|
||||||
}
|
}
|
||||||
for network in &report.networks {
|
for network in &report.networks {
|
||||||
draw_network(ui, agent, state, traffic, network);
|
draw_network(ui, agent, state, traffic, network, &report.endpoint_id);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -191,6 +192,7 @@ fn draw_network(
|
|||||||
state: &mut UiState,
|
state: &mut UiState,
|
||||||
traffic: &Traffic,
|
traffic: &Traffic,
|
||||||
network: &NetworkReport,
|
network: &NetworkReport,
|
||||||
|
own_id: &str,
|
||||||
) {
|
) {
|
||||||
ui.add_space(6.0);
|
ui.add_space(6.0);
|
||||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||||
@@ -233,7 +235,7 @@ fn draw_network(
|
|||||||
ui.label(format!(
|
ui.label(format!(
|
||||||
"{} connected · {} known",
|
"{} connected · {} known",
|
||||||
network.peers.len(),
|
network.peers.len(),
|
||||||
network.members.len()
|
devices::known_count(network, own_id)
|
||||||
));
|
));
|
||||||
ui.end_row();
|
ui.end_row();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ fn source(agent: Agent, plugin: Arc<WireguardPlugin>) -> Arc<dyn tsunagi::ipc::R
|
|||||||
cache_healthy: status.cache_healthy,
|
cache_healthy: status.cache_healthy,
|
||||||
networks,
|
networks,
|
||||||
dns: None,
|
dns: None,
|
||||||
|
..Default::default()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -331,6 +331,9 @@ struct Runtime {
|
|||||||
pending_state: Vec<(EndpointId, Vec<SignedRecord>)>,
|
pending_state: Vec<(EndpointId, Vec<SignedRecord>)>,
|
||||||
/// The highest version this agent has ever published for this network.
|
/// The highest version this agent has ever published for this network.
|
||||||
own_version: u64,
|
own_version: u64,
|
||||||
|
/// The last hostname each peer announced, kept across restarts so a
|
||||||
|
/// member that is away can still be called by name.
|
||||||
|
known_hostnames: HashMap<EndpointId, String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Runtime {
|
impl Runtime {
|
||||||
@@ -382,6 +385,7 @@ impl Runtime {
|
|||||||
state: StateSet::new(),
|
state: StateSet::new(),
|
||||||
pending_state: Vec::new(),
|
pending_state: Vec::new(),
|
||||||
own_version: 0,
|
own_version: 0,
|
||||||
|
known_hostnames: HashMap::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -844,6 +848,17 @@ impl Runtime {
|
|||||||
.own_record_version(self.network_id, self.local_id)
|
.own_record_version(self.network_id, self.local_id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
|
for (id, hostname) in self
|
||||||
|
.params
|
||||||
|
.storage
|
||||||
|
.peer_hostnames(self.network_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default()
|
||||||
|
{
|
||||||
|
if let Ok(id) = EndpointId::from_bytes(&id) {
|
||||||
|
self.known_hostnames.insert(id, hostname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self.ensure_own_claim().await;
|
self.ensure_own_claim().await;
|
||||||
self.publish_allocations().await;
|
self.publish_allocations().await;
|
||||||
@@ -1885,6 +1900,33 @@ impl Runtime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Keeps the name a peer announced, on disk too when it changed.
|
||||||
|
///
|
||||||
|
/// Written off the loop: a name that is not stored this time is stored
|
||||||
|
/// the next time the peer announces it.
|
||||||
|
fn remember_hostname(&mut self, peer: EndpointId, hostname: &str) {
|
||||||
|
if hostname.is_empty()
|
||||||
|
|| self
|
||||||
|
.known_hostnames
|
||||||
|
.get(&peer)
|
||||||
|
.is_some_and(|h| h == hostname)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.known_hostnames.insert(peer, hostname.to_string());
|
||||||
|
let storage = self.params.storage.clone();
|
||||||
|
let network_id = self.network_id;
|
||||||
|
let hostname = hostname.to_string();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(err) = storage
|
||||||
|
.remember_peer_hostname(network_id, *peer.as_bytes(), hostname)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::debug!(%err, "could not remember a peer's hostname");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
|
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
|
||||||
match &message {
|
match &message {
|
||||||
ControlMessage::Announce(announcement) => {
|
ControlMessage::Announce(announcement) => {
|
||||||
@@ -1894,6 +1936,7 @@ impl Runtime {
|
|||||||
session.broadcast = announcement.broadcast;
|
session.broadcast = announcement.broadcast;
|
||||||
session.capabilities = capabilities.clone();
|
session.capabilities = capabilities.clone();
|
||||||
}
|
}
|
||||||
|
self.remember_hostname(peer, &announcement.hostname);
|
||||||
self.update_broadcast();
|
self.update_broadcast();
|
||||||
self.dispatch_capabilities(peer, &capabilities);
|
self.dispatch_capabilities(peer, &capabilities);
|
||||||
self.ensure_links();
|
self.ensure_links();
|
||||||
@@ -1994,7 +2037,10 @@ impl Runtime {
|
|||||||
broadcast: session.broadcast,
|
broadcast: session.broadcast,
|
||||||
endpoint_id: session.peer,
|
endpoint_id: session.peer,
|
||||||
role: session.role,
|
role: session.role,
|
||||||
hostname: session.hostname.clone(),
|
hostname: session
|
||||||
|
.hostname
|
||||||
|
.clone()
|
||||||
|
.or_else(|| self.known_hostnames.get(&session.peer).cloned()),
|
||||||
protocols: session
|
protocols: session
|
||||||
.capabilities
|
.capabilities
|
||||||
.iter()
|
.iter()
|
||||||
@@ -2052,6 +2098,7 @@ impl Runtime {
|
|||||||
// both hold it would be untrue on one of them.
|
// both hold it would be untrue on one of them.
|
||||||
overlay_address_v4: self.state.address_of(&endpoint_id),
|
overlay_address_v4: self.state.address_of(&endpoint_id),
|
||||||
hostname: self.state.hostname_of(&endpoint_id).map(str::to_string),
|
hostname: self.state.hostname_of(&endpoint_id).map(str::to_string),
|
||||||
|
last_hostname: self.known_hostnames.get(&endpoint_id).cloned(),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|||||||
@@ -80,6 +80,11 @@ pub struct MemberStatus {
|
|||||||
/// Signed, so it is still known while the member is away — which is what
|
/// Signed, so it is still known while the member is away — which is what
|
||||||
/// lets an absent member be named rather than shown as a bare id.
|
/// lets an absent member be named rather than shown as a bare id.
|
||||||
pub hostname: Option<String>,
|
pub hostname: Option<String>,
|
||||||
|
/// The last name this agent saw it announce, whether or not it is here.
|
||||||
|
///
|
||||||
|
/// Not signed, so it is a convenience for naming a member that is away
|
||||||
|
/// and never a claim: the zone is served from `hostname`.
|
||||||
|
pub last_hostname: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Status of one authenticated session.
|
/// Status of one authenticated session.
|
||||||
|
|||||||
@@ -352,6 +352,34 @@ pub struct StatusReport {
|
|||||||
pub networks: Vec<NetworkReport>,
|
pub networks: Vec<NetworkReport>,
|
||||||
/// The local DNS service, when one was asked for.
|
/// The local DNS service, when one was asked for.
|
||||||
pub dns: Option<DnsReport>,
|
pub dns: Option<DnsReport>,
|
||||||
|
/// The state directory the agent is actually using.
|
||||||
|
///
|
||||||
|
/// A client that was not told one would look in its own default, which is
|
||||||
|
/// not the agent's when the agent runs as a service under another user.
|
||||||
|
pub state_dir: String,
|
||||||
|
/// The cache directory the agent is actually using.
|
||||||
|
pub cache_dir: String,
|
||||||
|
/// The executable the agent runs, which is what needs the capability.
|
||||||
|
pub program: String,
|
||||||
|
/// Whether the agent itself can manage the overlay interface.
|
||||||
|
///
|
||||||
|
/// It is the agent that creates the interface, so the client's own
|
||||||
|
/// capabilities say nothing about it.
|
||||||
|
pub privilege: PrivilegeReport,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the agent found when it checked whether it may manage an interface.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum PrivilegeReport {
|
||||||
|
/// Not checked.
|
||||||
|
#[default]
|
||||||
|
Unknown,
|
||||||
|
/// It can.
|
||||||
|
Available,
|
||||||
|
/// It cannot, with what was found.
|
||||||
|
Missing(String),
|
||||||
|
/// This platform has no provisioner yet.
|
||||||
|
Unsupported,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The local DNS service.
|
/// The local DNS service.
|
||||||
@@ -436,6 +464,8 @@ pub struct MemberReport {
|
|||||||
pub overlay_address_v4: Option<String>,
|
pub overlay_address_v4: Option<String>,
|
||||||
/// Consecutive failed dial attempts, when this agent is trying to reach it.
|
/// Consecutive failed dial attempts, when this agent is trying to reach it.
|
||||||
pub failed_dials: u32,
|
pub failed_dials: u32,
|
||||||
|
/// The last hostname this agent saw it announce, kept while it is away.
|
||||||
|
pub hostname: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One control plane peer.
|
/// One control plane peer.
|
||||||
|
|||||||
@@ -264,7 +264,8 @@ impl Storage {
|
|||||||
pub async fn remove_network(&self, network_id: NetworkId) -> Result<()> {
|
pub async fn remove_network(&self, network_id: NetworkId) -> Result<()> {
|
||||||
self.with_state(move |state| {
|
self.with_state(move |state| {
|
||||||
state.remove_network(network_id)?;
|
state.remove_network(network_id)?;
|
||||||
state.forget_signed_records(network_id)
|
state.forget_signed_records(network_id)?;
|
||||||
|
state.forget_peer_hostnames(network_id)
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
self.with_cache((), move |cache| cache.forget_network(network_id))
|
self.with_cache((), move |cache| cache.forget_network(network_id))
|
||||||
@@ -283,6 +284,26 @@ impl Storage {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Remembers the hostname a member announced, so it can still be named
|
||||||
|
/// once it is away.
|
||||||
|
pub async fn remember_peer_hostname(
|
||||||
|
&self,
|
||||||
|
network_id: NetworkId,
|
||||||
|
endpoint_id: [u8; 32],
|
||||||
|
hostname: String,
|
||||||
|
) -> Result<()> {
|
||||||
|
self.with_state(move |state| {
|
||||||
|
state.remember_peer_hostname(network_id, &endpoint_id, &hostname)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The hostnames members of a network last announced.
|
||||||
|
pub async fn peer_hostnames(&self, network_id: NetworkId) -> Result<Vec<([u8; 32], String)>> {
|
||||||
|
self.with_state(move |state| state.peer_hostnames(network_id))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
/// Records an address hint. Failures are non-fatal.
|
/// Records an address hint. Failures are non-fatal.
|
||||||
pub async fn record_hint(
|
pub async fn record_hint(
|
||||||
&self,
|
&self,
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use crate::identity::{DeviceIdentity, NetworkId, NetworkName, NetworkSecret};
|
|||||||
use crate::state::{RecordBody, SignedRecord};
|
use crate::state::{RecordBody, SignedRecord};
|
||||||
|
|
||||||
/// Schema version written by this build.
|
/// Schema version written by this build.
|
||||||
pub const SCHEMA_VERSION: i64 = 4;
|
pub const SCHEMA_VERSION: i64 = 5;
|
||||||
|
|
||||||
/// Key of the stored hostname setting.
|
/// Key of the stored hostname setting.
|
||||||
const SETTING_HOSTNAME: &str = "hostname";
|
const SETTING_HOSTNAME: &str = "hostname";
|
||||||
@@ -191,13 +191,34 @@ impl StateStore {
|
|||||||
PRAGMA user_version = 4;
|
PRAGMA user_version = 4;
|
||||||
COMMIT;").map_err(|err| self.corrupt(format!("cannot migrate schema to 4: {err}")))?;
|
COMMIT;").map_err(|err| self.corrupt(format!("cannot migrate schema to 4: {err}")))?;
|
||||||
}
|
}
|
||||||
|
if found < 5 {
|
||||||
|
self.conn
|
||||||
|
.execute_batch(
|
||||||
|
"BEGIN;
|
||||||
|
CREATE TABLE IF NOT EXISTS peer_hostnames (
|
||||||
|
network_id BLOB NOT NULL,
|
||||||
|
endpoint_id BLOB NOT NULL,
|
||||||
|
hostname TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (network_id, endpoint_id)
|
||||||
|
);
|
||||||
|
PRAGMA user_version = 5;
|
||||||
|
COMMIT;",
|
||||||
|
)
|
||||||
|
.map_err(|err| self.corrupt(format!("cannot migrate schema to 5: {err}")))?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Confirms the expected tables exist, so that a truncated or foreign
|
/// Confirms the expected tables exist, so that a truncated or foreign
|
||||||
/// database is reported rather than used.
|
/// database is reported rather than used.
|
||||||
fn verify_shape(&self) -> Result<()> {
|
fn verify_shape(&self) -> Result<()> {
|
||||||
for table in ["device_identity", "networks", "settings", "signed_records"] {
|
for table in [
|
||||||
|
"device_identity",
|
||||||
|
"networks",
|
||||||
|
"settings",
|
||||||
|
"signed_records",
|
||||||
|
"peer_hostnames",
|
||||||
|
] {
|
||||||
let present: Option<String> = self
|
let present: Option<String> = self
|
||||||
.conn
|
.conn
|
||||||
.query_row(
|
.query_row(
|
||||||
@@ -635,6 +656,61 @@ impl StateStore {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Remembers the hostname a member last announced.
|
||||||
|
pub fn remember_peer_hostname(
|
||||||
|
&self,
|
||||||
|
network_id: NetworkId,
|
||||||
|
endpoint_id: &[u8; 32],
|
||||||
|
hostname: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"INSERT INTO peer_hostnames (network_id, endpoint_id, hostname)
|
||||||
|
VALUES (?1, ?2, ?3)
|
||||||
|
ON CONFLICT(network_id, endpoint_id) DO UPDATE SET hostname = excluded.hostname",
|
||||||
|
params![
|
||||||
|
network_id.as_bytes().as_slice(),
|
||||||
|
endpoint_id.as_slice(),
|
||||||
|
hostname
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.map_err(|err| Error::Storage(format!("cannot remember a hostname: {err}")))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last hostname every member of a network announced.
|
||||||
|
pub fn peer_hostnames(&self, network_id: NetworkId) -> Result<Vec<([u8; 32], String)>> {
|
||||||
|
let mut stmt = self
|
||||||
|
.conn
|
||||||
|
.prepare("SELECT endpoint_id, hostname FROM peer_hostnames WHERE network_id = ?1")
|
||||||
|
.map_err(|err| Error::Storage(format!("cannot read hostnames: {err}")))?;
|
||||||
|
let rows = stmt
|
||||||
|
.query_map(params![network_id.as_bytes().as_slice()], |row| {
|
||||||
|
Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, String>(1)?))
|
||||||
|
})
|
||||||
|
.map_err(|err| Error::Storage(format!("cannot read hostnames: {err}")))?;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for row in rows {
|
||||||
|
let (id, hostname) =
|
||||||
|
row.map_err(|err| Error::Storage(format!("cannot read hostnames: {err}")))?;
|
||||||
|
if let Ok(id) = <[u8; 32]>::try_from(id.as_slice()) {
|
||||||
|
out.push((id, hostname));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgets every remembered hostname of a network.
|
||||||
|
pub fn forget_peer_hostnames(&self, network_id: NetworkId) -> Result<()> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"DELETE FROM peer_hostnames WHERE network_id = ?1",
|
||||||
|
params![network_id.as_bytes().as_slice()],
|
||||||
|
)
|
||||||
|
.map_err(|err| Error::Storage(format!("cannot forget hostnames: {err}")))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Reads an arbitrary setting.
|
/// Reads an arbitrary setting.
|
||||||
pub fn get_setting(&self, key: &str) -> Result<Option<String>> {
|
pub fn get_setting(&self, key: &str) -> Result<Option<String>> {
|
||||||
self.conn
|
self.conn
|
||||||
@@ -698,6 +774,29 @@ mod broadcast_storage_tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::identity::NetworkKeys;
|
use crate::identity::NetworkKeys;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_remembered_hostname_survives_a_restart_and_follows_the_latest_name() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("state.sqlite");
|
||||||
|
let name = NetworkName::new("hostnames").unwrap();
|
||||||
|
let secret = NetworkSecret::from_bytes([9; 32]).unwrap();
|
||||||
|
let id = NetworkKeys::derive(&name, &secret).network_id();
|
||||||
|
let peer = [3u8; 32];
|
||||||
|
|
||||||
|
let store = StateStore::open(&path).unwrap();
|
||||||
|
store.remember_peer_hostname(id, &peer, "laptop").unwrap();
|
||||||
|
store.remember_peer_hostname(id, &peer, "laptop-2").unwrap();
|
||||||
|
drop(store);
|
||||||
|
|
||||||
|
let store = StateStore::open(&path).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
store.peer_hostnames(id).unwrap(),
|
||||||
|
vec![(peer, "laptop-2".to_string())]
|
||||||
|
);
|
||||||
|
store.forget_peer_hostnames(id).unwrap();
|
||||||
|
assert!(store.peer_hostnames(id).unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn v3_migration_preserves_identity_and_networks_and_defaults_broadcast_on() {
|
fn v3_migration_preserves_identity_and_networks_and_defaults_broadcast_on() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
Reference in new issue
Block a user