Compare commits

...
6 Commits
Author SHA1 Message Date
Aleksandr Bogomiakov 68f19d1758 Release Tsunagi 1.0.10
Synchronize the Rust packages, internal dependency requirements, Android version name and Nix package version for the network card, exit picker, traffic monitor and macOS routing fixes. The speed-test protocol keeps its independent version.

Verified locked Cargo metadata and formatting for the release bump. Clippy and the macOS workspace suite passed before the metadata change (673 tests passed, 7 ignored).
2026-11-26 03:00:44 +02:00
Aleksandr Bogomiakov 8e0cfc97ac Keep Android exit lists scrolling and test exits by network
Deliver the primary touch release to egui one frame before clearing the pointer. This preserves the velocity that ScrollArea uses for a fling. Cancellations clear it immediately and a new primary touch takes precedence.

Add a speedometer to each network heading in the exit chooser. It reuses the Devices batch command and capability checks. Show queued or measured results in the existing rows and let the same control stop the batch without selecting a different exit.

Verified scroll deceleration, cancellation, consecutive gestures and per-network start/stop with egui input tests. The Android ARM64 check, formatting and workspace Clippy passed. The macOS workspace suite passed 673 tests with 7 ignored.
2026-11-26 02:58:21 +02:00
Aleksandr Bogomiakov 7b83aec3be Keep the network address visible as peers reconnect
The collapsed card allocated the graph and peer count before the address and reserved a fixed 110 points for every network name. A growing count could hide an assigned address, even beside a short name. Measure the title and reserve the address first. Use the remaining space for counts and the sparkline, and include the address in the card tooltip.

Reproduced the old layout failure and verified the vpn card at 320 and 359 points as its online count grows from 1 to 14. Confirmed the agent and macOS interface still had the reported address.
2026-11-26 02:57:38 +02:00
Aleksandr Bogomiakov 21de427c62 Show known mesh names in traffic monitor endpoints
Index peer and VIP addresses from the agent status by network ID. Use the mesh DNS zone spelling in the IP flow columns, retain ports and show the numeric endpoint on hover or long press. A checkbox switches the display without changing capture keys, numeric sorting or stored history.

Verified overlapping networks, external addresses, VIP withdrawal and the rendered checkbox and tooltip in the tsunagi-ui tests on macOS.
2026-11-26 02:57:09 +02:00
Aleksandr Bogomiakov a1da4bf498 Restore workspace checks on GitHub Actions
Install the GTK and Ayatana development packages in every Linux job that builds the tray. Check the core package explicitly in the library-only job. The peer exchange and WireGuard examples no longer exist. Their scenarios are integration tests in the workspace. Keep those tests and smoke-test the shipped tsng binary.

Open the Windows log-rotation fixture with write access when extending it. An append-only handle cannot set EOF on Windows. Verify the rotated file retains its full length. Remove public rustdoc links to private or platform-specific items while keeping warnings fatal.

Verified 697 workspace tests on Linux ARM64 and 668 on macOS. Formatting, Clippy, rustdoc with warnings denied, the core-only check and the CLI smoke test passed. Linux also passed the Rust 1.91.0 workspace check and the Debian upgrade-order fixture. No native Windows runner was available locally.
2026-11-26 02:24:36 +02:00
Aleksandr Bogomiakov 9920d4c10f Preserve macOS exit replies and isolate the Linux service fixture
Apple PF restores the forwarding tag from the physical NAT state on replies. Steer only packets sourced in an offered mesh and destined outside the offered ranges. Reverse-translated replies can then leave on the utun, including while the local host uses an upstream exit.

Apply the same rule in the authorized sharing helper. An older installed copy can still clear its anchors. Re-enabling sharing upgrades it through the normal authorization dialog and preserves existing subnet grants.

Run the Linux namespace B process with a service environment. Give its parent an explicit login environment in CI to keep exercising this boundary without weakening the agent’s login-session guard.

Reproduced the Linux denial and passed the corrected established-flow test in isolated kernel namespaces. On macOS the workspace suite, Clippy, formatting, exit helper regressions and the PF syntax check passed. The privileged two-utun test requires a disposable Mac and was not run locally.
2026-11-26 02:20:40 +02:00
41 changed files with 821 additions and 202 deletions

No files matched your search

