Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68f19d1758 | ||
|
|
8e0cfc97ac | ||
|
|
7b83aec3be | ||
|
|
21de427c62 | ||
|
|
a1da4bf498 | ||
|
|
9920d4c10f | ||
|
|
7dacc4517e | ||
|
|
43894612ee | ||
|
|
d8b7787430 | ||
|
|
b47acb8321 | ||
|
|
e3b74babba |
No files matched your search
@@ -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
|
||||
@@ -12,6 +12,7 @@ on:
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/linux_exit*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/linux.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/macos*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/macos/**'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/windows*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/macos.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/windows.rs'
|
||||
@@ -64,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
|
||||
@@ -79,7 +81,7 @@ jobs:
|
||||
"$TEST_BINARY" --ignored --exact "$EXIT_TEST" --list | grep -Fx "$EXIT_TEST: test"
|
||||
previous=$(sysctl -n net.inet.ip.forwarding)
|
||||
trap 'sudo -n sysctl -w "net.inet.ip.forwarding=$previous"' EXIT
|
||||
sudo -n sysctl -w net.inet.ip.forwarding=1
|
||||
sudo -n sysctl -w net.inet.ip.forwarding=0
|
||||
sudo -n -- "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --nocapture
|
||||
- name: Verify source selection on a real Wintun adapter
|
||||
if: runner.os == 'Windows'
|
||||
|
||||
Generated
+13
-10
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -6320,7 +6320,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"egui",
|
||||
@@ -6344,7 +6344,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"iroh",
|
||||
@@ -6359,7 +6359,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -6404,7 +6404,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -6427,7 +6427,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"caps",
|
||||
@@ -6447,7 +6447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui-phosphor",
|
||||
@@ -6463,17 +6463,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"postcard",
|
||||
"rusqlite",
|
||||
"tempfile",
|
||||
"tsunagi-core",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wg-quic"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
@@ -6500,7 +6503,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
|
||||
@@ -122,7 +122,9 @@ One exit serves the whole agent. Peers in every active Tsunagi network stay
|
||||
reachable on their own mesh routes.
|
||||
|
||||
The tray does the same with a checkbox. An exit node sees everything you send
|
||||
through it, so use only members you trust.
|
||||
through it, so use only members you trust. The folded network card shows its
|
||||
status and recent traffic. Expand it to see who is using this device for internet
|
||||
access.
|
||||
[Details and per-OS notes](docs/exit-node.md).
|
||||
|
||||
The initial data transport order is `wg,awg,wg-quic,tcp-tls` by default. AWG negotiates a
|
||||
@@ -150,13 +152,16 @@ Select a peer’s speedometer in **Devices** to measure download and upload
|
||||
through its current encrypted mesh path. The cell shows live rates in Mbit/s.
|
||||
Select the result to test again, or use **Test exits** to check the network’s
|
||||
online, compatible exit nodes one at a time. The test ends at the peer, so its
|
||||
Internet uplink beyond that peer is outside the measurement. A **≥** result is a
|
||||
sustained lower bound when the time or traffic budget runs out. A missing
|
||||
direction means the sample was too short. Both peers need speed-test support.
|
||||
Internet uplink beyond that peer is outside the measurement. Hover or long-press
|
||||
the result for details. “At least” means the receiver sustained that rate and
|
||||
the test ended before it could confirm the limit. A missing direction means
|
||||
the sample was too short. Both peers need speed-test support.
|
||||
|
||||
A test runs for up to five seconds. It raises the offered rate in steps and
|
||||
counts unique payload bytes at the receiver. The traffic ceiling is 96 MiB per
|
||||
direction for one peer, or 8 MiB when either endpoint reports a metered link.
|
||||
tries a higher rate again after a slow start. The receiver counts unique payload
|
||||
bytes across sustained trains of packets, including the last train before the
|
||||
traffic budget runs out. The traffic ceiling is 96 MiB per direction for one
|
||||
peer, or 8 MiB when either endpoint reports a metered link.
|
||||
A batch shares 128 MiB per direction among its exits, or 16 MiB on a metered
|
||||
initiator. These ceilings count probe IP packets before tunnel overhead.
|
||||
|
||||
@@ -193,6 +198,29 @@ when they reconnect. It does not ban the device: a newer signed claim can return
|
||||
Online nodes and the currently selected exit node cannot be forgotten.
|
||||
[State and limits](docs/sync-model.md#offline-node-cleanup).
|
||||
|
||||
### Traffic monitor
|
||||
|
||||
Open **Traffic monitor** (the pulse icon in the tray window or Android header) to
|
||||
start an empty live capture. **IP flows** groups both directions of a TCP or UDP
|
||||
address/port pair and repeated ICMP echoes for an address pair into one row. Select a network and peer, protocol or
|
||||
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. 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
|
||||
ends collection. Android pauses collection while the activity is in the background.
|
||||
Under heavy load the monitor displays the number of missed observations.
|
||||
|
||||
## Platforms
|
||||
|
||||
| Platform | Build | CLI `tsng` | Tray | Exit node: offer / use | Packages |
|
||||
|
||||
+3
-1
@@ -28,7 +28,9 @@ The tray and Android use the same egui network tiles, join form, device list, VI
|
||||
|
||||
Rotate the phone to select a network on the left and see its settings on the right. **Show devices** opens a table sized to the screen. Tap a peer for its version, data path and traffic. A green check marks a ready data channel, an amber spinning arc indicates a pending connection, and a red warning opens the error details. Hold an icon for its label. Rotating the phone keeps the selected peer and any edits in the VIP editor.
|
||||
|
||||
Tap the network name to expand its card, then open **Exit node…** to compare remote gateways by measured data RTT and data path. 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 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.
|
||||
|
||||
|
||||
@@ -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.6')
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.10')
|
||||
ndk { abiFilters abi }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import javax.microedition.khronos.opengles.GL10
|
||||
class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), GLSurfaceView.Renderer {
|
||||
private val density get() = resources.displayMetrics.density
|
||||
private val imm = activity.getSystemService(InputMethodManager::class.java)
|
||||
@Volatile private var paused = false
|
||||
private var imeMode = 0
|
||||
private var widthPx = 0
|
||||
private var heightPx = 0
|
||||
@@ -33,16 +34,23 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
|
||||
isFocusableInTouchMode = true
|
||||
requestFocus()
|
||||
}
|
||||
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
|
||||
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface(context.cacheDir.absolutePath)
|
||||
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
|
||||
override fun onDrawFrame(gl: GL10?) {
|
||||
if (paused) return
|
||||
if (pickExit.getAndSet(false)) Native.input(6, "")
|
||||
val landscape = resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE
|
||||
val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started, landscape)
|
||||
removeCallbacks(repaint)
|
||||
postDelayed(repaint, delay.coerceAtLeast(16))
|
||||
}
|
||||
override fun onPause() { super.onPause(); removeCallbacks(repaint) }
|
||||
override fun onPause() {
|
||||
paused = true
|
||||
queueEvent { Native.pauseTraffic() }
|
||||
super.onPause()
|
||||
removeCallbacks(repaint)
|
||||
}
|
||||
override fun onResume() { paused = false; super.onResume(); requestRender() }
|
||||
override fun onTouchEvent(e: MotionEvent): Boolean {
|
||||
val phase = when (e.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0
|
||||
|
||||
@@ -14,7 +14,8 @@ internal object Native {
|
||||
external fun networkChanged(instance: Long, addresses: String)
|
||||
external fun setMetered(instance: Long, metered: Boolean)
|
||||
|
||||
external fun surface()
|
||||
external fun surface(cacheDir: String)
|
||||
external fun pauseTraffic()
|
||||
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean, landscape: Boolean): Long
|
||||
external fun touch(action: Int, id: Int, x: Float, y: Float)
|
||||
external fun input(kind: Int, value: String)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.6"
|
||||
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.6" }
|
||||
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" }
|
||||
|
||||
@@ -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,
|
||||
@@ -38,7 +39,15 @@ fn with_display<T: Default>(f: impl FnOnce(&mut Display) -> T) -> T {
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) {
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_pauseTraffic(_: JNIEnv, _: JObject) {
|
||||
with_display(|d| d.ui.pause_monitor());
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
cache: JString,
|
||||
) {
|
||||
// SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current.
|
||||
let gl = unsafe {
|
||||
glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr()))
|
||||
@@ -52,9 +61,10 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
crate::view::configure(&ctx);
|
||||
let cache = env.get_string(&cache).ok().map(String::from);
|
||||
DISPLAY.with_borrow_mut(|d| {
|
||||
// If Android discarded the old EGL context, its GPU resources are already gone.
|
||||
let ui = d
|
||||
let mut ui = d
|
||||
.take()
|
||||
.map(|old| {
|
||||
// A rotation can recreate EGL. Keep expanded peers and scroll positions
|
||||
@@ -64,12 +74,15 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj
|
||||
old.ui
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(cache) = cache {
|
||||
ui.set_cache_dir(cache.into());
|
||||
}
|
||||
*d = Some(Display {
|
||||
painter,
|
||||
ctx,
|
||||
ui,
|
||||
events: Vec::new(),
|
||||
primary: None,
|
||||
touch: TouchInput::default(),
|
||||
start: Instant::now(),
|
||||
ime: -1,
|
||||
exit_active: false,
|
||||
@@ -92,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()
|
||||
};
|
||||
@@ -110,8 +123,12 @@ 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));
|
||||
if let Some(action) = action {
|
||||
let method = match action {
|
||||
SystemAction::Start => "startAgent",
|
||||
@@ -188,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)]
|
||||
|
||||
@@ -62,12 +62,15 @@ fn status() -> State {
|
||||
state
|
||||
}
|
||||
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||
submit(Request::Action(cmd))
|
||||
}
|
||||
fn submit(request: Request) -> Result<Response, String> {
|
||||
let (reply, result) = oneshot::channel();
|
||||
current()
|
||||
.as_ref()
|
||||
.ok_or("Tsunagi Agent stopped")?
|
||||
.commands
|
||||
.try_send((Request::Action(cmd), reply))
|
||||
.try_send((request, reply))
|
||||
.map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The Android application. Mesh state belongs to one service-owned Rust agent.
|
||||
|
||||
pub mod dns;
|
||||
mod monitor;
|
||||
pub mod plan;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
@@ -8,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;
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The GL thread holds a service subscription only while the inspector is visible.
|
||||
use crate::service::{Outcome, Response};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::oneshot::error::TryRecvError;
|
||||
use tsunagi::traffic::TrafficSubscription;
|
||||
use tsunagi_ui::monitor::Window;
|
||||
|
||||
pub(super) struct Monitor {
|
||||
pub view: Window,
|
||||
pending: Option<Response>,
|
||||
subscription: Option<TrafficSubscription>,
|
||||
next: Instant,
|
||||
failed: bool,
|
||||
}
|
||||
impl Monitor {
|
||||
pub fn new(cache: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
view: Window::new(cache),
|
||||
pending: None,
|
||||
subscription: None,
|
||||
next: Instant::now(),
|
||||
failed: false,
|
||||
}
|
||||
}
|
||||
pub fn pause(&mut self) {
|
||||
self.pending = None;
|
||||
self.subscription = None;
|
||||
}
|
||||
pub fn poll(&mut self, open: impl FnOnce() -> Result<Response, String>) {
|
||||
if self.failed {
|
||||
return;
|
||||
}
|
||||
if let Some(sub) = &self.subscription {
|
||||
if Instant::now() >= self.next {
|
||||
self.next = Instant::now() + Duration::from_secs(1);
|
||||
if !self.view.feed().sample(sub.snapshot()) {
|
||||
self.pause();
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let result = match &mut self.pending {
|
||||
Some(rx) => match rx.try_recv() {
|
||||
Ok(Ok(Outcome::Traffic(sub))) => {
|
||||
// Time spent in the background must expire old rows before new traffic can refresh them.
|
||||
self.view.feed().sample(Default::default());
|
||||
self.subscription = Some(sub);
|
||||
self.next = Instant::now() + Duration::from_secs(1);
|
||||
self.pending = None;
|
||||
return;
|
||||
}
|
||||
Ok(Err(e)) => Err(e),
|
||||
Err(TryRecvError::Empty) => return,
|
||||
_ => Err("Tsunagi Agent stopped".into()),
|
||||
},
|
||||
None => open().map(|r| self.pending = Some(r)),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
self.pending = None;
|
||||
self.failed = true;
|
||||
self.view.feed().error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ use zeroize::Zeroizing;
|
||||
|
||||
/// A platform notification or user gesture.
|
||||
pub enum Request {
|
||||
/// A visible monitor requested its own fresh observation interval.
|
||||
WatchTraffic,
|
||||
/// A command from the same form used by the tray.
|
||||
Action(Command),
|
||||
/// The visible activity requested current counters.
|
||||
@@ -150,6 +152,8 @@ pub(crate) async fn wait_for_exit_offer(
|
||||
|
||||
/// Private reply delivered only to the UI that requested the action.
|
||||
pub enum Outcome {
|
||||
/// Owned by one traffic screen and dropped when capture stops.
|
||||
Traffic(tsunagi::traffic::TrafficSubscription),
|
||||
/// The agent has applied the action.
|
||||
Applied,
|
||||
/// Revisions returned by a successful signed write.
|
||||
@@ -346,6 +350,10 @@ pub async fn serve(
|
||||
let Some((request, reply)) = command else { break };
|
||||
let refresh_zones = !matches!(request, Request::Refresh);
|
||||
let result = match request {
|
||||
Request::WatchTraffic => {
|
||||
let _ = reply.send(agent.subscribe_traffic().map(Outcome::Traffic));
|
||||
continue;
|
||||
}
|
||||
Request::Refresh => Ok(Outcome::Applied),
|
||||
Request::Action(cmd) => {
|
||||
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||
|
||||
@@ -44,6 +44,28 @@ async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matches!(*snapshots.borrow_and_update(), State::Ready(..)));
|
||||
// Occupy the other reader slots so this test observes the real service subscription
|
||||
// being acquired on screen open and released on both background and close.
|
||||
let other_windows: Vec<_> = (0..3)
|
||||
.map(|_| phone.agent.subscribe_traffic().unwrap())
|
||||
.collect();
|
||||
let mut monitor = crate::monitor::Monitor::new(None);
|
||||
for _ in 0..2 {
|
||||
monitor.poll(|| {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
commands.try_send((Request::WatchTraffic, tx)).unwrap();
|
||||
Ok(rx)
|
||||
});
|
||||
tsunagi::testing::wait_until("the visible Android monitor subscribed", || async {
|
||||
phone.agent.subscribe_traffic().is_err().then_some(())
|
||||
})
|
||||
.await;
|
||||
monitor.poll(|| panic!("a visible monitor must reuse its subscription"));
|
||||
monitor.pause();
|
||||
assert!(phone.agent.subscribe_traffic().is_ok());
|
||||
}
|
||||
drop((monitor, other_windows));
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(2200), snapshots.changed())
|
||||
.await
|
||||
@@ -738,6 +760,7 @@ async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded()
|
||||
};
|
||||
let opened = click(titles[0]);
|
||||
assert_eq!(positions(&opened, "Show devices").len(), 1);
|
||||
assert!(positions(&opened, "Exit node…").is_empty());
|
||||
use egui_phosphor::regular as icon;
|
||||
let vip = format!("{} VIP", icon::NETWORK);
|
||||
let y = |label: &str| positions(&opened, label)[0].y;
|
||||
@@ -749,6 +772,18 @@ async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded()
|
||||
let folded = click(positions(&opened, name.as_str())[0]);
|
||||
assert!(positions(&folded, "Show devices").is_empty());
|
||||
assert_eq!(positions(&folded, "Exit via gateway").len(), 1);
|
||||
let fab = positions(&folded, icon::SIGN_OUT)
|
||||
.into_iter()
|
||||
.find(|p| p.y > 625. && p.x > 265.)
|
||||
.expect("fixed exit button");
|
||||
let picker = click(fab);
|
||||
assert_eq!(positions(&picker, "No exit node").len(), 1);
|
||||
assert_eq!(positions(&picker, "gateway").len(), 1);
|
||||
let dialog = click(positions(&picker, "No exit node")[0]);
|
||||
assert_eq!(positions(&dialog, "Disconnect").len(), 1);
|
||||
let picker = click(positions(&dialog, "Cancel")[0]);
|
||||
assert!(positions(&picker, "Disconnect").is_empty());
|
||||
assert_eq!(positions(&picker, "gateway").len(), 1);
|
||||
agent.shutdown().await;
|
||||
}
|
||||
|
||||
@@ -781,6 +816,12 @@ fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_
|
||||
[("alpha", true), ("bravo", true), ("paused", false)].map(|(id, active)| NetworkReport {
|
||||
network_id: id.into(),
|
||||
name: "home".into(),
|
||||
peers: vec![tsunagi::ipc::PeerReport {
|
||||
endpoint_id: "same-device".into(),
|
||||
hostname: Some(format!("gateway-{id}")),
|
||||
exit_node: true,
|
||||
..Default::default()
|
||||
}],
|
||||
active,
|
||||
..Default::default()
|
||||
});
|
||||
@@ -795,6 +836,9 @@ fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_
|
||||
let chooser = draw(&mut phone, &state);
|
||||
assert!(chooser.iter().any(|s| s == "home · alpha"));
|
||||
assert!(chooser.iter().any(|s| s == "home · bravo"));
|
||||
assert!(chooser.iter().any(|s| s == "gateway-alpha"));
|
||||
assert!(chooser.iter().any(|s| s == "gateway-bravo"));
|
||||
assert_eq!(chooser.iter().filter(|s| *s == "No exit node").count(), 1);
|
||||
assert!(!chooser.iter().any(|s| s.contains("paused")));
|
||||
assert!(phone.back().is_none());
|
||||
assert!(draw(&mut phone, &state).iter().any(|s| s == "tsunagi"));
|
||||
|
||||
@@ -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]
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -20,17 +20,17 @@ enum Page {
|
||||
#[default]
|
||||
Home,
|
||||
About,
|
||||
Monitor,
|
||||
Join,
|
||||
Devices(String),
|
||||
Vips(String),
|
||||
Exit(String),
|
||||
ExitNetworks,
|
||||
Exits,
|
||||
Leave(String),
|
||||
}
|
||||
impl Page {
|
||||
fn network(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Devices(id) | Self::Vips(id) | Self::Exit(id) | Self::Leave(id) => Some(id),
|
||||
Self::Devices(id) | Self::Vips(id) | Self::Leave(id) => Some(id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -38,10 +38,11 @@ impl Page {
|
||||
match self {
|
||||
Self::Home => "tsunagi",
|
||||
Self::About => "About",
|
||||
Self::Monitor => "Traffic monitor",
|
||||
Self::Join => "Join a network",
|
||||
Self::Devices(_) => "Devices",
|
||||
Self::Vips(_) => "VIP",
|
||||
Self::Exit(_) | Self::ExitNetworks => "Exit node",
|
||||
Self::Exits => "Exit nodes",
|
||||
Self::Leave(_) => "Leave network",
|
||||
}
|
||||
}
|
||||
@@ -85,6 +86,8 @@ struct Pending {
|
||||
#[derive(Default)]
|
||||
pub struct Phone {
|
||||
page: Page,
|
||||
monitor: Option<crate::monitor::Monitor>,
|
||||
cache_dir: Option<std::path::PathBuf>,
|
||||
forms: UiState,
|
||||
traffic: Traffic,
|
||||
snapshot: Snapshot,
|
||||
@@ -108,7 +111,24 @@ pub fn configure(ctx: &Context) {
|
||||
}
|
||||
|
||||
impl Phone {
|
||||
/// Private directory available to a window's temporary SQLite database.
|
||||
pub fn set_cache_dir(&mut self, path: std::path::PathBuf) {
|
||||
self.cache_dir = Some(path);
|
||||
}
|
||||
/// Release the agent subscription immediately when the activity goes into the background.
|
||||
pub fn pause_monitor(&mut self) {
|
||||
if let Some(m) = &mut self.monitor {
|
||||
m.pause();
|
||||
}
|
||||
}
|
||||
/// Poll the service only while a traffic screen is visible.
|
||||
pub fn poll_monitor(&mut self, open: impl FnOnce() -> Result<Response, String>) {
|
||||
if let Some(m) = &mut self.monitor {
|
||||
m.poll(open);
|
||||
}
|
||||
}
|
||||
fn home(&mut self) {
|
||||
self.monitor = None;
|
||||
if let Some(previous) = self.before_picker.take() {
|
||||
self.forms.exit_confirm = None;
|
||||
self.page = previous;
|
||||
@@ -166,34 +186,56 @@ impl Phone {
|
||||
self.pick_exit = true;
|
||||
}
|
||||
|
||||
fn exit_networks(&mut self, ui: &mut egui::Ui, networks: &[tsunagi::ipc::NetworkReport]) {
|
||||
if networks.is_empty() {
|
||||
ui.label("Join a network to choose an exit node.");
|
||||
if ui.button("Join or create a network").clicked() {
|
||||
self.page = Page::Join;
|
||||
}
|
||||
return;
|
||||
fn open_exit_picker(&mut self) {
|
||||
if self.page != Page::Exits {
|
||||
self.before_picker = Some(std::mem::replace(&mut self.page, Page::Exits));
|
||||
self.forms.exit_confirm = None;
|
||||
}
|
||||
if !networks.iter().any(|n| n.active) {
|
||||
ui.label("Start a network to choose an exit node.");
|
||||
if ui.button("Show networks").clicked() {
|
||||
self.home();
|
||||
}
|
||||
return;
|
||||
}
|
||||
ui.label("Choose a network for the exit node");
|
||||
for n in networks.iter().filter(|n| n.active) {
|
||||
let ambiguous = networks.iter().any(|other| {
|
||||
other.active && other.name == n.name && other.network_id != n.network_id
|
||||
});
|
||||
let label = if ambiguous {
|
||||
format!("{} · {}", n.name, tsunagi_ui::format::short(&n.network_id))
|
||||
} else {
|
||||
n.name.clone()
|
||||
};
|
||||
if ui.button(label).clicked() {
|
||||
self.page = Page::Exit(n.network_id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// This control lives outside both portrait and landscape scroll areas.
|
||||
fn exit_button(&mut self, ctx: &Context, ready: bool) {
|
||||
let clicked = egui::Area::new("home exit button".into())
|
||||
.anchor(egui::Align2::RIGHT_BOTTOM, [-16., -16.])
|
||||
.order(egui::Order::Middle)
|
||||
.movable(false)
|
||||
.show(ctx, |ui| {
|
||||
let (rect, response) = ui.allocate_exact_size(
|
||||
egui::vec2(60., 60.),
|
||||
if ready {
|
||||
egui::Sense::click()
|
||||
} else {
|
||||
egui::Sense::hover()
|
||||
},
|
||||
);
|
||||
let (mut fill, mut ink) = devices::exit_action_colors(ui.visuals().dark_mode);
|
||||
if !ready {
|
||||
fill = ui.visuals().widgets.inactive.bg_fill;
|
||||
ink = ui.visuals().weak_text_color();
|
||||
}
|
||||
ui.painter().circle_filled(rect.center(), 30., fill);
|
||||
if ready && (response.hovered() || response.has_focus()) {
|
||||
ui.painter().circle_stroke(rect.center(), 27., (1_f32, ink));
|
||||
}
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon::SIGN_OUT,
|
||||
egui::FontId::proportional(29.),
|
||||
ink,
|
||||
);
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(
|
||||
egui::WidgetType::Button,
|
||||
ready,
|
||||
"Choose an exit node",
|
||||
)
|
||||
});
|
||||
tsunagi_ui::widgets::hint(response, "Choose an exit node").clicked()
|
||||
})
|
||||
.inner;
|
||||
if ready && clicked {
|
||||
self.open_exit_picker();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +260,13 @@ impl Phone {
|
||||
.id_salt("network list")
|
||||
.show(ui, |ui| {
|
||||
for network in &report.networks {
|
||||
home::draw_network_selector(ui, network, report, &mut self.forms);
|
||||
home::draw_network_selector(
|
||||
ui,
|
||||
network,
|
||||
report,
|
||||
&mut self.forms,
|
||||
&self.traffic,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -233,7 +281,7 @@ impl Phone {
|
||||
if let Some(n) = selected {
|
||||
ui.heading(&n.name);
|
||||
ui.push_id(&n.network_id, |ui| {
|
||||
if home::draw_network_details(
|
||||
home::draw_network_details(
|
||||
ui,
|
||||
actions,
|
||||
&mut self.forms,
|
||||
@@ -241,15 +289,14 @@ impl Phone {
|
||||
n,
|
||||
report,
|
||||
false,
|
||||
) {
|
||||
self.page = Page::Exit(n.network_id.clone());
|
||||
}
|
||||
);
|
||||
});
|
||||
} else {
|
||||
ui.heading("This device");
|
||||
ui.label("Tsunagi Agent is running");
|
||||
home::draw_header(ui, actions, &mut self.forms, report);
|
||||
}
|
||||
ui.add_space(80.);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -320,18 +367,13 @@ impl Phone {
|
||||
}
|
||||
if self.pick_exit && self.pending.is_none() {
|
||||
self.pick_exit = false;
|
||||
let mut active = report.networks.iter().filter(|n| n.active);
|
||||
let picker = match (active.next(), active.next()) {
|
||||
(Some(n), None) => Page::Exit(n.network_id.clone()),
|
||||
_ => Page::ExitNetworks,
|
||||
};
|
||||
if !matches!(self.page, Page::Exit(_) | Page::ExitNetworks) {
|
||||
self.before_picker = Some(std::mem::replace(&mut self.page, picker));
|
||||
}
|
||||
self.open_exit_picker();
|
||||
}
|
||||
Some(report)
|
||||
} else {
|
||||
if self.page.network().is_some() || self.page == Page::Join {
|
||||
if self.page.network().is_some()
|
||||
|| matches!(self.page, Page::Join | Page::Monitor | Page::Exits)
|
||||
{
|
||||
self.home();
|
||||
}
|
||||
self.snapshot = Snapshot::default();
|
||||
@@ -361,6 +403,11 @@ impl Phone {
|
||||
self.page = Page::About;
|
||||
}
|
||||
if report.is_some() {
|
||||
if tsunagi_ui::widgets::icon_button(ui, icon::PULSE, "Traffic monitor")
|
||||
.clicked()
|
||||
{
|
||||
self.page = Page::Monitor;
|
||||
}
|
||||
ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes");
|
||||
ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts");
|
||||
}
|
||||
@@ -381,7 +428,19 @@ impl Phone {
|
||||
.page
|
||||
.network()
|
||||
.and_then(|id| report?.networks.iter().find(|n| n.network_id == id));
|
||||
if self.page != Page::Monitor {
|
||||
self.monitor = None;
|
||||
}
|
||||
match (&self.page, selected) {
|
||||
(Page::Monitor, _) => {
|
||||
let m = self
|
||||
.monitor
|
||||
.get_or_insert_with(|| crate::monitor::Monitor::new(self.cache_dir.clone()));
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
m.view
|
||||
.show(ui, report.map(|r| r.as_ref()), self.snapshot.generation)
|
||||
});
|
||||
}
|
||||
(Page::About, _) => about::show(ctx, None, &self.snapshot),
|
||||
(Page::Vips(id), Some(network)) => {
|
||||
let editor = self.forms.vip_windows.entry(id.clone()).or_default();
|
||||
@@ -408,7 +467,7 @@ impl Phone {
|
||||
self.landscape_home(ui, &actions, report);
|
||||
return;
|
||||
}
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt(self.page.title()).auto_shrink([false, false]).show(ui, |ui| {
|
||||
let Some(report) = report else {
|
||||
match state {
|
||||
State::Starting => {ui.spinner(); ui.label("Starting Tsunagi Agent…");}
|
||||
@@ -425,19 +484,23 @@ impl Phone {
|
||||
ui.separator();
|
||||
if ui.button("Join or create a network").clicked() {self.page = Page::Join;}
|
||||
for n in &report.networks {
|
||||
if home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false) {self.page = Page::Exit(n.network_id.clone());}
|
||||
home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false);
|
||||
}
|
||||
ui.add_space(80.);
|
||||
}
|
||||
Page::Join => {
|
||||
home::draw_join(ui, &actions, &mut self.forms.join);
|
||||
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
|
||||
}
|
||||
Page::Exit(_) => {
|
||||
if let Some(n) = selected && let Some(choice) = devices::choose_exit(ui, n, &report.endpoint_id) {
|
||||
Page::Exits => {
|
||||
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() {
|
||||
self.before_picker = None;
|
||||
self.page = Page::Join;
|
||||
}
|
||||
}
|
||||
Page::ExitNetworks => self.exit_networks(ui, &report.networks),
|
||||
Page::Leave(id) => {
|
||||
if let Some(n) = selected {
|
||||
ui.label(format!("Leave {} on this phone? You will need its secret to join again.", n.name));
|
||||
@@ -463,6 +526,9 @@ impl Phone {
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.page == Page::Home && self.forms.exit_confirm.is_none() {
|
||||
self.exit_button(ctx, report.is_some() && !actions.busy());
|
||||
}
|
||||
devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.6"
|
||||
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"]
|
||||
@@ -98,9 +98,11 @@ futures-util = { version = "0.3", default-features = false, optional = true }
|
||||
# safe wrapper, which is how the provisioner observes an adapter by name
|
||||
# before deciding what to change. Creating an adapter needs the process to be
|
||||
# elevated and `wintun.dll` to be reachable at run time.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]
|
||||
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Networking_WinSock",
|
||||
"Win32_Security",
|
||||
|
||||
@@ -306,6 +306,13 @@ impl TransportContext for TransportCtx {
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
/// Start a fresh, independent observation interval for one local window.
|
||||
pub fn subscribe_traffic(
|
||||
&self,
|
||||
) -> std::result::Result<crate::traffic::TrafficSubscription, String> {
|
||||
self.inner.routes.traffic.subscribe()
|
||||
}
|
||||
|
||||
/// Atomically saves or removes a version-checked shared VIP draft.
|
||||
/// Every authenticated network member may edit any service.
|
||||
pub async fn save_vip(
|
||||
|
||||
@@ -463,7 +463,11 @@ impl Runtime {
|
||||
let (link_results_tx, link_results_rx) = mpsc::channel(64);
|
||||
let (candidate_tx, discovery_candidates) =
|
||||
mpsc::channel(params.limits.max_discovery_candidates.max(1));
|
||||
let hub = crate::dataplane::relay::RelayHub::new(network_id, local_id);
|
||||
let hub = crate::dataplane::relay::RelayHub::with_monitor(
|
||||
network_id,
|
||||
local_id,
|
||||
params.routes.traffic.clone(),
|
||||
);
|
||||
// The order the protocols were configured in is also how links are
|
||||
// preferred when a neighbour can be reached over more than one.
|
||||
hub.set_priority(
|
||||
@@ -545,6 +549,7 @@ impl Runtime {
|
||||
// address it holds.
|
||||
self.load_state().await;
|
||||
|
||||
let mut roster = self.params.roster_changed.subscribe();
|
||||
let mut ticker = tokio::time::interval(self.params.discovery_interval);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
|
||||
@@ -555,6 +560,7 @@ impl Runtime {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.shutdown.wait() => break,
|
||||
_ = roster.changed() => self.sync_exit_use(),
|
||||
_ = reach_refresh.tick(), if self.params.discovery_interval > REACH_EXPIRY / 3 => self.announce_reach(false),
|
||||
_ = self.hub.changed() => {
|
||||
self.ensure_links();
|
||||
@@ -586,6 +592,7 @@ impl Runtime {
|
||||
self.start_dials();
|
||||
}
|
||||
_ = ticker.tick() => {
|
||||
self.sync_exit_use(); // Retry an announcement if the control queue was full.
|
||||
self.discovery_round().await;
|
||||
self.ensure_links();
|
||||
self.update_paths();
|
||||
@@ -838,10 +845,12 @@ impl Runtime {
|
||||
/// Used when a plugin's capability changed, so peers do not have to wait
|
||||
/// for a reconnect to learn about it.
|
||||
fn reannounce(&mut self) {
|
||||
let announcement = ControlMessage::Announce(self.local_announcement());
|
||||
let announcement = self.local_announcement();
|
||||
self.announced_exit = announcement.exit_node;
|
||||
let via = self.exit_policy().via;
|
||||
let peers: Vec<EndpointId> = self.sessions.keys().copied().collect();
|
||||
for peer in peers {
|
||||
if let Err(err) = self.send_to(peer, announcement.clone()) {
|
||||
if let Err(err) = self.announce_to(peer, announcement.clone(), via) {
|
||||
tracing::debug!(%err, "could not queue re-announcement");
|
||||
}
|
||||
}
|
||||
@@ -849,6 +858,43 @@ impl Runtime {
|
||||
self.update_paths();
|
||||
}
|
||||
|
||||
fn announce_to(
|
||||
&mut self,
|
||||
peer: EndpointId,
|
||||
mut announcement: Announcement,
|
||||
via: Option<EndpointId>,
|
||||
) -> Result<()> {
|
||||
let selected = via == Some(peer);
|
||||
announcement.uses_your_exit = Some(selected);
|
||||
self.send_to(peer, ControlMessage::Announce(announcement))?;
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
session.notified_exit_use = Some(selected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// The selected route is shared by all network actors. A selection in another
|
||||
// network must also clear the old gateway, even if neither peer sends traffic.
|
||||
fn sync_exit_use(&mut self) {
|
||||
let via = self.exit_policy().via;
|
||||
let changed: Vec<_> = self
|
||||
.sessions
|
||||
.iter()
|
||||
.filter_map(|(id, session)| {
|
||||
(session.notified_exit_use != Some(via == Some(*id))).then_some(*id)
|
||||
})
|
||||
.collect();
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let announcement = self.local_announcement();
|
||||
for peer in changed {
|
||||
if let Err(err) = self.announce_to(peer, announcement.clone(), via) {
|
||||
tracing::debug!(%err, "could not queue exit selection");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues a message without blocking the runtime loop.
|
||||
///
|
||||
/// The envelope is encoded here so that the exact number of control bytes
|
||||
@@ -872,6 +918,12 @@ impl Runtime {
|
||||
|
||||
match session.outbound.try_send(zeroize::Zeroizing::new(encoded)) {
|
||||
Ok(()) => {
|
||||
self.params.routes.traffic.control(
|
||||
network,
|
||||
peer,
|
||||
crate::traffic::Direction::Tx,
|
||||
bytes,
|
||||
);
|
||||
session.messages_sent += 1;
|
||||
session.bytes_sent += bytes;
|
||||
self.metrics.control_messages_sent += 1;
|
||||
@@ -2727,8 +2779,8 @@ impl Runtime {
|
||||
|
||||
// Announce ourselves straight away so the peer learns our hostname and
|
||||
// capabilities without another round of discovery.
|
||||
let announcement = ControlMessage::Announce(self.local_announcement());
|
||||
if let Err(err) = self.send_to(peer, announcement) {
|
||||
let announcement = self.local_announcement();
|
||||
if let Err(err) = self.announce_to(peer, announcement, self.exit_policy().via) {
|
||||
tracing::debug!(%err, "could not queue initial announcement");
|
||||
}
|
||||
|
||||
@@ -2798,13 +2850,13 @@ impl Runtime {
|
||||
})
|
||||
.collect();
|
||||
let exit_node = self.exit_ready();
|
||||
self.announced_exit = exit_node;
|
||||
Announcement {
|
||||
broadcast: self.params.broadcast,
|
||||
exit_node,
|
||||
hostname: self.params.hostname.clone(),
|
||||
capabilities,
|
||||
agent_version: Some(env!("CARGO_PKG_VERSION").to_owned()),
|
||||
uses_your_exit: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2838,6 +2890,12 @@ impl Runtime {
|
||||
if current != Some(session_id) {
|
||||
return;
|
||||
}
|
||||
self.params.routes.traffic.control(
|
||||
self.network_id,
|
||||
peer,
|
||||
crate::traffic::Direction::Rx,
|
||||
bytes as u64,
|
||||
);
|
||||
self.metrics.control_messages_received += 1;
|
||||
self.metrics.control_bytes_received += bytes as u64;
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
@@ -3032,6 +3090,7 @@ impl Runtime {
|
||||
session
|
||||
.agent_version
|
||||
.clone_from(&announcement.agent_version);
|
||||
session.uses_our_exit = announcement.uses_your_exit;
|
||||
session.broadcast = announcement.broadcast;
|
||||
if session.exit_node != announcement.exit_node {
|
||||
session.exit_node = announcement.exit_node;
|
||||
@@ -3281,6 +3340,7 @@ impl Runtime {
|
||||
}
|
||||
|
||||
fn status(&self) -> NetworkStatus {
|
||||
let exit = self.exit_policy();
|
||||
let served = self.served_protocols();
|
||||
let mut peers: Vec<PeerStatus> = self
|
||||
.sessions
|
||||
@@ -3300,6 +3360,12 @@ impl Runtime {
|
||||
data_transport_detail: selected.map(|link| link.path_description()),
|
||||
broadcast: session.broadcast,
|
||||
exit_node: session.exit_node,
|
||||
uses_our_exit: exit.offer
|
||||
&& session.uses_our_exit.unwrap_or_else(|| {
|
||||
self.params
|
||||
.routes
|
||||
.recent_exit_client(self.network_id, session.peer)
|
||||
}),
|
||||
endpoint_id: session.peer,
|
||||
role: session.role,
|
||||
agent_version: session.agent_version.clone(),
|
||||
@@ -3377,7 +3443,6 @@ impl Runtime {
|
||||
members.sort_by(|a, b| a.endpoint_id.as_bytes().cmp(b.endpoint_id.as_bytes()));
|
||||
members.dedup_by(|a, b| a.endpoint_id == b.endpoint_id);
|
||||
|
||||
let exit = self.exit_policy();
|
||||
NetworkStatus {
|
||||
speed: self
|
||||
.params
|
||||
|
||||
@@ -93,6 +93,10 @@ pub(crate) struct Session {
|
||||
pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>,
|
||||
pub(crate) hostname: Option<String>,
|
||||
pub(crate) agent_version: Option<String>,
|
||||
/// Selection reported by this peer, or unknown for a pre-extension session.
|
||||
pub(super) uses_our_exit: Option<bool>,
|
||||
/// Last selection successfully queued to this recipient on this session.
|
||||
pub(super) notified_exit_use: Option<bool>,
|
||||
pub(crate) capabilities: Vec<PluginCapability>,
|
||||
pub(crate) broadcast: bool,
|
||||
/// The peer offers itself as an exit node in this network.
|
||||
@@ -253,6 +257,8 @@ pub(crate) fn spawn(
|
||||
reach_sent: None,
|
||||
hostname: None,
|
||||
agent_version: None,
|
||||
uses_our_exit: None,
|
||||
notified_exit_use: None,
|
||||
capabilities: Vec::new(),
|
||||
broadcast: false,
|
||||
exit_node: false,
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::dataplane::PluginCapability;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::NetworkId;
|
||||
use crate::ipc::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
|
||||
use crate::overlay::router::DiagnosticPeer;
|
||||
use crate::proto::message::{ControlMessage, TransportPayload};
|
||||
|
||||
type Key = (NetworkId, EndpointId);
|
||||
@@ -56,6 +57,7 @@ struct Channel {
|
||||
key: Key,
|
||||
id: u64,
|
||||
limit: u32,
|
||||
addresses: DiagnosticPeer,
|
||||
handle: wire::Handle,
|
||||
}
|
||||
|
||||
@@ -199,8 +201,16 @@ pub(super) fn receive_packet(
|
||||
&& channel.key == (network, peer)
|
||||
&& let Some(data) = wire::decode_packet(packet)
|
||||
&& data.id == channel.id
|
||||
&& inner.routes.peer_addresses(network, peer) == Some((data.destination, data.source))
|
||||
&& (data.destination, data.source) == (channel.addresses.local, channel.addresses.remote)
|
||||
&& channel.addresses.is_current(&inner.routes)
|
||||
{
|
||||
inner
|
||||
.routes
|
||||
.traffic
|
||||
.packet(network, peer, crate::traffic::Direction::Rx, packet, || {
|
||||
crate::traffic::Role::SpeedTest
|
||||
})
|
||||
.record();
|
||||
channel.handle.data(data);
|
||||
}
|
||||
true
|
||||
@@ -212,21 +222,22 @@ fn config(
|
||||
id: u64,
|
||||
bytes: u32,
|
||||
rtt: Option<Duration>,
|
||||
) -> Option<wire::Config> {
|
||||
let (local, remote) = inner.routes.peer_addresses(key.0, key.1)?;
|
||||
) -> Option<(wire::Config, DiagnosticPeer)> {
|
||||
let addresses = inner.routes.diagnostic_peer(key.0, key.1)?;
|
||||
let ceiling = if inner.speed.metered.load(Ordering::Relaxed) {
|
||||
wire::METERED_BYTES
|
||||
} else {
|
||||
wire::NORMAL_BYTES
|
||||
};
|
||||
Some(wire::Config {
|
||||
let cfg = wire::Config {
|
||||
id,
|
||||
local,
|
||||
remote,
|
||||
local: addresses.local,
|
||||
remote: addresses.remote,
|
||||
mtu: u16::try_from(inner.config.interface_mtu).unwrap_or(u16::MAX),
|
||||
byte_limit: bytes.min(ceiling),
|
||||
rtt: rtt.unwrap_or(Duration::from_millis(100)),
|
||||
})
|
||||
};
|
||||
Some((cfg, addresses))
|
||||
}
|
||||
|
||||
pub(super) fn receive_control(
|
||||
@@ -246,13 +257,14 @@ pub(super) fn receive_control(
|
||||
{
|
||||
return envelope(&wire::Control::Busy { id });
|
||||
}
|
||||
let cfg = config(inner, key, id, request.byte_limit, rtt())?;
|
||||
let (cfg, addresses) = config(inner, key, id, request.byte_limit, rtt())?;
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::respond(cfg, request);
|
||||
inner.speed.active.store(Some(Arc::new(Channel {
|
||||
key,
|
||||
id,
|
||||
limit,
|
||||
addresses,
|
||||
handle,
|
||||
})));
|
||||
drop(jobs);
|
||||
@@ -308,11 +320,22 @@ impl wire::Io for TestIo {
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
self.inner.upgrade().is_some_and(|inner| {
|
||||
inner
|
||||
let observation = inner.routes.traffic.packet(
|
||||
self.key.0,
|
||||
self.key.1,
|
||||
crate::traffic::Direction::Tx,
|
||||
&packet,
|
||||
|| crate::traffic::Role::SpeedTest,
|
||||
);
|
||||
let sent = inner
|
||||
.config
|
||||
.tunnel
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.carry(self.key.0, self.key.1, packet))
|
||||
.is_some_and(|t| t.carry(self.key.0, self.key.1, packet));
|
||||
if sent {
|
||||
observation.record();
|
||||
}
|
||||
sent
|
||||
})
|
||||
}
|
||||
|
||||
@@ -557,7 +580,7 @@ async fn run_outgoing(
|
||||
p.endpoint_id == key.1 && (!exits_only || p.exit_node) && supported(&p.capabilities)
|
||||
})?;
|
||||
let id = rand::random();
|
||||
let cfg = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
|
||||
let (cfg, addresses) = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::initiate(cfg);
|
||||
let io = TestIo::new(inner, key, Some(generation));
|
||||
@@ -573,6 +596,7 @@ async fn run_outgoing(
|
||||
key,
|
||||
id,
|
||||
limit,
|
||||
addresses,
|
||||
handle,
|
||||
})));
|
||||
}
|
||||
|
||||
@@ -145,6 +145,8 @@ pub struct MemberStatus {
|
||||
/// Status of one authenticated session.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PeerStatus {
|
||||
/// The connected member has selected this gateway, or recently sent exit traffic on a legacy session.
|
||||
pub uses_our_exit: bool,
|
||||
/// This authenticated peer accepts network broadcasts.
|
||||
pub broadcast: bool,
|
||||
/// This authenticated peer offers itself as an exit node.
|
||||
|
||||
@@ -51,13 +51,13 @@ pub const DATA_REASSEMBLY_TTL: Duration = Duration::from_secs(5);
|
||||
pub const DATA_RECENT_IDS: usize = 128;
|
||||
|
||||
/// Simultaneous TCP, UDP and ICMP work on a userspace exit.
|
||||
#[cfg(any(windows, test))]
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
pub(crate) const EXIT_FORWARD_FLOWS: usize = 256;
|
||||
/// Bounded packet queue shared by userspace exit clients.
|
||||
#[cfg(any(windows, test))]
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
pub(crate) const EXIT_FORWARD_QUEUE: usize = 64;
|
||||
/// Concurrent fragmented datagrams accepted by a userspace exit.
|
||||
#[cfg(any(windows, test))]
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
pub(crate) const EXIT_FORWARD_FRAGMENTS: usize = 32;
|
||||
|
||||
/// Where the two stores live.
|
||||
@@ -582,3 +582,8 @@ impl std::fmt::Debug for AgentConfig {
|
||||
}
|
||||
/// Maximum number of transport links a routed datagram may traverse.
|
||||
pub const ROUTING_HOP_LIMIT: u8 = 16;
|
||||
|
||||
/// Maximum distinct flows per local reader between polls (fits one IPC frame).
|
||||
pub(crate) const MAX_INTERVAL_FLOWS: usize = 2048;
|
||||
/// Independent local monitor windows per agent.
|
||||
pub(crate) const MAX_TRAFFIC_READERS: usize = 4;
|
||||
@@ -134,6 +134,8 @@ struct ForwardingTable {
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Plane {
|
||||
network: NetworkId,
|
||||
traffic: Arc<crate::traffic::TrafficMonitor>,
|
||||
local: PeerId,
|
||||
table: ArcSwap<ForwardingTable>,
|
||||
tally: Arc<Tally>,
|
||||
@@ -176,7 +178,15 @@ impl Plane {
|
||||
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
};
|
||||
let len = frame.len();
|
||||
if hop.send(envelope::decrement(frame)).is_ok() {
|
||||
self.traffic.relay(
|
||||
self.network,
|
||||
header.source,
|
||||
header.destination,
|
||||
header.protocol,
|
||||
len,
|
||||
);
|
||||
self.tally.forwarded.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -324,11 +334,21 @@ pub struct RelayHub {
|
||||
impl RelayHub {
|
||||
/// Creates the router at this network's local endpoint.
|
||||
pub fn new(network: NetworkId, local: EndpointId) -> Arc<Self> {
|
||||
Self::with_monitor(network, local, Arc::default())
|
||||
}
|
||||
|
||||
pub(crate) fn with_monitor(
|
||||
network: NetworkId,
|
||||
local: EndpointId,
|
||||
traffic: Arc<crate::traffic::TrafficMonitor>,
|
||||
) -> Arc<Self> {
|
||||
let tally = Arc::new(Tally::default());
|
||||
Arc::new(Self {
|
||||
network,
|
||||
state: Mutex::new(State {
|
||||
plane: Arc::new(Plane {
|
||||
network,
|
||||
traffic,
|
||||
local: *local.as_bytes(),
|
||||
table: ArcSwap::from_pointee(ForwardingTable::default()),
|
||||
tally: tally.clone(),
|
||||
|
||||
@@ -175,7 +175,10 @@ async fn ecmp_is_per_flow_direct_wins_and_existing_tunnel_survives_changes() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protocols() {
|
||||
let hub = RelayHub::new(network(), peer(2));
|
||||
use crate::traffic::{Flow, Role, TrafficMonitor};
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let window = monitor.subscribe().unwrap();
|
||||
let hub = RelayHub::with_monitor(network(), peer(2), monitor);
|
||||
let a = Wire::new(1, true);
|
||||
let c = Wire::new(3, true);
|
||||
hub.set_direct(peer(1), "ip", a.clone());
|
||||
@@ -199,6 +202,20 @@ async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protoc
|
||||
);
|
||||
assert_eq!(&sent[0][RELAY_OVERHEAD..], b"end-to-end encrypted");
|
||||
assert_eq!(hub.counters().forwarded, 1);
|
||||
let observed = window.snapshot();
|
||||
assert_eq!(observed.flows.len(), 1);
|
||||
let row = &observed.flows[0];
|
||||
assert_eq!(row.key.role, Role::Relay);
|
||||
assert_eq!(row.key.peer, id(1).min(id(4)));
|
||||
assert_eq!(
|
||||
row.key.flow,
|
||||
Flow::Relay {
|
||||
other: id(1).max(id(4)),
|
||||
wire_protocol: tag()
|
||||
}
|
||||
);
|
||||
assert_eq!(row.tx_bytes + row.rx_bytes, sent[0].len() as u64);
|
||||
assert_eq!(row.tx_packets + row.rx_packets, 1);
|
||||
hub.close();
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,9 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// The local traffic monitor could not start or poll its subscription.
|
||||
#[error("{0}")]
|
||||
TrafficMonitor(String),
|
||||
/// A requested mesh throughput test cannot run.
|
||||
#[error("{0}")]
|
||||
SpeedTest(String),
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Exit offers may need the local user's approval. The dialog belongs to the
|
||||
//! initiating client, outside the daemon's IPC deadline and network actors.
|
||||
use super::{EXCHANGE_TIMEOUT, Error, Path, Request, Response, Result, exchange};
|
||||
use crate::state::Ipv4Range;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Result of applying the local exit settings on the host.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ExitOfferOutcome {
|
||||
/// Current setting after applying the requested change.
|
||||
Set(bool),
|
||||
/// macOS denied the host operation for this local overlay range.
|
||||
NeedsAuthorization {
|
||||
/// Locally selected overlay range.
|
||||
range: Ipv4Range,
|
||||
/// Owner of the running agent.
|
||||
agent_uid: u32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Offers the running agent as an exit in one network, or withdraws it.
|
||||
pub async fn set_exit_offer(
|
||||
path: impl AsRef<Path>,
|
||||
network_id: &str,
|
||||
enabled: bool,
|
||||
) -> Result<bool> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let authorize = |path: &Path, range, uid| {
|
||||
use std::os::unix::fs::{FileTypeExt, MetadataExt};
|
||||
let socket = std::fs::symlink_metadata(path).map_err(|e| e.to_string())?;
|
||||
if !socket.file_type().is_socket() || uid == 0 || socket.uid() != uid {
|
||||
return Err("The local control socket does not belong to the account requesting exit authorization".into());
|
||||
}
|
||||
crate::overlay::hostrules::authorize_macos_exit(range, uid)
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let authorize =
|
||||
|_: &Path, _, _| Err("macOS exit authorization is unavailable on this platform".into());
|
||||
apply(path.as_ref(), network_id, enabled, authorize).await
|
||||
}
|
||||
|
||||
async fn apply(
|
||||
path: &Path,
|
||||
id: &str,
|
||||
enabled: bool,
|
||||
authorize: impl FnOnce(&Path, Ipv4Range, u32) -> std::result::Result<(), String> + Send + 'static,
|
||||
) -> Result<bool> {
|
||||
let request = |choice| Request::SetExitOffer {
|
||||
network_id: id.to_owned(),
|
||||
enabled: choice,
|
||||
};
|
||||
let decode = |answer| match answer {
|
||||
Response::ExitOffer(outcome) => Ok(outcome),
|
||||
Response::Error(message) => Err(Error::Storage(message)),
|
||||
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
|
||||
};
|
||||
let result = decode(exchange(path, &request(Some(enabled)), EXCHANGE_TIMEOUT).await?)?;
|
||||
match result {
|
||||
ExitOfferOutcome::Set(on) => Ok(on),
|
||||
ExitOfferOutcome::NeedsAuthorization { range, agent_uid } if enabled => {
|
||||
let path_owned = path.to_owned();
|
||||
tokio::task::spawn_blocking(move || authorize(&path_owned, range, agent_uid))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
Error::Storage(format!("could not finish macOS authorization: {err}"))
|
||||
})?
|
||||
.map_err(Error::Storage)?;
|
||||
// Reconcile the current settings. A different client may have withdrawn
|
||||
// its offer while the system was waiting for the user to respond.
|
||||
match decode(exchange(path, &request(None), EXCHANGE_TIMEOUT).await?)? {
|
||||
ExitOfferOutcome::Set(on) => Ok(on),
|
||||
ExitOfferOutcome::NeedsAuthorization { .. } => Err(Error::Storage(
|
||||
"macOS still denies the exit settings after authorization".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
ExitOfferOutcome::NeedsAuthorization { .. } => Err(Error::Storage(
|
||||
"unexpected authorization request while withdrawing an exit".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use crate::ipc::{ControlSocket, ControlSocketAccess, ReportSource, StatusReport};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
struct Source {
|
||||
calls: Mutex<Vec<Option<bool>>>,
|
||||
answers: Mutex<VecDeque<ExitOfferOutcome>>,
|
||||
}
|
||||
|
||||
impl ReportSource for Source {
|
||||
fn report(&self) -> crate::BoxFuture<'_, StatusReport> {
|
||||
Box::pin(async { StatusReport::default() })
|
||||
}
|
||||
|
||||
fn set_exit_offer(
|
||||
&self,
|
||||
id: String,
|
||||
change: Option<bool>,
|
||||
) -> crate::BoxFuture<'_, std::result::Result<ExitOfferOutcome, String>> {
|
||||
assert_eq!(id, "lab");
|
||||
self.calls.lock().unwrap().push(change);
|
||||
let answer = self
|
||||
.answers
|
||||
.lock()
|
||||
.unwrap()
|
||||
.pop_front()
|
||||
.ok_or("unexpected reapply".to_owned());
|
||||
Box::pin(async move { answer })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prompt_only_on_denial_and_retry_the_current_plan_once() {
|
||||
let subnet: Ipv4Range = "10.2.3.0/24".parse().unwrap();
|
||||
let need = ExitOfferOutcome::NeedsAuthorization {
|
||||
range: subnet,
|
||||
agent_uid: 501,
|
||||
};
|
||||
let on = ExitOfferOutcome::Set(true);
|
||||
let off = ExitOfferOutcome::Set(false);
|
||||
for (answers, enabled, grant, prompts, result) in [
|
||||
(vec![on], true, true, 0, Some(true)),
|
||||
(vec![off], false, true, 0, Some(false)),
|
||||
(vec![need, on], true, true, 1, Some(true)),
|
||||
(vec![need, off], true, true, 1, Some(false)),
|
||||
(vec![need, need], true, true, 1, None),
|
||||
(vec![need], true, false, 1, None),
|
||||
(vec![need], false, true, 0, None),
|
||||
] {
|
||||
let requests = answers.len();
|
||||
let source = Arc::new(Source {
|
||||
calls: Default::default(),
|
||||
answers: Mutex::new(answers.into()),
|
||||
});
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("agent.sock");
|
||||
let server = ControlSocket::bind(&path, source.clone(), ControlSocketAccess::Private)
|
||||
.await
|
||||
.unwrap();
|
||||
let approvals = Arc::new(AtomicUsize::new(0));
|
||||
let seen = approvals.clone();
|
||||
let actual = apply(&path, "lab", enabled, move |_, range, uid| {
|
||||
seen.fetch_add(1, Ordering::Relaxed);
|
||||
assert_eq!((range, uid), (subnet, 501));
|
||||
if grant {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("cancelled".into())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert_eq!(actual.ok(), result);
|
||||
assert_eq!(approvals.load(Ordering::Relaxed), prompts);
|
||||
let expected = if requests == 1 {
|
||||
vec![Some(enabled)]
|
||||
} else {
|
||||
vec![Some(enabled), None]
|
||||
};
|
||||
assert_eq!(*source.calls.lock().unwrap(), expected);
|
||||
server.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,10 @@
|
||||
//! rather than the crate's internal structures, so internal refactors do not
|
||||
//! silently change what a client sees.
|
||||
|
||||
mod exit_offer;
|
||||
pub use exit_offer::{ExitOfferOutcome, set_exit_offer};
|
||||
mod traffic;
|
||||
pub use traffic::TrafficStream;
|
||||
mod speed;
|
||||
pub use speed::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
|
||||
|
||||
@@ -174,6 +178,8 @@ pub fn default_control_socket_path() -> PathBuf {
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum Request {
|
||||
/// Open a dedicated, window-scoped local monitor connection.
|
||||
WatchTraffic,
|
||||
/// Save a complete version-checked service draft or its deletion.
|
||||
SaveVip {
|
||||
/// Exact network id.
|
||||
@@ -269,8 +275,8 @@ pub enum Request {
|
||||
SetExitOffer {
|
||||
/// Public network identifier.
|
||||
network_id: String,
|
||||
/// Whether members may send their internet traffic through this agent.
|
||||
enabled: bool,
|
||||
/// Set the desired offer, or reconcile its current value after authorization.
|
||||
enabled: Option<bool>,
|
||||
},
|
||||
/// Send all this device's internet traffic through a member of one
|
||||
/// network, or back the ordinary way.
|
||||
@@ -326,6 +332,7 @@ impl std::fmt::Debug for Request {
|
||||
"StartSpeedTest {{ {network_id}, peer: {peer:?}, metered: {metered} }}"
|
||||
),
|
||||
Request::StopSpeedTest { network_id } => write!(f, "StopSpeedTest({network_id})"),
|
||||
Request::WatchTraffic => f.write_str("WatchTraffic"),
|
||||
Request::Status => f.write_str("Status"),
|
||||
Request::SetBroadcast {
|
||||
network_id,
|
||||
@@ -345,7 +352,7 @@ impl std::fmt::Debug for Request {
|
||||
Request::SetExitOffer {
|
||||
network_id,
|
||||
enabled,
|
||||
} => write!(f, "SetExitOffer {{ {network_id}, enabled: {enabled} }}"),
|
||||
} => write!(f, "SetExitOffer {{ {network_id}, enabled: {enabled:?} }}"),
|
||||
Request::SetExitNode { network_id, peer } => {
|
||||
write!(f, "SetExitNode {{ {network_id}, peer: {peer:?} }}")
|
||||
}
|
||||
@@ -357,6 +364,8 @@ impl std::fmt::Debug for Request {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum Response {
|
||||
/// The connection now accepts interval polls.
|
||||
TrafficReady,
|
||||
/// A speed-test action was accepted.
|
||||
SpeedTestAccepted,
|
||||
/// Accepted configuration with fresh local routing observations.
|
||||
@@ -384,7 +393,7 @@ pub enum Response {
|
||||
/// A network's shared secret, redacted in `Debug`.
|
||||
Secret(RedactedText),
|
||||
/// Whether this agent now offers itself as an exit node.
|
||||
ExitOffer(bool),
|
||||
ExitOffer(ExitOfferOutcome),
|
||||
/// The member this device now sends its internet traffic through.
|
||||
ExitNode(Option<String>),
|
||||
/// The request could not be served.
|
||||
@@ -861,6 +870,9 @@ pub struct MemberReport {
|
||||
/// One control plane peer.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerReport {
|
||||
/// The connected member has selected this gateway, or recently sent exit traffic on a legacy session.
|
||||
#[serde(default)]
|
||||
pub uses_our_exit: bool,
|
||||
/// The software version reported by this authenticated peer, when available.
|
||||
pub agent_version: Option<String>,
|
||||
/// Actionable carrier failure or policy mismatch; absent for a usable route.
|
||||
@@ -1022,6 +1034,12 @@ impl OverlayPeerReport {
|
||||
/// running and what they can report or change. That is what keeps this module
|
||||
/// free of any knowledge of them.
|
||||
pub trait ReportSource: Send + Sync + 'static {
|
||||
/// Start a new independent interval subscription, when supported by the source.
|
||||
fn subscribe_traffic(
|
||||
&self,
|
||||
) -> std::result::Result<crate::traffic::TrafficSubscription, String> {
|
||||
Err("Traffic monitoring is unavailable".into())
|
||||
}
|
||||
/// Atomically saves a complete VIP draft using its original revision.
|
||||
fn save_vip(
|
||||
&self,
|
||||
@@ -1151,8 +1169,8 @@ pub trait ReportSource: Send + Sync + 'static {
|
||||
fn set_exit_offer(
|
||||
&self,
|
||||
_network_id: String,
|
||||
_enabled: bool,
|
||||
) -> BoxFuture<'_, std::result::Result<bool, String>> {
|
||||
_enabled: Option<bool>,
|
||||
) -> BoxFuture<'_, std::result::Result<ExitOfferOutcome, String>> {
|
||||
Box::pin(async move { Err("this agent cannot be an exit node".to_string()) })
|
||||
}
|
||||
|
||||
@@ -1196,13 +1214,17 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
///
|
||||
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
||||
/// changes shape.
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 27]);
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 29]);
|
||||
|
||||
/// Reads one request off an accepted stream, answers it, writes the response.
|
||||
///
|
||||
/// The per-platform adapters call this for every connection they accept, so
|
||||
/// the request handling is identical on every transport.
|
||||
pub(crate) async fn serve_connection<S>(mut stream: S, source: Arc<dyn ReportSource>) -> Result<()>
|
||||
pub(crate) async fn serve_connection<S>(
|
||||
mut stream: S,
|
||||
source: Arc<dyn ReportSource>,
|
||||
mut stopped: tokio::sync::watch::Receiver<()>,
|
||||
) -> Result<()>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
@@ -1220,6 +1242,16 @@ where
|
||||
}
|
||||
};
|
||||
let response = match request {
|
||||
Request::WatchTraffic => match source.subscribe_traffic() {
|
||||
Ok(sub) => {
|
||||
drop(source);
|
||||
return tokio::select! {
|
||||
_ = stopped.changed() => Ok(()),
|
||||
result = traffic::serve(stream,sub) => result,
|
||||
};
|
||||
}
|
||||
Err(reason) => Response::Error(reason),
|
||||
},
|
||||
Request::SaveVip {
|
||||
network_id,
|
||||
config,
|
||||
@@ -1478,23 +1510,6 @@ pub async fn set_dns(
|
||||
}
|
||||
}
|
||||
|
||||
/// Offers the running agent as an exit node in one network, or stops.
|
||||
pub async fn set_exit_offer(
|
||||
path: impl AsRef<Path>,
|
||||
network_id: &str,
|
||||
enabled: bool,
|
||||
) -> Result<bool> {
|
||||
let request = Request::SetExitOffer {
|
||||
network_id: network_id.to_owned(),
|
||||
enabled,
|
||||
};
|
||||
match exchange(path.as_ref(), &request, EXCHANGE_TIMEOUT).await? {
|
||||
Response::ExitOffer(enabled) => Ok(enabled),
|
||||
Response::Error(message) => Err(Error::Storage(message)),
|
||||
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends the running agent's internet traffic through a member of one
|
||||
/// network, or back the ordinary way with `None`.
|
||||
pub async fn set_exit_node(
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! A dedicated local connection is the lifetime of one traffic window.
|
||||
use super::{
|
||||
EXCHANGE_TIMEOUT, Error, Path, Request, Response, Result, read_message, transport,
|
||||
write_message,
|
||||
};
|
||||
use crate::traffic::{TrafficSnapshot, TrafficSubscription};
|
||||
use std::{future::Future, time::Duration};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
#[cfg(unix)]
|
||||
type Socket = tokio::net::UnixStream;
|
||||
#[cfg(windows)]
|
||||
type Socket = tokio::net::windows::named_pipe::NamedPipeClient;
|
||||
|
||||
async fn bounded<T>(duration: Duration, f: impl Future<Output = Result<T>>) -> Result<T> {
|
||||
tokio::time::timeout(duration, f)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout {
|
||||
what: "local traffic monitor".into(),
|
||||
})?
|
||||
}
|
||||
|
||||
/// A local monitor stream. Dropping it releases the agent's interval buffer.
|
||||
pub struct TrafficStream(Socket);
|
||||
impl TrafficStream {
|
||||
/// Starts observing now, independently of any other open window.
|
||||
pub async fn open(path: &Path) -> Result<Self> {
|
||||
bounded(EXCHANGE_TIMEOUT, async {
|
||||
let mut socket = transport::connect(path).await?;
|
||||
write_message(&mut socket, &Request::WatchTraffic).await?;
|
||||
match read_message(&mut socket).await? {
|
||||
Response::TrafficReady => Ok(Self(socket)),
|
||||
Response::Error(reason) => Err(Error::TrafficMonitor(reason)),
|
||||
_ => Err(Error::TrafficMonitor(
|
||||
"Unexpected answer opening traffic monitor".into(),
|
||||
)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Drains only this reader's interval.
|
||||
pub async fn snapshot(&mut self) -> Result<TrafficSnapshot> {
|
||||
bounded(EXCHANGE_TIMEOUT, async {
|
||||
write_message(&mut self.0, &0u8).await?;
|
||||
read_message(&mut self.0).await
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn serve<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
mut socket: S,
|
||||
sub: TrafficSubscription,
|
||||
) -> Result<()> {
|
||||
bounded(
|
||||
EXCHANGE_TIMEOUT,
|
||||
write_message(&mut socket, &Response::TrafficReady),
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
// A wedged or suspended client cannot keep the collector running indefinitely.
|
||||
let token: u8 = bounded(Duration::from_secs(15), read_message(&mut socket)).await?;
|
||||
if token != 0 {
|
||||
return Err(Error::TrafficMonitor("Invalid monitor poll".into()));
|
||||
}
|
||||
bounded(
|
||||
EXCHANGE_TIMEOUT,
|
||||
write_message(&mut socket, &sub.snapshot()),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -148,13 +148,15 @@ fn set_mode(path: &Path, mode: u32) -> Result<()> {
|
||||
}
|
||||
|
||||
async fn serve(listener: UnixListener, source: Arc<dyn ReportSource>) {
|
||||
let (_lifetime, stopped) = tokio::sync::watch::channel(());
|
||||
loop {
|
||||
let Ok((stream, _)) = listener.accept().await else {
|
||||
continue;
|
||||
};
|
||||
let source = Arc::clone(&source);
|
||||
let stopped = stopped.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = super::serve_connection(stream, source).await {
|
||||
if let Err(err) = super::serve_connection(stream, source, stopped).await {
|
||||
tracing::debug!(%err, "local control request failed");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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.
|
||||
@@ -217,6 +217,7 @@ async fn serve(
|
||||
first: tokio::net::windows::named_pipe::NamedPipeServer,
|
||||
source: Arc<dyn ReportSource>,
|
||||
) {
|
||||
let (_lifetime, stopped) = tokio::sync::watch::channel(());
|
||||
let mut server = first;
|
||||
loop {
|
||||
if server.connect().await.is_err() {
|
||||
@@ -235,15 +236,17 @@ async fn serve(
|
||||
// Nothing left to accept the next client on, but the one in
|
||||
// hand is still answered before the loop ends.
|
||||
let source = Arc::clone(&source);
|
||||
let stopped = stopped.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = super::serve_connection(connected, source).await;
|
||||
let _ = super::serve_connection(connected, source, stopped).await;
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
let source = Arc::clone(&source);
|
||||
let stopped = stopped.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = super::serve_connection(connected, source).await {
|
||||
if let Err(err) = super::serve_connection(connected, source, stopped).await {
|
||||
tracing::debug!(%err, "local control request failed");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -51,6 +51,7 @@ pub mod storage;
|
||||
pub mod task;
|
||||
#[cfg(feature = "testing")]
|
||||
pub mod testing;
|
||||
pub mod traffic;
|
||||
pub mod vip;
|
||||
|
||||
pub use agent::{Agent, AgentStatus, Event, NetworkStatus, PeerStatus};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! A Windows exit offer terminates its forwarded connections on physical
|
||||
//! On Windows and on Macs without a host utun, an exit terminates forwarded connections on physical
|
||||
//! sockets. This keeps them out of the destination-only routes used by local
|
||||
//! applications. The stack and its sockets live for the offer, independently
|
||||
//! of this device's upstream selection.
|
||||
@@ -23,6 +23,8 @@ use tokio::{
|
||||
task::{JoinHandle, JoinSet},
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) mod macos;
|
||||
mod tcp;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -42,13 +44,22 @@ impl Physical {
|
||||
let socket = TcpSocket::new_v4()?;
|
||||
#[cfg(windows)]
|
||||
windows::pin(&socket, self.index)?;
|
||||
#[cfg(target_os = "macos")]
|
||||
self.pin(&socket2::SockRef::from(&socket))?;
|
||||
socket.bind((self.address, 0).into())?;
|
||||
socket.connect(remote).await
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn pin(self, socket: &socket2::Socket) -> io::Result<()> {
|
||||
let index = std::num::NonZeroU32::new(self.index)
|
||||
.ok_or_else(|| io::Error::other("no physical exit interface"))?;
|
||||
socket.bind_device_by_index_v4(Some(index))
|
||||
}
|
||||
|
||||
fn datagram(self, protocol: socket2::Protocol) -> io::Result<UdpSocket> {
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
let ty = if protocol == Protocol::UDP {
|
||||
let ty = if protocol == Protocol::UDP || cfg!(target_os = "macos") {
|
||||
Type::DGRAM
|
||||
} else {
|
||||
Type::RAW
|
||||
@@ -56,6 +67,8 @@ impl Physical {
|
||||
let socket = Socket::new(Domain::IPV4, ty, Some(protocol))?;
|
||||
#[cfg(windows)]
|
||||
windows::pin(&socket, self.index)?;
|
||||
#[cfg(target_os = "macos")]
|
||||
self.pin(&socket)?;
|
||||
socket.bind(&SocketAddr::V4(SocketAddrV4::new(self.address, 0)).into())?;
|
||||
socket.set_nonblocking(true)?;
|
||||
UdpSocket::from_std(socket.into())
|
||||
@@ -328,7 +341,18 @@ async fn echo(
|
||||
let until = tokio::time::Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
let len = tokio::time::timeout_at(until, socket.recv(&mut buf)).await??;
|
||||
let Some(h) = packet::header(&buf[..len]) else {
|
||||
// Darwin ping sockets return a BSD IPv4 header whose length field is
|
||||
// the host-endian ICMP payload length. The connected socket supplies
|
||||
// its peer and the checksum and nonce below authenticate this reply.
|
||||
#[cfg(target_os = "macos")]
|
||||
let header = buf[..len]
|
||||
.first()
|
||||
.filter(|b| *b >> 4 == 4)
|
||||
.map(|b| usize::from(*b & 15) * 4)
|
||||
.filter(|h| *h >= 20 && *h <= len);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let header = packet::header(&buf[..len]);
|
||||
let Some(h) = header else {
|
||||
continue;
|
||||
};
|
||||
let body = &buf[h..len];
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
//! A Mac that cannot open a system utun can still serve an explicitly offered
|
||||
//! exit over bound user sockets. Ordinary host applications need a real utun.
|
||||
use super::Physical;
|
||||
use crate::BoxFuture;
|
||||
use crate::overlay::{
|
||||
OverlayError, TunDevice, TunFactory, TunRequest,
|
||||
hostrules::{
|
||||
BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan, ExitHostReport,
|
||||
ExitHostRules, RuleOutcome,
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
net::Ipv4Addr,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(in crate::overlay) struct SocketExit {
|
||||
// Only refreshed while offering. Keep the OS route lookup off the packet path.
|
||||
uplink: Arc<Mutex<Option<(Instant, Physical)>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NoHostTun(u32);
|
||||
impl TunDevice for NoHostTun {
|
||||
fn name(&self) -> &str {
|
||||
"userspace-exit"
|
||||
}
|
||||
fn mtu(&self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
fn recv(&self) -> BoxFuture<'_, Option<bytes::Bytes>> {
|
||||
Box::pin(async { None })
|
||||
}
|
||||
fn send<'a>(&'a self, _packet: bytes::Bytes) -> BoxFuture<'a, Result<(), OverlayError>> {
|
||||
Box::pin(async {
|
||||
Err(OverlayError::Unavailable(
|
||||
"this Mac has no host utun".into(),
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TunFactory for SocketExit {
|
||||
fn name(&self) -> &str {
|
||||
"userspace-exit"
|
||||
}
|
||||
fn on_host(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn create<'a>(
|
||||
&'a self,
|
||||
request: TunRequest,
|
||||
) -> BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
|
||||
Box::pin(async move { Ok(Arc::new(NoHostTun(request.mtu)) as Arc<dyn TunDevice>) })
|
||||
}
|
||||
fn host_rules(&self) -> Option<Arc<dyn BroadcastHostRules>> {
|
||||
Some(Arc::new(self.clone()))
|
||||
}
|
||||
}
|
||||
impl BroadcastHostRules for SocketExit {
|
||||
fn name(&self) -> &str {
|
||||
"userspace-exit"
|
||||
}
|
||||
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
|
||||
Some(self)
|
||||
}
|
||||
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
|
||||
Box::pin(async move {
|
||||
let failed = RuleOutcome::Failed("Local broadcast needs the system utun".into());
|
||||
BroadcastRulesReport {
|
||||
plan: plan.clone(),
|
||||
route: failed.clone(),
|
||||
firewall: failed,
|
||||
}
|
||||
})
|
||||
}
|
||||
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async {})
|
||||
}
|
||||
}
|
||||
|
||||
impl SocketExit {
|
||||
async fn reconcile(&self, plan: &ExitHostPlan) -> ExitHostReport {
|
||||
let physical = if plan.offer.is_empty() {
|
||||
Err("exit sharing is off".to_owned())
|
||||
} else {
|
||||
tokio::task::spawn_blocking(|| {
|
||||
let physical = crate::overlay::hostrules::macos_default_uplink()?;
|
||||
let iface = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.find(|i| i.name == physical)
|
||||
.ok_or_else(|| "the physical default interface is unavailable".to_owned())?;
|
||||
if iface.index == 0 || iface.is_loopback() || iface.name.starts_with("utun") {
|
||||
return Err("no physical IPv4 interface for exit sharing".into());
|
||||
}
|
||||
let address = iface
|
||||
.ipv4
|
||||
.iter()
|
||||
.map(|ip| ip.addr())
|
||||
.find(|ip| !ip.is_unspecified() && !ip.is_loopback() && !ip.is_link_local())
|
||||
.ok_or_else(|| {
|
||||
"the physical interface has no usable IPv4 address".to_owned()
|
||||
})?;
|
||||
Ok(Physical {
|
||||
index: iface.index,
|
||||
address,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|r| r)
|
||||
};
|
||||
*self.uplink.lock().unwrap_or_else(|e| e.into_inner()) =
|
||||
physical.as_ref().ok().map(|p| (Instant::now(), *p));
|
||||
let result = match physical {
|
||||
Ok(_) => RuleOutcome::Applied,
|
||||
Err(reason) => RuleOutcome::Failed(reason),
|
||||
};
|
||||
ExitHostReport {
|
||||
offer: plan
|
||||
.offer
|
||||
.iter()
|
||||
.map(|range| (*range, result.clone()))
|
||||
.collect(),
|
||||
forwarding: None,
|
||||
client: plan.client.then(|| {
|
||||
RuleOutcome::Failed(
|
||||
"Routing this Mac’s applications through a peer needs the system utun".into(),
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExitHostRules for SocketExit {
|
||||
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
|
||||
Box::pin(self.reconcile(plan))
|
||||
}
|
||||
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
*self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
})
|
||||
}
|
||||
fn refresh_offer<'a>(
|
||||
&'a self,
|
||||
plan: &'a ExitHostPlan,
|
||||
) -> BoxFuture<'a, Option<ExitHostReport>> {
|
||||
Box::pin(async move {
|
||||
if self
|
||||
.uplink
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.is_some_and(|(at, _)| at.elapsed() < Duration::from_secs(5))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(self.reconcile(plan).await)
|
||||
})
|
||||
}
|
||||
fn forwarded_uplink(&self) -> Option<(u32, Ipv4Addr)> {
|
||||
self.uplink
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.map(|(_, p)| (p.index, p.address))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use crate::overlay::egress::{Route, echo, ip_packet};
|
||||
#[derive(Debug)]
|
||||
struct DeniedUtun(bool);
|
||||
impl TunFactory for DeniedUtun {
|
||||
fn name(&self) -> &str {
|
||||
"utun"
|
||||
}
|
||||
fn on_host(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn create<'a>(
|
||||
&'a self,
|
||||
_: TunRequest,
|
||||
) -> BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
|
||||
Box::pin(async move {
|
||||
Err(if self.0 {
|
||||
OverlayError::UtunDenied("permission denied".into())
|
||||
} else {
|
||||
OverlayError::Unavailable("system error".into())
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
struct Returns(tokio::sync::mpsc::Sender<bytes::Bytes>);
|
||||
impl crate::overlay::PacketCarrier for Returns {
|
||||
fn carry(&self, _: Route, p: bytes::Bytes) -> bool {
|
||||
self.0.try_send(p).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_denied_utun_can_offer_while_an_unrelated_interface_failure_is_reported() {
|
||||
use crate::overlay::{Interface, RoutingTable};
|
||||
let (tx, _rx) = tokio::sync::mpsc::channel(2);
|
||||
let start = |denied| {
|
||||
Interface::start(
|
||||
Arc::new(DeniedUtun(denied)),
|
||||
"utun",
|
||||
1280,
|
||||
Arc::new(RoutingTable::new()),
|
||||
Arc::new(Returns(tx.clone())),
|
||||
)
|
||||
};
|
||||
assert!(matches!(
|
||||
start(false).await,
|
||||
Err(OverlayError::Unavailable(_))
|
||||
));
|
||||
let interface = start(true).await.unwrap();
|
||||
assert!(!interface.on_host());
|
||||
assert_eq!(interface.name(), "userspace-exit");
|
||||
interface.remove().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires an active physical IPv4 interface on macOS; uses a UDP listener on this Mac"]
|
||||
async fn a_user_exit_delivers_udp_and_the_reply_on_its_physical_interface() {
|
||||
use crate::{
|
||||
overlay::{ExitPolicy, Interface, NetworkRoutes, RoutingTable},
|
||||
vip::{Protocol, packet::Tuple},
|
||||
};
|
||||
use tokio::{net::UdpSocket, time::timeout};
|
||||
let net = crate::NetworkId::from_bytes([7; 32]);
|
||||
let peer = iroh::SecretKey::from_bytes(&[8; 32]).public();
|
||||
let own = Ipv4Addr::new(10, 2, 3, 1);
|
||||
let member = Ipv4Addr::new(10, 2, 3, 2);
|
||||
let routes = Arc::new(RoutingTable::new());
|
||||
routes
|
||||
.set_network(
|
||||
net,
|
||||
NetworkRoutes {
|
||||
local: Some(own),
|
||||
peers: vec![(member, peer)],
|
||||
range: Some("10.2.3.0/24".parse().unwrap()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let (tx, mut returns) = tokio::sync::mpsc::channel(2);
|
||||
let interface = Interface::start(
|
||||
Arc::new(DeniedUtun(true)),
|
||||
"utun",
|
||||
1280,
|
||||
routes.clone(),
|
||||
Arc::new(Returns(tx)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
routes.set_exit(
|
||||
net,
|
||||
ExitPolicy {
|
||||
offer: true,
|
||||
via: None,
|
||||
},
|
||||
);
|
||||
interface.sync_exit_rules().await;
|
||||
assert!(
|
||||
interface.exit_offer_ready(net),
|
||||
"{:?}",
|
||||
interface.exit_rules(net)
|
||||
);
|
||||
let device = crate::overlay::hostrules::macos_default_uplink().unwrap();
|
||||
let iface = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.find(|i| i.name == device)
|
||||
.unwrap();
|
||||
let external = iface
|
||||
.ipv4
|
||||
.iter()
|
||||
.map(|n| n.addr())
|
||||
.find(|a| !a.is_link_local())
|
||||
.unwrap();
|
||||
let server = UdpSocket::bind((external, 0)).await.unwrap();
|
||||
let tuple = Tuple {
|
||||
src: member,
|
||||
dst: external,
|
||||
sport: 51234,
|
||||
dport: server.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Udp,
|
||||
};
|
||||
let request = super::super::udp_packet(tuple, b"exit request").unwrap();
|
||||
let mut buf = [0; 32];
|
||||
timeout(Duration::from_secs(3), async {
|
||||
interface.deliver(net, peer, request.clone()).await.unwrap();
|
||||
let (len, from) = server.recv_from(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf[..len], b"exit request");
|
||||
assert_eq!(from.ip(), external);
|
||||
server.send_to(b"exit reply", from).await.unwrap();
|
||||
let reply = returns.recv().await.unwrap();
|
||||
assert_eq!(crate::vip::packet::tuple(&reply), Some(tuple.reverse()));
|
||||
assert_eq!(&reply[28..], b"exit reply");
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
routes.set_exit(net, Default::default());
|
||||
interface.sync_exit_rules().await;
|
||||
assert!(!interface.exit_offer_ready(net));
|
||||
assert!(interface.deliver(net, peer, request).await.is_err());
|
||||
interface.remove().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unprivileged_echo_uses_a_bound_datagram_and_restores_the_peer_identifier() {
|
||||
let lo = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.find(|i| i.is_loopback())
|
||||
.unwrap();
|
||||
let physical = Physical {
|
||||
index: lo.index,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
};
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
|
||||
let reply: super::super::Reply = Arc::new(move |_, bytes| {
|
||||
let _ = tx.try_send(bytes);
|
||||
});
|
||||
let origin = Route {
|
||||
network: crate::NetworkId::from_bytes([7; 32]),
|
||||
peer: iroh::SecretKey::from_bytes(&[8; 32]).public(),
|
||||
};
|
||||
let mut p = ip_packet(Ipv4Addr::new(10, 2, 3, 9), Ipv4Addr::LOCALHOST, 1, 8).unwrap();
|
||||
p[20] = 8;
|
||||
p[24..28].copy_from_slice(&[1, 2, 3, 4]);
|
||||
let sum = crate::vip::packet::checksum(&p[20..]);
|
||||
p[22..24].copy_from_slice(&sum.to_be_bytes());
|
||||
echo(physical, origin, p.into(), 20, &reply, 1280)
|
||||
.await
|
||||
.unwrap();
|
||||
let response = rx.try_recv().unwrap();
|
||||
assert_eq!(&response[20..22], &[0, 0]);
|
||||
assert_eq!(&response[24..28], &[1, 2, 3, 4]);
|
||||
assert_eq!(crate::vip::packet::checksum(&response[20..]), 0);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,21 @@ fn addr() -> Ipv4Addr {
|
||||
Ipv4Addr::new(10, 13, 37, 9)
|
||||
}
|
||||
|
||||
fn loopback() -> Physical {
|
||||
#[cfg(target_os = "macos")]
|
||||
let index = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.find(|i| i.is_loopback())
|
||||
.unwrap()
|
||||
.index;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let index = 0;
|
||||
Physical {
|
||||
index,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_udp_flow_keeps_its_external_port_while_the_upstream_changes_and_stops_with_its_offer() {
|
||||
let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
@@ -25,10 +40,7 @@ async fn a_udp_flow_keeps_its_external_port_while_the_upstream_changes_and_stops
|
||||
assert_eq!(r, route);
|
||||
let _ = replies.try_send(p);
|
||||
});
|
||||
let physical = Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
};
|
||||
let physical = loopback();
|
||||
gateway.configure(vec![(route.network, physical)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
@@ -71,13 +83,7 @@ async fn refused_tcp_returns_a_reset_to_the_originating_client() {
|
||||
assert_eq!(r, route);
|
||||
let _ = tx.try_send(p);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
route.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
gateway.configure(vec![(route.network, loopback())]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
@@ -135,10 +141,7 @@ async fn a_tcp_stream_to_the_same_destination_survives_offer_reconciliation() {
|
||||
assert_eq!(r, route);
|
||||
let _ = tx.try_send(p);
|
||||
});
|
||||
let physical = Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
};
|
||||
let physical = loopback();
|
||||
gateway.configure(vec![(route.network, physical)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
@@ -350,13 +353,7 @@ async fn resetting_a_half_open_mesh_handshake_closes_the_physical_socket() {
|
||||
let gateway = Gateway::new(1280, move |_, packet| {
|
||||
let _ = tx.try_send(packet);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
route.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
gateway.configure(vec![(route.network, loopback())]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
@@ -386,13 +383,7 @@ async fn a_server_half_close_still_receives_the_members_final_bytes_and_fin() {
|
||||
let gateway = Gateway::new(1280, move |_, packet| {
|
||||
let _ = out.try_send(packet);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
origin.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
gateway.configure(vec![(origin.network, loopback())]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
@@ -431,13 +422,7 @@ async fn at_capacity_existing_udp_flows_continue_and_a_new_tuple_is_dropped() {
|
||||
let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let origin = route();
|
||||
let gateway = Gateway::new(1280, |_, _| {});
|
||||
gateway.configure(vec![(
|
||||
origin.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
gateway.configure(vec![(origin.network, loopback())]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
|
||||
@@ -31,9 +31,8 @@ pub struct ExitRulesReport {
|
||||
pub offer: Option<RuleSetReport>,
|
||||
/// Whether the kernel forwards packets for the overlay interface.
|
||||
///
|
||||
/// `Some(false)` means the rules are in place but nothing passes until
|
||||
/// forwarding is turned on, which the agent never does itself. `None`
|
||||
/// when it could not be read.
|
||||
/// `Some(false)` means kernel forwarding is off. `None` when unavailable
|
||||
/// or when the exit forwards through physical sockets.
|
||||
pub forwarding: Option<bool>,
|
||||
/// The routes that send this device's traffic through its exit node.
|
||||
/// `None` means it uses none through this network.
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Last successful forwarding for older peers that cannot report their exit selection.
|
||||
use super::NetworkRoutes;
|
||||
use crate::identity::NetworkId;
|
||||
use arc_swap::ArcSwap;
|
||||
use iroh::EndpointId;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
type Stamps = HashMap<EndpointId, Arc<AtomicU64>>;
|
||||
const RECENT_SECS: u64 = 60;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct ExitActivity {
|
||||
started: Instant,
|
||||
networks: ArcSwap<HashMap<NetworkId, Arc<Stamps>>>,
|
||||
}
|
||||
|
||||
impl Default for ExitActivity {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
started: Instant::now(),
|
||||
networks: ArcSwap::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExitActivity {
|
||||
// Serialized by the routing write lock. Provision only signed allocations on
|
||||
// offering networks. Packets never create entries or lock the routing table here.
|
||||
pub(super) fn configure(&self, network: NetworkId, routes: Option<&NetworkRoutes>) {
|
||||
let previous = self.networks.load();
|
||||
let old = previous.get(&network);
|
||||
let offering = routes.filter(|r| r.exit.offer);
|
||||
if offering.is_none() && old.is_none() {
|
||||
return;
|
||||
}
|
||||
let mut next = (**previous).clone();
|
||||
if let Some(routes) = offering {
|
||||
let peers = routes
|
||||
.peers
|
||||
.iter()
|
||||
.map(|(_, id)| {
|
||||
let stamp = old.and_then(|s| s.get(id)).cloned().unwrap_or_default();
|
||||
(*id, stamp)
|
||||
})
|
||||
.collect();
|
||||
next.insert(network, Arc::new(peers));
|
||||
} else {
|
||||
next.remove(&network);
|
||||
}
|
||||
self.networks.store(Arc::new(next));
|
||||
}
|
||||
|
||||
pub(super) fn stamp(&self, network: NetworkId, peer: EndpointId) -> Option<Arc<AtomicU64>> {
|
||||
self.networks.load().get(&network)?.get(&peer).cloned()
|
||||
}
|
||||
|
||||
pub(super) fn forwarded(&self, stamp: &AtomicU64) {
|
||||
let now = self.started.elapsed().as_secs() + 1;
|
||||
if stamp.load(Ordering::Relaxed) < now {
|
||||
stamp.fetch_max(now, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn recent(&self, network: NetworkId, peer: EndpointId) -> bool {
|
||||
let now = self.started.elapsed().as_secs() + 1;
|
||||
self.stamp(network, peer).is_some_and(|s| {
|
||||
let last = s.load(Ordering::Relaxed);
|
||||
last > 0 && now.saturating_sub(last) < RECENT_SECS
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::overlay::ExitPolicy;
|
||||
#[test]
|
||||
fn only_delivered_exit_packets_count_and_old_stamps_cannot_revive_a_removed_offer() {
|
||||
let mut activity = ExitActivity::default();
|
||||
let network = NetworkId::from_bytes([1; 32]);
|
||||
let peer = iroh::SecretKey::from_bytes(&[2; 32]).public();
|
||||
let routes = NetworkRoutes {
|
||||
exit: ExitPolicy {
|
||||
offer: true,
|
||||
via: None,
|
||||
},
|
||||
peers: vec![(std::net::Ipv4Addr::LOCALHOST, peer)],
|
||||
..Default::default()
|
||||
};
|
||||
activity.configure(network, Some(&routes));
|
||||
assert!(!activity.recent(network, peer));
|
||||
let Some(stamp) = activity.stamp(network, peer) else {
|
||||
unreachable!()
|
||||
};
|
||||
activity.forwarded(&stamp);
|
||||
assert!(activity.recent(network, peer));
|
||||
activity.configure(network, Some(&routes));
|
||||
assert!(activity.recent(network, peer));
|
||||
activity.started -= std::time::Duration::from_secs(60);
|
||||
assert!(!activity.recent(network, peer));
|
||||
activity.configure(network, None);
|
||||
activity.configure(network, Some(&routes));
|
||||
activity.forwarded(&stamp);
|
||||
assert!(!activity.recent(network, peer));
|
||||
}
|
||||
}
|
||||
@@ -63,8 +63,7 @@ pub struct ExitHostReport {
|
||||
/// One outcome per offered range: its masquerade and forward rules.
|
||||
pub offer: Vec<(Ipv4Range, RuleOutcome)>,
|
||||
/// Whether the kernel forwards packets for the interface. `None` when it
|
||||
/// could not be read. The agent only reads this: turning forwarding on is
|
||||
/// the owner's decision.
|
||||
/// could not be read. A local macOS offer enables forwarding when needed.
|
||||
pub forwarding: Option<bool>,
|
||||
/// The routes and rules that send this device's traffic through the
|
||||
/// interface, when the plan asked for them.
|
||||
@@ -91,6 +90,14 @@ pub trait ExitHostRules: Send + Sync + std::fmt::Debug + 'static {
|
||||
Box::pin(async { None })
|
||||
}
|
||||
|
||||
/// Refresh a provider-only plan when the physical egress changes.
|
||||
fn refresh_offer<'a>(
|
||||
&'a self,
|
||||
_plan: &'a ExitHostPlan,
|
||||
) -> BoxFuture<'a, Option<ExitHostReport>> {
|
||||
Box::pin(async { None })
|
||||
}
|
||||
|
||||
/// The physical interface index and IPv4 address used by a userspace exit.
|
||||
/// Kernel-forwarding hosts do not need to expose an egress socket address.
|
||||
fn forwarded_uplink(&self) -> Option<(u32, std::net::Ipv4Addr)> {
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -22,7 +22,9 @@ use crate::BoxFuture;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
|
||||
use super::macos_exit::{HostState, apply_plan, clear_all, refresh_client, run_tool};
|
||||
use super::macos_exit::{
|
||||
HostState, apply_plan, clear_all, refresh_client, refresh_offer, run_tool,
|
||||
};
|
||||
use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome};
|
||||
|
||||
/// The limited-broadcast destination routed through the overlay interface.
|
||||
@@ -64,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.
|
||||
@@ -134,6 +136,22 @@ impl ExitHostRules for MacosHostRules {
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_offer<'a>(
|
||||
&'a self,
|
||||
plan: &'a ExitHostPlan,
|
||||
) -> BoxFuture<'a, Option<ExitHostReport>> {
|
||||
Box::pin(async move {
|
||||
let state = Arc::clone(&self.state);
|
||||
let plan = plan.clone();
|
||||
tokio::task::spawn_blocking(move || refresh_offer(&run_tool, &state, &plan))
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
tracing::warn!(%err, "cannot check the physical egress for exit sharing");
|
||||
None
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let name = interface.to_string();
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! System authorization for a single local user and IPv4 subnet.
|
||||
|
||||
pub(super) const NEEDS_AUTHORIZATION: &str = "Tsunagi exit sharing needs administrator approval";
|
||||
|
||||
/// Whether the local user's explicit enable action can be retried after authorization.
|
||||
pub fn macos_exit_needs_authorization(detail: &str) -> bool {
|
||||
macos_exit_authorization_uid(detail).is_some()
|
||||
}
|
||||
|
||||
/// The UID of the local agent that needs the grant, from a native authorization result.
|
||||
pub fn macos_exit_authorization_uid(detail: &str) -> Option<u32> {
|
||||
let suffix = detail
|
||||
.strip_prefix(NEEDS_AUTHORIZATION)?
|
||||
.strip_prefix(" for UID ")?;
|
||||
if !suffix.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
suffix.parse().ok().filter(|id| *id != 0)
|
||||
}
|
||||
|
||||
/// Ask the system to authorize exit sharing for this local user and subnet.
|
||||
/// Only a foreground client calls this, after the daemon tried its available rights.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn authorize_macos_exit(range: crate::state::Ipv4Range, agent_uid: u32) -> Result<(), String> {
|
||||
use std::process::Command;
|
||||
const INSTALL: &str = include_str!("authorize-exit.sh");
|
||||
const HELPER: &str = include_str!("exit-offer.sh");
|
||||
const DIALOG: &str = r#"on run argv
|
||||
set installCommand to "/bin/sh -c " & quoted form of (item 1 of argv) & " tsunagi " & quoted form of (item 2 of argv) & " " & quoted form of (item 3 of argv) & " " & quoted form of (item 4 of argv)
|
||||
do shell script installCommand with prompt ("Allow Tsunagi to share this Mac’s internet connection for " & (item 5 of argv) & " as local user " & (item 2 of argv) & "?") with administrator privileges
|
||||
end run"#;
|
||||
if agent_uid == 0 {
|
||||
return Err("The system agent already runs as administrator.".into());
|
||||
}
|
||||
crate::state::Ipv4Range::new(range.base, range.prefix_len).map_err(|e| e.to_string())?;
|
||||
let output = Command::new("/usr/bin/osascript")
|
||||
.args([
|
||||
"-e",
|
||||
DIALOG,
|
||||
"--",
|
||||
INSTALL,
|
||||
&agent_uid.to_string(),
|
||||
&format!("{}_{}", range.base, range.prefix_len),
|
||||
HELPER,
|
||||
&range.to_string(),
|
||||
])
|
||||
.output()
|
||||
.map_err(|e| format!("could not open macOS authorization: {e}"))?;
|
||||
if !output.status.success() {
|
||||
let reason = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(if reason.contains("(-128)") {
|
||||
"Exit sharing was not authorized.".to_string()
|
||||
} else {
|
||||
format!("Could not authorize exit sharing: {}", reason.trim())
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Invoked by the system authorization dialog. Each argument is a distinct
|
||||
# quoted word. The helper body is embedded in the calling binary at build time.
|
||||
set -eu
|
||||
export PATH=/usr/bin:/bin:/usr/sbin:/sbin LC_ALL=C
|
||||
umask 077
|
||||
uid=$1
|
||||
key=$2
|
||||
helper_body=$3
|
||||
case "$uid" in ''|*[!0-9]*) exit 1;; esac
|
||||
case "$key" in ''|*[!0-9._]*) exit 1;; esac
|
||||
directory=/private/etc/tsunagi-exit
|
||||
helper="$directory/offer-v1"
|
||||
/bin/mkdir -p "$directory" /private/etc/sudoers.d
|
||||
/bin/chmod 0755 "$directory"
|
||||
tmp=$(/usr/bin/mktemp -d "$directory/.install.XXXXXXXX")
|
||||
trap '/bin/rm -rf "$tmp"' EXIT
|
||||
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"
|
||||
/bin/chmod 0440 "$tmp/rule"
|
||||
/bin/mv -f "$tmp/offer" "$helper"
|
||||
/bin/mv -f "$tmp/rule" "/private/etc/sudoers.d/tsunagi-exit-$uid"
|
||||
: > "$directory/grant_${uid}_$key"
|
||||
@@ -0,0 +1,136 @@
|
||||
#!/bin/sh -p
|
||||
# Privileged helper for a previously authorized local account and overlay range.
|
||||
# The caller supplies no PF text, file names, executable paths or uplink.
|
||||
set -eu
|
||||
export PATH=/usr/bin:/bin:/usr/sbin:/sbin LC_ALL=C
|
||||
umask 077
|
||||
fail() { echo "Tsunagi exit sharing: $*" >&2; exit 1; }
|
||||
|
||||
uid=${SUDO_UID:-}
|
||||
case "$uid" in ''|*[!0-9]*) fail 'missing local user';; esac
|
||||
owner=${1:-}
|
||||
case "$owner" in ''|*[!0-9]*) fail 'invalid agent PID';; esac
|
||||
shift
|
||||
process_stamp() {
|
||||
/bin/ps -p "$1" -o uid= -o lstart= | /usr/bin/awk '{$1=$1; print}'
|
||||
}
|
||||
stamp=$(process_stamp "$owner")
|
||||
[ "${stamp%% *}" = "$uid" ] || fail 'agent PID does not belong to the authorized account'
|
||||
[ "$#" -ge 2 ] && [ "$#" -le 3 ] || fail 'expected an operation and utun'
|
||||
action=$1
|
||||
iface=$2
|
||||
case "$iface" in utun*) unit=${iface#utun};; *) fail 'expected a utun interface';; esac
|
||||
case "$unit" in ''|*[!0-9]*) fail 'invalid utun number';; esac
|
||||
[ "${#unit}" -le 8 ] || fail 'invalid utun number'
|
||||
case "$action:$#" in clear:2|clear:3|apply:3|forward:3) ;; *) fail 'unknown operation';; esac
|
||||
|
||||
state=/private/var/run/tsunagi-exit
|
||||
grants=/private/etc/tsunagi-exit
|
||||
/bin/mkdir -p "$state"
|
||||
prefix="tsng_${uid}_${unit}_"
|
||||
lock="$state/$uid.lock"
|
||||
/usr/bin/shlock -f "$lock" -p "$$" || fail 'another update is in progress'
|
||||
trap '/bin/rm -f "$lock"' EXIT
|
||||
|
||||
read_record() {
|
||||
{ IFS= read -r token && IFS= read -r saved_pid && IFS= read -r saved_stamp; } < "$1" || fail 'invalid PF ownership record'
|
||||
case "$token" in ''|*[!0-9]*) fail 'invalid PF ownership token';; esac
|
||||
case "$saved_pid" in ''|*[!0-9]*) fail 'invalid PF owner';; esac
|
||||
}
|
||||
clear_one() {
|
||||
record=$1
|
||||
[ -f "$record" ] || return 0
|
||||
name=${record##*/}
|
||||
anchor="com.apple/${name%.token}"
|
||||
read_record "$record"
|
||||
/sbin/pfctl -q -a "$anchor" -f /dev/null
|
||||
/sbin/pfctl -X "$token" >/dev/null
|
||||
/bin/rm -f "$record"
|
||||
}
|
||||
|
||||
if [ "$#" = 2 ]; then
|
||||
# At startup the kernel can assign a different utun. Recover orphaned
|
||||
# anchors for this account, even after PID reuse, and leave live agents alone.
|
||||
for record in "$state/tsng_${uid}_"*.token; do
|
||||
[ -f "$record" ] || continue
|
||||
read_record "$record"
|
||||
if [ "$(process_stamp "$saved_pid")" != "$saved_stamp" ]; then
|
||||
clear_one "$record"
|
||||
elif [ "$saved_pid" = "$owner" ]; then
|
||||
case "${record##*/}" in "$prefix"*) clear_one "$record";; esac
|
||||
fi
|
||||
done
|
||||
exit 0
|
||||
fi
|
||||
range=$3
|
||||
[ "${#range}" -le 18 ] || fail 'invalid IPv4 range'
|
||||
case "$range" in ''|*[!0-9./]*|*/*/*) fail 'invalid IPv4 range';; */*) ;; *) fail 'missing prefix';; esac
|
||||
key="${range%/*}_${range##*/}"
|
||||
name="$prefix$key"
|
||||
record="$state/$name.token"
|
||||
if [ -f "$record" ]; then
|
||||
read_record "$record"
|
||||
if [ "$(process_stamp "$saved_pid")" != "$saved_stamp" ]; then
|
||||
clear_one "$record"
|
||||
elif [ "$saved_pid" != "$owner" ]; then
|
||||
fail 'another live agent owns this exit anchor'
|
||||
fi
|
||||
fi
|
||||
if [ "$action" = clear ]; then clear_one "$record"; exit 0; fi
|
||||
[ -f "$grants/grant_${uid}_$key" ] || { echo 'Tsunagi exit sharing needs administrator approval' >&2; exit 1; }
|
||||
|
||||
# Verify the overlay's exact subnet and mask using the kernel's own address list.
|
||||
/sbin/ifconfig "$iface" | /usr/bin/awk -v range="$range" '
|
||||
function ip(s, a, i, n) {
|
||||
if (split(s, a, ".") != 4) return -1
|
||||
for (i=1; i<=4; i++) {
|
||||
if (a[i] !~ /^[0-9]+$/ || a[i] > 255) return -1
|
||||
n = n*256 + a[i]
|
||||
}
|
||||
return n
|
||||
}
|
||||
BEGIN { split(range,a,"/"); base=ip(a[1]); p=a[2]; step=2^(32-p) }
|
||||
$1=="inet" && ip($2)>=0 && base>=0 && p~/^[0-9]+$/ && p<=30 {
|
||||
for (i=3; i<NF; i++)
|
||||
if ($i=="netmask" && tolower($(i+1))==sprintf("0x%08x",4294967296-step) &&
|
||||
int(ip($2)/step)==int(base/step)) found=1
|
||||
}
|
||||
END { exit !found }
|
||||
' || fail 'the authorized range is not configured on this utun'
|
||||
|
||||
forward() {
|
||||
if [ "$(/usr/sbin/sysctl -n net.inet.ip.forwarding)" != 1 ]; then
|
||||
/usr/sbin/sysctl -w net.inet.ip.forwarding=1 >/dev/null || return 1
|
||||
fi
|
||||
[ "$(/usr/sbin/sysctl -n net.inet.ip.forwarding)" = 1 ]
|
||||
}
|
||||
if [ "$action" = forward ]; then forward; exit 0; fi
|
||||
|
||||
route=$(/sbin/route -n get default)
|
||||
out=$(printf '%s\n' "$route" | /usr/bin/awk '$1=="interface:" {print $2; exit}')
|
||||
case "$out" in ''|*[!a-zA-Z0-9]*) fail 'no usable default interface';; esac
|
||||
[ "$out" != "$iface" ] || fail 'the default route uses this utun'
|
||||
gateway=$(printf '%s\n' "$route" | /usr/bin/awk '$1=="gateway:" && $2 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ {print $2; exit}')
|
||||
via=$out
|
||||
if [ -n "$gateway" ]; then via="($out $gateway)"; fi
|
||||
anchor="com.apple/$name"
|
||||
tag="tsng_forward_$iface"
|
||||
fresh=false
|
||||
if [ ! -f "$record" ]; then
|
||||
message=$(/sbin/pfctl -E 2>&1) || fail "$message"
|
||||
token=$(printf '%s\n' "$message" | /usr/bin/awk -F: 'tolower($1) ~ /^token *$/ {gsub(/ /,"",$2); if ($2~/^[0-9]+$/) print $2}')
|
||||
case "$token" in ''|*[!0-9]*) fail 'PF did not return an ownership token';; esac
|
||||
if ! printf '%s\n' "$token" "$owner" "$stamp" > "$record"; then /sbin/pfctl -X "$token"; exit 1; fi
|
||||
fresh=true
|
||||
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 $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
|
||||
then
|
||||
if "$fresh"; then clear_one "$record"; fi
|
||||
fail 'could not load the exit-sharing PF anchor'
|
||||
fi
|
||||
if ! forward; then clear_one "$record"; fail 'IPv4 forwarding is still off'; fi
|
||||
@@ -8,9 +8,9 @@
|
||||
//! Per offered range, in the anchor `com.apple/tsunagi-exit-<if>`:
|
||||
//!
|
||||
//! ```text
|
||||
//! nat on <egress> inet from <range> to any -> (<egress>)
|
||||
//! 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)
|
||||
//! ```
|
||||
//!
|
||||
@@ -18,11 +18,11 @@
|
||||
//! evaluates `nat-anchor "com.apple/*"` and `anchor "com.apple/*"`, so the
|
||||
//! rules take effect without editing the user's ruleset. `pf` cannot say
|
||||
//! "every interface but one" in a translation address, so the egress is the
|
||||
//! interface of the physical default route. An active exit client refreshes
|
||||
//! the rules when this egress changes.
|
||||
//! interface of the physical default route. Both roles follow egress changes.
|
||||
//!
|
||||
//! The kernel's `net.inet.ip.forwarding` is only read, never written: it
|
||||
//! changes how the whole host behaves, which is the owner's decision.
|
||||
//! A local offer enables IPv4 forwarding after its rules are loaded. This
|
||||
//! host-wide switch has no ownership token, so cleanup only releases our PF
|
||||
//! reference and removes our own rules.
|
||||
//!
|
||||
//! # Using
|
||||
//!
|
||||
@@ -72,6 +72,9 @@ use crate::state::Ipv4Range;
|
||||
use super::RuleOutcome;
|
||||
use super::exit::{ExitHostPlan, ExitHostReport};
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "macos_exit_helper_tests.rs"]
|
||||
mod helper_tests;
|
||||
#[cfg(all(test, target_os = "macos", feature = "tun-device"))]
|
||||
#[path = "macos_exit_kernel.rs"]
|
||||
mod kernel;
|
||||
@@ -79,6 +82,21 @@ mod kernel;
|
||||
mod scoped;
|
||||
use scoped::ScopedRoutes;
|
||||
|
||||
use super::macos_authorization::NEEDS_AUTHORIZATION;
|
||||
#[cfg(test)]
|
||||
use super::macos_authorization::{macos_exit_authorization_uid, macos_exit_needs_authorization};
|
||||
|
||||
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 {
|
||||
@@ -86,6 +104,7 @@ pub(super) enum Tool {
|
||||
Pfctl,
|
||||
Sysctl,
|
||||
Id,
|
||||
OfferHelper,
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
@@ -95,6 +114,7 @@ impl Tool {
|
||||
Self::Pfctl => "/sbin/pfctl",
|
||||
Self::Sysctl => "/usr/sbin/sysctl",
|
||||
Self::Id => "/usr/bin/id",
|
||||
Self::OfferHelper => OFFER_HELPER,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,7 +141,21 @@ pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
let mut command = Command::new(tool.path());
|
||||
let mut command = if tool == Tool::OfferHelper {
|
||||
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");
|
||||
sudo.args(["-n", "--", OFFER_HELPER])
|
||||
.arg(std::process::id().to_string());
|
||||
sudo
|
||||
} else {
|
||||
Command::new(tool.path())
|
||||
};
|
||||
command
|
||||
.env("LC_ALL", "C")
|
||||
.args(args)
|
||||
@@ -192,6 +226,7 @@ pub(super) struct DefaultRoute {
|
||||
pub(super) struct HostState {
|
||||
token: Mutex<Option<String>>,
|
||||
routes: Mutex<ScopedRoutes>,
|
||||
helper_offers: Mutex<Vec<Ipv4Range>>,
|
||||
}
|
||||
|
||||
impl HostState {
|
||||
@@ -267,7 +302,13 @@ fn default_route(run: Run<'_>, overlay: &str) -> Result<DefaultRoute, String> {
|
||||
Ok(route)
|
||||
}
|
||||
|
||||
/// Whether the kernel forwards IPv4. Read only.
|
||||
/// Physical default interface shared with the socket-based exit forwarder.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::overlay) fn macos_default_uplink() -> Result<String, String> {
|
||||
default_route(&run_tool, "").map(|route| route.interface)
|
||||
}
|
||||
|
||||
/// Whether the kernel forwards IPv4.
|
||||
fn forwarding_state(run: Run<'_>) -> Option<bool> {
|
||||
let out = run_ok(
|
||||
run,
|
||||
@@ -283,6 +324,48 @@ fn forwarding_state(run: Run<'_>) -> Option<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn enable_forwarding(run: Run<'_>) -> Result<(), String> {
|
||||
match forwarding_state(run) {
|
||||
Some(true) => return Ok(()),
|
||||
Some(false) => {}
|
||||
None => return Err("cannot determine whether macOS forwards IPv4".into()),
|
||||
}
|
||||
run_ok(
|
||||
run,
|
||||
Tool::Sysctl,
|
||||
&owned(&["-w", "net.inet.ip.forwarding=1"]),
|
||||
None,
|
||||
)?;
|
||||
if forwarding_state(run) == Some(true) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("macOS did not enable IPv4 forwarding".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn permission_denied(reason: &str) -> bool {
|
||||
let reason = reason.to_ascii_lowercase();
|
||||
reason.contains("permission denied") || reason.contains("operation not permitted")
|
||||
}
|
||||
|
||||
fn authorized_offer(
|
||||
run: Run<'_>,
|
||||
action: &str,
|
||||
interface: &str,
|
||||
range: Ipv4Range,
|
||||
) -> Result<(), String> {
|
||||
let args = owned(&[action, interface, &range.to_string()]);
|
||||
match run(Tool::OfferHelper, &args, None) {
|
||||
Ran::Exited { success: true, .. } => Ok(()),
|
||||
Ran::Exited { stdout, stderr, .. }
|
||||
if !stderr.contains("sudo:") && !stderr.contains(NEEDS_AUTHORIZATION) =>
|
||||
{
|
||||
Err(failure(&stderr, &stdout))
|
||||
}
|
||||
_ => Err(NEEDS_AUTHORIZATION.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The effective user id of this process, from `id -u`.
|
||||
fn agent_uid(run: Run<'_>) -> Result<u32, String> {
|
||||
run_ok(run, Tool::Id, &owned(&["-u"]), None)
|
||||
@@ -345,23 +428,30 @@ fn pf_rules(
|
||||
from any to any flags any tagged {tag} keep state (if-bound)"
|
||||
));
|
||||
}
|
||||
for range in offer {
|
||||
// PF takes the first matching NAT rule. Preserve the transport's source
|
||||
// port even when its overlay source falls inside one of our own offers.
|
||||
nat.push(format!("nat on {out} inet from {range} to any -> ({out})"));
|
||||
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 {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.
|
||||
@@ -611,38 +701,80 @@ fn set_routes(
|
||||
|
||||
/// Makes the host match the plan.
|
||||
pub(super) fn apply_plan(run: Run<'_>, state: &HostState, plan: &ExitHostPlan) -> ExitHostReport {
|
||||
let native = apply_rules(run, state, plan, None);
|
||||
let client = plan.client.then(|| verdict(native.clone()));
|
||||
let offer = native.clone().and_then(|()| {
|
||||
if plan.offer.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
enable_forwarding(run)
|
||||
}
|
||||
});
|
||||
// Permission errors can be fixed by a previously approved local helper.
|
||||
// Configuration and tool errors retain their original diagnostics.
|
||||
let helper_uid =
|
||||
if !plan.offer.is_empty() && offer.as_ref().is_err_and(|why| permission_denied(why)) {
|
||||
agent_uid(run).ok().filter(|uid| *uid != 0)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let action = if native.is_ok() { "forward" } else { "apply" };
|
||||
let mut active = lock(&state.helper_offers);
|
||||
let mut wanted = Vec::new();
|
||||
let mut outcomes = Vec::new();
|
||||
for &range in &plan.offer {
|
||||
let outcome = if let Some(uid) = helper_uid {
|
||||
let outcome = authorized_offer(run, action, &plan.interface, range).map_err(|why| {
|
||||
if why == NEEDS_AUTHORIZATION {
|
||||
format!("{NEEDS_AUTHORIZATION} for UID {uid}")
|
||||
} else {
|
||||
why
|
||||
}
|
||||
});
|
||||
if action == "apply" && outcome.is_ok() {
|
||||
wanted.push(range);
|
||||
}
|
||||
outcome
|
||||
} else {
|
||||
offer.clone()
|
||||
};
|
||||
outcomes.push((range, verdict(outcome)));
|
||||
}
|
||||
for range in std::mem::take(&mut *active) {
|
||||
if !wanted.contains(&range)
|
||||
&& let Err(why) = authorized_offer(run, "clear", &plan.interface, range)
|
||||
{
|
||||
tracing::warn!(%range, %why, "could not clear the authorized exit rules");
|
||||
wanted.push(range);
|
||||
}
|
||||
}
|
||||
*active = wanted;
|
||||
if !active.is_empty() && !plan.client {
|
||||
lock(&state.routes).active = default_route(run, &plan.interface).ok();
|
||||
}
|
||||
let forwarding = if plan.offer.is_empty() {
|
||||
None
|
||||
} else {
|
||||
forwarding_state(run)
|
||||
};
|
||||
let outcome = apply_rules(run, state, plan, None);
|
||||
let verdict = |ok: bool, why: &str| {
|
||||
if ok {
|
||||
RuleOutcome::Applied
|
||||
} else {
|
||||
RuleOutcome::Failed(why.to_string())
|
||||
if forwarding != Some(true) {
|
||||
for (_, outcome) in &mut outcomes {
|
||||
if outcome.is_applied() {
|
||||
*outcome = RuleOutcome::Failed("macOS could not confirm IPv4 forwarding".into());
|
||||
}
|
||||
}
|
||||
};
|
||||
match outcome {
|
||||
Ok(()) => ExitHostReport {
|
||||
offer: plan
|
||||
.offer
|
||||
.iter()
|
||||
.map(|range| (*range, RuleOutcome::Applied))
|
||||
.collect(),
|
||||
forwarding,
|
||||
client: plan.client.then_some(RuleOutcome::Applied),
|
||||
},
|
||||
Err(why) => ExitHostReport {
|
||||
offer: plan
|
||||
.offer
|
||||
.iter()
|
||||
.map(|range| (*range, verdict(false, &why)))
|
||||
.collect(),
|
||||
forwarding,
|
||||
client: plan.client.then(|| verdict(false, &why)),
|
||||
},
|
||||
}
|
||||
ExitHostReport {
|
||||
offer: outcomes,
|
||||
forwarding,
|
||||
client,
|
||||
}
|
||||
}
|
||||
|
||||
fn verdict(result: Result<(), String>) -> RuleOutcome {
|
||||
match result {
|
||||
Ok(()) => RuleOutcome::Applied,
|
||||
Err(why) => RuleOutcome::Failed(why),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -696,18 +828,21 @@ fn apply_rules(
|
||||
return Err(reason);
|
||||
}
|
||||
scoped.retain(run, &wanted)?;
|
||||
scoped.active = Some(egress);
|
||||
} else {
|
||||
clear_routes(run, interface);
|
||||
clear_v6(run, &mut scoped)?;
|
||||
scoped.retain(run, &[])?;
|
||||
scoped.active = None;
|
||||
}
|
||||
scoped.active = Some(egress);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes everything this agent put there for the interface.
|
||||
pub(super) fn clear_all(run: Run<'_>, state: &HostState, interface: &str) {
|
||||
if safe_name(interface) {
|
||||
let _ = run(Tool::OfferHelper, &owned(&["clear", interface]), None);
|
||||
lock(&state.helper_offers).clear();
|
||||
}
|
||||
let mut scoped = lock(&state.routes);
|
||||
clear_routes(run, interface);
|
||||
if let Err(why) = scoped
|
||||
@@ -728,6 +863,26 @@ pub(super) fn clear_all(run: Run<'_>, state: &HostState, interface: &str) {
|
||||
release_pf(run, &state.token);
|
||||
}
|
||||
|
||||
/// An offer's NAT follows the host's physical default even without a local exit client.
|
||||
pub(super) fn refresh_offer(
|
||||
run: Run<'_>,
|
||||
state: &HostState,
|
||||
plan: &ExitHostPlan,
|
||||
) -> Option<ExitHostReport> {
|
||||
let mut routes = lock(&state.routes);
|
||||
if plan.client || plan.offer.is_empty() || !routes.check_due(std::time::Instant::now()) {
|
||||
return None;
|
||||
}
|
||||
if let Ok(egress) = default_route(run, &plan.interface)
|
||||
&& Some(&egress) == routes.active.as_ref()
|
||||
&& forwarding_state(run) == Some(true)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
drop(routes);
|
||||
Some(apply_plan(run, state, plan))
|
||||
}
|
||||
|
||||
/// The logical plan can be unchanged while Wi-Fi changes gateway or moves
|
||||
/// to Ethernet. Rebuild both PF and physical scope against that new egress.
|
||||
pub(super) fn refresh_client(
|
||||
@@ -768,7 +923,7 @@ pub(super) fn refresh_client(
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -795,7 +950,10 @@ destination: default\n\
|
||||
calls: RefCell<Vec<String>>,
|
||||
stdins: RefCell<Vec<String>>,
|
||||
default_route: Option<String>,
|
||||
forwarding: &'static str,
|
||||
forwarding: Cell<&'static str>,
|
||||
deny_forwarding: bool,
|
||||
deny_pf: bool,
|
||||
helper: bool,
|
||||
pf_missing: bool,
|
||||
pf_load_fails: bool,
|
||||
route_add_fails: bool,
|
||||
@@ -812,7 +970,10 @@ destination: default\n\
|
||||
calls: RefCell::new(Vec::new()),
|
||||
stdins: RefCell::new(Vec::new()),
|
||||
default_route: Some(DEFAULT_ROUTE.to_string()),
|
||||
forwarding: "1\n",
|
||||
forwarding: Cell::new("1\n"),
|
||||
deny_forwarding: false,
|
||||
deny_pf: false,
|
||||
helper: false,
|
||||
pf_missing: false,
|
||||
pf_load_fails: false,
|
||||
route_add_fails: false,
|
||||
@@ -841,8 +1002,21 @@ destination: default\n\
|
||||
stderr: why.to_string(),
|
||||
};
|
||||
match tool {
|
||||
Tool::Id if self.deny_forwarding || self.deny_pf => ok("501\n", ""),
|
||||
Tool::Id => ok("0\n", ""),
|
||||
Tool::Sysctl => ok(self.forwarding, ""),
|
||||
Tool::Sysctl if args == ["-w", "net.inet.ip.forwarding=1"] => {
|
||||
if self.deny_forwarding {
|
||||
return fail("Operation not permitted");
|
||||
}
|
||||
self.forwarding.set("1\n");
|
||||
ok("net.inet.ip.forwarding: 0 -> 1", "")
|
||||
}
|
||||
Tool::Sysctl => ok(self.forwarding.get(), ""),
|
||||
Tool::OfferHelper if self.helper => {
|
||||
self.forwarding.set("1\n");
|
||||
ok("", "")
|
||||
}
|
||||
Tool::OfferHelper => fail("sudo: a password is required"),
|
||||
Tool::Route if args.iter().any(|a| a == "-inet6") => {
|
||||
let half = args[args.iter().position(|a| a == "-net").unwrap() + 1].clone();
|
||||
let mut table = self.v6.borrow_mut();
|
||||
@@ -941,6 +1115,7 @@ destination: default\n\
|
||||
}
|
||||
Tool::Route => ok("", ""),
|
||||
Tool::Pfctl if self.pf_missing => Ran::Missing,
|
||||
Tool::Pfctl if self.deny_pf => fail("pfctl: /dev/pf: Permission denied"),
|
||||
Tool::Pfctl if args == ["-E"] => ok("", self.pf_enable_output),
|
||||
Tool::Pfctl if args.contains(&"-f".to_string()) && self.pf_load_fails => {
|
||||
fail("pfctl: Syntax error")
|
||||
@@ -1010,8 +1185,8 @@ destination: default\n\
|
||||
let text = pf_rules("utun5", &egress(), &[range()], None);
|
||||
assert_eq!(
|
||||
text,
|
||||
"nat on en0 inet from 10.13.37.0/24 to any -> (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\
|
||||
"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 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"
|
||||
);
|
||||
@@ -1019,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()];
|
||||
@@ -1035,7 +1236,7 @@ destination: default\n\
|
||||
);
|
||||
assert_eq!(
|
||||
nat.next(),
|
||||
Some("nat on en0 inet from 10.13.37.0/24 to any -> (en0)")
|
||||
Some("nat on en0 inet from 10.13.37.0/24 to any tagged tsng_forward_utun5 -> (en0)")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1117,7 +1318,7 @@ destination: default\n\
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offering_loads_the_anchor_and_reads_but_never_writes_forwarding() {
|
||||
fn offering_leaves_preexisting_forwarding_on() {
|
||||
let fake = Fake::new();
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
@@ -1133,12 +1334,12 @@ destination: default\n\
|
||||
);
|
||||
assert_eq!(
|
||||
fake.stdins.borrow()[0],
|
||||
"nat on en0 inet from 10.13.37.0/24 to any -> (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\
|
||||
"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 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"
|
||||
);
|
||||
// sysctl is only ever asked, never told.
|
||||
// Forwarding was already enabled by the owner.
|
||||
assert!(
|
||||
calls
|
||||
.iter()
|
||||
@@ -1152,15 +1353,67 @@ destination: default\n\
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarding_off_is_reported_and_unreadable_is_none() {
|
||||
fn a_local_offer_enables_forwarding_after_nat_and_never_disables_other_routers() {
|
||||
let fake = Fake::new();
|
||||
fake.forwarding.set("0\n");
|
||||
let state = HostState::default();
|
||||
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||
apply_plan(&run, &state, &plan(false, true));
|
||||
assert_eq!(fake.count("Sysctl"), 0);
|
||||
let report = apply_plan(&run, &state, &plan(true, false));
|
||||
assert_eq!(report.forwarding, Some(true));
|
||||
assert_eq!(report.offer[0].1, RuleOutcome::Applied);
|
||||
assert!(fake.position("Pfctl -q -a").unwrap() < fake.position("Sysctl -w").unwrap());
|
||||
apply_plan(&run, &state, &plan(true, false));
|
||||
clear_all(&run, &state, "utun5");
|
||||
assert_eq!(fake.count("Sysctl -w"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_forwarding_or_an_unwritable_switch_never_advertises_a_working_offer() {
|
||||
let mut fake = Fake::new();
|
||||
fake.forwarding = "0\n";
|
||||
fake.forwarding.set("0\n");
|
||||
fake.deny_forwarding = true;
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true));
|
||||
assert_eq!(report.forwarding, Some(false));
|
||||
fake.forwarding = "junk";
|
||||
assert!(
|
||||
matches!(&report.offer[0].1, RuleOutcome::Failed(why) if macos_exit_needs_authorization(why))
|
||||
);
|
||||
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||
fake.forwarding.set("junk");
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
assert_eq!(report.forwarding, None);
|
||||
assert!(matches!(&report.offer[0].1, RuleOutcome::Failed(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_denied_native_pf_uses_only_a_previously_authorized_offer_helper() {
|
||||
let mut fake = Fake::new();
|
||||
fake.deny_pf = true;
|
||||
fake.forwarding.set("0\n");
|
||||
let state = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &state, &plan(true, false));
|
||||
assert!(
|
||||
matches!(&report.offer[0].1, RuleOutcome::Failed(why) if macos_exit_needs_authorization(why))
|
||||
);
|
||||
assert!(
|
||||
matches!(&report.offer[0].1, RuleOutcome::Failed(why) if macos_exit_authorization_uid(why) == Some(501))
|
||||
);
|
||||
for suffix in ["0", "", "501: denied", "+501", "4294967296"] {
|
||||
assert_eq!(
|
||||
macos_exit_authorization_uid(&format!("{NEEDS_AUTHORIZATION} for UID {suffix}")),
|
||||
None
|
||||
);
|
||||
}
|
||||
assert!(fake.position("Pfctl -E").unwrap() < fake.position("OfferHelper").unwrap());
|
||||
fake.helper = true;
|
||||
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||
let report = apply_plan(&run, &state, &plan(true, false));
|
||||
assert_eq!(report.offer[0].1, RuleOutcome::Applied);
|
||||
assert_eq!(report.forwarding, Some(true));
|
||||
clear_all(&run, &state, "utun5");
|
||||
assert!(fake.position("OfferHelper clear utun5").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1326,10 +1579,26 @@ destination: default\n\
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serving_without_an_upstream_moves_nat_when_the_physical_interface_changes() {
|
||||
let mut fake = Fake::new();
|
||||
let state = HostState::default();
|
||||
let plan = plan(true, false);
|
||||
let first = apply_plan(&|t, a, s| fake.run(t, a, s), &state, &plan);
|
||||
assert_eq!(first.offer[0].1, RuleOutcome::Applied);
|
||||
fake.default_route = Some(DEFAULT_ROUTE.replace("en0", "en7"));
|
||||
let moved = refresh_offer(&|t, a, s| fake.run(t, a, s), &state, &plan).unwrap();
|
||||
assert_eq!(moved.offer[0].1, RuleOutcome::Applied);
|
||||
assert!(fake.stdins.borrow().last().unwrap().contains("nat on en7"));
|
||||
assert_eq!(moved.client, None);
|
||||
assert_eq!(fake.count(" add "), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_routes_are_added_when_the_rules_did_not_load() {
|
||||
let mut fake = Fake::new();
|
||||
fake.pf_load_fails = true;
|
||||
fake.forwarding.set("0\n");
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true));
|
||||
let Some(RuleOutcome::Failed(why)) = report.client else {
|
||||
@@ -1341,6 +1610,8 @@ destination: default\n\
|
||||
// Nothing sent the host's traffic into a tunnel it could not exempt
|
||||
// the agent from.
|
||||
assert_eq!(fake.count(" add "), 0);
|
||||
assert_eq!(fake.count("Sysctl -w"), 0);
|
||||
assert_eq!(fake.count("OfferHelper"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Exercise the installed sharing helper against a throwaway host and PF.
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const HELPER: &str = include_str!("macos/exit-offer.sh");
|
||||
const INSTALL: &str = include_str!("macos/authorize-exit.sh");
|
||||
|
||||
struct Host(tempfile::TempDir);
|
||||
|
||||
impl Host {
|
||||
fn new() -> Self {
|
||||
let host = Self(tempfile::tempdir().unwrap());
|
||||
let dir = host.0.path();
|
||||
let mut helper = HELPER.to_string();
|
||||
for (program, body) in [
|
||||
(
|
||||
"/bin/ps",
|
||||
r#"test -f "$HOST/process_$2" && cat "$HOST/process_$2""#,
|
||||
),
|
||||
(
|
||||
"/sbin/route",
|
||||
"printf 'gateway: 192.0.2.1\\ninterface: en7\\n'",
|
||||
),
|
||||
(
|
||||
"/sbin/ifconfig",
|
||||
"echo 'inet 10.13.37.4 --> 10.13.37.4 netmask 0xffffff00'",
|
||||
),
|
||||
("/usr/bin/shlock", "exit 0"),
|
||||
(
|
||||
"/usr/sbin/sysctl",
|
||||
r#"
|
||||
case "$1" in -n) cat "$HOST/forwarding";; -w) echo 1 > "$HOST/forwarding";; esac"#,
|
||||
),
|
||||
(
|
||||
"/sbin/pfctl",
|
||||
r#"
|
||||
echo "$*" >> "$HOST/pf.log"
|
||||
case "$1" in
|
||||
-E) echo 'Token : 77' >&2;;
|
||||
-q) if [ "$5" = - ]; then cat > "$HOST/rules"; fi;;
|
||||
esac"#,
|
||||
),
|
||||
] {
|
||||
let path = dir.join(Path::new(program).file_name().unwrap());
|
||||
fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
helper = helper.replace(program, path.to_str().unwrap());
|
||||
}
|
||||
let relocated = |text: &str| {
|
||||
text.replace(
|
||||
"/private/etc/tsunagi-exit",
|
||||
dir.join("grants").to_str().unwrap(),
|
||||
)
|
||||
.replace(
|
||||
"/private/var/run/tsunagi-exit",
|
||||
dir.join("state").to_str().unwrap(),
|
||||
)
|
||||
.replace(
|
||||
"/private/etc/sudoers.d",
|
||||
dir.join("policy").to_str().unwrap(),
|
||||
)
|
||||
};
|
||||
fs::write(dir.join("helper.sh"), relocated(&helper)).unwrap();
|
||||
fs::write(dir.join("forwarding"), "0\n").unwrap();
|
||||
fs::write(dir.join("process_321"), "501 Tue Nov 24 16:42:52 2026\n").unwrap();
|
||||
fs::write(
|
||||
dir.join("installer.sh"),
|
||||
relocated(INSTALL).replace("/usr/sbin/visudo", "/usr/bin/true"),
|
||||
)
|
||||
.unwrap();
|
||||
host
|
||||
}
|
||||
|
||||
fn run(&self, script: &str, args: &[&str]) -> Output {
|
||||
self.run_as("321", script, args)
|
||||
}
|
||||
|
||||
fn run_as(&self, pid: &str, script: &str, args: &[&str]) -> Output {
|
||||
let mut command = Command::new("/bin/sh");
|
||||
command.arg(self.0.path().join(script));
|
||||
if script == "helper.sh" {
|
||||
command.arg(pid);
|
||||
}
|
||||
command
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.env("HOST", self.0.path())
|
||||
.env("SUDO_UID", "501")
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn grant(&self, uid: &str, key: &str) {
|
||||
let result = self.run("installer.sh", &[uid, key, HELPER]);
|
||||
assert!(result.status.success(), "{:?}", result.stderr);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restarting_with_a_new_utun_releases_a_dead_agents_rules_and_preserves_other_agents() {
|
||||
let host = Host::new();
|
||||
host.grant("501", "10.13.37.0_24");
|
||||
let dir = host.0.path();
|
||||
for (pid, iface) in [("321", "utun4"), ("322", "utun5")] {
|
||||
fs::write(
|
||||
dir.join(format!("process_{pid}")),
|
||||
format!("501 born {pid}"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
host.run_as(pid, "helper.sh", &["apply", iface, "10.13.37.0/24"])
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
}
|
||||
// PID 321 has been reused since that holder's abrupt termination.
|
||||
fs::write(dir.join("process_321"), "501 later").unwrap();
|
||||
assert!(host.run("helper.sh", &["clear", "utun9"]).status.success());
|
||||
assert!(!dir.join("state/tsng_501_4_10.13.37.0_24.token").exists());
|
||||
assert!(dir.join("state/tsng_501_5_10.13.37.0_24.token").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn privileged_helper_accepts_only_a_granted_subnet_configured_on_the_utun() {
|
||||
let host = Host::new();
|
||||
host.grant("502", "10.13.37.0_24");
|
||||
host.grant("501", "10.13.37.0_16");
|
||||
for args in [
|
||||
["apply", "utun4", "10.13.37.0/24"],
|
||||
["apply", "utun4", "10.13.37.0/16"],
|
||||
["apply", "utun4", "10.13.37.0/24;whoami"],
|
||||
["apply", "en0", "10.13.37.0/24"],
|
||||
["apply", "utun4/../", "10.13.37.0/24"],
|
||||
["shell", "utun4", "10.13.37.0/24"],
|
||||
] {
|
||||
assert!(!host.run("helper.sh", &args).status.success(), "{args:?}");
|
||||
}
|
||||
assert!(!host.0.path().join("pf.log").exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(host.0.path().join("forwarding")).unwrap(),
|
||||
"0\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[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();
|
||||
host.grant("501", "10.13.37.0_24");
|
||||
let dir = host.0.path();
|
||||
let rule = fs::read_to_string(dir.join("policy/tsunagi-exit-501")).unwrap();
|
||||
assert_eq!(
|
||||
rule,
|
||||
format!(
|
||||
"#501 ALL = (root) NOPASSWD: NOSETENV: {}/grants/offer-v1\n",
|
||||
dir.display()
|
||||
)
|
||||
);
|
||||
for _ in 0..2 {
|
||||
let result = host.run("helper.sh", &["apply", "utun4", "10.13.37.0/24"]);
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
}
|
||||
assert_eq!(fs::read_to_string(dir.join("forwarding")).unwrap(), "1\n");
|
||||
let rules = fs::read_to_string(dir.join("rules")).unwrap();
|
||||
let uplink = super::DefaultRoute {
|
||||
interface: "en7".into(),
|
||||
gateway: Some("192.0.2.1".parse().unwrap()),
|
||||
};
|
||||
assert_eq!(
|
||||
rules,
|
||||
super::pf_rules("utun4", &uplink, &["10.13.37.0/24".parse().unwrap()], None)
|
||||
);
|
||||
assert!(host.run("helper.sh", &["clear", "utun4"]).status.success());
|
||||
assert!(host.run("helper.sh", &["clear", "utun4"]).status.success());
|
||||
let calls = fs::read_to_string(dir.join("pf.log")).unwrap();
|
||||
assert_eq!(calls.lines().filter(|line| *line == "-E").count(), 1);
|
||||
assert_eq!(calls.lines().filter(|line| *line == "-X 77").count(), 1);
|
||||
assert!(calls.contains("-q -a com.apple/tsng_501_4_10.13.37.0_24 -f /dev/null"));
|
||||
assert_eq!(fs::read_to_string(dir.join("forwarding")).unwrap(), "1\n");
|
||||
}
|
||||
@@ -86,6 +86,7 @@ impl Capture<'_> {
|
||||
Some(&rules),
|
||||
)
|
||||
.unwrap();
|
||||
enable_forwarding(&run_tool).unwrap();
|
||||
}
|
||||
fn enable(&mut self) {
|
||||
self.offer(true);
|
||||
@@ -314,8 +315,8 @@ async fn exit_preserves_underlay_and_both_meshes() {
|
||||
added_route: false,
|
||||
added_scoped: false,
|
||||
};
|
||||
// The disposable runner enables kernel forwarding. A keeps the same
|
||||
// translated address and port when B installs an upstream route to this IP.
|
||||
// The local offer enables kernel forwarding. A keeps the same translated
|
||||
// address and port when B installs an upstream route to this IP.
|
||||
capture.offer(false);
|
||||
let port = member_round_trip(&*overlay, &*uplink, 43001, b"member before").await;
|
||||
capture.enable();
|
||||
|
||||
@@ -74,9 +74,22 @@ pub use windows::WindowsHostRules;
|
||||
#[cfg(all(feature = "tun-device", target_os = "macos"))]
|
||||
mod macos;
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
#[path = "macos/authorization.rs"]
|
||||
mod macos_authorization;
|
||||
#[cfg(any(test, target_os = "macos"))]
|
||||
#[cfg_attr(
|
||||
not(all(feature = "tun-device", target_os = "macos")),
|
||||
allow(dead_code)
|
||||
)]
|
||||
mod macos_exit;
|
||||
#[cfg(all(feature = "tun-device", target_os = "macos"))]
|
||||
pub use macos::MacosHostRules;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use macos_authorization::{
|
||||
authorize_macos_exit, macos_exit_authorization_uid, macos_exit_needs_authorization,
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::overlay) use macos_exit::macos_default_uplink;
|
||||
|
||||
/// What the host should be told for one interface.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
||||
@@ -28,6 +28,7 @@ use iroh::EndpointId;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::identity::NetworkId;
|
||||
use crate::traffic::{Direction, Role};
|
||||
|
||||
use super::exit::{ExitRulesReport, RuleSetReport};
|
||||
use super::hostrules::{
|
||||
@@ -147,7 +148,7 @@ impl Tally {
|
||||
/// The overlay interface.
|
||||
pub struct Interface {
|
||||
device: Arc<dyn TunDevice>,
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
forwarding: Option<super::egress::Gateway>,
|
||||
factory: Arc<dyn TunFactory>,
|
||||
name: String,
|
||||
@@ -226,8 +227,24 @@ impl Interface {
|
||||
carrier: Arc<dyn PacketCarrier>,
|
||||
) -> Result<Self, OverlayError> {
|
||||
let name = name.into();
|
||||
let request = TunRequest::bare(name.clone(), mtu);
|
||||
let device = factory.create(request.clone()).await;
|
||||
#[cfg(target_os = "macos")]
|
||||
let (factory, device, use_sockets) = match device {
|
||||
Err(OverlayError::UtunDenied(reason)) if factory.on_host() => {
|
||||
tracing::warn!(%reason,"system utun unavailable; exit sharing will use physical sockets");
|
||||
let sockets: Arc<dyn TunFactory> =
|
||||
Arc::new(super::egress::macos::SocketExit::default());
|
||||
let device = sockets.create(request).await?;
|
||||
(sockets, device, true)
|
||||
}
|
||||
result => (factory, result?, false),
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let device = device?;
|
||||
#[cfg(windows)]
|
||||
let use_sockets = factory.on_host();
|
||||
let host_rules = factory.host_rules();
|
||||
let device = factory.create(TunRequest::bare(name.clone(), mtu)).await?;
|
||||
// The name the operating system actually gave the interface. On Linux
|
||||
// and Windows that is the one we asked for; on macOS the kernel assigns
|
||||
// the utun unit, so the real name differs and everything that
|
||||
@@ -237,8 +254,8 @@ impl Interface {
|
||||
let name = device.name().to_string();
|
||||
let tally = Arc::new(Tally::default());
|
||||
|
||||
#[cfg(windows)]
|
||||
let forwarding = factory.on_host().then(|| {
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
let forwarding = use_sockets.then(|| {
|
||||
let routes = routes.clone();
|
||||
let carrier = carrier.clone();
|
||||
super::egress::Gateway::new(mtu, move |route, packet| {
|
||||
@@ -252,7 +269,16 @@ impl Interface {
|
||||
Some(PacketSource::Member)
|
||||
)
|
||||
{
|
||||
carrier.carry(route, packet);
|
||||
let obs = routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| Role::ServeExit,
|
||||
);
|
||||
if carrier.carry(route, packet) {
|
||||
obs.record();
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
@@ -268,7 +294,10 @@ impl Interface {
|
||||
tokio::select! {
|
||||
_=interval.tick()=>{
|
||||
let (probes,jobs)=routes.vips.tick(routes.vips.check_capacity().saturating_sub(checks.len()));
|
||||
for (route,packet) in probes {carrier.carry(route,packet);}
|
||||
for (route,packet) in probes {
|
||||
let obs = routes.traffic.packet(route.network,route.peer,Direction::Tx,&packet,||Role::Vip);
|
||||
if carrier.carry(route,packet) {obs.record();}
|
||||
}
|
||||
for job in jobs {
|
||||
let factory = Arc::clone(&factory);
|
||||
checks.spawn(job.run(move |socket, source| factory.bind_overlay_socket(socket, source)));
|
||||
@@ -294,8 +323,14 @@ impl Interface {
|
||||
};
|
||||
match routes.vips.outgoing(packet.clone()) {
|
||||
crate::vip::router::Decision::Send(route, packet) => {
|
||||
let obs =
|
||||
routes
|
||||
.vips
|
||||
.observe_outgoing(&routes.traffic, Some(route), &packet);
|
||||
for part in crate::vip::packet::fragments(packet, mtu) {
|
||||
let len = part.len();
|
||||
if carrier.carry(route, part) {
|
||||
obs.record_fragment(len);
|
||||
tally.sent.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -303,13 +338,22 @@ impl Interface {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
crate::vip::router::Decision::Local(packet) => {
|
||||
for part in crate::vip::packet::fragments(packet, mtu) {
|
||||
let _ = device.send(part).await;
|
||||
crate::vip::router::Decision::Local(translated)
|
||||
| crate::vip::router::Decision::Reassembled(translated) => {
|
||||
let obs =
|
||||
routes
|
||||
.vips
|
||||
.observe_outgoing(&routes.traffic, None, &translated);
|
||||
for part in crate::vip::packet::fragments(translated, mtu) {
|
||||
let len = part.len();
|
||||
if device.send(part).await.is_ok() {
|
||||
obs.record_fragment(len);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
crate::vip::router::Decision::Drop => continue,
|
||||
crate::vip::router::Decision::Drop
|
||||
| crate::vip::router::Decision::ProbeReceived => continue,
|
||||
crate::vip::router::Decision::Pass => {}
|
||||
}
|
||||
let destination = header.destination();
|
||||
@@ -322,7 +366,15 @@ impl Interface {
|
||||
.flatten();
|
||||
if let Some(recipients) = recipients {
|
||||
for &route in recipients.iter() {
|
||||
let obs = routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| Role::Broadcast,
|
||||
);
|
||||
if carrier.carry(route, packet.clone()) {
|
||||
obs.record();
|
||||
tally.sent.fetch_add(1, Ordering::Relaxed);
|
||||
tally.broadcast_sent.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
@@ -352,7 +404,25 @@ impl Interface {
|
||||
continue;
|
||||
};
|
||||
let len = packet.len() as u64;
|
||||
let obs = routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| {
|
||||
if exit.is_some() {
|
||||
Role::ViaExit
|
||||
} else if let IpAddr::V4(src) = header.source()
|
||||
&& routes.accepts_exit_traffic(route.network, src)
|
||||
{
|
||||
Role::ServeExit
|
||||
} else {
|
||||
Role::Mesh
|
||||
}
|
||||
},
|
||||
);
|
||||
if carrier.carry(route, packet) {
|
||||
obs.record();
|
||||
if let Some(exit) = exit {
|
||||
exit.tx_bytes.fetch_add(len, Ordering::Relaxed);
|
||||
}
|
||||
@@ -365,7 +435,7 @@ impl Interface {
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
forwarding,
|
||||
device,
|
||||
factory,
|
||||
@@ -489,7 +559,7 @@ impl Interface {
|
||||
(state.plan.clone(), state.is_ok())
|
||||
};
|
||||
if wanted.is_empty() {
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(Vec::new());
|
||||
}
|
||||
@@ -503,6 +573,12 @@ impl Interface {
|
||||
return;
|
||||
}
|
||||
if planned.as_ref() == Some(&wanted) && ok {
|
||||
if !wanted.client
|
||||
&& !wanted.offer.is_empty()
|
||||
&& let Some(report) = exit.refresh_offer(&wanted).await
|
||||
{
|
||||
self.exit_state().report = Some(report);
|
||||
}
|
||||
if let Some(outcome) = exit.refresh(&wanted).await {
|
||||
if let RuleOutcome::Failed(reason) = &outcome {
|
||||
tracing::warn!(interface = %self.name, %reason, "cannot refresh exit-client socket protection");
|
||||
@@ -511,12 +587,12 @@ impl Interface {
|
||||
report.client = Some(outcome);
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
self.configure_forwarding(exit.forwarded_uplink());
|
||||
return;
|
||||
}
|
||||
let report = exit.apply(&wanted).await;
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
self.configure_forwarding(exit.forwarded_uplink());
|
||||
for (range, outcome) in &report.offer {
|
||||
match outcome {
|
||||
@@ -542,7 +618,7 @@ impl Interface {
|
||||
if cfg!(target_os = "windows") {
|
||||
"`Set-NetIPInterface -Forwarding Enabled` on the interfaces involved"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"`sysctl -w net.inet.ip.forwarding=1`, set again after every reboot"
|
||||
"enable the exit in Tsunagi to authorize forwarding on macOS"
|
||||
} else {
|
||||
"`sysctl -w net.ipv4.ip_forward=1` (or `net.ipv4.conf.<interface>.forwarding=1`), \
|
||||
and set it in sysctl.d to keep it"
|
||||
@@ -565,7 +641,7 @@ impl Interface {
|
||||
state.report = Some(report);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
fn configure_forwarding(&self, physical: Option<(u32, std::net::Ipv4Addr)>) {
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(
|
||||
@@ -690,7 +766,18 @@ impl Interface {
|
||||
{
|
||||
Some((_, outcome)) => RuleSetReport {
|
||||
ok: outcome.is_applied(),
|
||||
detail: offer_detail(outcome, &range),
|
||||
detail: {
|
||||
#[cfg(target_os = "macos")]
|
||||
if self.forwarding.is_some() && outcome.is_applied() {
|
||||
format!(
|
||||
"physical TCP, UDP and ICMP echo forwarding for {range}"
|
||||
)
|
||||
} else {
|
||||
offer_detail(outcome, &range)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
offer_detail(outcome, &range)
|
||||
},
|
||||
},
|
||||
None => failed("not applied yet"),
|
||||
}
|
||||
@@ -726,8 +813,8 @@ impl Interface {
|
||||
}
|
||||
|
||||
/// Whether this agent can really act as an exit node in a network: the
|
||||
/// rules members' traffic needs are in place. Kernel forwarding is not
|
||||
/// part of it, because the agent never turns that on itself.
|
||||
/// platform reports that its offer rules are applied. The macOS kernel backend
|
||||
/// includes enabling IPv4 forwarding in that outcome.
|
||||
pub fn exit_offer_ready(&self, network: NetworkId) -> bool {
|
||||
let Some((policy, Some(range))) = self.routes.exit_settings(network) else {
|
||||
return false;
|
||||
@@ -830,7 +917,7 @@ impl Interface {
|
||||
|
||||
/// Removes the interface from the host.
|
||||
pub async fn remove(&self) {
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(Vec::new());
|
||||
}
|
||||
@@ -937,39 +1024,112 @@ impl Interface {
|
||||
};
|
||||
// Source ownership was checked before any VIP reverse translation.
|
||||
let packet = match self.routes.vips.incoming(network, peer, packet.clone()) {
|
||||
crate::vip::router::Decision::Send(route, packet) => {
|
||||
crate::vip::router::Decision::Send(route, reply) => {
|
||||
self.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &packet, || Role::Vip)
|
||||
.record();
|
||||
let packet = reply;
|
||||
// Probe replies use the ordinary peer carrier, never the TUN.
|
||||
self.carrier.carry(route, packet);
|
||||
let tx = self.routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| Role::Vip,
|
||||
);
|
||||
if self.carrier.carry(route, packet) {
|
||||
tx.record();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::Local(packet) => {
|
||||
for part in crate::vip::packet::fragments(packet, self.mtu) {
|
||||
crate::vip::router::Decision::Local(translated) => {
|
||||
let obs =
|
||||
self.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &translated, || Role::Vip);
|
||||
for part in crate::vip::packet::fragments(translated, self.mtu) {
|
||||
let len = part.len();
|
||||
if self.device.send(part).await.is_ok() {
|
||||
obs.record_fragment(len);
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::Reassembled(reassembled) => {
|
||||
for part in crate::vip::packet::fragments(reassembled, self.mtu) {
|
||||
self.deliver_admitted(network, peer, part, broadcast, exit.as_ref(), forwarded)
|
||||
.await;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::ProbeReceived => {
|
||||
self.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &packet, || Role::Vip)
|
||||
.record();
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::Drop => return Ok(()),
|
||||
crate::vip::router::Decision::Pass => packet,
|
||||
};
|
||||
self.deliver_admitted(network, peer, packet, broadcast, exit.as_ref(), forwarded)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn deliver_admitted(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
packet: Bytes,
|
||||
broadcast: bool,
|
||||
exit: Option<&Arc<super::router::SelectedExit>>,
|
||||
forwarded: bool,
|
||||
) {
|
||||
let obs = self
|
||||
.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &packet, || {
|
||||
if forwarded {
|
||||
Role::ServeExit
|
||||
} else if exit.is_some() {
|
||||
Role::ViaExit
|
||||
} else if broadcast {
|
||||
Role::Broadcast
|
||||
} else {
|
||||
Role::Mesh
|
||||
}
|
||||
});
|
||||
// Only authenticated member traffic admitted by the exit policy can
|
||||
// open a physical socket. A rejected allocation never falls through
|
||||
// to Wintun, where the local upstream's split routes might recapture it.
|
||||
#[cfg(not(windows))]
|
||||
let _ = forwarded;
|
||||
#[cfg(windows)]
|
||||
let client = if forwarded {
|
||||
self.routes.exit_activity.stamp(network, peer)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
if forwarded && let Some(gateway) = &self.forwarding {
|
||||
if gateway.forward(Route { network, peer }, packet) {
|
||||
if let Some(stamp) = client {
|
||||
self.routes.exit_activity.forwarded(&stamp);
|
||||
}
|
||||
obs.record();
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.tally.undeliverable.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
return Ok(());
|
||||
return;
|
||||
}
|
||||
// Remote broadcasts terminate here. Only local TUN ingress can fan out.
|
||||
let len = packet.len() as u64;
|
||||
if self.device.send(packet).await.is_ok() {
|
||||
if let Some(stamp) = client {
|
||||
self.routes.exit_activity.forwarded(&stamp);
|
||||
}
|
||||
obs.record();
|
||||
if let Some(exit) = exit {
|
||||
exit.rx_bytes.fetch_add(len, Ordering::Relaxed);
|
||||
}
|
||||
@@ -980,7 +1140,6 @@ impl Interface {
|
||||
}
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The addresses the interface should be carrying, from the table.
|
||||
|
||||
@@ -33,6 +33,10 @@ pub enum OverlayError {
|
||||
/// reason and, where there is one, what to do about it.
|
||||
#[error("overlay unavailable: {0}")]
|
||||
Unavailable(String),
|
||||
/// The OS denied creation of a macOS host utun.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[error("overlay unavailable: {0}")]
|
||||
UtunDenied(String),
|
||||
/// Anything else.
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
@@ -40,9 +44,10 @@ pub enum OverlayError {
|
||||
|
||||
pub mod broadcast;
|
||||
pub mod config;
|
||||
#[cfg(any(windows, test))]
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
mod egress;
|
||||
pub mod exit;
|
||||
mod exit_activity;
|
||||
pub mod hostrules;
|
||||
pub mod interface;
|
||||
pub mod packet;
|
||||
|
||||
@@ -477,6 +477,11 @@ async fn run(program: &'static str, args: Vec<String>) -> Result<String, Overlay
|
||||
text
|
||||
}
|
||||
};
|
||||
if message.contains("Operation not permitted") || message.contains("Permission denied") {
|
||||
return Err(OverlayError::UtunDenied(format!(
|
||||
"{display} failed: {message}"
|
||||
)));
|
||||
}
|
||||
Err(OverlayError::Unavailable(format!(
|
||||
"{display} failed: {message}"
|
||||
)))
|
||||
|
||||
@@ -85,6 +85,44 @@ pub struct NetworkRoutes {
|
||||
pub peers: Vec<(Ipv4Addr, EndpointId)>,
|
||||
}
|
||||
|
||||
impl NetworkRoutes {
|
||||
fn address_pair(&self, peer: EndpointId) -> Option<(Ipv4Addr, Ipv4Addr)> {
|
||||
let local = self.local?;
|
||||
let (remote, _) = self.peers.iter().find(|(_, owner)| *owner == peer)?;
|
||||
Some((local, *remote))
|
||||
}
|
||||
}
|
||||
|
||||
/// The signed addresses negotiated for one running diagnostic. A new allocation can
|
||||
/// invalidate either end, so an active probe must recheck them when ownership changes.
|
||||
pub(crate) struct DiagnosticPeer {
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
pub(crate) local: Ipv4Addr,
|
||||
pub(crate) remote: Ipv4Addr,
|
||||
// Even revision of the checked routing table, plus one if both addresses matched.
|
||||
checked: AtomicU64,
|
||||
}
|
||||
|
||||
impl DiagnosticPeer {
|
||||
pub(crate) fn is_current(&self, table: &RoutingTable) -> bool {
|
||||
let revision = table.address_revision.load(Ordering::Acquire);
|
||||
let checked = self.checked.load(Ordering::Relaxed);
|
||||
if checked & !1 == revision {
|
||||
return checked & 1 != 0;
|
||||
}
|
||||
let networks = table.read();
|
||||
let pair = networks
|
||||
.get(&self.network)
|
||||
.and_then(|n| n.address_pair(self.peer));
|
||||
let valid = pair == Some((self.local, self.remote));
|
||||
let revision = table.address_revision.load(Ordering::Relaxed);
|
||||
self.checked
|
||||
.store(revision | u64::from(valid), Ordering::Relaxed);
|
||||
valid
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a network cannot be added to the table.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum RouteError {
|
||||
@@ -109,10 +147,14 @@ pub enum RouteError {
|
||||
/// Address ownership across every network this agent is in.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct RoutingTable {
|
||||
pub(crate) traffic: Arc<crate::traffic::TrafficMonitor>,
|
||||
pub(crate) vips: Arc<crate::vip::VipRouter>,
|
||||
pub(super) exit_activity: super::exit_activity::ExitActivity,
|
||||
broadcast: ArcSwap<BroadcastTable>,
|
||||
selected_exit: ArcSwapOption<SelectedExit>,
|
||||
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
|
||||
/// Advanced by two under the routing write lock when signed address ownership changes.
|
||||
address_revision: AtomicU64,
|
||||
}
|
||||
|
||||
impl RoutingTable {
|
||||
@@ -122,15 +164,20 @@ impl RoutingTable {
|
||||
}
|
||||
|
||||
/// Exact local and signed remote addresses for a mesh diagnostic. Exit routes do not qualify.
|
||||
pub(crate) fn peer_addresses(
|
||||
pub(crate) fn diagnostic_peer(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
) -> Option<(Ipv4Addr, Ipv4Addr)> {
|
||||
) -> Option<DiagnosticPeer> {
|
||||
let networks = self.read();
|
||||
let routes = networks.get(&network)?;
|
||||
let (address, _) = routes.peers.iter().find(|(_, owner)| *owner == peer)?;
|
||||
Some((routes.local?, *address))
|
||||
let (local, remote) = networks.get(&network)?.address_pair(peer)?;
|
||||
Some(DiagnosticPeer {
|
||||
network,
|
||||
peer,
|
||||
local,
|
||||
remote,
|
||||
checked: AtomicU64::new(self.address_revision.load(Ordering::Relaxed) | 1),
|
||||
})
|
||||
}
|
||||
|
||||
fn read(&self) -> std::sync::RwLockReadGuard<'_, HashMap<NetworkId, NetworkRoutes>> {
|
||||
@@ -197,7 +244,20 @@ impl RoutingTable {
|
||||
if routes.exit.via.is_some() {
|
||||
clear_other_exits(networks, network);
|
||||
}
|
||||
let ownership_changed = networks
|
||||
.get(&network)
|
||||
.is_none_or(|old| old.local != routes.local || old.peers != routes.peers);
|
||||
if ownership_changed
|
||||
|| networks
|
||||
.get(&network)
|
||||
.is_some_and(|old| old.exit.offer != routes.exit.offer)
|
||||
{
|
||||
self.exit_activity.configure(network, Some(&routes));
|
||||
}
|
||||
networks.insert(network, routes);
|
||||
if ownership_changed {
|
||||
self.address_revision.fetch_add(2, Ordering::Release);
|
||||
}
|
||||
self.refresh_exit(networks);
|
||||
self.broadcast
|
||||
.store(Arc::new(BroadcastTable::build(networks)));
|
||||
@@ -208,7 +268,10 @@ impl RoutingTable {
|
||||
pub fn remove_network(&self, network: NetworkId) {
|
||||
self.vips.remove_network(network);
|
||||
let mut networks = self.write();
|
||||
networks.remove(&network);
|
||||
self.exit_activity.configure(network, None);
|
||||
if networks.remove(&network).is_some() {
|
||||
self.address_revision.fetch_add(2, Ordering::Release);
|
||||
}
|
||||
self.refresh_exit(&networks);
|
||||
self.broadcast
|
||||
.store(Arc::new(BroadcastTable::build(&networks)));
|
||||
@@ -238,7 +301,11 @@ impl RoutingTable {
|
||||
pub(crate) fn update_exit(&self, network: NetworkId, update: impl FnOnce(&mut ExitPolicy)) {
|
||||
let mut networks = self.write();
|
||||
if let Some(routes) = networks.get_mut(&network) {
|
||||
let offered = routes.exit.offer;
|
||||
update(&mut routes.exit);
|
||||
if offered != routes.exit.offer {
|
||||
self.exit_activity.configure(network, Some(routes));
|
||||
}
|
||||
if routes.exit.via.is_some() {
|
||||
clear_other_exits(&mut networks, network);
|
||||
}
|
||||
@@ -260,6 +327,10 @@ impl RoutingTable {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn recent_exit_client(&self, network: NetworkId, peer: EndpointId) -> bool {
|
||||
self.exit_activity.recent(network, peer)
|
||||
}
|
||||
|
||||
pub(crate) fn exit_traffic(&self, network: NetworkId, peer: EndpointId) -> Option<ExitTraffic> {
|
||||
let current = self.selected_exit.load();
|
||||
let exit = current
|
||||
@@ -608,6 +679,60 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_running_diagnostic_tracks_signed_ownership_across_route_changes() {
|
||||
let table = RoutingTable::new();
|
||||
let id = network("diagnostic");
|
||||
let other = network("other");
|
||||
table.set_network(id, routes()).unwrap();
|
||||
let bound = table.diagnostic_peer(id, peer(2)).unwrap();
|
||||
assert_eq!((bound.local, bound.remote), (addr(1), addr(2)));
|
||||
assert!(bound.is_current(&table));
|
||||
assert!(table.diagnostic_peer(id, peer(9)).is_none());
|
||||
assert!(table.set_network(other, routes()).is_err());
|
||||
table.set_exit(
|
||||
id,
|
||||
ExitPolicy {
|
||||
offer: true,
|
||||
via: Some(peer(3)),
|
||||
},
|
||||
);
|
||||
assert!(bound.is_current(&table));
|
||||
|
||||
let mut changed = routes();
|
||||
changed.peers[1].0 = addr(9);
|
||||
table.update_allocations(id, changed.clone()).unwrap();
|
||||
assert!(bound.is_current(&table), "another member moved");
|
||||
changed.peers[0].0 = addr(7);
|
||||
table.update_allocations(id, changed).unwrap();
|
||||
assert!(
|
||||
!bound.is_current(&table),
|
||||
"the old peer address is no longer owned"
|
||||
);
|
||||
assert!(!bound.is_current(&table));
|
||||
let moved = table.diagnostic_peer(id, peer(2)).unwrap();
|
||||
assert!(moved.is_current(&table));
|
||||
table
|
||||
.update_allocations(
|
||||
id,
|
||||
NetworkRoutes {
|
||||
local: None,
|
||||
..routes()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!moved.is_current(&table));
|
||||
assert!(table.diagnostic_peer(id, peer(2)).is_none());
|
||||
table.update_allocations(id, routes()).unwrap();
|
||||
assert!(bound.is_current(&table));
|
||||
table.remove_network(id);
|
||||
table.set_network(other, routes()).unwrap();
|
||||
assert!(
|
||||
!bound.is_current(&table),
|
||||
"same member and IPs in a different network"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packet_goes_to_the_member_that_holds_its_destination() {
|
||||
let table = RoutingTable::new();
|
||||
|
||||
@@ -509,6 +509,12 @@ mod system {
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
if denied {
|
||||
return OverlayError::UtunDenied(format!(
|
||||
"permission denied creating utun for `{name}`: {error}. Use the installed Tsunagi service for a host interface; a per-user `tsng up` can serve an exit through sockets."
|
||||
));
|
||||
}
|
||||
if denied {
|
||||
let hint = if cfg!(target_os = "windows") {
|
||||
"Open PowerShell or Command Prompt with 'Run as administrator' and \
|
||||
@@ -516,9 +522,6 @@ mod system {
|
||||
} else if cfg!(target_os = "linux") {
|
||||
"Start `tsng up` as root or grant CAP_NET_ADMIN with \
|
||||
`sudo setcap cap_net_admin,cap_net_bind_service+p /path/to/tsunagi`."
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"Creating a utun interface needs root on macOS; start `tsng up` \
|
||||
with `sudo`, or install it as a root LaunchDaemon."
|
||||
} else {
|
||||
"Start `tsng up` with the privileges required to create a TUN interface."
|
||||
};
|
||||
@@ -549,8 +552,7 @@ mod system {
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
"Creating a utun interface needs root; start the agent with `sudo` or as a root \
|
||||
LaunchDaemon, or run with `--no-tun` to keep the tunnels off the operating system."
|
||||
"Check the Tsunagi system service and the macOS interface configuration."
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
||||
{
|
||||
|
||||
@@ -91,9 +91,17 @@ pub struct Announcement {
|
||||
/// Announced IP plugin capabilities. Opaque to the core.
|
||||
pub capabilities: Vec<PluginCapability>,
|
||||
/// Software release reported by this peer for display after authentication.
|
||||
/// Keep this trailer last: original v8 readers stop after the capabilities.
|
||||
/// Original v8 readers stop after the capabilities.
|
||||
#[serde(default, deserialize_with = "read_agent_version")]
|
||||
pub agent_version: Option<String>,
|
||||
/// Whether the sender selected the recipient of this authenticated session as its exit.
|
||||
/// Older v8 frames end before this optional display hint.
|
||||
#[serde(default, deserialize_with = "read_exit_use")]
|
||||
pub uses_your_exit: Option<bool>,
|
||||
}
|
||||
|
||||
fn read_exit_use<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
|
||||
Ok(Option::<bool>::deserialize(d).ok().flatten())
|
||||
}
|
||||
|
||||
fn read_agent_version<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
@@ -433,6 +441,10 @@ mod tests {
|
||||
let mut a = read(&legacy);
|
||||
assert_eq!(a.agent_version, None);
|
||||
a.agent_version = Some("2.1.0-rc.2+android".into());
|
||||
let mut version_only = legacy.clone();
|
||||
version_only.extend(encode(&a.agent_version).unwrap());
|
||||
assert_eq!(read(&version_only).uses_your_exit, None);
|
||||
a.uses_your_exit = Some(true);
|
||||
let wire = encode(&Envelope {
|
||||
network_id: old.0,
|
||||
message: ControlMessage::Announce(a.clone()),
|
||||
@@ -440,6 +452,16 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(decode::<OldFrame>(&wire).unwrap(), old);
|
||||
assert_eq!(read(&wire), a);
|
||||
type VersionFrame = (
|
||||
[u8; 32],
|
||||
u8,
|
||||
bool,
|
||||
bool,
|
||||
String,
|
||||
Vec<PluginCapability>,
|
||||
Option<String>,
|
||||
);
|
||||
assert_eq!(decode::<VersionFrame>(&wire).unwrap().6, a.agent_version);
|
||||
|
||||
for invalid in ["", "1.2.3\nforged", &"1".repeat(256)] {
|
||||
let mut wire = legacy.clone();
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
//! Window-scoped, local observations. Each reader owns just its current interval.
|
||||
//! The first branch on the packet path skips all monitor work when nobody is watching.
|
||||
use arc_swap::ArcSwap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{
|
||||
Arc, Mutex, Weak,
|
||||
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
NetworkId,
|
||||
config::{MAX_INTERVAL_FLOWS, MAX_TRAFFIC_READERS},
|
||||
iroh_types::EndpointId,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
/// How the local agent handled the observed traffic.
|
||||
pub enum Role {
|
||||
/// Ordinary authenticated overlay traffic.
|
||||
Mesh,
|
||||
/// Local internet traffic carried by the selected exit peer.
|
||||
ViaExit,
|
||||
/// Internet traffic forwarded for a remote exit client.
|
||||
ServeExit,
|
||||
/// Traffic translated or probed by the virtual service router.
|
||||
Vip,
|
||||
/// One accepted overlay broadcast copy.
|
||||
Broadcast,
|
||||
/// A sample from an admitted mesh throughput test.
|
||||
SpeedTest,
|
||||
/// Messages on an authenticated control session.
|
||||
Control,
|
||||
/// Opaque datagrams forwarded between other mesh members.
|
||||
Relay,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
/// Whether this role counts transport data rather than locally visible IP packets.
|
||||
pub fn transport(self) -> bool {
|
||||
matches!(self, Self::Control | Self::Relay)
|
||||
}
|
||||
}
|
||||
|
||||
/// Addresses on the side of this agent and on the side of its authenticated peer.
|
||||
/// For encrypted transit the two endpoint IDs are ordered, with TX from the first.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
pub struct FlowKey {
|
||||
/// Public network identity.
|
||||
pub network: [u8; 32],
|
||||
/// Authenticated peer, or first endpoint of an opaque relay pair.
|
||||
pub peer: [u8; 32],
|
||||
/// Local forwarding or transport role.
|
||||
pub role: Role,
|
||||
/// Admitted header metadata used for aggregation.
|
||||
pub flow: Flow,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
/// One bidirectional IP conversation, control session, or opaque relay pair.
|
||||
pub enum Flow {
|
||||
/// IPv4 endpoints from the agent-facing and peer-facing sides.
|
||||
Ip {
|
||||
/// Source when sending, destination when receiving.
|
||||
near: [u8; 4],
|
||||
/// Destination when sending, source when receiving.
|
||||
far: [u8; 4],
|
||||
/// IPv4 protocol number.
|
||||
protocol: u8,
|
||||
/// Transport header fields available in this packet.
|
||||
detail: IpDetail,
|
||||
},
|
||||
/// Aggregated authenticated control envelopes.
|
||||
Control,
|
||||
/// An end-to-end mesh envelope passing through this device.
|
||||
Relay {
|
||||
/// The second endpoint, ordered by public key.
|
||||
other: [u8; 32],
|
||||
/// Opaque plugin protocol tag carried by the relay header.
|
||||
wire_protocol: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
/// Transport fields read from an IPv4 header and its bounded prefix.
|
||||
pub enum IpDetail {
|
||||
/// TCP/UDP ports in near/far order.
|
||||
Ports(u16, u16),
|
||||
/// ICMP echo requests and replies for the address pair.
|
||||
Echo,
|
||||
/// Another ICMP type and code.
|
||||
Icmp(u8, u8),
|
||||
/// Noninitial fragment with no transport header.
|
||||
Fragment,
|
||||
/// Protocol has no recognised, readable transport prefix.
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum Direction {
|
||||
Tx,
|
||||
Rx,
|
||||
}
|
||||
|
||||
impl Flow {
|
||||
pub(crate) fn ip(packet: &[u8], dir: Direction) -> Option<Self> {
|
||||
let header = packet.get(..20)?;
|
||||
let offset = usize::from(header[0] & 15) * 4;
|
||||
let total = usize::from(u16::from_be_bytes([header[2], header[3]]));
|
||||
if header[0] >> 4 != 4 || offset < 20 {
|
||||
return None;
|
||||
}
|
||||
let body = packet.get(..total)?.get(offset..)?;
|
||||
let protocol = header[9];
|
||||
let a: [u8; 4] = header[12..16].try_into().ok()?;
|
||||
let b: [u8; 4] = header[16..20].try_into().ok()?;
|
||||
let (near, far) = match dir {
|
||||
Direction::Tx => (a, b),
|
||||
Direction::Rx => (b, a),
|
||||
};
|
||||
let detail = if (u16::from_be_bytes([header[6], header[7]]) & 0x1fff) != 0 {
|
||||
IpDetail::Fragment
|
||||
} else {
|
||||
match (protocol, body) {
|
||||
(6 | 17, [a, b, c, d, ..]) => {
|
||||
let (src, dst) = (u16::from_be_bytes([*a, *b]), u16::from_be_bytes([*c, *d]));
|
||||
match dir {
|
||||
Direction::Tx => IpDetail::Ports(src, dst),
|
||||
Direction::Rx => IpDetail::Ports(dst, src),
|
||||
}
|
||||
}
|
||||
(1, [0 | 8, 0, ..]) => IpDetail::Echo,
|
||||
(1, [kind, code, ..]) => IpDetail::Icmp(*kind, *code),
|
||||
_ => IpDetail::Other,
|
||||
}
|
||||
};
|
||||
Some(Self::Ip {
|
||||
near,
|
||||
far,
|
||||
protocol,
|
||||
detail,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
/// Counters added during one observation interval.
|
||||
pub struct FlowDelta {
|
||||
/// Stable bidirectional identity of this flow.
|
||||
pub key: FlowKey,
|
||||
/// Bytes sent in this interval.
|
||||
pub tx_bytes: u64,
|
||||
/// Bytes received in this interval.
|
||||
pub rx_bytes: u64,
|
||||
/// Packets or transport messages sent.
|
||||
pub tx_packets: u64,
|
||||
/// Packets or transport messages received.
|
||||
pub rx_packets: u64,
|
||||
/// Age of the most recent observation when the interval was drained.
|
||||
pub age_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Serialize, Deserialize)]
|
||||
/// An interval delta for one local subscriber.
|
||||
pub struct TrafficSnapshot {
|
||||
/// Flows observed since the previous drain.
|
||||
pub flows: Vec<FlowDelta>,
|
||||
/// Elapsed monotonic milliseconds since opening or the preceding drain.
|
||||
pub interval_ms: u64,
|
||||
/// Packets/messages that could not be counted during this interval.
|
||||
pub omitted: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Counts {
|
||||
tx: u64,
|
||||
rx: u64,
|
||||
ntx: u64,
|
||||
nrx: u64,
|
||||
last: Instant,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Bucket {
|
||||
// Concurrent writers can spill into a different lane, including the reverse
|
||||
// direction of the same flow. The window merges these after the drain.
|
||||
lanes: [Mutex<HashMap<FlowKey, Counts>>; 4],
|
||||
since: Mutex<Instant>,
|
||||
entries: AtomicUsize,
|
||||
omitted: AtomicU64,
|
||||
}
|
||||
|
||||
fn millis(d: Duration) -> u64 {
|
||||
u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
impl Bucket {
|
||||
fn add(&self, key: FlowKey, dir: Direction, len: u64, now: Instant) {
|
||||
for lane in &self.lanes {
|
||||
let Ok(mut flows) = lane.try_lock() else {
|
||||
continue;
|
||||
};
|
||||
let counts = match flows.entry(key) {
|
||||
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
|
||||
std::collections::hash_map::Entry::Vacant(e) => {
|
||||
if self.entries.fetch_add(1, Ordering::Relaxed) >= MAX_INTERVAL_FLOWS {
|
||||
self.entries.fetch_sub(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
e.insert(Counts {
|
||||
tx: 0,
|
||||
rx: 0,
|
||||
ntx: 0,
|
||||
nrx: 0,
|
||||
last: now,
|
||||
})
|
||||
}
|
||||
};
|
||||
counts.last = counts.last.max(now);
|
||||
let (bytes, packets) = match dir {
|
||||
Direction::Tx => (&mut counts.tx, &mut counts.ntx),
|
||||
Direction::Rx => (&mut counts.rx, &mut counts.nrx),
|
||||
};
|
||||
*bytes = bytes.saturating_add(len);
|
||||
*packets = packets.saturating_add(1);
|
||||
return;
|
||||
}
|
||||
self.omitted.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(crate) struct TrafficMonitor {
|
||||
active: AtomicBool,
|
||||
readers: ArcSwap<Vec<Weak<Bucket>>>,
|
||||
// Only registration/unregistration use this lock.
|
||||
registration: Mutex<()>,
|
||||
}
|
||||
|
||||
impl TrafficMonitor {
|
||||
pub(crate) fn subscribe(self: &Arc<Self>) -> Result<TrafficSubscription, String> {
|
||||
let _edit = self.registration.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut readers = (**self.readers.load()).clone();
|
||||
if readers.len() >= MAX_TRAFFIC_READERS {
|
||||
return Err("Too many traffic monitor windows are open".into());
|
||||
}
|
||||
let bucket = Arc::new(Bucket {
|
||||
lanes: Default::default(),
|
||||
since: Mutex::new(Instant::now()),
|
||||
entries: AtomicUsize::new(0),
|
||||
omitted: AtomicU64::new(0),
|
||||
});
|
||||
readers.push(Arc::downgrade(&bucket));
|
||||
self.readers.store(Arc::new(readers));
|
||||
self.active.store(true, Ordering::Release);
|
||||
Ok(TrafficSubscription {
|
||||
owner: Arc::downgrade(self),
|
||||
bucket,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(
|
||||
&self,
|
||||
make: impl FnOnce() -> Option<(FlowKey, Direction, u64)>,
|
||||
) -> Observation {
|
||||
if !self.active.load(Ordering::Acquire) {
|
||||
return Observation(None);
|
||||
}
|
||||
let readers = self.readers.load_full();
|
||||
Observation(make().map(|(key, dir, len)| Pending {
|
||||
readers,
|
||||
key,
|
||||
dir,
|
||||
len,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn packet(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
dir: Direction,
|
||||
packet: &[u8],
|
||||
role: impl FnOnce() -> Role,
|
||||
) -> Observation {
|
||||
self.prepare(|| {
|
||||
Some((
|
||||
FlowKey {
|
||||
network: *network.as_bytes(),
|
||||
peer: *peer.as_bytes(),
|
||||
role: role(),
|
||||
flow: Flow::ip(packet, dir)?,
|
||||
},
|
||||
dir,
|
||||
packet.len() as u64,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn control(&self, network: NetworkId, peer: EndpointId, dir: Direction, len: u64) {
|
||||
self.prepare(|| {
|
||||
Some((
|
||||
FlowKey {
|
||||
network: *network.as_bytes(),
|
||||
peer: *peer.as_bytes(),
|
||||
role: Role::Control,
|
||||
flow: Flow::Control,
|
||||
},
|
||||
dir,
|
||||
len,
|
||||
))
|
||||
})
|
||||
.record();
|
||||
}
|
||||
|
||||
pub(crate) fn relay(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
source: [u8; 32],
|
||||
dest: [u8; 32],
|
||||
wire_protocol: u64,
|
||||
len: usize,
|
||||
) {
|
||||
self.prepare(|| {
|
||||
let (peer, other, dir) = if source <= dest {
|
||||
(source, dest, Direction::Tx)
|
||||
} else {
|
||||
(dest, source, Direction::Rx)
|
||||
};
|
||||
Some((
|
||||
FlowKey {
|
||||
network: *network.as_bytes(),
|
||||
peer,
|
||||
role: Role::Relay,
|
||||
flow: Flow::Relay {
|
||||
other,
|
||||
wire_protocol,
|
||||
},
|
||||
},
|
||||
dir,
|
||||
len as u64,
|
||||
))
|
||||
})
|
||||
.record();
|
||||
}
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
readers: Arc<Vec<Weak<Bucket>>>,
|
||||
key: FlowKey,
|
||||
dir: Direction,
|
||||
len: u64,
|
||||
}
|
||||
pub(crate) struct Observation(Option<Pending>);
|
||||
impl Pending {
|
||||
fn count(&self, len: u64) {
|
||||
let now = Instant::now();
|
||||
for reader in self.readers.iter().filter_map(Weak::upgrade) {
|
||||
reader.add(self.key, self.dir, len, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Observation {
|
||||
pub(crate) fn record(self) {
|
||||
if let Some(pending) = self.0 {
|
||||
pending.count(pending.len);
|
||||
}
|
||||
}
|
||||
pub(crate) fn record_fragment(&self, len: usize) {
|
||||
if let Some(pending) = &self.0 {
|
||||
pending.count(len as u64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the reader and turns off observation when the last window disconnects.
|
||||
#[derive(Debug)]
|
||||
pub struct TrafficSubscription {
|
||||
owner: Weak<TrafficMonitor>,
|
||||
bucket: Arc<Bucket>,
|
||||
}
|
||||
|
||||
impl TrafficSubscription {
|
||||
/// Atomically start a fresh interval; serialisation never holds the collector lock.
|
||||
pub fn snapshot(&self) -> TrafficSnapshot {
|
||||
let (now, previous, lanes, omitted) = {
|
||||
let mut since = self.bucket.since.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let locks = self
|
||||
.bucket
|
||||
.lanes
|
||||
.each_ref()
|
||||
.map(|lane| lane.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let now = Instant::now();
|
||||
self.bucket.entries.store(0, Ordering::Relaxed);
|
||||
let lanes = locks.map(|mut lock| std::mem::take(&mut *lock));
|
||||
(
|
||||
now,
|
||||
std::mem::replace(&mut *since, now),
|
||||
lanes,
|
||||
self.bucket.omitted.swap(0, Ordering::Relaxed),
|
||||
)
|
||||
};
|
||||
let [mut flows, second, third, fourth] = lanes;
|
||||
for (key, c) in [second, third, fourth].into_iter().flatten() {
|
||||
flows
|
||||
.entry(key)
|
||||
.and_modify(|a| {
|
||||
a.tx = a.tx.saturating_add(c.tx);
|
||||
a.rx = a.rx.saturating_add(c.rx);
|
||||
a.ntx = a.ntx.saturating_add(c.ntx);
|
||||
a.nrx = a.nrx.saturating_add(c.nrx);
|
||||
a.last = a.last.max(c.last)
|
||||
})
|
||||
.or_insert(c);
|
||||
}
|
||||
TrafficSnapshot {
|
||||
interval_ms: millis(now.saturating_duration_since(previous)),
|
||||
omitted,
|
||||
flows: flows
|
||||
.into_iter()
|
||||
.map(|(key, c)| FlowDelta {
|
||||
key,
|
||||
tx_bytes: c.tx,
|
||||
rx_bytes: c.rx,
|
||||
tx_packets: c.ntx,
|
||||
rx_packets: c.nrx,
|
||||
age_ms: millis(now.saturating_duration_since(c.last)),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TrafficSubscription {
|
||||
fn drop(&mut self) {
|
||||
if let Some(monitor) = self.owner.upgrade() {
|
||||
let _edit = monitor
|
||||
.registration
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let bucket = Arc::downgrade(&self.bucket);
|
||||
let remaining: Vec<_> = monitor
|
||||
.readers
|
||||
.load()
|
||||
.iter()
|
||||
.filter(|r| !Weak::ptr_eq(r, &bucket))
|
||||
.cloned()
|
||||
.collect();
|
||||
let active = !remaining.is_empty();
|
||||
monitor.readers.store(Arc::new(remaining));
|
||||
monitor.active.store(active, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,147 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
|
||||
fn ip(proto: u8, reply: bool) -> Vec<u8> {
|
||||
let mut p = vec![0; 32];
|
||||
p[0] = 0x45;
|
||||
p[2..4].copy_from_slice(&32u16.to_be_bytes());
|
||||
p[9] = proto;
|
||||
let (a, b, x, y) = if reply {
|
||||
(2, 1, 443u16, 49152u16)
|
||||
} else {
|
||||
(1, 2, 49152, 443)
|
||||
};
|
||||
p[12..16].copy_from_slice(&[10, 0, 0, a]);
|
||||
p[16..20].copy_from_slice(&[10, 0, 0, b]);
|
||||
p[20..22].copy_from_slice(&x.to_be_bytes());
|
||||
p[22..24].copy_from_slice(&y.to_be_bytes());
|
||||
if proto == 1 {
|
||||
p[20] = if reply { 0 } else { 8 };
|
||||
p[21] = 0;
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dormant_monitor_and_independent_window_lifetimes() {
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let submit = || {
|
||||
monitor
|
||||
.prepare(|| Some((control(), Direction::Tx, 100)))
|
||||
.record()
|
||||
};
|
||||
fn control() -> FlowKey {
|
||||
FlowKey {
|
||||
network: [1; 32],
|
||||
peer: [2; 32],
|
||||
role: Role::Control,
|
||||
flow: Flow::Control,
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
monitor
|
||||
.prepare(|| panic!("observer ran while closed"))
|
||||
.0
|
||||
.is_none()
|
||||
);
|
||||
let a = monitor.subscribe().unwrap();
|
||||
assert!(a.snapshot().flows.is_empty());
|
||||
submit();
|
||||
let pending = monitor.prepare(|| Some((control(), Direction::Rx, 50)));
|
||||
let b = monitor.subscribe().unwrap();
|
||||
pending.record();
|
||||
submit();
|
||||
let a_sample = a.snapshot();
|
||||
assert_eq!(a_sample.flows[0].tx_bytes, 200);
|
||||
assert_eq!(a_sample.flows[0].rx_bytes, 50);
|
||||
assert_eq!(b.snapshot().flows[0].tx_bytes, 100);
|
||||
assert!(a.snapshot().flows.is_empty());
|
||||
drop((a, b));
|
||||
assert!(
|
||||
monitor
|
||||
.prepare(|| panic!("observer left active"))
|
||||
.0
|
||||
.is_none()
|
||||
);
|
||||
assert!(monitor.subscribe().unwrap().snapshot().flows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tuple_and_echo_replies_have_the_same_key_and_fragments_never_invent_ports() {
|
||||
for protocol in [6, 17, 1] {
|
||||
let key = Flow::ip(&ip(protocol, false), Direction::Tx).unwrap();
|
||||
assert_eq!(Some(key), Flow::ip(&ip(protocol, true), Direction::Rx));
|
||||
}
|
||||
let mut packet = ip(17, false);
|
||||
packet[7] = 1;
|
||||
assert!(matches!(
|
||||
Flow::ip(&packet, Direction::Tx),
|
||||
Some(Flow::Ip {
|
||||
detail: IpDetail::Fragment,
|
||||
..
|
||||
})
|
||||
));
|
||||
packet[0] = 0x4f;
|
||||
assert!(Flow::ip(&packet, Direction::Tx).is_none());
|
||||
assert!(Flow::ip(&[], Direction::Rx).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_interval_reports_overflow_and_preserves_known_counters() {
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let sub = monitor.subscribe().unwrap();
|
||||
for i in 0..=MAX_INTERVAL_FLOWS {
|
||||
let mut peer = [0; 32];
|
||||
peer[..8].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
monitor
|
||||
.prepare(|| {
|
||||
Some((
|
||||
FlowKey {
|
||||
network: [0; 32],
|
||||
peer,
|
||||
role: Role::Control,
|
||||
flow: Flow::Control,
|
||||
},
|
||||
Direction::Tx,
|
||||
20,
|
||||
))
|
||||
})
|
||||
.record();
|
||||
}
|
||||
let sample = sub.snapshot();
|
||||
assert_eq!(sample.flows.len(), MAX_INTERVAL_FLOWS);
|
||||
assert_eq!(sample.omitted, 1);
|
||||
assert!(postcard::to_stdvec(&sample).unwrap().len() < (1 << 20));
|
||||
assert_eq!(sub.snapshot().omitted, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_writers_share_the_flow_without_waiting_and_closed_windows_release_inflight_buffers() {
|
||||
let monitor = Arc::new(TrafficMonitor::default());
|
||||
let sub = monitor.subscribe().unwrap();
|
||||
let key = FlowKey {
|
||||
network: [1; 32],
|
||||
peer: [2; 32],
|
||||
role: Role::Control,
|
||||
flow: Flow::Control,
|
||||
};
|
||||
monitor.prepare(|| Some((key, Direction::Tx, 20))).record();
|
||||
let held = sub.bucket.lanes[0].lock().unwrap();
|
||||
monitor.prepare(|| Some((key, Direction::Rx, 30))).record();
|
||||
drop(held);
|
||||
let result = sub.snapshot();
|
||||
assert_eq!(result.flows.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
result.flows[0].tx_bytes,
|
||||
result.flows[0].rx_bytes,
|
||||
result.omitted
|
||||
),
|
||||
(20, 30, 0)
|
||||
);
|
||||
let pending = monitor.prepare(|| Some((key, Direction::Rx, 10)));
|
||||
let bucket = Arc::downgrade(&sub.bucket);
|
||||
drop(sub);
|
||||
assert!(bucket.upgrade().is_none());
|
||||
pending.record();
|
||||
}
|
||||
@@ -15,6 +15,8 @@ pub(crate) enum Decision {
|
||||
Pass,
|
||||
Send(Route, Bytes),
|
||||
Local(Bytes),
|
||||
Reassembled(Bytes),
|
||||
ProbeReceived,
|
||||
Drop,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
@@ -452,6 +454,69 @@ impl VipRouter {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Identify an outgoing VIP datagram on the client-facing side of NAT. Called
|
||||
/// once on the reassembled datagram; only accepted fragments contribute bytes.
|
||||
pub(crate) fn observe_outgoing(
|
||||
&self,
|
||||
monitor: &crate::traffic::TrafficMonitor,
|
||||
route: Option<Route>,
|
||||
bytes: &[u8],
|
||||
) -> crate::traffic::Observation {
|
||||
use crate::traffic::{Direction, Flow as ObservedFlow, FlowKey, IpDetail, Role};
|
||||
monitor.prepare(|| {
|
||||
let state = self.lock();
|
||||
let reverse = packet::tuple(bytes).map(Tuple::reverse);
|
||||
let (route, dir, client) = if let Some(route) = route {
|
||||
let original = reverse
|
||||
.and_then(|t| state.reverse.get(&(route.network, route.peer, t)))
|
||||
.copied();
|
||||
(route, Direction::Tx, original)
|
||||
} else {
|
||||
// A local backend both receives requests and returns replies through this TUN.
|
||||
let source = packet::addresses(bytes)?.0;
|
||||
state.networks.iter().find_map(|(id, n)| {
|
||||
let route = Route {
|
||||
network: *id,
|
||||
peer: n.local,
|
||||
};
|
||||
if let Some(t) = reverse.and_then(|t| state.reverse.get(&(*id, n.local, t))) {
|
||||
return Some((route, Direction::Tx, Some(*t)));
|
||||
}
|
||||
let reply = reverse
|
||||
.and_then(|t| state.flows.get(&t))
|
||||
.is_some_and(|f| f.local && f.key.network == *id);
|
||||
(reply || n.vips.iter().any(|v| v.address == Some(source))).then_some((
|
||||
route,
|
||||
Direction::Rx,
|
||||
None,
|
||||
))
|
||||
})?
|
||||
};
|
||||
let flow = match client {
|
||||
Some(t) => ObservedFlow::Ip {
|
||||
near: t.src.octets(),
|
||||
far: t.dst.octets(),
|
||||
protocol: match t.protocol {
|
||||
Protocol::Tcp => 6,
|
||||
Protocol::Udp => 17,
|
||||
},
|
||||
detail: IpDetail::Ports(t.sport, t.dport),
|
||||
},
|
||||
None => ObservedFlow::ip(bytes, dir)?,
|
||||
};
|
||||
Some((
|
||||
FlowKey {
|
||||
network: *route.network.as_bytes(),
|
||||
peer: *route.peer.as_bytes(),
|
||||
role: Role::Vip,
|
||||
flow,
|
||||
},
|
||||
dir,
|
||||
bytes.len() as u64,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn outgoing(&self, packet: Bytes) -> Decision {
|
||||
let mut s = self.lock();
|
||||
let Some((src, dst)) = packet::addresses(&packet) else {
|
||||
@@ -716,6 +781,7 @@ impl VipRouter {
|
||||
p.heard = Some(Instant::now());
|
||||
p.pending = None;
|
||||
p.misses = 0;
|
||||
return Decision::ProbeReceived;
|
||||
}
|
||||
return Decision::Drop;
|
||||
}
|
||||
@@ -763,7 +829,7 @@ impl VipRouter {
|
||||
return packet::rewrite_icmp(&packet, original).map_or(Decision::Drop, Decision::Local);
|
||||
}
|
||||
if was_fragmented {
|
||||
Decision::Local(packet)
|
||||
Decision::Reassembled(packet)
|
||||
} else {
|
||||
Decision::Pass
|
||||
}
|
||||
@@ -1021,6 +1087,9 @@ mod tests {
|
||||
};
|
||||
assert_eq!(route.peer, a);
|
||||
let wire = packet::tuple(&out).unwrap();
|
||||
let monitor = std::sync::Arc::new(crate::traffic::TrafficMonitor::default());
|
||||
let capture = monitor.subscribe().unwrap();
|
||||
r.observe_outgoing(&monitor, Some(route), &out).record();
|
||||
assert_eq!(wire.dport, 6443);
|
||||
assert_ne!(wire.sport, t.sport);
|
||||
let reply = packet(wire.reverse(), 0x12);
|
||||
@@ -1028,6 +1097,17 @@ mod tests {
|
||||
panic!("reverse NAT expected")
|
||||
};
|
||||
assert_eq!(packet::tuple(&reply), Some(t.reverse()));
|
||||
monitor
|
||||
.packet(n, a, crate::traffic::Direction::Rx, &reply, || {
|
||||
crate::traffic::Role::Vip
|
||||
})
|
||||
.record();
|
||||
let sample = capture.snapshot();
|
||||
assert_eq!(sample.flows.len(), 1);
|
||||
assert_eq!(
|
||||
(sample.flows[0].tx_packets, sample.flows[0].rx_packets),
|
||||
(1, 1)
|
||||
);
|
||||
assert_eq!(packet::checksum(&reply[..20]), 0);
|
||||
{
|
||||
r.lock().networks.get_mut(&n).unwrap().vips.clear();
|
||||
@@ -1073,6 +1153,9 @@ mod tests {
|
||||
let Decision::Local(out) = r.outgoing(packet(t, 0)) else {
|
||||
panic!("local delivery expected")
|
||||
};
|
||||
let monitor = std::sync::Arc::new(crate::traffic::TrafficMonitor::default());
|
||||
let capture = monitor.subscribe().unwrap();
|
||||
r.observe_outgoing(&monitor, None, &out).record();
|
||||
let wire = packet::tuple(&out).unwrap();
|
||||
assert_eq!(wire.src, t.dst);
|
||||
assert_eq!(wire.dst, t.src);
|
||||
@@ -1080,6 +1163,13 @@ mod tests {
|
||||
let Decision::Local(reply) = r.outgoing(packet(wire.reverse(), 0)) else {
|
||||
panic!("local reverse NAT expected")
|
||||
};
|
||||
r.observe_outgoing(&monitor, None, &reply).record();
|
||||
let sample = capture.snapshot();
|
||||
assert_eq!(sample.flows.len(), 1);
|
||||
assert_eq!(
|
||||
(sample.flows[0].tx_packets, sample.flows[0].rx_packets),
|
||||
(1, 1)
|
||||
);
|
||||
assert_eq!(packet::tuple(&reply), Some(t.reverse()));
|
||||
}
|
||||
#[tokio::test]
|
||||
|
||||
@@ -73,6 +73,7 @@ async fn an_authenticated_disconnect_reports_the_quic_close_code() {
|
||||
hostname: "returning-peer".into(),
|
||||
capabilities: Vec::new(),
|
||||
agent_version: None,
|
||||
uses_your_exit: None,
|
||||
});
|
||||
write_frame(
|
||||
&mut send,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.6"
|
||||
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.6" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.6" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.6" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.6" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.6" }
|
||||
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
|
||||
|
||||
|
||||
@@ -113,6 +113,7 @@ pub fn networks(
|
||||
data_rtt_ms: peer.data_rtt.map(|rtt| rtt.as_millis() as u64),
|
||||
data_transport_detail: peer.data_transport_detail.clone(),
|
||||
exit_node: peer.exit_node,
|
||||
uses_our_exit: peer.uses_our_exit,
|
||||
path: data_path_report(&peer.data_path),
|
||||
})
|
||||
.collect(),
|
||||
|
||||
@@ -14,7 +14,7 @@ use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until, timeout
|
||||
const TOTAL_TIME: Duration = Duration::from_secs(5);
|
||||
const DIRECTION_TIME: Duration = Duration::from_millis(1900);
|
||||
const FEEDBACK_TICK: Duration = Duration::from_millis(25);
|
||||
const PACE_TICK: Duration = Duration::from_millis(2);
|
||||
const PACE_TICK: Duration = Duration::from_millis(1);
|
||||
|
||||
/// Parameters for one locally admitted, authenticated peer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -318,15 +318,20 @@ impl Session {
|
||||
break;
|
||||
}
|
||||
let emit = pacer.packets(now, search.target).min(limit - packets);
|
||||
let elapsed_us = now.duration_since(start).as_micros() as u32;
|
||||
for index in 0..emit {
|
||||
// A full tunnel queue is part of the observed data path. Charging
|
||||
// attempted probes bounds work during overload and preserves sequence gaps.
|
||||
if !io.packet(builder.packet(search.stage, packets + index, elapsed_us)) {
|
||||
if index > 0 && index.is_multiple_of(64) {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let elapsed_us = start.elapsed().as_micros() as u32;
|
||||
let packet = builder.packet(search.stage, packets, elapsed_us);
|
||||
// A tunnel waiting for a handshake can retain a submitted
|
||||
// packet. Charge that attempt, then release the unissued
|
||||
// part of this batch for a later tick if the tunnel is full.
|
||||
packets += 1;
|
||||
if !io.packet(packet) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
packets += emit;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -403,25 +408,7 @@ impl Session {
|
||||
if rx.count > packets {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
// A short final burst can never establish a rate on its own. Only complete
|
||||
// receiver windows are eligible, even if the sender reports a higher value.
|
||||
let bps = estimate
|
||||
.bps
|
||||
.filter(|_| rx.best > 0)
|
||||
.map(|v| v.min(rx.best))
|
||||
.or_else(|| (rx.best > 0).then_some(rx.best));
|
||||
let quality = if bps.is_none() {
|
||||
Quality::Insufficient
|
||||
} else if estimate.quality == Quality::Measured {
|
||||
Quality::Measured
|
||||
} else {
|
||||
Quality::AtLeast
|
||||
};
|
||||
let reading = Reading {
|
||||
bps,
|
||||
bytes: rx.bytes(),
|
||||
quality,
|
||||
};
|
||||
let reading = rx.finish(estimate);
|
||||
send(
|
||||
io,
|
||||
Control::Report {
|
||||
|
||||
@@ -4,7 +4,10 @@ use crate::{Datagram, Direction, Feedback, Quality, Reading};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
const INITIAL_BPS: u64 = 4_000_000;
|
||||
const INITIAL_BPS: u64 = 8_000_000;
|
||||
// A tail shorter than a regular feedback period may still contain a sustained
|
||||
// train. Require both clocks to span this interval and multiple arrival groups.
|
||||
const MIN_TRAIN: Duration = Duration::from_millis(60);
|
||||
const MIN_BPS: u64 = 32_000;
|
||||
|
||||
pub(crate) struct Receiver {
|
||||
@@ -12,25 +15,74 @@ pub(crate) struct Receiver {
|
||||
mtu: u16,
|
||||
packets: u32,
|
||||
seen: Vec<u64>,
|
||||
stage: u8,
|
||||
window: Option<Window>,
|
||||
pub(crate) count: u32,
|
||||
pub(crate) best: u64,
|
||||
best: u64,
|
||||
}
|
||||
|
||||
struct Window {
|
||||
start: Instant,
|
||||
stage: u8,
|
||||
received: u32,
|
||||
starts_on_packet: bool,
|
||||
opening_group: u32,
|
||||
arrival_groups: u8,
|
||||
last_group: Instant,
|
||||
first_arrival: Instant,
|
||||
last_arrival: Instant,
|
||||
first: u32,
|
||||
highest: u32,
|
||||
first_send_us: u32,
|
||||
last_send_us: u32,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
fn new(probe: Datagram, now: Instant) -> Self {
|
||||
Self {
|
||||
received: 1,
|
||||
opening_group: 1,
|
||||
arrival_groups: 1,
|
||||
last_group: now,
|
||||
first_arrival: now,
|
||||
last_arrival: now,
|
||||
first: probe.sequence,
|
||||
highest: probe.sequence,
|
||||
first_send_us: probe.sent_us,
|
||||
last_send_us: probe.sent_us,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, probe: Datagram, now: Instant) {
|
||||
if self.arrival_groups < 3
|
||||
&& now.duration_since(self.last_group) >= Duration::from_millis(20)
|
||||
{
|
||||
self.arrival_groups += 1;
|
||||
self.last_group = now;
|
||||
}
|
||||
self.first = self.first.min(probe.sequence);
|
||||
self.highest = self.highest.max(probe.sequence);
|
||||
self.first_send_us = self.first_send_us.min(probe.sent_us);
|
||||
self.last_send_us = self.last_send_us.max(probe.sent_us);
|
||||
// Packets already in the first arrival batch did not traverse the measured interval.
|
||||
if now.duration_since(self.first_arrival) < Duration::from_millis(1) {
|
||||
self.opening_group += 1;
|
||||
}
|
||||
self.received += 1;
|
||||
self.last_arrival = now;
|
||||
}
|
||||
|
||||
fn rate(&self, mtu: u16) -> Option<u64> {
|
||||
let arrivals = self.last_arrival.duration_since(self.first_arrival);
|
||||
let sends = Duration::from_micros(u64::from(self.last_send_us - self.first_send_us));
|
||||
let packets = self.received.saturating_sub(self.opening_group);
|
||||
if packets < 3 || self.arrival_groups < 3 || arrivals < MIN_TRAIN || sends < MIN_TRAIN {
|
||||
return None;
|
||||
}
|
||||
// Feedback and End may arrive late, or queued packets may arrive together.
|
||||
// Use the slower of the sender's and receiver's independent train clocks.
|
||||
let elapsed = arrivals.max(sends).as_micros() as u64;
|
||||
Some((u64::from(packets) * u64::from(mtu - HEADER) * 8_000_000 / elapsed).min(MAX_BPS))
|
||||
}
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
pub(crate) fn new(direction: Direction, mtu: u16, budget: u32) -> Self {
|
||||
let packets = budget / u32::from(mtu);
|
||||
@@ -39,6 +91,7 @@ impl Receiver {
|
||||
mtu,
|
||||
packets,
|
||||
seen: vec![0; packets.div_ceil(64) as usize],
|
||||
stage: 0,
|
||||
window: None,
|
||||
count: 0,
|
||||
best: 0,
|
||||
@@ -59,43 +112,50 @@ impl Receiver {
|
||||
}
|
||||
*word |= bit;
|
||||
self.count += 1;
|
||||
if self.window.as_ref().is_none_or(|w| w.stage < probe.stage) {
|
||||
self.window = Some(Window {
|
||||
start: now,
|
||||
stage: probe.stage,
|
||||
received: 0,
|
||||
starts_on_packet: true,
|
||||
arrival_groups: 0,
|
||||
last_group: now,
|
||||
first_arrival: now,
|
||||
last_arrival: now,
|
||||
first: probe.sequence,
|
||||
highest: probe.sequence,
|
||||
last_send_us: probe.sent_us,
|
||||
});
|
||||
if probe.stage < self.stage {
|
||||
return;
|
||||
}
|
||||
if let Some(w) = &mut self.window
|
||||
&& w.stage == probe.stage
|
||||
if probe.stage > self.stage {
|
||||
self.finish_window();
|
||||
self.stage = probe.stage;
|
||||
}
|
||||
match &mut self.window {
|
||||
Some(window) => window.push(probe, now),
|
||||
None => self.window = Some(Window::new(probe, now)),
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_window(&mut self) {
|
||||
if let Some(rate) = self.window.take().and_then(|w| w.rate(self.mtu)) {
|
||||
self.best = self.best.max(rate);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish(mut self, estimate: Reading) -> Reading {
|
||||
self.finish_window();
|
||||
// Final delivery belongs to the receiver. A sender may have stopped on its
|
||||
// byte limit before receiving feedback for a faster, fully observed train.
|
||||
if self.best == 0 {
|
||||
return Reading {
|
||||
bps: None,
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::Insufficient,
|
||||
};
|
||||
}
|
||||
if estimate.quality == Quality::Measured
|
||||
&& let Some(rate) = estimate.bps
|
||||
&& self.best.abs_diff(rate) <= rate / 5
|
||||
{
|
||||
if w.received == 0 {
|
||||
w.first_arrival = now;
|
||||
w.last_group = now;
|
||||
w.arrival_groups = 1;
|
||||
w.first = probe.sequence;
|
||||
w.highest = probe.sequence;
|
||||
} else {
|
||||
if w.arrival_groups < 3
|
||||
&& now.duration_since(w.last_group) >= Duration::from_millis(20)
|
||||
{
|
||||
w.arrival_groups += 1;
|
||||
w.last_group = now;
|
||||
}
|
||||
w.first = w.first.min(probe.sequence);
|
||||
w.highest = w.highest.max(probe.sequence);
|
||||
}
|
||||
w.received += 1;
|
||||
w.last_arrival = now;
|
||||
w.last_send_us = w.last_send_us.max(probe.sent_us);
|
||||
return Reading {
|
||||
bps: Some(rate.min(self.best)),
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::Measured,
|
||||
};
|
||||
}
|
||||
Reading {
|
||||
bps: Some(self.best),
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::AtLeast,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,45 +167,39 @@ impl Receiver {
|
||||
// followed by silence must never turn into a capacity estimate.
|
||||
pub(crate) fn sample(&mut self, now: Instant, minimum: Duration) -> Option<Feedback> {
|
||||
let bytes = self.bytes();
|
||||
let w = self.window.as_mut()?;
|
||||
let elapsed = now.duration_since(w.start);
|
||||
let w = self.window.as_ref()?;
|
||||
let elapsed = now.duration_since(w.first_arrival);
|
||||
if elapsed < minimum {
|
||||
return None;
|
||||
}
|
||||
let span = w.highest - w.first + 1;
|
||||
let loss = (u64::from(span.saturating_sub(w.received)) * 1000 / u64::from(span)) as u16;
|
||||
let spread = w.last_arrival.duration_since(w.first_arrival);
|
||||
// The first packet of a stage starts its clock. Its bytes arrived before
|
||||
// the measured interval. Later windows start exactly when the last one closed.
|
||||
let sampled = w.received.saturating_sub(u32::from(w.starts_on_packet));
|
||||
let enough = sampled >= 3 && w.arrival_groups >= 3 && spread >= elapsed * 2 / 3;
|
||||
if !enough && elapsed < Duration::from_millis(600) {
|
||||
let rate = w.rate(self.mtu);
|
||||
if rate.is_none() && elapsed < Duration::from_millis(600) {
|
||||
return None;
|
||||
}
|
||||
let bps = if enough {
|
||||
(u64::from(sampled) * u64::from(self.mtu - HEADER) * 8_000_000
|
||||
/ elapsed.as_micros().max(1) as u64)
|
||||
.min(MAX_BPS)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let bps = rate.unwrap_or(0);
|
||||
let feedback = Feedback {
|
||||
stage: w.stage,
|
||||
stage: self.stage,
|
||||
bps,
|
||||
lost_per_mille: loss,
|
||||
bytes,
|
||||
echo_us: w.last_send_us,
|
||||
};
|
||||
w.start = now;
|
||||
w.received = 0;
|
||||
w.starts_on_packet = false;
|
||||
if bps > 0 {
|
||||
self.best = self.best.max(bps);
|
||||
}
|
||||
self.window = None;
|
||||
self.best = self.best.max(bps);
|
||||
Some(feedback)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Phase {
|
||||
Ramp,
|
||||
// A rate backed off from congestion needs another, higher offer to test it.
|
||||
Settle { verified: bool },
|
||||
Challenge { previous_rate: u64 },
|
||||
}
|
||||
|
||||
pub(crate) struct Search {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) target: u64,
|
||||
@@ -153,7 +207,7 @@ pub(crate) struct Search {
|
||||
baseline_delay: Option<u32>,
|
||||
initial_loss: Option<u16>,
|
||||
last_echo: Option<u32>,
|
||||
confirm: bool,
|
||||
phase: Phase,
|
||||
previous: Option<u64>,
|
||||
measured: Option<u64>,
|
||||
}
|
||||
@@ -167,7 +221,7 @@ impl Default for Search {
|
||||
baseline_delay: None,
|
||||
initial_loss: None,
|
||||
last_echo: None,
|
||||
confirm: false,
|
||||
phase: Phase::Ramp,
|
||||
previous: None,
|
||||
measured: None,
|
||||
}
|
||||
@@ -190,34 +244,53 @@ impl Search {
|
||||
let base = *self.baseline_delay.get_or_insert(delay);
|
||||
self.baseline_delay = Some(base.min(delay));
|
||||
let queuing = delay > base.saturating_add(45_000).max(base.saturating_mul(2));
|
||||
// A small, constant random loss is common on Wi-Fi and cellular links.
|
||||
// Reduce on growing loss, queue delay or a receiver rate below the offer.
|
||||
// Loss present at the first offer also reduces the payload rate that
|
||||
// can arrive at higher offers. Look for additional loss or queuing.
|
||||
// A very lossy first sample may already be an overloaded slow path.
|
||||
let baseline_loss = *self
|
||||
.initial_loss
|
||||
.get_or_insert(sample.lost_per_mille.min(100));
|
||||
.get_or_insert(sample.lost_per_mille.min(400));
|
||||
let expected = self.target * u64::from(1000 - baseline_loss) / 1000;
|
||||
let congested =
|
||||
sample.lost_per_mille > baseline_loss + 30 || bps < self.target * 4 / 5 || queuing;
|
||||
sample.lost_per_mille > baseline_loss + 30 || bps < expected * 4 / 5 || queuing;
|
||||
if congested {
|
||||
self.confirm = true;
|
||||
let verified = match self.phase {
|
||||
Phase::Challenge { previous_rate } => {
|
||||
bps.abs_diff(previous_rate) <= previous_rate / 5
|
||||
}
|
||||
Phase::Settle { verified } => verified && bps >= self.target * 4 / 5,
|
||||
Phase::Ramp => false,
|
||||
};
|
||||
self.phase = Phase::Settle { verified };
|
||||
self.previous = None;
|
||||
self.offer(if bps == 0 {
|
||||
self.target / 2
|
||||
} else {
|
||||
bps * 97 / 100
|
||||
});
|
||||
} else if self.confirm {
|
||||
} else if let Phase::Settle { verified } = self.phase {
|
||||
if sample.lost_per_mille > 100 {
|
||||
self.previous = None;
|
||||
return;
|
||||
}
|
||||
if let Some(prev) = self.previous
|
||||
if let Some(prev) = self.previous.replace(bps)
|
||||
&& prev.abs_diff(bps) <= bps / 6
|
||||
{
|
||||
self.measured = Some((prev + bps) / 2);
|
||||
} else {
|
||||
self.previous = Some(bps);
|
||||
let steady = (prev + bps) / 2;
|
||||
if verified {
|
||||
self.measured = Some(steady);
|
||||
} else if elapsed_us >= 850_000 {
|
||||
// A cold tunnel or one busy scheduler slice can look like a bottleneck.
|
||||
// Two samples at our own reduced rate prove only that we can sustain it.
|
||||
self.phase = Phase::Challenge {
|
||||
previous_rate: steady,
|
||||
};
|
||||
self.offer(steady * 2);
|
||||
self.previous = None;
|
||||
}
|
||||
}
|
||||
} else if self.target < MAX_BPS {
|
||||
self.phase = Phase::Ramp;
|
||||
self.offer(self.target.saturating_mul(4));
|
||||
}
|
||||
}
|
||||
@@ -272,7 +345,10 @@ impl Pacer {
|
||||
|
||||
pub(crate) fn packets(&mut self, now: Instant, bps: u64) -> u32 {
|
||||
// The event loop may have been descheduled. Never catch up with a long burst.
|
||||
let elapsed = now.duration_since(self.last_tick).as_nanos().min(3_000_000) as u64;
|
||||
let elapsed = now
|
||||
.duration_since(self.last_tick)
|
||||
.as_nanos()
|
||||
.min(12_000_000) as u64;
|
||||
self.last_tick = now;
|
||||
self.credit += elapsed * bps;
|
||||
let packets = self.credit / self.cost;
|
||||
@@ -323,11 +399,8 @@ mod tests {
|
||||
);
|
||||
assert_eq!(rx.count, 3);
|
||||
assert_eq!(rx.bytes(), 3 * u32::from(1280 - HEADER));
|
||||
assert!(
|
||||
rx.window
|
||||
.as_ref()
|
||||
.is_some_and(|w| w.stage == 1 && w.received == 2)
|
||||
);
|
||||
assert_eq!(rx.stage, 1);
|
||||
assert!(rx.window.as_ref().is_some_and(|w| w.received == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -351,6 +424,38 @@ mod tests {
|
||||
|
||||
const NORMAL_BYTES_FOR_TEST: u32 = 1024 * 1024;
|
||||
|
||||
#[test]
|
||||
fn final_rate_uses_delivered_payload_even_when_end_overtakes_feedback() {
|
||||
let start = Instant::now();
|
||||
let mut rx = Receiver::new(Direction::Download, 1280, NORMAL_BYTES_FOR_TEST);
|
||||
// The first train takes twice as long to arrive as to send. The faster
|
||||
// second train ends before the next feedback tick.
|
||||
for i in 0..=100 {
|
||||
rx.put(
|
||||
packet(i, 0, i * 1_000),
|
||||
start + Duration::from_millis(u64::from(i) * 2),
|
||||
);
|
||||
}
|
||||
let tick = Duration::from_millis(220);
|
||||
let initial = rx.sample(start + tick, tick).unwrap();
|
||||
let payload_bits = u64::from(1280 - HEADER) * 8;
|
||||
assert_eq!(initial.bps, payload_bits * 500);
|
||||
for i in 0..=100 {
|
||||
rx.put(
|
||||
packet(101 + i, 1, 250_000 + i * 1_000),
|
||||
start + Duration::from_millis(250 + u64::from(i)),
|
||||
);
|
||||
}
|
||||
let result = rx.finish(Reading {
|
||||
bytes: initial.bytes,
|
||||
bps: Some(initial.bps),
|
||||
quality: Quality::AtLeast,
|
||||
});
|
||||
assert_eq!(result.bps, Some(payload_bits * 1000));
|
||||
assert_eq!(result.quality, Quality::AtLeast);
|
||||
assert_eq!(result.bytes, 202 * u32::from(1280 - HEADER));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retransmitted_feedback_does_not_supply_two_confirmation_windows() {
|
||||
let mut search = Search::default();
|
||||
@@ -367,6 +472,12 @@ mod tests {
|
||||
search.observe(observed, 243_000);
|
||||
assert!(!search.done());
|
||||
search.observe(f(1, 970_000, 0, 45000, 360_000), 361_000);
|
||||
assert!(!search.done());
|
||||
search.observe(f(1, 970_000, 0, 100_000, 900_000), 901_000);
|
||||
assert_eq!(search.stage, 2);
|
||||
search.observe(f(2, 1_000_000, 450, 120_000, 1_060_000), 1_061_000);
|
||||
search.observe(f(3, 970_000, 0, 150_000, 1_220_000), 1_221_000);
|
||||
search.observe(f(3, 970_000, 0, 180_000, 1_380_000), 1_381_000);
|
||||
assert!(search.done());
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ struct Link {
|
||||
remote: Handle,
|
||||
start: Instant,
|
||||
rate: u64,
|
||||
warmup: Option<(Duration, u64)>,
|
||||
control_delay: Duration,
|
||||
drop_every: u32,
|
||||
state: Arc<Mutex<Delivery>>,
|
||||
@@ -45,11 +46,14 @@ impl Io for Link {
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
let probe = decode_packet(&packet).unwrap();
|
||||
let tick = self.start.elapsed().as_millis() as u64;
|
||||
let rate = self
|
||||
.warmup
|
||||
.filter(|(until, _)| self.start.elapsed() < *until)
|
||||
.map_or(self.rate, |(_, rate)| rate);
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state.tick != tick {
|
||||
let elapsed = tick - state.tick;
|
||||
state.credit =
|
||||
(state.credit + self.rate * elapsed / 8000).min(self.rate * 4 / 8000 + 1300);
|
||||
state.credit = (state.credit + rate * elapsed / 8000).min(rate * 4 / 8000 + 1300);
|
||||
state.tick = tick;
|
||||
}
|
||||
state.bytes += packet.len() as u64;
|
||||
@@ -83,7 +87,7 @@ fn config(local: u8, remote: u8, bytes: u32) -> Config {
|
||||
}
|
||||
|
||||
async fn measure(down: u64, up: u64, budget: u32) -> (Progress, Progress, Link, Link) {
|
||||
shaped(down, up, budget, Duration::ZERO, 0).await
|
||||
shaped(down, up, budget, Duration::ZERO, 0, None).await
|
||||
}
|
||||
|
||||
async fn shaped(
|
||||
@@ -92,6 +96,7 @@ async fn shaped(
|
||||
budget: u32,
|
||||
control_delay: Duration,
|
||||
drop_every: u32,
|
||||
warmup: Option<(Duration, u64)>,
|
||||
) -> (Progress, Progress, Link, Link) {
|
||||
let cfg = |a, b| Config {
|
||||
rtt: control_delay.max(Duration::from_millis(20)),
|
||||
@@ -105,7 +110,8 @@ async fn shaped(
|
||||
};
|
||||
let (b, responder) = respond(cfg(2, 1), start);
|
||||
let now = Instant::now();
|
||||
let link = |remote, rate| Link {
|
||||
let link = |remote, rate, warmup| Link {
|
||||
warmup,
|
||||
remote,
|
||||
start: now,
|
||||
rate,
|
||||
@@ -114,9 +120,13 @@ async fn shaped(
|
||||
state: Default::default(),
|
||||
samples: Default::default(),
|
||||
};
|
||||
let ab = link(b, up);
|
||||
let ba = link(a, down);
|
||||
let ab = link(b, up, None);
|
||||
let ba = link(a, down, warmup);
|
||||
let (a, b) = tokio::join!(initiator.run(ab.clone()), responder.run(ba.clone()));
|
||||
println!(
|
||||
"Shaped path {down}/{up} bit/s, receiver readings {:?}/{:?}",
|
||||
a.down.bps, a.up.bps
|
||||
);
|
||||
assert!(now.elapsed() <= Duration::from_secs(5));
|
||||
assert!(ab.state.lock().unwrap().bytes <= u64::from(budget));
|
||||
assert!(ba.state.lock().unwrap().bytes <= u64::from(budget));
|
||||
@@ -173,6 +183,7 @@ async fn persistent_random_loss_does_not_masquerade_as_a_slow_link() {
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(45),
|
||||
20,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
@@ -299,6 +310,7 @@ async fn slower_control_feedback_leaves_time_for_both_directions() {
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(130),
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a, b);
|
||||
@@ -329,10 +341,22 @@ async fn slow_links_accumulate_enough_arrivals_for_a_rate() {
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn persistent_heavy_loss_reports_only_sustained_lower_bounds() {
|
||||
let (a, _, _, _) = shaped(50_000_000, 50_000_000, NORMAL_BYTES, Duration::ZERO, 3).await;
|
||||
let (a, _, _, _) = shaped(
|
||||
50_000_000,
|
||||
50_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::ZERO,
|
||||
3,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
for r in [a.down, a.up] {
|
||||
assert_eq!(r.quality, Quality::AtLeast, "{r:?}");
|
||||
assert!(r.bps.is_some_and(|v| (100_000..=33_500_000).contains(&v)));
|
||||
assert!(
|
||||
r.bps
|
||||
.is_some_and(|v| (28_000_000..=36_000_000).contains(&v)),
|
||||
"{r:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,3 +375,109 @@ fn a_finished_rate_requires_evidence_of_delivered_payload() {
|
||||
assert!(Control::decode(&message.encode().unwrap()).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_cold_download_reprobes_after_the_path_warms_up() {
|
||||
let (result, _, _, _) = shaped(
|
||||
300_000_000,
|
||||
250_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::ZERO,
|
||||
0,
|
||||
Some((Duration::from_millis(850), 60_000_000)),
|
||||
)
|
||||
.await;
|
||||
for (reading, expected) in [(result.down, 300_000_000), (result.up, 250_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|rate| (expected * 8 / 10..=expected * 11 / 10).contains(&rate)),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delayed_feedback_does_not_hide_the_metered_receivers_last_sustained_rate() {
|
||||
let (result, _, _, _) = shaped(
|
||||
350_000_000,
|
||||
200_000_000,
|
||||
METERED_BYTES,
|
||||
Duration::from_millis(95),
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
for (reading, expected) in [(result.down, 350_000_000), (result.up, 200_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|rate| (expected * 75 / 100..=expected * 11 / 10).contains(&rate)),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_full_tunnel_charges_only_packets_actually_submitted_to_it() {
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
|
||||
struct BusyQueue {
|
||||
other: Handle,
|
||||
start: Instant,
|
||||
stalled: AtomicBool,
|
||||
submitted: AtomicU32,
|
||||
}
|
||||
|
||||
impl Io for BusyQueue {
|
||||
async fn control(&self, message: Control) -> bool {
|
||||
if let Control::End { packets, .. } = message {
|
||||
assert!(self.stalled.load(Ordering::Relaxed));
|
||||
assert_eq!(packets, self.submitted.load(Ordering::Relaxed));
|
||||
}
|
||||
if !matches!(message, Control::Start(_)) {
|
||||
self.other.control(message);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
let count = self.submitted.fetch_add(1, Ordering::Relaxed);
|
||||
let full = self.start.elapsed() > Duration::from_millis(180) && count.is_multiple_of(3);
|
||||
if full {
|
||||
self.stalled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
// A backpressured tunnel may drop the packet or retain it for a
|
||||
// pending handshake. Either outcome must respect the byte budget.
|
||||
if !full || count.is_multiple_of(2) {
|
||||
self.other.data(decode_packet(&packet).unwrap());
|
||||
}
|
||||
!full
|
||||
}
|
||||
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
let budget = 2 * 1024 * 1024;
|
||||
let (a, outgoing) = initiate(config(1, 2, budget));
|
||||
let (b, incoming) = respond(
|
||||
config(2, 1, budget),
|
||||
Start {
|
||||
id: 7,
|
||||
byte_limit: budget,
|
||||
mtu: 1280,
|
||||
},
|
||||
);
|
||||
let queue = |other| BusyQueue {
|
||||
other,
|
||||
start: Instant::now(),
|
||||
stalled: AtomicBool::new(false),
|
||||
submitted: AtomicU32::new(0),
|
||||
};
|
||||
let (initiator, responder) = tokio::join!(
|
||||
outgoing.run(queue(b.clone())),
|
||||
incoming.run(queue(a.clone()))
|
||||
);
|
||||
assert_eq!(initiator.state, State::Complete);
|
||||
assert_eq!(initiator, responder);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.6"
|
||||
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.6" }
|
||||
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"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.6"
|
||||
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.6" }
|
||||
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).
|
||||
|
||||
@@ -29,6 +29,7 @@ impl Client for AgentClient {
|
||||
}
|
||||
|
||||
/// Handle the UI holds: send commands, read the latest snapshot.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AgentClient {
|
||||
tx: mpsc::UnboundedSender<Command>,
|
||||
shared: Arc<Mutex<Snapshot>>,
|
||||
@@ -122,7 +123,7 @@ async fn worker(
|
||||
run(&resolve_socket(), command, &shared, &pending_copy, &ctx).await;
|
||||
refresh(&shared, &ctx).await;
|
||||
lock(&shared).busy = false;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -145,7 +146,7 @@ async fn refresh(shared: &Arc<Mutex<Snapshot>>, ctx: &egui::Context) {
|
||||
guard.at = Some(Instant::now());
|
||||
guard.socket = socket;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
|
||||
/// Runs one command and records its outcome.
|
||||
@@ -157,7 +158,7 @@ async fn run(
|
||||
ctx: &egui::Context,
|
||||
) {
|
||||
lock(shared).busy = true;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
|
||||
let outcome: Result<String, String> = match command {
|
||||
Command::SaveVip {
|
||||
@@ -302,7 +303,7 @@ async fn run(
|
||||
Some(outcome)
|
||||
};
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
|
||||
/// Where the GUI looks for the agent: `TSUNAGI_CONTROL_SOCKET` if set, else the
|
||||
|
||||
+152
-54
@@ -5,7 +5,7 @@
|
||||
//! 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::sync::{Arc, Mutex};
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
@@ -17,12 +17,19 @@ use crate::ui::{self, UiState};
|
||||
|
||||
use tsunagi_ui::app_fonts;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Views {
|
||||
state: UiState,
|
||||
traffic: Traffic,
|
||||
}
|
||||
|
||||
/// The window's state.
|
||||
pub(crate) struct App {
|
||||
agent: AgentClient,
|
||||
state: UiState,
|
||||
/// Traffic rates derived from successive snapshots.
|
||||
traffic: Traffic,
|
||||
runtime: tokio::runtime::Handle,
|
||||
monitor: Option<crate::monitor::Monitor>,
|
||||
views: Arc<Mutex<Views>>,
|
||||
device_revision: Option<(u64, tsunagi_ui::stats::Unit, bool)>,
|
||||
/// The snapshot generation last folded into `traffic`.
|
||||
sampled: u64,
|
||||
}
|
||||
@@ -41,8 +48,10 @@ impl App {
|
||||
let agent = AgentClient::spawn(&runtime, ctx);
|
||||
Ok(Self {
|
||||
agent,
|
||||
state: UiState::default(),
|
||||
traffic: Traffic::default(),
|
||||
runtime,
|
||||
monitor: None,
|
||||
views: Default::default(),
|
||||
device_revision: None,
|
||||
sampled: 0,
|
||||
})
|
||||
}
|
||||
@@ -51,41 +60,64 @@ impl App {
|
||||
impl eframe::App for App {
|
||||
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
let snapshot = self.agent.snapshot();
|
||||
let mut views = self.views.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Views { state, traffic } = &mut *views;
|
||||
if snapshot.generation != self.sampled
|
||||
&& let (Some(Ok(report)), Some(at)) = (&snapshot.status, snapshot.at)
|
||||
{
|
||||
self.traffic.observe(report, at);
|
||||
traffic.observe(report, at);
|
||||
self.sampled = snapshot.generation;
|
||||
}
|
||||
|
||||
ui::draw(ctx, &self.agent, &mut self.state, &snapshot, &self.traffic);
|
||||
self.show_devices_windows(ctx, &snapshot);
|
||||
self.show_vip_windows(ctx, &snapshot);
|
||||
self.show_about_window(ctx, &snapshot);
|
||||
ui::draw(ctx, &self.agent, state, &snapshot, traffic);
|
||||
if state.monitor_open {
|
||||
let monitor = self.monitor.get_or_insert_with(|| {
|
||||
crate::monitor::Monitor::new(&self.runtime, self.agent.socket())
|
||||
});
|
||||
if !monitor.show(ctx, &snapshot) {
|
||||
self.monitor = None;
|
||||
state.monitor_open = false;
|
||||
}
|
||||
}
|
||||
Self::show_vip_windows(ctx, &self.agent, state, &snapshot);
|
||||
Self::show_about_window(ctx, &self.agent, state, &snapshot);
|
||||
let revision = (snapshot.generation, state.unit, snapshot.busy);
|
||||
let refresh = self.device_revision != Some(revision);
|
||||
self.device_revision = Some(revision);
|
||||
if let Some(Ok(report)) = &snapshot.status {
|
||||
state
|
||||
.open_devices
|
||||
.retain(|id| report.networks.iter().any(|n| n.network_id == *id));
|
||||
let open: Vec<_> = state.open_devices.iter().cloned().collect();
|
||||
// The embedded fallback can run the child callback immediately.
|
||||
drop(views);
|
||||
self.show_devices_windows(ctx, report, &open, refresh);
|
||||
}
|
||||
|
||||
// A secret the worker fetched for the clipboard: copy it here, on the
|
||||
// UI thread that owns the clipboard, exactly once.
|
||||
if let Some(secret) = self.agent.take_pending_copy() {
|
||||
ctx.copy_text(secret);
|
||||
}
|
||||
|
||||
// Keep ticking so fresh status is picked up.
|
||||
ctx.request_repaint_after(Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn show_vip_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
||||
fn show_vip_windows(
|
||||
ctx: &egui::Context,
|
||||
agent: &AgentClient,
|
||||
state: &mut UiState,
|
||||
snapshot: &crate::agent::Snapshot,
|
||||
) {
|
||||
let Some(Ok(report)) = &snapshot.status else {
|
||||
return;
|
||||
};
|
||||
let ids: Vec<_> = self.state.vip_windows.keys().cloned().collect();
|
||||
let ids: Vec<_> = state.vip_windows.keys().cloned().collect();
|
||||
for id in ids {
|
||||
let Some(network) = report.networks.iter().find(|n| n.network_id == id) else {
|
||||
self.state.vip_windows.remove(&id);
|
||||
state.vip_windows.remove(&id);
|
||||
continue;
|
||||
};
|
||||
let Some(state) = self.state.vip_windows.get_mut(&id) else {
|
||||
let Some(editor) = state.vip_windows.get_mut(&id) else {
|
||||
continue;
|
||||
};
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
@@ -98,13 +130,13 @@ impl App {
|
||||
egui::ViewportId::from_hash_of(("vip", &id)),
|
||||
builder,
|
||||
|vctx, _| {
|
||||
let close = crate::vip::show(vctx, &self.agent, state, network, snapshot);
|
||||
let close = crate::vip::show(vctx, agent, editor, network, snapshot);
|
||||
if close {
|
||||
return false;
|
||||
}
|
||||
if vctx.input(|i| i.viewport().close_requested()) {
|
||||
if state.dirty() {
|
||||
state.request_close();
|
||||
if editor.dirty() {
|
||||
editor.request_close();
|
||||
vctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
true
|
||||
} else {
|
||||
@@ -116,13 +148,18 @@ impl App {
|
||||
},
|
||||
);
|
||||
if !keep {
|
||||
self.state.vip_windows.remove(&id);
|
||||
state.vip_windows.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Renders the About window while it is open.
|
||||
fn show_about_window(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
||||
if !self.state.about_open {
|
||||
fn show_about_window(
|
||||
ctx: &egui::Context,
|
||||
agent: &AgentClient,
|
||||
state: &mut UiState,
|
||||
snapshot: &crate::agent::Snapshot,
|
||||
) {
|
||||
if !state.about_open {
|
||||
return;
|
||||
}
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
@@ -131,7 +168,7 @@ impl App {
|
||||
.with_icon(crate::icon::window())
|
||||
.with_inner_size([560.0, 520.0])
|
||||
.with_min_inner_size([380.0, 280.0]);
|
||||
let socket = self.agent.socket();
|
||||
let socket = agent.socket();
|
||||
let keep = ctx.show_viewport_immediate(
|
||||
egui::ViewportId::from_hash_of("about"),
|
||||
builder,
|
||||
@@ -141,50 +178,63 @@ impl App {
|
||||
},
|
||||
);
|
||||
if !keep {
|
||||
self.state.about_open = false;
|
||||
state.about_open = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders one separate window per open network-devices view.
|
||||
fn show_devices_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
|
||||
let Some(Ok(report)) = &snapshot.status else {
|
||||
return;
|
||||
};
|
||||
let open: Vec<String> = self.state.open_devices.iter().cloned().collect();
|
||||
fn show_devices_windows(
|
||||
&self,
|
||||
ctx: &egui::Context,
|
||||
report: &Arc<tsunagi::ipc::StatusReport>,
|
||||
open: &[String],
|
||||
refresh: bool,
|
||||
) {
|
||||
for id in open {
|
||||
let Some(network) = report.networks.iter().find(|n| n.network_id == id) else {
|
||||
// The network is gone (left/forgotten); close its window.
|
||||
self.state.open_devices.remove(&id);
|
||||
let Some(index) = report.networks.iter().position(|n| n.network_id == *id) else {
|
||||
continue;
|
||||
};
|
||||
let viewport_id = egui::ViewportId::from_hash_of(("devices", &id));
|
||||
let viewport = egui::ViewportId::from_hash_of(("devices", id));
|
||||
let preferred = egui::vec2(1240., 740.);
|
||||
let size = ctx
|
||||
.input(|i| i.viewport().monitor_size)
|
||||
.map_or(preferred, |monitor| {
|
||||
preferred.min((monitor - egui::vec2(48., 80.)).max(egui::vec2(560., 400.)))
|
||||
});
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
.with_title(devices::title(network))
|
||||
.with_title(devices::title(&report.networks[index]))
|
||||
.with_app_id(crate::icon::APP_ID)
|
||||
.with_icon(crate::icon::window())
|
||||
.with_inner_size([1000.0, 640.0])
|
||||
.with_min_inner_size([560.0, 400.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 forget_confirm = &mut self.state.forget_confirm;
|
||||
let keep = ctx.show_viewport_immediate(viewport_id, builder, |vctx, _class| {
|
||||
.with_inner_size(size)
|
||||
.with_min_inner_size([560., 400.]);
|
||||
let views = self.views.clone();
|
||||
let agent = self.agent.clone();
|
||||
let report = report.clone();
|
||||
ctx.show_viewport_deferred(viewport, builder, move |ctx, _| {
|
||||
let mut views = views.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Views { state, traffic } = &mut *views;
|
||||
let network = &report.networks[index];
|
||||
if ctx.input(|i| i.viewport().close_requested()) {
|
||||
state.open_devices.remove(&network.network_id);
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
return;
|
||||
}
|
||||
let old_unit = state.unit;
|
||||
devices::show(
|
||||
vctx,
|
||||
agent,
|
||||
unit,
|
||||
(confirm, forget_confirm),
|
||||
ctx,
|
||||
&agent,
|
||||
&mut state.unit,
|
||||
(&mut state.exit_confirm, &mut state.forget_confirm),
|
||||
network,
|
||||
&report.endpoint_id,
|
||||
traffic,
|
||||
);
|
||||
!vctx.input(|i| i.viewport().close_requested())
|
||||
if old_unit != state.unit {
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
});
|
||||
if !keep {
|
||||
self.state.open_devices.remove(&id);
|
||||
if refresh {
|
||||
ctx.request_repaint_of(viewport);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,8 +242,56 @@ impl App {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn device_frames_are_scheduled_independently_of_the_main_window() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_embed_viewports(false);
|
||||
let agent = AgentClient::spawn(runtime.handle(), ctx.clone());
|
||||
let app = App {
|
||||
agent,
|
||||
runtime: runtime.handle().clone(),
|
||||
monitor: None,
|
||||
views: Default::default(),
|
||||
sampled: 0,
|
||||
device_revision: None,
|
||||
};
|
||||
let report = Arc::new(tsunagi::ipc::StatusReport {
|
||||
networks: vec![tsunagi::ipc::NetworkReport {
|
||||
network_id: "test-id".into(),
|
||||
name: "lab".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
});
|
||||
let id = egui::ViewportId::from_hash_of(("devices", "test-id"));
|
||||
let open = ["test-id".to_string()].into_iter().collect();
|
||||
app.views.lock().unwrap().state.open_devices = open;
|
||||
let out = ctx.run(Default::default(), |ctx| {
|
||||
app.show_devices_windows(ctx, &report, &["test-id".to_string()], true);
|
||||
});
|
||||
assert!(out.viewport_output[&id].class == egui::ViewportClass::Deferred);
|
||||
let draw = out.viewport_output[&id].viewport_ui_cb.as_ref().unwrap();
|
||||
let mut input = egui::RawInput {
|
||||
viewport_id: id,
|
||||
..Default::default()
|
||||
};
|
||||
input
|
||||
.viewports
|
||||
.entry(id)
|
||||
.or_default()
|
||||
.events
|
||||
.push(egui::ViewportEvent::Close);
|
||||
let _ = ctx.run(input, |ctx| draw(ctx));
|
||||
assert!(app.views.lock().unwrap().state.open_devices.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_icons_have_an_embedded_font_in_the_app() {
|
||||
let fonts = app_fonts();
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! It is the same shape as `dist/linux/tsunagi.svg` (a disc, a ring, a dot).
|
||||
|
||||
use crate::watch::Health;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
/// Normal operation. The colour of the logo itself.
|
||||
const BLUE: [u8; 3] = [0x2f, 0x80, 0xd8];
|
||||
@@ -89,12 +90,17 @@ pub(crate) fn tray(health: Health) -> Option<tray_icon::Icon> {
|
||||
}
|
||||
|
||||
/// The icon of the application's windows.
|
||||
pub(crate) fn window() -> eframe::egui::IconData {
|
||||
eframe::egui::IconData {
|
||||
rgba: rgba(BLUE),
|
||||
width: SIZE,
|
||||
height: SIZE,
|
||||
}
|
||||
pub(crate) fn window() -> Arc<eframe::egui::IconData> {
|
||||
// egui compares viewport icons by Arc identity. Reuse both the pixels and
|
||||
// their allocation so animating a row does not update a native window icon.
|
||||
static ICON: LazyLock<Arc<eframe::egui::IconData>> = LazyLock::new(|| {
|
||||
Arc::new(eframe::egui::IconData {
|
||||
rgba: rgba(BLUE),
|
||||
width: SIZE,
|
||||
height: SIZE,
|
||||
})
|
||||
});
|
||||
Arc::clone(&ICON)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -122,6 +128,13 @@ mod tests {
|
||||
assert_eq!(body, [GREEN[0], GREEN[1], GREEN[2], 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repainting_a_devices_viewport_does_not_ask_the_os_to_replace_its_icon() {
|
||||
let viewport = || eframe::egui::ViewportBuilder::default().with_icon(window());
|
||||
let (commands, recreate) = viewport().patch(viewport());
|
||||
assert!(!recreate && commands.is_empty(), "{commands:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_state_has_its_own_colour() {
|
||||
let colours = [
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
use tsunagi_ui::about;
|
||||
mod agent;
|
||||
mod app;
|
||||
mod monitor;
|
||||
use tsunagi_ui::devices;
|
||||
mod icon;
|
||||
use tsunagi_ui::stats;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! The local IPC subscription lives exactly as long as its viewport.
|
||||
use eframe::egui;
|
||||
use std::{path::PathBuf, time::Duration};
|
||||
use tsunagi::ipc::TrafficStream;
|
||||
use tsunagi_ui::monitor::Window;
|
||||
|
||||
pub(super) struct Monitor {
|
||||
view: Window,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Monitor {
|
||||
pub fn new(runtime: &tokio::runtime::Handle, socket: PathBuf) -> Self {
|
||||
let view = Window::new(None);
|
||||
let feed = view.feed();
|
||||
let task = runtime.spawn(async move {
|
||||
let capture = async {
|
||||
let mut stream = TrafficStream::open(&socket).await?;
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
if !feed.sample(stream.snapshot().await?) {
|
||||
return Ok::<_, tsunagi::Error>(());
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Err(e) = capture.await {
|
||||
feed.error(format!("Capture stopped · {e}"));
|
||||
}
|
||||
});
|
||||
Self { view, task }
|
||||
}
|
||||
pub fn show(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) -> bool {
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
.with_title("tsunagi · Traffic monitor")
|
||||
.with_app_id(crate::icon::APP_ID)
|
||||
.with_icon(crate::icon::window())
|
||||
.with_inner_size([920., 580.])
|
||||
.with_min_inner_size([340., 320.]);
|
||||
ctx.show_viewport_immediate(
|
||||
egui::ViewportId::from_hash_of("traffic-monitor"),
|
||||
builder,
|
||||
|ctx, _| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
self.view.show(
|
||||
ui,
|
||||
snapshot.status.as_ref().and_then(|r| r.as_deref().ok()),
|
||||
snapshot.generation,
|
||||
);
|
||||
});
|
||||
!ctx.input(|i| i.viewport().close_requested())
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Drop for Monitor {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,12 @@ pub(crate) fn draw(
|
||||
if tsunagi_ui::widgets::icon_button(ui, icon::INFO, "About Tsunagi").clicked() {
|
||||
state.about_open = true;
|
||||
}
|
||||
if matches!(&snapshot.status, Some(Ok(_)))
|
||||
&& tsunagi_ui::widgets::icon_button(ui, icon::PULSE, "Traffic monitor")
|
||||
.clicked()
|
||||
{
|
||||
state.monitor_open = true;
|
||||
}
|
||||
if snapshot.busy {
|
||||
ui.add(egui::Spinner::new());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.6"
|
||||
version = "1.0.10"
|
||||
description = "Shared egui widgets for the tray and Android clients."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -9,6 +9,9 @@ repository.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
postcard.workspace = true
|
||||
rusqlite = { version = "0.40", features = ["bundled", "functions"] }
|
||||
tempfile.workspace = true
|
||||
egui = "0.31"
|
||||
egui-phosphor = "0.9"
|
||||
zeroize = "1.9"
|
||||
|
||||
@@ -13,7 +13,9 @@ mod speed;
|
||||
mod speed_tests;
|
||||
mod status;
|
||||
pub use crate::exit::name_of;
|
||||
pub use exit_picker::choose_exit;
|
||||
pub use exit_picker::{
|
||||
choose_exit, choose_exit_from_networks, choose_exit_with_tests, exit_action_colors,
|
||||
};
|
||||
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
@@ -152,6 +154,62 @@ fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
|
||||
}
|
||||
}
|
||||
|
||||
// Reserve the version and the offline action before eliding a long hostname.
|
||||
fn short_name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
|
||||
ui.spacing_mut().item_spacing.x = 4.;
|
||||
let (mark, r) = ui.allocate_exact_size(egui::Vec2::splat(16.), egui::Sense::hover());
|
||||
device.channel().paint(ui, mark);
|
||||
widgets::hint(r, device.channel_hint());
|
||||
let font = egui::TextStyle::Small.resolve(ui.style());
|
||||
let version = device.version_label();
|
||||
let measure = |s: &str, font: egui::FontId| {
|
||||
ui.painter()
|
||||
.layout_no_wrap(s.into(), font, ui.visuals().text_color())
|
||||
.size()
|
||||
.x
|
||||
};
|
||||
let forget = if !device.online && !device.in_use && device.record_version.is_some() {
|
||||
measure("Forget", egui::TextStyle::Button.resolve(ui.style()))
|
||||
+ 2. * ui.spacing().button_padding.x
|
||||
+ 6.
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
let width = (ui.available_width() - measure(&version, font) - forget - 8.).max(1.);
|
||||
let name = device.name();
|
||||
let (rect, response) = ui.allocate_exact_size(
|
||||
egui::vec2(width, ui.spacing().interact_size.y),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
let hint = if let Some((taken, holder)) = &device.name_taken {
|
||||
format!("Name `{taken}` belongs to {holder}. Use this device's address.")
|
||||
} else {
|
||||
format!("{name}\n{}\nClick to copy the device address", device.id)
|
||||
};
|
||||
let ink = if device.name_taken.is_some() {
|
||||
AMBER
|
||||
} else {
|
||||
ui.visuals().text_color()
|
||||
};
|
||||
widgets::single_line(
|
||||
ui.painter(),
|
||||
rect,
|
||||
egui::Align::Min,
|
||||
&name,
|
||||
egui::TextStyle::Body.resolve(ui.style()),
|
||||
ink,
|
||||
);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &name));
|
||||
if widgets::hint(response, &hint).clicked() {
|
||||
ui.ctx()
|
||||
.copy_text(device.copy.as_deref().unwrap_or(device.id).to_owned());
|
||||
}
|
||||
ui.small(version).on_hover_text(format!(
|
||||
"Tsunagi {}",
|
||||
device.agent_version.unwrap_or("version unknown")
|
||||
));
|
||||
}
|
||||
|
||||
/// Draws the window body into its viewport.
|
||||
pub fn show(
|
||||
ctx: &egui::Context,
|
||||
@@ -188,7 +246,7 @@ pub fn show(
|
||||
"devices ({online} online / {} known)",
|
||||
devices.len()
|
||||
));
|
||||
speed.toolbar(ui);
|
||||
speed.batch_button(ui, false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -232,9 +290,21 @@ pub fn show(
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
let table = desktop_columns(ui, unit, network, &devices, traffic);
|
||||
let required = table.widths.iter().sum::<f32>() + crate::table::GAP * 8.;
|
||||
if required <= ui.available_width() {
|
||||
// Remembered desktop widths only grow. While this window is compact,
|
||||
// an animation frame need not format and measure all peers a second time.
|
||||
let available = ui.available_width();
|
||||
let id = egui::Id::new(("devices column widths", &network.network_id));
|
||||
let em = egui::TextStyle::Body.resolve(ui.style()).size;
|
||||
let could_fit = ui
|
||||
.data(|d| d.get_temp::<[f32; 9]>(id))
|
||||
.is_none_or(|w| fit_desktop_widths(w, available, em).is_some());
|
||||
let table =
|
||||
could_fit.then(|| desktop_columns(ui, unit, network, &devices, traffic));
|
||||
if let Some(mut table) = table
|
||||
&& let Some(widths) = fit_desktop_widths(table.widths, available, em)
|
||||
{
|
||||
table.short_identity = widths[0] < table.widths[0];
|
||||
table.widths = widths;
|
||||
device_table(
|
||||
ui,
|
||||
network,
|
||||
@@ -327,59 +397,104 @@ pub fn confirm_exit(
|
||||
}) 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("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((ctx.screen_rect().width() - 40.0).clamp(160.0, 380.0));
|
||||
let phone = ctx.os() == egui::os::OperatingSystem::Android;
|
||||
ui.label(if pending.stop {
|
||||
format!("Stop using {}?", pending.name)
|
||||
} else if phone {
|
||||
format!(
|
||||
"Route this phone’s IPv4 internet traffic through {}?",
|
||||
pending.name
|
||||
)
|
||||
let phone = ctx.os() == egui::os::OperatingSystem::Android;
|
||||
let id = egui::Id::new("confirm exit node");
|
||||
let mut modal = egui::Modal::new(id);
|
||||
if phone {
|
||||
modal = modal
|
||||
.area(egui::Modal::default_area(id).anchor(egui::Align2::CENTER_BOTTOM, [0., -10.]))
|
||||
.frame(
|
||||
egui::Frame::popup(&ctx.style())
|
||||
.fill(if ctx.style().visuals.dark_mode {
|
||||
egui::Color32::from_rgb(37, 44, 49)
|
||||
} else {
|
||||
egui::Color32::WHITE
|
||||
})
|
||||
.inner_margin(16)
|
||||
.corner_radius(14),
|
||||
);
|
||||
}
|
||||
let result = modal.show(ctx, |ui| {
|
||||
let width = (ctx.screen_rect().width() - 56.).clamp(140., 420.);
|
||||
if phone {
|
||||
ui.set_width(width);
|
||||
} else {
|
||||
ui.set_max_width(width);
|
||||
}
|
||||
let title = if pending.stop {
|
||||
"Disconnect exit node?"
|
||||
} else {
|
||||
"Use exit node?"
|
||||
};
|
||||
ui.label(
|
||||
egui::RichText::new(title)
|
||||
.size(if phone { 22. } else { 17. })
|
||||
.strong(),
|
||||
);
|
||||
ui.add_space(4.);
|
||||
let message = if pending.stop {
|
||||
format!(
|
||||
"Stop using {} and return to the local internet connection?",
|
||||
pending.name
|
||||
)
|
||||
} else if phone {
|
||||
format!(
|
||||
"Route this phone’s IPv4 internet traffic through {}?",
|
||||
pending.name
|
||||
)
|
||||
} else {
|
||||
format!("Use {} as exit node?", pending.name)
|
||||
};
|
||||
ui.label(
|
||||
egui::RichText::new(message)
|
||||
.size(if phone { 17. } else { 14. })
|
||||
.color(ui.visuals().strong_text_color()),
|
||||
);
|
||||
ui.add_space(if phone { 12. } else { 6. });
|
||||
ui.horizontal(|ui| {
|
||||
let action = match (phone, pending.stop) {
|
||||
(true, true) => "Disconnect",
|
||||
(true, false) => "Use exit node",
|
||||
(false, true) => "Stop",
|
||||
(false, false) => "Use",
|
||||
};
|
||||
let (bg, fg) = exit_action_colors(ui.visuals().dark_mode);
|
||||
let font = if phone { 17. } else { 14. };
|
||||
let size = if phone {
|
||||
egui::vec2((width - ui.spacing().item_spacing.x) / 2., 48.)
|
||||
} else {
|
||||
format!("Use {} as exit node?", pending.name)
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if phone {
|
||||
ui.spacing_mut().interact_size = egui::vec2(104., 48.);
|
||||
ui.spacing_mut().button_padding.x = 18.;
|
||||
}
|
||||
if ui
|
||||
.button(if pending.stop { "Stop" } else { "Use" })
|
||||
.clicked()
|
||||
{
|
||||
accepted = true;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
cancelled = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.spacing().interact_size
|
||||
};
|
||||
let cancel = ui
|
||||
.add(
|
||||
egui::Button::new(
|
||||
egui::RichText::new("Cancel")
|
||||
.size(font)
|
||||
.color(ui.visuals().strong_text_color()),
|
||||
)
|
||||
.min_size(size),
|
||||
)
|
||||
.clicked();
|
||||
let accept = ui
|
||||
.add_enabled(
|
||||
!agent.busy(),
|
||||
egui::Button::new(egui::RichText::new(action).size(font).color(fg).strong())
|
||||
.fill(bg)
|
||||
.min_size(size),
|
||||
)
|
||||
.clicked();
|
||||
(accept, cancel)
|
||||
})
|
||||
.inner
|
||||
});
|
||||
let (accepted, cancelled) = result.inner;
|
||||
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)) {
|
||||
if accepted || cancelled || result.should_close() {
|
||||
*confirm = None;
|
||||
}
|
||||
}
|
||||
@@ -464,24 +579,34 @@ fn known_ids<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<&'a str> {
|
||||
.as_ref()
|
||||
.map(|o| o.peers.as_slice())
|
||||
.unwrap_or(&[]);
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
let mut seen = std::collections::HashSet::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()))
|
||||
.chain(network.exit.via.as_deref());
|
||||
for id in candidates {
|
||||
if id != own_id && !ids.contains(&id) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
ids
|
||||
candidates
|
||||
.filter(|id| *id != own_id && seen.insert(*id))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many other devices can be reached now, by any path.
|
||||
pub fn online_count(network: &NetworkReport, own_id: &str) -> usize {
|
||||
devices(network, own_id).iter().filter(|d| d.online).count()
|
||||
network
|
||||
.peers
|
||||
.iter()
|
||||
.map(|p| p.endpoint_id.as_str())
|
||||
.chain(
|
||||
network
|
||||
.members
|
||||
.iter()
|
||||
.filter(|m| m.online)
|
||||
.map(|m| m.endpoint_id.as_str()),
|
||||
)
|
||||
.filter(|id| *id != own_id)
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
.len()
|
||||
}
|
||||
|
||||
/// How many other devices this network knows of, connected or not.
|
||||
@@ -505,30 +630,44 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
|
||||
.iter()
|
||||
.filter_map(|p| p.hostname.as_deref().map(|h| (p.endpoint_id.as_str(), h))),
|
||||
);
|
||||
let overlay_peers = network
|
||||
let overlay_peers: HashMap<_, _> = network
|
||||
.overlay
|
||||
.as_ref()
|
||||
.map(|o| o.peers.as_slice())
|
||||
.unwrap_or(&[]);
|
||||
.iter()
|
||||
.flat_map(|o| &o.peers)
|
||||
.map(|p| (p.endpoint_id.as_str(), p))
|
||||
.collect();
|
||||
let members: HashMap<_, _> = network
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| (m.endpoint_id.as_str(), m))
|
||||
.collect();
|
||||
let peers: HashMap<_, _> = network
|
||||
.peers
|
||||
.iter()
|
||||
.map(|p| (p.endpoint_id.as_str(), p))
|
||||
.collect();
|
||||
let peer_name = |id: &str| {
|
||||
hostnames
|
||||
.get(id)
|
||||
.map_or_else(|| format::short(id), |name| (*name).to_owned())
|
||||
};
|
||||
|
||||
let ids = known_ids(network, own_id);
|
||||
|
||||
let mut devices: Vec<Device> = ids
|
||||
let mut devices: Vec<Device> = known_ids(network, own_id)
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
let overlay = overlay_peers.iter().find(|p| p.endpoint_id == id);
|
||||
let member = network.members.iter().find(|m| m.endpoint_id == id);
|
||||
let peer = network.peers.iter().find(|p| p.endpoint_id == id);
|
||||
let overlay = overlay_peers.get(id).copied();
|
||||
let member = members.get(id).copied();
|
||||
let peer = peers.get(id).copied();
|
||||
let online = member.is_some_and(|m| m.online) || peer.is_some();
|
||||
let path = peer.map(|p| &p.path).or_else(|| member.map(|m| &m.path));
|
||||
let via_name = match path {
|
||||
Some(DataPathReport::Relayed { via, .. }) => Some(exit::name_of(network, via)),
|
||||
Some(DataPathReport::Relayed { via, .. }) => Some(peer_name(via)),
|
||||
_ => None,
|
||||
};
|
||||
let name_taken = member.and_then(|m| {
|
||||
m.hostname_conflict
|
||||
.as_ref()
|
||||
.map(|c| (c.name.as_str(), exit::name_of(network, &c.holder)))
|
||||
.map(|c| (c.name.as_str(), peer_name(&c.holder)))
|
||||
});
|
||||
let hostname = hostnames.get(id).copied();
|
||||
Device {
|
||||
@@ -626,25 +765,40 @@ fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 9] {
|
||||
})
|
||||
}
|
||||
|
||||
const MIN_PLOT_WIDTH: f32 = 100.;
|
||||
|
||||
fn stretch_columns(mut widths: [f32; 9], available: f32) -> [f32; 9] {
|
||||
let gaps = crate::table::GAP * (widths.len() - 1) as f32;
|
||||
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(100.0, 180.0);
|
||||
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(MIN_PLOT_WIDTH, 180.0);
|
||||
widths
|
||||
}
|
||||
|
||||
// Keep the numeric columns and controls intact. A long hostname or relay name
|
||||
// alone must not turn a normal desktop window into the touch roster.
|
||||
fn fit_desktop_widths(widths: [f32; 9], available: f32, em: f32) -> Option<[f32; 9]> {
|
||||
let mut widths = stretch_columns(widths, available);
|
||||
let mut excess = (widths.iter().sum::<f32>() + crate::table::GAP * 8. - available).max(0.);
|
||||
for (column, floor) in [(8, 4. * em), (0, 11. * em), (5, 4. * em)] {
|
||||
let take = (widths[column] - floor).max(0.).min(excess);
|
||||
widths[column] -= take;
|
||||
excess -= take;
|
||||
}
|
||||
(excess <= 0.1).then_some(widths)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
fn exit_action(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
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 {
|
||||
@@ -657,16 +811,21 @@ fn exit_cell(
|
||||
} else {
|
||||
(ui.visuals().text_color(), "Use this exit node")
|
||||
};
|
||||
ui.painter_at(rect).text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon::SIGN_OUT,
|
||||
egui::FontId::proportional(16.),
|
||||
color,
|
||||
);
|
||||
let response = ui
|
||||
.add(
|
||||
egui::Label::new(
|
||||
egui::RichText::new(egui_phosphor::regular::SIGN_OUT)
|
||||
.size(16.0)
|
||||
.color(color),
|
||||
)
|
||||
.sense(egui::Sense::click()),
|
||||
.interact(
|
||||
rect,
|
||||
ui.id().with(("exit action", network_id, device.id)),
|
||||
egui::Sense::click(),
|
||||
)
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, hint));
|
||||
if widgets::hint(response, hint).clicked() {
|
||||
*confirm = Some(ExitConfirm {
|
||||
network_id: network_id.to_string(),
|
||||
@@ -682,6 +841,7 @@ struct DesktopColumns {
|
||||
widths: [f32; 9],
|
||||
total: String,
|
||||
rate: String,
|
||||
short_identity: bool,
|
||||
}
|
||||
|
||||
fn desktop_columns(
|
||||
@@ -752,6 +912,7 @@ fn desktop_columns(
|
||||
widths,
|
||||
total,
|
||||
rate,
|
||||
short_identity: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -816,13 +977,21 @@ fn device_table(
|
||||
index % 2 == 0,
|
||||
|column, ui| match column {
|
||||
0 => {
|
||||
name_cell(ui, device);
|
||||
if table.short_identity {
|
||||
short_name_cell(ui, device);
|
||||
} else {
|
||||
name_cell(ui, device);
|
||||
}
|
||||
forget_button(ui, device, network, forget_confirm);
|
||||
}
|
||||
1 => {
|
||||
let rect = ui.max_rect();
|
||||
let speed_rect = rect.split_left_right_at_x(rect.right() - speed::WIDTH).1;
|
||||
exit_cell(ui, device, network_id, confirm);
|
||||
let exit_rect = egui::Rect::from_min_max(
|
||||
rect.min,
|
||||
egui::pos2(speed_rect.left(), rect.bottom()),
|
||||
);
|
||||
exit_action(ui, exit_rect, device, network_id, confirm);
|
||||
speed.cell(ui, speed_rect, device);
|
||||
}
|
||||
2 => tunnel_cell(ui, device),
|
||||
@@ -924,7 +1093,11 @@ fn data_path_cell(ui: &mut egui::Ui, device: &Device<'_>) {
|
||||
if !device.online {
|
||||
text = text.weak();
|
||||
}
|
||||
let response = ui.add(egui::Label::new(text).extend().sense(egui::Sense::click()));
|
||||
let response = ui.add(
|
||||
egui::Label::new(text)
|
||||
.truncate()
|
||||
.sense(egui::Sense::click()),
|
||||
);
|
||||
widgets::hint(
|
||||
response,
|
||||
match device.path {
|
||||
@@ -1555,6 +1728,45 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_frames_skip_the_hidden_desktop_layout_until_the_window_grows() {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
let id = egui::Id::new(("devices column widths", "lab"));
|
||||
let mut net = NetworkReport {
|
||||
network_id: "lab".into(),
|
||||
members: vec![member("peer", true, DataPathReport::None)],
|
||||
..Default::default()
|
||||
};
|
||||
let draw = |width, net: &NetworkReport| {
|
||||
let _ = ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 600.),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
show(
|
||||
ctx,
|
||||
&ReadOnly,
|
||||
&mut Unit::Bytes,
|
||||
(&mut None, &mut None),
|
||||
net,
|
||||
"self",
|
||||
&Traffic::default(),
|
||||
)
|
||||
},
|
||||
);
|
||||
ctx.data(|d| d.get_temp::<[f32; 9]>(id)).unwrap()
|
||||
};
|
||||
let first = draw(660., &net);
|
||||
net.members[0].hostname = Some("a-much-longer-peer-name-for-the-wide-table".into());
|
||||
assert_eq!(draw(660., &net), first);
|
||||
assert!(draw(2300., &net)[0] > first[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_relay_name_gets_its_full_column_width() {
|
||||
let mut relay = member("near", true, DataPathReport::None);
|
||||
|
||||
@@ -37,45 +37,82 @@ impl Column {
|
||||
}
|
||||
}
|
||||
|
||||
fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32)> {
|
||||
fn columns(
|
||||
ui: &Ui,
|
||||
width: f32,
|
||||
landscape: bool,
|
||||
unit: Unit,
|
||||
members: &[Device<'_>],
|
||||
) -> Vec<(Column, f32)> {
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let measure = |s: &str| {
|
||||
let text_width = |s: &str| {
|
||||
ui.painter()
|
||||
.layout_no_wrap(s.into(), font.clone(), Color32::WHITE)
|
||||
.size()
|
||||
.x
|
||||
+ 10.
|
||||
};
|
||||
let mut cols = vec![
|
||||
(Column::Device, 0.),
|
||||
(
|
||||
Column::Speed,
|
||||
if landscape {
|
||||
speed::WIDTH.min(width * 0.28)
|
||||
} else {
|
||||
speed::PORTRAIT_WIDTH.min(width * 0.18)
|
||||
},
|
||||
),
|
||||
];
|
||||
if landscape && width >= 510. {
|
||||
cols.push((Column::State, measure("Control only").min(width * 0.16)));
|
||||
let measure = |s: &str| text_width(s) + 10.;
|
||||
let disclosure = text_width(icon::CARET_RIGHT) + 3.;
|
||||
let name = 20. + text_width("device") + 3.;
|
||||
let available = width - name - disclosure;
|
||||
let small_speed = speed::PORTRAIT_WIDTH.min(width * 0.18);
|
||||
let address = measure("255.255.255.255").min(width * if landscape { 0.27 } else { 0.35 });
|
||||
let rtt = measure("Data RTT")
|
||||
.max(measure("9999 ms"))
|
||||
.min(width * if landscape { 0.15 } else { 0.22 });
|
||||
let traffic = (landscape && width >= 420.)
|
||||
.then(|| {
|
||||
// Account for both rounded values (up to 1024.0) and the unit
|
||||
// suffixes in the actual body font, independently of the live bytes.
|
||||
let digit = ui.fonts(|fonts| {
|
||||
('0'..='9')
|
||||
.max_by(|a, b| {
|
||||
fonts
|
||||
.glyph_width(&font, *a)
|
||||
.total_cmp(&fonts.glyph_width(&font, *b))
|
||||
})
|
||||
.unwrap_or('0')
|
||||
});
|
||||
let number = format!("{digit}{digit}{digit}{digit}.{digit}");
|
||||
let bytes_width = format::BYTE_UNITS.iter().fold(0.0_f32, |w, suffix| {
|
||||
w.max(measure(&format!("{number} {suffix} / {number} {suffix}")))
|
||||
});
|
||||
let floor = bytes_width.max(measure(Column::Traffic.title(unit)));
|
||||
match unit {
|
||||
Unit::Bytes => floor,
|
||||
Unit::Packets => members
|
||||
.iter()
|
||||
.filter(|m| m.online)
|
||||
.filter_map(|m| m.overlay)
|
||||
.fold(floor, |w, p| {
|
||||
w.max(measure(&traffic_pair(p.tx_packets, p.rx_packets, unit)))
|
||||
}),
|
||||
}
|
||||
})
|
||||
// An unusually long packet count can use the end of the device name,
|
||||
// but always leave room for its status icon and disclosure.
|
||||
.filter(|w| w + small_speed + 20. + text_width("…") + 3. + disclosure <= width);
|
||||
let mut spare = available - traffic.unwrap_or_default();
|
||||
let state = (landscape && width >= 510.).then(|| measure("Control only"));
|
||||
let speed = if landscape && speed::WIDTH + address + rtt + state.unwrap_or_default() <= spare {
|
||||
speed::WIDTH
|
||||
} else {
|
||||
small_speed
|
||||
};
|
||||
spare -= speed;
|
||||
let mut cols = vec![(Column::Device, 0.), (Column::Speed, speed)];
|
||||
for (column, want) in [(Column::Address, address), (Column::Rtt, rtt)] {
|
||||
if spare >= want {
|
||||
cols.push((column, want));
|
||||
spare -= want;
|
||||
}
|
||||
}
|
||||
cols.push((
|
||||
Column::Address,
|
||||
measure("255.255.255.255").min(width * if landscape { 0.27 } else { 0.35 }),
|
||||
));
|
||||
cols.push((
|
||||
Column::Rtt,
|
||||
measure("9999 ms").min(width * if landscape { 0.15 } else { 0.22 }),
|
||||
));
|
||||
if landscape && width >= 420. {
|
||||
cols.push((
|
||||
Column::Traffic,
|
||||
measure(Column::Traffic.title(unit))
|
||||
.max(measure("999 MB / 999 MB"))
|
||||
.min(width * 0.29),
|
||||
));
|
||||
let mut spare = width - cols.iter().map(|c| c.1).sum::<f32>() - 122.;
|
||||
if let Some(w) = state.filter(|w| *w <= spare) {
|
||||
cols.insert(2, (Column::State, w));
|
||||
spare -= w;
|
||||
}
|
||||
if let Some(w) = traffic {
|
||||
cols.push((Column::Traffic, w));
|
||||
for (column, desire) in [
|
||||
(Column::Version, measure("v1.0.4-rc.1")),
|
||||
(Column::Path, measure("tcp-tls direct")),
|
||||
@@ -90,7 +127,7 @@ fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32
|
||||
}
|
||||
let other: f32 = cols.iter().map(|c| c.1).sum();
|
||||
// Reserve the disclosure arrow at the end, including on small split screens.
|
||||
cols[0].1 = (width - other - 16.).max(0.);
|
||||
cols[0].1 = (width - other - disclosure).max(0.);
|
||||
cols
|
||||
}
|
||||
|
||||
@@ -117,7 +154,7 @@ pub(super) fn roster(
|
||||
let id = egui::Id::new(("expanded device", &network.network_id));
|
||||
let mut selected = ui.data(|d| d.get_temp::<String>(id));
|
||||
let width = ui.available_width();
|
||||
let columns = columns(ui, width, widgets::landscape(ui.ctx()), unit);
|
||||
let columns = columns(ui, width, widgets::landscape(ui.ctx()), unit, members);
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let size = vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 9.);
|
||||
ui.spacing_mut().item_spacing.y = 1.;
|
||||
@@ -206,14 +243,10 @@ pub(super) fn roster(
|
||||
);
|
||||
rect.min.x += 20.;
|
||||
if member.in_use || member.exit_node {
|
||||
ui.painter_at(rect).text(
|
||||
rect.right_center(),
|
||||
Align2::RIGHT_CENTER,
|
||||
icon::SIGN_OUT,
|
||||
font.clone(),
|
||||
if member.in_use { exit::GOOD } else { normal },
|
||||
);
|
||||
rect.max.x -= font.size + 3.;
|
||||
let edge = (rect.right() - (font.size + 10.)).max(rect.left());
|
||||
let button = Rect::from_min_max(pos2(edge, rect.top()), rect.max);
|
||||
super::exit_action(ui, button, member, &network.network_id, exit);
|
||||
rect.max.x = edge;
|
||||
}
|
||||
member.name()
|
||||
}
|
||||
|
||||
@@ -1,143 +1,205 @@
|
||||
//! The remote-exit chooser. Each radio row is one touch target, including its telemetry.
|
||||
use super::{ExitConfirm, devices, rtt_text};
|
||||
use crate::exit;
|
||||
use egui::{Align2, FontId, Pos2, Rect, Sense, Ui};
|
||||
//! One touch target per exit, grouped by the network that will carry the traffic.
|
||||
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;
|
||||
use tsunagi::ipc::{DataPathReport, NetworkReport};
|
||||
|
||||
/// Draw the selectable exits for one network and return a choice for confirmation.
|
||||
/// The per-network view uses the same chooser as the complete Android list.
|
||||
pub fn choose_exit(ui: &mut Ui, network: &NetworkReport, own: &str) -> Option<ExitConfirm> {
|
||||
ui.heading(&network.name);
|
||||
if let Some(rules) = &network.exit.client_rules
|
||||
&& !rules.ok
|
||||
{
|
||||
ui.colored_label(exit::LOUD, &rules.detail);
|
||||
}
|
||||
let width = ui.available_width();
|
||||
let (header, _) = ui.allocate_exact_size(egui::vec2(width, 22.), Sense::hover());
|
||||
let columns = Columns::new(header);
|
||||
let muted = ui.visuals().weak_text_color();
|
||||
for (x, label) in [
|
||||
(columns.name, "Exit node"),
|
||||
(columns.rtt, "Data RTT"),
|
||||
(columns.path, "Path"),
|
||||
] {
|
||||
ui.painter().text(
|
||||
egui::pos2(x, header.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
label,
|
||||
egui::TextStyle::Small.resolve(ui.style()),
|
||||
muted,
|
||||
);
|
||||
}
|
||||
let current = network.exit.via.as_deref();
|
||||
let mut choice = None;
|
||||
choose_exit_from_networks(ui, std::slice::from_ref(network), own)
|
||||
}
|
||||
|
||||
/// Local internet is one device-wide choice. Each peer selection keeps its network ID.
|
||||
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()
|
||||
.find_map(|n| n.exit.via.as_deref().map(|via| (n, via)));
|
||||
let local = Row {
|
||||
peer: None,
|
||||
name: "No exit node",
|
||||
address: None,
|
||||
rtt: None,
|
||||
path: "Local",
|
||||
transport: None,
|
||||
caption: "Use this phone’s connection",
|
||||
latency: None,
|
||||
path: None,
|
||||
selected: current.is_none(),
|
||||
glyph: icon::GLOBE,
|
||||
};
|
||||
if local.draw(ui, &network.network_id)
|
||||
&& let Some(id) = current
|
||||
let mut choice = None;
|
||||
if local.draw(ui, "local internet", None)
|
||||
&& let Some((network, id)) = current
|
||||
{
|
||||
choice = Some(ExitConfirm::stop_from_tile(network, id));
|
||||
}
|
||||
let mut candidates = devices(network, own);
|
||||
candidates.retain(|d| d.exit_node || d.in_use);
|
||||
candidates.sort_by_key(|d| !d.in_use);
|
||||
if let Some(id) = current
|
||||
&& !candidates.iter().any(|d| d.id == id)
|
||||
{
|
||||
Row {
|
||||
peer: Some(id),
|
||||
name: &exit::name_of(network, id),
|
||||
address: None,
|
||||
rtt: None,
|
||||
path: "Offline",
|
||||
transport: None,
|
||||
selected: true,
|
||||
}
|
||||
.draw(ui, &network.network_id);
|
||||
let mut groups: Vec<_> = networks
|
||||
.iter()
|
||||
.filter(|n| {
|
||||
n.exit.via.is_some()
|
||||
|| n.active && n.peers.iter().any(|p| p.exit_node && p.endpoint_id != own)
|
||||
})
|
||||
.collect();
|
||||
groups.sort_by_key(|n| (n.exit.via.is_none(), n.name.to_lowercase(), &n.network_id));
|
||||
if groups.is_empty() {
|
||||
ui.add_space(12.);
|
||||
ui.label(
|
||||
egui::RichText::new(if networks.is_empty() {
|
||||
"Join a network to choose an exit node."
|
||||
} else if networks.iter().all(|n| !n.active) {
|
||||
"Start a network to choose an exit node."
|
||||
} else {
|
||||
"No connected peers offer an exit node."
|
||||
})
|
||||
.size(16.),
|
||||
);
|
||||
}
|
||||
for candidate in &candidates {
|
||||
let name = candidate.name();
|
||||
let relayed;
|
||||
let (path, transport) = if !candidate.online {
|
||||
("Offline", None)
|
||||
} else if candidate.in_use && !network.exit.via_online || candidate.data_error.is_some() {
|
||||
("Unavailable", None)
|
||||
for network in groups {
|
||||
let ambiguous = networks
|
||||
.iter()
|
||||
.any(|n| n.name == network.name && n.network_id != network.network_id && n.active);
|
||||
let title = if ambiguous {
|
||||
format!("{} · {}", network.name, format::short(&network.network_id))
|
||||
} else {
|
||||
match candidate.path {
|
||||
Some(DataPathReport::Direct { transport }) => ("Direct", Some(transport.as_str())),
|
||||
Some(DataPathReport::Relayed { hops, .. }) => {
|
||||
relayed = format!("{hops} hops");
|
||||
("Relayed", Some(relayed.as_str()))
|
||||
network.name.clone()
|
||||
};
|
||||
ui.add_space(10.);
|
||||
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);
|
||||
}
|
||||
_ => ("Connecting", None),
|
||||
}
|
||||
};
|
||||
let row = Row {
|
||||
peer: Some(candidate.id),
|
||||
name: &name,
|
||||
address: candidate.address.as_deref(),
|
||||
rtt: candidate.data_rtt_ms,
|
||||
path,
|
||||
transport,
|
||||
selected: candidate.in_use,
|
||||
};
|
||||
if row.draw(ui, &network.network_id) && !candidate.in_use {
|
||||
choice = Some(ExitConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: candidate.id.into(),
|
||||
name,
|
||||
stop: false,
|
||||
main: true,
|
||||
});
|
||||
});
|
||||
if let Some(rules) = &network.exit.client_rules
|
||||
&& !rules.ok
|
||||
{
|
||||
ui.colored_label(exit::LOUD, &rules.detail);
|
||||
}
|
||||
let mut candidates = devices(network, own);
|
||||
candidates.retain(|d| d.exit_node || d.in_use);
|
||||
candidates.sort_by_key(|d| !d.in_use);
|
||||
if let Some(id) = network.exit.via.as_deref()
|
||||
&& !candidates.iter().any(|d| d.id == id)
|
||||
{
|
||||
Row {
|
||||
name: &exit::name_of(network, id),
|
||||
caption: "",
|
||||
latency: None,
|
||||
path: Some("Offline"),
|
||||
selected: true,
|
||||
glyph: icon::SIGN_OUT,
|
||||
}
|
||||
.draw(ui, (&network.network_id, id), None);
|
||||
}
|
||||
for d in candidates {
|
||||
let name = d.name();
|
||||
let path = if !d.online {
|
||||
"Offline".into()
|
||||
} else if d.in_use && !network.exit.via_online || d.data_error.is_some() {
|
||||
"Unavailable".into()
|
||||
} else {
|
||||
match d.path {
|
||||
Some(DataPathReport::Direct { transport }) => format!("Direct · {transport}"),
|
||||
Some(DataPathReport::Relayed { hops, .. }) => {
|
||||
format!("Relay · {hops} {}", if *hops == 1 { "hop" } else { "hops" })
|
||||
}
|
||||
_ => "Connecting".into(),
|
||||
}
|
||||
};
|
||||
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: 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), address) && !d.in_use {
|
||||
choice = Some(ExitConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: d.id.into(),
|
||||
name: format!("{name} · {title}"),
|
||||
stop: false,
|
||||
main: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if !candidates.iter().any(|d| d.exit_node) {
|
||||
ui.weak("No connected peers offer an exit node.");
|
||||
}
|
||||
choice
|
||||
}
|
||||
|
||||
struct Columns {
|
||||
name: f32,
|
||||
rtt: f32,
|
||||
path: f32,
|
||||
fn bold(size: f32) -> FontId {
|
||||
FontId::new(size, FontFamily::Name("Bold".into()))
|
||||
}
|
||||
impl Columns {
|
||||
fn new(rect: Rect) -> Self {
|
||||
let path = rect.right() - (rect.width() * 0.24).clamp(66., 110.);
|
||||
Self {
|
||||
name: rect.left() + 31.,
|
||||
rtt: path - 61.,
|
||||
path,
|
||||
}
|
||||
|
||||
/// Foreground and background for primary actions in the phone's light and dark themes.
|
||||
pub fn exit_action_colors(dark: bool) -> (Color32, Color32) {
|
||||
if dark {
|
||||
(
|
||||
Color32::from_rgb(141, 216, 244),
|
||||
Color32::from_rgb(9, 37, 50),
|
||||
)
|
||||
} else {
|
||||
(Color32::from_rgb(15, 88, 117), Color32::WHITE)
|
||||
}
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
peer: Option<&'a str>,
|
||||
name: &'a str,
|
||||
address: Option<&'a str>,
|
||||
rtt: Option<u64>,
|
||||
path: &'a str,
|
||||
transport: Option<&'a str>,
|
||||
caption: &'a str,
|
||||
latency: Option<&'a str>,
|
||||
path: Option<&'a str>,
|
||||
selected: bool,
|
||||
glyph: &'static str,
|
||||
}
|
||||
impl Row<'_> {
|
||||
fn draw(&self, ui: &mut Ui, network: &str) -> bool {
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let small = egui::TextStyle::Small.resolve(ui.style());
|
||||
let height = (font.size + small.size + 18.).max(52.);
|
||||
let (rect, _) =
|
||||
ui.allocate_exact_size(egui::vec2(ui.available_width(), height), Sense::hover());
|
||||
let id = ui.make_persistent_id(("exit choice", network, self.peer));
|
||||
let response = ui.interact(rect, id, Sense::click());
|
||||
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,
|
||||
ui.make_persistent_id(("exit choice", id)),
|
||||
Sense::click(),
|
||||
);
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::selected(
|
||||
egui::WidgetType::RadioButton,
|
||||
@@ -146,68 +208,125 @@ impl Row<'_> {
|
||||
self.name,
|
||||
)
|
||||
});
|
||||
let visuals = ui.style().interact_selectable(&response, self.selected);
|
||||
let dark = ui.visuals().dark_mode;
|
||||
let (text, detail, surface, selected_fill, accent) = if dark {
|
||||
(
|
||||
Color32::from_rgb(244, 248, 250),
|
||||
Color32::from_rgb(188, 202, 212),
|
||||
Color32::from_rgb(39, 45, 50),
|
||||
Color32::from_rgb(28, 58, 71),
|
||||
Color32::from_rgb(141, 216, 244),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
Color32::from_rgb(25, 38, 47),
|
||||
Color32::from_rgb(65, 86, 100),
|
||||
Color32::from_rgb(238, 242, 245),
|
||||
Color32::from_rgb(219, 240, 248),
|
||||
Color32::from_rgb(15, 88, 117),
|
||||
)
|
||||
};
|
||||
let painter = ui.painter();
|
||||
if self.selected || response.hovered() || response.has_focus() {
|
||||
painter.rect_filled(rect, 3., visuals.weak_bg_fill);
|
||||
}
|
||||
painter.hline(
|
||||
rect.x_range(),
|
||||
rect.bottom(),
|
||||
ui.visuals().widgets.noninteractive.bg_stroke,
|
||||
);
|
||||
let dot = rect.left_center() + egui::vec2(15., 0.);
|
||||
painter.circle_stroke(dot, 6., visuals.fg_stroke);
|
||||
if self.selected {
|
||||
painter.circle_filled(dot, 3., visuals.text_color());
|
||||
}
|
||||
let c = Columns::new(rect);
|
||||
let center = rect.center().y;
|
||||
let muted = ui.visuals().weak_text_color();
|
||||
let line = |x: f32, end: f32, y: f32, value: &str, font: &FontId, color| {
|
||||
let mut job =
|
||||
egui::text::LayoutJob::simple_singleline(value.into(), font.clone(), color);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
job.wrap.max_width = (end - x - 5.).max(0.);
|
||||
let text = painter.layout_job(job);
|
||||
painter.galley(Pos2::new(x, y - text.size().y * 0.5), text, color);
|
||||
};
|
||||
let pair = |x, end, label, detail: Option<&str>| {
|
||||
let y = if detail.is_some() {
|
||||
center - small.size * 0.55
|
||||
painter.rect_filled(
|
||||
rect,
|
||||
8.,
|
||||
if self.selected {
|
||||
selected_fill
|
||||
} else {
|
||||
center
|
||||
};
|
||||
line(x, end, y, label, &font, visuals.text_color());
|
||||
if let Some(detail) = detail {
|
||||
line(x, end, center + font.size * 0.65, detail, &small, muted);
|
||||
}
|
||||
};
|
||||
pair(c.name, c.rtt, self.name, self.address);
|
||||
line(
|
||||
c.rtt,
|
||||
c.path,
|
||||
center,
|
||||
&rtt_text(self.rtt),
|
||||
&font,
|
||||
visuals.text_color(),
|
||||
surface
|
||||
},
|
||||
);
|
||||
pair(c.path, rect.right(), self.path, self.transport);
|
||||
response.clicked()
|
||||
if self.selected || response.hovered() || response.has_focus() {
|
||||
painter.rect_stroke(rect, 8., (1_f32, accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
let glyph = if self.selected {
|
||||
icon::CHECK_CIRCLE
|
||||
} else {
|
||||
self.glyph
|
||||
};
|
||||
painter.text(
|
||||
pos2(rect.left() + 22., rect.center().y),
|
||||
Align2::CENTER_CENTER,
|
||||
glyph,
|
||||
FontId::proportional(23.),
|
||||
if self.selected { accent } else { detail },
|
||||
);
|
||||
let left = rect.left() + 44.;
|
||||
let right = rect.right() - 12.;
|
||||
let split = if self.path.is_some() {
|
||||
right - (rect.width() * 0.36).clamp(93., 142.)
|
||||
} else {
|
||||
right
|
||||
};
|
||||
let cell = |x, end, y, h| Rect::from_min_size(pos2(x, y), vec2(end - x, h));
|
||||
let line = |bounds, align, value, font, color| {
|
||||
widgets::single_line(painter, bounds, align, value, font, color)
|
||||
};
|
||||
let one = |x, end| cell(x, end, rect.top(), rect.height());
|
||||
let top = |x, end| cell(x, end, rect.top() + 5., 26.);
|
||||
let bottom = |x, end| cell(x, end, rect.top() + 32., 20.);
|
||||
line(
|
||||
if self.caption.is_empty() {
|
||||
one(left, split)
|
||||
} else {
|
||||
top(left, split)
|
||||
},
|
||||
Align::Min,
|
||||
self.name,
|
||||
bold(19.),
|
||||
text,
|
||||
);
|
||||
if !self.caption.is_empty() {
|
||||
line(
|
||||
bottom(left, split),
|
||||
Align::Min,
|
||||
self.caption,
|
||||
FontId::proportional(15.),
|
||||
detail,
|
||||
);
|
||||
}
|
||||
if let Some(path) = self.path {
|
||||
if let Some(rtt) = self.latency {
|
||||
line(
|
||||
top(split + 4., right),
|
||||
Align::Max,
|
||||
rtt,
|
||||
FontId::proportional(17.),
|
||||
text,
|
||||
);
|
||||
}
|
||||
line(
|
||||
if self.latency.is_some() {
|
||||
bottom(split + 4., right)
|
||||
} else {
|
||||
one(split + 4., right)
|
||||
},
|
||||
Align::Max,
|
||||
path,
|
||||
FontId::proportional(15.),
|
||||
detail,
|
||||
);
|
||||
}
|
||||
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
match hint {
|
||||
Some(hint) => widgets::hint(response, hint),
|
||||
None => response,
|
||||
}
|
||||
.clicked()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::choose_exit;
|
||||
use super::choose_exit_from_networks;
|
||||
use egui::{CentralPanel, Context, Event, PointerButton, Pos2, RawInput, Rect, Shape};
|
||||
use tsunagi::ipc::{DataPathReport, ExitReport, MemberReport, NetworkReport, PeerReport};
|
||||
|
||||
#[test]
|
||||
fn exit_table_fits_phone_widths_and_the_whole_row_selects_the_exact_peer() {
|
||||
let mut network = NetworkReport {
|
||||
active: true,
|
||||
name: "lab".into(),
|
||||
network_id: "network-id".into(),
|
||||
exit: ExitReport {
|
||||
@@ -244,8 +363,21 @@ mod tests {
|
||||
overlay_address_v4: Some("10.9.0.4".into()),
|
||||
..Default::default()
|
||||
});
|
||||
let mut other = network.clone();
|
||||
other.name = "work".into();
|
||||
other.network_id = "other-network".into();
|
||||
other.exit = ExitReport::default();
|
||||
other.peers[0].hostname = Some("office".into());
|
||||
other
|
||||
.members
|
||||
.iter_mut()
|
||||
.find(|m| m.endpoint_id == "new-id")
|
||||
.unwrap()
|
||||
.hostname = Some("office".into());
|
||||
let networks = [network, other];
|
||||
for width in [320., 430.] {
|
||||
let ctx = Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
let frame = |events| {
|
||||
let mut chosen = None;
|
||||
let out = ctx.run(
|
||||
@@ -256,7 +388,7 @@ mod tests {
|
||||
},
|
||||
|ctx| {
|
||||
CentralPanel::default().show(ctx, |ui| {
|
||||
chosen = choose_exit(ui, &network, "self");
|
||||
chosen = choose_exit_from_networks(ui, &networks, "self");
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -278,8 +410,7 @@ mod tests {
|
||||
"west",
|
||||
"10.9.0.4",
|
||||
"37 ms",
|
||||
"Direct",
|
||||
"wg",
|
||||
"Direct · wg",
|
||||
"Offline",
|
||||
] {
|
||||
assert!(
|
||||
@@ -327,6 +458,11 @@ mod tests {
|
||||
.1
|
||||
};
|
||||
assert!(tap("east").is_none());
|
||||
let office = tap("office").unwrap();
|
||||
assert_eq!(
|
||||
(office.network_id.as_str(), office.peer_id.as_str()),
|
||||
("other-network", "new-id")
|
||||
);
|
||||
let select = tap("west").unwrap();
|
||||
assert!(!select.stop);
|
||||
assert_eq!(
|
||||
|
||||
@@ -29,14 +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),
|
||||
|batch| format!("{} Stop {}/{}", icon::STOP, 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,
|
||||
@@ -49,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 {
|
||||
@@ -58,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),
|
||||
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 {
|
||||
@@ -125,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,
|
||||
@@ -217,27 +247,25 @@ fn activity(ui: &Ui, rect: Rect, color: Color32) {
|
||||
|
||||
// Round positive lower bounds down so the displayed minimum is supported by
|
||||
// the measurement, including near a precision or unit boundary.
|
||||
fn rate_number(rate: SpeedRate, divisor: f64, precision: usize) -> String {
|
||||
let mut value = rate.bps as f64 / divisor;
|
||||
fn detailed_rate(rate: SpeedRate, divisor: f64) -> String {
|
||||
let value = rate.bps as f64 / divisor;
|
||||
if rate.lower_bound {
|
||||
let scale = 10_f64.powi(precision as i32);
|
||||
value = (value * scale).floor() / scale;
|
||||
format!("at least {:.2}", (value * 100.).floor() / 100.)
|
||||
} else {
|
||||
format!("{value:.2}")
|
||||
}
|
||||
format!("{value:.precision$}")
|
||||
}
|
||||
|
||||
fn compact_rate(rate: SpeedRate) -> String {
|
||||
let bound = if rate.lower_bound { "≥" } else { "" };
|
||||
let (unit, precision, suffix) = match rate.bps {
|
||||
0 => return "0".into(),
|
||||
1..10_000 if rate.lower_bound => return ">0".into(),
|
||||
1..10_000 => return "<0.01".into(),
|
||||
10_000..1_000_000 => (1e6, 2, ""),
|
||||
1_000_000..10_000_000 => (1e6, 1, ""),
|
||||
10_000_000..10_000_000_000 => (1e6, 0, ""),
|
||||
_ => (1e9, 0, "k"),
|
||||
};
|
||||
format!("{bound}{}{suffix}", rate_number(rate, unit, precision))
|
||||
format!("{:.precision$}{suffix}", rate.bps as f64 / unit)
|
||||
}
|
||||
|
||||
fn tooltip(
|
||||
@@ -265,10 +293,9 @@ fn tooltip(
|
||||
} else {
|
||||
(1e6, "Mbit/s")
|
||||
};
|
||||
let bound = if rate.lower_bound { "at least " } else { "" };
|
||||
hint.push_str(&format!(
|
||||
"\n{label} {bound}{} {suffix}",
|
||||
rate_number(rate, divisor, 2)
|
||||
"\n{label} {} {suffix}",
|
||||
detailed_rate(rate, divisor)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -178,15 +248,17 @@ fn live_and_completed_readings_keep_the_same_row_and_tapping_retests_a_non_exit_
|
||||
);
|
||||
}
|
||||
let done = s.frame(&n, vec![]);
|
||||
for value in ["125", "≥35"] {
|
||||
let lines = positions(&done, |s| s.ends_with(value));
|
||||
let down_text = format!("{} 125", icon::ARROW_DOWN);
|
||||
let up_text = format!("{} 36", icon::ARROW_UP);
|
||||
for value in [&down_text, &up_text] {
|
||||
let lines = positions(&done, |s| s == value);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!((lines[0].x - button.x).abs() < 31.);
|
||||
assert!((lines[0].y - button.y).abs() < 12.);
|
||||
assert!(lines[0].x < width);
|
||||
}
|
||||
let down = positions(&done, |s| s.ends_with("125"))[0];
|
||||
let up = positions(&done, |s| s.ends_with("≥35"))[0];
|
||||
let down = positions(&done, |s| s == down_text)[0];
|
||||
let up = positions(&done, |s| s == up_text)[0];
|
||||
if width > 650. {
|
||||
assert!(
|
||||
(down.y - up.y).abs() < 1. && down.x < up.x,
|
||||
@@ -271,7 +343,9 @@ fn exit_batch_requires_an_online_capable_exit_and_stops_in_its_own_network() {
|
||||
s.click(&n, start);
|
||||
n.speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
|
||||
let batch = s.frame(&n, vec![]);
|
||||
assert!(!positions(&batch, |s| s.contains("0/1")).is_empty());
|
||||
assert!(!positions(&batch, |s| s == format!("{} Stop 0/1", icon::STOP_CIRCLE)).is_empty());
|
||||
let font = egui::TextStyle::Button.resolve(&s.ctx.style());
|
||||
assert!(s.ctx.fonts(|f| f.has_glyphs(&font, icon::STOP_CIRCLE)));
|
||||
s.click(&n, positions(&batch, |s| s.contains("Stop"))[0]);
|
||||
assert!(matches!(s.log.0.borrow().as_slice(), [
|
||||
Command::StartSpeedTest { network_id, peer: None },
|
||||
|
||||
@@ -10,9 +10,7 @@ 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.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) const FORWARDING_COMMAND: &str = "sudo sysctl -w net.inet.ip.forwarding=1";
|
||||
/// Platform instructions for hosts where an administrator manages forwarding.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(crate) const FORWARDING_COMMAND: &str =
|
||||
"Get-NetIPInterface | Set-NetIPInterface -Forwarding Enabled";
|
||||
@@ -54,8 +52,7 @@ pub(crate) fn warnings(network: &NetworkReport) -> Vec<Warning> {
|
||||
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"
|
||||
"Exit node {name} is offline. Internet traffic is blocked until it returns or you disconnect it."
|
||||
),
|
||||
copy: None,
|
||||
});
|
||||
@@ -90,6 +87,9 @@ pub(crate) fn warnings(network: &NetworkReport) -> Vec<Warning> {
|
||||
Some(_) => {}
|
||||
}
|
||||
if exit.forwarding == Some(false) {
|
||||
#[cfg(target_os = "macos")]
|
||||
out.push(Warning { text: "IPv4 forwarding is off. Enable the exit to authorize sharing this Mac’s internet.".into(),copy:None });
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
out.push(Warning {
|
||||
text: format!("exit node: kernel forwarding is OFF — run: {FORWARDING_COMMAND}"),
|
||||
copy: Some(FORWARDING_COMMAND),
|
||||
@@ -148,7 +148,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_working_exit_node_is_quiet_and_forwarding_off_gives_the_command() {
|
||||
fn a_working_exit_is_quiet_and_forwarding_off_explains_the_platform_action() {
|
||||
let working = ExitReport {
|
||||
via: Some("abcdef0123456789".into()),
|
||||
via_online: true,
|
||||
@@ -164,6 +164,9 @@ mod tests {
|
||||
..Default::default()
|
||||
}));
|
||||
assert_eq!(offering.len(), 1);
|
||||
#[cfg(target_os = "macos")]
|
||||
assert!(offering[0].copy.is_none() && offering[0].text.contains("authorize"));
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
assert_eq!(offering[0].copy, Some(FORWARDING_COMMAND));
|
||||
}
|
||||
}
|
||||
@@ -22,19 +22,21 @@ pub fn short(id: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Display units for the whole range of the agent's 64-bit byte counters.
|
||||
pub(crate) const BYTE_UNITS: [&str; 7] = ["B", "kB", "MB", "GB", "TB", "PB", "EB"];
|
||||
|
||||
/// A byte count in binary units.
|
||||
pub fn bytes(n: f64) -> String {
|
||||
const UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
|
||||
let mut value = n.max(0.0);
|
||||
let mut unit = 0;
|
||||
while value >= 1024.0 && unit < UNITS.len() - 1 {
|
||||
while value >= 1024.0 && unit < BYTE_UNITS.len() - 1 {
|
||||
value /= 1024.0;
|
||||
unit += 1;
|
||||
}
|
||||
if unit == 0 {
|
||||
format!("{} B", value as u64)
|
||||
} else {
|
||||
format!("{value:.1} {}", UNITS[unit])
|
||||
format!("{value:.1} {}", BYTE_UNITS[unit])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,6 +107,41 @@ fn lerp_color(a: egui::Color32, b: egui::Color32, t: f32) -> egui::Color32 {
|
||||
egui::Color32::from_rgb(mix(a.r(), b.r()), mix(a.g(), b.g()), mix(a.b(), b.b()))
|
||||
}
|
||||
|
||||
/// Small unlabelled trace painted in an existing network or table row.
|
||||
pub(crate) fn mini_traffic(
|
||||
painter: &egui::Painter,
|
||||
rect: egui::Rect,
|
||||
series: Option<&Series>,
|
||||
unit: Unit,
|
||||
idle: egui::Color32,
|
||||
active: bool,
|
||||
) {
|
||||
let baseline = rect.bottom() - 1.;
|
||||
let history = series.map(|s| s.history(unit));
|
||||
if active && let Some(history) = history {
|
||||
let n = history.len().min(24);
|
||||
let samples = history.iter().skip(history.len() - n);
|
||||
let peak = samples.clone().copied().fold(0_f32, f32::max);
|
||||
if n >= 2 && peak > 0. {
|
||||
let points = samples
|
||||
.enumerate()
|
||||
.map(|(i, s)| {
|
||||
egui::pos2(
|
||||
rect.left() + rect.width() * i as f32 / (n - 1) as f32,
|
||||
baseline - (rect.height() - 2.) * s / peak,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
painter.add(egui::Shape::line(
|
||||
points,
|
||||
egui::Stroke::new(1.5_f32, ACCENT),
|
||||
));
|
||||
return;
|
||||
}
|
||||
}
|
||||
painter.hline(rect.x_range(), baseline, egui::Stroke::new(1_f32, idle));
|
||||
}
|
||||
|
||||
/// A fixed-height sparkline of a series' recent rate, with the peak (top-left)
|
||||
/// and current value (bottom-right) overlaid. The space is always reserved —
|
||||
/// even with no data — so the layout never jumps when data arrives.
|
||||
@@ -113,6 +150,17 @@ pub fn sparkline(ui: &mut egui::Ui, series: Option<&Series>, unit: Unit, height:
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
let painter = ui.painter_at(rect);
|
||||
let visuals = ui.visuals();
|
||||
if width < 84.0 {
|
||||
mini_traffic(
|
||||
&painter,
|
||||
rect.shrink2(egui::vec2(1., 3.)),
|
||||
series,
|
||||
unit,
|
||||
visuals.weak_text_color(),
|
||||
true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
painter.rect_filled(rect, 2.0, visuals.extreme_bg_color);
|
||||
|
||||
let Some(series) = series else {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Shared compact network tiles, device header and join form.
|
||||
mod card;
|
||||
use crate::{
|
||||
client::{Client, Command},
|
||||
devices, exit, format,
|
||||
@@ -42,6 +43,8 @@ pub struct UiState {
|
||||
pub vip_windows: std::collections::BTreeMap<String, crate::vip::Window>,
|
||||
/// Whether the About window is open.
|
||||
pub about_open: bool,
|
||||
/// Whether the global traffic monitor viewport is open.
|
||||
pub monitor_open: bool,
|
||||
/// An exit-node choice waiting for the user to confirm it.
|
||||
pub exit_confirm: Option<devices::ExitConfirm>,
|
||||
/// A selected offline claim waiting for cleanup confirmation.
|
||||
@@ -59,6 +62,7 @@ impl Default for UiState {
|
||||
open_devices: BTreeSet::new(),
|
||||
vip_windows: Default::default(),
|
||||
about_open: false,
|
||||
monitor_open: false,
|
||||
exit_confirm: None,
|
||||
forget_confirm: None,
|
||||
}
|
||||
@@ -123,24 +127,21 @@ pub fn draw_network(
|
||||
network: &NetworkReport,
|
||||
report: &StatusReport,
|
||||
offer_exit: bool,
|
||||
) -> bool {
|
||||
let mut pick_exit = false;
|
||||
) {
|
||||
ui.add_space(5.0);
|
||||
ui.push_id(&network.network_id, |ui| {
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width(ui.available_width());
|
||||
let open = state.expanded_networks.contains(&network.network_id);
|
||||
if overview(ui, network, report, state, open) {
|
||||
if overview(ui, network, report, state, open, traffic) {
|
||||
state.toggle_network(&network.network_id, !open);
|
||||
}
|
||||
if state.expanded_networks.contains(&network.network_id) {
|
||||
ui.separator();
|
||||
pick_exit =
|
||||
draw_network_details(ui, agent, state, traffic, network, report, offer_exit);
|
||||
draw_network_details(ui, agent, state, traffic, network, report, offer_exit);
|
||||
}
|
||||
});
|
||||
});
|
||||
pick_exit
|
||||
}
|
||||
|
||||
impl UiState {
|
||||
@@ -172,20 +173,23 @@ fn overview(
|
||||
report: &StatusReport,
|
||||
state: &mut UiState,
|
||||
open: bool,
|
||||
traffic: &Traffic,
|
||||
) -> bool {
|
||||
let status = if network.active {
|
||||
format!(
|
||||
"{} online",
|
||||
devices::online_count(network, &report.endpoint_id)
|
||||
)
|
||||
} else {
|
||||
"Stopped".into()
|
||||
};
|
||||
let clicked = network_header(ui, &network.name, &status, open).clicked();
|
||||
let warnings = exit::warnings(network);
|
||||
let clicked = card::header(
|
||||
ui,
|
||||
network,
|
||||
report,
|
||||
open,
|
||||
traffic.network(&network.network_id),
|
||||
state.unit,
|
||||
warnings.first().map(|w| w.text.as_str()),
|
||||
)
|
||||
.clicked();
|
||||
if let Some(via) = &network.exit.via {
|
||||
draw_selected_exit(ui, network, via, state);
|
||||
}
|
||||
for warning in exit::warnings(network) {
|
||||
for warning in warnings {
|
||||
draw_exit_warning(ui, &warning);
|
||||
}
|
||||
if !network.range_conflicts.is_empty() {
|
||||
@@ -200,6 +204,7 @@ pub fn draw_network_selector(
|
||||
network: &NetworkReport,
|
||||
report: &StatusReport,
|
||||
state: &mut UiState,
|
||||
traffic: &Traffic,
|
||||
) {
|
||||
let open = state.selected_network.as_deref() == Some(&network.network_id);
|
||||
ui.push_id(&network.network_id, |ui| {
|
||||
@@ -209,7 +214,7 @@ pub fn draw_network_selector(
|
||||
}
|
||||
frame.show(ui, |ui| {
|
||||
ui.set_min_width(ui.available_width());
|
||||
if overview(ui, network, report, state, open) {
|
||||
if overview(ui, network, report, state, open, traffic) {
|
||||
state.toggle_network(&network.network_id, !open);
|
||||
}
|
||||
});
|
||||
@@ -225,7 +230,7 @@ pub fn draw_network_details(
|
||||
network: &NetworkReport,
|
||||
report: &StatusReport,
|
||||
offer_exit: bool,
|
||||
) -> bool {
|
||||
) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui
|
||||
.button(format!("{} Copy secret", icon::COPY))
|
||||
@@ -252,7 +257,7 @@ pub fn draw_network_details(
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
draw_metadata(ui, network, &report.endpoint_id);
|
||||
card::metadata(ui, network, &report.endpoint_id);
|
||||
draw_protocols(ui, agent, network, &report.available_protocols);
|
||||
format::sparkline(ui, traffic.network(&network.network_id), state.unit, 34.0);
|
||||
network_settings(ui, agent, network, offer_exit)
|
||||
@@ -261,7 +266,9 @@ pub fn draw_network_details(
|
||||
fn draw_metadata(ui: &mut egui::Ui, network: &NetworkReport, own_id: &str) {
|
||||
egui::Grid::new(ui.id().with("metadata"))
|
||||
.num_columns(2)
|
||||
.spacing([10.0, 3.0])
|
||||
.min_col_width(0.)
|
||||
.max_col_width(ui.available_width())
|
||||
.spacing([3.0, 3.0])
|
||||
.show(ui, |ui| {
|
||||
widgets::field(ui, icon::TAG, "", "Network name");
|
||||
format::copy_field(ui, &network.name, &network.name);
|
||||
@@ -294,8 +301,7 @@ fn network_settings(
|
||||
agent: &dyn Client,
|
||||
network: &NetworkReport,
|
||||
offer_exit: bool,
|
||||
) -> bool {
|
||||
let mut pick_exit = false;
|
||||
) {
|
||||
if !network.range_conflicts.is_empty() {
|
||||
for conflict in &network.range_conflicts {
|
||||
ui.label(format!(
|
||||
@@ -350,8 +356,20 @@ fn network_settings(
|
||||
enabled: offering,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
pick_exit = ui.button("Exit node…").clicked();
|
||||
#[cfg(target_os = "macos")]
|
||||
if offering
|
||||
&& network.exit.offer_rules.as_ref().is_some_and(|rules| {
|
||||
!rules.ok && tsunagi::overlay::hostrules::macos_exit_needs_authorization(&rules.detail)
|
||||
})
|
||||
&& ui.add_enabled(!agent.busy(), egui::Button::new("Authorize…"))
|
||||
.on_hover_text("Allow this network to share the Mac’s internet connection")
|
||||
.clicked()
|
||||
{
|
||||
agent.send(Command::SetExitOffer {
|
||||
network_id: network.network_id.clone(),
|
||||
enabled: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
let leave = egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE))
|
||||
.fill(LEAVE_RED);
|
||||
@@ -361,60 +379,6 @@ fn network_settings(
|
||||
});
|
||||
}
|
||||
});
|
||||
pick_exit
|
||||
}
|
||||
|
||||
fn network_header(ui: &mut egui::Ui, name: &str, status: &str, open: bool) -> egui::Response {
|
||||
let height = ui.text_style_height(&egui::TextStyle::Heading).max(30.0);
|
||||
let (rect, response) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width(), height),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(egui::WidgetType::CollapsingHeader, ui.is_enabled(), name)
|
||||
});
|
||||
let visuals = ui.style().interact(&response);
|
||||
if response.hovered() || response.has_focus() {
|
||||
ui.painter().rect_filled(rect, 3.0, visuals.weak_bg_fill);
|
||||
}
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
ui.painter().text(
|
||||
rect.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
if open {
|
||||
icon::CARET_DOWN
|
||||
} else {
|
||||
icon::CARET_RIGHT
|
||||
},
|
||||
font.clone(),
|
||||
visuals.text_color(),
|
||||
);
|
||||
let end = ui.painter().text(
|
||||
rect.right_center(),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
status,
|
||||
font.clone(),
|
||||
ui.visuals().text_color(),
|
||||
);
|
||||
let left = rect.left() + font.size + 6.0;
|
||||
let mut job = egui::text::LayoutJob::simple_singleline(
|
||||
name.into(),
|
||||
egui::FontId::new(font.size + 4.0, egui::FontFamily::Name("Bold".into())),
|
||||
ui.visuals().strong_text_color(),
|
||||
);
|
||||
job.wrap.max_width = (end.left() - left - 8.0).max(0.0);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
let title = ui.painter().layout_job(job);
|
||||
ui.painter().galley(
|
||||
egui::pos2(left, rect.center().y - title.size().y / 2.0),
|
||||
title,
|
||||
visuals.text_color(),
|
||||
);
|
||||
widgets::hint(
|
||||
response.on_hover_cursor(egui::CursorIcon::PointingHand),
|
||||
name,
|
||||
)
|
||||
}
|
||||
|
||||
fn draw_selected_exit(ui: &mut egui::Ui, network: &NetworkReport, via: &str, state: &mut UiState) {
|
||||
@@ -425,17 +389,23 @@ fn draw_selected_exit(ui: &mut egui::Ui, network: &NetworkReport, via: &str, sta
|
||||
exit::LOUD
|
||||
};
|
||||
let name = exit::name_of(network, via);
|
||||
let button = ui
|
||||
.add(egui::Button::new(egui::RichText::new(icon::SIGN_OUT).color(color)).frame(false));
|
||||
let clicked = widgets::hint(button, "Stop using this exit node").clicked();
|
||||
if widgets::hint(
|
||||
ui.link(format!("Exit via {name}")),
|
||||
"Stop using this exit node",
|
||||
)
|
||||
.clicked()
|
||||
|| clicked
|
||||
{
|
||||
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
|
||||
if ui.ctx().os() == egui::os::OperatingSystem::Android {
|
||||
ui.label(egui::RichText::new(icon::SIGN_OUT).color(color));
|
||||
ui.label(format!("Exit via {name}"));
|
||||
} else {
|
||||
let button = ui.add(
|
||||
egui::Button::new(egui::RichText::new(icon::SIGN_OUT).color(color)).frame(false),
|
||||
);
|
||||
let clicked = widgets::hint(button, "Stop using this exit node").clicked();
|
||||
if widgets::hint(
|
||||
ui.link(format!("Exit via {name}")),
|
||||
"Stop using this exit node",
|
||||
)
|
||||
.clicked()
|
||||
|| clicked
|
||||
{
|
||||
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
|
||||
}
|
||||
}
|
||||
if let Some(t) = network.exit.traffic {
|
||||
for (glyph, bytes, hint) in [
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
//! The one-line network summary and the exit clients alongside its metadata.
|
||||
use super::{draw_metadata, exit, format, widgets};
|
||||
use crate::stats::{Series, Unit};
|
||||
use egui::{
|
||||
Align, Align2, Color32, FontId, Layout, Rect, Sense, TextStyle, Ui, UiBuilder, pos2, vec2,
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||
|
||||
fn health<'a>(
|
||||
network: &'a NetworkReport,
|
||||
report: &'a StatusReport,
|
||||
warning: Option<&'a str>,
|
||||
) -> (Color32, &'a str) {
|
||||
let amber = Color32::from_rgb(225, 164, 54);
|
||||
if network.range_conflict.is_some() || !network.range_conflicts.is_empty() {
|
||||
return (amber, "Overlapping network ranges");
|
||||
}
|
||||
if !network.active {
|
||||
return (Color32::GRAY, "Stopped");
|
||||
}
|
||||
if let Some(error) = report.overlay_config_error.as_deref() {
|
||||
return (exit::LOUD, error);
|
||||
}
|
||||
if let Some(message) = warning {
|
||||
return (
|
||||
if network.exit.via.is_some() && !network.exit.via_online {
|
||||
exit::LOUD
|
||||
} else {
|
||||
amber
|
||||
},
|
||||
message,
|
||||
);
|
||||
}
|
||||
if network.hostname_conflict.is_some() {
|
||||
return (amber, "Device hostname is already in use");
|
||||
}
|
||||
if network.handshake_failures > 0 && network.peers.is_empty() {
|
||||
return (amber, "Handshakes failed and no peers are connected");
|
||||
}
|
||||
(exit::GOOD, "Active")
|
||||
}
|
||||
|
||||
pub(super) fn header(
|
||||
ui: &mut Ui,
|
||||
net: &NetworkReport,
|
||||
report: &StatusReport,
|
||||
open: bool,
|
||||
series: Option<&Series>,
|
||||
unit: Unit,
|
||||
warning: Option<&str>,
|
||||
) -> egui::Response {
|
||||
let font = TextStyle::Body.resolve(ui.style());
|
||||
let ink = ui.visuals().text_color();
|
||||
let online = crate::devices::online_count(net, &report.endpoint_id);
|
||||
let known = crate::devices::known_count(net, &report.endpoint_id);
|
||||
let users = net.peers.iter().filter(|p| p.uses_our_exit).count();
|
||||
let (color, status) = health(net, report, warning);
|
||||
let height = ui.text_style_height(&TextStyle::Heading).max(30.);
|
||||
let (rect, response) =
|
||||
ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click());
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(
|
||||
egui::WidgetType::CollapsingHeader,
|
||||
ui.is_enabled(),
|
||||
format!("{} · {status}", net.name),
|
||||
)
|
||||
});
|
||||
if response.hovered() || response.has_focus() {
|
||||
ui.painter()
|
||||
.rect_filled(rect, 3., ui.style().interact(&response).weak_bg_fill);
|
||||
}
|
||||
let painter = ui.painter_at(rect);
|
||||
let center = rect.center().y;
|
||||
let caret = painter.text(
|
||||
rect.left_center(),
|
||||
Align2::LEFT_CENTER,
|
||||
if open {
|
||||
icon::CARET_DOWN
|
||||
} else {
|
||||
icon::CARET_RIGHT
|
||||
},
|
||||
font.clone(),
|
||||
ink,
|
||||
);
|
||||
let dot = pos2(caret.right() + 7., center);
|
||||
painter.circle_filled(dot, 4., color);
|
||||
let left = dot.x + 9.;
|
||||
let mut right = rect.right() - 2.;
|
||||
let quiet = ui.visuals().weak_text_color();
|
||||
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() - GAP;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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,
|
||||
);
|
||||
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)));
|
||||
}
|
||||
if let Some(series) = series {
|
||||
hint.push_str(&format!(
|
||||
"\nNetwork traffic {}",
|
||||
format::rate(series.rate(unit), unit)
|
||||
));
|
||||
}
|
||||
widgets::hint(
|
||||
response.on_hover_cursor(egui::CursorIcon::PointingHand),
|
||||
&hint,
|
||||
)
|
||||
}
|
||||
|
||||
fn user_count(count: usize) -> String {
|
||||
format!("{count} exit user{}", if count == 1 { "" } else { "s" })
|
||||
}
|
||||
|
||||
pub(super) fn metadata(ui: &mut Ui, net: &NetworkReport, own_id: &str) {
|
||||
let right = ui.max_rect().right();
|
||||
let top = ui.next_widget_position();
|
||||
let width = ui.available_width();
|
||||
let metadata_width = if ui.ctx().os() == egui::os::OperatingSystem::Android {
|
||||
(width * 0.43).min(140.)
|
||||
} else {
|
||||
(width * 0.46).min(158.)
|
||||
};
|
||||
// Keep identical geometry with zero, one or many exit users. The scroll pane
|
||||
// is bounded by the metadata the card already drew.
|
||||
let left = ui
|
||||
.scope_builder(
|
||||
UiBuilder::new()
|
||||
.max_rect(Rect::from_min_size(
|
||||
top,
|
||||
vec2(metadata_width, ui.available_height()),
|
||||
))
|
||||
.layout(Layout::top_down(Align::Min)),
|
||||
|ui| {
|
||||
ui.set_max_width(metadata_width);
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
draw_metadata(ui, net, own_id);
|
||||
},
|
||||
)
|
||||
.response
|
||||
.rect;
|
||||
if !net.exit.offering {
|
||||
return;
|
||||
}
|
||||
let mut users: Vec<_> = net
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|p| p.uses_our_exit)
|
||||
.map(|p| {
|
||||
let name = p
|
||||
.hostname
|
||||
.as_ref()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| exit::name_of(net, &p.endpoint_id));
|
||||
(name, p.endpoint_id.as_str())
|
||||
})
|
||||
.collect();
|
||||
if users.is_empty() {
|
||||
return;
|
||||
}
|
||||
users.sort_unstable();
|
||||
// The roster is a small block attached to the metadata, even on a wide window.
|
||||
let x = top.x + metadata_width + 6.;
|
||||
let rect = Rect::from_min_max(
|
||||
pos2(x, left.top()),
|
||||
pos2(right.min(x + 142.), left.bottom()),
|
||||
);
|
||||
if rect.width() < 34. {
|
||||
return;
|
||||
}
|
||||
let mut pane = ui.new_child(
|
||||
UiBuilder::new()
|
||||
.id_salt("exit users")
|
||||
.max_rect(rect)
|
||||
.layout(Layout::top_down(Align::Min)),
|
||||
);
|
||||
pane.set_clip_rect(ui.clip_rect().intersect(rect));
|
||||
pane.spacing_mut().item_spacing.y = 0.;
|
||||
pane.painter()
|
||||
.rect_filled(rect, 5., pane.visuals().faint_bg_color);
|
||||
user_list(&mut pane, rect.shrink2(vec2(5., 1.)), &users);
|
||||
}
|
||||
|
||||
fn user_list(ui: &mut Ui, rect: Rect, peers: &[(String, &str)]) {
|
||||
use egui::scroll_area::{ScrollBarVisibility, State};
|
||||
let font = TextStyle::Body.resolve(ui.style());
|
||||
let title_font = FontId::new(font.size + 1., egui::FontFamily::Name("Bold".into()));
|
||||
let heading = Rect::from_min_size(rect.min, vec2(rect.width(), (font.size + 6.).ceil()));
|
||||
let row = ui.text_style_height(&TextStyle::Body).ceil() + 1.;
|
||||
let available = (rect.bottom() - heading.bottom() - 1.).max(0.);
|
||||
let height = ((available / row).floor().max(1.) * row).min(available);
|
||||
let overflow = peers.len() as f32 * row > height + 0.1;
|
||||
let step_width = 20.;
|
||||
let text_right = heading.right() - if overflow { 2. * step_width } else { 0. };
|
||||
let title = Rect::from_min_max(heading.min, pos2(text_right, heading.bottom()));
|
||||
widgets::single_line(
|
||||
ui.painter(),
|
||||
title,
|
||||
Align::Min,
|
||||
&user_count(peers.len()),
|
||||
title_font,
|
||||
ui.visuals().strong_text_color(),
|
||||
);
|
||||
let hint = ui.interact(title, ui.id().with("exit user count"), Sense::hover());
|
||||
widgets::hint(
|
||||
hint,
|
||||
"Peers using this device for internet access. Older peers appear for one minute after forwarding traffic.",
|
||||
);
|
||||
if height <= 0. {
|
||||
return;
|
||||
}
|
||||
let bounds = Rect::from_min_size(
|
||||
pos2(rect.left(), heading.bottom() + 1.),
|
||||
vec2(rect.width(), height),
|
||||
);
|
||||
let mut list = ui.new_child(
|
||||
UiBuilder::new()
|
||||
.id_salt("peer names")
|
||||
.max_rect(bounds)
|
||||
.layout(Layout::top_down(Align::Min)),
|
||||
);
|
||||
let salt = egui::Id::new("scroll");
|
||||
let id = list.make_persistent_id(salt);
|
||||
let mut scroll = egui::ScrollArea::vertical()
|
||||
.id_salt(salt)
|
||||
.max_height(height)
|
||||
.auto_shrink([false, false])
|
||||
.scroll_bar_visibility(ScrollBarVisibility::AlwaysHidden);
|
||||
if overflow {
|
||||
let offset = State::load(ui.ctx(), id).unwrap_or_default().offset.y;
|
||||
let last = (peers.len() as f32 * row - height).max(0.);
|
||||
for (x, glyph, hint, delta) in [
|
||||
(text_right, icon::CARET_UP, "Scroll up one peer", -row),
|
||||
(
|
||||
text_right + step_width,
|
||||
icon::CARET_DOWN,
|
||||
"Scroll down one peer",
|
||||
row,
|
||||
),
|
||||
] {
|
||||
let arrow =
|
||||
Rect::from_min_size(pos2(x, heading.top()), vec2(step_width, heading.height()));
|
||||
let next = (offset + delta).clamp(0., last);
|
||||
let enabled = (next - offset).abs() > 0.5;
|
||||
let r = ui.interact(
|
||||
arrow,
|
||||
id.with(glyph),
|
||||
if enabled {
|
||||
Sense::click()
|
||||
} else {
|
||||
Sense::hover()
|
||||
},
|
||||
);
|
||||
let ink = if enabled {
|
||||
ui.visuals().text_color()
|
||||
} else {
|
||||
ui.visuals().weak_text_color()
|
||||
};
|
||||
if enabled && (r.hovered() || r.has_focus()) {
|
||||
ui.painter()
|
||||
.rect_filled(arrow, 3., ui.style().interact(&r).weak_bg_fill);
|
||||
}
|
||||
ui.painter().text(
|
||||
arrow.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
glyph,
|
||||
font.clone(),
|
||||
ink,
|
||||
);
|
||||
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, hint));
|
||||
if enabled
|
||||
&& widgets::hint(r.on_hover_cursor(egui::CursorIcon::PointingHand), hint).clicked()
|
||||
{
|
||||
scroll = scroll.vertical_scroll_offset(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
scroll.show_rows(&mut list, row, peers.len(), |ui, range| {
|
||||
for (name, id) in &peers[range] {
|
||||
let (cell, response) =
|
||||
ui.allocate_exact_size(vec2(ui.available_width(), row), Sense::hover());
|
||||
widgets::single_line(
|
||||
ui.painter(),
|
||||
cell,
|
||||
Align::Min,
|
||||
name,
|
||||
font.clone(),
|
||||
ui.visuals().text_color(),
|
||||
);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, name));
|
||||
widgets::hint(response, &format!("{name}\n{id}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,7 @@ mod exit;
|
||||
pub mod format;
|
||||
pub mod home;
|
||||
pub mod listeners;
|
||||
pub mod monitor;
|
||||
#[cfg(test)]
|
||||
mod presentation_tests;
|
||||
pub mod stats;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! 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)]
|
||||
pub(super) enum Column {
|
||||
Peer,
|
||||
Network,
|
||||
Near,
|
||||
Far,
|
||||
Protocol,
|
||||
Role,
|
||||
Sent,
|
||||
Received,
|
||||
SendRate,
|
||||
ReceiveRate,
|
||||
SentPackets,
|
||||
ReceivedPackets,
|
||||
Seen,
|
||||
PeerId,
|
||||
}
|
||||
|
||||
impl Column {
|
||||
pub fn title(self) -> &'static str {
|
||||
match self {
|
||||
Self::Peer => "Peer",
|
||||
Self::Network => "Network",
|
||||
Self::Near => "Endpoint A",
|
||||
Self::Far => "Endpoint B",
|
||||
Self::Protocol => "Protocol",
|
||||
Self::Role => "Role",
|
||||
Self::Sent => "Sent",
|
||||
Self::Received => "Received",
|
||||
Self::SendRate => "TX rate",
|
||||
Self::ReceiveRate => "RX rate",
|
||||
Self::SentPackets => "TX packets",
|
||||
Self::ReceivedPackets => "RX packets",
|
||||
Self::Seen => "Last seen",
|
||||
Self::PeerId => "Peer ID",
|
||||
}
|
||||
}
|
||||
pub fn hint(self) -> &'static str {
|
||||
match self {
|
||||
Self::Peer => "Authenticated peer",
|
||||
Self::Network => "Tsunagi network",
|
||||
Self::Near => "Agent-side endpoint, or the first endpoint of an encrypted relay",
|
||||
Self::Far => "Peer-side endpoint, or the second endpoint of an encrypted relay",
|
||||
Self::Protocol => "IP protocol or transport session",
|
||||
Self::Role => "How this agent handles the traffic",
|
||||
Self::Sent => "Total bytes sent from A to B",
|
||||
Self::Received => "Total bytes received from B to A",
|
||||
Self::SendRate => "Bytes per second from A to B",
|
||||
Self::ReceiveRate => "Bytes per second from B to A",
|
||||
Self::SentPackets => "Packets sent from A to B",
|
||||
Self::ReceivedPackets => "Packets received from B to A",
|
||||
Self::Seen => "Time since the last observation",
|
||||
Self::PeerId => "Public peer ID. Select a value to copy it.",
|
||||
}
|
||||
}
|
||||
pub fn descending_first(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Sent
|
||||
| Self::Received
|
||||
| Self::SendRate
|
||||
| Self::ReceiveRate
|
||||
| Self::SentPackets
|
||||
| Self::ReceivedPackets
|
||||
| Self::Seen
|
||||
)
|
||||
}
|
||||
pub fn sql(self) -> &'static str {
|
||||
match self {
|
||||
Self::Sent => "tx",
|
||||
Self::Received => "rx",
|
||||
Self::SendRate => "tx_rate",
|
||||
Self::ReceiveRate => "rx_rate",
|
||||
Self::SentPackets => "ntx",
|
||||
Self::ReceivedPackets => "nrx",
|
||||
Self::Seen => "last",
|
||||
Self::PeerId => "peer",
|
||||
_ => "flow_label(key)",
|
||||
}
|
||||
}
|
||||
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 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),
|
||||
Self::Network => names.network(&key.network),
|
||||
Self::Near => endpoints(key, names).0,
|
||||
Self::Far => endpoints(key, names).1,
|
||||
Self::Protocol => endpoints(key, names).2,
|
||||
Self::Role => role_name(key.role).into(),
|
||||
_ => return Value::Null,
|
||||
};
|
||||
Value::Text(label.to_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct Sort {
|
||||
pub column: Column,
|
||||
pub descending: bool,
|
||||
}
|
||||
impl Default for Sort {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
column: Column::Seen,
|
||||
descending: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Sort {
|
||||
pub fn select(&mut self, column: Column) {
|
||||
self.descending = if self.column == column {
|
||||
!self.descending
|
||||
} else {
|
||||
column.descending_first()
|
||||
};
|
||||
self.column = column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
//! A private scratch database belongs to one window and one worker thread.
|
||||
//! A capture with millions of flows uses disk, and the UI reads one page at a time.
|
||||
use super::{Column, Names, Sort};
|
||||
use rusqlite::functions::FunctionFlags;
|
||||
use rusqlite::{Connection, params, params_from_iter, types::Value};
|
||||
use std::{path::Path, sync::Arc};
|
||||
use tsunagi::traffic::{Flow, FlowDelta, Role};
|
||||
|
||||
pub(super) const PAGE_SIZE: usize = 64;
|
||||
pub(super) const RATE_LIFETIME_MS: u64 = 1900;
|
||||
const RETAIN_MS: u64 = 60_000;
|
||||
|
||||
#[derive(Default, Clone, PartialEq)]
|
||||
pub(super) struct Filter {
|
||||
pub network: Option<[u8; 32]>,
|
||||
pub peer: Option<[u8; 32]>,
|
||||
pub protocol: Option<u8>,
|
||||
pub role: Option<Role>,
|
||||
pub transport: bool,
|
||||
pub sort: Sort,
|
||||
pub before: Option<Cursor>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub(super) struct Cursor {
|
||||
value: Value,
|
||||
id: i64,
|
||||
}
|
||||
|
||||
pub(super) struct Row {
|
||||
order_value: Value,
|
||||
pub id: i64,
|
||||
pub data: FlowDelta,
|
||||
pub last: u64,
|
||||
pub sampled: u64,
|
||||
pub tx_rate: f32,
|
||||
pub rx_rate: f32,
|
||||
}
|
||||
impl Row {
|
||||
pub fn cursor(&self) -> Cursor {
|
||||
Cursor {
|
||||
value: self.order_value.clone(),
|
||||
id: self.id,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct Page {
|
||||
pub rows: Vec<Row>,
|
||||
pub more: bool,
|
||||
}
|
||||
|
||||
pub(super) struct History {
|
||||
connection: Connection,
|
||||
indexed: Option<Column>,
|
||||
names: Arc<Names>,
|
||||
}
|
||||
|
||||
// SQLite counters are signed 64-bit integers; clamp only at its representable maximum.
|
||||
fn integer(n: u64) -> i64 {
|
||||
i64::try_from(n).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
impl History {
|
||||
pub fn open(directory: Option<&Path>) -> Result<Self, String> {
|
||||
// SQLite chooses a delete-on-close temp file on the desktop. Android supplies
|
||||
// its private writable cache directory (the system temp directory can be read-only).
|
||||
let file = directory
|
||||
.map(tempfile::NamedTempFile::new_in)
|
||||
.transpose()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let path = file
|
||||
.as_ref()
|
||||
.map(|f| f.path())
|
||||
.unwrap_or_else(|| Path::new(""));
|
||||
let db = Connection::open(path).map_err(|e| e.to_string())?;
|
||||
db.execute_batch("PRAGMA locking_mode=EXCLUSIVE;
|
||||
PRAGMA journal_mode=OFF;
|
||||
PRAGMA synchronous=OFF;
|
||||
PRAGMA cache_size=-2048;
|
||||
CREATE TABLE flow (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, key BLOB UNIQUE NOT NULL, network BLOB NOT NULL,
|
||||
peer BLOB NOT NULL, other BLOB, role INTEGER NOT NULL, protocol INTEGER, transport INTEGER NOT NULL,
|
||||
tx INTEGER NOT NULL, rx INTEGER NOT NULL, ntx INTEGER NOT NULL, nrx INTEGER NOT NULL,
|
||||
last INTEGER NOT NULL, sampled INTEGER NOT NULL, tx_rate REAL NOT NULL, rx_rate REAL NOT NULL
|
||||
);
|
||||
CREATE INDEX live_rates ON flow(sampled) WHERE tx_rate>0 OR rx_rate>0;
|
||||
CREATE INDEX by_last ON flow(last);
|
||||
CREATE INDEX by_layer ON flow(transport,id);
|
||||
CREATE INDEX by_network ON flow(transport,network,id);
|
||||
CREATE INDEX by_peer ON flow(transport,network,peer,id);
|
||||
CREATE INDEX by_other ON flow(transport,network,other,id) WHERE other IS NOT NULL;
|
||||
CREATE INDEX by_role ON flow(transport,role,id);
|
||||
CREATE INDEX by_protocol ON flow(transport,protocol,id);").map_err(|e|e.to_string())?;
|
||||
// All platforms that pass a directory are Unix; unlink the open file so even
|
||||
// force-stopping the activity releases it when the OS closes the descriptor.
|
||||
drop(file);
|
||||
Ok(Self {
|
||||
connection: db,
|
||||
indexed: None,
|
||||
names: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn use_names(&mut self, names: Arc<Names>) {
|
||||
if !Arc::ptr_eq(&self.names, &names) {
|
||||
self.names = names;
|
||||
if self.indexed.is_some_and(Column::uses_names) {
|
||||
self.indexed = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One index serves the active ordering, including its stable tie-breaker.
|
||||
// Long captures pay its setup cost once per change on the window worker.
|
||||
fn prepare_order(&mut self, column: Column) -> rusqlite::Result<()> {
|
||||
if self.indexed == Some(column) {
|
||||
return Ok(());
|
||||
}
|
||||
self.connection
|
||||
.execute_batch("DROP INDEX IF EXISTS by_view")?;
|
||||
let expr = column.sql();
|
||||
if expr == "flow_label(key)" {
|
||||
let names = self.names.clone();
|
||||
self.connection.create_scalar_function(
|
||||
"flow_label",
|
||||
1,
|
||||
FunctionFlags::SQLITE_UTF8
|
||||
| FunctionFlags::SQLITE_DETERMINISTIC
|
||||
| FunctionFlags::SQLITE_INNOCUOUS,
|
||||
move |ctx| {
|
||||
let bytes = ctx.get_raw(0).as_blob()?;
|
||||
let key = postcard::from_bytes(bytes)
|
||||
.map_err(|e| rusqlite::Error::UserFunctionError(Box::new(e)))?;
|
||||
Ok(column.label_key(&key, &names))
|
||||
},
|
||||
)?;
|
||||
}
|
||||
self.connection.execute_batch(&format!(
|
||||
"CREATE INDEX by_view ON flow(transport,{expr},id)"
|
||||
))?;
|
||||
self.indexed = Some(column);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn interrupt(&self) -> rusqlite::InterruptHandle {
|
||||
self.connection.get_interrupt_handle()
|
||||
}
|
||||
|
||||
pub fn apply(
|
||||
&mut self,
|
||||
data: &[FlowDelta],
|
||||
now: u64,
|
||||
interval: u64,
|
||||
keep: bool,
|
||||
) -> Result<(), String> {
|
||||
let txn = self.connection.transaction().map_err(|e| e.to_string())?;
|
||||
{
|
||||
let mut statement=txn.prepare_cached("INSERT INTO flow (key,network,peer,other,role,protocol,transport,tx,rx,ntx,nrx,last,sampled,tx_rate,rx_rate)
|
||||
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15)
|
||||
ON CONFLICT(key) DO UPDATE SET tx=min(9223372036854775807,tx+excluded.tx),rx=min(9223372036854775807,rx+excluded.rx),ntx=min(9223372036854775807,ntx+excluded.ntx),nrx=min(9223372036854775807,nrx+excluded.nrx),
|
||||
last=max(last,excluded.last), sampled=excluded.sampled,tx_rate=excluded.tx_rate,rx_rate=excluded.rx_rate").map_err(|e|e.to_string())?;
|
||||
let seconds = interval.max(1) as f64 / 1000.;
|
||||
for d in data {
|
||||
let key = postcard::to_stdvec(&d.key).map_err(|e| e.to_string())?;
|
||||
let (protocol, other) = match &d.key.flow {
|
||||
Flow::Ip { protocol, .. } => (Some(*protocol), None),
|
||||
Flow::Relay { other, .. } => (None, Some(other.as_slice())),
|
||||
Flow::Control => (None, None),
|
||||
};
|
||||
statement
|
||||
.execute(params![
|
||||
key,
|
||||
&d.key.network[..],
|
||||
&d.key.peer[..],
|
||||
other,
|
||||
d.key.role as i64,
|
||||
protocol,
|
||||
d.key.role.transport(),
|
||||
integer(d.tx_bytes),
|
||||
integer(d.rx_bytes),
|
||||
integer(d.tx_packets),
|
||||
integer(d.rx_packets),
|
||||
integer(now.saturating_sub(d.age_ms)),
|
||||
integer(now),
|
||||
d.tx_bytes as f64 / seconds,
|
||||
d.rx_bytes as f64 / seconds
|
||||
])
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
if now >= RATE_LIFETIME_MS {
|
||||
txn.execute(
|
||||
"UPDATE flow SET tx_rate=0,rx_rate=0 WHERE sampled<=? AND (tx_rate>0 OR rx_rate>0)",
|
||||
[integer(now - RATE_LIFETIME_MS)],
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
if !keep && now >= RETAIN_MS {
|
||||
txn.execute(
|
||||
"DELETE FROM flow WHERE last <= ?1",
|
||||
[integer(now - RETAIN_MS)],
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
txn.commit().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn page(&mut self, f: &Filter) -> Result<Page, String> {
|
||||
self.prepare_order(f.sort.column)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let expr = f.sort.column.sql();
|
||||
let mut sql = format!(
|
||||
"SELECT id,key,tx,rx,ntx,nrx,last,sampled,tx_rate,rx_rate,{expr} FROM flow WHERE transport=?"
|
||||
);
|
||||
let mut args = vec![Value::Integer(i64::from(f.transport))];
|
||||
if let Some(n) = f.network {
|
||||
sql.push_str(" AND network=?");
|
||||
args.push(Value::Blob(n.to_vec()));
|
||||
}
|
||||
if let Some(p) = f.peer {
|
||||
sql.push_str(" AND (peer=? OR other=?)");
|
||||
args.extend([Value::Blob(p.to_vec()), Value::Blob(p.to_vec())]);
|
||||
}
|
||||
if let Some(r) = f.role {
|
||||
sql.push_str(" AND role=?");
|
||||
args.push(Value::Integer(r as i64));
|
||||
}
|
||||
if let Some(p) = f.protocol {
|
||||
sql.push_str(" AND protocol=?");
|
||||
args.push(Value::Integer(p.into()));
|
||||
}
|
||||
let (op, direction) = if f.sort.descending {
|
||||
("<", "DESC")
|
||||
} else {
|
||||
(">", "ASC")
|
||||
};
|
||||
if let Some(cursor) = &f.before {
|
||||
sql.push_str(&format!(" AND ({expr},id){op}(?,?)"));
|
||||
args.extend([cursor.value.clone(), Value::Integer(cursor.id)]);
|
||||
}
|
||||
sql.push_str(&format!(
|
||||
" ORDER BY {expr} {direction},id {direction} LIMIT ?"
|
||||
));
|
||||
args.push(Value::Integer(PAGE_SIZE as i64 + 1));
|
||||
let mut q = self
|
||||
.connection
|
||||
.prepare_cached(&sql)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let rows = q
|
||||
.query_map(params_from_iter(args), |r| {
|
||||
let blob: Vec<u8> = r.get(1)?;
|
||||
let key = postcard::from_bytes(&blob).map_err(|e| {
|
||||
rusqlite::Error::FromSqlConversionFailure(
|
||||
1,
|
||||
rusqlite::types::Type::Blob,
|
||||
Box::new(e),
|
||||
)
|
||||
})?;
|
||||
Ok(Row {
|
||||
id: r.get(0)?,
|
||||
order_value: r.get(10)?,
|
||||
data: FlowDelta {
|
||||
key,
|
||||
tx_bytes: r.get::<_, i64>(2)? as u64,
|
||||
rx_bytes: r.get::<_, i64>(3)? as u64,
|
||||
tx_packets: r.get::<_, i64>(4)? as u64,
|
||||
rx_packets: r.get::<_, i64>(5)? as u64,
|
||||
age_ms: 0,
|
||||
},
|
||||
last: r.get::<_, i64>(6)? as u64,
|
||||
sampled: r.get::<_, i64>(7)? as u64,
|
||||
tx_rate: r.get(8)?,
|
||||
rx_rate: r.get(9)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| e.to_string())?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut page = Page {
|
||||
more: rows.len() > PAGE_SIZE,
|
||||
rows,
|
||||
};
|
||||
page.rows.truncate(PAGE_SIZE);
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
//! Live traffic inspector shared by the tray and Android clients.
|
||||
mod columns;
|
||||
mod history;
|
||||
mod table;
|
||||
use columns::{Column, Sort};
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod worker;
|
||||
|
||||
use crate::{format::short, widgets};
|
||||
use egui::Ui;
|
||||
use egui_phosphor::regular as icon;
|
||||
use history::{Cursor, Filter};
|
||||
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, sync::Arc, time::Duration};
|
||||
use tsunagi::{
|
||||
NetworkId,
|
||||
dns::ZoneName,
|
||||
ipc::{NetworkReport, StatusReport},
|
||||
iroh_types::EndpointId,
|
||||
traffic::{Flow, FlowKey, IpDetail, Role},
|
||||
};
|
||||
pub use worker::Feed;
|
||||
use worker::Worker;
|
||||
|
||||
type Id = [u8; 32];
|
||||
#[derive(Clone, Default)]
|
||||
struct Network {
|
||||
name: String,
|
||||
peers: BTreeMap<Id, String>,
|
||||
}
|
||||
#[derive(Clone, Default)]
|
||||
struct Names {
|
||||
networks: BTreeMap<Id, Network>,
|
||||
generation: Option<u64>,
|
||||
addresses: BTreeMap<(Id, Ipv4Addr), String>,
|
||||
resolve_addresses: bool,
|
||||
}
|
||||
|
||||
fn public_id(id: &Id) -> String {
|
||||
id.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
impl Names {
|
||||
fn refresh(&mut self, report: Option<&StatusReport>, generation: u64) -> bool {
|
||||
let Some(report) = report else { return false };
|
||||
if self.generation == Some(generation) {
|
||||
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);
|
||||
changed = true;
|
||||
}
|
||||
// Resolve duplicate membership and live entries first. A stale member name
|
||||
// must not trigger a rebuild of a multi-day capture's index every poll.
|
||||
let mut reported = BTreeMap::new();
|
||||
for (key, name) in n
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| (&m.endpoint_id, m.hostname.as_deref()))
|
||||
.chain(
|
||||
n.peers
|
||||
.iter()
|
||||
.map(|p| (&p.endpoint_id, p.hostname.as_deref())),
|
||||
)
|
||||
.chain(std::iter::once((
|
||||
&report.endpoint_id,
|
||||
Some(report.hostname.as_str()),
|
||||
)))
|
||||
{
|
||||
let label = reported.entry(key).or_default();
|
||||
if let Some(name) = name.filter(|s| !s.is_empty()) {
|
||||
*label = Some(name);
|
||||
}
|
||||
}
|
||||
for (key, name) in reported {
|
||||
if let Ok(peer) = key.parse::<EndpointId>() {
|
||||
use std::collections::btree_map::Entry;
|
||||
match entry.peers.entry(*peer.as_bytes()) {
|
||||
Entry::Vacant(e) => {
|
||||
e.insert(name.map_or_else(|| short(key), str::to_owned));
|
||||
changed = true;
|
||||
}
|
||||
Entry::Occupied(mut e) => {
|
||||
if let Some(name) = name
|
||||
&& name != e.get()
|
||||
{
|
||||
*e.get_mut() = name.into();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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());
|
||||
};
|
||||
if self
|
||||
.networks
|
||||
.values()
|
||||
.any(|other| !std::ptr::eq(other, n) && other.name == n.name)
|
||||
{
|
||||
format!(
|
||||
"{} · {}",
|
||||
n.name,
|
||||
short(&NetworkId::from_bytes(*id).to_string())
|
||||
)
|
||||
} else {
|
||||
n.name.clone()
|
||||
}
|
||||
}
|
||||
fn peer(&self, network: &Id, id: &Id) -> String {
|
||||
self.networks
|
||||
.get(network)
|
||||
.and_then(|n| n.peers.get(id))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| short(&public_id(id)))
|
||||
}
|
||||
}
|
||||
|
||||
fn role_name(r: Role) -> &'static str {
|
||||
match r {
|
||||
Role::Mesh => "Mesh",
|
||||
Role::ViaExit => "Via exit node",
|
||||
Role::ServeExit => "Serving exit",
|
||||
Role::Vip => "VIP",
|
||||
Role::Broadcast => "Broadcast",
|
||||
Role::SpeedTest => "Speed test",
|
||||
Role::Control => "Control",
|
||||
Role::Relay => "Encrypted relay",
|
||||
}
|
||||
}
|
||||
fn protocol(n: u8) -> String {
|
||||
match n {
|
||||
1 => "ICMP".into(),
|
||||
6 => "TCP".into(),
|
||||
17 => "UDP".into(),
|
||||
n => format!("IP {n}"),
|
||||
}
|
||||
}
|
||||
fn endpoints(k: &FlowKey, n: &Names) -> (String, String, String) {
|
||||
match k.flow {
|
||||
Flow::Control => (
|
||||
"This agent".into(),
|
||||
n.peer(&k.network, &k.peer),
|
||||
"Control session".into(),
|
||||
),
|
||||
Flow::Relay {
|
||||
other,
|
||||
wire_protocol,
|
||||
} => (
|
||||
n.peer(&k.network, &k.peer),
|
||||
n.peer(&k.network, &other),
|
||||
format!("Relay · {wire_protocol:x}"),
|
||||
),
|
||||
Flow::Ip {
|
||||
near,
|
||||
far,
|
||||
protocol: p,
|
||||
detail,
|
||||
} => {
|
||||
let (a, b) = (Ipv4Addr::from(near), Ipv4Addr::from(far));
|
||||
match detail {
|
||||
IpDetail::Ports(x, y) => (format!("{a}:{x}"), format!("{b}:{y}"), protocol(p)),
|
||||
_ => (
|
||||
a.to_string(),
|
||||
b.to_string(),
|
||||
match detail {
|
||||
IpDetail::Echo => "ICMP echo".into(),
|
||||
IpDetail::Icmp(t, c) => format!("ICMP {t}/{c}"),
|
||||
IpDetail::Fragment => format!("{} fragment", protocol(p)),
|
||||
_ => protocol(p),
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn ago(ms: u64) -> String {
|
||||
let s = ms / 1000;
|
||||
match s {
|
||||
0 => "now".into(),
|
||||
1..60 => format!("{s}s"),
|
||||
60..3600 => format!("{}m", s / 60),
|
||||
3600..86400 => format!("{}h", s / 3600),
|
||||
_ => format!("{}d", s / 86400),
|
||||
}
|
||||
}
|
||||
|
||||
/// State and temporary storage of exactly one visible monitor.
|
||||
pub struct Window {
|
||||
worker: Worker,
|
||||
names: Names,
|
||||
filter: Filter,
|
||||
keep: bool,
|
||||
previous: Vec<Option<Cursor>>,
|
||||
column_page: usize,
|
||||
}
|
||||
impl Window {
|
||||
/// Creates an empty view. Android supplies its application-private cache directory.
|
||||
pub fn new(directory: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
worker: Worker::new(directory),
|
||||
names: Names {
|
||||
resolve_addresses: true,
|
||||
..Names::default()
|
||||
},
|
||||
filter: Filter::default(),
|
||||
keep: false,
|
||||
previous: Vec::new(),
|
||||
column_page: 0,
|
||||
}
|
||||
}
|
||||
/// The endpoint into which this window's subscription feeds interval snapshots.
|
||||
pub fn feed(&self) -> Feed {
|
||||
self.worker.feed.clone()
|
||||
}
|
||||
|
||||
fn controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
|
||||
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);
|
||||
});
|
||||
}
|
||||
if ui.available_width() < 580. {
|
||||
let width = ((ui.available_width() - ui.spacing().item_spacing.x) / 2.).max(60.);
|
||||
ui.horizontal(|ui| self.identity_filters(ui, width));
|
||||
ui.horizontal(|ui| self.flow_filters(ui, width));
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
self.identity_filters(ui, 135.);
|
||||
self.flow_filters(ui, 135.);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn layers(&mut self, ui: &mut Ui) {
|
||||
let layer = self.filter.transport;
|
||||
ui.selectable_value(
|
||||
&mut self.filter.transport,
|
||||
false,
|
||||
format!("{} IP flows", icon::ARROWS_LEFT_RIGHT),
|
||||
);
|
||||
ui.selectable_value(
|
||||
&mut self.filter.transport,
|
||||
true,
|
||||
format!("{} Transport", icon::GIT_FORK),
|
||||
)
|
||||
.on_hover_text(
|
||||
"Authenticated control sessions and encrypted traffic relayed between peers",
|
||||
);
|
||||
if layer != self.filter.transport {
|
||||
self.filter.role = None;
|
||||
self.filter.protocol = None;
|
||||
}
|
||||
}
|
||||
|
||||
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"),
|
||||
"Keep inactive flows for this window session. Otherwise they expire after 60 seconds.",
|
||||
);
|
||||
grid.chooser(ui, &mut self.column_page);
|
||||
}
|
||||
|
||||
fn identity_filters(&mut self, ui: &mut Ui, width: f32) {
|
||||
let network = self.filter.network;
|
||||
egui::ComboBox::from_id_salt("flow-network")
|
||||
.width(width)
|
||||
.truncate()
|
||||
.selected_text(
|
||||
network.map_or_else(|| "All networks".into(), |id| self.names.network(&id)),
|
||||
)
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.filter.network, None, "All networks");
|
||||
for id in self.names.networks.keys() {
|
||||
ui.selectable_value(
|
||||
&mut self.filter.network,
|
||||
Some(*id),
|
||||
self.names.network(id),
|
||||
);
|
||||
}
|
||||
});
|
||||
if self.filter.network != network {
|
||||
self.filter.peer = None;
|
||||
}
|
||||
ui.add_enabled_ui(self.filter.network.is_some(), |ui| {
|
||||
let id = self.filter.network.unwrap_or_default();
|
||||
let peer = self
|
||||
.filter
|
||||
.peer
|
||||
.map_or_else(|| "All peers".into(), |p| self.names.peer(&id, &p));
|
||||
egui::ComboBox::from_id_salt("flow-peer")
|
||||
.width(width)
|
||||
.truncate()
|
||||
.selected_text(peer)
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.filter.peer, None, "All peers");
|
||||
if let Some(net) = self.names.networks.get(&id) {
|
||||
for (peer, label) in &net.peers {
|
||||
ui.selectable_value(&mut self.filter.peer, Some(*peer), label)
|
||||
.on_hover_text(public_id(peer));
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
.response
|
||||
.on_disabled_hover_text("Choose a network to filter its peers");
|
||||
}
|
||||
|
||||
fn flow_filters(&mut self, ui: &mut Ui, width: f32) {
|
||||
if !self.filter.transport {
|
||||
egui::ComboBox::from_id_salt("flow-protocol")
|
||||
.width(width)
|
||||
.truncate()
|
||||
.selected_text(
|
||||
self.filter
|
||||
.protocol
|
||||
.map_or_else(|| "All protocols".into(), protocol),
|
||||
)
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.filter.protocol, None, "All protocols");
|
||||
for p in self.worker.protocols() {
|
||||
ui.selectable_value(&mut self.filter.protocol, Some(p), protocol(p));
|
||||
}
|
||||
});
|
||||
}
|
||||
let roles: &[Role] = if self.filter.transport {
|
||||
&[Role::Control, Role::Relay]
|
||||
} else {
|
||||
&[
|
||||
Role::Mesh,
|
||||
Role::ViaExit,
|
||||
Role::ServeExit,
|
||||
Role::Vip,
|
||||
Role::Broadcast,
|
||||
Role::SpeedTest,
|
||||
]
|
||||
};
|
||||
egui::ComboBox::from_id_salt("flow-role")
|
||||
.width(width)
|
||||
.truncate()
|
||||
.selected_text(self.filter.role.map_or("All roles", role_name))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.filter.role, None, "All roles");
|
||||
for &role in roles {
|
||||
ui.selectable_value(&mut self.filter.role, Some(role), role_name(role));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Draw the responsive inspector inside the current viewport.
|
||||
pub fn show(&mut self, ui: &mut Ui, report: Option<&StatusReport>, generation: u64) {
|
||||
if self.names.refresh(report, generation) {
|
||||
self.worker.names(Arc::new(self.names.clone()));
|
||||
}
|
||||
table::style(ui);
|
||||
let before = self.filter.clone();
|
||||
let keep = self.keep;
|
||||
let grid = table::Grid::new(ui);
|
||||
self.column_page = self.column_page.min(grid.pages.len() - 1);
|
||||
self.controls(ui, &grid);
|
||||
if self.filter != before {
|
||||
self.filter.before = None;
|
||||
self.previous.clear();
|
||||
}
|
||||
if self.filter != before || self.keep != keep {
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
let (page, omitted, error) = self.worker.view();
|
||||
if let Some(e) = &error {
|
||||
ui.colored_label(ui.visuals().error_fg_color, e);
|
||||
}
|
||||
if omitted > 0 {
|
||||
ui.colored_label(
|
||||
ui.visuals().warn_fg_color,
|
||||
format!("{omitted} observations omitted during capture"),
|
||||
);
|
||||
}
|
||||
ui.separator();
|
||||
let now = self.worker.feed.elapsed();
|
||||
if !self.previous.is_empty() || page.more {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui
|
||||
.add_enabled(
|
||||
!self.previous.is_empty(),
|
||||
egui::Button::new(format!("{} Previous", icon::CARET_LEFT)),
|
||||
)
|
||||
.clicked()
|
||||
&& let Some(cursor) = self.previous.pop()
|
||||
{
|
||||
self.filter.before = cursor;
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
ui.label(format!("Page {}", self.previous.len() + 1));
|
||||
if ui
|
||||
.add_enabled(
|
||||
page.more,
|
||||
egui::Button::new(format!("Next {}", icon::CARET_RIGHT)),
|
||||
)
|
||||
.clicked()
|
||||
&& let Some(row) = page.rows.last()
|
||||
{
|
||||
self.previous.push(self.filter.before.clone());
|
||||
self.filter.before = Some(row.cursor());
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
});
|
||||
}
|
||||
let columns = &grid.pages[self.column_page];
|
||||
if let Some(column) = grid.header(ui, columns, self.filter.sort) {
|
||||
self.filter.sort.select(column);
|
||||
self.filter.before = None;
|
||||
self.previous.clear();
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
if page.rows.is_empty() {
|
||||
ui.add_space(10.);
|
||||
ui.label(if error.is_some() {
|
||||
"No captured flows in this view."
|
||||
} else if self.filter.network.is_some()
|
||||
|| self.filter.role.is_some()
|
||||
|| self.filter.protocol.is_some()
|
||||
|| self.filter.before.is_some()
|
||||
{
|
||||
"No flows match these filters."
|
||||
} else {
|
||||
"Listening for traffic…"
|
||||
});
|
||||
} else {
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("flow-rows")
|
||||
.auto_shrink([false, false])
|
||||
.show_rows(ui, grid.row_height, page.rows.len(), |ui, visible| {
|
||||
for index in visible {
|
||||
grid.row(ui, columns, &page.rows[index], &self.names, now, index);
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.ctx().request_repaint_after(Duration::from_secs(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
//! One shared column layout for the pinned header and the virtualized rows.
|
||||
use super::{
|
||||
Column, Names, Sort, ago, endpoints,
|
||||
history::{RATE_LIFETIME_MS, Row},
|
||||
public_id, role_name,
|
||||
};
|
||||
use crate::{
|
||||
format::{bytes, short},
|
||||
widgets,
|
||||
};
|
||||
use egui::{
|
||||
Align, Align2, Color32, FontFamily, FontId, Layout, Rect, RichText, Sense, Ui, UiBuilder, pos2,
|
||||
vec2,
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
const PAD: f32 = 8.;
|
||||
const GAP: f32 = 12.;
|
||||
|
||||
struct Colors {
|
||||
text: Color32,
|
||||
secondary: Color32,
|
||||
sent: Color32,
|
||||
received: Color32,
|
||||
header: Color32,
|
||||
stripe: Color32,
|
||||
}
|
||||
impl Colors {
|
||||
fn new(dark: bool) -> Self {
|
||||
let tone = |dark_rgb: [u8; 3], light_rgb: [u8; 3]| {
|
||||
let [r, g, b] = if dark { dark_rgb } else { light_rgb };
|
||||
Color32::from_rgb(r, g, b)
|
||||
};
|
||||
Self {
|
||||
text: tone([239, 244, 249], [27, 40, 53]),
|
||||
secondary: tone([195, 207, 219], [62, 79, 96]),
|
||||
sent: tone([140, 211, 255], [16, 89, 145]),
|
||||
received: tone([145, 226, 185], [16, 102, 72]),
|
||||
header: tone([42, 55, 68], [224, 234, 243]),
|
||||
stripe: tone([35, 42, 49], [240, 245, 249]),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn style(ui: &mut Ui) {
|
||||
let colors = Colors::new(ui.visuals().dark_mode);
|
||||
let style = ui.style_mut();
|
||||
for id in [egui::TextStyle::Body, egui::TextStyle::Button] {
|
||||
if let Some(font) = style.text_styles.get_mut(&id) {
|
||||
font.size = font.size.max(15.);
|
||||
}
|
||||
}
|
||||
style.visuals.widgets.noninteractive.fg_stroke.color = colors.text;
|
||||
style.visuals.widgets.inactive.fg_stroke.color = colors.text;
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Slot {
|
||||
column: Column,
|
||||
left: f32,
|
||||
width: f32,
|
||||
}
|
||||
pub(super) struct Grid {
|
||||
pub pages: Vec<Vec<Slot>>,
|
||||
pub row_height: f32,
|
||||
width: f32,
|
||||
body: FontId,
|
||||
bold: FontId,
|
||||
mono: FontId,
|
||||
colors: Colors,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
pub fn new(ui: &Ui) -> Self {
|
||||
use Column::*;
|
||||
// Leave the same scroll gutter above and below, even while the bar animates.
|
||||
let width = (ui.available_width() - ui.spacing().scroll.allocated_width()).max(1.);
|
||||
let body = egui::FontSelection::Default.resolve(ui.style());
|
||||
let bold = FontId::new(body.size, FontFamily::Name("Bold".into()));
|
||||
let mono = FontId::monospace(body.size);
|
||||
let measure = |s: &str, f: &FontId| {
|
||||
ui.painter()
|
||||
.layout_no_wrap(s.into(), f.clone(), Color32::WHITE)
|
||||
.size()
|
||||
.x
|
||||
};
|
||||
let height = ui.fonts(|f| {
|
||||
f.row_height(&body)
|
||||
.max(f.row_height(&bold))
|
||||
.max(f.row_height(&mono))
|
||||
});
|
||||
let minimum = |col: Column| {
|
||||
let sample = match col {
|
||||
Near | Far => "255.255.255.255:65535",
|
||||
Network => "network",
|
||||
Protocol => "ICMP echo",
|
||||
Role => "Serving exit",
|
||||
Sent | Received => "1024.0 MB",
|
||||
SendRate | ReceiveRate => "1024.0 MB/s",
|
||||
SentPackets | ReceivedPackets => "99999999",
|
||||
Seen => "Last seen",
|
||||
PeerId => "0123456789ab…",
|
||||
Peer => "device-name",
|
||||
};
|
||||
let font = if matches!(col, Near | Far | PeerId) {
|
||||
&mono
|
||||
} else {
|
||||
&body
|
||||
};
|
||||
measure(sample, font)
|
||||
.max(measure(col.title(), &bold) + 15.)
|
||||
.ceil()
|
||||
+ 2.
|
||||
};
|
||||
// Keep the peer visible on each column page. Put the most useful live
|
||||
// numbers on the first page, then arrange each page in reading order.
|
||||
let mut remaining = vec![
|
||||
Sent,
|
||||
Received,
|
||||
Seen,
|
||||
Far,
|
||||
Near,
|
||||
Protocol,
|
||||
Role,
|
||||
Network,
|
||||
SendRate,
|
||||
ReceiveRate,
|
||||
SentPackets,
|
||||
ReceivedPackets,
|
||||
PeerId,
|
||||
];
|
||||
let inner = (width - 2. * PAD).max(1.);
|
||||
let pinned = minimum(Peer).min(inner * 0.32);
|
||||
let room = (inner - pinned - GAP).max(0.);
|
||||
let mut pages = Vec::new();
|
||||
while !remaining.is_empty() {
|
||||
let mut fields = vec![(Peer, pinned)];
|
||||
let mut free = room;
|
||||
remaining.retain(|c| {
|
||||
let w = minimum(*c).min(room);
|
||||
if fields.len() == 1 || w <= free {
|
||||
fields.push((*c, w));
|
||||
free -= w + GAP;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
fields.sort_by_key(|(c, _)| *c);
|
||||
let weight = |c: Column| {
|
||||
if matches!(c, Peer | Near | Far | Network | Role) {
|
||||
2.
|
||||
} else {
|
||||
1.
|
||||
}
|
||||
};
|
||||
let parts: f32 = fields.iter().map(|(c, _)| weight(*c)).sum();
|
||||
let extra = (free + GAP).max(0.) / parts;
|
||||
let mut x = PAD;
|
||||
pages.push(
|
||||
fields
|
||||
.into_iter()
|
||||
.map(|(column, w)| {
|
||||
let slot = Slot {
|
||||
column,
|
||||
left: x,
|
||||
width: w + extra * weight(column),
|
||||
};
|
||||
x += slot.width + GAP;
|
||||
slot
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
Self {
|
||||
pages,
|
||||
row_height: height.ceil() + 8.,
|
||||
width,
|
||||
body,
|
||||
bold,
|
||||
mono,
|
||||
colors: Colors::new(ui.visuals().dark_mode),
|
||||
}
|
||||
}
|
||||
pub fn chooser(&self, ui: &mut Ui, page: &mut usize) {
|
||||
if self.pages.len() == 1 {
|
||||
return;
|
||||
}
|
||||
let response = egui::ComboBox::from_id_salt("traffic-columns")
|
||||
.selected_text(format!(
|
||||
"{} Columns {}/{}",
|
||||
icon::COLUMNS,
|
||||
*page + 1,
|
||||
self.pages.len()
|
||||
))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.set_max_width((ui.ctx().screen_rect().width() - 45.).clamp(100., 400.));
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
|
||||
for (i, slots) in self.pages.iter().enumerate() {
|
||||
let fields = slots
|
||||
.iter()
|
||||
.skip(1)
|
||||
.map(|s| s.column.title())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · ");
|
||||
ui.selectable_value(page, i, fields);
|
||||
}
|
||||
})
|
||||
.response;
|
||||
widgets::hint(
|
||||
response,
|
||||
"Choose which columns to show. The peer stays visible.",
|
||||
);
|
||||
}
|
||||
fn ink(&self, column: Column) -> Color32 {
|
||||
match column {
|
||||
Column::Sent | Column::SentPackets | Column::SendRate => self.colors.sent,
|
||||
Column::Received | Column::ReceivedPackets | Column::ReceiveRate => {
|
||||
self.colors.received
|
||||
}
|
||||
Column::Network | Column::Seen => self.colors.secondary,
|
||||
_ => self.colors.text,
|
||||
}
|
||||
}
|
||||
pub fn header(&self, ui: &mut Ui, slots: &[Slot], sort: Sort) -> Option<Column> {
|
||||
let (row, _) =
|
||||
ui.allocate_exact_size(vec2(self.width, self.row_height + 3.), Sense::hover());
|
||||
ui.painter().rect_filled(row, 3., self.colors.header);
|
||||
let mut clicked = None;
|
||||
for slot in slots {
|
||||
let col = slot.column;
|
||||
let bounds = slot.rect(row);
|
||||
let active = sort.column == col;
|
||||
let mut text = bounds;
|
||||
if active {
|
||||
let right = numeric(col);
|
||||
let x = if right {
|
||||
text.min.x += 14.;
|
||||
bounds.left()
|
||||
} else {
|
||||
text.max.x -= 14.;
|
||||
bounds.right()
|
||||
};
|
||||
ui.painter().text(
|
||||
pos2(x, row.center().y),
|
||||
if right {
|
||||
Align2::LEFT_CENTER
|
||||
} else {
|
||||
Align2::RIGHT_CENTER
|
||||
},
|
||||
if sort.descending {
|
||||
icon::CARET_DOWN
|
||||
} else {
|
||||
icon::CARET_UP
|
||||
},
|
||||
self.body.clone(),
|
||||
self.colors.text,
|
||||
);
|
||||
}
|
||||
cell(
|
||||
ui,
|
||||
text,
|
||||
col.title(),
|
||||
&self.bold,
|
||||
self.ink(col),
|
||||
numeric(col),
|
||||
);
|
||||
let r = ui
|
||||
.interact(
|
||||
bounds,
|
||||
ui.id().with(("sort traffic", col.title())),
|
||||
Sense::click(),
|
||||
)
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
let direction = if active && sort.descending {
|
||||
"descending"
|
||||
} else {
|
||||
"ascending"
|
||||
};
|
||||
let hint = if active {
|
||||
format!("{} · Sorted {direction}. Select to reverse.", col.hint())
|
||||
} else {
|
||||
format!("{} · Select to sort.", col.hint())
|
||||
};
|
||||
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &hint));
|
||||
if widgets::hint(r, &hint).clicked() {
|
||||
clicked = Some(col);
|
||||
}
|
||||
}
|
||||
clicked
|
||||
}
|
||||
pub fn row(&self, ui: &mut Ui, slots: &[Slot], r: &Row, names: &Names, now: u64, index: usize) {
|
||||
let (row, _) = ui.allocate_exact_size(vec2(self.width, self.row_height), Sense::hover());
|
||||
if index % 2 == 1 {
|
||||
ui.painter().rect_filled(row, 0., self.colors.stripe);
|
||||
}
|
||||
let key = &r.data.key;
|
||||
let (near, far, protocol) = endpoints(key, names);
|
||||
let live = now.saturating_sub(r.sampled) < RATE_LIFETIME_MS;
|
||||
for slot in slots {
|
||||
use Column::*;
|
||||
let col = slot.column;
|
||||
let label = match col {
|
||||
Peer => names.peer(&key.network, &key.peer),
|
||||
Network => names.network(&key.network),
|
||||
Near => near.clone(),
|
||||
Far => far.clone(),
|
||||
Protocol => protocol.clone(),
|
||||
Role => role_name(key.role).into(),
|
||||
Sent => bytes(r.data.tx_bytes as f64),
|
||||
Received => bytes(r.data.rx_bytes as f64),
|
||||
SendRate | ReceiveRate => {
|
||||
let rate = if !live {
|
||||
0.
|
||||
} else if col == SendRate {
|
||||
r.tx_rate
|
||||
} else {
|
||||
r.rx_rate
|
||||
};
|
||||
format!("{}/s", bytes(f64::from(rate)))
|
||||
}
|
||||
SentPackets => r.data.tx_packets.to_string(),
|
||||
ReceivedPackets => r.data.rx_packets.to_string(),
|
||||
Seen => ago(now.saturating_sub(r.last)),
|
||||
PeerId => short(&public_id(&key.peer)),
|
||||
};
|
||||
let font = match col {
|
||||
Peer => &self.bold,
|
||||
Near | Far | PeerId => &self.mono,
|
||||
_ => &self.body,
|
||||
};
|
||||
let bounds = slot.rect(row);
|
||||
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
|
||||
.interact(
|
||||
bounds,
|
||||
ui.id().with(("copy flow peer", r.id)),
|
||||
Sense::click(),
|
||||
)
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
button.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Copy peer ID")
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Slot {
|
||||
fn rect(&self, row: Rect) -> Rect {
|
||||
Rect::from_min_size(
|
||||
pos2(row.left() + self.left, row.top()),
|
||||
vec2(self.width, row.height()),
|
||||
)
|
||||
}
|
||||
}
|
||||
fn numeric(c: Column) -> bool {
|
||||
c.descending_first()
|
||||
}
|
||||
fn cell(
|
||||
ui: &mut Ui,
|
||||
bounds: Rect,
|
||||
text: &str,
|
||||
font: &FontId,
|
||||
color: Color32,
|
||||
right: bool,
|
||||
) -> egui::Response {
|
||||
let layout = if right {
|
||||
Layout::right_to_left(Align::Center)
|
||||
} else {
|
||||
Layout::left_to_right(Align::Center)
|
||||
};
|
||||
// Glyph origins are snapped to physical pixels. Leave a point inside each
|
||||
// edge so the overhang of a right-aligned digit or bold header stays visible.
|
||||
let content = bounds.shrink2(vec2(1., 0.));
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(content).layout(layout));
|
||||
child.set_clip_rect(ui.clip_rect().intersect(bounds));
|
||||
child.add(
|
||||
egui::Label::new(RichText::new(text).font(font.clone()).color(color))
|
||||
.selectable(false)
|
||||
.truncate(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[test]
|
||||
fn all_columns_are_reachable_without_horizontal_scrolling() {
|
||||
use Column::*;
|
||||
let expected = BTreeSet::from([
|
||||
Network,
|
||||
Near,
|
||||
Far,
|
||||
Protocol,
|
||||
Role,
|
||||
Sent,
|
||||
Received,
|
||||
SendRate,
|
||||
ReceiveRate,
|
||||
SentPackets,
|
||||
ReceivedPackets,
|
||||
Seen,
|
||||
PeerId,
|
||||
]);
|
||||
for size in [15., 20.] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
ctx.style_mut(|s| {
|
||||
s.text_styles
|
||||
.insert(egui::TextStyle::Body, FontId::proportional(size));
|
||||
});
|
||||
for width in [320., 480., 760., 920., 1600.] {
|
||||
let input = egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 400.))),
|
||||
..Default::default()
|
||||
};
|
||||
let _ = ctx.run(input, |ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
style(ui);
|
||||
let grid = Grid::new(ui);
|
||||
let mut seen = BTreeSet::new();
|
||||
for page in &grid.pages {
|
||||
assert_eq!(page[0].column, Peer);
|
||||
for slot in &page[1..] {
|
||||
assert!(seen.insert(slot.column));
|
||||
assert!(
|
||||
slot.width > 0. && slot.left + slot.width <= grid.width + 0.1
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(seen, expected);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
use super::history::*;
|
||||
use tsunagi::traffic::*;
|
||||
|
||||
fn sample(port: u16, tx: bool) -> FlowDelta {
|
||||
FlowDelta {
|
||||
key: FlowKey {
|
||||
network: [1; 32],
|
||||
peer: [2; 32],
|
||||
role: Role::Mesh,
|
||||
flow: Flow::Ip {
|
||||
near: [10, 0, 0, 1],
|
||||
far: [10, 0, 0, 2],
|
||||
protocol: 6,
|
||||
detail: IpDetail::Ports(port, 443),
|
||||
},
|
||||
},
|
||||
tx_bytes: if tx { 90 } else { 0 },
|
||||
rx_bytes: if tx { 0 } else { 100 },
|
||||
tx_packets: u64::from(tx),
|
||||
rx_packets: u64::from(!tx),
|
||||
age_ms: 0,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn window_history_expires_and_long_capture_is_paged_and_bidirectional() {
|
||||
let mut db = History::open(None).unwrap();
|
||||
let filter = Filter::default();
|
||||
db.apply(&[sample(1, true)], 1_000, 1_000, false).unwrap();
|
||||
db.apply(&[sample(1, false)], 2_000, 1_000, false).unwrap();
|
||||
let p = db.page(&filter).unwrap();
|
||||
assert_eq!(
|
||||
(p.rows[0].data.tx_bytes, p.rows[0].data.rx_bytes),
|
||||
(90, 100)
|
||||
);
|
||||
db.apply(&[], 62_000, 1_000, false).unwrap();
|
||||
assert!(db.page(&filter).unwrap().rows.is_empty());
|
||||
let flows: Vec<_> = (0..151).map(|port| sample(port, true)).collect();
|
||||
db.apply(&flows, 63_000, 1_000, true).unwrap();
|
||||
db.apply(&[], 3 * 86_400_000, 1_000, true).unwrap();
|
||||
let p = db.page(&filter).unwrap();
|
||||
assert_eq!(p.rows.len(), PAGE_SIZE);
|
||||
assert!(p.more);
|
||||
let next = Filter {
|
||||
before: Some(p.rows.last().unwrap().cursor()),
|
||||
..filter.clone()
|
||||
};
|
||||
assert!(
|
||||
db.page(&next)
|
||||
.unwrap()
|
||||
.rows
|
||||
.iter()
|
||||
.all(|r| r.id < p.rows.last().unwrap().id)
|
||||
);
|
||||
assert!(
|
||||
db.page(&Filter {
|
||||
network: Some([9; 32]),
|
||||
..filter.clone()
|
||||
})
|
||||
.unwrap()
|
||||
.rows
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
db.page(&Filter {
|
||||
transport: true,
|
||||
..filter.clone()
|
||||
})
|
||||
.unwrap()
|
||||
.rows
|
||||
.is_empty()
|
||||
);
|
||||
drop(db);
|
||||
assert!(
|
||||
History::open(None)
|
||||
.unwrap()
|
||||
.page(&filter)
|
||||
.unwrap()
|
||||
.rows
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_filter_matches_both_relay_endpoints_only_in_the_selected_network() {
|
||||
let mut db = History::open(None).unwrap();
|
||||
let mut relay = sample(80, true);
|
||||
relay.key.flow = Flow::Relay {
|
||||
other: [3; 32],
|
||||
wire_protocol: 1,
|
||||
};
|
||||
relay.key.role = Role::Relay;
|
||||
let mut other_net = relay.clone();
|
||||
other_net.key.network = [9; 32];
|
||||
db.apply(&[relay, other_net, sample(80, true)], 1000, 1000, true)
|
||||
.unwrap();
|
||||
for id in [[2; 32], [3; 32]] {
|
||||
let f = Filter {
|
||||
network: Some([1; 32]),
|
||||
peer: Some(id),
|
||||
transport: true,
|
||||
role: Some(Role::Relay),
|
||||
..Filter::default()
|
||||
};
|
||||
let page = db.page(&f).unwrap();
|
||||
assert_eq!(page.rows.len(), 1);
|
||||
assert_eq!(page.rows[0].data.key.network, [1; 32]);
|
||||
}
|
||||
let filtered = Filter {
|
||||
network: Some([1; 32]),
|
||||
protocol: Some(17),
|
||||
..Filter::default()
|
||||
};
|
||||
assert!(db.page(&filtered).unwrap().rows.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn private_cache_file_is_unlinked_and_remains_writable_across_transactions() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut db = History::open(Some(dir.path())).unwrap();
|
||||
let batch: Vec<_> = (0..4096).map(|n| sample(n, true)).collect();
|
||||
for t in [1000, 3 * 86_400_000] {
|
||||
db.apply(&batch, t, 1000, true).unwrap();
|
||||
}
|
||||
assert_eq!(dir.path().read_dir().unwrap().count(), 0);
|
||||
let p = db.page(&Filter::default()).unwrap();
|
||||
assert!(p.more);
|
||||
assert_eq!(p.rows[0].data.tx_bytes, 180);
|
||||
db.apply(&[], 3 * 86_400_000 + 60_000, 1_000, false)
|
||||
.unwrap();
|
||||
assert!(db.page(&Filter::default()).unwrap().rows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sorting_uses_the_entire_filtered_capture_and_pages_through_ties() {
|
||||
use super::{Column, Sort};
|
||||
let mut db = History::open(None).unwrap();
|
||||
let mut data: Vec<_> = (0..150)
|
||||
.map(|port| {
|
||||
let mut flow = sample(port, true);
|
||||
flow.tx_bytes = u64::from((port * 7) % 13) * 1024;
|
||||
flow
|
||||
})
|
||||
.collect();
|
||||
let mut foreign = sample(443, true);
|
||||
foreign.key.network = [7; 32];
|
||||
foreign.tx_bytes = 99_000_000;
|
||||
data.push(foreign);
|
||||
db.apply(&data, 1000, 1000, true).unwrap();
|
||||
for descending in [false, true] {
|
||||
let mut filter = Filter {
|
||||
network: Some([1; 32]),
|
||||
sort: Sort {
|
||||
column: Column::Sent,
|
||||
descending,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut seen = Vec::new();
|
||||
loop {
|
||||
let page = db.page(&filter).unwrap();
|
||||
seen.extend(page.rows.iter().map(|r| (r.data.tx_bytes, r.id)));
|
||||
if !page.more {
|
||||
break;
|
||||
}
|
||||
filter.before = Some(page.rows.last().unwrap().cursor());
|
||||
}
|
||||
assert_eq!(seen.len(), 150);
|
||||
assert!(seen.windows(2).all(|pair| if descending {
|
||||
pair[0] > pair[1]
|
||||
} else {
|
||||
pair[0] < pair[1]
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_member_name_does_not_reindex_the_capture_every_refresh() {
|
||||
use tsunagi::ipc::{MemberReport, NetworkReport, PeerReport, StatusReport};
|
||||
let peer = tsunagi::identity::DeviceIdentity::from_secret_bytes(&[9; 32]).endpoint_id();
|
||||
let network = tsunagi::NetworkId::from_bytes([3; 32]);
|
||||
let mut report = StatusReport {
|
||||
networks: vec![NetworkReport {
|
||||
network_id: network.to_string(),
|
||||
name: "lab".into(),
|
||||
members: vec![MemberReport {
|
||||
endpoint_id: peer.to_string(),
|
||||
hostname: Some("old".into()),
|
||||
..Default::default()
|
||||
}],
|
||||
peers: vec![PeerReport {
|
||||
endpoint_id: peer.to_string(),
|
||||
hostname: Some("current".into()),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mut names = super::Names::default();
|
||||
assert!(names.refresh(Some(&report), 1));
|
||||
assert_eq!(names.peer(network.as_bytes(), peer.as_bytes()), "current");
|
||||
assert!(!names.refresh(Some(&report), 2));
|
||||
report.networks[0].peers[0].hostname = None;
|
||||
assert!(names.refresh(Some(&report), 3));
|
||||
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};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
let mut db = History::open(None).unwrap();
|
||||
let first = sample(200, true);
|
||||
let mut second = sample(9, true);
|
||||
second.key.peer = [3; 32];
|
||||
if let Flow::Ip { ref mut far, .. } = second.key.flow {
|
||||
*far = [10, 0, 0, 10];
|
||||
}
|
||||
second.tx_bytes = 250;
|
||||
let mut names = Names::default();
|
||||
names.networks.insert(
|
||||
[1; 32],
|
||||
Network {
|
||||
name: "lab".into(),
|
||||
peers: BTreeMap::from([([2; 32], "zeta".into()), ([3; 32], "Alpha".into())]),
|
||||
},
|
||||
);
|
||||
db.use_names(Arc::new(names.clone()));
|
||||
db.apply(&[first.clone(), second.clone()], 1000, 1000, true)
|
||||
.unwrap();
|
||||
let filter = |column| Filter {
|
||||
sort: Sort {
|
||||
column,
|
||||
descending: false,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
db.page(&filter(Column::Peer)).unwrap().rows[0]
|
||||
.data
|
||||
.key
|
||||
.peer,
|
||||
[3; 32]
|
||||
);
|
||||
names
|
||||
.networks
|
||||
.get_mut(&[1; 32])
|
||||
.unwrap()
|
||||
.peers
|
||||
.insert([2; 32], "aardvark".into());
|
||||
db.use_names(Arc::new(names));
|
||||
for (column, id) in [(Column::Peer, 2), (Column::Near, 3), (Column::Far, 2)] {
|
||||
assert_eq!(
|
||||
db.page(&filter(column)).unwrap().rows[0].data.key.peer,
|
||||
[id; 32]
|
||||
);
|
||||
}
|
||||
db.apply(&[first], 3000, 1000, true).unwrap();
|
||||
let speeds = db.page(&filter(Column::SendRate)).unwrap();
|
||||
assert_eq!(
|
||||
(speeds.rows[0].data.key.peer, speeds.rows[0].tx_rate),
|
||||
([3; 32], 0.)
|
||||
);
|
||||
assert!(speeds.rows[1].tx_rate > 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_rows_stay_on_one_line_and_headers_sort_in_both_themes() {
|
||||
use super::{Column, Network, Window};
|
||||
use egui::{Color32, Context, Event, Pos2, Rect, Shape, Theme};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
for (theme, width) in [
|
||||
(Theme::Dark, 920.),
|
||||
(Theme::Light, 920.),
|
||||
(Theme::Dark, 320.),
|
||||
] {
|
||||
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 {
|
||||
name: "lab".into(),
|
||||
peers: [([2; 32], "alder".into()), ([3; 32], "birch".into())].into(),
|
||||
},
|
||||
);
|
||||
let left = sample(55201, true);
|
||||
let mut right = sample(7, false);
|
||||
right.key.peer = [3; 32];
|
||||
let feed = win.feed();
|
||||
assert!(win.worker.view().0.rows.is_empty());
|
||||
feed.sample(TrafficSnapshot {
|
||||
flows: vec![left, right],
|
||||
interval_ms: 1000,
|
||||
omitted: 0,
|
||||
});
|
||||
let wait = |win: &Window| {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while win.worker.view().0.rows.len() != 2 {
|
||||
assert!(Instant::now() < deadline);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
};
|
||||
wait(&win);
|
||||
let draw = |win: &mut Window, events: Vec<Event>| {
|
||||
ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 480.))),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
win.show(ui, None, 0);
|
||||
assert!(ui.min_rect().right() <= width);
|
||||
});
|
||||
},
|
||||
)
|
||||
};
|
||||
let label = |frame: &egui::FullOutput, value: &str| {
|
||||
frame
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
Shape::Text(t) if t.galley.text() == value => {
|
||||
let section = &t.galley.job.sections[0].format;
|
||||
assert!(
|
||||
section.font_id.size >= 14.,
|
||||
"{value} at {}",
|
||||
section.font_id.size
|
||||
);
|
||||
assert!(
|
||||
s.clip_rect.contains_rect(t.visual_bounding_rect()),
|
||||
"{value} clipped at {width}: {:?} outside {:?}",
|
||||
t.visual_bounding_rect(),
|
||||
s.clip_rect
|
||||
);
|
||||
Some((
|
||||
t.visual_bounding_rect(),
|
||||
t.override_text_color.unwrap_or(section.color),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing {value} at {width}"))
|
||||
};
|
||||
let click = |win: &mut Window, pos| {
|
||||
for pressed in [true, false] {
|
||||
draw(
|
||||
win,
|
||||
vec![
|
||||
Event::PointerMoved(pos),
|
||||
Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
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()
|
||||
.find_map(|s| match &s.shape {
|
||||
Shape::Text(t) if t.galley.text().contains("Columns 1/") => {
|
||||
Some(t.visual_bounding_rect())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
chooser.right() < width,
|
||||
"column chooser is outside the viewport at {width}"
|
||||
);
|
||||
let (peer, _) = label(&frame, "alder");
|
||||
let (sent, ink) = label(&frame, "90 B");
|
||||
let (header, _) = label(&frame, "Sent");
|
||||
assert!((peer.center().y - sent.center().y).abs() < 2.);
|
||||
assert!((label(&frame, "birch").0.center().y - peer.center().y).abs() < 34.);
|
||||
assert!((sent.right() - header.right()).abs() < 2.);
|
||||
assert!(sent.left() > width * 0.33 || width < 400.);
|
||||
let bg = if theme == Theme::Dark {
|
||||
Color32::from_gray(35)
|
||||
} else {
|
||||
Color32::from_gray(239)
|
||||
};
|
||||
let luminance = |c: Color32| {
|
||||
let v = egui::Rgba::from(c);
|
||||
0.2126 * v.r() + 0.7152 * v.g() + 0.0722 * v.b()
|
||||
};
|
||||
let (a, b) = (luminance(ink), luminance(bg));
|
||||
assert!(
|
||||
(a.max(b) + 0.05) / (a.min(b) + 0.05) >= 4.5,
|
||||
"contrast of {ink:?} at {width}"
|
||||
);
|
||||
click(&mut win, peer.center());
|
||||
frame = draw(&mut win, vec![]);
|
||||
assert!(!frame.shapes.iter().any(
|
||||
|s| matches!(&s.shape,Shape::Text(t) if t.galley.text().contains("packets sent"))
|
||||
));
|
||||
assert!(
|
||||
(label(&frame, "birch").0.center().y - label(&frame, "alder").0.center().y).abs() < 34.
|
||||
);
|
||||
for descending in [true, false] {
|
||||
click(&mut win, header.center());
|
||||
assert_eq!(
|
||||
(win.filter.sort.column, win.filter.sort.descending),
|
||||
(Column::Sent, descending)
|
||||
);
|
||||
frame = draw(&mut win, vec![]);
|
||||
assert_eq!(
|
||||
label(&frame, "alder").0.top() < label(&frame, "birch").0.top(),
|
||||
descending
|
||||
);
|
||||
}
|
||||
drop(win);
|
||||
assert!(!feed.sample(TrafficSnapshot::default()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
use super::{
|
||||
Names,
|
||||
history::{Filter, History, Page},
|
||||
};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
path::PathBuf,
|
||||
sync::{Arc, Condvar, Mutex, MutexGuard},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tsunagi::traffic::TrafficSnapshot;
|
||||
|
||||
struct Work {
|
||||
samples: VecDeque<(u64, TrafficSnapshot)>,
|
||||
filter: Filter,
|
||||
names: Arc<Names>,
|
||||
keep: bool,
|
||||
dirty: bool,
|
||||
closed: bool,
|
||||
omitted: u64,
|
||||
protocols: std::collections::BTreeSet<u8>,
|
||||
interrupt: Option<rusqlite::InterruptHandle>,
|
||||
page: Arc<Page>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
start: Instant,
|
||||
state: Mutex<Work>,
|
||||
wake: Condvar,
|
||||
}
|
||||
impl Shared {
|
||||
fn lock(&self) -> MutexGuard<'_, Work> {
|
||||
self.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
/// A bounded input for the window. Returns false when capture has closed or failed.
|
||||
#[derive(Clone)]
|
||||
pub struct Feed(Arc<Shared>);
|
||||
impl Feed {
|
||||
/// Queue an interval without blocking packet forwarding or the render thread.
|
||||
pub fn sample(&self, s: TrafficSnapshot) -> bool {
|
||||
let mut w = self.0.lock();
|
||||
if w.closed {
|
||||
return false;
|
||||
}
|
||||
for row in &s.flows {
|
||||
if let tsunagi::traffic::Flow::Ip { protocol, .. } = row.key.flow {
|
||||
w.protocols.insert(protocol);
|
||||
}
|
||||
}
|
||||
w.omitted = w.omitted.saturating_add(s.omitted);
|
||||
if w.samples.len() >= 2 {
|
||||
w.omitted = w.omitted.saturating_add(
|
||||
s.flows
|
||||
.iter()
|
||||
.map(|r| r.rx_packets.saturating_add(r.tx_packets))
|
||||
.fold(0u64, u64::saturating_add),
|
||||
);
|
||||
} else {
|
||||
w.samples.push_back((self.elapsed(), s));
|
||||
}
|
||||
self.0.wake.notify_one();
|
||||
true
|
||||
}
|
||||
/// Display a capture failure while keeping the rows already collected available.
|
||||
pub fn error(&self, reason: String) {
|
||||
self.0.lock().error = Some(reason);
|
||||
}
|
||||
pub(super) fn elapsed(&self) -> u64 {
|
||||
self.0.start.elapsed().as_millis() as u64
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Worker {
|
||||
pub feed: Feed,
|
||||
}
|
||||
impl Worker {
|
||||
pub fn new(directory: Option<PathBuf>) -> Self {
|
||||
let shared = Arc::new(Shared {
|
||||
start: Instant::now(),
|
||||
state: Mutex::new(Work {
|
||||
samples: VecDeque::new(),
|
||||
filter: Filter::default(),
|
||||
names: Arc::default(),
|
||||
keep: false,
|
||||
dirty: true,
|
||||
closed: false,
|
||||
omitted: 0,
|
||||
protocols: [1, 6, 17].into_iter().collect(),
|
||||
interrupt: None,
|
||||
page: Arc::default(),
|
||||
error: None,
|
||||
}),
|
||||
wake: Condvar::new(),
|
||||
});
|
||||
let thread = shared.clone();
|
||||
let spawn = std::thread::Builder::new()
|
||||
.name("tsng-traffic-window".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = run(&thread, directory) {
|
||||
let mut w = thread.lock();
|
||||
w.error = Some(format!("Traffic history: {e}"));
|
||||
w.closed = true;
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawn {
|
||||
let mut w = shared.lock();
|
||||
w.error = Some(e.to_string());
|
||||
w.closed = true;
|
||||
}
|
||||
Self { feed: Feed(shared) }
|
||||
}
|
||||
pub fn protocols(&self) -> Vec<u8> {
|
||||
self.feed.0.lock().protocols.iter().copied().collect()
|
||||
}
|
||||
pub fn names(&self, names: Arc<Names>) {
|
||||
let mut w = self.feed.0.lock();
|
||||
w.names = names;
|
||||
w.dirty = true;
|
||||
self.feed.0.wake.notify_one();
|
||||
}
|
||||
pub fn options(&self, filter: Filter, keep: bool) {
|
||||
let mut w = self.feed.0.lock();
|
||||
if w.filter != filter {
|
||||
w.page = Arc::default();
|
||||
}
|
||||
w.filter = filter;
|
||||
w.keep = keep;
|
||||
w.dirty = true;
|
||||
self.feed.0.wake.notify_one();
|
||||
}
|
||||
pub fn view(&self) -> (Arc<Page>, u64, Option<String>) {
|
||||
let w = self.feed.0.lock();
|
||||
(w.page.clone(), w.omitted, w.error.clone())
|
||||
}
|
||||
}
|
||||
impl Drop for Worker {
|
||||
fn drop(&mut self) {
|
||||
let mut w = self.feed.0.lock();
|
||||
w.closed = true;
|
||||
w.samples.clear();
|
||||
w.page = Arc::default();
|
||||
if let Some(db) = &w.interrupt {
|
||||
db.interrupt();
|
||||
}
|
||||
self.feed.0.wake.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn run(shared: &Shared, directory: Option<PathBuf>) -> Result<(), String> {
|
||||
let mut db = History::open(directory.as_deref())?;
|
||||
shared.lock().interrupt = Some(db.interrupt());
|
||||
loop {
|
||||
let (mut samples, filter, keep, names) = {
|
||||
let w = shared.lock();
|
||||
let (mut w, _) = shared
|
||||
.wake
|
||||
.wait_timeout_while(w, Duration::from_secs(1), |w| {
|
||||
!w.closed && !w.dirty && w.samples.is_empty()
|
||||
})
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
if w.closed {
|
||||
return Ok(());
|
||||
}
|
||||
w.dirty = false;
|
||||
(
|
||||
std::mem::take(&mut w.samples),
|
||||
w.filter.clone(),
|
||||
w.keep,
|
||||
w.names.clone(),
|
||||
)
|
||||
};
|
||||
db.use_names(names.clone());
|
||||
if samples.is_empty() {
|
||||
db.apply(&[], shared.start.elapsed().as_millis() as u64, 0, keep)?;
|
||||
}
|
||||
for (now, s) in samples.drain(..) {
|
||||
db.apply(&s.flows, now, s.interval_ms, keep)?;
|
||||
}
|
||||
let page = Arc::new(db.page(&filter)?);
|
||||
let mut w = shared.lock();
|
||||
if !w.closed && filter == w.filter && Arc::ptr_eq(&names, &w.names) {
|
||||
w.page = page;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,3 +260,387 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
|
||||
}
|
||||
assert!(label(&draw(portrait, 4., vec![]), "Endpoint ID").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_roster_reserves_the_full_tx_rx_pair_as_counters_grow() {
|
||||
use egui::os::OperatingSystem::{Android, Mac};
|
||||
|
||||
for (os, width, font_size, density) in [
|
||||
(Android, 480., 13., 1.),
|
||||
(Mac, 600., 13., 2.),
|
||||
(Mac, 740., 13., 1.),
|
||||
(Android, 800., 19., 2.625),
|
||||
] {
|
||||
let ctx = Context::default();
|
||||
ctx.set_os(os);
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
ctx.style_mut(|style| {
|
||||
style
|
||||
.text_styles
|
||||
.insert(egui::TextStyle::Body, egui::FontId::proportional(font_size));
|
||||
});
|
||||
let mut net = NetworkReport {
|
||||
name: "lab".into(),
|
||||
peers: vec![PeerReport {
|
||||
endpoint_id: "alpha".into(),
|
||||
hostname: Some("alpha".into()),
|
||||
agent_version: Some("1.0.6".into()),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mut input = egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 320.))),
|
||||
..Default::default()
|
||||
};
|
||||
input
|
||||
.viewports
|
||||
.get_mut(&egui::ViewportId::ROOT)
|
||||
.unwrap()
|
||||
.native_pixels_per_point = Some(density);
|
||||
let mut first_cell = None;
|
||||
for (mut unit, tx, rx, expected) in [
|
||||
(Unit::Bytes, 0, 0, "0 B / 0 B"),
|
||||
(Unit::Bytes, 293_069, 294_400, "286.2 kB / 287.5 kB"),
|
||||
(
|
||||
Unit::Bytes,
|
||||
(1 << 30) - 1,
|
||||
(1 << 20) - 1,
|
||||
"1024.0 MB / 1024.0 kB",
|
||||
),
|
||||
(Unit::Bytes, u64::MAX, 1 << 50, "16.0 EB / 1.0 PB"),
|
||||
(Unit::Packets, 1_234_567, 7_654_321, "1234567 / 7654321"),
|
||||
(
|
||||
Unit::Packets,
|
||||
u64::MAX,
|
||||
u64::MAX - 1,
|
||||
"18446744073709551615 / 18446744073709551614",
|
||||
),
|
||||
] {
|
||||
net.overlay = Some(OverlayReport {
|
||||
peers: vec![OverlayPeerReport {
|
||||
endpoint_id: "alpha".into(),
|
||||
tx_bytes: tx,
|
||||
rx_bytes: rx,
|
||||
tx_packets: tx,
|
||||
rx_packets: rx,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
});
|
||||
let output = ctx.run(input.clone(), |ctx| {
|
||||
devices::show(
|
||||
ctx,
|
||||
&ReadOnly,
|
||||
&mut unit,
|
||||
(&mut None, &mut None),
|
||||
&net,
|
||||
"self",
|
||||
&Traffic::default(),
|
||||
);
|
||||
});
|
||||
let (text, cell) = output
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == expected => Some((t, s.clip_rect)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing {expected} at {width}"));
|
||||
assert!(!text.galley.elided, "{expected} truncated at {width}");
|
||||
assert!(
|
||||
cell.contains_rect(text.visual_bounding_rect()),
|
||||
"{expected} clipped"
|
||||
);
|
||||
assert!(cell.left() >= 0. && cell.right() <= width);
|
||||
if unit == Unit::Bytes {
|
||||
let bounds = (cell.left(), cell.right());
|
||||
assert_eq!(*first_cell.get_or_insert(bounds), bounds);
|
||||
}
|
||||
assert!(label(&output, "alpha").unwrap().right() <= cell.left());
|
||||
let disclosure = label(&output, icon::CARET_RIGHT).unwrap();
|
||||
assert!(cell.right() <= disclosure.left() && disclosure.right() <= width);
|
||||
if let Some(version) = label(&output, "v1.0.6") {
|
||||
assert!(cell.right() <= version.left() && version.right() <= disclosure.left());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_full_table_survives_long_names_and_compact_exit_icon_starts_and_stops() {
|
||||
use std::cell::RefCell;
|
||||
#[derive(Default)]
|
||||
struct Actions(RefCell<Vec<Command>>);
|
||||
impl Client for Actions {
|
||||
fn busy(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn send(&self, command: Command) {
|
||||
self.0.borrow_mut().push(command);
|
||||
}
|
||||
}
|
||||
let client = Actions::default();
|
||||
let mut net = NetworkReport {
|
||||
active: true,
|
||||
name: "lab".into(),
|
||||
network_id: "lab-id".into(),
|
||||
peers: vec![PeerReport {
|
||||
endpoint_id: "gw-device".into(),
|
||||
hostname: Some("a-long-gateway-name-repeated".repeat(3)),
|
||||
exit_node: true,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
for (width, full, stopping) in [
|
||||
(1230., true, false),
|
||||
(990., true, false),
|
||||
(640., false, false),
|
||||
(640., false, true),
|
||||
] {
|
||||
let ctx = Context::default();
|
||||
ctx.set_os(egui::os::OperatingSystem::Mac);
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
net.exit.via = stopping.then(|| "gw-device".into());
|
||||
let mut pending = None;
|
||||
let mut draw = |time, events| {
|
||||
frame(&ctx, egui::vec2(width, 680.), time, events, |ctx| {
|
||||
devices::show(
|
||||
ctx,
|
||||
&client,
|
||||
&mut Unit::Bytes,
|
||||
(&mut pending, &mut None),
|
||||
&net,
|
||||
"local",
|
||||
&Traffic::default(),
|
||||
)
|
||||
})
|
||||
};
|
||||
draw(0., vec![]);
|
||||
let out = draw(0.1, vec![]);
|
||||
assert_eq!(
|
||||
label(&out, "RTT data / control").is_some(),
|
||||
full,
|
||||
"width {width}"
|
||||
);
|
||||
let at = label(&out, icon::SIGN_OUT).unwrap().center();
|
||||
draw(0.2, vec![Event::PointerMoved(at), press(at, true)]);
|
||||
draw(0.3, vec![press(at, false)]);
|
||||
draw(0.4, vec![]);
|
||||
let out = draw(0.5, vec![]);
|
||||
let accept = label(&out, if stopping { "Stop" } else { "Use" })
|
||||
.expect("confirmation")
|
||||
.center();
|
||||
assert!(label(&out, "Endpoint ID").is_none());
|
||||
draw(0.6, vec![Event::PointerMoved(accept), press(accept, true)]);
|
||||
draw(0.7, vec![press(accept, false)]);
|
||||
assert!(
|
||||
matches!(client.0.borrow_mut().pop(),Some(Command::SetExitNode { network_id,peer }) if network_id=="lab-id" && peer.as_deref()==(!stopping).then_some("gw-device"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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 [
|
||||
(360., egui::os::OperatingSystem::Android),
|
||||
(860., egui::os::OperatingSystem::Mac),
|
||||
] {
|
||||
let ctx = Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
ctx.set_os(os);
|
||||
let mut state = home::UiState::default();
|
||||
let mut network = NetworkReport {
|
||||
name: "office".into(),
|
||||
network_id: "lab".into(),
|
||||
active: true,
|
||||
range: Some("10.2.3.0/24".into()),
|
||||
overlay: Some(OverlayReport {
|
||||
address: Some("10.2.3.4".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
for i in 0..12 {
|
||||
network.peers.push(PeerReport {
|
||||
endpoint_id: format!("public-{i:02}"),
|
||||
hostname: Some(format!("peer-{i:02}")),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
network.exit.offering = true;
|
||||
network.exit.forwarding = Some(true);
|
||||
network.exit.offer_rules = Some(tsunagi::ipc::RuleSetReport {
|
||||
ok: true,
|
||||
detail: "ok".into(),
|
||||
});
|
||||
let report = tsunagi::ipc::StatusReport::default();
|
||||
let mut draw = |net: &NetworkReport, time, events| {
|
||||
let mut height = 0.;
|
||||
let out = frame(&ctx, egui::vec2(width, 720.), time, events, |ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
home::draw_network(
|
||||
ui,
|
||||
&ReadOnly,
|
||||
&mut state,
|
||||
&Traffic::default(),
|
||||
net,
|
||||
&report,
|
||||
true,
|
||||
);
|
||||
height = ui.min_rect().height();
|
||||
assert!(ui.min_rect().right() <= width);
|
||||
});
|
||||
});
|
||||
(out, height)
|
||||
};
|
||||
draw(&network, 0., vec![]);
|
||||
let (folded, _) = draw(&network, 0.1, vec![]);
|
||||
let title = label(&folded, "office").unwrap().center();
|
||||
draw(
|
||||
&network,
|
||||
0.2,
|
||||
vec![Event::PointerMoved(title), press(title, true)],
|
||||
);
|
||||
draw(&network, 0.3, vec![press(title, false)]);
|
||||
let (empty, baseline) = draw(&network, 0.4, vec![]);
|
||||
assert!(label(&empty, "peer-00").is_none());
|
||||
let address_icon = if os == egui::os::OperatingSystem::Android {
|
||||
icon::DEVICE_MOBILE
|
||||
} else {
|
||||
icon::LAPTOP
|
||||
};
|
||||
for (glyph, value) in [
|
||||
(icon::TAG, "office"),
|
||||
(icon::HASH, "lab"),
|
||||
(icon::TREE_STRUCTURE, "10.2.3.0/24"),
|
||||
(address_icon, "10.2.3.4"),
|
||||
(icon::DEVICES, "12 online · 12 known"),
|
||||
] {
|
||||
let marker = label(&empty, glyph).unwrap();
|
||||
let cell = empty
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == value => {
|
||||
Some(t.visual_bounding_rect())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.find(|cell| (cell.center().y - marker.center().y).abs() < 5.)
|
||||
.unwrap();
|
||||
let gap = cell.left() - marker.right();
|
||||
assert!(
|
||||
(1.0..=7.0).contains(&gap),
|
||||
"{value} has a {gap} pt icon gap"
|
||||
);
|
||||
}
|
||||
network.peers[0].uses_our_exit = true;
|
||||
let (one, h) = draw(&network, 0.5, vec![]);
|
||||
assert!(label(&one, "1 exit user").is_some() && label(&one, "peer-00").is_some());
|
||||
assert!((h - baseline).abs() < 1.);
|
||||
for p in &mut network.peers {
|
||||
p.uses_our_exit = true;
|
||||
}
|
||||
let (many, h) = draw(&network, 0.6, vec![]);
|
||||
assert!(label(&many, "12 exit users").is_some());
|
||||
assert!((h - baseline).abs() < 1.);
|
||||
let first = label(&many, "peer-00").unwrap();
|
||||
let heading = label(&many, "12 exit users").unwrap();
|
||||
if os == egui::os::OperatingSystem::Android {
|
||||
assert!(
|
||||
heading.left() <= 168.,
|
||||
"mobile roster belongs close to the metadata"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
(first.left() - heading.left()).abs() < 3.,
|
||||
"roster names align with the heading"
|
||||
);
|
||||
let row = label(&many, "peer-01").unwrap().top() - first.top();
|
||||
let down = many
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == icon::CARET_DOWN => {
|
||||
Some(t.visual_bounding_rect())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.max_by(|a, b| a.left().total_cmp(&b.left()))
|
||||
.unwrap()
|
||||
.center();
|
||||
assert!((down.y - heading.center().y).abs() < 3. && down.x - first.left() < 160.);
|
||||
draw(
|
||||
&network,
|
||||
0.7,
|
||||
vec![Event::PointerMoved(down), press(down, true)],
|
||||
);
|
||||
draw(&network, 0.8, vec![press(down, false)]);
|
||||
let (scrolled, h) = draw(&network, 0.9, vec![]);
|
||||
assert!((label(&scrolled, "peer-01").unwrap().top() - first.top()).abs() < 1. && row > 10.);
|
||||
assert!((h - baseline).abs() < 1.);
|
||||
for p in &mut network.peers {
|
||||
p.uses_our_exit = false;
|
||||
}
|
||||
let (empty, h) = draw(&network, 1., vec![]);
|
||||
assert!(label(&empty, "peer-01").is_none());
|
||||
assert!((h - baseline).abs() < 1.);
|
||||
}
|
||||
}
|
||||
@@ -79,3 +79,25 @@ pub(crate) fn device_address(ui: &mut Ui) {
|
||||
};
|
||||
field(ui, glyph, "", "This device’s IPv4 address");
|
||||
}
|
||||
|
||||
/// Paint a bounded line in a fixed cell, with an ellipsis for long hostnames.
|
||||
pub(crate) fn single_line(
|
||||
painter: &egui::Painter,
|
||||
cell: egui::Rect,
|
||||
align: egui::Align,
|
||||
value: &str,
|
||||
font: egui::FontId,
|
||||
ink: egui::Color32,
|
||||
) {
|
||||
if !cell.is_positive() {
|
||||
return;
|
||||
}
|
||||
let mut job = egui::text::LayoutJob::simple_singleline(value.into(), font, ink);
|
||||
job.wrap.max_width = cell.width();
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
let text = painter.layout_job(job);
|
||||
let bounds =
|
||||
egui::Align2([align, egui::Align::Center]).align_size_within_rect(text.size(), cell);
|
||||
painter.galley(bounds.min, text, ink);
|
||||
}
|
||||
@@ -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.6"
|
||||
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.6" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
|
||||
iroh.workspace = true
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -245,6 +245,20 @@ async fn an_exit_keeps_serving_its_client_while_switching_its_own_upstream() {
|
||||
c.wait_for_tunnels(net, 2)
|
||||
);
|
||||
a.agent.set_exit_via(net, Some(b.id())).await.unwrap();
|
||||
wait_until(
|
||||
"only the selected gateway sees the idle exit client",
|
||||
|| async {
|
||||
let gateway = b.status(net).await;
|
||||
let other = c.status(net).await;
|
||||
(gateway
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.endpoint_id == a.id() && p.uses_our_exit)
|
||||
&& other.peers.iter().all(|p| !p.uses_our_exit))
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let (at, bt, ct) = (a.tun().await, b.tun().await, c.tun().await);
|
||||
let (aa, ba) = (a.overlay(net).await, b.overlay(net).await);
|
||||
for (epoch, upstream) in [false, true, false, true].into_iter().enumerate() {
|
||||
@@ -272,6 +286,19 @@ async fn an_exit_keeps_serving_its_client_while_switching_its_own_upstream() {
|
||||
assert_eq!(a.status(net).await.exit_via, Some(b.id()));
|
||||
assert!(b.status(net).await.exit_offer);
|
||||
}
|
||||
a.agent.set_exit_via(net, None).await.unwrap();
|
||||
wait_until(
|
||||
"deselection removes a client even immediately after forwarding",
|
||||
|| async {
|
||||
b.status(net)
|
||||
.await
|
||||
.peers
|
||||
.iter()
|
||||
.all(|p| !p.uses_our_exit)
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let _ = tokio::join!(a.shutdown(), b.shutdown(), c.shutdown());
|
||||
}
|
||||
|
||||
@@ -298,6 +325,26 @@ async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() {
|
||||
.set_exit_via(exit.id, Some(exit.peer.id()))
|
||||
.await
|
||||
.unwrap();
|
||||
wait_until(
|
||||
"selection is visible in exactly the chosen network",
|
||||
|| async {
|
||||
let alpha_used = left
|
||||
.status(alpha.id)
|
||||
.await
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.uses_our_exit);
|
||||
let beta_used = right
|
||||
.status(beta.id)
|
||||
.await
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.uses_our_exit);
|
||||
(alpha_used == (exit.id == alpha.id) && beta_used == (exit.id == beta.id))
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let plan = client.rules.exit().installed().unwrap();
|
||||
assert_eq!(plan.client_source, Some(exit.client_addr));
|
||||
assert_eq!(plan.overlay.len(), 2);
|
||||
@@ -584,6 +631,8 @@ async fn a_member_sends_its_internet_traffic_through_an_exit_node_and_gets_the_a
|
||||
.client
|
||||
);
|
||||
|
||||
let server_window = server.agent.subscribe_traffic().unwrap();
|
||||
let client_window = client.agent.subscribe_traffic().unwrap();
|
||||
// An ordinary packet for the internet leaves the client's interface and
|
||||
// arrives on the server's, from the client's overlay address.
|
||||
client_tun.push_from_os(ipv4_packet(client_addr, INTERNET, b"GET /"));
|
||||
@@ -605,6 +654,34 @@ async fn a_member_sends_its_internet_traffic_through_an_exit_node_and_gets_the_a
|
||||
assert_eq!(&direct[12..16], &client_addr.octets());
|
||||
assert_eq!(&direct[16..20], &server_addr.octets());
|
||||
|
||||
// Both endpoints see one conversation in opposite directions, attributed to
|
||||
// the authenticated membership. The direct mesh packet is a separate row.
|
||||
use tsunagi::traffic::Role;
|
||||
for (window, role, peer, tx, rx) in [
|
||||
(
|
||||
server_window,
|
||||
Role::ServeExit,
|
||||
client.id(),
|
||||
reply.len(),
|
||||
request.len(),
|
||||
),
|
||||
(
|
||||
client_window,
|
||||
Role::ViaExit,
|
||||
server.id(),
|
||||
request.len(),
|
||||
reply.len(),
|
||||
),
|
||||
] {
|
||||
let snap = window.snapshot();
|
||||
let flow = snap.flows.iter().find(|r| r.key.role == role).unwrap();
|
||||
assert_eq!((flow.tx_packets, flow.rx_packets), (1, 1));
|
||||
assert_eq!((flow.tx_bytes, flow.rx_bytes), (tx as u64, rx as u64));
|
||||
assert_eq!(flow.key.peer, *peer.as_bytes());
|
||||
assert_eq!(flow.key.network, *id.as_bytes());
|
||||
assert!(snap.flows.iter().any(|r| r.key.role == Role::Mesh));
|
||||
}
|
||||
|
||||
// Stopping puts everything back, and the choice is gone.
|
||||
client.agent.set_exit_via(id, None).await.unwrap();
|
||||
assert!(client.status(id).await.exit_via.is_none());
|
||||
|
||||
@@ -37,6 +37,7 @@ fn source(agent: Agent, plugin: Arc<WireguardPlugin>) -> Arc<dyn tsunagi::ipc::R
|
||||
.peers
|
||||
.iter()
|
||||
.map(|peer| tsunagi::ipc::PeerReport {
|
||||
uses_our_exit: peer.uses_our_exit,
|
||||
agent_version: peer.agent_version.clone(),
|
||||
data_error: None,
|
||||
endpoint_id: peer.endpoint_id.to_string(),
|
||||
@@ -256,6 +257,9 @@ fn the_socket_path_is_derived_and_short_enough() {
|
||||
struct Control(Agent);
|
||||
|
||||
impl tsunagi::ipc::ReportSource for Control {
|
||||
fn subscribe_traffic(&self) -> Result<tsunagi::traffic::TrafficSubscription, String> {
|
||||
self.0.subscribe_traffic()
|
||||
}
|
||||
fn report(&self) -> BoxFuture<'_, StatusReport> {
|
||||
Box::pin(async move { StatusReport::default() })
|
||||
}
|
||||
@@ -429,3 +433,38 @@ async fn a_client_can_add_a_network_to_a_running_agent() {
|
||||
control.shutdown().await;
|
||||
agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_monitor_connection_has_an_empty_start_and_releases_its_reader_on_disconnect() {
|
||||
use tsunagi::ipc::TrafficStream;
|
||||
let dir = TempDir::new().unwrap();
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let agent = Agent::spawn(config_with(dir.path(), &discovery))
|
||||
.await
|
||||
.unwrap();
|
||||
let path = control_socket_path(dir.path());
|
||||
let listener = ControlSocket::bind(
|
||||
&path,
|
||||
Arc::new(Control(agent.clone())),
|
||||
ControlSocketAccess::Private,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut window = TrafficStream::open(&path).await.unwrap();
|
||||
assert!(window.snapshot().await.unwrap().flows.is_empty());
|
||||
let remaining: Vec<_> = (0..3).map(|_| agent.subscribe_traffic().unwrap()).collect();
|
||||
assert!(TrafficStream::open(&path).await.is_err());
|
||||
assert!(request_status(&path).await.is_ok());
|
||||
drop(window);
|
||||
wait_until(
|
||||
"closing the window released the agent subscription",
|
||||
|| async { agent.subscribe_traffic().ok() },
|
||||
)
|
||||
.await;
|
||||
let mut next = TrafficStream::open(&path).await.unwrap();
|
||||
assert!(next.snapshot().await.unwrap().flows.is_empty());
|
||||
listener.shutdown().await;
|
||||
assert!(next.snapshot().await.is_err());
|
||||
drop(remaining);
|
||||
agent.shutdown().await;
|
||||
}
|
||||
@@ -2220,3 +2220,37 @@ async fn peer_speed_measures_both_wireguard_directions_and_can_be_repeated() {
|
||||
a.shutdown().await;
|
||||
b.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "throughput varies with CPU and runner load; run with --nocapture"]
|
||||
async fn sample_encrypted_loopback_speed() {
|
||||
use tsunagi::ipc::SpeedPhase;
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let (name, secret) = network("loopback-speed-sample");
|
||||
let a = WgAgent::spawn(&discovery, "speeda").await;
|
||||
let b = WgAgent::spawn(&discovery, "speedb").await;
|
||||
let net = a.agent.join_network(&name, &secret).await.unwrap();
|
||||
b.agent.join_network(&name, &secret).await.unwrap();
|
||||
a.wait_for_tunnels(net, 1).await;
|
||||
b.wait_for_tunnels(net, 1).await;
|
||||
let peer = b.agent.endpoint_id();
|
||||
for metered in [false, true, false, true] {
|
||||
a.agent
|
||||
.start_speed_test(net, Some(peer), metered)
|
||||
.await
|
||||
.unwrap();
|
||||
let report = wait_until("both directions completed", || async {
|
||||
let status = a.agent.network_status(net).await.ok()?.speed;
|
||||
let p = status.peers.get(&peer.to_string())?;
|
||||
matches!(p.phase, SpeedPhase::Done | SpeedPhase::Failed(_)).then(|| p.clone())
|
||||
})
|
||||
.await;
|
||||
println!(
|
||||
"metered={metered} down={:?} up={:?} bytes={} time={}ms",
|
||||
report.down, report.up, report.bytes, report.elapsed_ms
|
||||
);
|
||||
assert_eq!(report.phase, SpeedPhase::Done);
|
||||
}
|
||||
a.shutdown().await;
|
||||
b.shutdown().await;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "1.0.6"
|
||||
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.6" }
|
||||
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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi"
|
||||
version = "1.0.6"
|
||||
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.6" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6", features = ["tun-device", "dns-publish"] }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.6" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.6" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.6" }
|
||||
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
|
||||
|
||||
+91
-38
@@ -1539,6 +1539,9 @@ struct AgentControl {
|
||||
}
|
||||
|
||||
impl tsunagi::ipc::ReportSource for AgentControl {
|
||||
fn subscribe_traffic(&self) -> Result<tsunagi::traffic::TrafficSubscription, String> {
|
||||
self.agent.subscribe_traffic()
|
||||
}
|
||||
fn save_vip(
|
||||
&self,
|
||||
network: String,
|
||||
@@ -1746,17 +1749,57 @@ impl tsunagi::ipc::ReportSource for AgentControl {
|
||||
fn set_exit_offer(
|
||||
&self,
|
||||
network_id: String,
|
||||
enabled: bool,
|
||||
) -> tsunagi::BoxFuture<'_, Result<bool, String>> {
|
||||
enabled: Option<bool>,
|
||||
) -> tsunagi::BoxFuture<'_, Result<tsunagi::ipc::ExitOfferOutcome, String>> {
|
||||
use tsunagi::ipc::ExitOfferOutcome;
|
||||
Box::pin(async move {
|
||||
let id = network_id
|
||||
.parse()
|
||||
.map_err(|err| format!("invalid network id: {err}"))?;
|
||||
self.agent
|
||||
.set_exit_offer(id, enabled)
|
||||
if let Some(change) = enabled {
|
||||
self.agent
|
||||
.set_exit_offer(id, change)
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
if !change || !self.agent.is_active(id).await {
|
||||
return Ok(ExitOfferOutcome::Set(change));
|
||||
}
|
||||
} else {
|
||||
// Wait for the actor to apply the current plan before reading its report.
|
||||
// Re-announcing cannot turn on an offer withdrawn during authorization.
|
||||
if !self.agent.is_active(id).await {
|
||||
return Ok(ExitOfferOutcome::Set(false));
|
||||
}
|
||||
self.agent
|
||||
.reannounce(id)
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
}
|
||||
let net = self
|
||||
.agent
|
||||
.network_status(id)
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
Ok(enabled)
|
||||
#[cfg(target_os = "macos")]
|
||||
if net.exit_offer
|
||||
&& let Some(rule) = &net.exit_rules.offer
|
||||
&& !rule.ok
|
||||
{
|
||||
if let Some(agent_uid) =
|
||||
tsunagi::overlay::hostrules::macos_exit_authorization_uid(&rule.detail)
|
||||
&& let Some(range) = net.range
|
||||
{
|
||||
return Ok(ExitOfferOutcome::NeedsAuthorization { range, agent_uid });
|
||||
}
|
||||
if enabled.is_none() {
|
||||
return Err(rule.detail.clone());
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
if enabled.is_none() && net.exit_offer && net.exit_rules.offer.is_none() {
|
||||
return Err("The agent has no usable data interface for exit sharing. Check the data transports in the network settings.".into());
|
||||
}
|
||||
Ok(ExitOfferOutcome::Set(net.exit_offer))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2439,31 +2482,18 @@ async fn broadcast_command(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What to run to turn kernel forwarding on, which the agent never does.
|
||||
#[cfg(target_os = "macos")]
|
||||
const FORWARDING_COMMAND: &str = "sudo sysctl -w net.inet.ip.forwarding=1";
|
||||
#[cfg(target_os = "windows")]
|
||||
const FORWARDING_COMMAND: &str = "Get-NetIPInterface | Set-NetIPInterface -Forwarding Enabled # in an administrator PowerShell";
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
const FORWARDING_COMMAND: &str = "sudo sysctl -w net.ipv4.ip_forward=1";
|
||||
|
||||
/// How to keep forwarding on across reboots.
|
||||
#[cfg(target_os = "macos")]
|
||||
const FORWARDING_PERSIST: &str = "macOS forgets it at reboot; set it again from a boot script \
|
||||
such as a LaunchDaemon";
|
||||
#[cfg(target_os = "windows")]
|
||||
const FORWARDING_PERSIST: &str = "the setting is kept across reboots";
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
const FORWARDING_PERSIST: &str =
|
||||
"keep it across reboots with `net.ipv4.ip_forward = 1` in /etc/sysctl.d/99-tsunagi.conf";
|
||||
|
||||
/// The warning for an exit node whose rules are in place while the kernel is
|
||||
/// not forwarding, so that nothing passes.
|
||||
fn forwarding_off_note() -> String {
|
||||
format!(
|
||||
"kernel forwarding is OFF, so nothing passes yet: run `{FORWARDING_COMMAND}` \
|
||||
({FORWARDING_PERSIST})"
|
||||
)
|
||||
"IPv4 forwarding is off. Enable the exit in Tsunagi to request macOS authorization.".into()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn forwarding_off_note() -> String {
|
||||
#[cfg(target_os = "windows")]
|
||||
let instruction = "run `Get-NetIPInterface | Set-NetIPInterface -Forwarding Enabled` in an administrator PowerShell";
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let instruction = "run `sudo sysctl -w net.ipv4.ip_forward=1` and set `net.ipv4.ip_forward = 1` in /etc/sysctl.d/99-tsunagi.conf to keep it across reboots";
|
||||
format!("kernel forwarding is OFF, so nothing passes yet: {instruction}")
|
||||
}
|
||||
|
||||
/// Offers this device as an exit node in a network, or stops.
|
||||
@@ -2473,13 +2503,12 @@ async fn exit_offer_command(
|
||||
wanted: &str,
|
||||
choice: BroadcastChoice,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let configured = stored_networks(paths);
|
||||
let network = resolve_network(&configured, wanted)?;
|
||||
let enabled = matches!(choice, BroadcastChoice::On);
|
||||
let id = network.network_id.to_string();
|
||||
|
||||
if !tsunagi::ipc::is_serving(socket).await {
|
||||
let storage = tsunagi::storage::Storage::open(paths)?;
|
||||
let configured = storage.list_networks().await?;
|
||||
let network = resolve_network(&configured, wanted)?;
|
||||
let id = network.network_id.to_string();
|
||||
storage.set_exit_node(network.network_id, enabled).await?;
|
||||
storage.release_ownership_lock();
|
||||
println!(
|
||||
@@ -2495,18 +2524,26 @@ async fn exit_offer_command(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
tsunagi::ipc::set_exit_offer(socket, &id, enabled).await?;
|
||||
let live = tsunagi::ipc::request_status(socket).await?;
|
||||
let entries = live
|
||||
.networks
|
||||
.iter()
|
||||
.map(|net| (net.network_id.clone(), net.name.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let network = &live.networks[resolve_network_index(&entries, wanted)?];
|
||||
let id = &network.network_id;
|
||||
let enabled = tsunagi::ipc::set_exit_offer(socket, id, enabled).await?;
|
||||
println!(
|
||||
"exit node {} for `{}` ({})",
|
||||
if enabled { "on" } else { "off" },
|
||||
network.name,
|
||||
short(&id, 10)
|
||||
short(id, 10)
|
||||
);
|
||||
if !enabled {
|
||||
return Ok(());
|
||||
}
|
||||
let status = tsunagi::ipc::request_status(socket).await?;
|
||||
let Some(report) = status.networks.iter().find(|n| n.network_id == id) else {
|
||||
let Some(report) = status.networks.iter().find(|n| &n.network_id == id) else {
|
||||
return Ok(());
|
||||
};
|
||||
match &report.exit.offer_rules {
|
||||
@@ -2520,6 +2557,18 @@ async fn exit_offer_command(
|
||||
if report.exit.forwarding == Some(false) {
|
||||
eprintln!("warning: {}", forwarding_off_note());
|
||||
}
|
||||
if !report
|
||||
.exit
|
||||
.offer_rules
|
||||
.as_ref()
|
||||
.is_some_and(|rules| rules.ok)
|
||||
|| report.exit.forwarding == Some(false)
|
||||
{
|
||||
println!(
|
||||
"Exit sharing is enabled in the configuration and is waiting for the host to be ready."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
println!(
|
||||
"\nMembers can now send all their internet traffic through this device, and it \
|
||||
can see it. `tsng network exit-node {wanted} off` stops."
|
||||
@@ -5249,6 +5298,7 @@ mod status_tests {
|
||||
relay_sent_via: 0,
|
||||
relay_received_via: 0,
|
||||
peers: vec![PeerReport {
|
||||
uses_our_exit: false,
|
||||
agent_version: None,
|
||||
data_error: None,
|
||||
endpoint_id: ONLINE.into(),
|
||||
@@ -5592,7 +5642,7 @@ mod status_tests {
|
||||
out.push(network_section(&network, OWN, false));
|
||||
let text = out.render(false);
|
||||
assert_eq!(out.worst(), Health::Degraded, "{text}");
|
||||
assert!(text.contains(FORWARDING_COMMAND), "{text}");
|
||||
assert!(text.contains(&forwarding_off_note()), "{text}");
|
||||
assert!(text.contains("ok (nat + forward)"), "{text}");
|
||||
|
||||
network.exit.forwarding = Some(true);
|
||||
@@ -6307,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]
|
||||
|
||||
@@ -730,7 +730,10 @@ fn an_exit_node_is_offered_per_network_only_when_asked_and_nobody_offers_by_defa
|
||||
"{}",
|
||||
String::from_utf8_lossy(&on.stderr)
|
||||
);
|
||||
assert!(String::from_utf8_lossy(&on.stdout).contains("exit node on"));
|
||||
let output = String::from_utf8_lossy(&on.stdout);
|
||||
assert!(output.contains("exit node on"));
|
||||
assert!(output.contains("waiting for the host"));
|
||||
assert!(!output.contains("Members can now"));
|
||||
assert!(offered());
|
||||
|
||||
let off = agent.run(&["network", "exit-node", "exit-offer", "off"]);
|
||||
|
||||
Vendored
+11
-3
@@ -1,8 +1,10 @@
|
||||
# Running tsunagi on macOS
|
||||
|
||||
The agent needs **root** on macOS: creating a `utun` interface and writing
|
||||
`/etc/resolver` are both root-only, and macOS has no per-capability grant like
|
||||
Linux. There are two ways to run it.
|
||||
The tray and CLI run as your normal account. The packaged service creates the
|
||||
system `utun` and publishes `/etc/resolver` entries. A separate user agent
|
||||
with its own writable state and cache can also offer an exit through physical
|
||||
TCP, UDP and ICMP echo sockets when macOS denies creation of its utun.
|
||||
The system service provides the host's overlay addresses and routes.
|
||||
|
||||
## Quick start — `sudo`
|
||||
|
||||
@@ -41,6 +43,12 @@ The cask starts the service for you. The agent runs as root, and its control
|
||||
socket is open to the `admin` group, so the CLI and the tray work without
|
||||
`sudo` for an administrator.
|
||||
|
||||
Enabling exit sharing configures IPv4 forwarding and the network's PF rules.
|
||||
The system agent already has the required permissions. For a user agent with
|
||||
an existing utun, the tray and CLI can request the missing permission in a
|
||||
macOS administrator dialog. [Exit sharing on macOS](../../docs/exit-node.md#macos)
|
||||
describes the per-user subnet grant and its removal.
|
||||
|
||||
After upgrading the CLI, run `sudo brew services restart tsunagi` to load the
|
||||
new binary into the system daemon. Running `brew services start tsunagi` in
|
||||
a user shell creates a separate launch agent. If that happened, remove the
|
||||
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user