Exit nodes: offer one per network, send all traffic through a member

A member can offer itself as an exit node per network (off by default); it is
announced over the control channel (ctrl/4) once its iptables masquerade and
forward rules are in place, with a warning when kernel forwarding is off. A
device picks one member as its exit node via policy routing, with the agent's
own uid exempt from the tunnel; if the exit node disappears the rules stay
and traffic is dropped, loudly reported. CLI: `network exit-node`,
`exit-node`; tray: tile checkbox, warnings and a per-device icon with
confirmation. Linux only.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Aleksandr BogomiakovandClaude committed 2026-10-03 01:14:51 +01:00
1 parent c62d29fa14
commit b2431d7eb1
34 files changed
+4148 -61

No files matched your search

+24
View File
@@ -25,6 +25,14 @@ pub(crate) enum Command {
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.
@@ -185,6 +193,22 @@ async fn run(
.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!("joined {}", report.name))
+11 -2
View File
@@ -112,15 +112,24 @@ impl App {
let viewport_id = egui::ViewportId::from_hash_of(("devices", &id));
let builder = egui::ViewportBuilder::default()
.with_title(devices::title(network))
.with_inner_size([900.0, 540.0])
.with_inner_size([940.0, 540.0])
.with_min_inner_size([480.0, 320.0]);
let agent = &self.agent;
let traffic = &self.traffic;
// The window shares the single unit setting, so its toggle and the
// main window's stay in step.
let unit = &mut self.state.unit;
let confirm = &mut self.state.exit_confirm;
let keep = ctx.show_viewport_immediate(viewport_id, builder, |vctx, _class| {
devices::show(vctx, agent, unit, network, &report.endpoint_id, traffic);
devices::show(
vctx,
agent,
unit,
confirm,
network,
&report.endpoint_id,
traffic,
);
!vctx.input(|i| i.viewport().close_requested())
});
if !keep {
+182 -25
View File
@@ -11,7 +11,8 @@ use eframe::egui;
use tsunagi::ipc::{NetworkReport, OverlayPeerReport};
use crate::agent::AgentClient;
use crate::agent::{AgentClient, Command};
use crate::exit;
use crate::format;
use crate::stats::{Traffic, Unit};
@@ -33,9 +34,28 @@ struct Device<'a> {
address: Option<String>,
handshake_secs: Option<u64>,
overlay: Option<&'a OverlayPeerReport>,
/// It is connected and offers to be an exit node.
exit_node: bool,
/// It is the exit node this device sends its internet traffic through.
in_use: bool,
}
/// An exit-node choice the user has to confirm: all their traffic goes through
/// somebody else's device, or stops doing so.
pub(crate) struct ExitConfirm {
network_id: String,
peer_id: String,
name: String,
/// Stop using it, rather than start.
stop: bool,
}
impl Device<'_> {
fn name(&self) -> String {
self.hostname
.map_or_else(|| format::short(self.id), str::to_string)
}
fn sort_key(&self) -> String {
self.hostname.unwrap_or(self.id).to_lowercase()
}
@@ -64,8 +84,9 @@ fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
/// Draws the window body into its viewport.
pub(crate) fn show(
ctx: &egui::Context,
_agent: &AgentClient,
agent: &AgentClient,
unit: &mut Unit,
confirm: &mut Option<ExitConfirm>,
network: &NetworkReport,
own_id: &str,
traffic: &Traffic,
@@ -102,9 +123,85 @@ pub(crate) fn show(
egui::ScrollArea::both()
.auto_shrink([false, false])
.show(ui, |ui| {
device_table(ui, unit, &network.network_id, &devices, traffic);
device_table(ui, unit, network, &devices, traffic, confirm);
});
});
confirm_exit(ctx, agent, confirm, &network.network_id);
}
/// The confirmation for an exit-node choice, drawn in the window it was
/// made in. Everything behind it is blocked until it is answered.
fn confirm_exit(
ctx: &egui::Context,
agent: &AgentClient,
confirm: &mut Option<ExitConfirm>,
network_id: &str,
) {
let Some(pending) = confirm.as_ref().filter(|c| c.network_id == network_id) else {
return;
};
egui::Area::new(egui::Id::new("exit confirm backdrop"))
.order(egui::Order::Middle)
.fixed_pos(egui::Pos2::ZERO)
.show(ctx, |ui| {
let screen = ctx.screen_rect();
ui.allocate_response(screen.size(), egui::Sense::click_and_drag());
ui.painter()
.rect_filled(screen, 0.0, egui::Color32::from_black_alpha(140));
});
let (mut accepted, mut cancelled) = (false, false);
egui::Window::new(if pending.stop {
"Stop using exit node"
} else {
"Use as exit node"
})
.order(egui::Order::Foreground)
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
ui.set_max_width(380.0);
if pending.stop {
ui.label(format!("Stop using {} as exit node?", pending.name));
ui.label("Your internet traffic will leave this device the ordinary way again.");
} else {
ui.label(
egui::RichText::new(format!(
"Send ALL your internet traffic through {}?",
pending.name
))
.strong(),
);
ui.label(
"Everything not on this network will leave through that device, which can \
see it.",
);
}
ui.add_space(8.0);
ui.horizontal(|ui| {
let label = if pending.stop {
"Stop"
} else {
"Use as exit node"
};
if ui.button(label).clicked() {
accepted = true;
}
if ui.button("Cancel").clicked() {
cancelled = true;
}
});
});
if accepted {
agent.send(Command::SetExitNode {
network_id: pending.network_id.clone(),
peer: (!pending.stop).then(|| pending.peer_id.clone()),
});
}
if accepted || cancelled || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
*confirm = None;
}
}
/// The network's own settings and counters.
@@ -165,7 +262,8 @@ fn known_ids<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<&'a str> {
.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()));
.chain(network.members.iter().map(|m| m.endpoint_id.as_str()))
.chain(network.exit.via.as_deref());
for id in candidates {
if id != own_id && !ids.contains(&id) {
ids.push(id);
@@ -221,6 +319,12 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
.or_else(|| member.and_then(|m| m.overlay_address_v4.clone())),
handshake_secs: overlay.and_then(|p| p.handshake_secs_ago),
overlay,
exit_node: online
&& network
.peers
.iter()
.any(|p| p.endpoint_id == id && p.exit_node),
in_use: network.exit.via.as_deref() == Some(id),
}
})
.collect();
@@ -235,8 +339,9 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
/// The widest value each column is expected to hold, so the table starts out
/// wide enough and does not reflow as numbers grow.
const COLUMN_SAMPLES: [&str; 8] = [
const COLUMN_SAMPLES: [&str; 9] = [
"",
"exit",
"tcp-tls",
"255.255.255.255",
"23h 59m",
@@ -252,11 +357,11 @@ const COLUMN_SAMPLES: [&str; 8] = [
/// gets shorter — `14.4 MB/s` giving way to `382 pkt/s` — would pull the
/// column in and push every cell after it. Remembering the widest seen keeps
/// the table where it is.
fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 8] {
let stored: Option<[f32; 8]> = ui.memory(|m| m.data.get_temp(id));
fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 9] {
let stored: Option<[f32; 9]> = ui.memory(|m| m.data.get_temp(id));
stored.unwrap_or_else(|| {
let font = egui::TextStyle::Body.resolve(ui.style());
let mut widths = [0.0; 8];
let mut widths = [0.0; 9];
for (width, sample) in widths.iter_mut().zip(COLUMN_SAMPLES) {
if !sample.is_empty() {
*width = ui.fonts(|fonts| {
@@ -272,7 +377,7 @@ fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 8] {
}
/// One cell, at least as wide as its column has ever been.
fn cell(ui: &mut egui::Ui, column: usize, widths: &mut [f32; 8], add: impl FnOnce(&mut egui::Ui)) {
fn cell(ui: &mut egui::Ui, column: usize, widths: &mut [f32; 9], add: impl FnOnce(&mut egui::Ui)) {
let floor = widths[column];
let response = ui.scope(|ui| {
ui.set_min_width(floor);
@@ -281,15 +386,66 @@ fn cell(ui: &mut egui::Ui, column: usize, widths: &mut [f32; 8], add: impl FnOnc
widths[column] = widths[column].max(response.response.rect.width());
}
/// The exit-node mark of a device: shown when it offers to be one, bright
/// for the one in use, and clickable (to confirm) only while that can be done.
///
/// The one in use stays clickable even when it has gone away, since stopping
/// is the only way out of the traffic being blocked.
fn exit_cell(
ui: &mut egui::Ui,
device: &Device<'_>,
network_id: &str,
confirm: &mut Option<ExitConfirm>,
) {
if !device.exit_node && !device.in_use {
ui.label("");
return;
}
let (color, hint) = if device.in_use {
let color = if device.online {
exit::GOOD
} else {
exit::LOUD
};
(color, "in use as your exit node — click to stop")
} else {
(
ui.visuals().text_color(),
"offers to be an exit node — click to send all your internet traffic through it",
)
};
let response = ui
.add(
egui::Label::new(
egui::RichText::new(egui_phosphor::regular::SIGN_OUT)
.size(16.0)
.color(color),
)
.sense(egui::Sense::click()),
)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(hint);
if response.clicked() {
*confirm = Some(ExitConfirm {
network_id: network_id.to_string(),
peer_id: device.id.to_string(),
name: device.name(),
stop: device.in_use,
});
}
}
/// One table of all devices: online rows carry live counters and a plot,
/// offline rows show what is known (name and address) and dashes.
fn device_table(
ui: &mut egui::Ui,
unit: Unit,
network_id: &str,
network: &NetworkReport,
devices: &[Device<'_>],
traffic: &Traffic,
confirm: &mut Option<ExitConfirm>,
) {
let network_id = network.network_id.as_str();
if devices.is_empty() {
ui.weak("none");
return;
@@ -297,12 +453,13 @@ fn device_table(
let widths_id = egui::Id::new(("devices column widths", network_id));
let mut widths = column_widths(ui, widths_id);
egui::Grid::new("devices")
.num_columns(8)
.num_columns(9)
.striped(true)
.spacing([10.0, 4.0])
.show(ui, |ui| {
for (column, header) in [
"device",
"exit",
"proto",
"address",
"handshake",
@@ -323,15 +480,18 @@ fn device_table(
for device in devices {
cell(ui, 0, &mut widths, |ui| name_cell(ui, device));
cell(ui, 1, &mut widths, |ui| {
exit_cell(ui, device, network_id, confirm);
});
cell(ui, 2, &mut widths, |ui| {
ui.label(device.proto);
});
cell(ui, 2, &mut widths, |ui| match &device.address {
cell(ui, 3, &mut widths, |ui| match &device.address {
Some(address) => format::copy_field(ui, address, address),
None => {
ui.weak("—");
}
});
cell(ui, 3, &mut widths, |ui| {
cell(ui, 4, &mut widths, |ui| {
ui.label(
device
.handshake_secs
@@ -342,17 +502,17 @@ fn device_table(
match device.overlay.filter(|_| device.online) {
Some(peer) => {
let series = traffic.peer(network_id, &peer.public_key);
cell(ui, 4, &mut widths, |ui| {
cell(ui, 5, &mut widths, |ui| {
ui.label(format!("{}/{}", peer.tx_packets, peer.rx_packets));
});
cell(ui, 5, &mut widths, |ui| {
cell(ui, 6, &mut widths, |ui| {
ui.label(format!(
"{} / {}",
format::bytes(peer.tx_bytes as f64),
format::bytes(peer.rx_bytes as f64)
));
});
cell(ui, 6, &mut widths, |ui| {
cell(ui, 7, &mut widths, |ui| {
ui.add(
egui::Label::new(format::series_rate(series, unit))
.wrap_mode(egui::TextWrapMode::Extend),
@@ -363,7 +523,7 @@ fn device_table(
});
}
None => {
for column in 4..7 {
for column in 5..8 {
cell(ui, column, &mut widths, |ui| {
ui.weak("—");
});
@@ -386,22 +546,22 @@ fn device_table(
cell(ui, 0, &mut widths, |ui| {
ui.strong("total");
});
for column in 1..4 {
for column in 1..5 {
cell(ui, column, &mut widths, |ui| {
ui.label("");
});
}
cell(ui, 4, &mut widths, |ui| {
cell(ui, 5, &mut widths, |ui| {
ui.strong(format!("{tx_packets}/{rx_packets}"));
});
cell(ui, 5, &mut widths, |ui| {
cell(ui, 6, &mut widths, |ui| {
ui.strong(format!(
"{} / {}",
format::bytes(tx_bytes as f64),
format::bytes(rx_bytes as f64)
));
});
cell(ui, 6, &mut widths, |ui| {
cell(ui, 7, &mut widths, |ui| {
ui.add(
egui::Label::new(
egui::RichText::new(format::series_rate(traffic.network(network_id), unit))
@@ -412,10 +572,7 @@ fn device_table(
});
ui.end_row();
});
ui.memory_mut(|m| {
m.data
.insert_temp(egui::Id::new("devices column widths"), widths)
});
ui.memory_mut(|m| m.data.insert_temp(widths_id, widths));
}
fn yes_no(value: bool) -> &'static str {
+164
View File
@@ -0,0 +1,164 @@
//! Exit nodes as the windows show them: what to call one, and what is wrong
//! with the ones in play.
use eframe::egui;
use tsunagi::ipc::NetworkReport;
use crate::format;
/// An exit node that is working.
pub(crate) const GOOD: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a);
/// Something about exit nodes the user has to look at.
pub(crate) const LOUD: egui::Color32 = egui::Color32::from_rgb(0xe0, 0x4a, 0x3c);
/// What to run to turn kernel forwarding on, which the agent never does.
pub(crate) const FORWARDING_COMMAND: &str = "sudo sysctl -w net.ipv4.ip_forward=1";
/// One thing wrong, loud enough to read at a glance.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Warning {
pub(crate) text: String,
/// A command the user will want, copied by clicking the warning.
pub(crate) copy: Option<&'static str>,
}
/// What to call a device in a network, even while it is away.
pub(crate) fn name_of(network: &NetworkReport, id: &str) -> String {
network
.peers
.iter()
.find(|peer| peer.endpoint_id == id)
.and_then(|peer| peer.hostname.clone())
.or_else(|| {
network
.members
.iter()
.find(|member| member.endpoint_id == id)
.and_then(|member| member.hostname.clone())
})
.unwrap_or_else(|| format::short(id))
}
/// Everything wrong with a network's exit-node settings, most urgent first.
pub(crate) fn warnings(network: &NetworkReport) -> Vec<Warning> {
let exit = &network.exit;
let mut out = Vec::new();
if let Some(via) = &exit.via {
let name = name_of(network, via);
if !exit.via_online {
out.push(Warning {
text: format!(
"exit node {name} is offline — your internet traffic is blocked until it \
returns; stop using it from the devices window"
),
copy: None,
});
} else {
match &exit.client_rules {
Some(rules) if rules.ok => {}
Some(rules) => out.push(Warning {
text: format!(
"the routes to exit node {name} are incomplete: {}",
rules.detail
),
copy: None,
}),
None => out.push(Warning {
text: format!("the routes to exit node {name} are not installed"),
copy: None,
}),
}
}
}
if exit.offering {
match &exit.offer_rules {
Some(rules) if !rules.ok => out.push(Warning {
text: format!("exit node: its rules are incomplete: {}", rules.detail),
copy: None,
}),
None => out.push(Warning {
text: "exit node: its rules are not installed yet".to_string(),
copy: None,
}),
Some(_) => {}
}
if exit.forwarding == Some(false) {
out.push(Warning {
text: format!("exit node: kernel forwarding is OFF — run: {FORWARDING_COMMAND}"),
copy: Some(FORWARDING_COMMAND),
});
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use tsunagi::ipc::{ExitReport, PeerReport, RuleSetReport};
fn network(exit: ExitReport) -> NetworkReport {
NetworkReport {
peers: vec![PeerReport {
endpoint_id: "abcdef0123456789".into(),
hostname: Some("music".into()),
exit_node: true,
..Default::default()
}],
exit,
..Default::default()
}
}
fn ok() -> Option<RuleSetReport> {
Some(RuleSetReport {
ok: true,
detail: "ok".into(),
})
}
#[test]
fn a_network_with_no_exit_settings_has_nothing_to_warn_about() {
assert!(warnings(&network(ExitReport::default())).is_empty());
}
#[test]
fn a_lost_exit_node_says_the_traffic_is_blocked() {
let found = warnings(&network(ExitReport {
via: Some("abcdef0123456789".into()),
via_online: false,
client_rules: ok(),
..Default::default()
}));
assert_eq!(found.len(), 1);
assert!(
found[0].text.contains("music is offline"),
"{}",
found[0].text
);
assert!(found[0].text.contains("blocked"), "{}", found[0].text);
}
#[test]
fn a_working_exit_node_is_quiet_and_forwarding_off_gives_the_command() {
let working = ExitReport {
via: Some("abcdef0123456789".into()),
via_online: true,
client_rules: ok(),
..Default::default()
};
assert!(warnings(&network(working)).is_empty());
let offering = warnings(&network(ExitReport {
offering: true,
offer_rules: ok(),
forwarding: Some(false),
..Default::default()
}));
assert_eq!(offering.len(), 1);
assert_eq!(offering[0].copy, Some(FORWARDING_COMMAND));
}
}
+1
View File
@@ -13,6 +13,7 @@ mod about;
mod agent;
mod app;
mod devices;
mod exit;
mod format;
mod stats;
mod tray;
+60
View File
@@ -16,6 +16,7 @@ use tsunagi::ipc::{NetworkReport, StatusReport};
use crate::agent::{AgentClient, Command, Snapshot};
use crate::devices;
use crate::exit;
use crate::format;
use crate::stats::{Traffic, Unit};
@@ -42,6 +43,8 @@ pub(crate) struct UiState {
pub(crate) open_devices: BTreeSet<String>,
/// Whether the About window is open.
pub(crate) about_open: bool,
/// An exit-node choice waiting for the user to confirm it.
pub(crate) exit_confirm: Option<devices::ExitConfirm>,
}
impl Default for UiState {
@@ -52,6 +55,7 @@ impl Default for UiState {
host_edit: None,
open_devices: BTreeSet::new(),
about_open: false,
exit_confirm: None,
}
}
}
@@ -261,6 +265,36 @@ fn draw_network(
enabled: broadcast,
});
}
let mut offering = network.exit.offering;
if ui
.checkbox(&mut offering, "exit node")
.on_hover_text(
"let other members send all their internet traffic through this \
device, which can see it",
)
.changed()
{
agent.send(Command::SetExitOffer {
network_id: network.network_id.clone(),
enabled: offering,
});
}
});
ui.horizontal(|ui| {
if let Some(via) = &network.exit.via {
ui.weak("exit");
ui.label(exit::name_of(network, via));
if ui
.small_button("off")
.on_hover_text("send internet traffic the ordinary way again")
.clicked()
{
agent.send(Command::SetExitNode {
network_id: network.network_id.clone(),
peer: None,
});
}
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Show devices").clicked() {
state.open_devices.insert(network.network_id.clone());
@@ -276,9 +310,35 @@ fn draw_network(
}
});
});
for warning in exit::warnings(network) {
draw_exit_warning(ui, &warning);
}
});
}
/// A prominent line about an exit node. One that carries a command copies it
/// when clicked.
fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) {
let text = egui::RichText::new(format!("{} {}", icon::WARNING, warning.text))
.color(exit::LOUD)
.strong();
let label = egui::Label::new(text).wrap();
match warning.copy {
Some(command) => {
let response = ui
.add(label.sense(egui::Sense::click()))
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text("click to copy the command");
if response.clicked() {
ui.ctx().copy_text(command.to_owned());
}
}
None => {
ui.add(label);
}
}
}
/// The join form: aligned name and secret, a generate button, and Join.
fn draw_join(ui: &mut egui::Ui, agent: &AgentClient, join: &mut JoinForm) {
const INPUT_WIDTH: f32 = 208.0;