Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b47acb8321 | ||
|
|
e3b74babba |
No files matched your search
Generated
+13
-10
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -6320,7 +6320,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"egui",
|
||||
@@ -6344,7 +6344,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"iroh",
|
||||
@@ -6359,7 +6359,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -6404,7 +6404,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -6427,7 +6427,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"caps",
|
||||
@@ -6447,7 +6447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui-phosphor",
|
||||
@@ -6463,17 +6463,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"postcard",
|
||||
"rusqlite",
|
||||
"tempfile",
|
||||
"tsunagi-core",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wg-quic"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
@@ -6500,7 +6503,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
|
||||
@@ -150,13 +150,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 +196,24 @@ 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.
|
||||
|
||||
**Transport** shows authenticated control sessions and encrypted datagrams
|
||||
forwarded between two other endpoints. For relay rows the arrows follow the
|
||||
two displayed endpoints in order. Rates update once per second. Select a row
|
||||
to see its packet counts. The monitor records header metadata and counters only.
|
||||
|
||||
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 |
|
||||
|
||||
@@ -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.7')
|
||||
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.7"
|
||||
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.7" }
|
||||
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||
|
||||
@@ -38,7 +38,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 +60,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,6 +73,9 @@ 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,
|
||||
@@ -112,6 +124,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||
let output = d.ctx.run(input, |ctx| {
|
||||
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",
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -20,6 +20,7 @@ enum Page {
|
||||
#[default]
|
||||
Home,
|
||||
About,
|
||||
Monitor,
|
||||
Join,
|
||||
Devices(String),
|
||||
Vips(String),
|
||||
@@ -38,6 +39,7 @@ 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",
|
||||
@@ -85,6 +87,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 +112,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;
|
||||
@@ -331,7 +352,7 @@ impl Phone {
|
||||
}
|
||||
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) {
|
||||
self.home();
|
||||
}
|
||||
self.snapshot = Snapshot::default();
|
||||
@@ -361,6 +382,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 +407,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();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
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.7"
|
||||
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"]
|
||||
|
||||
@@ -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(
|
||||
@@ -872,6 +876,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;
|
||||
@@ -2838,6 +2848,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) {
|
||||
|
||||
@@ -201,6 +201,13 @@ pub(super) fn receive_packet(
|
||||
&& data.id == channel.id
|
||||
&& inner.routes.peer_addresses(network, peer) == Some((data.destination, data.source))
|
||||
{
|
||||
inner
|
||||
.routes
|
||||
.traffic
|
||||
.packet(network, peer, crate::traffic::Direction::Rx, packet, || {
|
||||
crate::traffic::Role::SpeedTest
|
||||
})
|
||||
.record();
|
||||
channel.handle.data(data);
|
||||
}
|
||||
true
|
||||
@@ -308,11 +315,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
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
//! rather than the crate's internal structures, so internal refactors do not
|
||||
//! silently change what a client sees.
|
||||
|
||||
mod traffic;
|
||||
pub use traffic::TrafficStream;
|
||||
mod speed;
|
||||
pub use speed::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
|
||||
|
||||
@@ -174,6 +176,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.
|
||||
@@ -326,6 +330,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,
|
||||
@@ -357,6 +362,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.
|
||||
@@ -1022,6 +1029,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,
|
||||
@@ -1196,13 +1209,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', 28]);
|
||||
|
||||
/// 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 +1237,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,
|
||||
|
||||
@@ -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?;
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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::{
|
||||
@@ -252,7 +253,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 +278,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 +307,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 +322,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 +350,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 +388,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);
|
||||
}
|
||||
@@ -937,39 +991,101 @@ 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)]
|
||||
if forwarded && let Some(gateway) = &self.forwarding {
|
||||
if gateway.forward(Route { network, peer }, packet) {
|
||||
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() {
|
||||
obs.record();
|
||||
if let Some(exit) = exit {
|
||||
exit.rx_bytes.fetch_add(len, Ordering::Relaxed);
|
||||
}
|
||||
@@ -980,7 +1096,6 @@ impl Interface {
|
||||
}
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The addresses the interface should be carrying, from the table.
|
||||
|
||||
@@ -109,6 +109,7 @@ 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>,
|
||||
broadcast: ArcSwap<BroadcastTable>,
|
||||
selected_exit: ArcSwapOption<SelectedExit>,
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.6"
|
||||
version = "1.0.7"
|
||||
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.7" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.7" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.7" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.7" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.7" }
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
|
||||
@@ -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.7"
|
||||
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.7" }
|
||||
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.7"
|
||||
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.7" }
|
||||
# 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).
|
||||
|
||||
@@ -20,6 +20,8 @@ use tsunagi_ui::app_fonts;
|
||||
/// The window's state.
|
||||
pub(crate) struct App {
|
||||
agent: AgentClient,
|
||||
runtime: tokio::runtime::Handle,
|
||||
monitor: Option<crate::monitor::Monitor>,
|
||||
state: UiState,
|
||||
/// Traffic rates derived from successive snapshots.
|
||||
traffic: Traffic,
|
||||
@@ -41,6 +43,8 @@ impl App {
|
||||
let agent = AgentClient::spawn(&runtime, ctx);
|
||||
Ok(Self {
|
||||
agent,
|
||||
runtime,
|
||||
monitor: None,
|
||||
state: UiState::default(),
|
||||
traffic: Traffic::default(),
|
||||
sampled: 0,
|
||||
@@ -59,6 +63,15 @@ impl eframe::App for App {
|
||||
}
|
||||
|
||||
ui::draw(ctx, &self.agent, &mut self.state, &snapshot, &self.traffic);
|
||||
if self.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;
|
||||
self.state.monitor_open = false;
|
||||
}
|
||||
}
|
||||
self.show_devices_windows(ctx, &snapshot);
|
||||
self.show_vip_windows(ctx, &snapshot);
|
||||
self.show_about_window(ctx, &snapshot);
|
||||
|
||||
@@ -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.7"
|
||||
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"] }
|
||||
tempfile.workspace = true
|
||||
egui = "0.31"
|
||||
egui-phosphor = "0.9"
|
||||
zeroize = "1.9"
|
||||
|
||||
@@ -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.;
|
||||
|
||||
@@ -217,27 +217,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 +263,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)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,15 +178,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,
|
||||
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,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 +61,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,
|
||||
}
|
||||
|
||||
@@ -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,202 @@
|
||||
//! 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 rusqlite::{Connection, params, params_from_iter, types::Value};
|
||||
use std::path::Path;
|
||||
use tsunagi::traffic::{Flow, FlowDelta, Role};
|
||||
|
||||
pub(super) const PAGE_SIZE: usize = 64;
|
||||
const RETAIN_MS: u64 = 60_000;
|
||||
|
||||
#[derive(Default, Clone, PartialEq, Eq)]
|
||||
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 before: Option<i64>,
|
||||
}
|
||||
|
||||
pub(super) struct Row {
|
||||
pub id: i64,
|
||||
pub data: FlowDelta,
|
||||
pub last: u64,
|
||||
pub sampled: u64,
|
||||
pub tx_rate: f32,
|
||||
pub rx_rate: f32,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct Page {
|
||||
pub rows: Vec<Row>,
|
||||
pub more: bool,
|
||||
}
|
||||
|
||||
pub(super) struct History {
|
||||
connection: Connection,
|
||||
}
|
||||
|
||||
// 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 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 })
|
||||
}
|
||||
|
||||
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 !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(&self, f: &Filter) -> Result<Page, String> {
|
||||
let mut sql = String::from(
|
||||
"SELECT id,key,tx,rx,ntx,nrx,last,sampled,tx_rate,rx_rate 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()));
|
||||
}
|
||||
if let Some(cursor) = f.before {
|
||||
sql.push_str(" AND id<?");
|
||||
args.push(Value::Integer(cursor));
|
||||
}
|
||||
sql.push_str(" ORDER BY id DESC 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)?,
|
||||
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,550 @@
|
||||
//! Live traffic inspector shared by the tray and Android clients.
|
||||
mod history;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod worker;
|
||||
|
||||
use crate::{
|
||||
format::{bytes, short},
|
||||
widgets,
|
||||
};
|
||||
use egui::{RichText, Ui};
|
||||
use egui_phosphor::regular as icon;
|
||||
use history::{Filter, Row};
|
||||
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, time::Duration};
|
||||
use tsunagi::{
|
||||
NetworkId,
|
||||
ipc::StatusReport,
|
||||
iroh_types::EndpointId,
|
||||
traffic::{Flow, FlowKey, IpDetail, Role},
|
||||
};
|
||||
pub use worker::Feed;
|
||||
use worker::Worker;
|
||||
|
||||
type Id = [u8; 32];
|
||||
#[derive(Default)]
|
||||
struct Network {
|
||||
name: String,
|
||||
peers: BTreeMap<Id, String>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Names {
|
||||
networks: BTreeMap<Id, Network>,
|
||||
generation: Option<u64>,
|
||||
}
|
||||
|
||||
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) {
|
||||
let Some(report) = report else { return };
|
||||
if self.generation == Some(generation) {
|
||||
return;
|
||||
}
|
||||
self.generation = Some(generation);
|
||||
for n in &report.networks {
|
||||
let Ok(id) = n.network_id.parse::<NetworkId>() else {
|
||||
continue;
|
||||
};
|
||||
let entry = self.networks.entry(*id.as_bytes()).or_default();
|
||||
entry.name = n.name.clone();
|
||||
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()),
|
||||
)))
|
||||
{
|
||||
if let Ok(peer) = key.parse::<EndpointId>() {
|
||||
let label = name.filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
let current = entry
|
||||
.peers
|
||||
.entry(*peer.as_bytes())
|
||||
.or_insert_with(|| short(key));
|
||||
if let Some(label) = label {
|
||||
*current = label;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 role_text(role: Role) -> String {
|
||||
let glyph = match role {
|
||||
Role::ViaExit => icon::SIGN_OUT,
|
||||
Role::ServeExit => icon::SIGN_IN,
|
||||
Role::Relay => icon::GIT_FORK,
|
||||
Role::Broadcast => icon::BROADCAST,
|
||||
Role::SpeedTest => icon::GAUGE,
|
||||
_ => return role_name(role).to_owned(),
|
||||
};
|
||||
format!("{glyph} {}", role_name(role))
|
||||
}
|
||||
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<i64>>,
|
||||
selected: Option<i64>,
|
||||
}
|
||||
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::default(),
|
||||
filter: Filter::default(),
|
||||
keep: false,
|
||||
previous: Vec::new(),
|
||||
selected: None,
|
||||
}
|
||||
}
|
||||
/// 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) {
|
||||
ui.horizontal_wrapped(|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;
|
||||
}
|
||||
widgets::hint(ui.checkbox(&mut self.keep,"Keep until close"),
|
||||
"Keep inactive flows for this window session. Otherwise they expire after 60 seconds.");
|
||||
});
|
||||
let width = ((ui.available_width() - ui.spacing().item_spacing.x) / 2.).clamp(60., 135.);
|
||||
if ui.available_width() < 580. {
|
||||
ui.horizontal(|ui| self.identity_filters(ui, width));
|
||||
ui.horizontal(|ui| self.flow_filters(ui, width));
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
self.identity_filters(ui, width);
|
||||
self.flow_filters(ui, width);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
self.names.refresh(report, generation);
|
||||
let before = self.filter.clone();
|
||||
let keep = self.keep;
|
||||
self.controls(ui);
|
||||
if self.filter != before {
|
||||
self.filter.before = None;
|
||||
self.previous.clear();
|
||||
self.selected = None;
|
||||
}
|
||||
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();
|
||||
let wide = ui.available_width() >= 690.;
|
||||
if !self.previous.is_empty() || page.more {
|
||||
ui.horizontal(|ui| {
|
||||
if ui
|
||||
.add_enabled(
|
||||
!self.previous.is_empty(),
|
||||
egui::Button::new(format!("{} Newer", icon::CARET_LEFT)),
|
||||
)
|
||||
.clicked()
|
||||
&& let Some(cursor) = self.previous.pop()
|
||||
{
|
||||
self.filter.before = cursor;
|
||||
self.selected = None;
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
ui.weak(format!("Page {}", self.previous.len() + 1));
|
||||
if ui
|
||||
.add_enabled(
|
||||
page.more,
|
||||
egui::Button::new(format!("Older {}", icon::CARET_RIGHT)),
|
||||
)
|
||||
.clicked()
|
||||
&& let Some(r) = page.rows.last()
|
||||
{
|
||||
self.previous.push(self.filter.before);
|
||||
self.filter.before = Some(r.id);
|
||||
self.selected = None;
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
});
|
||||
}
|
||||
if page.rows.is_empty() {
|
||||
ui.add_space(14.);
|
||||
ui.weak(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 {
|
||||
if wide {
|
||||
desktop_header(ui);
|
||||
}
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("flow-rows")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
for row in &page.rows {
|
||||
let chosen = self.selected == Some(row.id);
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(5, 3))
|
||||
.fill(if chosen {
|
||||
ui.visuals().selection.bg_fill
|
||||
} else if row.id % 2 == 0 {
|
||||
ui.visuals().faint_bg_color
|
||||
} else {
|
||||
egui::Color32::TRANSPARENT
|
||||
})
|
||||
.show(ui, |ui| {
|
||||
let summary = ui.scope(|ui| self.row(ui, row, now, wide)).response;
|
||||
let selected = ui.interact(
|
||||
summary.rect,
|
||||
ui.id().with(("flow", row.id)),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
if selected.clicked() {
|
||||
self.selected = if chosen { None } else { Some(row.id) };
|
||||
}
|
||||
|
||||
if chosen {
|
||||
ui.separator();
|
||||
let key = &row.data.key;
|
||||
let (a, b, p) = endpoints(key, &self.names);
|
||||
ui.label(format!("{a} ↔ {b} · {p}"));
|
||||
ui.label(format!(
|
||||
"{} {} packets sent {} {} received",
|
||||
icon::ARROW_UP,
|
||||
row.data.tx_packets,
|
||||
icon::ARROW_DOWN,
|
||||
row.data.rx_packets
|
||||
));
|
||||
let id = public_id(&key.peer);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak("Peer ID");
|
||||
crate::format::copy_field(ui, &short(&id), &id);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.ctx().request_repaint_after(Duration::from_secs(1));
|
||||
}
|
||||
|
||||
fn row(&self, ui: &mut Ui, r: &Row, now: u64, wide: bool) {
|
||||
let k = &r.data.key;
|
||||
let (a, b, p) = endpoints(k, &self.names);
|
||||
let network = self.names.network(&k.network);
|
||||
let peer = self.names.peer(&k.network, &k.peer);
|
||||
let role = role_text(k.role);
|
||||
let current = now.saturating_sub(r.sampled) < 1900;
|
||||
let rates = |n: f32| format!("{}/s", bytes(if current { n as f64 } else { 0. }));
|
||||
let (tx, rx) = (bytes(r.data.tx_bytes as f64), bytes(r.data.rx_bytes as f64));
|
||||
let age = ago(now.saturating_sub(r.last));
|
||||
if wide {
|
||||
let widths = widths(ui);
|
||||
ui.horizontal(|ui| {
|
||||
cell(ui, widths[0], &peer, &network);
|
||||
cell(ui, widths[1], &a, &b);
|
||||
cell(ui, widths[2], &p, &role);
|
||||
cell(ui, widths[3], &tx, &rates(r.tx_rate));
|
||||
cell(ui, widths[4], &rx, &rates(r.rx_rate));
|
||||
cell(ui, widths[5], &age, "");
|
||||
});
|
||||
} else {
|
||||
ui.set_min_width(ui.available_width());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(peer);
|
||||
ui.weak(&network);
|
||||
ui.label(role);
|
||||
ui.weak(age);
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(&p);
|
||||
ui.monospace(&a);
|
||||
ui.weak("↔");
|
||||
ui.monospace(&b);
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(format!("{} {tx}", icon::ARROW_UP))
|
||||
.on_hover_text("Sent");
|
||||
ui.weak(rates(r.tx_rate));
|
||||
ui.separator();
|
||||
ui.label(format!("{} {rx}", icon::ARROW_DOWN))
|
||||
.on_hover_text("Received");
|
||||
ui.weak(rates(r.rx_rate));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
fn widths(ui: &Ui) -> [f32; 6] {
|
||||
let usable = (ui.available_width() - ui.spacing().item_spacing.x * 5. - 4.).max(0.);
|
||||
[0.18, 0.30, 0.18, 0.13, 0.13, 0.08].map(|s| s * usable)
|
||||
}
|
||||
fn cell(ui: &mut Ui, width: f32, one: &str, two: &str) {
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(width, 0.),
|
||||
egui::Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
ui.add(egui::Label::new(one).truncate()).on_hover_text(one);
|
||||
if !two.is_empty() {
|
||||
ui.add(egui::Label::new(RichText::new(two).weak().small()).truncate())
|
||||
.on_hover_text(two);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
fn desktop_header(ui: &mut Ui) {
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(5, 2))
|
||||
.show(ui, |ui| {
|
||||
let widths = widths(ui);
|
||||
ui.horizontal(|ui| {
|
||||
for ((title, hint), width) in [
|
||||
("Peer / network", "Authenticated peer and local network"),
|
||||
(
|
||||
"Endpoints",
|
||||
"This side ↔ peer side. Encrypted relay shows the two named endpoints.",
|
||||
),
|
||||
(
|
||||
"Protocol / role",
|
||||
"IP protocol or transport observation and forwarding role",
|
||||
),
|
||||
(
|
||||
"↑ Sent",
|
||||
"Total and rate toward the peer (first to second endpoint for relay)",
|
||||
),
|
||||
(
|
||||
"↓ Received",
|
||||
"Total and rate from the peer (second to first endpoint for relay)",
|
||||
),
|
||||
("Seen", "Time since last activity"),
|
||||
]
|
||||
.into_iter()
|
||||
.zip(widths)
|
||||
{
|
||||
ui.add_sized(
|
||||
[width, 17.],
|
||||
egui::Label::new(RichText::new(title).small().weak())
|
||||
.halign(egui::Align::Min)
|
||||
.truncate(),
|
||||
)
|
||||
.on_hover_text(hint);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
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().id),
|
||||
..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 live_monitor_has_readable_rows_inside_phone_and_desktop_widths() {
|
||||
use super::Window;
|
||||
use std::time::{Duration, Instant};
|
||||
let mut win = Window::new(None);
|
||||
let feed = win.feed();
|
||||
assert!(win.worker.view().0.rows.is_empty());
|
||||
feed.sample(TrafficSnapshot {
|
||||
flows: vec![sample(55201, true)],
|
||||
interval_ms: 1_000,
|
||||
omitted: 0,
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while win.worker.view().0.rows.is_empty() {
|
||||
assert!(Instant::now() < deadline, "worker did not publish the flow");
|
||||
std::thread::yield_now();
|
||||
}
|
||||
for width in [320., 390., 720., 900.] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
let frame = ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 600.),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
win.show(ui, None, 0);
|
||||
assert!(
|
||||
ui.min_rect().right() <= width,
|
||||
"monitor grew beyond {width}: {:?}",
|
||||
ui.min_rect()
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
for value in ["10.0.0.1:55201", "10.0.0.2:443", "TCP", "Mesh"] {
|
||||
assert!(frame.shapes.iter().any(|s|matches!(&s.shape,egui::Shape::Text(t) if t.galley.text().contains(value) && t.visual_bounding_rect().right()<=width)), "{value} outside {width}");
|
||||
}
|
||||
}
|
||||
drop(win);
|
||||
assert!(!feed.sample(TrafficSnapshot::default()));
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
use super::history::{Filter, History, Page};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
path::PathBuf,
|
||||
sync::{Arc, Condvar, Mutex, MutexGuard},
|
||||
time::Instant,
|
||||
};
|
||||
use tsunagi::traffic::TrafficSnapshot;
|
||||
|
||||
struct Work {
|
||||
samples: VecDeque<(u64, TrafficSnapshot)>,
|
||||
filter: Filter,
|
||||
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(),
|
||||
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 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) = {
|
||||
let w = shared.lock();
|
||||
let mut w = shared
|
||||
.wake
|
||||
.wait_while(w, |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)
|
||||
};
|
||||
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 {
|
||||
w.page = page;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,3 +260,109 @@ 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.7"
|
||||
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.7" }
|
||||
iroh.workspace = true
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -584,6 +584,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 +607,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());
|
||||
|
||||
@@ -256,6 +256,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 +432,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.7"
|
||||
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.7" }
|
||||
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.7"
|
||||
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.7" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.7", features = ["tun-device", "dns-publish"] }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.7" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.7" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.7" }
|
||||
iroh.workspace = true
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -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,
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ let
|
||||
in
|
||||
rustPlatform.buildRustPackage {
|
||||
pname = if withTray then "tsunagi" else "tsunagi-cli";
|
||||
version = "1.0.6";
|
||||
version = "1.0.7";
|
||||
|
||||
src = lib.cleanSource ../.;
|
||||
cargoLock.lockFile = ../Cargo.lock;
|
||||
|
||||
Reference in new issue
Block a user