+14 -6
View File
@@ -23,6 +23,12 @@ jobs:
with:
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2
- &linux-tray-deps
name: Install GTK and AppIndicator development files
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends libgtk-3-dev libayatana-appindicator3-dev
- run: cargo fmt --all -- --check
- run: cargo clippy --locked --workspace --all-targets -- -D warnings
- name: Check Debian release candidate upgrade ordering
@@ -39,11 +45,11 @@ jobs:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo test --locked --workspace --all-targets
- name: run the examples
run: |
cargo run --locked --example two_agents
cargo run --locked --example wireguard_mesh
- *linux-tray-deps
- name: Test the workspace, including peer exchange and WireGuard integration
run: cargo test --locked --workspace --all-targets
- name: Start the command line client
run: cargo run --locked --bin tsng -- --version
# The library must keep building without the command line binary and
# without interface support, for embedders that want neither.
@@ -54,7 +60,7 @@ jobs:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo check --locked --no-default-features --lib
- run: cargo check --locked -p tsunagi-core --no-default-features --lib
docs:
name: rustdoc
@@ -63,6 +69,7 @@ jobs:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- *linux-tray-deps
- run: cargo doc --locked --workspace --no-deps
env:
RUSTDOCFLAGS: -D warnings
@@ -74,4 +81,5 @@ jobs:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@1.91.0
- uses: Swatinem/rust-cache@v2
- *linux-tray-deps
- run: cargo check --locked --workspace --all-targets
+2 -1
View File
@@ -65,7 +65,8 @@ jobs:
- name: Verify separate forwarding and local egress in Linux namespaces
if: runner.os == 'Linux'
shell: bash
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
# The invoking login and the service inside namespace B have distinct environments.
run: sudo -n -- env XDG_RUNTIME_DIR="/run/user/$(id -u)" "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
- name: Verify source selection on a real utun
if: runner.os == 'macOS'
shell: bash
Generated
+10 -10
View File
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tsunagi"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"anstream",
"anstyle",
@@ -6320,7 +6320,7 @@ dependencies = [
[[package]]
name = "tsunagi-android"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"bytes",
"egui",
@@ -6344,7 +6344,7 @@ dependencies = [
[[package]]
name = "tsunagi-awg"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"bytes",
"iroh",
@@ -6359,7 +6359,7 @@ dependencies = [
[[package]]
name = "tsunagi-core"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"arc-swap",
"bytes",
@@ -6404,7 +6404,7 @@ dependencies = [
[[package]]
name = "tsunagi-runtime"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"tokio",
"tracing",
@@ -6427,7 +6427,7 @@ dependencies = [
[[package]]
name = "tsunagi-tcp-tls"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"bytes",
"caps",
@@ -6447,7 +6447,7 @@ dependencies = [
[[package]]
name = "tsunagi-tray"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"eframe",
"egui-phosphor",
@@ -6463,7 +6463,7 @@ dependencies = [
[[package]]
name = "tsunagi-ui"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"egui",
"egui-phosphor",
@@ -6476,7 +6476,7 @@ dependencies = [
[[package]]
name = "tsunagi-wg-quic"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"boringtun",
"bytes",
@@ -6503,7 +6503,7 @@ dependencies = [
[[package]]
name = "tsunagi-wireguard"
version = "1.0.9"
version = "1.0.10"
dependencies = [
"boringtun",
"bytes",
+7 -2
View File
@@ -206,10 +206,15 @@ address/port pair and repeated ICMP echoes for an address pair into one row. Sel
role to narrow it down. **Via exit node** shows your outgoing internet traffic.
**Serving exit** shows traffic your device forwards for another peer.
**Resolve names** shows known peers and VIPs by their network names in the
endpoint columns. Hover over a name, or press and hold on Android, to see the
IP address. Clear the checkbox to show all endpoints numerically.
**Transport** shows authenticated control sessions and encrypted datagrams
forwarded between two other endpoints. For relay rows the arrows follow the
two displayed endpoints in order. Rates update once per second. Select a row
to see its packet counts. The monitor records header metadata and counters only.
two displayed endpoints in order. Rates update once per second. Use the
**TX packets** and **RX packets** columns to see packet counts. The monitor
records header metadata and counters only.
Inactive rows expire after 60 seconds. **Keep until close** retains flows in a
private temporary table owned by the window. Closing it discards the table and
+2
View File
@@ -30,6 +30,8 @@ Rotate the phone to select a network on the left and see its settings on the rig
Tap the round exit button at the bottom right of the home screen. The list groups available gateways by network and shows each peer’s measured data RTT and path. **No exit node** returns to this phone’s internet connection. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
Tap the speedometer beside a network name in the exit list to test its compatible online exits one at a time. Each row shows download and upload in Mbit/s. The stop button ends the test and skips queued peers. Testing keeps the current exit selection.
To switch the exit from the notification shade, edit Android Quick Settings and add **Tsunagi Exit**. The first tap opens the exit chooser if you have never used one. Subsequent taps disconnect the selected exit or reconnect the last peer in its original network. The tile shows the peer name and whether the selected peer is offline. Mesh access stays available when the exit is off.
## Check two networks on an emulator
+1 -1
View File
@@ -24,7 +24,7 @@ android {
targetSdk 35
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.9')
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.10')
ndk { abiFilters abi }
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-android"
version = "1.0.9"
version = "1.0.10"
description = "Android VPN client and egui views for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
crate-type = ["cdylib"]
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.9" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.10" }
tsunagi-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
+11 -37
View File
@@ -1,8 +1,9 @@
//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets.
use crate::view::{Phone, SystemAction};
use egui::{
Event, ImeEvent, Key, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase,
use crate::{
touch::TouchInput,
view::{Phone, SystemAction},
};
use egui::{Event, ImeEvent, Key, Modifiers, Pos2, TouchPhase};
use egui_glow::{Painter, glow};
use jni::{
JNIEnv,
@@ -26,7 +27,7 @@ struct Display {
ctx: egui::Context,
ui: Phone,
events: Vec<Event>,
primary: Option<i32>,
touch: TouchInput,
start: Instant,
ime: i32,
exit_active: bool,
@@ -81,7 +82,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(
ctx,
ui,
events: Vec::new(),
primary: None,
touch: TouchInput::default(),
start: Instant::now(),
ime: -1,
exit_active: false,
@@ -104,7 +105,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
let size = egui::vec2(w as f32, h as f32) / scale;
let mut input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
events: std::mem::take(&mut d.events),
events: d.touch.take_frame(&mut d.events),
time: Some(d.start.elapsed().as_secs_f64()),
..Default::default()
};
@@ -122,6 +123,9 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
}
d.exit_active = exit_active;
let output = d.ctx.run(input, |ctx| {
if !d.events.is_empty() {
ctx.request_repaint();
}
action = d.ui.draw(ctx, &state, super::send).or(action);
});
d.ui.poll_monitor(|| super::submit(crate::service::Request::WatchTraffic));
@@ -201,37 +205,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_touch(
2 => TouchPhase::End,
_ => TouchPhase::Cancel,
};
d.events.push(Event::Touch {
device_id: TouchDeviceId(0),
id: TouchId(id as u64),
phase,
pos,
force: None,
});
if phase == TouchPhase::Start && d.primary.is_none() {
d.primary = Some(id);
}
if d.primary != Some(id) {
return;
}
if phase != TouchPhase::Cancel {
d.events.push(Event::PointerMoved(pos));
}
if phase != TouchPhase::Move {
if phase == TouchPhase::Cancel {
d.events.push(Event::PointerGone);
}
d.events.push(Event::PointerButton {
pos,
button: PointerButton::Primary,
pressed: phase == TouchPhase::Start,
modifiers: Modifiers::NONE,
});
}
if matches!(phase, TouchPhase::Cancel | TouchPhase::End) {
d.events.push(Event::PointerGone);
d.primary = None;
}
d.touch.push(&mut d.events, phase, id, pos);
});
}
#[unsafe(no_mangle)]
+2
View File
@@ -9,6 +9,8 @@ mod android;
pub mod service;
#[cfg(test)]
mod tests;
#[cfg(any(target_os = "android", test))]
mod touch;
#[cfg(unix)]
pub mod tun;
pub mod view;
+161
View File
@@ -0,0 +1,161 @@
//! Translate Android fingers into egui touch events and one primary pointer.
use egui::{Event, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase};
#[derive(Default)]
pub(crate) struct TouchInput {
primary: Option<i32>,
clear_after_release: bool,
}
impl TouchInput {
pub(crate) fn push(&mut self, events: &mut Vec<Event>, phase: TouchPhase, id: i32, pos: Pos2) {
events.push(Event::Touch {
device_id: TouchDeviceId(0),
id: TouchId(id as u64),
phase,
pos,
force: None,
});
if phase == TouchPhase::Start && self.primary.is_none() {
self.primary = Some(id);
self.clear_after_release = false;
}
if self.primary != Some(id) {
return;
}
if phase != TouchPhase::Cancel {
events.push(Event::PointerMoved(pos));
}
if phase != TouchPhase::Move {
events.push(Event::PointerButton {
pos,
button: PointerButton::Primary,
pressed: phase == TouchPhase::Start,
modifiers: Modifiers::NONE,
});
}
match phase {
TouchPhase::End => {
self.primary = None;
self.clear_after_release = true;
}
TouchPhase::Cancel => {
self.primary = None;
events.push(Event::PointerGone);
}
_ => {}
}
}
pub(crate) fn take_frame(&mut self, events: &mut Vec<Event>) -> Vec<Event> {
let frame = std::mem::take(events);
// ScrollArea reads the release velocity in this frame. PointerGone clears
// egui's position history, so clear the touch hover in the following frame.
if std::mem::take(&mut self.clear_after_release) {
events.push(Event::PointerGone);
}
frame
}
}
#[cfg(test)]
mod tests {
use super::*;
use egui::{CentralPanel, Context, RawInput, Rect, ScrollArea, pos2, vec2};
#[test]
fn a_flick_coasts_and_slows_while_a_cancelled_drag_stops() {
for end in [TouchPhase::End, TouchPhase::Cancel] {
let ctx = Context::default();
ctx.set_os(egui::os::OperatingSystem::Android);
let mut input = TouchInput::default();
let mut events = Vec::new();
let mut frame_no = 0;
let mut frame = |touch| {
if let Some((phase, y)) = touch {
input.push(&mut events, phase, 0, pos2(80., y));
}
frame_no += 1;
let mut offset = 0.;
let _ = ctx.run(
RawInput {
time: Some(f64::from(frame_no) / 60.),
events: input.take_frame(&mut events),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(320., 320.))),
..Default::default()
},
|ctx| {
CentralPanel::default().show(ctx, |ui| {
offset = ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
for i in 0..60 {
ui.add_sized(
[270., 40.],
egui::Button::new(format!("Peer {i}")),
);
}
})
.state
.offset
.y;
});
},
);
offset
};
// The first layout measures the content. The next registers its drag area.
frame(None);
frame(None);
frame(Some((TouchPhase::Start, 220.)));
for y in [208., 190., 168., 146.] {
frame(Some((TouchPhase::Move, y)));
}
let released = frame(Some((end, 126.)));
let first = frame(None);
let second = frame(None);
assert!(released > 0., "{end:?} should follow a drag");
if end == TouchPhase::End {
assert!(
second > first && first > released,
"the scroll should coast after release"
);
assert!(
second - first < first - released,
"the fling should decelerate"
);
} else {
assert_eq!((released, first), (first, second));
}
}
}
#[test]
fn a_new_primary_touch_supersedes_a_release_in_the_same_frame() {
let mut input = TouchInput::default();
let mut events = Vec::new();
for (phase, id) in [
(TouchPhase::Start, 1),
(TouchPhase::End, 1),
(TouchPhase::Start, 2),
] {
input.push(&mut events, phase, id, Pos2::ZERO);
}
let frame = input.take_frame(&mut events);
assert!(matches!(
frame.last(),
Some(Event::PointerButton { pressed: true, .. })
));
assert!(events.is_empty());
input.push(&mut events, TouchPhase::End, 2, Pos2::ZERO);
let release = input.take_frame(&mut events);
assert!(matches!(
release.last(),
Some(Event::PointerButton { pressed: false, .. })
));
assert!(matches!(
input.take_frame(&mut events).as_slice(),
[Event::PointerGone]
));
}
}
+1 -1
View File
@@ -493,7 +493,7 @@ impl Phone {
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
}
Page::Exits => {
if let Some(choice) = devices::choose_exit_from_networks(ui, &report.networks, &report.endpoint_id) {
if let Some(choice) = devices::choose_exit_with_tests(ui, &report.networks, &report.endpoint_id, &actions) {
self.forms.exit_confirm = Some(choice);
}
if report.networks.is_empty() && ui.button("Join or create a network").clicked() {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-awg"
version = "1.0.9"
version = "1.0.10"
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true
rust-version.workspace = true
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-core"
version = "1.0.9"
version = "1.0.10"
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
readme = "../../README.md"
keywords = ["mesh", "p2p", "iroh", "networking"]
+1 -1
View File
@@ -3,7 +3,7 @@
//! One of the per-platform adapters; see [`super`]. It provides only what is
//! particular to a Unix socket — binding a listener, connecting a client, and
//! the owner-only permissions — and hands every accepted connection to the
//! shared [`serve_connection`](super::serve_connection). The request framing,
//! shared connection handler. The request framing,
//! the dispatch and the client wrappers are the same on every platform and
//! live in [`super`], re-exported here so `ipc::unix::request_status` and its
//! siblings keep resolving.
+2 -2
View File
@@ -1,9 +1,9 @@
//! A named-pipe adapter for the local control interface.
//!
//! The Windows counterpart of [`super::unix`]. It provides only what is
//! The Windows counterpart of the Unix socket adapter. It provides only what is
//! particular to a named pipe — creating the server instance, opening a client
//! and turning the state directory path into a pipe name — and hands every
//! accepted connection to the shared [`serve_connection`](super::serve_connection).
//! accepted connection to the shared connection handler.
//! The framing, the dispatch and the client wrappers are the same on every
//! platform and live in [`super`], re-exported here so `ipc::windows::request_status`
//! and its siblings resolve just as their Unix equivalents do.
@@ -669,6 +669,8 @@ fn serving_an_established_flow_while_switching_the_local_exit() {
.arg(std::env::current_exe().unwrap())
.args(["--ignored", "--exact", CHAIN_TEST, "--nocapture"])
.env("TSUNAGI_EXIT_CHAIN_A", &a.0)
// B runs as a system service, even when the test was started from a login.
.env_remove("XDG_RUNTIME_DIR")
.output()
.unwrap();
assert!(
@@ -66,8 +66,8 @@ fn firewall_todo(plan: &BroadcastRulesPlan) -> String {
)
}
/// The macOS implementation: `route` for the route, no firewall yet, and
/// `pf` plus `route` for exit nodes (see [`super::macos_exit`]).
/// Installs macOS broadcast routes with `route` and manages exit routing with
/// `pf` and `route`.
#[derive(Debug, Default)]
pub struct MacosHostRules {
/// The PF reference and the physical routes owned by this agent.
@@ -14,7 +14,7 @@ helper="$directory/offer-v1"
/bin/chmod 0755 "$directory"
tmp=$(/usr/bin/mktemp -d "$directory/.install.XXXXXXXX")
trap '/bin/rm -rf "$tmp"' EXIT
printf '%s\n' "$helper_body" > "$tmp/offer"
printf '%s' "$helper_body" > "$tmp/offer"
printf '#%s ALL = (root) NOPASSWD: NOSETENV: %s\n' "$uid" "$helper" > "$tmp/rule"
/usr/sbin/visudo -c -q -f "$tmp/rule"
/bin/chmod 0755 "$tmp/offer"
@@ -125,7 +125,7 @@ if [ ! -f "$record" ]; then
fi
if ! /sbin/pfctl -q -a "$anchor" -f - <<RULES
nat on $out inet from $range to any tagged $tag -> ($out)
pass out quick on $iface route-to $via inet from any to any tagged $tag no state
pass out quick on $iface route-to $via inet from $range to ! $range tagged $tag no state
pass in quick on $iface inet from $range to ! $range tag $tag no state
pass out quick on $out inet from any to any flags any tagged $tag keep state (if-bound)
RULES
@@ -10,7 +10,7 @@
//! ```text
//! nat on <egress> inet from <range> to any tagged <forwarded> -> (<egress>)
//! pass in quick on <if> inet from <range> to ! <range> tag <forwarded> no state
//! pass out quick on <if> route-to (<egress> <gateway>) inet from <range> to any tagged <forwarded> no state
//! pass out quick on <if> route-to (<egress> <gateway>) inet from <range> to ! <range> tagged <forwarded> no state
//! pass out quick on <egress> inet from any to any flags any tagged <forwarded> keep state (if-bound)
//! ```
//!
@@ -88,6 +88,15 @@ use super::macos_authorization::{macos_exit_authorization_uid, macos_exit_needs_
const OFFER_HELPER: &str = "/private/etc/tsunagi-exit/offer-v1";
fn offer_helper_available(path: &std::path::Path, action: &str) -> bool {
// A previous release can still remove its own PF anchors. Applying its
// obsolete rules would silently restore the broken return path.
if action == "clear" {
return path.is_file();
}
std::fs::read(path).is_ok_and(|bytes| bytes == include_bytes!("macos/exit-offer.sh").as_slice())
}
/// The programs this module runs, always by absolute path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Tool {
@@ -133,7 +142,11 @@ pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran
use std::process::{Command, Stdio};
let mut command = if tool == Tool::OfferHelper {
if !std::path::Path::new(OFFER_HELPER).is_file() {
let path = std::path::Path::new(OFFER_HELPER);
if !args
.first()
.is_some_and(|op| offer_helper_available(path, op))
{
return Ran::Missing;
}
let mut sudo = Command::new("/usr/bin/sudo");
@@ -415,23 +428,30 @@ fn pf_rules(
from any to any flags any tagged {tag} keep state (if-bound)"
));
}
for range in offer {
if let [first, rest @ ..] = offer {
let members = if rest.is_empty() {
first.to_string()
} else {
let name = format!("<tsunagi_offer_{interface}>");
let ranges: Vec<_> = offer.iter().map(ToString::to_string).collect();
tables.push(format!("table {name} const {{ {} }}", ranges.join(", ")));
name
};
let tag = format!("tsng_forward_{interface}");
nat.push(format!(
"nat on {out} inet from {range} to any tagged {tag} -> ({out})"
"nat on {out} inet from {members} to any tagged {tag} -> ({out})"
));
// Classify at authenticated overlay ingress. Only packets the host
// actually forwards AND its routes send back to our utun need steering.
// Local services, connected LANs and the owner's forwarding switch
// retain their native kernel behavior.
filter.push(format!(
"pass in quick on {interface} inet from {range} to ! {range} tag {tag} no state"
"pass in quick on {interface} inet from {members} to ! {members} tag {tag} no state"
));
}
if !offer.is_empty() {
let tag = format!("tsng_forward_{interface}");
// PF restores the state's tag on replies after undoing NAT. A reply
// routed back to a member must leave on the overlay with that tag.
filter.insert(0, format!(
"pass out quick on {interface} route-to {via} inet from any to any tagged {tag} no state"
"pass out quick on {interface} route-to {via} inet from {members} to ! {members} tagged {tag} no state"
));
// Keep the outbound NAT state on the physical interface. A floating
// state could consume packets on the utun before the reroute rule runs.
@@ -1166,7 +1186,7 @@ destination: default\n\
assert_eq!(
text,
"nat on en0 inet from 10.13.37.0/24 to any tagged tsng_forward_utun5 -> (en0)\n\
pass out quick on utun5 route-to (en0 192.168.1.1) inet from any to any tagged tsng_forward_utun5 no state\n\
pass out quick on utun5 route-to (en0 192.168.1.1) inet from 10.13.37.0/24 to ! 10.13.37.0/24 tagged tsng_forward_utun5 no state\n\
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
);
@@ -1174,6 +1194,32 @@ destination: default\n\
assert!(text.find("nat on").unwrap() < text.find("pass in").unwrap());
}
#[test]
fn forwarding_excludes_replies_to_every_offered_mesh() {
let ranges = [range(), "10.99.0.0/16".parse().unwrap()];
let client = ClientRules {
uid: 0,
overlay: &ranges,
};
for local_exit in [None, Some(&client)] {
let text = pf_rules("utun5", &egress(), &ranges, local_exit);
let offered = "<tsunagi_offer_utun5>";
assert!(text.contains(&format!(
"table {offered} const {{ 10.13.37.0/24, 10.99.0.0/16 }}"
)));
let mut steering = text
.lines()
.filter(|r| r.contains("route-to") && r.contains("tagged tsng_forward_"));
assert!(
steering
.next()
.unwrap()
.contains(&format!("from {offered} to ! {offered} "))
);
assert!(steering.next().is_none());
}
}
#[test]
fn the_agents_tagged_nat_precedes_any_general_masquerade_for_offered_ranges() {
let ranges = [range()];
@@ -1289,7 +1335,7 @@ destination: default\n\
assert_eq!(
fake.stdins.borrow()[0],
"nat on en0 inet from 10.13.37.0/24 to any tagged tsng_forward_utun5 -> (en0)\n\
pass out quick on utun5 route-to (en0 192.168.1.1) inet from any to any tagged tsng_forward_utun5 no state\n\
pass out quick on utun5 route-to (en0 192.168.1.1) inet from 10.13.37.0/24 to ! 10.13.37.0/24 tagged tsng_forward_utun5 no state\n\
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
);
@@ -146,6 +146,25 @@ fn privileged_helper_accepts_only_a_granted_subnet_configured_on_the_utun() {
);
}
#[test]
fn an_update_replaces_the_old_helper_and_preserves_existing_subnet_grants() {
let host = Host::new();
let helper = host.0.path().join("grants/offer-v1");
assert!(!super::offer_helper_available(&helper, "clear"));
host.grant("501", "10.13.37.0_24");
fs::write(&helper, "#!/bin/sh\n# previous release\n").unwrap();
assert!(!super::offer_helper_available(&helper, "apply"));
assert!(super::offer_helper_available(&helper, "clear"));
host.grant("501", "10.99.0.0_16");
assert!(super::offer_helper_available(&helper, "apply"));
assert!(
host.0
.path()
.join("grants/grant_501_10.13.37.0_24")
.is_file()
);
}
#[test]
fn authorized_exit_owns_one_pf_reference_and_clears_only_its_anchor() {
let host = Host::new();
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-runtime"
version = "1.0.9"
version = "1.0.10"
description = "Built-in mesh transports and status reporting for native tsunagi agents."
edition.workspace = true
rust-version.workspace = true
@@ -8,11 +8,11 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.9" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.9" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.9" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.9" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.10" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.10" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.10" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.10" }
tokio.workspace = true
tracing.workspace = true
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tcp-tls"
version = "1.0.9"
version = "1.0.10"
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
rustls = "0.23"
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tray"
version = "1.0.9"
version = "1.0.10"
description = "Tray application to manage a running tsunagi agent."
edition.workspace = true
rust-version.workspace = true
@@ -16,7 +16,7 @@ tsunagi-ui = { path = "../tsunagi-ui" }
# The agent control client and the report types: the GUI is a thin client over
# the same local control interface the CLI uses, so it reuses these directly
# and never re-implements the protocol.
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
# Native, lightweight GUI — no web engine. eframe re-exports egui.
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
# Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-ui"
version = "1.0.9"
version = "1.0.10"
description = "Shared egui widgets for the tray and Android clients."
edition.workspace = true
rust-version.workspace = true
+4 -2
View File
@@ -13,7 +13,9 @@ mod speed;
mod speed_tests;
mod status;
pub use crate::exit::name_of;
pub use exit_picker::{choose_exit, choose_exit_from_networks, exit_action_colors};
pub use exit_picker::{
choose_exit, choose_exit_from_networks, choose_exit_with_tests, exit_action_colors,
};
use egui_phosphor::regular as icon;
@@ -244,7 +246,7 @@ pub fn show(
"devices ({online} online / {} known)",
devices.len()
));
speed.toolbar(ui);
speed.batch_button(ui, false);
});
};
+57 -20
View File
@@ -1,5 +1,5 @@
//! One touch target per exit, grouped by the network that will carry the traffic.
use super::{ExitConfirm, devices};
use super::{Client, ExitConfirm, devices, speed};
use crate::{exit, format, widgets};
use egui::{Align, Align2, Color32, FontFamily, FontId, Rect, Sense, Ui, pos2, vec2};
use egui_phosphor::regular as icon;
@@ -15,6 +15,25 @@ pub fn choose_exit_from_networks(
ui: &mut Ui,
networks: &[NetworkReport],
own: &str,
) -> Option<ExitConfirm> {
chooser(ui, networks, own, None)
}
/// The interactive Android picker can also measure every eligible exit in one network.
pub fn choose_exit_with_tests(
ui: &mut Ui,
networks: &[NetworkReport],
own: &str,
client: &dyn Client,
) -> Option<ExitConfirm> {
chooser(ui, networks, own, Some(client))
}
fn chooser(
ui: &mut Ui,
networks: &[NetworkReport],
own: &str,
client: Option<&dyn Client>,
) -> Option<ExitConfirm> {
let current = networks
.iter()
@@ -28,7 +47,7 @@ pub fn choose_exit_from_networks(
glyph: icon::GLOBE,
};
let mut choice = None;
if local.draw(ui, "local internet")
if local.draw(ui, "local internet", None)
&& let Some((network, id)) = current
{
choice = Some(ExitConfirm::stop_from_tile(network, id));
@@ -64,17 +83,30 @@ pub fn choose_exit_from_networks(
network.name.clone()
};
ui.add_space(10.);
let (header, hint) =
ui.allocate_exact_size(vec2(ui.available_width(), 30.), Sense::hover());
widgets::single_line(
ui.painter(),
header,
Align::Min,
&title,
bold(19.),
ui.visuals().strong_text_color(),
);
widgets::hint(hint, &network.network_id);
ui.push_id(&network.network_id, |ui| {
ui.horizontal(|ui| {
let (height, button_space) = if client.is_some() {
(44., 44. + ui.spacing().item_spacing.x)
} else {
(30., 0.)
};
let title_width = (ui.available_width() - button_space).max(0.);
let (header, hint) =
ui.allocate_exact_size(vec2(title_width, height), Sense::hover());
widgets::single_line(
ui.painter(),
header,
Align::Min,
&title,
bold(19.),
ui.visuals().strong_text_color(),
);
widgets::hint(hint, &network.network_id);
if let Some(client) = client {
speed::Controls::new(network, client).batch_button(ui, true);
}
});
});
if let Some(rules) = &network.exit.client_rules
&& !rules.ok
{
@@ -94,7 +126,7 @@ pub fn choose_exit_from_networks(
selected: true,
glyph: icon::SIGN_OUT,
}
.draw(ui, (&network.network_id, id));
.draw(ui, (&network.network_id, id), None);
}
for d in candidates {
let name = d.name();
@@ -112,15 +144,17 @@ pub fn choose_exit_from_networks(
}
};
let latency = d.data_rtt_ms.map(|ms| format!("{ms} ms"));
let speed = network.speed.peers.get(d.id).map(speed::exit_caption);
let address = d.address.as_deref();
let row = Row {
name: &name,
caption: d.address.as_deref().unwrap_or(""),
caption: speed.as_deref().or(address).unwrap_or(""),
latency: latency.as_deref(),
path: Some(&path),
selected: d.in_use,
glyph: icon::SIGN_OUT,
};
if row.draw(ui, (&network.network_id, d.id)) && !d.in_use {
if row.draw(ui, (&network.network_id, d.id), address) && !d.in_use {
choice = Some(ExitConfirm {
network_id: network.network_id.clone(),
peer_id: d.id.into(),
@@ -159,7 +193,7 @@ struct Row<'a> {
glyph: &'static str,
}
impl Row<'_> {
fn draw(&self, ui: &mut Ui, id: impl std::hash::Hash) -> bool {
fn draw(&self, ui: &mut Ui, id: impl std::hash::Hash, hint: Option<&str>) -> bool {
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 58.), Sense::hover());
let response = ui.interact(
rect,
@@ -273,9 +307,12 @@ impl Row<'_> {
detail,
);
}
response
.on_hover_cursor(egui::CursorIcon::PointingHand)
.clicked()
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
match hint {
Some(hint) => widgets::hint(response, hint),
None => response,
}
.clicked()
}
}
+51 -28
View File
@@ -29,21 +29,15 @@ impl<'a> Controls<'a> {
self.network.speed.capable.iter().any(|peer| peer == id)
}
pub(super) fn toolbar(&self, ui: &mut Ui) {
let (label, help, available) = if self.running {
pub(super) fn batch_button(&self, ui: &mut Ui, icon_only: bool) {
let (glyph, label, help, available) = if self.running {
ui.ctx().request_repaint_after(Duration::from_millis(250));
let label = self.network.speed.batch.map_or_else(
|| format!("{} Stop test", icon::STOP_CIRCLE),
|batch| {
format!(
"{} Stop {}/{}",
icon::STOP_CIRCLE,
batch.done,
batch.total
)
},
|| "Stop test".to_owned(),
|batch| format!("Stop {}/{}", batch.done, batch.total),
);
(
icon::STOP_CIRCLE,
label,
"Stop this speed test and skip any queued exits.",
true,
@@ -56,7 +50,8 @@ impl<'a> Controls<'a> {
.iter()
.any(|p| p.exit_node && self.capable(&p.endpoint_id));
(
format!("{} Test exits", icon::GAUGE),
icon::GAUGE,
"Test exits".to_owned(),
if available {
"Test each compatible online exit node in this network, one at a time."
} else {
@@ -65,22 +60,26 @@ impl<'a> Controls<'a> {
available,
)
};
// Leave room for the batch count before starting. A wrapping toolbar
// must keep the same height when the button becomes Stop.
let width = ui
.painter()
.layout_no_wrap(
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
egui::TextStyle::Button.resolve(ui.style()),
ui.visuals().text_color(),
)
.size()
.x
+ 2. * ui.spacing().button_padding.x;
let button = ui.add_enabled(
available && !self.client.busy(),
egui::Button::new(label).min_size(vec2(width, 0.)),
);
let button = if icon_only {
egui::Button::new(egui::RichText::new(glyph).size(22.)).min_size(vec2(44., 44.))
} else {
// Switching to Stop must not wrap a toolbar onto a second line.
let width = ui
.painter()
.layout_no_wrap(
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
egui::TextStyle::Button.resolve(ui.style()),
ui.visuals().text_color(),
)
.size()
.x
+ 2. * ui.spacing().button_padding.x;
egui::Button::new(format!("{glyph} {label}")).min_size(vec2(width, 0.))
};
let button = ui.add_enabled(available && !self.client.busy(), button);
button.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, button.enabled(), &label)
});
if widgets::hint(button, help).clicked() {
let network_id = self.network.network_id.clone();
let command = if self.running {
@@ -132,6 +131,30 @@ impl<'a> Controls<'a> {
}
}
pub(super) fn exit_caption(test: &SpeedPeerReport) -> String {
match test.phase {
SpeedPhase::Queued => "Queued".into(),
SpeedPhase::Preparing => "Starting…".into(),
SpeedPhase::Cancelled => "Stopped".into(),
SpeedPhase::Failed(_) => "Test failed".into(),
SpeedPhase::Download | SpeedPhase::Upload | SpeedPhase::Done => {
let rate = |value: Option<SpeedRate>, phase| {
value.map_or_else(
|| if test.phase == phase { "…" } else { "—" }.into(),
compact_rate,
)
};
format!(
"{} {} {} {} Mbit/s",
icon::ARROW_DOWN,
rate(test.down, SpeedPhase::Download),
icon::ARROW_UP,
rate(test.up, SpeedPhase::Upload)
)
}
}
}
fn paint_reading(
ui: &Ui,
rect: Rect,
@@ -52,6 +52,76 @@ fn reading(phase: SpeedPhase) -> SpeedPeerReport {
}
}
#[test]
fn exit_picker_tests_only_the_tapped_network_and_keeps_the_route_selection() {
let screen = Screen::new(320., true);
let a = network();
let mut b = network();
b.name = "office".into();
b.network_id = "office-id".into();
b.exit.via = Some("alice".into());
let mut nets = [a, b];
let draw = |nets: &[NetworkReport], events| {
screen.ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(320., 650.),
)),
events,
..Default::default()
},
|ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
assert!(choose_exit_with_tests(ui, nets, "self", &screen.log).is_none());
assert!(ui.min_rect().right() <= 320.);
});
},
)
};
let tap = |nets: &[NetworkReport], pos| {
for pressed in [true, false] {
draw(
nets,
vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
},
],
);
}
};
let first = draw(&nets, vec![]);
let gauges = positions(&first, |s| s == icon::GAUGE);
assert_eq!(gauges.len(), 2);
let office = positions(&first, |s| s == "office")[0];
let button = *gauges.iter().find(|p| (p.y - office.y).abs() < 4.).unwrap();
tap(&nets, button);
assert!(
matches!(screen.log.0.borrow().as_slice(), [Command::StartSpeedTest { network_id, peer: None }] if network_id == "office-id")
);
nets[1].speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
nets[1]
.speed
.peers
.insert("alice".into(), reading(SpeedPhase::Upload));
let live = draw(&nets, vec![]);
assert!(!positions(&live, |s| s.contains("125") && s.contains("Mbit/s")).is_empty());
let stop = positions(&live, |s| s == icon::STOP_CIRCLE)[0];
tap(&nets, stop);
assert!(
matches!(screen.log.0.borrow().last(), Some(Command::StopSpeedTest { network_id }) if network_id == "office-id")
);
nets[1].speed = Default::default();
draw(&nets, vec![]);
tap(&nets, button);
assert_eq!(screen.log.0.borrow().len(), 2);
}
struct Screen {
ctx: egui::Context,
width: f32,
+40 -27
View File
@@ -88,39 +88,52 @@ pub(super) fn header(
let left = dot.x + 9.;
let mut right = rect.right() - 2.;
let quiet = ui.visuals().weak_text_color();
// Preserve a useful piece of the name even on the narrow landscape selector.
if right - left > 98. {
let width = (rect.width() * 0.15).clamp(26., 64.);
let title_font = FontId::new(font.size + 4., egui::FontFamily::Name("Bold".into()));
let strong = ui.visuals().strong_text_color();
let title = painter.layout_no_wrap(net.name.clone(), title_font.clone(), strong);
let mut spare = right - left - title.size().x.min(64.);
const GAP: f32 = 8.;
let mut reserve = |text| {
let galley = painter.layout_no_wrap(text, font.clone(), ink);
let width = galley.size().x + GAP;
if width > spare {
return None;
}
spare -= width;
Some(galley)
};
// Reserve the address first. Peer counts grow as sessions reconnect.
let address = net.overlay.as_ref().and_then(|o| o.address.as_deref());
let ip = address.and_then(|s| reserve(s.to_owned()));
let peers = reserve(format!("{} {online}/{known}", icon::DEVICES));
let clients = if users > 0 {
reserve(format!("{} {users}", icon::SIGN_IN))
} else {
None
};
let width = (rect.width() * 0.15).min(64.).min(spare - GAP);
if width >= 26. {
let plot = Rect::from_center_size(pos2(right - width / 2., center), vec2(width, 14.));
format::mini_traffic(&painter, plot, series, unit, quiet, net.active);
right = plot.left() - 7.;
right = plot.left() - GAP;
}
let mut field = |text: String, reserved: f32| {
let galley = painter.layout_no_wrap(text, font.clone(), ink);
if right - left - galley.size().x >= reserved {
right -= galley.size().x;
painter.galley(pos2(right, center - galley.size().y / 2.), galley, ink);
right -= 8.;
}
};
field(format!("{} {online}/{known}", icon::DEVICES), 45.);
if users > 0 {
field(format!("{} {users}", icon::SIGN_IN), 60.);
for galley in [peers, clients, ip].into_iter().flatten() {
right -= galley.size().x;
painter.galley(pos2(right, center - galley.size().y / 2.), galley, ink);
right -= GAP;
}
if let Some(addr) = net.overlay.as_ref().and_then(|o| o.address.as_deref()) {
field(addr.to_owned(), 110.);
}
let mut job = egui::text::LayoutJob::simple_singleline(
net.name.clone(),
FontId::new(font.size + 4., egui::FontFamily::Name("Bold".into())),
ui.visuals().strong_text_color(),
widgets::single_line(
&painter,
Rect::from_min_max(pos2(left, rect.top()), pos2(right.max(left), rect.bottom())),
Align::Min,
&net.name,
title_font,
strong,
);
job.wrap.max_width = (right - left).max(1.);
job.wrap.max_rows = 1;
job.wrap.break_anywhere = true;
let name = painter.layout_job(job);
painter.galley(pos2(left, center - name.size().y / 2.), name, ink);
let mut hint = format!("{} · {status}\n{online} online · {known} known", net.name);
if let Some(address) = address {
hint.push_str(&format!("\n{address}"));
}
if users > 0 {
hint.push_str(&format!("\n{}", user_count(users)));
}
+22 -12
View File
@@ -1,6 +1,7 @@
//! Fields shared by the table, its column chooser and the history ordering.
use super::{Names, endpoints, role_name};
use rusqlite::types::Value;
use std::net::Ipv4Addr;
use tsunagi::traffic::{Flow, FlowKey, IpDetail};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
@@ -86,21 +87,30 @@ impl Column {
pub fn uses_names(self) -> bool {
matches!(self, Self::Peer | Self::Network | Self::Near | Self::Far)
}
pub fn ip_endpoint(self, key: &FlowKey) -> Option<(Ipv4Addr, Option<u16>)> {
let Flow::Ip {
near, far, detail, ..
} = key.flow
else {
return None;
};
let ip = match self {
Self::Near => near,
Self::Far => far,
_ => return None,
};
let port = match detail {
IpDetail::Ports(a, b) => Some(if self == Self::Near { a } else { b }),
_ => None,
};
Some((ip.into(), port))
}
// SQLite indexes this value only while sorting by a descriptive column.
// Numeric IPv4 address and port order is independent of their spelling.
pub fn label_key(self, key: &FlowKey, names: &Names) -> Value {
if let Flow::Ip {
near, far, detail, ..
} = key.flow
&& matches!(self, Self::Near | Self::Far)
{
let near_side = self == Self::Near;
let ip = u32::from_be_bytes(if near_side { near } else { far });
let port = match detail {
IpDetail::Ports(a, b) => 1 + i64::from(if near_side { a } else { b }),
_ => 0,
};
return Value::Integer((i64::from(ip) << 17) + port);
if let Some((ip, port)) = self.ip_endpoint(key) {
let port = port.map_or(0, |p| i64::from(p) + 1);
return Value::Integer((i64::from(u32::from(ip)) << 17) + port);
}
let label = match self {
Self::Peer => names.peer(&key.network, &key.peer),
+72 -4
View File
@@ -14,7 +14,8 @@ use history::{Cursor, Filter};
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, sync::Arc, time::Duration};
use tsunagi::{
NetworkId,
ipc::StatusReport,
dns::ZoneName,
ipc::{NetworkReport, StatusReport},
iroh_types::EndpointId,
traffic::{Flow, FlowKey, IpDetail, Role},
};
@@ -31,6 +32,8 @@ struct Network {
struct Names {
networks: BTreeMap<Id, Network>,
generation: Option<u64>,
addresses: BTreeMap<(Id, Ipv4Addr), String>,
resolve_addresses: bool,
}
fn public_id(id: &Id) -> String {
@@ -43,11 +46,13 @@ impl Names {
return false;
}
self.generation = Some(generation);
self.addresses.clear();
let mut changed = false;
for n in &report.networks {
let Ok(id) = n.network_id.parse::<NetworkId>() else {
continue;
};
self.index_addresses(*id.as_bytes(), n, &report.hostname);
let entry = self.networks.entry(*id.as_bytes()).or_default();
if entry.name != n.name {
entry.name.clone_from(&n.name);
@@ -97,6 +102,53 @@ impl Names {
}
changed
}
fn index_addresses(&mut self, id: Id, network: &NetworkReport, hostname: &str) {
let Ok(zone) = ZoneName::new(&network.name) else {
return;
};
let mut add = |address: Option<Ipv4Addr>, name: Option<&str>| {
if let (Some(ip), Some(name)) = (
address,
name.map(|s| s.trim_matches('.')).filter(|s| !s.is_empty()),
) {
self.addresses
.entry((id, ip))
.or_insert_with(|| format!("{}.{}", name.to_ascii_lowercase(), zone.as_str()));
}
};
if network.hostname_conflict.is_none()
&& let Some(own) = &network.overlay
{
add(
own.address.as_deref().and_then(|s| s.parse().ok()),
Some(hostname),
);
}
for member in &network.members {
if member.hostname_conflict.is_none() {
add(
member
.overlay_address_v4
.as_deref()
.and_then(|s| s.parse().ok()),
member.hostname.as_deref(),
);
}
}
for vip in &network.vips {
if vip.error.is_none() {
add(vip.address, Some(&vip.config.name));
}
}
}
fn resolved_endpoint(&self, key: &FlowKey, column: Column) -> Option<String> {
let (ip, port) = column.ip_endpoint(key)?;
let name = self.addresses.get(&(key.network, ip))?;
Some(match port {
Some(port) => format!("{name}:{port}"),
None => name.clone(),
})
}
fn network(&self, id: &Id) -> String {
let Some(n) = self.networks.get(id) else {
return short(&NetworkId::from_bytes(*id).to_string());
@@ -207,7 +259,10 @@ impl Window {
pub fn new(directory: Option<PathBuf>) -> Self {
Self {
worker: Worker::new(directory),
names: Names::default(),
names: Names {
resolve_addresses: true,
..Names::default()
},
filter: Filter::default(),
keep: false,
previous: Vec::new(),
@@ -220,12 +275,16 @@ impl Window {
}
fn controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
if ui.available_width() < 540. {
ui.horizontal(|ui| self.layers(ui));
if ui.available_width() < 620. {
ui.horizontal_wrapped(|ui| {
self.layers(ui);
self.resolve_option(ui);
});
ui.horizontal(|ui| self.history_controls(ui, grid));
} else {
ui.horizontal(|ui| {
self.layers(ui);
self.resolve_option(ui);
self.history_controls(ui, grid);
});
}
@@ -262,6 +321,15 @@ impl Window {
}
}
fn resolve_option(&mut self, ui: &mut Ui) {
if !self.filter.transport {
widgets::hint(
ui.checkbox(&mut self.names.resolve_addresses, "Resolve names"),
"Show this network’s peer and VIP names. Hover or hold a name to see its IP address.",
);
}
}
fn history_controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
widgets::hint(
ui.checkbox(&mut self.keep, "Keep until close"),
+16 -1
View File
@@ -328,7 +328,19 @@ impl Grid {
_ => &self.body,
};
let bounds = slot.rect(row);
let response = cell(ui, bounds, &label, font, self.ink(col), numeric(col));
let resolved = if names.resolve_addresses {
names.resolved_endpoint(key, col)
} else {
None
};
let response = cell(
ui,
bounds,
resolved.as_deref().unwrap_or(&label),
font,
self.ink(col),
numeric(col),
);
if col == PeerId {
let full = public_id(&key.peer);
let button = ui
@@ -344,6 +356,9 @@ impl Grid {
if widgets::hint(button, &format!("Copy peer ID\n{full}")).clicked() {
ui.ctx().copy_text(full);
}
} else if resolved.is_some() {
// A click sense also gives Android long presses a target.
widgets::hint(response.interact(Sense::click()), &label);
} else {
widgets::hint(response, &label);
}
+100
View File
@@ -207,6 +207,76 @@ fn a_stale_member_name_does_not_reindex_the_capture_every_refresh() {
assert_eq!(names.peer(network.as_bytes(), peer.as_bytes()), "old");
}
#[test]
fn endpoint_names_use_the_rows_network_and_current_peer_and_vip_records() {
use super::{Column, Names};
use tsunagi::ipc::{MemberReport, NetworkReport, OverlayReport, StatusReport};
use tsunagi::vip::{VipConfig, VipStatus};
let network = |id, name: &str, host: &str| NetworkReport {
network_id: tsunagi::NetworkId::from_bytes([id; 32]).to_string(),
name: name.into(),
members: vec![MemberReport {
hostname: Some(host.into()),
overlay_address_v4: Some("10.0.0.2".into()),
..Default::default()
}],
overlay: Some(OverlayReport {
address: Some("10.0.0.1".into()),
..Default::default()
}),
..Default::default()
};
let mut report = StatusReport {
hostname: "laptop".into(),
networks: vec![network(1, "tsng", "music"), network(2, "vpn", "home")],
..Default::default()
};
report.networks[0].vips.push(VipStatus {
config: VipConfig::new("radio"),
revision: String::new(),
address: Some("10.0.0.3".parse().unwrap()),
error: None,
listeners: vec![],
});
let mut names = Names::default();
names.refresh(Some(&report), 1);
let mut key = sample(55201, true).key;
assert_eq!(
names.resolved_endpoint(&key, Column::Near).as_deref(),
Some("laptop.tsng:55201")
);
assert_eq!(
names.resolved_endpoint(&key, Column::Far).as_deref(),
Some("music.tsng:443")
);
key.network = [2; 32];
assert_eq!(
names.resolved_endpoint(&key, Column::Far).as_deref(),
Some("home.vpn:443")
);
key.network = [1; 32];
key.flow = Flow::Ip {
near: [10, 0, 0, 3],
far: [1, 1, 1, 1],
protocol: 1,
detail: IpDetail::Echo,
};
assert_eq!(
names.resolved_endpoint(&key, Column::Near).as_deref(),
Some("radio.tsng")
);
assert_eq!(names.resolved_endpoint(&key, Column::Far), None);
report.networks[0].vips[0].error = Some("address conflict".into());
report.networks[0].members.clear();
names.refresh(Some(&report), 2);
assert_eq!(names.resolved_endpoint(&key, Column::Near), None);
assert_eq!(
names.resolved_endpoint(&sample(1, true).key, Column::Far),
None
);
}
#[test]
fn sorting_uses_display_names_numeric_endpoints_and_live_rates() {
use super::{Column, Names, Network, Sort};
@@ -280,7 +350,14 @@ fn monitor_rows_stay_on_one_line_and_headers_sort_in_both_themes() {
let ctx = Context::default();
ctx.set_theme(theme);
ctx.set_fonts(crate::app_fonts());
ctx.style_mut(|s| {
s.interaction.tooltip_delay = 0.;
s.interaction.show_tooltips_only_when_still = false;
});
let mut win = Window::new(None);
win.names
.addresses
.insert(([1; 32], [10, 0, 0, 2].into()), "music.lab".into());
win.names.networks.insert(
[1; 32],
Network {
@@ -366,6 +443,29 @@ fn monitor_rows_stay_on_one_line_and_headers_sort_in_both_themes() {
wait(win);
};
let mut frame = draw(&mut win, vec![]);
let checkbox = label(&frame, "Resolve names").0.center();
if width > 900. {
let name = label(&frame, "music.lab:443").0.center();
draw(&mut win, vec![Event::PointerMoved(name)]);
frame = draw(&mut win, vec![]);
assert!(
frame.shapes.iter().any(
|s| matches!(&s.shape, Shape::Text(t) if t.galley.text() == "10.0.0.2:443")
),
"hovering a resolved name reveals the numeric endpoint"
);
click(&mut win, checkbox);
frame = draw(&mut win, vec![]);
label(&frame, "10.0.0.2:443");
assert!(
!frame.shapes.iter().any(
|s| matches!(&s.shape, Shape::Text(t) if t.galley.text() == "music.lab:443")
)
);
click(&mut win, checkbox);
frame = draw(&mut win, vec![]);
label(&frame, "music.lab:443");
}
let chooser = frame
.shapes
.iter()
@@ -441,6 +441,61 @@ fn desktop_full_table_survives_long_names_and_compact_exit_icon_starts_and_stops
}
}
#[test]
fn collapsed_vpn_keeps_its_address_as_peers_reconnect() {
let ctx = Context::default();
ctx.set_fonts(crate::app_fonts());
let mut state = home::UiState::default();
let report = tsunagi::ipc::StatusReport::default();
let address = "10.78.107.201";
let mut network = NetworkReport {
name: "vpn".into(),
active: true,
overlay: Some(OverlayReport {
address: Some(address.into()),
..Default::default()
}),
members: (0..14)
.map(|i| MemberReport {
endpoint_id: format!("peer-{i}"),
..Default::default()
})
.collect(),
..Default::default()
};
for width in [320., 359.] {
for online in [1, 9, 10, 12, 14] {
for (i, member) in network.members.iter_mut().enumerate() {
member.online = i < online;
}
let out = frame(
&ctx,
egui::vec2(width, 240.),
online as f64,
vec![],
|ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
home::draw_network(
ui,
&ReadOnly,
&mut state,
&Traffic::default(),
&network,
&report,
true,
);
});
},
);
let name = label(&out, "vpn").unwrap();
let address = label(&out, address).expect("the local address stays visible");
let count = label(&out, &format!("{} {online}/14", icon::DEVICES)).unwrap();
assert!(name.right() < address.left() && address.right() < count.left());
assert!(count.right() <= width);
}
}
}
#[test]
fn exit_users_scroll_a_row_inside_the_existing_card_and_disappear_on_deselection() {
for (width, os) in [
+2 -2
View File
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
# Its own version, and deliberately separate from the wire version it
# negotiates: a release here does not stop it talking to a peer on an older
# build, because what peers compare is `ANNOUNCEMENT_VERSION`.
version = "1.0.9"
version = "1.0.10"
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
edition.workspace = true
rust-version.workspace = true
@@ -11,7 +11,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
iroh.workspace = true
tokio.workspace = true
serde.workspace = true
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-wireguard"
version = "1.0.9"
version = "1.0.10"
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
serde.workspace = true
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi"
version = "1.0.9"
version = "1.0.10"
description = "The tsunagi command line agent."
edition.workspace = true
rust-version.workspace = true
@@ -12,11 +12,11 @@ name = "tsng"
path = "src/main.rs"
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.9" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.9" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.9" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.9" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.10" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.10" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.10" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.10" }
iroh.workspace = true
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
tracing.workspace = true
+5 -2
View File
@@ -6357,14 +6357,17 @@ mod service_log_tests {
);
let big = std::fs::File::options()
.append(true)
.write(true)
.open(logs.join("tsng.log"))
.unwrap();
big.set_len(SERVICE_LOG_LIMIT + 1).unwrap();
drop(big);
let file = open_log_in(&logs).unwrap();
assert_eq!(file.metadata().unwrap().len(), 0);
assert!(logs.join("tsng.log.old").exists());
assert_eq!(
std::fs::metadata(logs.join("tsng.log.old")).unwrap().len(),
SERVICE_LOG_LIMIT + 1
);
}
#[test]
+7 -4
View File
@@ -116,9 +116,10 @@ and configured networks.
- **Offering:** a `pf` anchor `com.apple/tsunagi-exit-<interface>` (the stock
`/etc/pf.conf` already evaluates `com.apple/*`) holds
NAT for traffic tagged on entry from an offered range. A tagged packet that the
kernel would forward back to the utun gets a PF `route-to` through the
physical gateway. The physical NAT state is interface-bound.
NAT for traffic tagged on entry from an offered range. If the kernel chooses
the utun for a member's outbound internet packet, PF steers it through the
physical gateway. Replies keep the tag after reverse NAT and return to the
member over the utun. The physical NAT state is interface-bound.
`pf` is enabled if it was off, and that reference is released when the rules
go. After installing the rules the agent enables IPv4 forwarding and checks
the kernel's answer before advertising the exit. Stopping the offer removes
@@ -133,7 +134,9 @@ and configured networks.
a separate grant. The helper checks the live utun address and mask, selects
the uplink from the kernel, and manages its own PF anchor and enable token.
It accepts only sharing operations. The agent can subsequently reconcile and
remove these rules without prompting. At startup it reclaims orphaned helper
remove these rules without prompting. When an update changes the helper,
enabling sharing again prompts once to replace it and keeps existing subnet
grants. At startup the agent reclaims orphaned helper
anchors for the account by checking the owning process and its start time.
For a system agent with the necessary
rights, the initial enable completes directly.
+1 -1
View File
@@ -34,7 +34,7 @@ let
in
rustPlatform.buildRustPackage {
pname = if withTray then "tsunagi" else "tsunagi-cli";
version = "1.0.9";
version = "1.0.10";
src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock;