Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7afed15f76 | ||
|
|
e7de9b44af | ||
|
|
200e716c28 | ||
|
|
fb7a959d23 | ||
|
|
6a0a87e76c |
No files matched your search
@@ -5,6 +5,12 @@ on:
|
||||
branches: [master]
|
||||
paths:
|
||||
- '.github/workflows/subnet-source.yml'
|
||||
- 'crates/tsunagi-core/src/overlay/egress.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/egress/**'
|
||||
- 'crates/tsunagi-core/src/overlay/interface.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/router.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/linux_exit*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/linux.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/macos*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/hostrules/windows*.rs'
|
||||
- 'crates/tsunagi-core/src/overlay/provision/macos.rs'
|
||||
@@ -27,6 +33,8 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
test: overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit
|
||||
- os: macos-latest
|
||||
test: overlay::provision::macos::tests::unbound_sockets_choose_each_networks_source_on_one_real_utun
|
||||
- os: windows-latest
|
||||
@@ -53,6 +61,10 @@ jobs:
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
if ($tests -notcontains "$($env:TEST_NAME): test") { throw "Missing ignored test: $env:TEST_NAME" }
|
||||
"TEST_BINARY=$binary" >> $env:GITHUB_ENV
|
||||
- name: Verify separate forwarding and local egress in Linux namespaces
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
|
||||
- name: Verify source selection on a real utun
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
@@ -65,6 +77,9 @@ jobs:
|
||||
EXIT_TEST: overlay::hostrules::macos_exit::kernel::exit_preserves_underlay_and_both_meshes
|
||||
run: |
|
||||
"$TEST_BINARY" --ignored --exact "$EXIT_TEST" --list | grep -Fx "$EXIT_TEST: test"
|
||||
previous=$(sysctl -n net.inet.ip.forwarding)
|
||||
trap 'sudo -n sysctl -w "net.inet.ip.forwarding=$previous"' EXIT
|
||||
sudo -n sysctl -w net.inet.ip.forwarding=1
|
||||
sudo -n -- "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --nocapture
|
||||
- name: Verify source selection on a real Wintun adapter
|
||||
if: runner.os == 'Windows'
|
||||
@@ -81,6 +96,16 @@ jobs:
|
||||
Copy-Item (Join-Path $directory 'wintun/bin/amd64/wintun.dll') (Split-Path -Parent $env:TEST_BINARY)
|
||||
& $env:TEST_BINARY --ignored --exact $env:TEST_NAME --nocapture
|
||||
exit $LASTEXITCODE
|
||||
- name: Verify forwarded and local traffic to the same destination
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
timeout-minutes: 2
|
||||
run: |
|
||||
$test = 'overlay::egress::tests::physical_member_sockets_survive_a_more_specific_wintun_route'
|
||||
$listing = @(& $env:TEST_BINARY --ignored --exact $test --list)
|
||||
if ($listing -notcontains "${test}: test") { throw "Missing ignored test $test" }
|
||||
& $env:TEST_BINARY --ignored --exact $test --nocapture
|
||||
exit $LASTEXITCODE
|
||||
- name: Verify one Windows exit bypass route through the physical gateway
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
|
||||
Generated
+22
-10
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -6320,7 +6320,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"egui",
|
||||
@@ -6344,7 +6344,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"iroh",
|
||||
@@ -6359,7 +6359,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -6385,6 +6385,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"simple-dns",
|
||||
"smoltcp",
|
||||
"socket2",
|
||||
"subtle",
|
||||
"tempfile",
|
||||
"thiserror 2.0.20",
|
||||
@@ -6394,6 +6395,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsunagi-core",
|
||||
"tsunagi-speedtest",
|
||||
"tun",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
@@ -6402,7 +6404,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -6413,9 +6415,19 @@ dependencies = [
|
||||
"tsunagi-wireguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-speedtest"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"postcard",
|
||||
"serde",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"caps",
|
||||
@@ -6435,7 +6447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui-phosphor",
|
||||
@@ -6451,7 +6463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
@@ -6461,7 +6473,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wg-quic"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
@@ -6488,7 +6500,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
|
||||
@@ -145,6 +145,21 @@ change applies on the next start. In the tray or on Android, click the network
|
||||
name to expand its card. Open **data transports** to enable transports and set
|
||||
their initial preference order. **Show devices** lists peers and their reported
|
||||
Tsunagi versions. On Android, tap a device to see its version and traffic.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
Adjacent peers need a common external transport at the same wire version.
|
||||
Peers that both support link comparison probe another mutually enabled transport
|
||||
while traffic continues on the current one. They can switch to a faster healthy link.
|
||||
|
||||
@@ -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.4')
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.6')
|
||||
ndk { abiFilters abi }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,9 @@ class MeshVpn : VpnService() {
|
||||
@Volatile private var upstream: Network? = null
|
||||
private val changes = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) = useUnderlay(network)
|
||||
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
|
||||
if (network == upstream && !closed) Native.setMetered(instance, isMetered(capabilities))
|
||||
}
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
|
||||
if (network == upstream && !closed) updateAddresses(properties)
|
||||
}
|
||||
@@ -50,11 +53,15 @@ class MeshVpn : VpnService() {
|
||||
// Falling back to the default network here could send iroh into its own TUN.
|
||||
setUnderlyingNetworks(emptyArray())
|
||||
physicalAddresses = ""
|
||||
Native.setMetered(instance, true)
|
||||
Native.networkChanged(instance, "")
|
||||
}
|
||||
}
|
||||
|
||||
private var physicalAddresses = ""
|
||||
// Query the network the agent actually uses, even while its VPN is the app default.
|
||||
private fun isMetered(capabilities: NetworkCapabilities?) =
|
||||
capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) != true
|
||||
private fun addresses(properties: LinkProperties?) = properties?.linkAddresses.orEmpty()
|
||||
.mapNotNull { it.address.hostAddress?.substringBefore('%') }.distinct().take(32).joinToString(",")
|
||||
private fun updateAddresses(properties: LinkProperties) {
|
||||
@@ -69,10 +76,14 @@ class MeshVpn : VpnService() {
|
||||
upstream = network
|
||||
setUnderlyingNetworks(arrayOf(network))
|
||||
physicalAddresses = addresses(connectivity.getLinkProperties(network))
|
||||
val metered = isMetered(connectivity.getNetworkCapabilities(network))
|
||||
if (instance == 0L) {
|
||||
Native.trust(applicationContext)
|
||||
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses)
|
||||
} else Native.networkChanged(instance, physicalAddresses)
|
||||
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses, metered)
|
||||
} else {
|
||||
Native.setMetered(instance, metered)
|
||||
Native.networkChanged(instance, physicalAddresses)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
|
||||
@@ -6,12 +6,13 @@ import android.content.Context
|
||||
internal object Native {
|
||||
init { System.loadLibrary("tsunagi_android") }
|
||||
external fun trust(context: Context)
|
||||
external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String): Long
|
||||
external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String, metered: Boolean): Long
|
||||
external fun failed(instance: Long): Boolean
|
||||
external fun stop(instance: Long)
|
||||
external fun disconnectExit(instance: Long, network: String, peer: String): Boolean
|
||||
external fun tileExit(instance: Long, network: String, peer: String, connect: Boolean, waitForDiscovery: Boolean): String?
|
||||
external fun networkChanged(instance: Long, addresses: String)
|
||||
external fun setMetered(instance: Long, metered: Boolean)
|
||||
|
||||
external fun surface()
|
||||
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean, landscape: Boolean): Long
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
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.4" }
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.6" }
|
||||
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||
|
||||
@@ -4,7 +4,7 @@ mod display;
|
||||
mod dns;
|
||||
use crate::{
|
||||
plan::VpnPlan,
|
||||
service::{Reply, Request, Response, State},
|
||||
service::{Reply, Request, Response, ServiceSignals, State},
|
||||
tun::AndroidTun,
|
||||
};
|
||||
use jni::{
|
||||
@@ -29,7 +29,7 @@ struct Session {
|
||||
commands: mpsc::Sender<(Request, Reply)>,
|
||||
state: watch::Receiver<State>,
|
||||
underlay: watch::Sender<Vec<std::net::IpAddr>>,
|
||||
stop: watch::Sender<bool>,
|
||||
signals: watch::Sender<ServiceSignals>,
|
||||
}
|
||||
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||
// Stop/start can cross on the Android main thread. The previous agent closes
|
||||
@@ -44,9 +44,14 @@ fn status() -> State {
|
||||
let Some(session) = current.as_mut() else {
|
||||
return State::Off;
|
||||
};
|
||||
let state = session.state.borrow().clone();
|
||||
let report = match &state {
|
||||
State::Ready(report, _) => Some(report.as_ref()),
|
||||
_ => None,
|
||||
};
|
||||
if session
|
||||
.last_refresh
|
||||
.is_none_or(|last| last.elapsed() >= std::time::Duration::from_secs(2))
|
||||
.is_none_or(|last| last.elapsed() >= tsunagi_ui::client::status_poll_interval(report))
|
||||
&& session
|
||||
.commands
|
||||
.try_send((Request::Refresh, oneshot::channel().0))
|
||||
@@ -54,7 +59,7 @@ fn status() -> State {
|
||||
{
|
||||
session.last_refresh = Some(std::time::Instant::now());
|
||||
}
|
||||
session.state.borrow().clone()
|
||||
state
|
||||
}
|
||||
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||
let (reply, result) = oneshot::channel();
|
||||
@@ -131,6 +136,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
state_dir: JString,
|
||||
cache_dir: JString,
|
||||
addresses: JString,
|
||||
metered: jni::sys::jboolean,
|
||||
) -> jlong {
|
||||
let result = (|| -> Result<i64, Box<dyn std::error::Error>> {
|
||||
// Keep the application (never an activity) alive for DNS throughout the process.
|
||||
@@ -188,18 +194,21 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
let (underlay, physical) = watch::channel(underlay_ips(&addresses));
|
||||
let (commands, rx) = mpsc::channel(16);
|
||||
let (state, state_rx) = watch::channel(State::Starting);
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
let (signals, updates) = watch::channel(ServiceSignals {
|
||||
stopped: false,
|
||||
metered: metered != 0,
|
||||
});
|
||||
static NEXT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
|
||||
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut slot = current();
|
||||
if let Some(old) = slot.as_ref() {
|
||||
old.stop.send_replace(true);
|
||||
old.signals.send_modify(|s| s.stopped = true);
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name("tsunagi-agent".into())
|
||||
.spawn(move || {
|
||||
let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if *stopped.borrow() {
|
||||
if updates.borrow().stopped {
|
||||
return;
|
||||
}
|
||||
let run = || -> Result<(), Box<dyn std::error::Error>> {
|
||||
@@ -226,7 +235,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
.await?;
|
||||
let agent = Agent::spawn(config).await?;
|
||||
let _listeners = carriers.listen(&agent);
|
||||
crate::service::serve(agent, wg, dns, rx, &state, stopped, |notice| {
|
||||
crate::service::serve(agent, wg, dns, rx, &state, updates, |notice| {
|
||||
update_exit_notification(¬ice_vm, ¬ice_service, id, notice);
|
||||
})
|
||||
.await;
|
||||
@@ -243,7 +252,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
commands,
|
||||
state: state_rx,
|
||||
underlay,
|
||||
stop,
|
||||
signals,
|
||||
});
|
||||
Ok(id)
|
||||
})();
|
||||
@@ -400,7 +409,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_stop(_: JNIEnv, _: JObject, id:
|
||||
if slot.as_ref().is_some_and(|s| s.id == id)
|
||||
&& let Some(session) = slot.take()
|
||||
{
|
||||
session.stop.send_replace(true);
|
||||
session.signals.send_modify(|s| s.stopped = true);
|
||||
}
|
||||
}
|
||||
fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
|
||||
@@ -411,6 +420,21 @@ fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
|
||||
.collect()
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_setMetered(
|
||||
_: JNIEnv,
|
||||
_: JObject,
|
||||
id: jlong,
|
||||
metered: jni::sys::jboolean,
|
||||
) {
|
||||
if let Some(s) = current().as_ref().filter(|s| s.id == id) {
|
||||
s.signals.send_if_modified(|signals| {
|
||||
let changed = signals.metered != (metered != 0);
|
||||
signals.metered = metered != 0;
|
||||
changed
|
||||
});
|
||||
}
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_networkChanged(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
|
||||
@@ -34,6 +34,15 @@ pub enum Request {
|
||||
},
|
||||
}
|
||||
|
||||
/// The latest service lifecycle and cost of the physical network Android selected.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct ServiceSignals {
|
||||
/// End this instance.
|
||||
pub stopped: bool,
|
||||
/// Android reports that data on the current underlay may be billed.
|
||||
pub metered: bool,
|
||||
}
|
||||
|
||||
/// A configured default route stays visible if its remote peer goes offline.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ExitNotice {
|
||||
@@ -158,6 +167,14 @@ pub type Response = tokio::sync::oneshot::Receiver<Result<Outcome, String>>;
|
||||
pub async fn apply(
|
||||
command: Command,
|
||||
agent: &Agent,
|
||||
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
|
||||
apply_on_link(command, agent, false).await
|
||||
}
|
||||
|
||||
async fn apply_on_link(
|
||||
command: Command,
|
||||
agent: &Agent,
|
||||
metered: bool,
|
||||
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
|
||||
match command {
|
||||
Command::Join { name, secret } => {
|
||||
@@ -201,6 +218,16 @@ pub async fn apply(
|
||||
.set_exit_via(network_id.parse()?, peer.map(|p| p.parse()).transpose()?)
|
||||
.await?
|
||||
}
|
||||
Command::StartSpeedTest { network_id, peer } => {
|
||||
agent
|
||||
.start_speed_test(
|
||||
network_id.parse()?,
|
||||
peer.map(|p| p.parse()).transpose()?,
|
||||
metered,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Command::StopSpeedTest { network_id } => agent.stop_speed_test(network_id.parse()?),
|
||||
Command::SetExitOffer { .. } => {
|
||||
return Err("This phone can only use a remote exit node.".into());
|
||||
}
|
||||
@@ -293,7 +320,7 @@ pub async fn serve(
|
||||
dns: crate::dns::Resolver,
|
||||
mut commands: mpsc::Receiver<(Request, Reply)>,
|
||||
state: &watch::Sender<State>,
|
||||
mut stop: watch::Receiver<bool>,
|
||||
mut signals: watch::Receiver<ServiceSignals>,
|
||||
mut publish_exit: impl FnMut(Option<&ExitNotice>),
|
||||
) {
|
||||
let mut roster = agent.watch_roster();
|
||||
@@ -301,10 +328,20 @@ pub async fn serve(
|
||||
let mut cached_zones = None;
|
||||
let mut retry = false;
|
||||
let mut published_exit = None;
|
||||
let mut link = *signals.borrow_and_update();
|
||||
agent.set_speed_test_metered(link.metered);
|
||||
loop {
|
||||
if link.stopped {
|
||||
break;
|
||||
}
|
||||
let (reply, mut refresh_zones) = tokio::select! {
|
||||
biased;
|
||||
_ = async { drop(stop.wait_for(|stopped| *stopped).await) } => break,
|
||||
changed = signals.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
link = *signals.borrow_and_update();
|
||||
agent.set_speed_test_metered(link.metered);
|
||||
continue;
|
||||
}
|
||||
command = commands.recv() => {
|
||||
let Some((request, reply)) = command else { break };
|
||||
let refresh_zones = !matches!(request, Request::Refresh);
|
||||
@@ -314,7 +351,7 @@ pub async fn serve(
|
||||
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||
dns.replace(None);
|
||||
}
|
||||
apply(cmd, &agent).await.map_err(|e| e.to_string())
|
||||
apply_on_link(cmd, &agent, link.metered).await.map_err(|e| e.to_string())
|
||||
}
|
||||
Request::NetworkChanged => {
|
||||
agent.endpoint().network_change().await;
|
||||
|
||||
@@ -24,7 +24,7 @@ async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand
|
||||
.await
|
||||
.unwrap();
|
||||
let (state, mut snapshots) = watch::channel(State::Starting);
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
let (stop, stopped) = watch::channel(crate::service::ServiceSignals::default());
|
||||
let (commands, requests) = mpsc::channel(4);
|
||||
let agent = phone.agent.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
@@ -59,7 +59,7 @@ async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand
|
||||
tokio::time::timeout(Duration::from_secs(5), snapshots.wait_for(|s| {
|
||||
matches!(s, State::Ready(r, _) if r.dns.as_ref().is_some_and(|d| d.zones.iter().any(|z| z == "background-mesh")))
|
||||
})).await.unwrap().unwrap();
|
||||
stop.send_replace(true);
|
||||
stop.send_modify(|s| s.stopped = true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
|
||||
.unwrap();
|
||||
let agent = phone.agent.clone();
|
||||
let (commands, requests) = mpsc::channel(4);
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
let (stop, stopped) = watch::channel(crate::service::ServiceSignals::default());
|
||||
let (published, mut notices) = watch::channel(None);
|
||||
let (state, mut live) = watch::channel(State::Starting);
|
||||
let task = tokio::spawn(async move {
|
||||
@@ -225,7 +225,7 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
|
||||
.unwrap();
|
||||
notice_matching(&mut notices, Option::is_none).await;
|
||||
assert!(phone.agent.is_active(id).await);
|
||||
stop.send_replace(true);
|
||||
stop.send_modify(|s| s.stopped = true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
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.4"
|
||||
version = "1.0.6"
|
||||
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"]
|
||||
@@ -35,6 +35,7 @@ dns-publish = ["dep:zbus"]
|
||||
testing = ["dep:tempfile", "dep:tracing-subscriber"]
|
||||
|
||||
[dependencies]
|
||||
tsunagi-speedtest = { path = "../tsunagi-speedtest", version = "0.1.0" }
|
||||
arc-swap = "1.9"
|
||||
iroh.workspace = true
|
||||
# `net` for the local control interface: a Unix socket on Unix, a named pipe
|
||||
@@ -98,13 +99,18 @@ futures-util = { version = "0.3", default-features = false, optional = true }
|
||||
# before deciding what to change. Creating an adapter needs the process to be
|
||||
# elevated and `wintun.dll` to be reachable at run time.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Networking_WinSock",
|
||||
"Win32_Security",
|
||||
"Win32_Security_Authorization",
|
||||
"Win32_Foundation",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
# Its own tests use the harness it publishes.
|
||||
tsunagi-core = { path = ".", features = ["testing"] }
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "process", "test-util"] }
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::time::Duration;
|
||||
|
||||
use iroh::EndpointId;
|
||||
|
||||
use crate::identity::NetworkId;
|
||||
use crate::identity::{NetworkId, NetworkName};
|
||||
use crate::net::TransportKind;
|
||||
use crate::proto::ControlMessage;
|
||||
use crate::proto::handshake::Role;
|
||||
@@ -48,8 +48,12 @@ pub enum Event {
|
||||
PeerDisconnected {
|
||||
/// The network the session belonged to.
|
||||
network: NetworkId,
|
||||
/// Its locally configured name.
|
||||
network_name: NetworkName,
|
||||
/// The peer.
|
||||
peer: EndpointId,
|
||||
/// Last known name of the authenticated peer, when available.
|
||||
hostname: Option<String>,
|
||||
/// Why the session ended. Free of secrets.
|
||||
reason: String,
|
||||
},
|
||||
|
||||
@@ -22,6 +22,7 @@ mod events;
|
||||
mod network;
|
||||
mod session;
|
||||
mod shutdown;
|
||||
mod speed;
|
||||
mod status;
|
||||
|
||||
pub use events::Event;
|
||||
@@ -95,6 +96,7 @@ pub struct Agent {
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
config: AgentConfig,
|
||||
speed: speed::SpeedTests,
|
||||
limits: Arc<Limits>,
|
||||
storage: Storage,
|
||||
identity: DeviceIdentity,
|
||||
@@ -220,6 +222,9 @@ impl PacketSink for Sink {
|
||||
let Some(inner) = self.0.upgrade() else {
|
||||
return;
|
||||
};
|
||||
if speed::receive_packet(&inner, network, peer, &packet) {
|
||||
return;
|
||||
}
|
||||
let Some(interface) = inner.interface.get() else {
|
||||
return;
|
||||
};
|
||||
@@ -444,6 +449,7 @@ impl Agent {
|
||||
|
||||
let (range_changed, range_updates) = watch::channel(());
|
||||
let inner = Arc::new(Inner {
|
||||
speed: speed::SpeedTests::default(),
|
||||
limits,
|
||||
storage,
|
||||
identity,
|
||||
@@ -511,7 +517,8 @@ impl Agent {
|
||||
.tun_factory
|
||||
.as_ref()
|
||||
.map(|_| Arc::new(Sink(Arc::downgrade(&inner))) as Arc<dyn PacketSink>);
|
||||
let context = PluginContext::new(plugin_tx, inner.identity.endpoint_id(), sink);
|
||||
let context =
|
||||
PluginContext::new(plugin_tx, inner.identity.endpoint_id(), sink, &inner.routes);
|
||||
if let Some(tunnel) = &inner.config.tunnel {
|
||||
tunnel.attach(context);
|
||||
}
|
||||
@@ -1006,6 +1013,7 @@ impl Agent {
|
||||
self.inner.ensure_interface().await;
|
||||
}
|
||||
let handle = network::spawn(RuntimeParams {
|
||||
agent: Arc::downgrade(&self.inner),
|
||||
vips,
|
||||
retirements,
|
||||
broadcast,
|
||||
@@ -1079,6 +1087,7 @@ impl Agent {
|
||||
}
|
||||
|
||||
async fn stop_network_locked(&self, network_id: NetworkId) -> Result<()> {
|
||||
self.inner.speed.remove_network(network_id);
|
||||
let handle = {
|
||||
let mut networks = self.inner.networks.write().await;
|
||||
networks
|
||||
@@ -1315,6 +1324,7 @@ impl Agent {
|
||||
})
|
||||
.collect();
|
||||
networks.push(NetworkStatus {
|
||||
speed: Default::default(),
|
||||
vips,
|
||||
protocols: self.effective_protocols(stored.protocols.as_ref()),
|
||||
auto_start: stored.auto_start,
|
||||
@@ -1394,6 +1404,7 @@ impl Agent {
|
||||
/// After this returns, the state directory can be opened by another agent.
|
||||
pub async fn shutdown(&self) {
|
||||
self.inner.shutdown.trigger();
|
||||
self.inner.speed.shutdown();
|
||||
let lifecycle_guard = self.inner.lifecycle.lock().await;
|
||||
|
||||
let handles: Vec<NetworkHandle> = {
|
||||
|
||||
@@ -177,6 +177,7 @@ impl NetworkHandle {
|
||||
|
||||
/// Everything a network runtime needs to run.
|
||||
pub(crate) struct RuntimeParams {
|
||||
pub(super) agent: std::sync::Weak<super::Inner>,
|
||||
pub(crate) vips: crate::vip::VipSet,
|
||||
pub(crate) retirements: Vec<SignedRetirement>,
|
||||
pub(crate) broadcast: bool,
|
||||
@@ -656,7 +657,7 @@ impl Runtime {
|
||||
message,
|
||||
reply,
|
||||
} => {
|
||||
if matches!(&message, ControlMessage::Transport { .. })
|
||||
if matches!(&message, ControlMessage::Transport { protocol, .. } if protocol != tsunagi_speedtest::PROTOCOL)
|
||||
&& let Some(interface) = self.params.interface.clone()
|
||||
{
|
||||
// Locally bound pair sockets must be protected before their
|
||||
@@ -2691,6 +2692,9 @@ impl Runtime {
|
||||
return;
|
||||
}
|
||||
if let Some(old) = self.sessions.remove(&peer) {
|
||||
if let Some(inner) = self.params.agent.upgrade() {
|
||||
inner.speed.disconnected(self.network_id, peer);
|
||||
}
|
||||
old.abort();
|
||||
old.conn
|
||||
.close(0u32.into(), b"replaced by preferred session");
|
||||
@@ -2779,6 +2783,12 @@ impl Runtime {
|
||||
if self.params.carriers.len() > 1 {
|
||||
capabilities.push(selection::capability());
|
||||
}
|
||||
if self.params.interface.is_some()
|
||||
&& self.params.tunnel.is_some()
|
||||
&& !self.params.carriers.is_empty()
|
||||
{
|
||||
capabilities.push(super::speed::capability());
|
||||
}
|
||||
capabilities.truncate(self.params.limits.max_capabilities);
|
||||
self.local_capabilities = capabilities
|
||||
.iter()
|
||||
@@ -2855,13 +2865,21 @@ impl Runtime {
|
||||
SessionEvent::Closed {
|
||||
session_id,
|
||||
peer,
|
||||
reason,
|
||||
mut reason,
|
||||
} => {
|
||||
let current = self.sessions.get(&peer).map(|session| session.id);
|
||||
if current != Some(session_id) {
|
||||
return;
|
||||
}
|
||||
if let Some(inner) = self.params.agent.upgrade() {
|
||||
inner.speed.disconnected(self.network_id, peer);
|
||||
}
|
||||
if let Some(session) = self.sessions.remove(&peer) {
|
||||
// Read the cause before local cleanup closes a still-open connection.
|
||||
if let Some(cause) = session.conn.close_reason() {
|
||||
reason =
|
||||
format!("{reason} ({})", super::session::describe_quic_close(cause));
|
||||
}
|
||||
session.abort();
|
||||
session.conn.close(0u32.into(), b"session ended");
|
||||
}
|
||||
@@ -2885,7 +2903,13 @@ impl Runtime {
|
||||
self.params.roster_changed.send_replace(());
|
||||
self.emit(Event::PeerDisconnected {
|
||||
network: self.network_id,
|
||||
network_name: self.params.keys.name().clone(),
|
||||
peer,
|
||||
hostname: self
|
||||
.known_hostnames
|
||||
.get(&peer)
|
||||
.cloned()
|
||||
.or_else(|| self.state.hostname_of(&peer).map(str::to_owned)),
|
||||
reason,
|
||||
});
|
||||
}
|
||||
@@ -2923,6 +2947,25 @@ impl Runtime {
|
||||
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
|
||||
match &message {
|
||||
ControlMessage::Transport { protocol, payload } => {
|
||||
if protocol == tsunagi_speedtest::PROTOCOL {
|
||||
if super::speed::supported(&self.local_capabilities)
|
||||
&& let Some(session) = self.sessions.get(&peer)
|
||||
&& super::speed::supported(&session.capabilities)
|
||||
&& let Some(message) =
|
||||
tsunagi_speedtest::Control::decode(payload.as_bytes())
|
||||
&& let Some(inner) = self.params.agent.upgrade()
|
||||
&& let Some(reply) = super::speed::receive_control(
|
||||
&inner,
|
||||
self.network_id,
|
||||
peer,
|
||||
message,
|
||||
|| snapshot_connection(&session.conn).rtt,
|
||||
)
|
||||
{
|
||||
let _ = self.send_to(peer, reply);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if protocol == selection::PROTOCOL {
|
||||
self.receive_choice(peer, payload.as_bytes());
|
||||
return;
|
||||
@@ -2975,7 +3018,7 @@ impl Runtime {
|
||||
let changed = self.sessions.get(&peer).is_some_and(|session| {
|
||||
let selection = |caps: &[PluginCapability]| {
|
||||
caps.iter()
|
||||
.filter(|c| c.enabled)
|
||||
.filter(|c| c.enabled && c.protocol != tsunagi_speedtest::PROTOCOL)
|
||||
.map(|c| (c.protocol.clone(), c.version))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
@@ -3336,6 +3379,18 @@ impl Runtime {
|
||||
|
||||
let exit = self.exit_policy();
|
||||
NetworkStatus {
|
||||
speed: self
|
||||
.params
|
||||
.agent
|
||||
.upgrade()
|
||||
.map(|inner| {
|
||||
inner.speed.report(
|
||||
self.network_id,
|
||||
&peers,
|
||||
super::speed::supported(&self.local_capabilities),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
vips: self.params.routes.vips.statuses(self.network_id),
|
||||
protocols: self
|
||||
.params
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use iroh::EndpointId;
|
||||
use iroh::endpoint::{Connection, RecvStream, SendStream};
|
||||
use iroh::endpoint::{Connection, ConnectionError, RecvStream, SendStream};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
@@ -60,6 +60,22 @@ pub(crate) enum SessionEvent {
|
||||
},
|
||||
}
|
||||
|
||||
/// The transport category and code are useful in logs. Remote close text is
|
||||
/// arbitrary peer-supplied data and may contain secrets or control characters.
|
||||
pub(super) fn describe_quic_close(cause: ConnectionError) -> String {
|
||||
match cause {
|
||||
ConnectionError::ApplicationClosed(close) => {
|
||||
format!("QUIC closed by peer, application code {}", close.error_code)
|
||||
}
|
||||
ConnectionError::ConnectionClosed(close) => {
|
||||
format!("QUIC closed by peer, transport code {}", close.error_code)
|
||||
}
|
||||
ConnectionError::TransportError(error) => format!("QUIC transport error {}", error.code),
|
||||
ConnectionError::LocallyClosed => "QUIC closed locally".to_owned(),
|
||||
other => format!("QUIC: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A live session, as held by the network runtime.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Session {
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
//! Local ownership of one bounded throughput diagnostic. Control carries
|
||||
//! negotiation and receiver feedback. Every data packet uses the current cipher and carrier.
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, Weak};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use bytes::Bytes;
|
||||
use iroh::EndpointId;
|
||||
use tsunagi_speedtest as wire;
|
||||
|
||||
use super::{Agent, DataPath, Inner, PeerStatus};
|
||||
use crate::dataplane::PluginCapability;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::NetworkId;
|
||||
use crate::ipc::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
|
||||
use crate::proto::message::{ControlMessage, TransportPayload};
|
||||
|
||||
type Key = (NetworkId, EndpointId);
|
||||
|
||||
/// A batch can spend at most this many IPv4 bytes in *each* direction.
|
||||
/// Every remaining peer gets an equal reservation even when earlier probes are lost.
|
||||
const BATCH_BYTES: u32 = 128 * 1024 * 1024;
|
||||
const METERED_BATCH_BYTES: u32 = 16 * 1024 * 1024;
|
||||
|
||||
pub(super) fn capability() -> PluginCapability {
|
||||
PluginCapability {
|
||||
protocol: wire::PROTOCOL.into(),
|
||||
version: wire::VERSION,
|
||||
enabled: true,
|
||||
data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn supported(caps: &[PluginCapability]) -> bool {
|
||||
caps.iter()
|
||||
.any(|c| c.enabled && c.protocol == wire::PROTOCOL && c.version == wire::VERSION)
|
||||
}
|
||||
|
||||
fn envelope(message: &wire::Control) -> Option<ControlMessage> {
|
||||
Some(ControlMessage::Transport {
|
||||
protocol: wire::PROTOCOL.into(),
|
||||
payload: TransportPayload::new(message.encode().ok()?),
|
||||
})
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
}
|
||||
|
||||
struct Channel {
|
||||
key: Key,
|
||||
id: u64,
|
||||
limit: u32,
|
||||
handle: wire::Handle,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
generation: u64,
|
||||
network: NetworkId,
|
||||
batch: Option<SpeedBatchReport>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Jobs {
|
||||
job: Option<Job>,
|
||||
history: BTreeMap<Key, SpeedPeerReport>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SpeedTests {
|
||||
// Admission, completion and cancellation serialize here. Decrypted packets
|
||||
// only read the active channel and its receiver counter.
|
||||
jobs: Mutex<Jobs>,
|
||||
active: ArcSwapOption<Channel>,
|
||||
metered: AtomicBool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for SpeedTests {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SpeedTests").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl SpeedTests {
|
||||
fn lock(&self) -> MutexGuard<'_, Jobs> {
|
||||
self.jobs.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn clear_channel(&self, key: Key, id: u64) {
|
||||
// Called with the jobs lock held so an old task cannot clear its successor.
|
||||
if self
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.key == key && c.id == id)
|
||||
{
|
||||
self.active.store(None);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn report(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peers: &[PeerStatus],
|
||||
enabled: bool,
|
||||
) -> SpeedReport {
|
||||
let jobs = self.lock();
|
||||
SpeedReport {
|
||||
batch: jobs
|
||||
.job
|
||||
.as_ref()
|
||||
.filter(|j| j.network == network)
|
||||
.and_then(|j| j.batch),
|
||||
peers: jobs
|
||||
.history
|
||||
.iter()
|
||||
.filter(|((net, _), _)| *net == network)
|
||||
.map(|((_, peer), report)| (peer.to_string(), report.clone()))
|
||||
.collect(),
|
||||
capable: peers
|
||||
.iter()
|
||||
.filter(|p| enabled && supported(&p.capabilities))
|
||||
.map(|p| p.endpoint_id.to_string())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn disconnected(&self, network: NetworkId, peer: EndpointId) {
|
||||
if let Some(c) = self
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.key == (network, peer))
|
||||
{
|
||||
c.handle.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_locked(&self, jobs: &mut Jobs, network: NetworkId) {
|
||||
if let Some(c) = self.active.load().as_ref().filter(|c| c.key.0 == network) {
|
||||
c.handle.cancel();
|
||||
}
|
||||
if jobs.job.as_ref().is_some_and(|job| job.network == network) {
|
||||
jobs.job = None;
|
||||
for ((net, _), report) in &mut jobs.history {
|
||||
if *net == network
|
||||
&& matches!(
|
||||
report.phase,
|
||||
SpeedPhase::Queued
|
||||
| SpeedPhase::Preparing
|
||||
| SpeedPhase::Download
|
||||
| SpeedPhase::Upload
|
||||
)
|
||||
{
|
||||
match report.phase {
|
||||
SpeedPhase::Download => report.down = None,
|
||||
SpeedPhase::Upload => report.up = None,
|
||||
_ => {}
|
||||
}
|
||||
report.phase = SpeedPhase::Cancelled;
|
||||
report.measured_at_unix_secs = now();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn remove_network(&self, network: NetworkId) {
|
||||
let mut jobs = self.lock();
|
||||
self.cancel_locked(&mut jobs, network);
|
||||
jobs.history.retain(|(net, _), _| *net != network);
|
||||
}
|
||||
|
||||
pub(super) fn shutdown(&self) {
|
||||
let mut jobs = self.lock();
|
||||
jobs.job = None;
|
||||
if let Some(channel) = self.active.swap(None) {
|
||||
channel.handle.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognized probe frames never go to a host socket. Admission is stricter
|
||||
/// than exit traffic: both addresses must be the current signed overlay pair.
|
||||
pub(super) fn receive_packet(
|
||||
inner: &Inner,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
packet: &[u8],
|
||||
) -> bool {
|
||||
if !wire::is_test_packet(packet) {
|
||||
return false;
|
||||
}
|
||||
if let Some(channel) = inner.speed.active.load().as_ref()
|
||||
&& channel.key == (network, peer)
|
||||
&& let Some(data) = wire::decode_packet(packet)
|
||||
&& data.id == channel.id
|
||||
&& inner.routes.peer_addresses(network, peer) == Some((data.destination, data.source))
|
||||
{
|
||||
channel.handle.data(data);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn config(
|
||||
inner: &Inner,
|
||||
key: Key,
|
||||
id: u64,
|
||||
bytes: u32,
|
||||
rtt: Option<Duration>,
|
||||
) -> Option<wire::Config> {
|
||||
let (local, remote) = inner.routes.peer_addresses(key.0, key.1)?;
|
||||
let ceiling = if inner.speed.metered.load(Ordering::Relaxed) {
|
||||
wire::METERED_BYTES
|
||||
} else {
|
||||
wire::NORMAL_BYTES
|
||||
};
|
||||
Some(wire::Config {
|
||||
id,
|
||||
local,
|
||||
remote,
|
||||
mtu: u16::try_from(inner.config.interface_mtu).unwrap_or(u16::MAX),
|
||||
byte_limit: bytes.min(ceiling),
|
||||
rtt: rtt.unwrap_or(Duration::from_millis(100)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn receive_control(
|
||||
inner: &Arc<Inner>,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
message: wire::Control,
|
||||
rtt: impl FnOnce() -> Option<Duration>,
|
||||
) -> Option<ControlMessage> {
|
||||
let key = (network, peer);
|
||||
let id = message.id();
|
||||
if let wire::Control::Start(request) = message {
|
||||
let jobs = inner.speed.lock();
|
||||
if inner.shutdown.is_triggered()
|
||||
|| jobs.job.is_some()
|
||||
|| inner.speed.active.load().is_some()
|
||||
{
|
||||
return envelope(&wire::Control::Busy { id });
|
||||
}
|
||||
let cfg = config(inner, key, id, request.byte_limit, rtt())?;
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::respond(cfg, request);
|
||||
inner.speed.active.store(Some(Arc::new(Channel {
|
||||
key,
|
||||
id,
|
||||
limit,
|
||||
handle,
|
||||
})));
|
||||
drop(jobs);
|
||||
let io = TestIo::new(inner, key, None);
|
||||
tokio::spawn(async move {
|
||||
let owner = io.inner.clone();
|
||||
session.run(io).await;
|
||||
if let Some(inner) = owner.upgrade() {
|
||||
let _guard = inner.speed.lock();
|
||||
inner.speed.clear_channel(key, id);
|
||||
}
|
||||
});
|
||||
} else if let Some(c) = inner
|
||||
.speed
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.key == key && c.id == id)
|
||||
{
|
||||
c.handle.control(message);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
struct TestIo {
|
||||
inner: Weak<Inner>,
|
||||
key: Key,
|
||||
generation: Option<u64>,
|
||||
started: Instant,
|
||||
}
|
||||
|
||||
impl TestIo {
|
||||
fn new(inner: &Arc<Inner>, key: Key, generation: Option<u64>) -> Self {
|
||||
Self {
|
||||
inner: Arc::downgrade(inner),
|
||||
key,
|
||||
generation,
|
||||
started: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl wire::Io for TestIo {
|
||||
async fn control(&self, message: wire::Control) -> bool {
|
||||
let (Some(inner), Some(message)) = (self.inner.upgrade(), envelope(&message)) else {
|
||||
return false;
|
||||
};
|
||||
Agent { inner }
|
||||
.send(self.key.0, self.key.1, message)
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
self.inner.upgrade().is_some_and(|inner| {
|
||||
inner
|
||||
.config
|
||||
.tunnel
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.carry(self.key.0, self.key.1, packet))
|
||||
})
|
||||
}
|
||||
|
||||
fn progress(&self, update: wire::Progress) {
|
||||
if !matches!(
|
||||
update.state,
|
||||
wire::State::Starting | wire::State::Download | wire::State::Upload
|
||||
) {
|
||||
return; // Publish terminal results together with releasing the slot.
|
||||
}
|
||||
if let Some(generation) = self.generation
|
||||
&& let Some(inner) = self.inner.upgrade()
|
||||
{
|
||||
let mut jobs = inner.speed.lock();
|
||||
if jobs
|
||||
.job
|
||||
.as_ref()
|
||||
.is_some_and(|j| j.generation == generation)
|
||||
&& let Some(report) = jobs.history.get_mut(&self.key)
|
||||
{
|
||||
update_report(report, update, self.started);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_report(report: &mut SpeedPeerReport, progress: wire::Progress, started: Instant) {
|
||||
let live = matches!(progress.state, wire::State::Download | wire::State::Upload);
|
||||
let rate = |reading: wire::Reading| {
|
||||
reading
|
||||
.bps
|
||||
.filter(|_| match reading.quality {
|
||||
wire::Quality::Measured | wire::Quality::AtLeast => true,
|
||||
wire::Quality::Measuring => live,
|
||||
wire::Quality::Insufficient => false,
|
||||
})
|
||||
.map(|bps| SpeedRate {
|
||||
bps,
|
||||
lower_bound: reading.quality == wire::Quality::AtLeast,
|
||||
})
|
||||
};
|
||||
report.down = rate(progress.down);
|
||||
report.up = rate(progress.up);
|
||||
report.bytes = u64::from(progress.down.bytes) + u64::from(progress.up.bytes);
|
||||
report.elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
report.measured_at_unix_secs = now();
|
||||
report.phase = match progress.state {
|
||||
wire::State::Starting => SpeedPhase::Preparing,
|
||||
wire::State::Download => SpeedPhase::Download,
|
||||
wire::State::Upload => SpeedPhase::Upload,
|
||||
wire::State::Complete if report.down.is_some() || report.up.is_some() => SpeedPhase::Done,
|
||||
wire::State::Complete => SpeedPhase::Failed("Insufficient data for a reliable rate".into()),
|
||||
wire::State::Busy => SpeedPhase::Failed("Peer is already running a speed test".into()),
|
||||
wire::State::TimedOut => {
|
||||
SpeedPhase::Failed("Peer did not finish the speed test in time".into())
|
||||
}
|
||||
wire::State::Cancelled => SpeedPhase::Cancelled,
|
||||
wire::State::Failed => {
|
||||
SpeedPhase::Failed("The data path could not complete the speed test".into())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn describe_path(peer: &PeerStatus) -> Option<String> {
|
||||
match &peer.data_path {
|
||||
DataPath::None => None,
|
||||
DataPath::Direct { transport } => Some(match &peer.data_transport_detail {
|
||||
Some(detail) => format!("{transport} · {detail}"),
|
||||
None => transport.clone(),
|
||||
}),
|
||||
DataPath::Relayed { hops, via } => Some(format!("{hops} hops via {}", via.fmt_short())),
|
||||
}
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
/// Runs one peer diagnostic, or sequentially tests the capable exit nodes in the network.
|
||||
pub async fn start_speed_test(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: Option<EndpointId>,
|
||||
metered: bool,
|
||||
) -> Result<()> {
|
||||
let status = self.network_status(network).await?;
|
||||
let targets: Vec<_> = status
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
peer.map_or(p.exit_node, |selected| p.endpoint_id == selected)
|
||||
&& status.speed.capable.contains(&p.endpoint_id.to_string())
|
||||
})
|
||||
.map(|p| p.endpoint_id)
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return Err(Error::SpeedTest(
|
||||
if peer.is_some() {
|
||||
"Peer is offline or does not support this speed-test version"
|
||||
} else {
|
||||
"No online exit nodes support speed tests in this network"
|
||||
}
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let cap = self.inner.limits.max_speed_results;
|
||||
if targets.len() > cap {
|
||||
return Err(Error::SpeedTest("Too many peers for one test batch".into()));
|
||||
}
|
||||
let generation = rand::random();
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
if self.inner.shutdown.is_triggered() {
|
||||
return Err(Error::Stopped);
|
||||
}
|
||||
if jobs.job.is_some() || self.inner.speed.active.load().is_some() {
|
||||
return Err(Error::SpeedTest(
|
||||
"Another speed test is already running".into(),
|
||||
));
|
||||
}
|
||||
// Make room before inserting the queue, preserving results of other networks when possible.
|
||||
for target in &targets {
|
||||
jobs.history.remove(&(network, *target));
|
||||
}
|
||||
while jobs.history.len() + targets.len() > cap {
|
||||
let Some(oldest) = jobs
|
||||
.history
|
||||
.iter()
|
||||
.min_by_key(|(_, r)| r.measured_at_unix_secs)
|
||||
.map(|(k, _)| *k)
|
||||
else {
|
||||
break;
|
||||
};
|
||||
jobs.history.remove(&oldest);
|
||||
}
|
||||
let count = targets.len() as u32;
|
||||
jobs.job = Some(Job {
|
||||
generation,
|
||||
network,
|
||||
batch: peer.is_none().then_some(SpeedBatchReport {
|
||||
done: 0,
|
||||
total: count,
|
||||
}),
|
||||
});
|
||||
for target in &targets {
|
||||
jobs.history.insert(
|
||||
(network, *target),
|
||||
SpeedPeerReport {
|
||||
measured_at_unix_secs: now(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let owner = Arc::downgrade(&self.inner);
|
||||
let metered = metered || self.inner.speed.metered.load(Ordering::Relaxed);
|
||||
let per_peer = if metered {
|
||||
wire::METERED_BYTES
|
||||
} else {
|
||||
wire::NORMAL_BYTES
|
||||
};
|
||||
let limit = if peer.is_none() {
|
||||
per_peer.min(
|
||||
if metered {
|
||||
METERED_BATCH_BYTES
|
||||
} else {
|
||||
BATCH_BYTES
|
||||
} / count,
|
||||
)
|
||||
} else {
|
||||
per_peer
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
for (index, target) in targets.into_iter().enumerate() {
|
||||
let key = (network, target);
|
||||
let Some(inner) = owner.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let result = run_outgoing(&inner, key, generation, limit, peer.is_none()).await;
|
||||
let mut jobs = inner.speed.lock();
|
||||
if let Some((id, _, _)) = &result {
|
||||
inner.speed.clear_channel(key, *id);
|
||||
}
|
||||
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
|
||||
return;
|
||||
}
|
||||
if let Some(report) = jobs.history.get_mut(&key) {
|
||||
match result {
|
||||
Some((_, update, started)) => update_report(report, update, started),
|
||||
None => {
|
||||
report.phase = SpeedPhase::Failed(
|
||||
"Peer is no longer eligible or its overlay address is unavailable"
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if index + 1 == count as usize {
|
||||
jobs.job = None;
|
||||
} else if let Some(batch) = jobs.job.as_mut().and_then(|j| j.batch.as_mut()) {
|
||||
batch.done += 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cancels the current test and any queued peers in this network.
|
||||
pub fn stop_speed_test(&self, network: NetworkId) {
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
self.inner.speed.cancel_locked(&mut jobs, network);
|
||||
}
|
||||
|
||||
/// Applies the host's actual metered-link policy to incoming and outgoing measurements.
|
||||
pub fn set_speed_test_metered(&self, metered: bool) {
|
||||
if self.inner.speed.metered.swap(metered, Ordering::Relaxed) || !metered {
|
||||
return;
|
||||
}
|
||||
let mut jobs = self.inner.speed.lock();
|
||||
if let Some(network) = jobs.job.as_ref().map(|j| j.network) {
|
||||
self.inner.speed.cancel_locked(&mut jobs, network);
|
||||
} else if let Some(c) = self
|
||||
.inner
|
||||
.speed
|
||||
.active
|
||||
.load()
|
||||
.as_ref()
|
||||
.filter(|c| c.limit > wire::METERED_BYTES)
|
||||
{
|
||||
c.handle.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_outgoing(
|
||||
inner: &Arc<Inner>,
|
||||
key: Key,
|
||||
generation: u64,
|
||||
limit: u32,
|
||||
exits_only: bool,
|
||||
) -> Option<(u64, wire::Progress, Instant)> {
|
||||
let agent = Agent {
|
||||
inner: Arc::clone(inner),
|
||||
};
|
||||
let status = agent.network_status(key.0).await.ok()?;
|
||||
let peer = status.peers.iter().find(|p| {
|
||||
p.endpoint_id == key.1 && (!exits_only || p.exit_node) && supported(&p.capabilities)
|
||||
})?;
|
||||
let id = rand::random();
|
||||
let cfg = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::initiate(cfg);
|
||||
let io = TestIo::new(inner, key, Some(generation));
|
||||
{
|
||||
let mut jobs = inner.speed.lock();
|
||||
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
|
||||
return None;
|
||||
}
|
||||
let report = jobs.history.get_mut(&key)?;
|
||||
report.phase = SpeedPhase::Preparing;
|
||||
report.path = describe_path(peer);
|
||||
inner.speed.active.store(Some(Arc::new(Channel {
|
||||
key,
|
||||
id,
|
||||
limit,
|
||||
handle,
|
||||
})));
|
||||
}
|
||||
let started = io.started;
|
||||
let update = session.run(io).await;
|
||||
Some((id, update, started))
|
||||
}
|
||||
@@ -240,6 +240,8 @@ pub struct RangeConflict {
|
||||
/// Status of one network.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NetworkStatus {
|
||||
/// Available mesh throughput tests, with local progress and results.
|
||||
pub speed: crate::ipc::SpeedReport,
|
||||
/// Shared service configuration with this client's routing observations.
|
||||
pub vips: Vec<crate::vip::VipStatus>,
|
||||
/// Enabled local data-plane protocols, in preference order.
|
||||
|
||||
@@ -50,6 +50,16 @@ pub const DATA_REASSEMBLY_TTL: Duration = Duration::from_secs(5);
|
||||
/// Completed or discarded packet IDs retained to ignore late duplicate fragments.
|
||||
pub const DATA_RECENT_IDS: usize = 128;
|
||||
|
||||
/// Simultaneous TCP, UDP and ICMP work on a userspace exit.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) const EXIT_FORWARD_FLOWS: usize = 256;
|
||||
/// Bounded packet queue shared by userspace exit clients.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) const EXIT_FORWARD_QUEUE: usize = 64;
|
||||
/// Concurrent fragmented datagrams accepted by a userspace exit.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) const EXIT_FORWARD_FRAGMENTS: usize = 32;
|
||||
|
||||
/// Where the two stores live.
|
||||
///
|
||||
/// The mandatory state and the disposable cache are separate both logically and
|
||||
@@ -211,6 +221,8 @@ pub struct Limits {
|
||||
pub max_discovery_candidates: usize,
|
||||
/// Maximum simultaneous authenticated sessions per network.
|
||||
pub max_sessions_per_network: usize,
|
||||
/// Maximum per-peer speed results or queued tests retained by the agent.
|
||||
pub max_speed_results: usize,
|
||||
/// Maximum simultaneous inbound connections being handshaken.
|
||||
pub max_inbound_handshakes: usize,
|
||||
/// Capacity of a session's outbound queue, providing backpressure.
|
||||
@@ -247,6 +259,7 @@ impl Default for Limits {
|
||||
max_concurrent_dials: 8,
|
||||
max_discovery_candidates: 16,
|
||||
max_sessions_per_network: 64,
|
||||
max_speed_results: 256,
|
||||
max_inbound_handshakes: 32,
|
||||
session_send_queue: 64,
|
||||
event_buffer: 512,
|
||||
|
||||
@@ -15,7 +15,7 @@ pub mod relay;
|
||||
pub mod routing;
|
||||
pub mod transport;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use iroh::EndpointId;
|
||||
use tokio::sync::mpsc;
|
||||
@@ -176,6 +176,7 @@ pub struct PluginContext {
|
||||
/// Where decrypted packets go. Absent when nothing is carrying traffic,
|
||||
/// in which case a protocol still runs and its packets are discarded.
|
||||
sink: Option<Arc<dyn PacketSink>>,
|
||||
routes: Weak<crate::overlay::RoutingTable>,
|
||||
}
|
||||
|
||||
impl PluginContext {
|
||||
@@ -183,14 +184,23 @@ impl PluginContext {
|
||||
sender: mpsc::Sender<PluginRequest>,
|
||||
local: EndpointId,
|
||||
sink: Option<Arc<dyn PacketSink>>,
|
||||
routes: &Arc<crate::overlay::RoutingTable>,
|
||||
) -> Self {
|
||||
Self {
|
||||
sender: Some(sender),
|
||||
local: Some(local),
|
||||
sink,
|
||||
routes: Arc::downgrade(routes),
|
||||
}
|
||||
}
|
||||
|
||||
/// The peer whose tunnel should stay ready for traffic even while idle.
|
||||
/// Only the locally selected internet exit in its own network qualifies.
|
||||
pub fn warm_peer(&self, network: NetworkId) -> Option<EndpointId> {
|
||||
let (selected, peer) = self.routes.upgrade()?.exit_via()?;
|
||||
(selected == network).then_some(peer)
|
||||
}
|
||||
|
||||
/// Where to hand a decrypted packet.
|
||||
///
|
||||
/// Always answers: with no interface to write to, the packets are
|
||||
@@ -208,15 +218,15 @@ impl PluginContext {
|
||||
sender: None,
|
||||
local: None,
|
||||
sink: None,
|
||||
routes: Weak::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A context configured with a custom packet sink.
|
||||
pub fn with_sink(sink: Arc<dyn PacketSink>) -> Self {
|
||||
Self {
|
||||
sender: None,
|
||||
local: None,
|
||||
sink: Some(sink),
|
||||
..Self::detached()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,6 +241,7 @@ impl PluginContext {
|
||||
sender: Some(sender),
|
||||
local: Some(local),
|
||||
sink,
|
||||
..Self::detached()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,9 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// A requested mesh throughput test cannot run.
|
||||
#[error("{0}")]
|
||||
SpeedTest(String),
|
||||
/// A node-history cleanup is unsafe, stale or cannot be performed.
|
||||
#[error("cannot forget node: {0}")]
|
||||
ForgetNode(String),
|
||||
|
||||
@@ -25,6 +25,9 @@
|
||||
//! rather than the crate's internal structures, so internal refactors do not
|
||||
//! silently change what a client sees.
|
||||
|
||||
mod speed;
|
||||
pub use speed::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
|
||||
|
||||
#[cfg(unix)]
|
||||
pub mod unix;
|
||||
#[cfg(windows)]
|
||||
@@ -277,6 +280,20 @@ pub enum Request {
|
||||
/// The member's endpoint id, or `None` to stop using an exit node.
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Begin a peer test or a sequential batch of advertised exits.
|
||||
StartSpeedTest {
|
||||
/// Active network identifier.
|
||||
network_id: String,
|
||||
/// One peer, or all online exits when absent.
|
||||
peer: Option<String>,
|
||||
/// Apply the smaller metered-link byte budget.
|
||||
metered: bool,
|
||||
},
|
||||
/// Cancel the active local test or batch in this network.
|
||||
StopSpeedTest {
|
||||
/// Active network identifier.
|
||||
network_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Request {
|
||||
@@ -300,6 +317,15 @@ impl std::fmt::Debug for Request {
|
||||
f,
|
||||
"SetProtocols {{ {network_id}, protocols: {protocols:?} }}"
|
||||
),
|
||||
Request::StartSpeedTest {
|
||||
network_id,
|
||||
peer,
|
||||
metered,
|
||||
} => write!(
|
||||
f,
|
||||
"StartSpeedTest {{ {network_id}, peer: {peer:?}, metered: {metered} }}"
|
||||
),
|
||||
Request::StopSpeedTest { network_id } => write!(f, "StopSpeedTest({network_id})"),
|
||||
Request::Status => f.write_str("Status"),
|
||||
Request::SetBroadcast {
|
||||
network_id,
|
||||
@@ -331,6 +357,8 @@ impl std::fmt::Debug for Request {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum Response {
|
||||
/// A speed-test action was accepted.
|
||||
SpeedTestAccepted,
|
||||
/// Accepted configuration with fresh local routing observations.
|
||||
Vips(Vec<crate::vip::VipStatus>),
|
||||
/// An observed offline claim was durably retired.
|
||||
@@ -711,6 +739,9 @@ pub struct ProtocolReport {
|
||||
/// One network.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct NetworkReport {
|
||||
/// Current capabilities and results of peer speed tests.
|
||||
#[serde(default)]
|
||||
pub speed: SpeedReport,
|
||||
/// Shared VIPs and this client's routing observations.
|
||||
#[serde(default)]
|
||||
pub vips: Vec<crate::vip::VipStatus>,
|
||||
@@ -940,10 +971,12 @@ pub struct OverlayPeerReport {
|
||||
pub public_key: String,
|
||||
/// The overlay address the network agreed it holds.
|
||||
pub address: Option<String>,
|
||||
/// Seconds since the last WireGuard handshake.
|
||||
///
|
||||
/// `None` means the tunnel has never handshaken and cannot carry traffic.
|
||||
/// Seconds since the last WireGuard handshake while its session key is usable.
|
||||
pub handshake_secs_ago: Option<u64>,
|
||||
/// An established tunnel has no recent or pending IP traffic. An expired
|
||||
/// key on a tunnel required to stay warm is reported as waiting instead.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
/// Packets encrypted and sent to this peer.
|
||||
pub tx_packets: u64,
|
||||
/// Packets decrypted from this peer.
|
||||
@@ -1061,6 +1094,24 @@ pub trait ReportSource: Send + Sync + 'static {
|
||||
Box::pin(async move { Err("this agent cannot change broadcast participation".into()) })
|
||||
}
|
||||
|
||||
/// Queues a diagnostic against one peer, or all current exit peers.
|
||||
fn start_speed_test(
|
||||
&self,
|
||||
_network_id: String,
|
||||
_peer: Option<String>,
|
||||
_metered: bool,
|
||||
) -> BoxFuture<'_, std::result::Result<(), String>> {
|
||||
Box::pin(async { Err("this agent cannot test peer speeds".into()) })
|
||||
}
|
||||
|
||||
/// Cancels an individual test and any remaining batch members.
|
||||
fn stop_speed_test(
|
||||
&self,
|
||||
_network_id: String,
|
||||
) -> BoxFuture<'_, std::result::Result<(), String>> {
|
||||
Box::pin(async { Err("this agent cannot stop speed tests".into()) })
|
||||
}
|
||||
|
||||
/// Stops serving a network, or starts serving it again.
|
||||
///
|
||||
/// Defaulted to a refusal, like the others.
|
||||
@@ -1145,7 +1196,7 @@ 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', 25]);
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 27]);
|
||||
|
||||
/// Reads one request off an accepted stream, answers it, writes the response.
|
||||
///
|
||||
@@ -1231,6 +1282,18 @@ where
|
||||
Ok(secret) => Response::Secret(RedactedText::new(secret)),
|
||||
Err(reason) => Response::Error(reason),
|
||||
},
|
||||
Request::StartSpeedTest {
|
||||
network_id,
|
||||
peer,
|
||||
metered,
|
||||
} => match source.start_speed_test(network_id, peer, metered).await {
|
||||
Ok(()) => Response::SpeedTestAccepted,
|
||||
Err(reason) => Response::Error(reason),
|
||||
},
|
||||
Request::StopSpeedTest { network_id } => match source.stop_speed_test(network_id).await {
|
||||
Ok(()) => Response::SpeedTestAccepted,
|
||||
Err(reason) => Response::Error(reason),
|
||||
},
|
||||
Request::SetExitOffer {
|
||||
network_id,
|
||||
enabled,
|
||||
@@ -1450,6 +1513,43 @@ pub async fn set_exit_node(
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures the mesh data path to one peer, or queues the network's online exit nodes.
|
||||
pub async fn start_speed_test(
|
||||
path: impl AsRef<Path>,
|
||||
network_id: &str,
|
||||
peer: Option<&str>,
|
||||
metered: bool,
|
||||
) -> Result<()> {
|
||||
speed_request(
|
||||
path.as_ref(),
|
||||
Request::StartSpeedTest {
|
||||
network_id: network_id.to_owned(),
|
||||
peer: peer.map(str::to_owned),
|
||||
metered,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stops the current local speed test and clears its remaining queue.
|
||||
pub async fn stop_speed_test(path: impl AsRef<Path>, network_id: &str) -> Result<()> {
|
||||
speed_request(
|
||||
path.as_ref(),
|
||||
Request::StopSpeedTest {
|
||||
network_id: network_id.to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn speed_request(path: &Path, request: Request) -> Result<()> {
|
||||
match exchange(path, &request, EXCHANGE_TIMEOUT).await? {
|
||||
Response::SpeedTestAccepted => Ok(()),
|
||||
Response::Error(reason) => Err(Error::SpeedTest(reason)),
|
||||
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks a running agent for a configured network's shared secret, in its
|
||||
/// `tsn1…` text form, so a local client can copy it. The secret is never
|
||||
/// logged by this path.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Local presentation of receiver-measured peer throughput.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Tests last requested on this device, scoped to one network.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedReport {
|
||||
/// Progress of the current sequential exit-node test.
|
||||
pub batch: Option<SpeedBatchReport>,
|
||||
/// Per-peer progress or the last local result, keyed by endpoint ID.
|
||||
pub peers: BTreeMap<String, SpeedPeerReport>,
|
||||
/// Currently connected peers advertising the same diagnostic wire version.
|
||||
pub capable: Vec<String>,
|
||||
}
|
||||
|
||||
/// Progress of an exit-node batch.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedBatchReport {
|
||||
/// Number of peers that have finished, including failures.
|
||||
pub done: u32,
|
||||
/// Number selected when the batch started.
|
||||
pub total: u32,
|
||||
}
|
||||
|
||||
/// A receiver-confirmed rate in decimal bits per second.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedRate {
|
||||
/// Measured bits per second.
|
||||
pub bps: u64,
|
||||
/// The test reached its budget before establishing a throughput ceiling.
|
||||
pub lower_bound: bool,
|
||||
}
|
||||
|
||||
/// Locally observed phase of one diagnostic.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum SpeedPhase {
|
||||
/// Waiting behind another exit in the same batch.
|
||||
#[default]
|
||||
Queued,
|
||||
/// Negotiating over the authenticated control session.
|
||||
Preparing,
|
||||
/// Receiving test data.
|
||||
Download,
|
||||
/// Sending test data.
|
||||
Upload,
|
||||
/// Measurement is complete.
|
||||
Done,
|
||||
/// The test could not produce a result, with an explanation for the user.
|
||||
Failed(String),
|
||||
/// The test was stopped.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// A single live or completed diagnostic on this device.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpeedPeerReport {
|
||||
/// Current or terminal phase.
|
||||
pub phase: SpeedPhase,
|
||||
/// Download rate from the remote peer.
|
||||
pub down: Option<SpeedRate>,
|
||||
/// Upload rate to the remote peer.
|
||||
pub up: Option<SpeedRate>,
|
||||
/// Time since the individual test began.
|
||||
pub elapsed_ms: u32,
|
||||
/// Unique payload bytes received across both directions.
|
||||
pub bytes: u64,
|
||||
/// Wall-clock time of the most recent update, for display only.
|
||||
pub measured_at_unix_secs: u64,
|
||||
/// Data path at the start of the measurement, when known.
|
||||
pub path: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
//! A Windows exit offer terminates its forwarded connections on physical
|
||||
//! sockets. This keeps them out of the destination-only routes used by local
|
||||
//! applications. The stack and its sockets live for the offer, independently
|
||||
//! of this device's upstream selection.
|
||||
use super::router::Route;
|
||||
use crate::identity::NetworkId;
|
||||
use crate::vip::{
|
||||
Protocol,
|
||||
packet::{self, Tuple},
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use smoltcp::wire::{IpAddress, TcpPacket, UdpPacket};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io,
|
||||
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
net::{TcpSocket, UdpSocket},
|
||||
sync::{mpsc, watch},
|
||||
task::{JoinHandle, JoinSet},
|
||||
};
|
||||
|
||||
mod tcp;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
use crate::config::{EXIT_FORWARD_FLOWS, EXIT_FORWARD_FRAGMENTS, EXIT_FORWARD_QUEUE};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Physical {
|
||||
pub index: u32,
|
||||
pub address: Ipv4Addr,
|
||||
}
|
||||
|
||||
impl Physical {
|
||||
async fn tcp(self, remote: SocketAddr) -> io::Result<tokio::net::TcpStream> {
|
||||
let socket = TcpSocket::new_v4()?;
|
||||
#[cfg(windows)]
|
||||
windows::pin(&socket, self.index)?;
|
||||
socket.bind((self.address, 0).into())?;
|
||||
socket.connect(remote).await
|
||||
}
|
||||
|
||||
fn datagram(self, protocol: socket2::Protocol) -> io::Result<UdpSocket> {
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
let ty = if protocol == Protocol::UDP {
|
||||
Type::DGRAM
|
||||
} else {
|
||||
Type::RAW
|
||||
};
|
||||
let socket = Socket::new(Domain::IPV4, ty, Some(protocol))?;
|
||||
#[cfg(windows)]
|
||||
windows::pin(&socket, self.index)?;
|
||||
socket.bind(&SocketAddr::V4(SocketAddrV4::new(self.address, 0)).into())?;
|
||||
socket.set_nonblocking(true)?;
|
||||
UdpSocket::from_std(socket.into())
|
||||
}
|
||||
}
|
||||
|
||||
type Reply = Arc<dyn Fn(Route, Bytes) + Send + Sync>;
|
||||
type Offers = Vec<(NetworkId, Physical)>;
|
||||
|
||||
pub(super) struct Gateway {
|
||||
input: mpsc::Sender<(Route, Bytes)>,
|
||||
offers: watch::Sender<Offers>,
|
||||
worker: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Gateway {
|
||||
pub fn new(mtu: u32, reply: impl Fn(Route, Bytes) + Send + Sync + 'static) -> Self {
|
||||
let (input, packets) = mpsc::channel(EXIT_FORWARD_QUEUE);
|
||||
let (offers, serving) = watch::channel(Vec::new());
|
||||
let worker = tokio::spawn(run(mtu, Arc::new(reply), packets, serving));
|
||||
Self {
|
||||
input,
|
||||
offers,
|
||||
worker,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configure(&self, mut offers: Offers) {
|
||||
offers.sort_by_key(|(network, _)| *network);
|
||||
self.offers.send_if_modified(|old| {
|
||||
if *old == offers {
|
||||
return false;
|
||||
}
|
||||
*old = offers;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
pub fn forward(&self, origin: Route, packet: Bytes) -> bool {
|
||||
self.offers
|
||||
.borrow()
|
||||
.iter()
|
||||
.any(|(network, _)| *network == origin.network)
|
||||
&& self.input.try_send((origin, packet)).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Gateway {
|
||||
fn drop(&mut self) {
|
||||
self.worker.abort();
|
||||
}
|
||||
}
|
||||
|
||||
type FlowKey = (NetworkId, iroh::EndpointId, Tuple);
|
||||
struct Flow {
|
||||
tx: mpsc::Sender<Bytes>,
|
||||
task: tokio::task::AbortHandle,
|
||||
}
|
||||
|
||||
async fn run(
|
||||
mtu: u32,
|
||||
reply: Reply,
|
||||
mut incoming: mpsc::Receiver<(Route, Bytes)>,
|
||||
mut serving: watch::Receiver<Offers>,
|
||||
) {
|
||||
let mut flows: HashMap<FlowKey, Flow> = HashMap::new();
|
||||
let mut jobs = JoinSet::new();
|
||||
let mut fragments = packet::Reassembly::default();
|
||||
loop {
|
||||
let (origin, part) = tokio::select! {
|
||||
biased;
|
||||
changed = serving.changed() => {
|
||||
if changed.is_err() { return; }
|
||||
let offers = serving.borrow_and_update();
|
||||
flows.retain(|(network, _, _), flow| {
|
||||
let keep = offers.iter().any(|(net, _)| net == network);
|
||||
if !keep { flow.task.abort(); }
|
||||
keep
|
||||
});
|
||||
// Incomplete datagrams from a withdrawn offer must not survive a rejoin.
|
||||
fragments = packet::Reassembly::default();
|
||||
continue;
|
||||
}
|
||||
Some(result) = jobs.join_next_with_id(), if !jobs.is_empty() => {
|
||||
if let Ok((id, Some(key))) = result
|
||||
&& flows.get(&key).is_some_and(|flow| flow.task.id() == id) {
|
||||
flows.remove(&key);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
input = incoming.recv() => match input { Some(input) => input, None => return },
|
||||
};
|
||||
let Some(physical) = serving
|
||||
.borrow()
|
||||
.iter()
|
||||
.find(|(net, _)| *net == origin.network)
|
||||
.map(|(_, p)| *p)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(packet) =
|
||||
fragments.accept(part, EXIT_FORWARD_FRAGMENTS, Some(*origin.peer.as_bytes()))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(n) = packet::header(&packet) else {
|
||||
continue;
|
||||
};
|
||||
if packet[8] <= 1 {
|
||||
continue;
|
||||
}
|
||||
if packet[9] == 1 {
|
||||
if jobs.len() < EXIT_FORWARD_FLOWS
|
||||
&& packet.get(n) == Some(&8)
|
||||
&& packet.len() >= n + 8
|
||||
&& packet[n + 1] == 0
|
||||
&& packet::checksum(&packet[n..]) == 0
|
||||
{
|
||||
let reply = reply.clone();
|
||||
let mut offers = serving.clone();
|
||||
jobs.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = offers.wait_for(|nets| !nets.iter().any(|(net, _)| *net == origin.network)) => {},
|
||||
_ = echo(physical, origin, packet, n, &reply, mtu) => {}
|
||||
}
|
||||
None
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(tuple) = packet::tuple(&packet) else {
|
||||
continue;
|
||||
};
|
||||
let src = IpAddress::Ipv4(tuple.src);
|
||||
let dst = IpAddress::Ipv4(tuple.dst);
|
||||
let valid =
|
||||
match tuple.protocol {
|
||||
Protocol::Tcp => TcpPacket::new_checked(&packet[n..])
|
||||
.is_ok_and(|p| p.verify_checksum(&src, &dst)),
|
||||
Protocol::Udp => UdpPacket::new_checked(&packet[n..])
|
||||
.is_ok_and(|p| p.verify_checksum(&src, &dst)),
|
||||
};
|
||||
if !valid {
|
||||
continue;
|
||||
}
|
||||
let key = (origin.network, origin.peer, tuple);
|
||||
if let Some(flow) = flows.get(&key) {
|
||||
let _ = flow.tx.try_send(packet);
|
||||
continue;
|
||||
}
|
||||
if jobs.len() >= EXIT_FORWARD_FLOWS
|
||||
|| (tuple.protocol == Protocol::Tcp && !packet::tcp_syn(&packet))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (tx, rx) = mpsc::channel(EXIT_FORWARD_QUEUE.min(16));
|
||||
let reply = reply.clone();
|
||||
let task = jobs.spawn(async move {
|
||||
match tuple.protocol {
|
||||
Protocol::Tcp => tcp::serve(physical, origin, tuple, packet, rx, reply, mtu).await,
|
||||
Protocol::Udp => {
|
||||
let _ = udp(physical, origin, tuple, packet, rx, reply, mtu).await;
|
||||
}
|
||||
}
|
||||
Some(key)
|
||||
});
|
||||
flows.insert(key, Flow { tx, task });
|
||||
}
|
||||
}
|
||||
|
||||
fn remote(t: Tuple) -> SocketAddr {
|
||||
SocketAddr::V4(SocketAddrV4::new(t.dst, t.dport))
|
||||
}
|
||||
|
||||
fn respond(reply: &Reply, origin: Route, packet: Bytes, mtu: u32) {
|
||||
for part in packet::fragments(packet, mtu) {
|
||||
reply(origin, part);
|
||||
}
|
||||
}
|
||||
|
||||
async fn udp(
|
||||
physical: Physical,
|
||||
origin: Route,
|
||||
tuple: Tuple,
|
||||
first: Bytes,
|
||||
mut incoming: mpsc::Receiver<Bytes>,
|
||||
reply: Reply,
|
||||
mtu: u32,
|
||||
) -> io::Result<()> {
|
||||
let socket = physical.datagram(socket2::Protocol::UDP)?;
|
||||
socket.connect(remote(tuple)).await?;
|
||||
let socket = &socket;
|
||||
let send = |p: Bytes| async move {
|
||||
if let Some(n) = packet::header(&p) {
|
||||
socket.send(&p[n + 8..]).await?;
|
||||
}
|
||||
Ok::<_, io::Error>(())
|
||||
};
|
||||
send(first).await?;
|
||||
let mut buf = vec![0; 65_507];
|
||||
loop {
|
||||
tokio::select! {
|
||||
packet = incoming.recv() => match packet { Some(p) => send(p).await?, None => return Ok(()) },
|
||||
result = socket.recv(&mut buf) => {
|
||||
let len = result?;
|
||||
if let Some(p) = udp_packet(tuple.reverse(), &buf[..len]) { respond(&reply, origin, p, mtu); }
|
||||
},
|
||||
_ = tokio::time::sleep(Duration::from_secs(120)) => return Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ip_packet(
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
proto: u8,
|
||||
payload_len: usize,
|
||||
) -> Option<Vec<u8>> {
|
||||
let len = u16::try_from(20usize.checked_add(payload_len)?).ok()?;
|
||||
let mut bytes = vec![0; usize::from(len)];
|
||||
bytes[0] = 0x45;
|
||||
bytes[2..4].copy_from_slice(&len.to_be_bytes());
|
||||
bytes[4..6].copy_from_slice(&rand::random::<u16>().to_be_bytes());
|
||||
bytes[8] = 64;
|
||||
bytes[9] = proto;
|
||||
bytes[12..16].copy_from_slice(&source.octets());
|
||||
bytes[16..20].copy_from_slice(&destination.octets());
|
||||
let checksum = packet::checksum(&bytes[..20]);
|
||||
bytes[10..12].copy_from_slice(&checksum.to_be_bytes());
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
fn udp_packet(tuple: Tuple, body: &[u8]) -> Option<Bytes> {
|
||||
let mut bytes = ip_packet(tuple.src, tuple.dst, 17, body.len().checked_add(8)?)?;
|
||||
let mut p = UdpPacket::new_unchecked(&mut bytes[20..]);
|
||||
p.set_src_port(tuple.sport);
|
||||
p.set_dst_port(tuple.dport);
|
||||
p.set_len((body.len() + 8) as u16);
|
||||
p.payload_mut().copy_from_slice(body);
|
||||
p.fill_checksum(&tuple.src.into(), &tuple.dst.into());
|
||||
Some(bytes.into())
|
||||
}
|
||||
|
||||
async fn echo(
|
||||
physical: Physical,
|
||||
origin: Route,
|
||||
packet: Bytes,
|
||||
n: usize,
|
||||
reply: &Reply,
|
||||
mtu: u32,
|
||||
) -> io::Result<()> {
|
||||
let Some((source, destination)) = packet::addresses(&packet) else {
|
||||
return Ok(());
|
||||
};
|
||||
let socket = physical.datagram(socket2::Protocol::ICMPV4)?;
|
||||
socket.set_ttl(u32::from(packet[8] - 1))?;
|
||||
socket.connect((destination, 0)).await?;
|
||||
// Raw ICMP sockets can observe other echo replies. An independent nonce and
|
||||
// the original data correlate a reply with this one authenticated request.
|
||||
let nonce = rand::random::<u32>().to_be_bytes();
|
||||
let mut request = packet[n..].to_vec();
|
||||
request[4..8].copy_from_slice(&nonce);
|
||||
request[2..4].fill(0);
|
||||
let checksum = packet::checksum(&request);
|
||||
request[2..4].copy_from_slice(&checksum.to_be_bytes());
|
||||
socket.send(&request).await?;
|
||||
// Winsock delivers unrelated replies to other raw ICMP sockets too. A longer
|
||||
// reply must not trigger WSAEMSGSIZE and abort this request.
|
||||
let mut buf = vec![0; usize::from(u16::MAX)];
|
||||
let until = tokio::time::Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
let len = tokio::time::timeout_at(until, socket.recv(&mut buf)).await??;
|
||||
let Some(h) = packet::header(&buf[..len]) else {
|
||||
continue;
|
||||
};
|
||||
let body = &buf[h..len];
|
||||
if buf[9] != 1
|
||||
|| body.len() != request.len()
|
||||
|| body[0..2] != [0, 0]
|
||||
|| body[4..] != request[4..]
|
||||
|| packet::checksum(body) != 0
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(mut out) = ip_packet(destination, source, 1, body.len()) {
|
||||
out[20..].copy_from_slice(body);
|
||||
out[24..28].copy_from_slice(&packet[n + 4..n + 8]);
|
||||
out[22..24].fill(0);
|
||||
let checksum = packet::checksum(&out[20..]);
|
||||
out[22..24].copy_from_slice(&checksum.to_be_bytes());
|
||||
respond(reply, origin, out.into(), mtu);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! smoltcp owns the member-facing half of one stream. The OS owns the
|
||||
//! physical TCP connection. Both directions apply backpressure independently.
|
||||
use super::*;
|
||||
use smoltcp::{
|
||||
iface::{Config, Interface, SocketSet},
|
||||
phy::{self, Device, DeviceCapabilities, Medium},
|
||||
socket::tcp::{Socket, SocketBuffer, State},
|
||||
time::Instant as NetTime,
|
||||
wire::{HardwareAddress, IpCidr},
|
||||
};
|
||||
use std::collections::VecDeque;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
struct Wire {
|
||||
mtu: usize,
|
||||
input: Option<Bytes>,
|
||||
output: VecDeque<Bytes>,
|
||||
}
|
||||
|
||||
struct Rx(Bytes);
|
||||
impl phy::RxToken for Rx {
|
||||
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
|
||||
f(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
struct Tx<'a>(&'a mut VecDeque<Bytes>);
|
||||
impl phy::TxToken for Tx<'_> {
|
||||
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
|
||||
let mut bytes = vec![0; len];
|
||||
let result = f(&mut bytes);
|
||||
self.0.push_back(bytes.into());
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Device for Wire {
|
||||
type RxToken<'a> = Rx;
|
||||
type TxToken<'a> = Tx<'a>;
|
||||
fn receive(&mut self, _: NetTime) -> Option<(Rx, Tx<'_>)> {
|
||||
self.input.take().map(|p| (Rx(p), Tx(&mut self.output)))
|
||||
}
|
||||
fn transmit(&mut self, _: NetTime) -> Option<Tx<'_>> {
|
||||
(self.output.len() < EXIT_FORWARD_QUEUE).then_some(Tx(&mut self.output))
|
||||
}
|
||||
fn capabilities(&self) -> DeviceCapabilities {
|
||||
let mut caps = DeviceCapabilities::default();
|
||||
caps.medium = Medium::Ip;
|
||||
caps.max_transmission_unit = self.mtu;
|
||||
caps
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn serve(
|
||||
physical: Physical,
|
||||
origin: Route,
|
||||
flow: Tuple,
|
||||
syn: Bytes,
|
||||
mut incoming: mpsc::Receiver<Bytes>,
|
||||
reply: Reply,
|
||||
mtu: u32,
|
||||
) {
|
||||
let Ok(Ok(mut upstream)) =
|
||||
tokio::time::timeout(Duration::from_secs(8), physical.tcp(remote(flow))).await
|
||||
else {
|
||||
if let Some(reset) = packet::reject(&syn) {
|
||||
reply(origin, reset);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let mut wire = Wire {
|
||||
mtu: mtu as usize,
|
||||
input: Some(syn),
|
||||
output: VecDeque::new(),
|
||||
};
|
||||
let mut config = Config::new(HardwareAddress::Ip);
|
||||
config.random_seed = rand::random();
|
||||
let mut iface = Interface::new(config, &mut wire, NetTime::ZERO);
|
||||
iface.update_ip_addrs(|ips| {
|
||||
let _ = ips.push(IpCidr::new(flow.dst.into(), 0));
|
||||
});
|
||||
let mut sockets = SocketSet::new(Vec::new());
|
||||
let buffer = || SocketBuffer::new(vec![0; 64 * 1024]);
|
||||
let mut tcp = Socket::new(buffer(), buffer());
|
||||
tcp.set_timeout(Some(smoltcp::time::Duration::from_secs(120)));
|
||||
if tcp.listen((flow.dst, flow.dport)).is_err() {
|
||||
return;
|
||||
}
|
||||
let handle = sockets.add(tcp);
|
||||
let start = std::time::Instant::now();
|
||||
let mut remote_fin = false;
|
||||
let mut local_fin = false;
|
||||
loop {
|
||||
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
|
||||
iface.poll(now, &mut wire, &mut sockets);
|
||||
let tcp = sockets.get_mut::<Socket>(handle);
|
||||
if tcp.can_recv() {
|
||||
let write = tcp.recv(|buf| match upstream.try_write(buf) {
|
||||
Ok(n) => (n, Ok(n > 0)),
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => (0, Ok(false)),
|
||||
Err(e) => (0, Err(e)),
|
||||
});
|
||||
if matches!(write, Ok(Err(_))) {
|
||||
tcp.abort();
|
||||
}
|
||||
}
|
||||
if !local_fin
|
||||
&& !tcp.may_recv()
|
||||
&& matches!(
|
||||
tcp.state(),
|
||||
State::CloseWait | State::Closing | State::LastAck | State::TimeWait
|
||||
)
|
||||
{
|
||||
let _ = upstream.shutdown().await;
|
||||
local_fin = true;
|
||||
}
|
||||
if tcp.can_send() && !remote_fin {
|
||||
match tcp.send(|buf| match upstream.try_read(buf) {
|
||||
Ok(n) => (n, Ok(Some(n))),
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => (0, Ok(None)),
|
||||
Err(e) => (0, Err(e)),
|
||||
}) {
|
||||
Ok(Ok(Some(0))) => {
|
||||
remote_fin = true;
|
||||
tcp.close();
|
||||
}
|
||||
Ok(Err(_)) => tcp.abort(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
iface.poll(now, &mut wire, &mut sockets);
|
||||
for p in wire.output.drain(..) {
|
||||
reply(origin, p);
|
||||
}
|
||||
let tcp = sockets.get::<Socket>(handle);
|
||||
// A reset during the handshake returns smoltcp to Listen. This
|
||||
// worker owns exactly one physical connection and must never accept
|
||||
// a second SYN on that connection or retain an idle flow slot.
|
||||
if matches!(tcp.state(), State::Listen | State::Closed) {
|
||||
return;
|
||||
}
|
||||
let delay = iface
|
||||
.poll_delay(now, &sockets)
|
||||
.map(Duration::from)
|
||||
.unwrap_or(Duration::from_secs(3600));
|
||||
tokio::select! {
|
||||
packet = incoming.recv() => match packet { Some(p) => wire.input = Some(p), None => return },
|
||||
ready = upstream.readable(), if !remote_fin && tcp.can_send() => { if ready.is_err() { return; } }
|
||||
ready = upstream.writable(), if tcp.can_recv() => { if ready.is_err() { return; } }
|
||||
_ = tokio::time::sleep(delay) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
//! These run on loopback on every host. The gateway uses the same code as
|
||||
//! Windows, with a loopback source in place of the pinned physical adapter.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
use tokio::net::{TcpListener, UdpSocket};
|
||||
|
||||
fn route() -> Route {
|
||||
Route {
|
||||
network: NetworkId::from_bytes([4; 32]),
|
||||
peer: iroh::SecretKey::from_bytes(&[3; 32]).public(),
|
||||
}
|
||||
}
|
||||
|
||||
fn addr() -> Ipv4Addr {
|
||||
Ipv4Addr::new(10, 13, 37, 9)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_udp_flow_keeps_its_external_port_while_the_upstream_changes_and_stops_with_its_offer() {
|
||||
let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let route = route();
|
||||
let (replies, mut rx) = mpsc::channel(8);
|
||||
let gateway = Gateway::new(1280, move |r, p| {
|
||||
assert_eq!(r, route);
|
||||
let _ = replies.try_send(p);
|
||||
});
|
||||
let physical = Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
};
|
||||
gateway.configure(vec![(route.network, physical)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 10403,
|
||||
dport: server.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Udp,
|
||||
};
|
||||
let mut port = None;
|
||||
for body in [b"first".as_slice(), b"after upstream change"] {
|
||||
gateway.configure(vec![(route.network, physical)]);
|
||||
assert!(gateway.forward(route, udp_packet(flow, body).unwrap()));
|
||||
let mut buf = [0; 128];
|
||||
let (n, from) = tokio::time::timeout(Duration::from_secs(2), server.recv_from(&mut buf))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&buf[..n], body);
|
||||
assert_eq!(port.get_or_insert(from.port()), &from.port());
|
||||
server.send_to(body, from).await.unwrap();
|
||||
let answer = tokio::time::timeout(Duration::from_secs(2), rx.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(crate::vip::packet::tuple(&answer), Some(flow.reverse()));
|
||||
assert_eq!(&answer[28..], body);
|
||||
}
|
||||
gateway.configure(Vec::new());
|
||||
assert!(!gateway.forward(route, udp_packet(flow, b"withdrawn").unwrap()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refused_tcp_returns_a_reset_to_the_originating_client() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
let (tx, mut rx) = mpsc::channel(2);
|
||||
let route = route();
|
||||
let gateway = Gateway::new(1280, move |r, p| {
|
||||
assert_eq!(r, route);
|
||||
let _ = tx.try_send(p);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
route.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 42000,
|
||||
dport: port,
|
||||
protocol: Protocol::Tcp,
|
||||
};
|
||||
let mut syn = vec![0; 40];
|
||||
syn[0] = 0x45;
|
||||
syn[2..4].copy_from_slice(&40u16.to_be_bytes());
|
||||
syn[8] = 64;
|
||||
syn[9] = 6;
|
||||
syn[32] = 0x50;
|
||||
syn[33] = 2;
|
||||
let checksum = crate::vip::packet::checksum(&syn[..20]);
|
||||
syn[10..12].copy_from_slice(&checksum.to_be_bytes());
|
||||
assert!(gateway.forward(route, crate::vip::packet::rewrite(&syn, flow).unwrap()));
|
||||
let answer = tokio::time::timeout(Duration::from_secs(2), rx.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(crate::vip::packet::tcp_reset(&answer));
|
||||
assert_eq!(crate::vip::packet::tuple(&answer), Some(flow.reverse()));
|
||||
}
|
||||
|
||||
fn tcp_packet(tuple: Tuple, flags: u8, seq: u32, ack: u32, body: &[u8]) -> Bytes {
|
||||
let mut bytes = ip_packet(tuple.src, tuple.dst, 6, 20 + body.len()).unwrap();
|
||||
bytes[24..28].copy_from_slice(&seq.to_be_bytes());
|
||||
bytes[28..32].copy_from_slice(&ack.to_be_bytes());
|
||||
bytes[32] = 0x50;
|
||||
bytes[33] = flags;
|
||||
bytes[34..36].copy_from_slice(&65535u16.to_be_bytes());
|
||||
bytes[40..].copy_from_slice(body);
|
||||
packet::rewrite(&bytes, tuple).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_tcp_stream_to_the_same_destination_survives_offer_reconciliation() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
for expected in [b"one", b"two"] {
|
||||
let mut body = [0; 3];
|
||||
socket.read_exact(&mut body).await.unwrap();
|
||||
assert_eq!(&body, expected);
|
||||
socket.write_all(&body).await.unwrap();
|
||||
}
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(4), async {
|
||||
let route = route();
|
||||
let (tx, mut rx) = mpsc::channel(16);
|
||||
let gateway = Gateway::new(1280, move |r, p| {
|
||||
assert_eq!(r, route);
|
||||
let _ = tx.try_send(p);
|
||||
});
|
||||
let physical = Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
};
|
||||
gateway.configure(vec![(route.network, physical)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 43210,
|
||||
dport: port,
|
||||
protocol: Protocol::Tcp,
|
||||
};
|
||||
let mut seq: u32 = 123;
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 2, seq, 0, &[])));
|
||||
let synack = rx.recv().await.unwrap();
|
||||
assert!(packet::syn_ack(&synack));
|
||||
let mut ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
|
||||
seq += 1;
|
||||
for body in [b"one", b"two"] {
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 0x18, seq, ack, body)));
|
||||
seq += body.len() as u32;
|
||||
loop {
|
||||
let p = rx.recv().await.unwrap();
|
||||
let tcp = TcpPacket::new_checked(&p[20..]).unwrap();
|
||||
if !tcp.payload().is_empty() {
|
||||
assert_eq!(tcp.payload(), body);
|
||||
ack = ack.wrapping_add(body.len() as u32);
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 0x10, seq, ack, &[])));
|
||||
break;
|
||||
}
|
||||
}
|
||||
// A configuration change for a different membership cannot create a new B socket.
|
||||
gateway.configure(vec![
|
||||
(route.network, physical),
|
||||
(NetworkId::from_bytes([7; 32]), physical),
|
||||
]);
|
||||
}
|
||||
server.await.unwrap();
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Two disposable Wintun adapters provide an offline "WAN" and an upstream.
|
||||
/// A longer prefix on the latter captures local applications for the same IP.
|
||||
#[cfg(all(windows, feature = "tun-device"))]
|
||||
#[tokio::test]
|
||||
#[ignore = "requires an elevated disposable Windows runner and wintun.dll"]
|
||||
async fn physical_member_sockets_survive_a_more_specific_wintun_route() {
|
||||
use crate::overlay::{
|
||||
Cidr,
|
||||
provision::{InterfacePlan, InterfaceProvisioner, WintunProvisioner},
|
||||
tun::TunDevice,
|
||||
};
|
||||
let wan = Ipv4Addr::new(198, 18, 222, 1);
|
||||
let upstream = Ipv4Addr::new(198, 18, 222, 5);
|
||||
let site = Ipv4Addr::new(198, 18, 222, 6);
|
||||
for dev in netdev::get_interfaces() {
|
||||
assert!(
|
||||
dev.ipv4
|
||||
.iter()
|
||||
.all(|net| !net.contains(&wan) && !net.contains(&site)),
|
||||
"test subnet is in use on {}",
|
||||
dev.name
|
||||
);
|
||||
}
|
||||
async fn read(device: &dyn TunDevice, endpoint: SocketAddrV4, body: &[u8]) -> Tuple {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let p = device.recv().await.unwrap();
|
||||
if let Some(t) = packet::tuple(&p)
|
||||
&& t.dst == *endpoint.ip()
|
||||
&& t.dport == endpoint.port()
|
||||
&& p.get(28..) == Some(body)
|
||||
{
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
async fn wait_source(site: SocketAddrV4, wanted: Ipv4Addr) {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let s = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
|
||||
if s.connect(site).await.is_ok() && s.local_addr().unwrap().ip() == wanted {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let id = rand::random::<u32>();
|
||||
let provision = WintunProvisioner::new().unwrap();
|
||||
let uplink = provision
|
||||
.reconcile(&InterfacePlan::new(
|
||||
format!("tsfw-a-{id:x}"),
|
||||
1280,
|
||||
vec![Cidr::new(wan.into(), 24).unwrap()],
|
||||
))
|
||||
.await
|
||||
.unwrap()
|
||||
.device
|
||||
.unwrap();
|
||||
let site = SocketAddrV4::new(site, 38201);
|
||||
wait_source(site, wan).await;
|
||||
let index = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.find(|i| i.ipv4.iter().any(|a| a.addr() == wan))
|
||||
.unwrap()
|
||||
.index;
|
||||
let physical = Physical {
|
||||
index,
|
||||
address: wan,
|
||||
};
|
||||
let origin = route();
|
||||
let (tx, mut rx) = mpsc::channel(8);
|
||||
let gateway = Gateway::new(1280, move |_, packet| {
|
||||
let _ = tx.try_send(packet);
|
||||
});
|
||||
gateway.configure(vec![(origin.network, physical)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: *site.ip(),
|
||||
sport: 21002,
|
||||
dport: site.port(),
|
||||
protocol: Protocol::Udp,
|
||||
};
|
||||
let mut send = async |tuple, payload: &[u8]| {
|
||||
assert!(gateway.forward(origin, udp_packet(tuple, payload).unwrap()));
|
||||
let observed = read(&*uplink, site, payload).await;
|
||||
assert_eq!(observed.src, wan);
|
||||
uplink
|
||||
.send(udp_packet(observed.reverse(), payload).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let back = tokio::time::timeout(Duration::from_secs(5), rx.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(packet::tuple(&back), Some(tuple.reverse()));
|
||||
observed.sport
|
||||
};
|
||||
let initial = send(flow, b"before").await;
|
||||
let capture = provision
|
||||
.reconcile(&InterfacePlan::new(
|
||||
format!("tsfw-c-{id:x}"),
|
||||
1280,
|
||||
vec![Cidr::new(upstream.into(), 30).unwrap()],
|
||||
))
|
||||
.await
|
||||
.unwrap()
|
||||
.device
|
||||
.unwrap();
|
||||
wait_source(site, upstream).await;
|
||||
let local = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
|
||||
local.send_to(b"local B", site).await.unwrap();
|
||||
assert_eq!(read(&*capture, site, b"local B").await.src, upstream);
|
||||
assert_eq!(send(flow, b"same A socket").await, initial);
|
||||
send(
|
||||
Tuple {
|
||||
sport: 21003,
|
||||
..flow
|
||||
},
|
||||
b"new A socket",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Raw ICMP uses the identical physical interface selection and restores A's
|
||||
// identifier and sequence after reading the actual reply from the uplink.
|
||||
let mut ping = ip_packet(addr(), *site.ip(), 1, 12).unwrap();
|
||||
ping[20] = 8;
|
||||
ping[24..32].copy_from_slice(b"pingdata");
|
||||
let checksum = packet::checksum(&ping[20..]);
|
||||
ping[22..24].copy_from_slice(&checksum.to_be_bytes());
|
||||
assert!(gateway.forward(origin, ping.into()));
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let wire = uplink.recv().await.unwrap();
|
||||
let Some(n) = packet::header(&wire) else {
|
||||
continue;
|
||||
};
|
||||
if wire[9] != 1 || wire.get(n + 8..) != Some(b"data") {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(packet::addresses(&wire), Some((wan, *site.ip())));
|
||||
let mut pong = ip_packet(*site.ip(), wan, 1, wire.len() - n).unwrap();
|
||||
pong[20..].copy_from_slice(&wire[n..]);
|
||||
pong[20..24].fill(0);
|
||||
let checksum = packet::checksum(&pong[20..]);
|
||||
pong[22..24].copy_from_slice(&checksum.to_be_bytes());
|
||||
uplink.send(pong.into()).await.unwrap();
|
||||
break;
|
||||
}
|
||||
let reply = rx.recv().await.unwrap();
|
||||
assert_eq!(packet::addresses(&reply), Some((*site.ip(), addr())));
|
||||
assert_eq!(&reply[24..], b"pingdata");
|
||||
assert_eq!(packet::checksum(&reply[20..]), 0);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resetting_a_half_open_mesh_handshake_closes_the_physical_socket() {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let route = route();
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
let gateway = Gateway::new(1280, move |_, packet| {
|
||||
let _ = tx.try_send(packet);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
route.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 43211,
|
||||
dport: listener.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Tcp,
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 2, 500, 0, &[])));
|
||||
let (mut physical, _) = listener.accept().await.unwrap();
|
||||
let synack = rx.recv().await.unwrap();
|
||||
assert!(packet::syn_ack(&synack));
|
||||
let ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
|
||||
assert!(gateway.forward(route, tcp_packet(flow, 0x14, 501, ack, &[])));
|
||||
assert_eq!(physical.read(&mut [0; 1]).await.unwrap(), 0);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_server_half_close_still_receives_the_members_final_bytes_and_fin() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let (out, mut rx) = mpsc::channel(8);
|
||||
let origin = route();
|
||||
let gateway = Gateway::new(1280, move |_, packet| {
|
||||
let _ = out.try_send(packet);
|
||||
});
|
||||
gateway.configure(vec![(
|
||||
origin.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 42041,
|
||||
dport: listener.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Tcp,
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
assert!(gateway.forward(origin, tcp_packet(flow, 2, 200, 0, &[])));
|
||||
let (mut server, _) = listener.accept().await.unwrap();
|
||||
server.shutdown().await.unwrap();
|
||||
let synack = rx.recv().await.unwrap();
|
||||
assert!(packet::syn_ack(&synack));
|
||||
let ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
|
||||
assert!(gateway.forward(origin, tcp_packet(flow, 0x10, 201, ack, &[])));
|
||||
loop {
|
||||
let p = rx.recv().await.unwrap();
|
||||
if TcpPacket::new_checked(&p[20..]).unwrap().fin() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(gateway.forward(
|
||||
origin,
|
||||
tcp_packet(flow, 0x19, 201, ack.wrapping_add(1), b"last bytes")
|
||||
));
|
||||
let mut received = Vec::new();
|
||||
server.read_to_end(&mut received).await.unwrap();
|
||||
assert_eq!(received, b"last bytes");
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn at_capacity_existing_udp_flows_continue_and_a_new_tuple_is_dropped() {
|
||||
let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let origin = route();
|
||||
let gateway = Gateway::new(1280, |_, _| {});
|
||||
gateway.configure(vec![(
|
||||
origin.network,
|
||||
Physical {
|
||||
index: 0,
|
||||
address: Ipv4Addr::LOCALHOST,
|
||||
},
|
||||
)]);
|
||||
let flow = Tuple {
|
||||
src: addr(),
|
||||
dst: Ipv4Addr::LOCALHOST,
|
||||
sport: 1024,
|
||||
dport: server.local_addr().unwrap().port(),
|
||||
protocol: Protocol::Udp,
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
let mut buf = [0; 2];
|
||||
for i in 0..EXIT_FORWARD_FLOWS {
|
||||
let p = udp_packet(
|
||||
Tuple {
|
||||
sport: flow.sport + i as u16,
|
||||
..flow
|
||||
},
|
||||
b"a",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(gateway.forward(origin, p));
|
||||
assert_eq!(server.recv(&mut buf).await.unwrap(), 1);
|
||||
}
|
||||
let extra = Tuple {
|
||||
sport: u16::MAX,
|
||||
..flow
|
||||
};
|
||||
assert!(gateway.forward(origin, udp_packet(extra, b"no").unwrap()));
|
||||
assert!(gateway.forward(origin, udp_packet(flow, b"ok").unwrap()));
|
||||
assert_eq!(server.recv(&mut buf).await.unwrap(), 2);
|
||||
assert_eq!(&buf, b"ok");
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Winsock takes the IPv4 interface index in network byte order.
|
||||
#![allow(unsafe_code)]
|
||||
use std::{io, os::windows::io::AsRawSocket};
|
||||
use windows_sys::Win32::Networking::WinSock::{
|
||||
IP_UNICAST_IF, IPPROTO_IP, SOCKET_ERROR, WSAGetLastError, setsockopt,
|
||||
};
|
||||
|
||||
pub(super) fn pin(socket: &impl AsRawSocket, index: u32) -> io::Result<()> {
|
||||
#[cfg(test)]
|
||||
if index == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if index == 0 {
|
||||
return Err(io::Error::other("no physical exit interface"));
|
||||
}
|
||||
let bytes = index.to_be_bytes();
|
||||
// The socket owner stays alive for the call. Winsock reads exactly the
|
||||
// four bytes of the interface index and retains no pointer to them.
|
||||
if unsafe {
|
||||
setsockopt(
|
||||
socket.as_raw_socket() as _,
|
||||
IPPROTO_IP,
|
||||
IP_UNICAST_IF,
|
||||
bytes.as_ptr(),
|
||||
4,
|
||||
)
|
||||
} == SOCKET_ERROR
|
||||
{
|
||||
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -91,6 +91,12 @@ pub trait ExitHostRules: Send + Sync + std::fmt::Debug + 'static {
|
||||
Box::pin(async { None })
|
||||
}
|
||||
|
||||
/// The physical interface index and IPv4 address used by a userspace exit.
|
||||
/// Kernel-forwarding hosts do not need to expose an egress socket address.
|
||||
fn forwarded_uplink(&self) -> Option<(u32, std::net::Ipv4Addr)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether using an exit node on this host needs the underlay addresses
|
||||
/// the agent talks to, because the host cannot exempt the agent's own
|
||||
/// traffic from the default route by user id (Windows). The default is no.
|
||||
@@ -112,6 +118,9 @@ pub fn exit_tag_prefix(interface: &str) -> String {
|
||||
/// The one-line detail for a set of offer outcomes.
|
||||
pub fn offer_detail(outcome: &RuleOutcome, range: &Ipv4Range) -> String {
|
||||
match outcome {
|
||||
RuleOutcome::Applied if cfg!(windows) => {
|
||||
format!("physical TCP, UDP and ICMP echo forwarding for {range}")
|
||||
}
|
||||
RuleOutcome::Applied => format!("masquerade + forward for {range} in place"),
|
||||
RuleOutcome::Failed(reason) => reason.clone(),
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//!
|
||||
//! # Offering
|
||||
//!
|
||||
//! For every network that offers this agent as an exit node, three rules,
|
||||
//! For every network that offers this agent as an exit node, rules
|
||||
//! selected by that network's range and carrying the tag
|
||||
//! `tsunagi-exit:<if>:<range>`:
|
||||
//!
|
||||
@@ -11,6 +11,8 @@
|
||||
//! -t nat POSTROUTING -s <range> ! -o <if> -j MASQUERADE
|
||||
//! -t filter FORWARD -i <if> -s <range> ! -o <if> -j ACCEPT
|
||||
//! -t filter FORWARD -o <if> -d <range> -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
|
||||
//! -t mangle PREROUTING -i <if> -s <range> -j MARK --set-xmark <underlay bit>
|
||||
//! -t mangle PREROUTING ! -i <if> -m conntrack --ctorigsrc <range> --ctdir REPLY --ctstate SNAT -j MARK --set-xmark <underlay bit>
|
||||
//! ```
|
||||
//!
|
||||
//! `! -o <if>` is the egress without naming it: whatever interface the
|
||||
@@ -28,7 +30,7 @@
|
||||
//! 5205: from all fwmark 0x40000000/0x40000000 lookup main
|
||||
//! 5206: from all uidrange <euid>-<euid> lookup main
|
||||
//! 5290: from all lookup main suppress_prefixlength 0
|
||||
//! 5300: from all lookup 0x7473
|
||||
//! 5300: from all iif lo lookup 0x7473
|
||||
//! ```
|
||||
//!
|
||||
//! The first two keep the agent's *own* sockets and marked replies off the tunnel: its QUIC, relay,
|
||||
@@ -56,7 +58,11 @@ use super::linux::{
|
||||
use super::linux_exit_mark;
|
||||
|
||||
/// The chains the offering rules live in: `(table, chain)`.
|
||||
const CHAINS: [(&str, &str); 2] = [("nat", "POSTROUTING"), ("filter", "FORWARD")];
|
||||
const CHAINS: [(&str, &str); 3] = [
|
||||
("nat", "POSTROUTING"),
|
||||
("filter", "FORWARD"),
|
||||
("mangle", "PREROUTING"),
|
||||
];
|
||||
|
||||
/// One firewall rule: where it goes, and its match and target.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -70,7 +76,7 @@ fn owned(words: &[&str]) -> Vec<String> {
|
||||
words.iter().map(|word| word.to_string()).collect()
|
||||
}
|
||||
|
||||
/// The three rules of one offered range.
|
||||
/// The rules of one offered range.
|
||||
///
|
||||
/// Each carries a comment naming its interface and range, which is how it is
|
||||
/// found again. A kernel without the `comment` match (small router builds
|
||||
@@ -125,6 +131,37 @@ fn offer_rules(interface: &str, range: &Ipv4Range, comment: bool) -> Vec<Rule> {
|
||||
&["-j", "ACCEPT"],
|
||||
),
|
||||
},
|
||||
// These marks select the physical routing table for clients we
|
||||
// forward, including the reverse-path check on physical replies.
|
||||
// The conntrack original tuple survives switching our own upstream.
|
||||
Rule {
|
||||
table: "mangle",
|
||||
chain: "PREROUTING",
|
||||
spec: spec(
|
||||
&["-i", interface, "-s", &range_text],
|
||||
&["-j", "MARK", "--set-xmark", linux_exit_mark::MARK],
|
||||
),
|
||||
},
|
||||
Rule {
|
||||
table: "mangle",
|
||||
chain: "PREROUTING",
|
||||
spec: spec(
|
||||
&[
|
||||
"!",
|
||||
"-i",
|
||||
interface,
|
||||
"-m",
|
||||
"conntrack",
|
||||
"--ctorigsrc",
|
||||
&range_text,
|
||||
"--ctdir",
|
||||
"REPLY",
|
||||
"--ctstate",
|
||||
"SNAT",
|
||||
],
|
||||
&["-j", "MARK", "--set-xmark", linux_exit_mark::MARK],
|
||||
),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -159,7 +196,7 @@ struct Found {
|
||||
|
||||
/// Every rule in an `iptables -S <chain>` listing that is ours: carrying a
|
||||
/// tag that starts with `prefix`, or, on a kernel with no `comment` match,
|
||||
/// being exactly one of the three rules this module writes for some range.
|
||||
/// being exactly one of the rules this module writes for some range.
|
||||
/// Anything else in the chain is left alone.
|
||||
fn tagged_rules(listing: &str, chain: &str, prefix: &str) -> Vec<Found> {
|
||||
// `tsunagi-exit:<interface>:`
|
||||
@@ -198,7 +235,7 @@ fn uncommented_tag(interface: &str, chain: &str, rest: &[String]) -> Option<Stri
|
||||
}
|
||||
let range: Ipv4Range = rest
|
||||
.windows(2)
|
||||
.find(|pair| pair[0] == "-s" || pair[0] == "-d")
|
||||
.find(|pair| matches!(pair[0].as_str(), "-s" | "-d" | "--ctorigsrc"))
|
||||
.and_then(|pair| pair[1].parse().ok())?;
|
||||
offer_rules(interface, &range, false)
|
||||
.iter()
|
||||
@@ -380,7 +417,7 @@ fn read_sysctl(path: &str) -> Option<String> {
|
||||
std::fs::read_to_string(path).ok()
|
||||
}
|
||||
|
||||
fn check_kernel_rpf(overlay: &str) -> Result<(), String> {
|
||||
fn check_kernel_rpf(overlay: &str, uid: u32) -> Result<(), String> {
|
||||
let directory = "/proc/sys/net/ipv4/conf";
|
||||
let value = |name: &str, setting: &str| -> Result<u32, String> {
|
||||
read_sysctl(&format!("{directory}/{name}/{setting}"))
|
||||
@@ -391,7 +428,7 @@ fn check_kernel_rpf(overlay: &str) -> Result<(), String> {
|
||||
for entry in std::fs::read_dir(directory).map_err(|err| err.to_string())? {
|
||||
let entry = entry.map_err(|err| err.to_string())?;
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if name != "all" && name != "default" && name != "lo" && name != overlay {
|
||||
if name != "all" && name != "default" && name != "lo" && (name != overlay || uid == 0) {
|
||||
interfaces.push((
|
||||
name.clone(),
|
||||
value(&name, "rp_filter")?,
|
||||
@@ -481,7 +518,7 @@ impl LinuxHostRules {
|
||||
}
|
||||
let name = interface.to_string();
|
||||
let prepared = Self::blocking(move || {
|
||||
check_kernel_rpf(&name)?;
|
||||
check_kernel_rpf(&name, euid)?;
|
||||
linux_exit_mark::install(
|
||||
&run_firewall,
|
||||
&name,
|
||||
@@ -567,7 +604,7 @@ impl LinuxHostRules {
|
||||
.ok()
|
||||
.and_then(|s| parse_euid(&s))
|
||||
.ok_or("cannot read agent UID")?;
|
||||
check_kernel_rpf(&work_name)?;
|
||||
check_kernel_rpf(&work_name, uid)?;
|
||||
let v6 = std::path::Path::new("/proc/sys/net/ipv6").is_dir();
|
||||
let sockets = linux_exit_mark::local_sockets(uid, v6)?;
|
||||
if previous
|
||||
@@ -671,7 +708,21 @@ mod tests {
|
||||
#[test]
|
||||
fn the_rules_masquerade_the_range_out_of_every_other_interface_and_forward_it() {
|
||||
let rules = offer_rules("tsun0", &range(), true);
|
||||
assert_eq!(rules.len(), 3);
|
||||
assert_eq!(rules.len(), 5);
|
||||
let outgoing = words(&rules[3].spec);
|
||||
let replies = words(&rules[4].spec);
|
||||
assert!(
|
||||
outgoing.starts_with("-i tsun0 -s 10.13.37.0/24 "),
|
||||
"{outgoing}"
|
||||
);
|
||||
assert!(
|
||||
replies.contains("--ctorigsrc 10.13.37.0/24 --ctdir REPLY --ctstate SNAT"),
|
||||
"{replies}"
|
||||
);
|
||||
for rule in &rules[3..] {
|
||||
assert_eq!((rule.table, rule.chain), ("mangle", "PREROUTING"));
|
||||
assert!(words(&rule.spec).ends_with("-j MARK --set-xmark 0x40000000/0x40000000"));
|
||||
}
|
||||
assert_eq!(
|
||||
words(&rules[0].spec),
|
||||
"-s 10.13.37.0/24 ! -o tsun0 -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j MASQUERADE"
|
||||
@@ -805,7 +856,7 @@ mod tests {
|
||||
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||
let inserted = fake.verbs("-I");
|
||||
assert_eq!(inserted.len(), 3, "{inserted:?}");
|
||||
assert_eq!(inserted.len(), 5, "{inserted:?}");
|
||||
assert!(
|
||||
inserted.iter().all(|call| !call.contains("comment")),
|
||||
"{inserted:?}"
|
||||
@@ -837,12 +888,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_host_gets_the_three_rules() {
|
||||
fn a_fresh_host_gets_the_offer_rules() {
|
||||
let fake = Fake::new(false);
|
||||
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||
let inserted = fake.verbs("-I");
|
||||
assert_eq!(inserted.len(), 3, "{inserted:?}");
|
||||
assert_eq!(inserted.len(), 5, "{inserted:?}");
|
||||
assert!(inserted[0].contains("-t nat -I POSTROUTING 1"));
|
||||
assert!(fake.verbs("-D").is_empty());
|
||||
}
|
||||
@@ -857,6 +908,15 @@ mod tests {
|
||||
)
|
||||
.with_rule("filter", &format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"))
|
||||
.with_rule("filter", &format!("-A FORWARD -o tsun0 -m comment --comment {tag} -j ACCEPT"));
|
||||
let fake = offer_rules("tsun0", &range(), true)
|
||||
.into_iter()
|
||||
.filter(|rule| rule.chain == "PREROUTING")
|
||||
.fold(fake, |fake, rule| {
|
||||
fake.with_rule(
|
||||
rule.table,
|
||||
&format!("-A {} {}", rule.chain, words(&rule.spec)),
|
||||
)
|
||||
});
|
||||
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
|
||||
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
|
||||
assert!(fake.verbs("-I").is_empty());
|
||||
@@ -875,7 +935,7 @@ mod tests {
|
||||
"-A POSTROUTING -s 10.99.0.0/24 -m comment --comment {old_tag} -j MASQUERADE"
|
||||
),
|
||||
)
|
||||
// Only one of the three for the current range.
|
||||
// Only one rule for the current range.
|
||||
.with_rule(
|
||||
"filter",
|
||||
&format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"),
|
||||
@@ -897,7 +957,7 @@ mod tests {
|
||||
deleted.iter().all(|call| !call.contains("eth0")),
|
||||
"{deleted:?}"
|
||||
);
|
||||
assert_eq!(fake.verbs("-I").len(), 3);
|
||||
assert_eq!(fake.verbs("-I").len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -467,3 +467,214 @@ while True:
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
const CHAIN_TEST: &str = "overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit";
|
||||
|
||||
fn chain_namespace(role: &str) -> Namespace {
|
||||
let name = format!("tsng-chain-{role}-{}", std::process::id());
|
||||
ip(&["netns", "add", &name]);
|
||||
let guard = Namespace(name);
|
||||
ip(&["-n", &guard.0, "link", "set", "lo", "up"]);
|
||||
guard
|
||||
}
|
||||
|
||||
fn connect(a: &Namespace, left: &str, b: &Namespace, right: &str) {
|
||||
ip(&[
|
||||
"link", "add", left, "netns", &a.0, "type", "veth", "peer", "name", right, "netns", &b.0,
|
||||
]);
|
||||
ip(&["-n", &a.0, "link", "set", left, "up"]);
|
||||
ip(&["-n", &b.0, "link", "set", right, "up"]);
|
||||
}
|
||||
|
||||
fn python_in(namespace: &str) -> Command {
|
||||
let mut cmd = Command::new("ip");
|
||||
cmd.args(["netns", "exec", namespace, "python3"]);
|
||||
cmd
|
||||
}
|
||||
|
||||
fn chain_echo(namespace: &Namespace, name: &str) -> Echo {
|
||||
let code = r#"import socketserver, sys
|
||||
class Echo(socketserver.StreamRequestHandler):
|
||||
def handle(self):
|
||||
for line in self.rfile:
|
||||
self.wfile.write(f'{sys.argv[1]} {self.client_address[0]} '.encode() + line)
|
||||
with socketserver.ThreadingTCPServer(('198.51.100.2', 42100), Echo) as server:
|
||||
print('ready', flush=True)
|
||||
server.serve_forever()
|
||||
"#;
|
||||
let mut server = Echo(
|
||||
python_in(&namespace.0)
|
||||
.args(["-u", "-c", code, name])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let mut ready = String::new();
|
||||
BufReader::new(server.0.stdout.take().unwrap())
|
||||
.read_line(&mut ready)
|
||||
.unwrap();
|
||||
assert_eq!(ready.trim(), "ready");
|
||||
server
|
||||
}
|
||||
|
||||
fn short_chain_probe(mut cmd: Command, phase: &str, expected: &str) {
|
||||
let probe = r#"import socket
|
||||
with socket.create_connection(('198.51.100.2', 42100), timeout=3) as s:
|
||||
s.sendall(b'new\n')
|
||||
print(s.makefile('rb').readline().decode().strip())
|
||||
"#;
|
||||
let result = cmd.args(["-c", probe]).output().unwrap();
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"TCP probe {phase} expected {expected}: {}\n{}\n{}\n{}",
|
||||
String::from_utf8_lossy(&result.stderr),
|
||||
ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]),
|
||||
ip(&["-4", "rule", "show"]),
|
||||
ip(&["neigh", "show"]),
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), expected);
|
||||
}
|
||||
|
||||
fn chain_middle(a: &str) {
|
||||
use super::{BroadcastHostRules, ExitHostPlan, RuleOutcome};
|
||||
let range = "10.13.37.0/24".parse().unwrap();
|
||||
std::fs::write("/proc/sys/net/ipv4/ip_forward", "1").unwrap();
|
||||
// A root agent's UID bypass can also match a kernel reverse lookup.
|
||||
// Both the NAT reply from the uplink and the reply from C on tsun0 must
|
||||
// survive strict filtering when the remote Internet address is identical.
|
||||
for setting in ["rp_filter", "src_valid_mark"] {
|
||||
std::fs::write(format!("/proc/sys/net/ipv4/conf/all/{setting}"), "1").unwrap();
|
||||
}
|
||||
let filter: Vec<String> = [
|
||||
"-t",
|
||||
"mangle",
|
||||
"-A",
|
||||
"PREROUTING",
|
||||
"-m",
|
||||
"rpfilter",
|
||||
"--invert",
|
||||
"--validmark",
|
||||
"-j",
|
||||
"DROP",
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let rpf = run_firewall(false, &filter);
|
||||
assert!(
|
||||
matches!(rpf, super::linux::Ran::Exited { success: true, .. }),
|
||||
"{rpf:?}"
|
||||
);
|
||||
let provisioner = NetlinkProvisioner::new().unwrap();
|
||||
let host = provisioner.host_rules();
|
||||
let exit = host.exit_rules().unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let apply = |select| {
|
||||
let plan = ExitHostPlan {
|
||||
interface: "tsun0".into(),
|
||||
offer: vec![range],
|
||||
overlay: vec![range],
|
||||
client: select,
|
||||
client_source: select.then(|| "10.13.37.1".parse().unwrap()),
|
||||
..Default::default()
|
||||
};
|
||||
let result = runtime.block_on(exit.apply(&plan));
|
||||
assert_eq!(result.offer, [(range, RuleOutcome::Applied)]);
|
||||
assert_eq!(result.client, select.then_some(RuleOutcome::Applied));
|
||||
};
|
||||
apply(false);
|
||||
// The socket is created once and remains open across both reconciliations.
|
||||
let persistent = r#"import socket, sys
|
||||
with socket.create_connection(('198.51.100.2',42100), timeout=3) as s:
|
||||
out = s.makefile('rb')
|
||||
for line in sys.stdin.buffer:
|
||||
s.sendall(line)
|
||||
print(out.readline().decode().strip(), flush=True)
|
||||
"#;
|
||||
let mut stream = Echo(
|
||||
python_in(a)
|
||||
.args(["-u", "-c", persistent])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let mut input = stream.0.stdin.take().unwrap();
|
||||
let mut output = BufReader::new(stream.0.stdout.take().unwrap());
|
||||
for (change, phase, b_egress) in [
|
||||
(None, "before", "uplink 192.0.2.1 new"),
|
||||
(Some(true), "selected", "exit-c 10.13.37.1 new"),
|
||||
(Some(false), "cleared", "uplink 192.0.2.1 new"),
|
||||
] {
|
||||
if let Some(selected) = change {
|
||||
apply(selected);
|
||||
}
|
||||
writeln!(input, "{phase}").unwrap();
|
||||
let mut reply = String::new();
|
||||
output.read_line(&mut reply).unwrap();
|
||||
assert_eq!(
|
||||
reply.trim(),
|
||||
format!("uplink 192.0.2.1 {phase}"),
|
||||
"ongoing TCP stream from A"
|
||||
);
|
||||
short_chain_probe(python_in(a), phase, "uplink 192.0.2.1 new");
|
||||
// A regular application on B sends to exactly the same IP and port as A.
|
||||
let mut local = Command::new("python3");
|
||||
local.uid(991).gid(991);
|
||||
short_chain_probe(local, phase, b_egress);
|
||||
}
|
||||
runtime.block_on(exit.clear("tsun0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs Linux network namespaces, iproute2, iptables and Python"]
|
||||
fn serving_an_established_flow_while_switching_the_local_exit() {
|
||||
if let Ok(a) = std::env::var("TSUNAGI_EXIT_CHAIN_A") {
|
||||
chain_middle(&a);
|
||||
return;
|
||||
}
|
||||
let a = chain_namespace("a");
|
||||
let b = chain_namespace("b");
|
||||
let c = chain_namespace("c");
|
||||
let uplink = chain_namespace("wan");
|
||||
// Emulate the one overlay interface on B. The bridge is a separate
|
||||
// namespace so that A, B and C see only packets on their own veth.
|
||||
let mesh = chain_namespace("lan");
|
||||
ip(&["-n", &mesh.0, "link", "add", "mesh", "type", "bridge"]);
|
||||
ip(&["-n", &mesh.0, "link", "set", "mesh", "up"]);
|
||||
for (ns, port, address) in [
|
||||
(&a, "to-a", "10.13.37.2/24"),
|
||||
(&b, "to-b", "10.13.37.1/24"),
|
||||
(&c, "to-c", "10.13.37.3/24"),
|
||||
] {
|
||||
connect(ns, "tsun0", &mesh, port);
|
||||
ip(&["-n", &mesh.0, "link", "set", port, "master", "mesh"]);
|
||||
ip(&["-n", &ns.0, "addr", "add", address, "dev", "tsun0"]);
|
||||
}
|
||||
connect(&b, "wan-b", &uplink, "wan");
|
||||
ip(&["-n", &b.0, "addr", "add", "192.0.2.1/24", "dev", "wan-b"]);
|
||||
ip(&["-n", &uplink.0, "addr", "add", "192.0.2.2/24", "dev", "wan"]);
|
||||
ip(&["-n", &a.0, "route", "add", "default", "via", "10.13.37.1"]);
|
||||
ip(&["-n", &b.0, "route", "add", "default", "via", "192.0.2.2"]);
|
||||
for ns in [&uplink, &c] {
|
||||
ip(&["-n", &ns.0, "addr", "add", "198.51.100.2/32", "dev", "lo"]);
|
||||
}
|
||||
let _physical = chain_echo(&uplink, "uplink");
|
||||
let _exit = chain_echo(&c, "exit-c");
|
||||
let result = Command::new("ip")
|
||||
.args(["netns", "exec", &b.0])
|
||||
.arg(std::env::current_exe().unwrap())
|
||||
.args(["--ignored", "--exact", CHAIN_TEST, "--nocapture"])
|
||||
.env("TSUNAGI_EXIT_CHAIN_A", &a.0)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&result.stdout),
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
}
|
||||
@@ -8,8 +8,10 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
/// Outside Tailscale's 0xff0000 mask and ordinary low-bit WireGuard marks.
|
||||
pub(crate) const UNDERLAY_MARK: u32 = 0x4000_0000;
|
||||
pub(crate) const UNDERLAY_MASK: u32 = UNDERLAY_MARK;
|
||||
const MARK: &str = "0x40000000/0x40000000";
|
||||
pub(super) const MARK: &str = "0x40000000/0x40000000";
|
||||
const MASK: &str = "0x40000000";
|
||||
/// An authenticated return packet from this host’s own upstream exit.
|
||||
pub(crate) const EXIT_REPLY_MARK: u32 = 0x2000_0000;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) struct Listener {
|
||||
@@ -141,11 +143,11 @@ fn words(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|s| (*s).into()).collect()
|
||||
}
|
||||
|
||||
fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||
fn rules(interface: &str, uid: u32, ipv6: bool) -> Vec<(&'static str, Vec<String>)> {
|
||||
let tag = tag(interface);
|
||||
let uid = uid.to_string();
|
||||
let owner = uid.to_string();
|
||||
// Insert at position one in this order: final OUTPUT order is MARK, SAVE.
|
||||
vec![
|
||||
let mut rules = vec![
|
||||
(
|
||||
"PREROUTING",
|
||||
words(&[
|
||||
@@ -175,7 +177,7 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||
"-m",
|
||||
"owner",
|
||||
"--uid-owner",
|
||||
&uid,
|
||||
&owner,
|
||||
"-m",
|
||||
"mark",
|
||||
"--mark",
|
||||
@@ -199,7 +201,7 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||
"-m",
|
||||
"owner",
|
||||
"--uid-owner",
|
||||
&uid,
|
||||
&owner,
|
||||
"-m",
|
||||
"comment",
|
||||
"--comment",
|
||||
@@ -210,7 +212,40 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
|
||||
MARK,
|
||||
]),
|
||||
),
|
||||
]
|
||||
];
|
||||
if !ipv6 && uid == 0 {
|
||||
// Both xt_rpfilter and the kernel's strict rp_filter perform the
|
||||
// reverse lookup as UID 0. For an established local application's
|
||||
// reply from our upstream, the /0 must point back to this interface,
|
||||
// ahead of the root daemon's UID bypass. The actual packet's LOCAL
|
||||
// destination still uses routing table local at priority zero.
|
||||
rules.push((
|
||||
"PREROUTING",
|
||||
words(&[
|
||||
"-i",
|
||||
interface,
|
||||
"-m",
|
||||
"addrtype",
|
||||
"--dst-type",
|
||||
"LOCAL",
|
||||
"-m",
|
||||
"conntrack",
|
||||
"--ctdir",
|
||||
"REPLY",
|
||||
"--ctstate",
|
||||
"ESTABLISHED,RELATED",
|
||||
"-m",
|
||||
"comment",
|
||||
"--comment",
|
||||
&tag,
|
||||
"-j",
|
||||
"MARK",
|
||||
"--set-xmark",
|
||||
"0x20000000/0x20000000",
|
||||
]),
|
||||
));
|
||||
}
|
||||
rules
|
||||
}
|
||||
|
||||
fn execute(run: RunFamily<'_>, v6: bool, args: Vec<String>) -> Result<String, String> {
|
||||
@@ -295,7 +330,7 @@ fn install_with_listeners(
|
||||
clear(run, interface, v6)?;
|
||||
let result = (|| {
|
||||
for family in [false, true].into_iter().filter(|family| !family || v6) {
|
||||
for (chain, spec) in rules(interface, uid) {
|
||||
for (chain, spec) in rules(interface, uid, family) {
|
||||
let args = words(&["-t", "mangle", "-I", chain, "1"])
|
||||
.into_iter()
|
||||
.chain(spec)
|
||||
@@ -409,6 +444,25 @@ mod tests {
|
||||
assert_eq!(UNDERLAY_MASK & 0x00ff_0000, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_root_daemons_mark_local_ipv4_replies_from_their_own_exit() {
|
||||
for (uid, v6) in [(990, false), (0, true), (0, false)] {
|
||||
let rules = rules("tsun0", uid, v6);
|
||||
let marked: Vec<_> = rules
|
||||
.iter()
|
||||
.filter(|(_, args)| args.contains(&"0x20000000/0x20000000".to_string()))
|
||||
.collect();
|
||||
if uid == 0 && !v6 {
|
||||
assert_eq!(marked.len(), 1);
|
||||
assert_eq!(marked[0].0, "PREROUTING");
|
||||
let text = marked[0].1.join(" ");
|
||||
assert!(text.contains("-i tsun0 -m addrtype --dst-type LOCAL -m conntrack --ctdir REPLY --ctstate ESTABLISHED,RELATED"));
|
||||
} else {
|
||||
assert!(marked.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_retains_other_interfaces_and_rolls_back_partial_ipv6_installation() {
|
||||
let calls = RefCell::new(Vec::new());
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
//!
|
||||
//! ```text
|
||||
//! nat on <egress> inet from <range> to any -> (<egress>)
|
||||
//! pass in quick on <if> inet from <range> to ! <range>
|
||||
//! pass in quick on <if> inet from <range> to ! <range> tag <forwarded> no state
|
||||
//! pass out quick on <if> route-to (<egress> <gateway>) inet from <range> to any tagged <forwarded> no state
|
||||
//! pass out quick on <egress> inet from any to any flags any tagged <forwarded> keep state (if-bound)
|
||||
//! ```
|
||||
//!
|
||||
//! The anchor lives under `com.apple/` on purpose: the stock `/etc/pf.conf`
|
||||
@@ -310,6 +312,10 @@ fn pf_rules(
|
||||
let mut nat = Vec::new();
|
||||
let mut filter = Vec::new();
|
||||
let mut tables = Vec::new();
|
||||
let via = match egress.gateway {
|
||||
Some(gateway) => format!("({out} {gateway})"),
|
||||
None => out.clone(),
|
||||
};
|
||||
if let Some(client) = client {
|
||||
let tag = format!("tsng_underlay_{interface}");
|
||||
nat.push(format!(
|
||||
@@ -327,10 +333,6 @@ fn pf_rules(
|
||||
));
|
||||
format!("! <tsunagi_overlay_{interface}>")
|
||||
};
|
||||
let via = match egress.gateway {
|
||||
Some(gateway) => format!("({out} {gateway})"),
|
||||
None => out.clone(),
|
||||
};
|
||||
filter.push(format!(
|
||||
"pass out quick on {interface} route-to {via} inet proto {{ tcp udp }} \
|
||||
from any to {target} user {} tag {tag} no state",
|
||||
@@ -347,8 +349,24 @@ fn pf_rules(
|
||||
// PF takes the first matching NAT rule. Preserve the transport's source
|
||||
// port even when its overlay source falls inside one of our own offers.
|
||||
nat.push(format!("nat on {out} inet from {range} to any -> ({out})"));
|
||||
let tag = format!("tsng_forward_{interface}");
|
||||
// Classify at authenticated overlay ingress. Only packets the host
|
||||
// actually forwards AND its routes send back to our utun need steering.
|
||||
// Local services, connected LANs and the owner's forwarding switch
|
||||
// retain their native kernel behavior.
|
||||
filter.push(format!(
|
||||
"pass in quick on {interface} inet from {range} to ! {range}"
|
||||
"pass in quick on {interface} inet from {range} to ! {range} tag {tag} no state"
|
||||
));
|
||||
}
|
||||
if !offer.is_empty() {
|
||||
let tag = format!("tsng_forward_{interface}");
|
||||
filter.insert(0, format!(
|
||||
"pass out quick on {interface} route-to {via} inet from any to any tagged {tag} no state"
|
||||
));
|
||||
// Keep the outbound NAT state on the physical interface. A floating
|
||||
// state could consume packets on the utun before the reroute rule runs.
|
||||
filter.push(format!(
|
||||
"pass out quick on {out} inet from any to any flags any tagged {tag} keep state (if-bound)"
|
||||
));
|
||||
}
|
||||
tables
|
||||
@@ -993,7 +1011,9 @@ destination: default\n\
|
||||
assert_eq!(
|
||||
text,
|
||||
"nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\n"
|
||||
pass out quick on utun5 route-to (en0 192.168.1.1) inet from any to any tagged tsng_forward_utun5 no state\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
|
||||
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
|
||||
);
|
||||
// Translation precedes filtering, as pf requires.
|
||||
assert!(text.find("nat on").unwrap() < text.find("pass in").unwrap());
|
||||
@@ -1114,7 +1134,9 @@ destination: default\n\
|
||||
assert_eq!(
|
||||
fake.stdins.borrow()[0],
|
||||
"nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\n"
|
||||
pass out quick on utun5 route-to (en0 192.168.1.1) inet from any to any tagged tsng_forward_utun5 no state\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
|
||||
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
|
||||
);
|
||||
// sysctl is only ever asked, never told.
|
||||
assert!(
|
||||
|
||||
@@ -66,14 +66,14 @@ impl Drop for Capture<'_> {
|
||||
}
|
||||
|
||||
impl Capture<'_> {
|
||||
fn enable(&mut self) {
|
||||
fn offer(&self, use_upstream: bool) {
|
||||
let ranges = [FIRST, SECOND]
|
||||
.map(|ip| Ipv4Range::new(Ipv4Addr::from(u32::from(ip) & !0xf), 28).unwrap());
|
||||
let rules = pf_rules(
|
||||
self.overlay,
|
||||
&self.uplink,
|
||||
&[],
|
||||
Some(&ClientRules {
|
||||
&ranges[..1],
|
||||
use_upstream.then_some(&ClientRules {
|
||||
uid: 0,
|
||||
overlay: &ranges,
|
||||
}),
|
||||
@@ -86,6 +86,9 @@ impl Capture<'_> {
|
||||
Some(&rules),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
fn enable(&mut self) {
|
||||
self.offer(true);
|
||||
run_ok(
|
||||
&run_tool,
|
||||
Tool::Route,
|
||||
@@ -250,6 +253,45 @@ async fn udp_round_trip(uplink: &dyn TunDevice, socket: &UdpSocket, stage: &str)
|
||||
assert_eq!(&buf[..len], b"QUIC path");
|
||||
}
|
||||
|
||||
async fn member_round_trip(
|
||||
overlay: &dyn TunDevice,
|
||||
uplink: &dyn TunDevice,
|
||||
port: u16,
|
||||
data: &[u8],
|
||||
) -> u16 {
|
||||
let member = Ipv4Addr::from(u32::from(FIRST) + 2);
|
||||
let ip = Ipv4Repr {
|
||||
src_addr: member,
|
||||
dst_addr: REMOTE,
|
||||
next_header: IpProtocol::Udp,
|
||||
payload_len: 8 + data.len(),
|
||||
hop_limit: 64,
|
||||
};
|
||||
let mut raw = vec![0; ip.buffer_len() + ip.payload_len];
|
||||
let mut out = Ipv4Packet::new_unchecked(&mut raw[..]);
|
||||
ip.emit(&mut out, &Default::default());
|
||||
let mut udp = UdpPacket::new_unchecked(out.payload_mut());
|
||||
udp.set_len(ip.payload_len as u16);
|
||||
udp.set_src_port(port);
|
||||
udp.set_dst_port(8020);
|
||||
udp.payload_mut().copy_from_slice(data);
|
||||
udp.fill_checksum(&member.into(), &REMOTE.into());
|
||||
overlay.send(raw.into()).await.unwrap();
|
||||
let outbound = packet(uplink, REMOTE, IpProtocol::Udp, 8020, data).await;
|
||||
let physical = Ipv4Packet::new_checked(&outbound[..]).unwrap();
|
||||
assert_eq!(physical.src_addr(), UPLINK);
|
||||
let translated = UdpPacket::new_checked(physical.payload())
|
||||
.unwrap()
|
||||
.src_port();
|
||||
uplink.send(reply(&outbound)).await.unwrap();
|
||||
let inbound = packet(overlay, member, IpProtocol::Udp, port, data).await;
|
||||
assert_eq!(
|
||||
Ipv4Packet::new_checked(&inbound[..]).unwrap().src_addr(),
|
||||
REMOTE
|
||||
);
|
||||
translated
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires root, the stock Apple PF anchor, and a disposable macOS runner"]
|
||||
async fn exit_preserves_underlay_and_both_meshes() {
|
||||
@@ -272,7 +314,16 @@ async fn exit_preserves_underlay_and_both_meshes() {
|
||||
added_route: false,
|
||||
added_scoped: false,
|
||||
};
|
||||
// The disposable runner enables kernel forwarding. A keeps the same
|
||||
// translated address and port when B installs an upstream route to this IP.
|
||||
capture.offer(false);
|
||||
let port = member_round_trip(&*overlay, &*uplink, 43001, b"member before").await;
|
||||
capture.enable();
|
||||
assert_eq!(
|
||||
member_round_trip(&*overlay, &*uplink, 43001, b"member during").await,
|
||||
port
|
||||
);
|
||||
member_round_trip(&*overlay, &*uplink, 43002, b"new member flow").await;
|
||||
check_capture_routes(overlay.name(), uplink.name());
|
||||
udp_round_trip(&*uplink, &existing_quic, "existing socket after exit").await;
|
||||
|
||||
|
||||
@@ -159,6 +159,19 @@ async fn step(what: &'static str, script: String) -> RuleOutcome {
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WindowsHostRules {
|
||||
relay_cache: Arc<Mutex<RelayCache>>,
|
||||
uplink: Arc<Mutex<Option<(u32, Ipv4Addr)>>>,
|
||||
}
|
||||
|
||||
/// A temporary inventory failure cannot revoke existing sockets. A positive
|
||||
/// withdrawal of the last offer releases their uplink.
|
||||
fn remember_uplink(
|
||||
cache: &Mutex<Option<(u32, Ipv4Addr)>>,
|
||||
offering: bool,
|
||||
observed: Option<(u32, Ipv4Addr)>,
|
||||
) {
|
||||
if !offering || observed.is_some() {
|
||||
*cache.lock().unwrap_or_else(|e| e.into_inner()) = observed;
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowsHostRules {
|
||||
@@ -233,6 +246,10 @@ fn resolve_host(host: &str) -> Vec<std::net::Ipv4Addr> {
|
||||
}
|
||||
|
||||
impl ExitHostRules for WindowsHostRules {
|
||||
fn forwarded_uplink(&self) -> Option<(u32, Ipv4Addr)> {
|
||||
*self.uplink.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn needs_bypass(&self) -> bool {
|
||||
true
|
||||
}
|
||||
@@ -241,17 +258,20 @@ impl ExitHostRules for WindowsHostRules {
|
||||
Box::pin(async move {
|
||||
let job = plan.clone();
|
||||
let cache = Arc::clone(&self.relay_cache);
|
||||
let uplink = Arc::clone(&self.uplink);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let hosts = cache.lock().unwrap_or_else(|p| p.into_inner()).lookup(
|
||||
&job.bypass_hosts,
|
||||
Instant::now(),
|
||||
&resolve_host,
|
||||
);
|
||||
windows_exit::apply_plan(
|
||||
let (report, physical) = windows_exit::reconcile(
|
||||
&|script| run_powershell_output(script),
|
||||
&|host| hosts.get(host).cloned().unwrap_or_default(),
|
||||
&job,
|
||||
)
|
||||
);
|
||||
remember_uplink(&uplink, !job.offer.is_empty(), physical);
|
||||
report
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
@@ -271,11 +291,12 @@ impl ExitHostRules for WindowsHostRules {
|
||||
|
||||
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
|
||||
Box::pin(async move {
|
||||
if !plan.client {
|
||||
if !plan.client && plan.offer.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let job = plan.clone();
|
||||
let cache = Arc::clone(&self.relay_cache);
|
||||
let uplink = Arc::clone(&self.uplink);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let now = Instant::now();
|
||||
let mut cache = cache.lock().unwrap_or_else(|p| p.into_inner());
|
||||
@@ -287,6 +308,16 @@ impl ExitHostRules for WindowsHostRules {
|
||||
}
|
||||
let hosts = cache.lookup(&job.bypass_hosts, now, &resolve_host);
|
||||
drop(cache);
|
||||
if !job.offer.is_empty() {
|
||||
remember_uplink(
|
||||
&uplink,
|
||||
true,
|
||||
windows_exit::uplink(&run_powershell_output, &job.interface).ok(),
|
||||
);
|
||||
}
|
||||
if !job.client {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
match windows_exit::refresh_bypass(
|
||||
&run_powershell_output,
|
||||
@@ -307,7 +338,9 @@ impl ExitHostRules for WindowsHostRules {
|
||||
Box::pin(async move {
|
||||
let name = interface.to_string();
|
||||
let cache = Arc::clone(&self.relay_cache);
|
||||
let uplink = Arc::clone(&self.uplink);
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
*uplink.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
*cache.lock().unwrap_or_else(|p| p.into_inner()) = RelayCache::default();
|
||||
windows_exit::clear_all(&|script| run_powershell_output(script), &name)
|
||||
})
|
||||
@@ -355,6 +388,22 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn transient_uplink_lookup_failure_preserves_the_live_forwarding_address() {
|
||||
let cache = Mutex::new(None);
|
||||
let old = (4, Ipv4Addr::new(192, 0, 2, 5));
|
||||
let new = (7, Ipv4Addr::new(198, 51, 100, 3));
|
||||
for (offering, observed, expected) in [
|
||||
(true, Some(old), Some(old)),
|
||||
(true, None, Some(old)),
|
||||
(true, Some(new), Some(new)),
|
||||
(false, None, None),
|
||||
] {
|
||||
remember_uplink(&cache, offering, observed);
|
||||
assert_eq!(*cache.lock().unwrap(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_dns_survives_a_transient_failure_and_retires_rotated_addresses() {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Exit-node host rules on Windows: WinNAT through PowerShell.
|
||||
//! Physical exit socket selection and client routes on Windows, through PowerShell.
|
||||
//!
|
||||
//! Compiled on every platform so the scripts and the plan logic are tested
|
||||
//! everywhere; only `WindowsHostRules` runs them, and only on Windows. It
|
||||
@@ -6,20 +6,10 @@
|
||||
//!
|
||||
//! # Offering
|
||||
//!
|
||||
//! One NAT object per offered range, named with the usual tag
|
||||
//! `tsunagi-exit:<if>:<range>`:
|
||||
//!
|
||||
//! ```text
|
||||
//! New-NetNat -Name <tag> -InternalIPInterfaceAddressPrefix <range>
|
||||
//! ```
|
||||
//!
|
||||
//! WinNAT translates that range out of whichever interface the traffic leaves
|
||||
//! by, which is the Windows counterpart of the Linux masquerade. Windows
|
||||
//! forwards per interface, and the egress is not known here, so forwarding is
|
||||
//! only *read* for the overlay interface; turning it on for the interfaces
|
||||
//! involved is the owner's decision (`Set-NetIPInterface -Forwarding Enabled`).
|
||||
//! Some Windows versions allow a single NAT per host: a second offered range
|
||||
//! then reports its own failure.
|
||||
//! Forwarded TCP/UDP and ICMP echo use sockets pinned to the physical
|
||||
//! interface and address. This keeps a member's traffic independent of local
|
||||
//! split routes even for the same destination. The userspace gateway owns the
|
||||
//! flows; changing a local upstream does not recreate them.
|
||||
//!
|
||||
//! # Using
|
||||
//!
|
||||
@@ -51,7 +41,7 @@
|
||||
use super::RuleOutcome;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, exit_tag, exit_tag_prefix};
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, exit_tag_prefix};
|
||||
use crate::state::Ipv4Range;
|
||||
|
||||
/// The route metric that marks a bypass route as this agent's.
|
||||
@@ -68,64 +58,67 @@ fn ps_literal(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
/// Creates the NAT of one range, replacing one this agent made before.
|
||||
fn nat_script(interface: &str, range: &Ipv4Range) -> String {
|
||||
let name = ps_literal(&exit_tag(interface, range));
|
||||
let prefix = ps_literal(&range.to_string());
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
$name = {name}\n\
|
||||
Get-NetNat -Name $name -ErrorAction SilentlyContinue | \
|
||||
Remove-NetNat -Confirm:$false -ErrorAction SilentlyContinue\n\
|
||||
New-NetNat -Name $name -InternalIPInterfaceAddressPrefix {prefix} | Out-Null\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes this interface's NAT objects except those named in `keep`.
|
||||
fn prune_script(interface: &str, keep: &[Ipv4Range]) -> String {
|
||||
/// Remove only obsolete WinNAT objects created by older Tsunagi releases.
|
||||
fn legacy_nat_cleanup(interface: &str) -> String {
|
||||
let prefix = ps_literal(&exit_tag_prefix(interface));
|
||||
let keep: Vec<String> = keep
|
||||
.iter()
|
||||
.map(|range| ps_literal(&exit_tag(interface, range)))
|
||||
.collect();
|
||||
format!(
|
||||
"$ErrorActionPreference = 'SilentlyContinue'\n\
|
||||
$prefix = {prefix}\n\
|
||||
$keep = @({})\n\
|
||||
Get-NetNat | Where-Object {{ $_.Name.StartsWith($prefix) -and \
|
||||
($keep -notcontains $_.Name) }} | Remove-NetNat -Confirm:$false\n\
|
||||
exit 0\n",
|
||||
keep.join(", ")
|
||||
$prefix = {prefix}\n\
|
||||
Get-NetNat | Where-Object {{ $_.Name.StartsWith($prefix) }} | Remove-NetNat -Confirm:$false\n\
|
||||
exit 0"
|
||||
)
|
||||
}
|
||||
|
||||
/// Prints `Enabled` or `Disabled` for the interface's IPv4 forwarding.
|
||||
fn forwarding_script(interface: &str) -> String {
|
||||
/// Both client bypasses and forwarded sockets use the winning /0 outside Wintun.
|
||||
fn select_gateway(interface: &str) -> String {
|
||||
let alias = ps_literal(interface);
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
(Get-NetIPInterface -InterfaceAlias {alias} -AddressFamily IPv4).Forwarding\n"
|
||||
$alias = {alias}\n\
|
||||
$best = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 \
|
||||
-PolicyStore ActiveStore | Where-Object {{ $_.InterfaceAlias -ne $alias -and \
|
||||
$_.NextHop -ne '0.0.0.0' -and $_.State -ne 'Dead' }} | Sort-Object {{ $_.RouteMetric + \
|
||||
(Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \
|
||||
Select-Object -First 1\n\
|
||||
if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Prints the physical default and the more specific routes that already
|
||||
/// outrank the split defaults. Ignore our own host routes when refreshing.
|
||||
/// Read a usable source on the selected physical interface, even while the two
|
||||
/// client /1 routes point at Wintun. Never ask the default via the test target.
|
||||
fn uplink_script(interface: &str) -> String {
|
||||
format!(
|
||||
"{}$source = Get-NetIPAddress -InterfaceIndex $best.InterfaceIndex -AddressFamily IPv4 \
|
||||
-AddressState Preferred | Where-Object {{ -not $_.SkipAsSource }} | Select-Object -First 1\n\
|
||||
if (-not $source) {{ throw 'the physical interface has no usable IPv4 address' }}\n\
|
||||
\"$($best.InterfaceIndex) $($source.IPAddress)\"",
|
||||
select_gateway(interface)
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn uplink(run: RunScript<'_>, interface: &str) -> Result<(u32, Ipv4Addr), String> {
|
||||
let text = run(&uplink_script(interface))?;
|
||||
parse_gateway(&text)
|
||||
.filter(|(i, ip)| {
|
||||
*i != 0
|
||||
&& !ip.is_unspecified()
|
||||
&& !ip.is_multicast()
|
||||
&& !ip.is_loopback()
|
||||
&& !ip.is_broadcast()
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
"cannot determine the physical interface and IPv4 source for forwarding".into()
|
||||
})
|
||||
}
|
||||
|
||||
fn gateway_script(interface: &str) -> String {
|
||||
let alias = ps_literal(interface);
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\n\
|
||||
$alias = {alias}\n\
|
||||
$best = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 \
|
||||
-PolicyStore ActiveStore | Where-Object {{ $_.InterfaceAlias -ne $alias -and \
|
||||
$_.NextHop -ne '0.0.0.0' }} | Sort-Object {{ $_.RouteMetric + \
|
||||
(Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \
|
||||
Select-Object -First 1\n\
|
||||
if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n\
|
||||
\"$($best.InterfaceIndex) $($best.NextHop)\"\n\
|
||||
"{}\"$($best.InterfaceIndex) $($best.NextHop)\"\n\
|
||||
Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{ \
|
||||
$_.InterfaceAlias -ne $alias -and $_.State -ne 'Dead' -and \
|
||||
-not ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32')) }} | \
|
||||
Select-Object -ExpandProperty DestinationPrefix\n"
|
||||
Select-Object -ExpandProperty DestinationPrefix\n",
|
||||
select_gateway(interface)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -269,35 +262,25 @@ fn apply_client(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_forwarding(text: &str) -> Option<bool> {
|
||||
match text.trim().to_ascii_lowercase().as_str() {
|
||||
"enabled" | "1" => Some(true),
|
||||
"disabled" | "0" => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the host match the plan.
|
||||
pub(super) fn apply_plan(
|
||||
/// Decide the egress for all offered memberships, then reconcile the separate
|
||||
/// destination routes used by this device's applications.
|
||||
pub(super) fn reconcile(
|
||||
run: RunScript<'_>,
|
||||
resolve: Resolve<'_>,
|
||||
plan: &ExitHostPlan,
|
||||
) -> ExitHostReport {
|
||||
) -> (ExitHostReport, Option<(u32, Ipv4Addr)>) {
|
||||
let interface = plan.interface.as_str();
|
||||
// What an earlier plan left and this one no longer wants.
|
||||
let pruned = run(&prune_script(interface, &plan.offer));
|
||||
let physical = (!plan.offer.is_empty()).then(|| uplink(run, interface));
|
||||
let offer = plan
|
||||
.offer
|
||||
.iter()
|
||||
.map(|range| {
|
||||
let outcome = match &pruned {
|
||||
Err(why) => RuleOutcome::Failed(why.clone()),
|
||||
Ok(_) => match run(&nat_script(interface, range)) {
|
||||
Ok(_) => RuleOutcome::Applied,
|
||||
Err(why) => RuleOutcome::Failed(why),
|
||||
},
|
||||
let result = match &physical {
|
||||
Some(Ok(_)) => RuleOutcome::Applied,
|
||||
Some(Err(why)) => RuleOutcome::Failed(why.clone()),
|
||||
None => RuleOutcome::Failed("no exit offer".into()),
|
||||
};
|
||||
(*range, outcome)
|
||||
(*range, result)
|
||||
})
|
||||
.collect();
|
||||
let client = if plan.client {
|
||||
@@ -310,23 +293,19 @@ pub(super) fn apply_plan(
|
||||
let _ = run(&remove_client_script(interface));
|
||||
None
|
||||
};
|
||||
let forwarding = if plan.offer.is_empty() {
|
||||
None
|
||||
} else {
|
||||
run(&forwarding_script(interface))
|
||||
.ok()
|
||||
.and_then(|text| parse_forwarding(&text))
|
||||
};
|
||||
ExitHostReport {
|
||||
offer,
|
||||
forwarding,
|
||||
client,
|
||||
}
|
||||
(
|
||||
ExitHostReport {
|
||||
offer,
|
||||
forwarding: None,
|
||||
client,
|
||||
},
|
||||
physical.and_then(Result::ok),
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes every NAT object of this agent's for the interface.
|
||||
pub(super) fn clear_all(run: RunScript<'_>, interface: &str) {
|
||||
if let Err(why) = run(&prune_script(interface, &[])) {
|
||||
if let Err(why) = run(&legacy_nat_cleanup(interface)) {
|
||||
tracing::warn!(interface, "cannot remove the exit node NAT: {why}");
|
||||
}
|
||||
if let Err(why) = run(&remove_client_script(interface)) {
|
||||
@@ -357,84 +336,51 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nat_is_named_with_the_tag_and_replaces_its_own() {
|
||||
let script = nat_script("tsun0", &range());
|
||||
assert!(
|
||||
script.contains("$name = 'tsunagi-exit:tsun0:10.13.37.0/24'"),
|
||||
"{script}"
|
||||
);
|
||||
assert!(script.contains("-InternalIPInterfaceAddressPrefix '10.13.37.0/24'"));
|
||||
assert!(
|
||||
script.find("Remove-NetNat").unwrap() < script.find("New-NetNat").unwrap(),
|
||||
"{script}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quote_in_a_value_cannot_escape_the_literal() {
|
||||
let script = nat_script("x'; Remove-Item C:\\ #", &range());
|
||||
assert!(script.contains("'tsunagi-exit:x''; Remove-Item C:\\ #:10.13.37.0/24'"));
|
||||
assert!(prune_script("x'y", &[]).contains("'tsunagi-exit:x''y:'"));
|
||||
assert!(forwarding_script("x'y").contains("'x''y'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pruning_keeps_wanted_ranges_and_only_selects_this_interfaces_nats() {
|
||||
let script = prune_script("tsun0", &[range()]);
|
||||
assert!(script.contains("$prefix = 'tsunagi-exit:tsun0:'"));
|
||||
assert!(script.contains("$keep = @('tsunagi-exit:tsun0:10.13.37.0/24')"));
|
||||
assert!(script.contains("StartsWith($prefix)"));
|
||||
assert!(script.contains("exit 0"));
|
||||
assert!(prune_script("tsun0", &[]).contains("$keep = @()"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarding_text_is_read_never_written() {
|
||||
assert_eq!(parse_forwarding("Enabled\r\n"), Some(true));
|
||||
assert_eq!(parse_forwarding("Disabled"), Some(false));
|
||||
assert_eq!(parse_forwarding("what"), None);
|
||||
let script = forwarding_script("tsun0");
|
||||
assert!(script.contains("Get-NetIPInterface"));
|
||||
assert!(!script.contains("Set-NetIPInterface"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offering_prunes_then_creates_and_reads_forwarding() {
|
||||
fn selecting_an_upstream_never_recreates_a_forwarded_session_or_installs_a_destination_exception()
|
||||
{
|
||||
let calls = RefCell::new(Vec::new());
|
||||
let run = |script: &str| -> Result<String, String> {
|
||||
calls.borrow_mut().push(script.to_string());
|
||||
Ok(if script.contains("Get-NetIPInterface") {
|
||||
"Disabled\n".to_string()
|
||||
Ok(if script.contains("Get-NetIPAddress") {
|
||||
"7 192.0.2.15".into()
|
||||
} else if script.contains("Select-Object -ExpandProperty DestinationPrefix") {
|
||||
"7 192.0.2.1".into()
|
||||
} else {
|
||||
String::new()
|
||||
})
|
||||
};
|
||||
let report = apply_plan(&run, &no_names, &plan(false));
|
||||
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
|
||||
assert_eq!(report.forwarding, Some(false));
|
||||
assert_eq!(report.client, None);
|
||||
let calls = calls.borrow();
|
||||
assert!(calls[0].contains("StartsWith"), "{calls:?}");
|
||||
assert!(calls[1].contains("New-NetNat"), "{calls:?}");
|
||||
// Without a client, the routes of an earlier plan are taken away.
|
||||
assert!(calls[2].contains("RouteMetric -eq 7373"), "{calls:?}");
|
||||
assert!(calls[3].contains("Get-NetIPInterface"), "{calls:?}");
|
||||
for client in [false, true, false] {
|
||||
let (report, physical) = reconcile(&run, &no_names, &plan(client));
|
||||
assert_eq!(physical, Some((7, "192.0.2.15".parse().unwrap())));
|
||||
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
|
||||
assert_eq!(report.forwarding, None);
|
||||
}
|
||||
assert!(
|
||||
!calls
|
||||
.borrow()
|
||||
.iter()
|
||||
.any(|s| s.contains("NetNat") || s.contains("Set-NetIPInterface"))
|
||||
);
|
||||
assert!(uplink_script("x'y").contains("'x''y'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_nat_is_that_ranges_failure() {
|
||||
let run = |script: &str| -> Result<String, String> {
|
||||
if script.contains("New-NetNat") {
|
||||
Err("A NAT with this prefix already exists".into())
|
||||
} else {
|
||||
Ok(String::new())
|
||||
}
|
||||
};
|
||||
let report = apply_plan(&run, &no_names, &plan(false));
|
||||
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
|
||||
panic!("{report:?}");
|
||||
};
|
||||
assert!(why.contains("already exists"), "{why}");
|
||||
fn failure_to_find_a_physical_source_never_advertises_a_working_exit() {
|
||||
for line in [
|
||||
"",
|
||||
"0 198.51.100.3",
|
||||
"5 0.0.0.0",
|
||||
"5 127.0.0.1",
|
||||
"3 10.0.0.1 extra",
|
||||
] {
|
||||
let (report, physical) = reconcile(&|_| Ok(line.into()), &no_names, &plan(false));
|
||||
assert_eq!(physical, None);
|
||||
assert!(matches!(&report.offer[0].1, RuleOutcome::Failed(_)));
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_plan(run: RunScript<'_>, resolve: Resolve<'_>, plan: &ExitHostPlan) -> ExitHostReport {
|
||||
reconcile(run, resolve, plan).0
|
||||
}
|
||||
|
||||
fn no_names(_: &str) -> Vec<Ipv4Addr> {
|
||||
@@ -764,7 +710,7 @@ exit 0"#
|
||||
};
|
||||
clear_all(&run, "tsun0");
|
||||
let seen = seen.borrow();
|
||||
assert!(seen[0].contains("$keep = @()"));
|
||||
assert!(seen[0].contains("StartsWith($prefix)"));
|
||||
assert!(seen[0].contains("'tsunagi-exit:tsun0:'"));
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,8 @@ impl Tally {
|
||||
/// The overlay interface.
|
||||
pub struct Interface {
|
||||
device: Arc<dyn TunDevice>,
|
||||
#[cfg(windows)]
|
||||
forwarding: Option<super::egress::Gateway>,
|
||||
factory: Arc<dyn TunFactory>,
|
||||
name: String,
|
||||
mtu: u32,
|
||||
@@ -235,6 +237,25 @@ impl Interface {
|
||||
let name = device.name().to_string();
|
||||
let tally = Arc::new(Tally::default());
|
||||
|
||||
#[cfg(windows)]
|
||||
let forwarding = factory.on_host().then(|| {
|
||||
let routes = routes.clone();
|
||||
let carrier = carrier.clone();
|
||||
super::egress::Gateway::new(mtu, move |route, packet| {
|
||||
if let Some(IpHeader::V4 {
|
||||
source,
|
||||
destination,
|
||||
}) = IpHeader::parse(&packet)
|
||||
&& routes.accepts_exit_traffic(route.network, source)
|
||||
&& matches!(
|
||||
routes.packet_source(route.network, route.peer, destination),
|
||||
Some(PacketSource::Member)
|
||||
)
|
||||
{
|
||||
carrier.carry(route, packet);
|
||||
}
|
||||
})
|
||||
});
|
||||
let vip_task = {
|
||||
let factory = Arc::clone(&factory);
|
||||
let routes = Arc::clone(&routes);
|
||||
@@ -320,9 +341,11 @@ impl Interface {
|
||||
tally.multicast.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
let selected = match destination {
|
||||
IpAddr::V4(address) => routes.packet_route(address),
|
||||
IpAddr::V6(_) => None,
|
||||
let selected = match (header.source(), destination) {
|
||||
(IpAddr::V4(source), IpAddr::V4(address)) => {
|
||||
routes.packet_route(Some(source), address)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let Some((route, exit)) = selected else {
|
||||
tally.note_unroutable(destination);
|
||||
@@ -342,6 +365,8 @@ impl Interface {
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
#[cfg(windows)]
|
||||
forwarding,
|
||||
device,
|
||||
factory,
|
||||
name,
|
||||
@@ -464,6 +489,10 @@ impl Interface {
|
||||
(state.plan.clone(), state.is_ok())
|
||||
};
|
||||
if wanted.is_empty() {
|
||||
#[cfg(windows)]
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(Vec::new());
|
||||
}
|
||||
if planned.is_some() {
|
||||
exit.clear(&self.name).await;
|
||||
let mut state = self.exit_state();
|
||||
@@ -482,9 +511,13 @@ impl Interface {
|
||||
report.client = Some(outcome);
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
self.configure_forwarding(exit.forwarded_uplink());
|
||||
return;
|
||||
}
|
||||
let report = exit.apply(&wanted).await;
|
||||
#[cfg(windows)]
|
||||
self.configure_forwarding(exit.forwarded_uplink());
|
||||
for (range, outcome) in &report.offer {
|
||||
match outcome {
|
||||
RuleOutcome::Applied => tracing::info!(
|
||||
@@ -532,6 +565,22 @@ impl Interface {
|
||||
state.report = Some(report);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn configure_forwarding(&self, physical: Option<(u32, std::net::Ipv4Addr)>) {
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(
|
||||
self.routes
|
||||
.exit_offers()
|
||||
.into_iter()
|
||||
.filter_map(|(network, _)| {
|
||||
let (index, address) = physical?;
|
||||
Some((network, super::egress::Physical { index, address }))
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the host routes its own transport by destination.
|
||||
pub(crate) fn needs_underlay_targets(&self) -> bool {
|
||||
self.host_rules
|
||||
@@ -781,6 +830,10 @@ impl Interface {
|
||||
|
||||
/// Removes the interface from the host.
|
||||
pub async fn remove(&self) {
|
||||
#[cfg(windows)]
|
||||
if let Some(gateway) = &self.forwarding {
|
||||
gateway.configure(Vec::new());
|
||||
}
|
||||
// The route goes with the interface; the firewall rule does not, so
|
||||
// it is taken out explicitly while the interface is still known.
|
||||
if let Some(rules) = &self.host_rules {
|
||||
@@ -848,14 +901,14 @@ impl Interface {
|
||||
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(Rejected::WrongSource);
|
||||
};
|
||||
let (broadcast, exit) = match (origin, header.destination()) {
|
||||
let (broadcast, exit, forwarded) = match (origin, header.destination()) {
|
||||
(
|
||||
PacketSource::ExitReply {
|
||||
local: Some(local),
|
||||
exit,
|
||||
},
|
||||
IpAddr::V4(destination),
|
||||
) if destination == local => (false, Some(exit)),
|
||||
) if destination == local => (false, Some(exit), false),
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.is_broadcast(destination) =>
|
||||
{
|
||||
@@ -865,13 +918,17 @@ impl Interface {
|
||||
self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(Rejected::BroadcastDenied);
|
||||
}
|
||||
(true, None)
|
||||
(true, None, false)
|
||||
}
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.is_local_destination(network, destination)
|
||||
|| self.routes.accepts_exit_traffic(network, destination) =>
|
||||
if self.routes.is_local_destination(network, destination) =>
|
||||
{
|
||||
(false, None)
|
||||
(false, None, false)
|
||||
}
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.accepts_exit_traffic(network, destination) =>
|
||||
{
|
||||
(false, None, true)
|
||||
}
|
||||
_ => {
|
||||
self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -896,6 +953,20 @@ impl Interface {
|
||||
crate::vip::router::Decision::Drop => return Ok(()),
|
||||
crate::vip::router::Decision::Pass => packet,
|
||||
};
|
||||
// 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) {
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.tally.undeliverable.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// 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() {
|
||||
|
||||
@@ -40,6 +40,8 @@ pub enum OverlayError {
|
||||
|
||||
pub mod broadcast;
|
||||
pub mod config;
|
||||
#[cfg(any(windows, test))]
|
||||
mod egress;
|
||||
pub mod exit;
|
||||
pub mod hostrules;
|
||||
pub mod interface;
|
||||
|
||||
@@ -55,7 +55,7 @@ use crate::BoxFuture;
|
||||
use crate::overlay::OverlayError;
|
||||
|
||||
use super::super::config::Cidr;
|
||||
use super::super::hostrules::linux_exit_mark::{UNDERLAY_MARK, UNDERLAY_MASK};
|
||||
use super::super::hostrules::linux_exit_mark::{EXIT_REPLY_MARK, UNDERLAY_MARK, UNDERLAY_MASK};
|
||||
use super::super::tun::{TunDevice, TunRequest};
|
||||
use super::privilege::{NetAdmin, Privilege, probe_net_admin};
|
||||
use super::{
|
||||
@@ -671,6 +671,7 @@ const EXIT_TABLE: u32 = 0x7473;
|
||||
/// The main table.
|
||||
const MAIN_TABLE: u32 = 254;
|
||||
/// Protect marked underlay and initial socket routing before Tailscale's rules.
|
||||
const EXIT_REPLY_PRIORITY: u32 = 5204;
|
||||
const EXIT_MARK_PRIORITY: u32 = 5205;
|
||||
const EXIT_BYPASS_PRIORITY: u32 = 5206;
|
||||
const LEGACY_EXIT_BYPASS_PRIORITY: u32 = 5280;
|
||||
@@ -704,6 +705,15 @@ fn rule_priority(rule: &RuleMessage) -> Option<u32> {
|
||||
fn is_exit_rule(rule: &RuleMessage) -> bool {
|
||||
let table = rule_table(rule);
|
||||
match rule_priority(rule) {
|
||||
Some(EXIT_REPLY_PRIORITY) => {
|
||||
table == EXIT_TABLE
|
||||
&& rule
|
||||
.attributes
|
||||
.contains(&RuleAttribute::FwMark(EXIT_REPLY_MARK))
|
||||
&& rule
|
||||
.attributes
|
||||
.contains(&RuleAttribute::FwMask(EXIT_REPLY_MARK))
|
||||
}
|
||||
Some(EXIT_MARK_PRIORITY) => {
|
||||
table == MAIN_TABLE
|
||||
&& rule
|
||||
@@ -865,11 +875,11 @@ async fn replace_exit_default(
|
||||
/// ip rule add priority 5205 fwmark 0x40000000/0x40000000 lookup main
|
||||
/// ip rule add priority 5206 uidrange <uid>-<uid> lookup main
|
||||
/// ip rule add priority 5290 lookup main suppress_prefixlength 0
|
||||
/// ip rule add priority 5300 lookup 0x7473
|
||||
/// ip rule add priority 5300 iif lo lookup 0x7473
|
||||
/// ```
|
||||
///
|
||||
/// and the same for IPv6 with `ip -6 route replace unreachable default table
|
||||
/// 0x7473`, so that IPv6 is refused instead of leaving the ordinary way.
|
||||
/// 0x7473` and no interface selector, so IPv6 is refused.
|
||||
///
|
||||
/// What an earlier call left is removed first, so repeating it is safe, and
|
||||
/// the rules go in last, so a failure part way never leaves a rule that
|
||||
@@ -886,7 +896,24 @@ async fn set_exit_client(
|
||||
};
|
||||
replace_exit_default(&handle, name, source).await?;
|
||||
|
||||
add_mark_bypass(&handle, false).await?;
|
||||
if uid == 0 {
|
||||
add_mark_rule(
|
||||
&handle,
|
||||
false,
|
||||
EXIT_TABLE,
|
||||
EXIT_REPLY_PRIORITY,
|
||||
EXIT_REPLY_MARK,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
add_mark_rule(
|
||||
&handle,
|
||||
false,
|
||||
MAIN_TABLE,
|
||||
EXIT_MARK_PRIORITY,
|
||||
UNDERLAY_MARK,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut bypass = handle
|
||||
.rule()
|
||||
@@ -930,6 +957,7 @@ async fn set_exit_client(
|
||||
.table_id(EXIT_TABLE)
|
||||
.action(RuleAction::ToTable)
|
||||
.priority(EXIT_DEFAULT_PRIORITY)
|
||||
.input_interface("lo")
|
||||
.execute()
|
||||
.await
|
||||
.map_err(|err| fail("rule for the default route", err))?;
|
||||
@@ -960,7 +988,7 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O
|
||||
};
|
||||
}
|
||||
|
||||
add_mark_bypass(handle, true).await?;
|
||||
add_mark_rule(handle, true, MAIN_TABLE, EXIT_MARK_PRIORITY, UNDERLAY_MARK).await?;
|
||||
let mut bypass = handle
|
||||
.rule()
|
||||
.add()
|
||||
@@ -1008,14 +1036,20 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O
|
||||
.map_err(|err| fail("rule for the default route", err))
|
||||
}
|
||||
|
||||
async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), OverlayError> {
|
||||
async fn add_mark_rule(
|
||||
handle: &rtnetlink::Handle,
|
||||
v6: bool,
|
||||
table: u32,
|
||||
priority: u32,
|
||||
bit: u32,
|
||||
) -> Result<(), OverlayError> {
|
||||
let mut rule = handle
|
||||
.rule()
|
||||
.add()
|
||||
.table_id(MAIN_TABLE)
|
||||
.table_id(table)
|
||||
.action(RuleAction::ToTable)
|
||||
.priority(EXIT_MARK_PRIORITY)
|
||||
.fw_mark(UNDERLAY_MARK);
|
||||
.priority(priority)
|
||||
.fw_mark(bit);
|
||||
rule.message_mut().header.family = if v6 {
|
||||
rtnetlink::packet_route::AddressFamily::Inet6
|
||||
} else {
|
||||
@@ -1023,9 +1057,11 @@ async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), Ove
|
||||
};
|
||||
rule.message_mut()
|
||||
.attributes
|
||||
.push(RuleAttribute::FwMask(UNDERLAY_MASK));
|
||||
.push(RuleAttribute::FwMask(bit));
|
||||
rule.execute().await.map_err(|err| {
|
||||
OverlayError::Unavailable(format!("cannot protect marked underlay traffic: {err}"))
|
||||
OverlayError::Unavailable(format!(
|
||||
"cannot add exit routing rule {priority} for mark {bit:#x}: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -121,6 +121,18 @@ impl RoutingTable {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Exact local and signed remote addresses for a mesh diagnostic. Exit routes do not qualify.
|
||||
pub(crate) fn peer_addresses(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
) -> Option<(Ipv4Addr, Ipv4Addr)> {
|
||||
let networks = self.read();
|
||||
let routes = networks.get(&network)?;
|
||||
let (address, _) = routes.peers.iter().find(|(_, owner)| *owner == peer)?;
|
||||
Some((routes.local?, *address))
|
||||
}
|
||||
|
||||
fn read(&self) -> std::sync::RwLockReadGuard<'_, HashMap<NetworkId, NetworkRoutes>> {
|
||||
match self.networks.read() {
|
||||
Ok(guard) => guard,
|
||||
@@ -292,11 +304,12 @@ impl RoutingTable {
|
||||
/// unicast destination, goes to this device's exit node when it has one:
|
||||
/// that is what sending *all* traffic through a member means.
|
||||
pub fn route(&self, destination: Ipv4Addr) -> Option<Route> {
|
||||
self.packet_route(destination).map(|(route, _)| route)
|
||||
self.packet_route(None, destination).map(|(route, _)| route)
|
||||
}
|
||||
|
||||
pub(super) fn packet_route(
|
||||
&self,
|
||||
source: Option<Ipv4Addr>,
|
||||
destination: Ipv4Addr,
|
||||
) -> Option<(Route, Option<Arc<SelectedExit>>)> {
|
||||
let networks = self.read();
|
||||
@@ -324,6 +337,14 @@ impl RoutingTable {
|
||||
return None;
|
||||
}
|
||||
let exit = self.selected_exit.load_full()?;
|
||||
// The host's default route may hand a forwarded packet back to the TUN.
|
||||
// Only this device can originate traffic for its own upstream. Replies
|
||||
// to a member above still route by destination with their internet source.
|
||||
if let Some(source) = source
|
||||
&& networks.get(&exit.route.network)?.local != Some(source)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((exit.route, Some(exit)))
|
||||
}
|
||||
|
||||
@@ -383,7 +404,10 @@ impl RoutingTable {
|
||||
///
|
||||
/// Choosing another exit replaces the previous one under the table's write lock.
|
||||
pub fn exit_via(&self) -> Option<(NetworkId, EndpointId)> {
|
||||
exit_via(&self.read())
|
||||
self.selected_exit
|
||||
.load()
|
||||
.as_ref()
|
||||
.map(|exit| (exit.route.network, exit.route.peer))
|
||||
}
|
||||
|
||||
/// Whether a default route is selected and the local source valid in that network.
|
||||
@@ -857,6 +881,32 @@ mod tests {
|
||||
|
||||
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
|
||||
|
||||
#[test]
|
||||
fn tunnel_warming_follows_the_selected_membership_on_restore_switch_and_off() {
|
||||
let table = Arc::new(RoutingTable::new());
|
||||
let (tx, _rx) = tokio::sync::mpsc::channel(1);
|
||||
let context = crate::dataplane::PluginContext::new(tx, peer(1), None, &table);
|
||||
let (a, b) = (network("left"), network("right"));
|
||||
let exit = peer(2);
|
||||
table.set_network(a, with_exit(false, Some(exit))).unwrap();
|
||||
table.set_network(b, NetworkRoutes::default()).unwrap();
|
||||
assert_eq!(context.warm_peer(a), Some(exit));
|
||||
assert_eq!(context.warm_peer(b), None);
|
||||
let select = |via| ExitPolicy { offer: true, via };
|
||||
table.set_exit(b, select(Some(exit)));
|
||||
assert_eq!(context.warm_peer(a), None);
|
||||
assert_eq!(context.warm_peer(b), Some(exit));
|
||||
table.set_exit(b, select(None));
|
||||
assert_eq!(
|
||||
context.warm_peer(b),
|
||||
None,
|
||||
"offering an exit does not select one"
|
||||
);
|
||||
table.set_exit(a, select(Some(exit)));
|
||||
table.remove_network(a);
|
||||
assert_eq!(context.warm_peer(a), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() {
|
||||
let table = RoutingTable::new();
|
||||
|
||||
@@ -47,6 +47,79 @@ async fn open_control_stream(
|
||||
|
||||
const LIMIT: usize = 64 * 1024;
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_authenticated_disconnect_reports_the_quic_close_code() {
|
||||
let agent = TestAgent::spawn(&SharedMemoryDiscovery::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let (name, secret) = network("disconnect-diagnostics");
|
||||
let id = agent.agent.join_network(&name, &secret).await.unwrap();
|
||||
let member = raw_endpoint().await;
|
||||
let (conn, mut send, mut recv) = open_control_stream(&member, agent.agent.local_addr()).await;
|
||||
let mut events = agent.agent.subscribe();
|
||||
tsunagi::proto::handshake::initiate(
|
||||
&conn,
|
||||
&mut send,
|
||||
&mut recv,
|
||||
member.id(),
|
||||
&NetworkKeys::derive(&name, &secret),
|
||||
&tsunagi::Limits::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let message = ControlMessage::Announce(tsunagi::proto::message::Announcement {
|
||||
broadcast: true,
|
||||
exit_node: false,
|
||||
hostname: "returning-peer".into(),
|
||||
capabilities: Vec::new(),
|
||||
agent_version: None,
|
||||
});
|
||||
write_frame(
|
||||
&mut send,
|
||||
&encode(&Envelope {
|
||||
network_id: *id.as_bytes(),
|
||||
message,
|
||||
})
|
||||
.unwrap(),
|
||||
LIMIT,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
tsunagi::testing::wait_until("peer hostname is known", || async {
|
||||
agent
|
||||
.agent
|
||||
.network_status(id)
|
||||
.await
|
||||
.ok()?
|
||||
.peers
|
||||
.into_iter()
|
||||
.find(|p| {
|
||||
p.endpoint_id == member.id() && p.hostname.as_deref() == Some("returning-peer")
|
||||
})
|
||||
})
|
||||
.await;
|
||||
conn.close(42u32.into(), b"private remote text\nsecond line");
|
||||
let (reported_network, hostname, reason) = wait_event(&mut events, |event| match event {
|
||||
Event::PeerDisconnected {
|
||||
network,
|
||||
network_name,
|
||||
peer,
|
||||
hostname,
|
||||
reason,
|
||||
} if *network == id && *peer == member.id() => {
|
||||
Some((network_name.clone(), hostname.clone(), reason.clone()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(reported_network, name);
|
||||
assert_eq!(hostname.as_deref(), Some("returning-peer"));
|
||||
assert!(reason.contains("application code 42"), "{reason}");
|
||||
assert!(!reason.contains("private remote text"));
|
||||
member.close().await;
|
||||
agent.agent.shutdown().await;
|
||||
}
|
||||
|
||||
/// Sends `Hello` and reads the responder's `HelloAck`.
|
||||
async fn exchange_hellos(
|
||||
send: &mut SendStream,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
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.4" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.4" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" }
|
||||
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" }
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ pub fn networks(
|
||||
address: peer.overlay_address_v4.map(|a| a.to_string()),
|
||||
handshake_secs_ago: tunnel
|
||||
.and_then(|t| t.health.since_handshake.map(|s| s.as_secs())),
|
||||
idle: tunnel.is_some_and(|t| t.health.idle),
|
||||
tx_packets: tunnel.map_or(0, |t| t.stats.tx_packets),
|
||||
rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets),
|
||||
tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes),
|
||||
@@ -86,6 +87,7 @@ pub fn networks(
|
||||
};
|
||||
|
||||
NetworkReport {
|
||||
speed: network.speed.clone(),
|
||||
vips: network.vips.clone(),
|
||||
protocols: network.protocols.clone(),
|
||||
auto_start: network.auto_start,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "tsunagi-speedtest"
|
||||
version = "0.1.0"
|
||||
description = "Bounded, adaptive goodput measurements over an authenticated mesh tunnel"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bytes.workspace = true
|
||||
postcard.workspace = true
|
||||
serde.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,490 @@
|
||||
use crate::measurement::{Pacer, Receiver, Search};
|
||||
use crate::packet::{MAX_MTU, MIN_MTU, PacketBuilder};
|
||||
use crate::{
|
||||
Control, Datagram, Direction, Feedback, NORMAL_BYTES, Progress, Quality, Reading, Start, State,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use std::future::Future;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until, timeout_at};
|
||||
|
||||
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);
|
||||
|
||||
/// Parameters for one locally admitted, authenticated peer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Config {
|
||||
/// Fresh random identifier for the exchange. A responder uses the identifier from the request.
|
||||
pub id: u64,
|
||||
/// Local overlay IPv4 address on this network.
|
||||
pub local: Ipv4Addr,
|
||||
/// Authenticated peer's overlay address on this network.
|
||||
pub remote: Ipv4Addr,
|
||||
/// Maximum complete diagnostic datagram size supported by this route.
|
||||
pub mtu: u16,
|
||||
/// Local policy's maximum diagnostic IPv4 bytes in each direction.
|
||||
pub byte_limit: u32,
|
||||
/// Recent peer RTT, used to select the feedback interval and bound the final drain.
|
||||
pub rtt: Duration,
|
||||
}
|
||||
|
||||
/// Delivery for exactly one network and peer. The host uses its usual network
|
||||
/// authentication for control and its ordinary encrypted packet path for probes.
|
||||
pub trait Io: Send + Sync {
|
||||
/// Enqueue or send one reliable authenticated control record.
|
||||
fn control(&self, message: Control) -> impl Future<Output = bool> + Send;
|
||||
/// Attempt to send one packet without blocking the tunnel or buffering unbounded data.
|
||||
fn packet(&self, packet: Bytes) -> bool;
|
||||
/// Publish a live observation or terminal state.
|
||||
fn progress(&self, update: Progress);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Ingress(Mutex<Option<Receiver>>);
|
||||
|
||||
impl Ingress {
|
||||
fn with<T>(&self, f: impl FnOnce(&mut Option<Receiver>) -> T) -> T {
|
||||
let mut guard = self.0.lock().unwrap_or_else(|poison| poison.into_inner());
|
||||
f(&mut guard)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloneable, nonblocking ingress for a single test. Data is counted in place;
|
||||
/// it is never put on the reliable message queue.
|
||||
#[derive(Clone)]
|
||||
pub struct Handle {
|
||||
id: u64,
|
||||
local: Ipv4Addr,
|
||||
remote: Ipv4Addr,
|
||||
events: mpsc::Sender<Control>,
|
||||
cancel: watch::Sender<bool>,
|
||||
ingress: Arc<Ingress>,
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
/// Deliver an authenticated control record for an existing test.
|
||||
pub fn control(&self, message: Control) {
|
||||
if message.id() == self.id && message.valid() {
|
||||
if matches!(message, Control::Cancel { .. }) {
|
||||
self.cancel();
|
||||
} else {
|
||||
let _ = self.events.try_send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Count a validated probe from the bound peer in the current receiving direction.
|
||||
pub fn data(&self, packet: Datagram) {
|
||||
if packet.id == self.id && packet.source == self.remote && packet.destination == self.local
|
||||
{
|
||||
self.ingress.with(|rx| {
|
||||
if let Some(rx) = rx {
|
||||
rx.put(packet, Instant::now());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt local work, including outstanding control sends.
|
||||
pub fn cancel(&self) {
|
||||
self.cancel.send_replace(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// A single, bounded two-direction exchange. Nothing runs until the host calls `run`.
|
||||
pub struct Session {
|
||||
cfg: Config,
|
||||
request: Option<Start>,
|
||||
events: mpsc::Receiver<Control>,
|
||||
cancel: watch::Receiver<bool>,
|
||||
ingress: Arc<Ingress>,
|
||||
progress: Progress,
|
||||
}
|
||||
|
||||
/// Prepare an outgoing session. The test begins when its runner sends its Start record.
|
||||
pub fn initiate(config: Config) -> (Handle, Session) {
|
||||
new_session(config, None)
|
||||
}
|
||||
|
||||
/// Prepare the response to a verified Start. Local and requested traffic limits are intersected.
|
||||
pub fn respond(mut config: Config, request: Start) -> (Handle, Session) {
|
||||
config.id = request.id;
|
||||
new_session(config, Some(request))
|
||||
}
|
||||
|
||||
fn new_session(config: Config, request: Option<Start>) -> (Handle, Session) {
|
||||
let (tx, events) = mpsc::channel(32);
|
||||
let (cancel_tx, cancel) = watch::channel(false);
|
||||
let ingress = Arc::new(Ingress::default());
|
||||
let handle = Handle {
|
||||
id: config.id,
|
||||
local: config.local,
|
||||
remote: config.remote,
|
||||
events: tx,
|
||||
cancel: cancel_tx,
|
||||
ingress: ingress.clone(),
|
||||
};
|
||||
let session = Session {
|
||||
cfg: config,
|
||||
request,
|
||||
events,
|
||||
cancel,
|
||||
ingress,
|
||||
progress: Progress::default(),
|
||||
};
|
||||
(handle, session)
|
||||
}
|
||||
|
||||
fn open_control(control: Option<Control>) -> Result<Control, State> {
|
||||
match control {
|
||||
Some(Control::Busy { .. }) => Err(State::Busy),
|
||||
Some(Control::Cancel { .. }) => Err(State::Cancelled),
|
||||
Some(control) => Ok(control),
|
||||
None => Err(State::Cancelled),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(io: &impl Io, message: Control) -> Result<(), State> {
|
||||
if io.control(message).await {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(State::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run both directions under one five-second deadline and return the same final
|
||||
/// snapshot that is published to the host. Dropping the future stops packet generation.
|
||||
pub async fn run(mut self, io: impl Io) -> Progress {
|
||||
let deadline = Instant::now() + TOTAL_TIME;
|
||||
let mut cancellation = self.cancel.clone();
|
||||
io.progress(self.progress);
|
||||
let state = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.wait_for(|v| *v) => State::Cancelled,
|
||||
result = timeout_at(deadline, self.exchange(&io, deadline)) => {
|
||||
match result { Ok(Ok(())) => State::Complete, Ok(Err(state)) => state, Err(_) => State::TimedOut }
|
||||
}
|
||||
};
|
||||
self.ingress.with(|rx| *rx = None);
|
||||
self.progress.state = state;
|
||||
io.progress(self.progress);
|
||||
if matches!(state, State::Cancelled | State::Failed | State::TimedOut) {
|
||||
// A blocked control stream must never delay local release or shutdown.
|
||||
let _ = timeout_at(
|
||||
deadline.min(Instant::now() + Duration::from_millis(20)),
|
||||
io.control(Control::Cancel { id: self.cfg.id }),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
self.progress
|
||||
}
|
||||
|
||||
async fn exchange(&mut self, io: &impl Io, deadline: Instant) -> Result<(), State> {
|
||||
let id = self.cfg.id;
|
||||
self.cfg.byte_limit = self.cfg.byte_limit.min(NORMAL_BYTES);
|
||||
self.cfg.mtu = self.cfg.mtu.min(MAX_MTU);
|
||||
if self.cfg.mtu < MIN_MTU || self.cfg.byte_limit == 0 || self.cfg.local == self.cfg.remote {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
if let Some(start) = self.request {
|
||||
if !Control::Start(start).valid() {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
self.cfg.mtu = self.cfg.mtu.min(start.mtu);
|
||||
self.cfg.byte_limit = self.cfg.byte_limit.min(start.byte_limit);
|
||||
send(
|
||||
io,
|
||||
Control::Accepted {
|
||||
id,
|
||||
mtu: self.cfg.mtu,
|
||||
byte_limit: self.cfg.byte_limit,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
send(
|
||||
io,
|
||||
Control::Start(Start {
|
||||
id,
|
||||
mtu: self.cfg.mtu,
|
||||
byte_limit: self.cfg.byte_limit,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
if let Control::Accepted {
|
||||
mtu, byte_limit, ..
|
||||
} = open_control(self.events.recv().await)?
|
||||
{
|
||||
if mtu > self.cfg.mtu || byte_limit > self.cfg.byte_limit {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
self.cfg.mtu = mtu;
|
||||
self.cfg.byte_limit = byte_limit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for direction in [Direction::Download, Direction::Upload] {
|
||||
self.progress.state = match direction {
|
||||
Direction::Download => State::Download,
|
||||
Direction::Upload => State::Upload,
|
||||
};
|
||||
io.progress(self.progress);
|
||||
let sender = (direction == Direction::Download) == self.request.is_some();
|
||||
let result = if sender {
|
||||
self.send_probes(io, direction, deadline).await?
|
||||
} else {
|
||||
self.receive_probes(io, direction).await?
|
||||
};
|
||||
*self.progress.at(direction) = result;
|
||||
io.progress(self.progress);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_probes(
|
||||
&mut self,
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
deadline: Instant,
|
||||
) -> Result<Reading, State> {
|
||||
loop {
|
||||
if matches!(open_control(self.events.recv().await)?, Control::Ready { direction: d, .. } if d == direction)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
let start = Instant::now();
|
||||
// Leave room for the opposite direction and the final reliable report.
|
||||
let remaining = deadline
|
||||
.saturating_duration_since(start)
|
||||
.saturating_sub(Duration::from_millis(200));
|
||||
let phase = if direction == Direction::Download {
|
||||
remaining / 2
|
||||
} else {
|
||||
remaining
|
||||
};
|
||||
let end = start + phase.min(DIRECTION_TIME);
|
||||
let mut tick = interval_at(start + PACE_TICK, PACE_TICK);
|
||||
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let mut search = Search::default();
|
||||
let mut pacer = Pacer::new(start, self.cfg.mtu);
|
||||
let builder = PacketBuilder::new(
|
||||
self.cfg.local,
|
||||
self.cfg.remote,
|
||||
self.cfg.id,
|
||||
direction,
|
||||
self.cfg.mtu,
|
||||
);
|
||||
let limit = self.cfg.byte_limit / u32::from(self.cfg.mtu);
|
||||
let mut packets = 0;
|
||||
let mut last_bytes = 0;
|
||||
let mut last_feedback = start;
|
||||
let max_silence = (self
|
||||
.cfg
|
||||
.rtt
|
||||
.saturating_mul(3)
|
||||
.saturating_add(Duration::from_millis(200)))
|
||||
.clamp(Duration::from_millis(700), Duration::from_millis(950));
|
||||
while packets < limit && !search.done() && Instant::now() < end {
|
||||
tokio::select! {
|
||||
control = self.events.recv() => {
|
||||
if let Control::Feedback { direction: d, sample, .. } = open_control(control)?
|
||||
&& d == direction && sample.bytes >= last_bytes && sample.bytes <= self.cfg.byte_limit
|
||||
{
|
||||
if sample.bytes > last_bytes {
|
||||
last_feedback = Instant::now();
|
||||
last_bytes = sample.bytes;
|
||||
}
|
||||
if sample.bps > 0 {
|
||||
*self.progress.at(direction) = Reading { bps: Some(sample.bps), bytes: last_bytes, quality: Quality::Measuring };
|
||||
io.progress(self.progress);
|
||||
}
|
||||
search.observe(sample, start.elapsed().as_micros() as u32);
|
||||
}
|
||||
}
|
||||
_ = tick.tick() => {
|
||||
let now = Instant::now();
|
||||
let silence = if last_bytes == 0 { max_silence.max(Duration::from_millis(1100)) } else { max_silence };
|
||||
if now.duration_since(last_feedback) > silence {
|
||||
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)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
packets += emit;
|
||||
}
|
||||
}
|
||||
}
|
||||
send(
|
||||
io,
|
||||
Control::End {
|
||||
id: self.cfg.id,
|
||||
direction,
|
||||
packets,
|
||||
reading: search.result(last_bytes),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
if let Control::Report {
|
||||
direction: d,
|
||||
reading,
|
||||
..
|
||||
} = open_control(self.events.recv().await)?
|
||||
&& d == direction
|
||||
{
|
||||
if reading.bytes > packets * u32::from(self.cfg.mtu - crate::packet::HEADER) {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
return Ok(reading);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn receive_probes(
|
||||
&mut self,
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
) -> Result<Reading, State> {
|
||||
let id = self.cfg.id;
|
||||
self.ingress
|
||||
.with(|rx| *rx = Some(Receiver::new(direction, self.cfg.mtu, self.cfg.byte_limit)));
|
||||
send(io, Control::Ready { id, direction }).await?;
|
||||
let mut tick = interval_at(Instant::now() + FEEDBACK_TICK, FEEDBACK_TICK);
|
||||
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let window = self
|
||||
.cfg
|
||||
.rtt
|
||||
.clamp(Duration::from_millis(100), Duration::from_millis(220));
|
||||
let (packets, estimate) = loop {
|
||||
tokio::select! {
|
||||
control = self.events.recv() => {
|
||||
if let Control::End { direction: d, packets, reading, .. } = open_control(control)?
|
||||
&& d == direction
|
||||
{
|
||||
if packets > self.cfg.byte_limit / u32::from(self.cfg.mtu) { return Err(State::Failed); }
|
||||
break (packets, reading);
|
||||
}
|
||||
}
|
||||
_ = tick.tick() => {
|
||||
let sample = self.ingress.with(|rx| rx.as_mut().and_then(|r| r.sample(Instant::now(), window)));
|
||||
if let Some(sample) = sample {
|
||||
self.update_receiver(io, direction, sample);
|
||||
send(io, Control::Feedback { id, direction, sample }).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let received = self.ingress.with(|rx| rx.as_ref().map_or(0, |r| r.count));
|
||||
if received < packets {
|
||||
// Reliable End and encrypted probes may take different paths.
|
||||
let drain = self
|
||||
.cfg
|
||||
.rtt
|
||||
.clamp(Duration::from_millis(25), Duration::from_millis(120));
|
||||
sleep_until(Instant::now() + drain).await;
|
||||
}
|
||||
let rx = self.ingress.with(Option::take).ok_or(State::Failed)?;
|
||||
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,
|
||||
};
|
||||
send(
|
||||
io,
|
||||
Control::Report {
|
||||
id,
|
||||
direction,
|
||||
reading,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(reading)
|
||||
}
|
||||
|
||||
fn update_receiver(&mut self, io: &impl Io, direction: Direction, sample: Feedback) {
|
||||
let reading = self.progress.at(direction);
|
||||
reading.bytes = sample.bytes;
|
||||
if sample.bps > 0 {
|
||||
reading.bps = Some(sample.bps);
|
||||
}
|
||||
io.progress(self.progress);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_ingress_is_bound_to_the_session_id_and_both_assigned_addresses() {
|
||||
let local = Ipv4Addr::new(10, 1, 2, 3);
|
||||
let remote = Ipv4Addr::new(10, 1, 2, 4);
|
||||
let conf = Config {
|
||||
id: 42,
|
||||
local,
|
||||
remote,
|
||||
mtu: 1280,
|
||||
byte_limit: 32_000,
|
||||
rtt: Duration::ZERO,
|
||||
};
|
||||
let (handle, _) = initiate(conf);
|
||||
handle.ingress.with(|rx| {
|
||||
*rx = Some(Receiver::new(
|
||||
Direction::Download,
|
||||
conf.mtu,
|
||||
conf.byte_limit,
|
||||
))
|
||||
});
|
||||
let make = |src, dst, id, seq| {
|
||||
let raw = PacketBuilder::new(src, dst, id, Direction::Download, 1280).packet(0, seq, 7);
|
||||
crate::decode_packet(&raw).unwrap()
|
||||
};
|
||||
for (ipfrom, ipto, id, seq) in [
|
||||
(remote, local, 41, 0),
|
||||
(local, remote, 42, 1),
|
||||
(Ipv4Addr::LOCALHOST, local, 42, 2),
|
||||
(remote, Ipv4Addr::LOCALHOST, 42, 3),
|
||||
(remote, local, 42, 4),
|
||||
] {
|
||||
handle.data(make(ipfrom, ipto, id, seq));
|
||||
}
|
||||
assert_eq!(
|
||||
handle.ingress.with(|rx| rx.as_ref().map(|r| r.count)),
|
||||
Some(1)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Directional goodput measurements for an authenticated peer on its existing IPv4 tunnel.
|
||||
//!
|
||||
//! The host advertises and negotiates this crate's wire version, admits at most one
|
||||
//! test at a time, and delivers control messages over its reliable authenticated
|
||||
//! channel. Probe packets take the same encrypted IPv4 path as application traffic.
|
||||
|
||||
mod engine;
|
||||
mod measurement;
|
||||
mod packet;
|
||||
mod wire;
|
||||
|
||||
pub use engine::{Config, Handle, Io, Session, initiate, respond};
|
||||
pub use packet::{Datagram, decode_packet, is_test_packet};
|
||||
pub use wire::{Control, Direction, Feedback, Progress, Quality, Reading, Start, State};
|
||||
|
||||
/// Capability negotiated by peers for this protocol.
|
||||
pub const PROTOCOL: &str = "speedtest";
|
||||
/// Wire version of the control records and IPv4 payload, independent of software versions.
|
||||
pub const VERSION: u16 = 1;
|
||||
/// Absolute per-direction diagnostic IPv4 traffic budget.
|
||||
pub const NORMAL_BYTES: u32 = 96 * 1024 * 1024;
|
||||
/// Suggested per-direction budget on metered paths.
|
||||
pub const METERED_BYTES: u32 = 8 * 1024 * 1024;
|
||||
@@ -0,0 +1,372 @@
|
||||
use crate::packet::HEADER;
|
||||
use crate::wire::MAX_BPS;
|
||||
use crate::{Datagram, Direction, Feedback, Quality, Reading};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
const INITIAL_BPS: u64 = 4_000_000;
|
||||
const MIN_BPS: u64 = 32_000;
|
||||
|
||||
pub(crate) struct Receiver {
|
||||
pub(crate) direction: Direction,
|
||||
mtu: u16,
|
||||
packets: u32,
|
||||
seen: Vec<u64>,
|
||||
window: Option<Window>,
|
||||
pub(crate) count: u32,
|
||||
pub(crate) best: u64,
|
||||
}
|
||||
|
||||
struct Window {
|
||||
start: Instant,
|
||||
stage: u8,
|
||||
received: u32,
|
||||
starts_on_packet: bool,
|
||||
arrival_groups: u8,
|
||||
last_group: Instant,
|
||||
first_arrival: Instant,
|
||||
last_arrival: Instant,
|
||||
first: u32,
|
||||
highest: u32,
|
||||
last_send_us: u32,
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
pub(crate) fn new(direction: Direction, mtu: u16, budget: u32) -> Self {
|
||||
let packets = budget / u32::from(mtu);
|
||||
Self {
|
||||
direction,
|
||||
mtu,
|
||||
packets,
|
||||
seen: vec![0; packets.div_ceil(64) as usize],
|
||||
window: None,
|
||||
count: 0,
|
||||
best: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn put(&mut self, probe: Datagram, now: Instant) {
|
||||
if probe.direction != self.direction
|
||||
|| probe.size != self.mtu
|
||||
|| probe.sequence >= self.packets
|
||||
{
|
||||
return;
|
||||
}
|
||||
let word = &mut self.seen[(probe.sequence / 64) as usize];
|
||||
let bit = 1u64 << (probe.sequence % 64);
|
||||
if *word & bit != 0 {
|
||||
return;
|
||||
}
|
||||
*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 let Some(w) = &mut self.window
|
||||
&& w.stage == probe.stage
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&self) -> u32 {
|
||||
self.count * u32::from(self.mtu - HEADER)
|
||||
}
|
||||
|
||||
// A rate needs observations spread over a real interval. A queued burst
|
||||
// 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);
|
||||
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) {
|
||||
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 feedback = Feedback {
|
||||
stage: w.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);
|
||||
}
|
||||
Some(feedback)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Search {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) target: u64,
|
||||
best: u64,
|
||||
baseline_delay: Option<u32>,
|
||||
initial_loss: Option<u16>,
|
||||
last_echo: Option<u32>,
|
||||
confirm: bool,
|
||||
previous: Option<u64>,
|
||||
measured: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for Search {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
stage: 0,
|
||||
target: INITIAL_BPS,
|
||||
best: 0,
|
||||
baseline_delay: None,
|
||||
initial_loss: None,
|
||||
last_echo: None,
|
||||
confirm: false,
|
||||
previous: None,
|
||||
measured: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Search {
|
||||
pub(crate) fn observe(&mut self, sample: Feedback, elapsed_us: u32) {
|
||||
if sample.stage != self.stage
|
||||
|| self.measured.is_some()
|
||||
|| sample.echo_us > elapsed_us
|
||||
|| self.last_echo.is_some_and(|echo| echo >= sample.echo_us)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.last_echo = Some(sample.echo_us);
|
||||
let bps = sample.bps;
|
||||
self.best = self.best.max(bps);
|
||||
let delay = elapsed_us - sample.echo_us;
|
||||
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.
|
||||
let baseline_loss = *self
|
||||
.initial_loss
|
||||
.get_or_insert(sample.lost_per_mille.min(100));
|
||||
let congested =
|
||||
sample.lost_per_mille > baseline_loss + 30 || bps < self.target * 4 / 5 || queuing;
|
||||
if congested {
|
||||
self.confirm = true;
|
||||
self.previous = None;
|
||||
self.offer(if bps == 0 {
|
||||
self.target / 2
|
||||
} else {
|
||||
bps * 97 / 100
|
||||
});
|
||||
} else if self.confirm {
|
||||
if sample.lost_per_mille > 100 {
|
||||
self.previous = None;
|
||||
return;
|
||||
}
|
||||
if let Some(prev) = self.previous
|
||||
&& prev.abs_diff(bps) <= bps / 6
|
||||
{
|
||||
self.measured = Some((prev + bps) / 2);
|
||||
} else {
|
||||
self.previous = Some(bps);
|
||||
}
|
||||
} else if self.target < MAX_BPS {
|
||||
self.offer(self.target.saturating_mul(4));
|
||||
}
|
||||
}
|
||||
|
||||
fn offer(&mut self, bps: u64) {
|
||||
self.target = bps.clamp(MIN_BPS, MAX_BPS);
|
||||
self.stage = self.stage.saturating_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn done(&self) -> bool {
|
||||
self.measured.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn result(&self, bytes: u32) -> Reading {
|
||||
if let Some(bps) = self.measured {
|
||||
Reading {
|
||||
bps: Some(bps),
|
||||
bytes,
|
||||
quality: Quality::Measured,
|
||||
}
|
||||
} else if self.best > 0 {
|
||||
Reading {
|
||||
bps: Some(self.best),
|
||||
bytes,
|
||||
quality: Quality::AtLeast,
|
||||
}
|
||||
} else {
|
||||
Reading {
|
||||
bps: None,
|
||||
bytes,
|
||||
quality: Quality::Insufficient,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Pacer {
|
||||
last_tick: Instant,
|
||||
// Fractional packet credit in payload bit-nanoseconds.
|
||||
credit: u64,
|
||||
cost: u64,
|
||||
}
|
||||
|
||||
impl Pacer {
|
||||
pub(crate) fn new(start: Instant, mtu: u16) -> Self {
|
||||
Self {
|
||||
last_tick: start,
|
||||
credit: 0,
|
||||
cost: u64::from(mtu - HEADER) * 8_000_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
self.last_tick = now;
|
||||
self.credit += elapsed * bps;
|
||||
let packets = self.credit / self.cost;
|
||||
self.credit %= self.cost;
|
||||
packets.min(512) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
fn packet(sequence: u32, stage: u8, sent_us: u32) -> Datagram {
|
||||
Datagram {
|
||||
id: 7,
|
||||
source: Ipv4Addr::LOCALHOST,
|
||||
destination: Ipv4Addr::BROADCAST,
|
||||
direction: Direction::Download,
|
||||
stage,
|
||||
sequence,
|
||||
sent_us,
|
||||
size: 1280,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_reordered_packets_are_counted_once_and_do_not_reopen_earlier_stages() {
|
||||
let t = Instant::now();
|
||||
let mut rx = Receiver::new(Direction::Download, 1280, 1280 * 8);
|
||||
for (i, s) in [(7, 1), (1, 0), (3, 1), (3, 1), (8, 1), (u32::MAX, 1)] {
|
||||
rx.put(packet(i, s, 0), t);
|
||||
}
|
||||
rx.put(
|
||||
Datagram {
|
||||
direction: Direction::Upload,
|
||||
..packet(4, 1, 0)
|
||||
},
|
||||
t,
|
||||
);
|
||||
rx.put(
|
||||
Datagram {
|
||||
size: 1500,
|
||||
..packet(5, 1, 0)
|
||||
},
|
||||
t,
|
||||
);
|
||||
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)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_burst_or_compressed_catchup_cannot_establish_throughput() {
|
||||
let start = Instant::now();
|
||||
let mut receiver = Receiver::new(Direction::Download, 1280, NORMAL_BYTES_FOR_TEST);
|
||||
for i in 0..500 {
|
||||
receiver.put(packet(i, 0, i), start);
|
||||
}
|
||||
let window = Duration::from_millis(120);
|
||||
for i in 500..520 {
|
||||
receiver.put(packet(i, 0, i), start + window);
|
||||
}
|
||||
assert!(receiver.sample(start + window, window).is_none());
|
||||
let feedback = receiver
|
||||
.sample(start + Duration::from_millis(650), window)
|
||||
.unwrap();
|
||||
assert_eq!(feedback.bps, 0);
|
||||
assert_eq!(receiver.best, 0);
|
||||
}
|
||||
|
||||
const NORMAL_BYTES_FOR_TEST: u32 = 1024 * 1024;
|
||||
|
||||
#[test]
|
||||
fn retransmitted_feedback_does_not_supply_two_confirmation_windows() {
|
||||
let mut search = Search::default();
|
||||
let f = |stage, bps, lost_per_mille, bytes, echo_us| Feedback {
|
||||
stage,
|
||||
bps,
|
||||
lost_per_mille,
|
||||
bytes,
|
||||
echo_us,
|
||||
};
|
||||
search.observe(f(0, 1_000_000, 700, 15000, 120_000), 121_000);
|
||||
let observed = f(1, 970_000, 0, 30000, 241_000);
|
||||
search.observe(observed, 242_000);
|
||||
search.observe(observed, 243_000);
|
||||
assert!(!search.done());
|
||||
search.observe(f(1, 970_000, 0, 45000, 360_000), 361_000);
|
||||
assert!(search.done());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
use crate::Direction;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub(crate) const MIN_MTU: u16 = 576;
|
||||
pub(crate) const MAX_MTU: u16 = 1500;
|
||||
pub(crate) const HEADER: u16 = 46;
|
||||
const MAGIC: &[u8; 8] = b"TSNGSP01";
|
||||
const IP_PROTOCOL: u8 = 253; // RFC 3692 local experiment, disambiguated by MAGIC.
|
||||
|
||||
/// Fields from a validated version-one diagnostic IPv4 packet. Probes carry no arbitrary stream data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Datagram {
|
||||
/// Measurement identifier from the authenticated control exchange.
|
||||
pub id: u64,
|
||||
/// Source address of the inner IPv4 datagram.
|
||||
pub source: Ipv4Addr,
|
||||
/// Destination address of the inner IPv4 datagram.
|
||||
pub destination: Ipv4Addr,
|
||||
pub(crate) direction: Direction,
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) sequence: u32,
|
||||
pub(crate) sent_us: u32,
|
||||
pub(crate) size: u16,
|
||||
}
|
||||
|
||||
impl Datagram {
|
||||
/// Number of delivered diagnostic payload bytes, excluding both headers.
|
||||
pub fn payload_len(self) -> u16 {
|
||||
self.size - HEADER
|
||||
}
|
||||
}
|
||||
|
||||
/// Identify this crate's reserved IPv4 payload, including malformed records that should be dropped.
|
||||
pub fn is_test_packet(bytes: &[u8]) -> bool {
|
||||
if bytes.len() < 20 || bytes[0] >> 4 != 4 || bytes[9] != IP_PROTOCOL {
|
||||
return false;
|
||||
}
|
||||
let offset = usize::from(bytes[0] & 0x0f) * 4;
|
||||
offset >= 20 && bytes.get(offset..offset + MAGIC.len()) == Some(MAGIC)
|
||||
}
|
||||
|
||||
/// Validate an entire diagnostic datagram before handing its fixed-size metadata to the receiver.
|
||||
pub fn decode_packet(bytes: &[u8]) -> Option<Datagram> {
|
||||
let size = u16::try_from(bytes.len()).ok()?;
|
||||
if !(MIN_MTU..=MAX_MTU).contains(&size)
|
||||
|| bytes[0] != 0x45
|
||||
|| bytes[9] != IP_PROTOCOL
|
||||
|| bytes[20..28] != *MAGIC
|
||||
|| u16::from_be_bytes([bytes[2], bytes[3]]) != size
|
||||
|| u16::from_be_bytes([bytes[6], bytes[7]]) & !0x4000 != 0
|
||||
|| checksum(&bytes[..20]) != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let direction = match bytes[36] {
|
||||
0 => Direction::Download,
|
||||
1 => Direction::Upload,
|
||||
_ => return None,
|
||||
};
|
||||
let sent_us = u32::from_be_bytes(bytes[42..46].try_into().ok()?);
|
||||
if sent_us > 5_000_000 {
|
||||
return None;
|
||||
}
|
||||
Some(Datagram {
|
||||
source: Ipv4Addr::from(<[u8; 4]>::try_from(&bytes[12..16]).ok()?),
|
||||
destination: Ipv4Addr::from(<[u8; 4]>::try_from(&bytes[16..20]).ok()?),
|
||||
id: u64::from_be_bytes(bytes[28..36].try_into().ok()?),
|
||||
direction,
|
||||
stage: bytes[37],
|
||||
sequence: u32::from_be_bytes(bytes[38..42].try_into().ok()?),
|
||||
sent_us,
|
||||
size,
|
||||
})
|
||||
}
|
||||
|
||||
// Build the immutable header and deterministic padding once per direction. The
|
||||
// underlying data tunnel encrypts the packet before it goes on the wire.
|
||||
pub(crate) struct PacketBuilder(Bytes);
|
||||
|
||||
impl PacketBuilder {
|
||||
pub(crate) fn new(
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
id: u64,
|
||||
direction: Direction,
|
||||
mtu: u16,
|
||||
) -> Self {
|
||||
let mut bytes = BytesMut::zeroed(usize::from(mtu));
|
||||
bytes[0] = 0x45;
|
||||
bytes[2..4].copy_from_slice(&mtu.to_be_bytes());
|
||||
bytes[6] = 0x40;
|
||||
bytes[8] = 64;
|
||||
bytes[9] = IP_PROTOCOL;
|
||||
bytes[12..16].copy_from_slice(&source.octets());
|
||||
bytes[16..20].copy_from_slice(&destination.octets());
|
||||
let check = checksum(&bytes[..20]);
|
||||
bytes[10..12].copy_from_slice(&check.to_be_bytes());
|
||||
bytes[20..28].copy_from_slice(MAGIC);
|
||||
bytes[28..36].copy_from_slice(&id.to_be_bytes());
|
||||
bytes[36] = match direction {
|
||||
Direction::Download => 0,
|
||||
Direction::Upload => 1,
|
||||
};
|
||||
Self(bytes.freeze())
|
||||
}
|
||||
|
||||
pub(crate) fn packet(&self, stage: u8, sequence: u32, sent_us: u32) -> Bytes {
|
||||
let mut bytes = BytesMut::from(self.0.as_ref());
|
||||
bytes[37] = stage;
|
||||
bytes[38..42].copy_from_slice(&sequence.to_be_bytes());
|
||||
bytes[42..46].copy_from_slice(&sent_us.to_be_bytes());
|
||||
bytes.freeze()
|
||||
}
|
||||
}
|
||||
|
||||
fn checksum(bytes: &[u8]) -> u16 {
|
||||
let mut sum: u32 = bytes
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|&word| u32::from(u16::from_be_bytes(word)))
|
||||
.sum();
|
||||
while sum > u32::from(u16::MAX) {
|
||||
sum = (sum & 0xffff) + (sum >> 16);
|
||||
}
|
||||
!(sum as u16)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
fn probe() -> Bytes {
|
||||
PacketBuilder::new(
|
||||
Ipv4Addr::new(10, 1, 10, 1),
|
||||
Ipv4Addr::new(10, 1, 10, 2),
|
||||
42,
|
||||
Direction::Upload,
|
||||
1280,
|
||||
)
|
||||
.packet(3, 908, 12_000)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routeable_ip_header_and_test_metadata_round_trip() {
|
||||
let bytes = probe();
|
||||
assert!(is_test_packet(&bytes));
|
||||
let data = decode_packet(&bytes).unwrap();
|
||||
assert_eq!(data.source, Ipv4Addr::new(10, 1, 10, 1));
|
||||
assert_eq!(data.destination, Ipv4Addr::new(10, 1, 10, 2));
|
||||
assert_eq!(
|
||||
(
|
||||
data.id,
|
||||
data.direction,
|
||||
data.stage,
|
||||
data.sequence,
|
||||
data.sent_us
|
||||
),
|
||||
(42, Direction::Upload, 3, 908, 12_000)
|
||||
);
|
||||
assert_eq!(data.payload_len(), 1280 - HEADER);
|
||||
for n in [0, 1, 19, 27, 45, 100, 1279] {
|
||||
assert!(decode_packet(&bytes[..n]).is_none());
|
||||
}
|
||||
for (byte, value) in [
|
||||
(0, 0x65),
|
||||
(2, 0x04),
|
||||
(6, 0x20),
|
||||
(9, 17),
|
||||
(10, 0),
|
||||
(20, b'z'),
|
||||
(36, 3),
|
||||
(42, 255),
|
||||
] {
|
||||
let mut bad = bytes.to_vec();
|
||||
bad[byte] = value;
|
||||
assert!(decode_packet(&bad).is_none(), "corrupted {byte}");
|
||||
}
|
||||
let mut broken = bytes.to_vec();
|
||||
broken[36] = 123;
|
||||
assert!(is_test_packet(&broken));
|
||||
broken[20] = 0;
|
||||
assert!(!is_test_packet(&broken));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use crate::NORMAL_BYTES;
|
||||
use crate::packet::{MAX_MTU, MIN_MTU};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Both endpoints name directions from the initiating user's point of view.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Direction {
|
||||
/// From the responding peer to the initiator.
|
||||
Download,
|
||||
/// From the initiator to the responding peer.
|
||||
Upload,
|
||||
}
|
||||
|
||||
/// What the received samples establish about the path.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Quality {
|
||||
/// Measurement in progress.
|
||||
#[default]
|
||||
Measuring,
|
||||
/// The receiver confirmed a stable rate after the probe reached the path's limit.
|
||||
Measured,
|
||||
/// Sustained delivery at this rate was established before the time or byte budget ended.
|
||||
AtLeast,
|
||||
/// No full observation window was available.
|
||||
Insufficient,
|
||||
}
|
||||
|
||||
/// Useful probe payload received in one direction.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Reading {
|
||||
/// Delivered bits per second, if there was enough evidence to calculate a rate.
|
||||
pub bps: Option<u64>,
|
||||
/// Unique, received probe payload bytes, excluding IPv4 and diagnostic headers.
|
||||
pub bytes: u32,
|
||||
/// Meaning of the reported rate.
|
||||
pub quality: Quality,
|
||||
}
|
||||
|
||||
/// Lifecycle of a single bidirectional test.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum State {
|
||||
/// Negotiating a test.
|
||||
#[default]
|
||||
Starting,
|
||||
/// Receiving from the peer.
|
||||
Download,
|
||||
/// Sending to the peer.
|
||||
Upload,
|
||||
/// Both direction reports were exchanged.
|
||||
Complete,
|
||||
/// A participant cancelled this test.
|
||||
Cancelled,
|
||||
/// The other endpoint is already testing.
|
||||
Busy,
|
||||
/// A participant failed to finish before the deadline.
|
||||
TimedOut,
|
||||
/// The transport failed, configuration was invalid, or a peer sent inconsistent results.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A snapshot suitable for status or a live display.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Progress {
|
||||
/// Current phase or final outcome.
|
||||
pub state: State,
|
||||
/// Peer to initiator.
|
||||
pub down: Reading,
|
||||
/// Initiator to peer.
|
||||
pub up: Reading,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
pub(crate) fn at(&mut self, direction: Direction) -> &mut Reading {
|
||||
match direction {
|
||||
Direction::Download => &mut self.down,
|
||||
Direction::Upload => &mut self.up,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Request to start one measurement under both peers' local limits.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Start {
|
||||
/// Fresh random identifier selected by the initiator.
|
||||
pub id: u64,
|
||||
/// Maximum diagnostic IPv4 bytes to send per direction.
|
||||
pub byte_limit: u32,
|
||||
/// Maximum complete IPv4 datagram size supported by the initiating endpoint.
|
||||
pub mtu: u16,
|
||||
}
|
||||
|
||||
/// Receiver-clock observation at one offered rate.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Feedback {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) bps: u64,
|
||||
pub(crate) lost_per_mille: u16,
|
||||
pub(crate) bytes: u32,
|
||||
pub(crate) echo_us: u32,
|
||||
}
|
||||
|
||||
/// Bounded records carried by the authenticated, reliable control connection.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Control {
|
||||
/// Request a test between these two peers.
|
||||
Start(Start),
|
||||
/// Negotiated maximum datagram size and per-direction budget.
|
||||
Accepted {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Per-direction budget in IPv4 bytes.
|
||||
byte_limit: u32,
|
||||
/// Size of every probe datagram.
|
||||
mtu: u16,
|
||||
},
|
||||
/// The responder already has an active test.
|
||||
Busy {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
},
|
||||
/// Receiver has installed its data sink before the sender begins.
|
||||
Ready {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction about to start.
|
||||
direction: Direction,
|
||||
},
|
||||
/// Observed goodput and loss over a full interval of the receiver's clock.
|
||||
Feedback {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction being measured.
|
||||
direction: Direction,
|
||||
/// Receiver's observation.
|
||||
sample: Feedback,
|
||||
},
|
||||
/// The sender has stopped issuing probes and shares the result of its rate search.
|
||||
End {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction ending.
|
||||
direction: Direction,
|
||||
/// Number of IPv4 datagrams issued by the sender.
|
||||
packets: u32,
|
||||
/// Rate search result based on receiver feedback.
|
||||
reading: Reading,
|
||||
},
|
||||
/// Final delivery numbers after draining late probes.
|
||||
Report {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction completed.
|
||||
direction: Direction,
|
||||
/// Agreed result for this direction.
|
||||
reading: Reading,
|
||||
},
|
||||
/// End the exchange early in either direction.
|
||||
Cancel {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) const MAX_BPS: u64 = 8_000_000_000;
|
||||
const MAX_RECORD: usize = 64;
|
||||
|
||||
impl Control {
|
||||
/// Identifier used to bind the record to an already authenticated peer and session.
|
||||
pub fn id(&self) -> u64 {
|
||||
match *self {
|
||||
Self::Start(start) => start.id,
|
||||
Self::Accepted { id, .. }
|
||||
| Self::Busy { id }
|
||||
| Self::Ready { id, .. }
|
||||
| Self::Feedback { id, .. }
|
||||
| Self::End { id, .. }
|
||||
| Self::Report { id, .. }
|
||||
| Self::Cancel { id } => id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a control record into its compact version-one representation.
|
||||
pub fn encode(&self) -> Result<Vec<u8>, postcard::Error> {
|
||||
postcard::to_stdvec(self)
|
||||
}
|
||||
|
||||
/// Parse exactly one version-one record. Trailing bytes and values outside the protocol limits are rejected.
|
||||
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||
if bytes.len() > MAX_RECORD {
|
||||
return None;
|
||||
}
|
||||
let (control, rest) = postcard::take_from_bytes::<Self>(bytes).ok()?;
|
||||
(rest.is_empty() && control.valid()).then_some(control)
|
||||
}
|
||||
|
||||
pub(crate) fn valid(self) -> bool {
|
||||
match self {
|
||||
Self::Start(Start {
|
||||
byte_limit, mtu, ..
|
||||
})
|
||||
| Self::Accepted {
|
||||
byte_limit, mtu, ..
|
||||
} => (1..=NORMAL_BYTES).contains(&byte_limit) && (MIN_MTU..=MAX_MTU).contains(&mtu),
|
||||
Self::Feedback { sample, .. } => {
|
||||
sample.bps <= MAX_BPS
|
||||
&& sample.lost_per_mille <= 1000
|
||||
&& sample.bytes <= NORMAL_BYTES
|
||||
&& sample.echo_us <= 5_000_000
|
||||
}
|
||||
Self::End {
|
||||
packets, reading, ..
|
||||
} => packets <= NORMAL_BYTES / u32::from(MIN_MTU) && valid_result(reading),
|
||||
Self::Report { reading, .. } => valid_result(reading),
|
||||
Self::Busy { .. } | Self::Ready { .. } | Self::Cancel { .. } => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_result(reading: Reading) -> bool {
|
||||
reading.bytes <= NORMAL_BYTES
|
||||
&& match reading.quality {
|
||||
Quality::Insufficient => reading.bps.is_none(),
|
||||
Quality::Measured | Quality::AtLeast => {
|
||||
reading.bytes > 0 && reading.bps.is_some_and(|v| (1..=MAX_BPS).contains(&v))
|
||||
}
|
||||
Quality::Measuring => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
//! Independently clocked sessions exchange real control records and shaped IPv4 probes.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use bytes::Bytes;
|
||||
use std::future::Future;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
use tsunagi_speedtest::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Link {
|
||||
remote: Handle,
|
||||
start: Instant,
|
||||
rate: u64,
|
||||
control_delay: Duration,
|
||||
drop_every: u32,
|
||||
state: Arc<Mutex<Delivery>>,
|
||||
samples: Arc<Mutex<Vec<Progress>>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Delivery {
|
||||
// Tokens represent one millisecond of useful payload on this shaped path.
|
||||
tick: u64,
|
||||
credit: u64,
|
||||
bytes: u64,
|
||||
packets: u32,
|
||||
}
|
||||
|
||||
impl Io for Link {
|
||||
async fn control(&self, message: Control) -> bool {
|
||||
// The harness creates the responding session with the real Start record.
|
||||
if !matches!(message, Control::Start(_)) {
|
||||
if !self.control_delay.is_zero() {
|
||||
tokio::time::sleep(self.control_delay).await;
|
||||
}
|
||||
self.remote
|
||||
.control(Control::decode(&message.encode().unwrap()).unwrap());
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
let probe = decode_packet(&packet).unwrap();
|
||||
let tick = self.start.elapsed().as_millis() as u64;
|
||||
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.tick = tick;
|
||||
}
|
||||
state.bytes += packet.len() as u64;
|
||||
if state.credit >= probe.payload_len() as u64 {
|
||||
state.credit -= probe.payload_len() as u64;
|
||||
state.packets += 1;
|
||||
if self.drop_every != 0 && state.packets.is_multiple_of(self.drop_every) {
|
||||
return true;
|
||||
}
|
||||
self.remote.data(probe);
|
||||
// Duplicates must never add more bytes or improve the reported rate.
|
||||
self.remote.data(probe);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn progress(&self, update: Progress) {
|
||||
self.samples.lock().unwrap().push(update);
|
||||
}
|
||||
}
|
||||
|
||||
fn config(local: u8, remote: u8, bytes: u32) -> Config {
|
||||
Config {
|
||||
id: 7,
|
||||
local: Ipv4Addr::new(10, 11, 12, local),
|
||||
remote: Ipv4Addr::new(10, 11, 12, remote),
|
||||
mtu: 1280,
|
||||
byte_limit: bytes,
|
||||
rtt: Duration::from_millis(20),
|
||||
}
|
||||
}
|
||||
|
||||
async fn measure(down: u64, up: u64, budget: u32) -> (Progress, Progress, Link, Link) {
|
||||
shaped(down, up, budget, Duration::ZERO, 0).await
|
||||
}
|
||||
|
||||
async fn shaped(
|
||||
down: u64,
|
||||
up: u64,
|
||||
budget: u32,
|
||||
control_delay: Duration,
|
||||
drop_every: u32,
|
||||
) -> (Progress, Progress, Link, Link) {
|
||||
let cfg = |a, b| Config {
|
||||
rtt: control_delay.max(Duration::from_millis(20)),
|
||||
..config(a, b, budget)
|
||||
};
|
||||
let (a, initiator) = initiate(cfg(1, 2));
|
||||
let start = Start {
|
||||
id: 7,
|
||||
byte_limit: budget,
|
||||
mtu: 1280,
|
||||
};
|
||||
let (b, responder) = respond(cfg(2, 1), start);
|
||||
let now = Instant::now();
|
||||
let link = |remote, rate| Link {
|
||||
remote,
|
||||
start: now,
|
||||
rate,
|
||||
control_delay,
|
||||
drop_every,
|
||||
state: Default::default(),
|
||||
samples: Default::default(),
|
||||
};
|
||||
let ab = link(b, up);
|
||||
let ba = link(a, down);
|
||||
let (a, b) = tokio::join!(initiator.run(ab.clone()), responder.run(ba.clone()));
|
||||
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));
|
||||
(a, b, ab, ba)
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn both_directions_measure_delivery_and_show_it_before_completion() {
|
||||
let (a, b, ab, _) = measure(10_000_000, 40_000_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (sample, expected) in [(a.down, 10_000_000), (a.up, 40_000_000)] {
|
||||
let bps = sample.bps.unwrap();
|
||||
assert!(
|
||||
(expected * 8 / 10..=expected * 12 / 10).contains(&bps),
|
||||
"{sample:?}"
|
||||
);
|
||||
assert_eq!(sample.quality, Quality::Measured, "{sample:?}");
|
||||
}
|
||||
let updates = ab.samples.lock().unwrap();
|
||||
assert!(
|
||||
updates
|
||||
.iter()
|
||||
.any(|p| p.state == State::Download && p.down.bps.is_some())
|
||||
);
|
||||
assert!(
|
||||
updates
|
||||
.iter()
|
||||
.any(|p| p.state == State::Upload && p.up.bps.is_some())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_fast_path_extends_the_probe_but_never_turns_a_short_burst_into_a_peak() {
|
||||
let (a, _, _, _) = measure(1_000_000_000, 1_000_000_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
assert!(a.down.bytes > 16 * 1024 * 1024);
|
||||
assert!(
|
||||
a.down
|
||||
.bps
|
||||
.is_some_and(|v| (700_000_000..=1_150_000_000).contains(&v)),
|
||||
"{a:?}"
|
||||
);
|
||||
let (short, _, _, _) = measure(1_000_000_000, 1_000_000_000, 4096).await;
|
||||
assert_eq!(short.down.quality, Quality::Insufficient);
|
||||
assert_eq!(short.down.bps, None);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn persistent_random_loss_does_not_masquerade_as_a_slow_link() {
|
||||
let (a, _, _, _) = shaped(
|
||||
20_000_000,
|
||||
45_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(45),
|
||||
20,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (reading, rate) in [(a.down, 20_000_000), (a.up, 45_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|v| (rate * 7 / 10..=rate * 11 / 10).contains(&v)),
|
||||
"{a:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn fast_metered_path_returns_a_sustained_lower_bound_within_its_budget() {
|
||||
let (a, _, _, _) = measure(4_000_000_000, 4_000_000_000, METERED_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for reading in [a.down, a.up] {
|
||||
assert_eq!(reading.quality, Quality::AtLeast);
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|v| (50_000_000..1_000_000_000).contains(&v))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn unreachable_data_path_cannot_synthesize_a_rate_or_keep_the_exchange_open() {
|
||||
let (a, _, _, _) = measure(0, 0, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for reading in [a.down, a.up] {
|
||||
assert_eq!(reading.quality, Quality::Insufficient);
|
||||
assert_eq!(reading.bps, None);
|
||||
}
|
||||
}
|
||||
|
||||
struct Silent;
|
||||
impl Io for Silent {
|
||||
fn control(&self, _: Control) -> impl Future<Output = bool> + Send {
|
||||
std::future::pending()
|
||||
}
|
||||
fn packet(&self, _: Bytes) -> bool {
|
||||
false
|
||||
}
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_blocked_control_stream_cannot_hold_up_cancellation_or_the_deadline() {
|
||||
let (handle, runner) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
let task = tokio::spawn(runner.run(Silent));
|
||||
tokio::task::yield_now().await;
|
||||
handle.cancel();
|
||||
let before = Instant::now();
|
||||
assert_eq!(task.await.unwrap().state, State::Cancelled);
|
||||
assert!(before.elapsed() <= Duration::from_millis(25));
|
||||
|
||||
let (_keep_ingress, runner) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
let before = Instant::now();
|
||||
assert_eq!(runner.run(Silent).await.state, State::TimedOut);
|
||||
assert!(before.elapsed() <= Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_records_have_finite_limits_and_exact_framing() {
|
||||
let message = Control::Start(Start {
|
||||
id: 42,
|
||||
byte_limit: NORMAL_BYTES,
|
||||
mtu: 1280,
|
||||
});
|
||||
let mut wire = message.encode().unwrap();
|
||||
assert_eq!(Control::decode(&wire), Some(message));
|
||||
for n in 0..wire.len() {
|
||||
assert_eq!(Control::decode(&wire[..n]), None);
|
||||
}
|
||||
wire.push(0);
|
||||
assert_eq!(Control::decode(&wire), None);
|
||||
assert_eq!(Control::decode(&[255; 65]), None);
|
||||
for (byte_limit, mtu) in [
|
||||
(0, 1280),
|
||||
(NORMAL_BYTES + 1, 1280),
|
||||
(1000, 4),
|
||||
(1000, u16::MAX),
|
||||
] {
|
||||
let wire = Control::Start(Start {
|
||||
id: 1,
|
||||
byte_limit,
|
||||
mtu,
|
||||
})
|
||||
.encode()
|
||||
.unwrap();
|
||||
assert_eq!(Control::decode(&wire), None);
|
||||
}
|
||||
}
|
||||
|
||||
struct OpenControl;
|
||||
impl Io for OpenControl {
|
||||
fn control(&self, _: Control) -> impl Future<Output = bool> + Send {
|
||||
std::future::ready(true)
|
||||
}
|
||||
fn packet(&self, _: Bytes) -> bool {
|
||||
false
|
||||
}
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn an_unrelated_busy_reply_does_not_cancel_the_active_request() {
|
||||
let (handle, session) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
handle.control(Control::Busy { id: 8 });
|
||||
let task = tokio::spawn(session.run(OpenControl));
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!task.is_finished());
|
||||
handle.control(Control::Busy { id: 7 });
|
||||
assert_eq!(task.await.unwrap().state, State::Busy);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn slower_control_feedback_leaves_time_for_both_directions() {
|
||||
let (a, b, _, _) = shaped(
|
||||
12_000_000,
|
||||
25_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(130),
|
||||
0,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a.state, State::Complete);
|
||||
assert!(
|
||||
a.down
|
||||
.bps
|
||||
.is_some_and(|v| (9_000_000..=14_000_000).contains(&v))
|
||||
);
|
||||
assert!(
|
||||
a.up.bps
|
||||
.is_some_and(|v| (17_000_000..=28_000_000).contains(&v))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn slow_links_accumulate_enough_arrivals_for_a_rate() {
|
||||
let (a, _, _, _) = measure(100_000, 256_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (r, rate) in [(a.down, 100_000), (a.up, 256_000)] {
|
||||
assert!(
|
||||
r.bps
|
||||
.is_some_and(|v| (rate * 65 / 100..=rate * 125 / 100).contains(&v)),
|
||||
"{r:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
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)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_rate_requires_evidence_of_delivered_payload() {
|
||||
for quality in [Quality::AtLeast, Quality::Measured] {
|
||||
let message = Control::Report {
|
||||
id: 1,
|
||||
direction: Direction::Download,
|
||||
reading: Reading {
|
||||
bps: Some(8_000_000_000),
|
||||
bytes: 0,
|
||||
quality,
|
||||
},
|
||||
};
|
||||
assert!(Control::decode(&message.encode().unwrap()).is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
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.4" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" }
|
||||
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.4"
|
||||
version = "1.0.6"
|
||||
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.4" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" }
|
||||
# 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).
|
||||
|
||||
@@ -9,16 +9,13 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Instant;
|
||||
|
||||
use eframe::egui;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use tsunagi::ipc;
|
||||
|
||||
/// How often the worker refreshes status while idle.
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(2);
|
||||
|
||||
use tsunagi_ui::client::Client;
|
||||
pub(crate) use tsunagi_ui::client::{Command, Snapshot, VipSaveResult};
|
||||
|
||||
@@ -105,12 +102,19 @@ async fn worker(
|
||||
ctx: egui::Context,
|
||||
) {
|
||||
refresh(&shared, &ctx).await;
|
||||
let mut tick = tokio::time::interval(POLL_INTERVAL);
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
|
||||
loop {
|
||||
let interval = {
|
||||
let snapshot = lock(&shared);
|
||||
tsunagi_ui::client::status_poll_interval(
|
||||
snapshot
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s.as_ref().ok())
|
||||
.map(Arc::as_ref),
|
||||
)
|
||||
};
|
||||
tokio::select! {
|
||||
_ = tick.tick() => {
|
||||
_ = tokio::time::sleep(interval) => {
|
||||
refresh(&shared, &ctx).await;
|
||||
}
|
||||
command = rx.recv() => {
|
||||
@@ -245,6 +249,16 @@ async fn run(
|
||||
})
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
Command::StartSpeedTest { network_id, peer } => {
|
||||
ipc::start_speed_test(socket, &network_id, peer.as_deref(), false)
|
||||
.await
|
||||
.map(|_| String::new())
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
Command::StopSpeedTest { network_id } => ipc::stop_speed_test(socket, &network_id)
|
||||
.await
|
||||
.map(|_| String::new())
|
||||
.map_err(|err| err.to_string()),
|
||||
Command::Join { name, secret } => ipc::join_network(socket, &name, &secret)
|
||||
.await
|
||||
.map(|report| {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
description = "Shared egui widgets for the tray and Android clients."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Commands and observations shared by both graphical clients.
|
||||
use std::{path::PathBuf, time::Instant};
|
||||
use tsunagi::ipc::StatusReport;
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tsunagi::ipc::{SpeedPhase, SpeedReport, StatusReport};
|
||||
|
||||
/// A request from the UI to the agent.
|
||||
pub enum Command {
|
||||
@@ -62,6 +65,18 @@ pub enum Command {
|
||||
/// Selected member identity.
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Measure one peer, or all compatible online exits in sequence.
|
||||
StartSpeedTest {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Exact peer identity, or all exits when absent.
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Cancel this network's current test and any queued exits.
|
||||
StopSpeedTest {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
},
|
||||
/// Join a network, or start one already configured.
|
||||
Join {
|
||||
/// Network name.
|
||||
@@ -119,3 +134,25 @@ pub trait Client {
|
||||
/// An earlier action is waiting for an acknowledgement.
|
||||
fn busy(&self) -> bool;
|
||||
}
|
||||
|
||||
pub(crate) fn speed_running(report: &SpeedReport) -> bool {
|
||||
report.batch.is_some()
|
||||
|| report.peers.values().any(|peer| {
|
||||
matches!(
|
||||
peer.phase,
|
||||
SpeedPhase::Queued
|
||||
| SpeedPhase::Preparing
|
||||
| SpeedPhase::Download
|
||||
| SpeedPhase::Upload
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Poll more frequently while showing a short, live speed measurement.
|
||||
pub fn status_poll_interval(report: Option<&StatusReport>) -> Duration {
|
||||
if report.is_some_and(|r| r.networks.iter().any(|n| speed_running(&n.speed))) {
|
||||
Duration::from_millis(250)
|
||||
} else {
|
||||
Duration::from_secs(2)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@
|
||||
use std::collections::HashMap;
|
||||
mod compact;
|
||||
mod exit_picker;
|
||||
mod speed;
|
||||
#[cfg(test)]
|
||||
mod speed_tests;
|
||||
mod status;
|
||||
pub use crate::exit::name_of;
|
||||
pub use exit_picker::choose_exit;
|
||||
@@ -160,6 +163,7 @@ pub fn show(
|
||||
traffic: &Traffic,
|
||||
) {
|
||||
let (confirm, forget_confirm) = confirmations;
|
||||
let speed = speed::Controls::new(network, agent);
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
// Reserve the unit switch even when a network name fills the viewport.
|
||||
@@ -176,6 +180,17 @@ pub fn show(
|
||||
});
|
||||
// A copy of the chosen unit for the read-only rendering below.
|
||||
let unit = *unit;
|
||||
let devices = devices(network, own_id);
|
||||
let roster_tools = |ui: &mut egui::Ui| {
|
||||
let online = devices.iter().filter(|d| d.online).count();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(format!(
|
||||
"devices ({online} online / {} known)",
|
||||
devices.len()
|
||||
));
|
||||
speed.toolbar(ui);
|
||||
});
|
||||
};
|
||||
|
||||
if ctx.os() == egui::os::OperatingSystem::Android || ui.available_width() < 620.0 {
|
||||
egui::ScrollArea::vertical()
|
||||
@@ -189,24 +204,21 @@ pub fn show(
|
||||
} else {
|
||||
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0);
|
||||
}
|
||||
roster_tools(ui);
|
||||
compact::roster(
|
||||
ui,
|
||||
network,
|
||||
own_id,
|
||||
&devices,
|
||||
traffic,
|
||||
unit,
|
||||
(confirm, forget_confirm),
|
||||
&speed,
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
let devices = devices(network, own_id);
|
||||
let online = devices.iter().filter(|d| d.online).count();
|
||||
ui.columns(2, |columns| {
|
||||
columns[0].strong(format!(
|
||||
"devices ({online} online / {} known)",
|
||||
devices.len()
|
||||
));
|
||||
roster_tools(&mut columns[0]);
|
||||
columns[0].collapsing("Network details", |ui| summary(ui, network));
|
||||
let plot = &mut columns[1];
|
||||
plot.label("Network traffic");
|
||||
@@ -217,18 +229,32 @@ pub fn show(
|
||||
});
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
egui::ScrollArea::both()
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
device_table(
|
||||
ui,
|
||||
unit,
|
||||
network,
|
||||
&devices,
|
||||
traffic,
|
||||
confirm,
|
||||
forget_confirm,
|
||||
);
|
||||
let table = desktop_columns(ui, unit, network, &devices, traffic);
|
||||
let required = table.widths.iter().sum::<f32>() + crate::table::GAP * 8.;
|
||||
if required <= ui.available_width() {
|
||||
device_table(
|
||||
ui,
|
||||
network,
|
||||
&devices,
|
||||
(traffic, unit),
|
||||
(confirm, forget_confirm),
|
||||
&speed,
|
||||
&table,
|
||||
);
|
||||
} else {
|
||||
compact::roster(
|
||||
ui,
|
||||
network,
|
||||
&devices,
|
||||
traffic,
|
||||
unit,
|
||||
(confirm, forget_confirm),
|
||||
&speed,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
confirm_exit(ctx, agent, confirm, Some(&network.network_id));
|
||||
@@ -652,22 +678,20 @@ fn exit_cell(
|
||||
}
|
||||
}
|
||||
|
||||
/// One table of all devices: online rows carry live counters and a plot,
|
||||
/// offline rows show what is known (name and address) and dashes.
|
||||
fn device_table(
|
||||
ui: &mut egui::Ui,
|
||||
struct DesktopColumns {
|
||||
widths: [f32; 9],
|
||||
total: String,
|
||||
rate: String,
|
||||
}
|
||||
|
||||
fn desktop_columns(
|
||||
ui: &egui::Ui,
|
||||
unit: Unit,
|
||||
network: &NetworkReport,
|
||||
devices: &[Device<'_>],
|
||||
traffic: &Traffic,
|
||||
confirm: &mut Option<ExitConfirm>,
|
||||
forget_confirm: &mut Option<ForgetConfirm>,
|
||||
) {
|
||||
) -> DesktopColumns {
|
||||
let network_id = network.network_id.as_str();
|
||||
if devices.is_empty() {
|
||||
ui.weak("none");
|
||||
return;
|
||||
}
|
||||
let widths_id = egui::Id::new(("devices column widths", network_id));
|
||||
let mut widths = column_widths(ui, widths_id);
|
||||
let previous_widths = widths;
|
||||
@@ -684,6 +708,7 @@ fn device_table(
|
||||
for (column, header) in headers.iter().enumerate() {
|
||||
widths[column] = widths[column].max(measure((*header).to_owned()));
|
||||
}
|
||||
widths[1] = widths[1].max(measure("exit".into()) + 4. + speed::WIDTH);
|
||||
let (mut tx_total, mut rx_total) = (0_u64, 0_u64);
|
||||
for device in devices {
|
||||
let name = format!(
|
||||
@@ -723,9 +748,51 @@ fn device_table(
|
||||
}
|
||||
ui.memory_mut(|m| m.data.insert_temp(widths_id, widths));
|
||||
let widths = stretch_columns(widths, ui.available_width());
|
||||
crate::table::row(ui, "device headers", &widths, false, |column, ui| {
|
||||
DesktopColumns {
|
||||
widths,
|
||||
total,
|
||||
rate,
|
||||
}
|
||||
}
|
||||
|
||||
/// One table of all devices: online rows carry live counters and a plot,
|
||||
/// offline rows show what is known (name and address) and dashes.
|
||||
fn device_table(
|
||||
ui: &mut egui::Ui,
|
||||
network: &NetworkReport,
|
||||
devices: &[Device<'_>],
|
||||
(traffic, unit): (&Traffic, Unit),
|
||||
(confirm, forget_confirm): (&mut Option<ExitConfirm>, &mut Option<ForgetConfirm>),
|
||||
speed: &speed::Controls<'_>,
|
||||
table: &DesktopColumns,
|
||||
) {
|
||||
if devices.is_empty() {
|
||||
ui.weak("none");
|
||||
return;
|
||||
}
|
||||
let network_id = &network.network_id;
|
||||
let headers = column_headers(unit);
|
||||
let widths = &table.widths;
|
||||
crate::table::row(ui, "device headers", widths, false, |column, ui| {
|
||||
let response = ui.weak(headers[column]);
|
||||
match column {
|
||||
1 => {
|
||||
let rect = ui.max_rect();
|
||||
let speed_rect = rect.split_left_right_at_x(rect.right() - speed::WIDTH).1;
|
||||
let r = ui.interact(
|
||||
speed_rect,
|
||||
ui.id().with("speed units"),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
ui.painter_at(speed_rect).text(
|
||||
speed_rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
speed::HEADER,
|
||||
egui::TextStyle::Body.resolve(ui.style()),
|
||||
ui.visuals().weak_text_color(),
|
||||
);
|
||||
widgets::hint(r, speed::HEADER_HINT);
|
||||
}
|
||||
2 => {
|
||||
response.on_hover_text("Encrypted data channel readiness.");
|
||||
}
|
||||
@@ -745,14 +812,19 @@ fn device_table(
|
||||
crate::table::row(
|
||||
ui,
|
||||
device.id,
|
||||
&widths,
|
||||
widths,
|
||||
index % 2 == 0,
|
||||
|column, ui| match column {
|
||||
0 => {
|
||||
name_cell(ui, device);
|
||||
forget_button(ui, device, network, forget_confirm);
|
||||
}
|
||||
1 => exit_cell(ui, device, network_id, confirm),
|
||||
1 => {
|
||||
let rect = ui.max_rect();
|
||||
let speed_rect = rect.split_left_right_at_x(rect.right() - speed::WIDTH).1;
|
||||
exit_cell(ui, device, network_id, confirm);
|
||||
speed.cell(ui, speed_rect, device);
|
||||
}
|
||||
2 => tunnel_cell(ui, device),
|
||||
3 => {
|
||||
ui.label(rtt_pair(device)).on_hover_text(
|
||||
@@ -789,17 +861,17 @@ fn device_table(
|
||||
crate::table::row(
|
||||
ui,
|
||||
"device totals",
|
||||
&widths,
|
||||
widths,
|
||||
false,
|
||||
|column, ui| match column {
|
||||
0 => {
|
||||
ui.strong("total");
|
||||
}
|
||||
6 => {
|
||||
ui.strong(&total);
|
||||
ui.strong(&table.total);
|
||||
}
|
||||
7 => {
|
||||
ui.strong(&rate);
|
||||
ui.strong(&table.rate);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
@@ -920,6 +992,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn device_table(
|
||||
ui: &mut egui::Ui,
|
||||
unit: Unit,
|
||||
network: &NetworkReport,
|
||||
devices: &[Device<'_>],
|
||||
traffic: &Traffic,
|
||||
confirm: &mut Option<ExitConfirm>,
|
||||
forget: &mut Option<ForgetConfirm>,
|
||||
) {
|
||||
let table = desktop_columns(ui, unit, network, devices, traffic);
|
||||
super::device_table(
|
||||
ui,
|
||||
network,
|
||||
devices,
|
||||
(traffic, unit),
|
||||
(confirm, forget),
|
||||
&speed::Controls::new(network, &ReadOnly),
|
||||
&table,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phone_roster_fits_each_width_and_expands_only_the_tapped_member() {
|
||||
let mut network = NetworkReport {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! A width-constrained device table for touch. Optional columns move into the
|
||||
//! expanded row before any essential columns run out of space.
|
||||
use super::{
|
||||
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text,
|
||||
devices, exit, forget_button, format, icon, rtt_text, traffic_pair, tunnel_cell,
|
||||
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text, exit,
|
||||
forget_button, format, icon, rtt_text, speed, traffic_pair, tunnel_cell,
|
||||
};
|
||||
use crate::widgets;
|
||||
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, Vec2, pos2, vec2};
|
||||
@@ -10,6 +10,7 @@ use egui::{Align2, Color32, FontId, Rect, Sense, Ui, Vec2, pos2, vec2};
|
||||
#[derive(Clone, Copy)]
|
||||
enum Column {
|
||||
Device,
|
||||
Speed,
|
||||
State,
|
||||
Address,
|
||||
Rtt,
|
||||
@@ -23,6 +24,7 @@ impl Column {
|
||||
fn title(self, unit: Unit) -> &'static str {
|
||||
match self {
|
||||
Self::Device => "device",
|
||||
Self::Speed => speed::HEADER,
|
||||
Self::State => "State",
|
||||
Self::Address => "IPv4",
|
||||
Self::Rtt => "Data RTT",
|
||||
@@ -44,7 +46,17 @@ fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32
|
||||
.x
|
||||
+ 10.
|
||||
};
|
||||
let mut cols = vec![(Column::Device, 0.)];
|
||||
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)));
|
||||
}
|
||||
@@ -56,7 +68,7 @@ fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32
|
||||
Column::Rtt,
|
||||
measure("9999 ms").min(width * if landscape { 0.15 } else { 0.22 }),
|
||||
));
|
||||
if landscape {
|
||||
if landscape && width >= 420. {
|
||||
cols.push((
|
||||
Column::Traffic,
|
||||
measure(Column::Traffic.title(unit))
|
||||
@@ -95,17 +107,12 @@ fn text_cell(ui: &Ui, rect: Rect, text: &str, font: &FontId, color: Color32) {
|
||||
pub(super) fn roster(
|
||||
ui: &mut Ui,
|
||||
network: &NetworkReport,
|
||||
own_id: &str,
|
||||
members: &[Device<'_>],
|
||||
traffic: &Traffic,
|
||||
unit: Unit,
|
||||
(exit, forget): (&mut Option<ExitConfirm>, &mut Option<ForgetConfirm>),
|
||||
speed: &speed::Controls<'_>,
|
||||
) {
|
||||
let members = devices(network, own_id);
|
||||
let online = members.iter().filter(|m| m.online).count();
|
||||
ui.strong(format!(
|
||||
"devices ({online} online / {} known)",
|
||||
members.len()
|
||||
));
|
||||
// An Android rotation changes the surrounding scroll area but not the selected peer.
|
||||
let id = egui::Id::new(("expanded device", &network.network_id));
|
||||
let mut selected = ui.data(|d| d.get_temp::<String>(id));
|
||||
@@ -121,13 +128,25 @@ pub(super) fn roster(
|
||||
if matches!(column, Column::Device) {
|
||||
rect.min.x += 20.;
|
||||
}
|
||||
text_cell(
|
||||
ui,
|
||||
rect,
|
||||
column.title(unit),
|
||||
&font,
|
||||
ui.visuals().text_color(),
|
||||
);
|
||||
if matches!(column, Column::Speed) {
|
||||
ui.painter_at(rect).text(
|
||||
rect.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
column.title(unit),
|
||||
font.clone(),
|
||||
ui.visuals().text_color(),
|
||||
);
|
||||
let r = ui.interact(rect, id.with("speed units"), Sense::click());
|
||||
widgets::hint(r, speed::HEADER_HINT);
|
||||
} else {
|
||||
text_cell(
|
||||
ui,
|
||||
rect,
|
||||
column.title(unit),
|
||||
&font,
|
||||
ui.visuals().text_color(),
|
||||
);
|
||||
}
|
||||
x += w;
|
||||
}
|
||||
for (index, member) in members.iter().enumerate() {
|
||||
@@ -176,6 +195,10 @@ pub(super) fn roster(
|
||||
let mut rect = Rect::from_min_size(pos2(x, row.top()), vec2(w, row.height()));
|
||||
x += w;
|
||||
let text = match column {
|
||||
Column::Speed => {
|
||||
speed.cell(ui, rect, member);
|
||||
continue;
|
||||
}
|
||||
Column::Device => {
|
||||
channel.paint(
|
||||
ui,
|
||||
@@ -184,13 +207,13 @@ pub(super) fn roster(
|
||||
rect.min.x += 20.;
|
||||
if member.in_use || member.exit_node {
|
||||
ui.painter_at(rect).text(
|
||||
rect.left_center(),
|
||||
Align2::LEFT_CENTER,
|
||||
rect.right_center(),
|
||||
Align2::RIGHT_CENTER,
|
||||
icon::SIGN_OUT,
|
||||
font.clone(),
|
||||
if member.in_use { exit::GOOD } else { normal },
|
||||
);
|
||||
rect.min.x += font.size + 3.;
|
||||
rect.max.x -= font.size + 3.;
|
||||
}
|
||||
member.name()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! The same speed control occupies one fixed cell throughout a measurement.
|
||||
use super::{Client, Command, Device, NetworkReport, format, icon, widgets};
|
||||
use crate::client::speed_running;
|
||||
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, pos2, vec2};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tsunagi::ipc::{SpeedPeerReport, SpeedPhase, SpeedRate};
|
||||
|
||||
pub(super) const WIDTH: f32 = 108.;
|
||||
pub(super) const PORTRAIT_WIDTH: f32 = 56.;
|
||||
pub(super) const HEADER: &str = "Mbit/s";
|
||||
pub(super) const HEADER_HINT: &str = "Peer speed test · download / upload in megabits per second";
|
||||
|
||||
pub(super) struct Controls<'a> {
|
||||
network: &'a NetworkReport,
|
||||
client: &'a dyn Client,
|
||||
running: bool,
|
||||
}
|
||||
|
||||
impl<'a> Controls<'a> {
|
||||
pub(super) fn new(network: &'a NetworkReport, client: &'a dyn Client) -> Self {
|
||||
Self {
|
||||
network,
|
||||
client,
|
||||
running: speed_running(&network.speed),
|
||||
}
|
||||
}
|
||||
|
||||
fn capable(&self, id: &str) -> bool {
|
||||
self.network.speed.capable.iter().any(|peer| peer == id)
|
||||
}
|
||||
|
||||
pub(super) fn toolbar(&self, ui: &mut Ui) {
|
||||
let (label, help, available) = if self.running {
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(250));
|
||||
let label = self.network.speed.batch.map_or_else(
|
||||
|| format!("{} Stop test", icon::STOP),
|
||||
|batch| format!("{} Stop {}/{}", icon::STOP, batch.done, batch.total),
|
||||
);
|
||||
(
|
||||
label,
|
||||
"Stop this speed test and skip any queued exits.",
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
let available = self.network.active
|
||||
&& self
|
||||
.network
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.exit_node && self.capable(&p.endpoint_id));
|
||||
(
|
||||
format!("{} Test exits", icon::GAUGE),
|
||||
if available {
|
||||
"Test each compatible online exit node in this network, one at a time."
|
||||
} else {
|
||||
"No online exit in this network supports peer speed tests."
|
||||
},
|
||||
available,
|
||||
)
|
||||
};
|
||||
// Leave room for the batch count before starting. A wrapping toolbar
|
||||
// must keep the same height when the button becomes Stop.
|
||||
let width = ui
|
||||
.painter()
|
||||
.layout_no_wrap(
|
||||
format!("{} Stop 9999/9999", icon::STOP),
|
||||
egui::TextStyle::Button.resolve(ui.style()),
|
||||
ui.visuals().text_color(),
|
||||
)
|
||||
.size()
|
||||
.x
|
||||
+ 2. * ui.spacing().button_padding.x;
|
||||
let button = ui.add_enabled(
|
||||
available && !self.client.busy(),
|
||||
egui::Button::new(label).min_size(vec2(width, 0.)),
|
||||
);
|
||||
if widgets::hint(button, help).clicked() {
|
||||
let network_id = self.network.network_id.clone();
|
||||
let command = if self.running {
|
||||
Command::StopSpeedTest { network_id }
|
||||
} else {
|
||||
Command::StartSpeedTest {
|
||||
network_id,
|
||||
peer: None,
|
||||
}
|
||||
};
|
||||
self.client.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cell(&self, ui: &mut Ui, rect: Rect, peer: &Device<'_>) {
|
||||
if !ui.is_rect_visible(rect) {
|
||||
return;
|
||||
}
|
||||
let reading = self.network.speed.peers.get(peer.id);
|
||||
let supported = self.capable(peer.id);
|
||||
let ready = self.network.active && peer.online && supported;
|
||||
let can_start = ready && !self.running && !self.client.busy();
|
||||
let id = ui.make_persistent_id(("test peer speed", &self.network.network_id, peer.id));
|
||||
let r = ui.interact(rect, id, Sense::click());
|
||||
let r = if can_start {
|
||||
r.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
} else {
|
||||
r
|
||||
};
|
||||
let v = ui.visuals();
|
||||
let color = if ready {
|
||||
v.hyperlink_color
|
||||
} else {
|
||||
v.weak_text_color()
|
||||
};
|
||||
if can_start && (r.hovered() || r.has_focus()) {
|
||||
ui.painter()
|
||||
.rect_filled(rect.shrink(1.), 3., v.widgets.hovered.weak_bg_fill);
|
||||
}
|
||||
paint_reading(ui, rect, reading, ready, color);
|
||||
let hint = tooltip(peer, reading, supported, self.running);
|
||||
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, can_start, &hint));
|
||||
if widgets::hint(r, &hint).clicked() && can_start {
|
||||
self.client.send(Command::StartSpeedTest {
|
||||
network_id: self.network.network_id.clone(),
|
||||
peer: Some(peer.id.into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_reading(
|
||||
ui: &Ui,
|
||||
rect: Rect,
|
||||
reading: Option<&SpeedPeerReport>,
|
||||
ready: bool,
|
||||
color: Color32,
|
||||
) {
|
||||
let painter = ui.painter_at(rect);
|
||||
let Some(test) = reading else {
|
||||
let glyph = if ready { icon::GAUGE } else { "—" };
|
||||
painter.text(
|
||||
rect.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
glyph,
|
||||
FontId::proportional(16.),
|
||||
color,
|
||||
);
|
||||
return;
|
||||
};
|
||||
let v = ui.visuals();
|
||||
let small = egui::TextStyle::Small.resolve(ui.style());
|
||||
let label = |s: &str, ink: Color32| {
|
||||
painter.text(rect.center(), Align2::CENTER_CENTER, s, small.clone(), ink);
|
||||
};
|
||||
match test.phase {
|
||||
SpeedPhase::Queued => label("Queued", v.weak_text_color()),
|
||||
SpeedPhase::Preparing => {
|
||||
label("Starting", color);
|
||||
activity(ui, rect, color);
|
||||
}
|
||||
SpeedPhase::Failed(_) => label(&format!("{} Retry", icon::WARNING), v.error_fg_color),
|
||||
SpeedPhase::Cancelled => label(&format!("{} Retry", icon::ARROW_CLOCKWISE), color),
|
||||
SpeedPhase::Download | SpeedPhase::Upload | SpeedPhase::Done => {
|
||||
// Reserve the same two slots for idle, live and completed readings.
|
||||
let inline = rect.width() >= WIDTH - 1.;
|
||||
let font = if inline {
|
||||
small.clone()
|
||||
} else {
|
||||
FontId::proportional(small.size.min(rect.height() * 0.46))
|
||||
};
|
||||
for (offset, arrow, rate, phase) in [
|
||||
(-0.23, icon::ARROW_DOWN, test.down, SpeedPhase::Download),
|
||||
(0.23, icon::ARROW_UP, test.up, SpeedPhase::Upload),
|
||||
] {
|
||||
let measuring = test.phase == phase;
|
||||
let value = rate.map_or_else(
|
||||
|| if measuring { "…" } else { "—" }.to_owned(),
|
||||
compact_rate,
|
||||
);
|
||||
let ink = if measuring {
|
||||
v.hyperlink_color
|
||||
} else if rate.is_some() {
|
||||
v.text_color()
|
||||
} else {
|
||||
v.weak_text_color()
|
||||
};
|
||||
painter.text(
|
||||
rect.center()
|
||||
+ if inline {
|
||||
vec2(rect.width() * offset, 0.)
|
||||
} else {
|
||||
vec2(0., rect.height() * offset)
|
||||
},
|
||||
Align2::CENTER_CENTER,
|
||||
format!("{arrow} {value}"),
|
||||
font.clone(),
|
||||
ink,
|
||||
);
|
||||
}
|
||||
if test.phase != SpeedPhase::Done {
|
||||
activity(ui, rect, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A moving mark indicates an active phase even before the first receiver
|
||||
// report arrives. Repaint only visible, active cells.
|
||||
fn activity(ui: &Ui, rect: Rect, color: Color32) {
|
||||
let bar = rect.shrink2(vec2(4., 1.));
|
||||
let width = bar.width() * 0.24;
|
||||
let t = ui.input(|i| (i.time % 1.) as f32);
|
||||
let x = bar.left() + (bar.width() - width) * (t * std::f32::consts::PI).sin().powi(2);
|
||||
ui.painter_at(rect).line_segment(
|
||||
[pos2(x, bar.bottom()), pos2(x + width, bar.bottom())],
|
||||
(1., color),
|
||||
);
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(80));
|
||||
}
|
||||
|
||||
// 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;
|
||||
if rate.lower_bound {
|
||||
let scale = 10_f64.powi(precision as i32);
|
||||
value = (value * scale).floor() / scale;
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
fn tooltip(
|
||||
peer: &Device<'_>,
|
||||
test: Option<&SpeedPeerReport>,
|
||||
supported: bool,
|
||||
running: bool,
|
||||
) -> String {
|
||||
let mut hint = format!("Speed to {}", peer.name());
|
||||
if let Some(test) = test {
|
||||
let phase = match &test.phase {
|
||||
SpeedPhase::Queued => "Waiting for the previous exit",
|
||||
SpeedPhase::Preparing => "Opening the data channel",
|
||||
SpeedPhase::Download => "Measuring download",
|
||||
SpeedPhase::Upload => "Measuring upload",
|
||||
SpeedPhase::Done => "Completed",
|
||||
SpeedPhase::Failed(error) => error.as_str(),
|
||||
SpeedPhase::Cancelled => "Stopped",
|
||||
};
|
||||
hint.push_str(&format!("\n{phase}"));
|
||||
for (label, rate) in [("Download", test.down), ("Upload", test.up)] {
|
||||
if let Some(rate) = rate {
|
||||
let (divisor, suffix) = if rate.bps < 1_000_000 {
|
||||
(1000., "kbit/s")
|
||||
} 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)
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(path) = &test.path {
|
||||
hint.push_str(&format!("\nPath at start {path}"));
|
||||
}
|
||||
if test.elapsed_ms > 0 || test.bytes > 0 {
|
||||
hint.push_str(&format!(
|
||||
"\n{} transferred in {:.1} s",
|
||||
format::bytes(test.bytes as f64),
|
||||
f64::from(test.elapsed_ms) / 1000.
|
||||
));
|
||||
}
|
||||
if test.measured_at_unix_secs > 0
|
||||
&& matches!(
|
||||
test.phase,
|
||||
SpeedPhase::Done | SpeedPhase::Failed(_) | SpeedPhase::Cancelled
|
||||
)
|
||||
&& let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH)
|
||||
{
|
||||
let age = now.as_secs().saturating_sub(test.measured_at_unix_secs);
|
||||
let age = if age < 60 {
|
||||
format!("{age} s")
|
||||
} else if age < 3600 {
|
||||
format!("{} min", age / 60)
|
||||
} else {
|
||||
format!("{} h", age / 3600)
|
||||
};
|
||||
hint.push_str(&format!("\nMeasured {age} ago"));
|
||||
}
|
||||
}
|
||||
if !peer.online {
|
||||
hint.push_str("\nPeer is offline.");
|
||||
} else if !supported {
|
||||
hint.push_str("\nNo compatible speed-test session with this peer.");
|
||||
} else if !running {
|
||||
hint.push_str(if test.is_some() {
|
||||
"\nTap to test again."
|
||||
} else {
|
||||
"\nTap to test download and upload."
|
||||
});
|
||||
}
|
||||
hint
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
use tsunagi::ipc::{PeerReport, SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate};
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClientLog(RefCell<Vec<Command>>);
|
||||
|
||||
impl Client for ClientLog {
|
||||
fn send(&self, cmd: Command) {
|
||||
self.0.borrow_mut().push(cmd);
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn network() -> NetworkReport {
|
||||
let mut n = NetworkReport {
|
||||
active: true,
|
||||
name: "mesh".into(),
|
||||
network_id: "network".into(),
|
||||
..Default::default()
|
||||
};
|
||||
for (id, offers_exit) in [("alice", true), ("ben", false), ("older", true)] {
|
||||
n.peers.push(PeerReport {
|
||||
endpoint_id: id.into(),
|
||||
hostname: Some(id.into()),
|
||||
exit_node: offers_exit,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
n.speed.capable = vec!["alice".into(), "ben".into()];
|
||||
n
|
||||
}
|
||||
|
||||
fn reading(phase: SpeedPhase) -> SpeedPeerReport {
|
||||
SpeedPeerReport {
|
||||
phase,
|
||||
down: Some(SpeedRate {
|
||||
bps: 125_000_000,
|
||||
lower_bound: false,
|
||||
}),
|
||||
up: Some(SpeedRate {
|
||||
bps: 35_995_000,
|
||||
lower_bound: true,
|
||||
}),
|
||||
bytes: 1_900_000,
|
||||
elapsed_ms: 600,
|
||||
path: Some("wg direct".into()),
|
||||
measured_at_unix_secs: 0,
|
||||
}
|
||||
}
|
||||
|
||||
struct Screen {
|
||||
ctx: egui::Context,
|
||||
width: f32,
|
||||
log: ClientLog,
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
fn new(width: f32, mobile: bool) -> Self {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
if mobile {
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
}
|
||||
Self {
|
||||
ctx,
|
||||
width,
|
||||
log: ClientLog::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(&self, n: &NetworkReport, events: Vec<egui::Event>) -> egui::FullOutput {
|
||||
self.frame_at(n, None, events)
|
||||
}
|
||||
|
||||
fn frame_at(
|
||||
&self,
|
||||
n: &NetworkReport,
|
||||
time: Option<f64>,
|
||||
events: Vec<egui::Event>,
|
||||
) -> egui::FullOutput {
|
||||
self.ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(self.width, 650.),
|
||||
)),
|
||||
events,
|
||||
time,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
show(
|
||||
ctx,
|
||||
&self.log,
|
||||
&mut Unit::Bytes,
|
||||
(&mut None, &mut None),
|
||||
n,
|
||||
"self",
|
||||
&Traffic::default(),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn click(&self, n: &NetworkReport, pos: egui::Pos2) {
|
||||
for pressed in [true, false] {
|
||||
self.frame(
|
||||
n,
|
||||
vec![
|
||||
egui::Event::PointerMoved(pos),
|
||||
egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn positions(out: &egui::FullOutput, find: impl Fn(&str) -> bool) -> Vec<egui::Pos2> {
|
||||
out.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if find(t.galley.text()) => {
|
||||
Some(t.pos + t.galley.rect.center().to_vec2())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_and_completed_readings_keep_the_same_row_and_tapping_retests_a_non_exit_peer() {
|
||||
for (width, mobile) in [(320., true), (860., true), (1440., false)] {
|
||||
let mut n = network();
|
||||
let s = Screen::new(width, mobile);
|
||||
s.frame(&n, vec![]);
|
||||
let idle = s.frame(&n, vec![]);
|
||||
let gauges = positions(&idle, |s| s == icon::GAUGE);
|
||||
assert_eq!(gauges.len(), 2, "capable peers only");
|
||||
let button = gauges[1];
|
||||
let peer_pos = positions(&idle, |s| s == "ben")[0];
|
||||
let after = positions(&idle, |s| s == "older")[0];
|
||||
s.click(&n, button);
|
||||
for phase in [
|
||||
SpeedPhase::Preparing,
|
||||
SpeedPhase::Download,
|
||||
SpeedPhase::Upload,
|
||||
SpeedPhase::Done,
|
||||
] {
|
||||
let live_down = phase == SpeedPhase::Download;
|
||||
let mut report = reading(phase);
|
||||
if live_down {
|
||||
report.down = Some(SpeedRate {
|
||||
bps: 19_900_000,
|
||||
lower_bound: false,
|
||||
});
|
||||
report.up = None;
|
||||
}
|
||||
n.speed.peers.insert("ben".into(), report);
|
||||
let out = s.frame(&n, vec![]);
|
||||
if live_down {
|
||||
assert!(!positions(&out, |s| s == format!("{} 20", icon::ARROW_DOWN)).is_empty());
|
||||
assert!(!positions(&out, |s| s == format!("{} —", icon::ARROW_UP)).is_empty());
|
||||
}
|
||||
assert_eq!(positions(&out, |s| s == "ben"), [peer_pos]);
|
||||
assert_eq!(positions(&out, |s| s == "older"), [after]);
|
||||
assert!(
|
||||
positions(&out, |s| s == "Endpoint ID").is_empty(),
|
||||
"speed tap expanded a row"
|
||||
);
|
||||
}
|
||||
let done = s.frame(&n, vec![]);
|
||||
for value in ["125", "≥35"] {
|
||||
let lines = positions(&done, |s| s.ends_with(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];
|
||||
if width > 650. {
|
||||
assert!(
|
||||
(down.y - up.y).abs() < 1. && down.x < up.x,
|
||||
"wide screens show both rates on one line"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
(down.x - up.x).abs() < 1. && down.y < up.y,
|
||||
"portrait shows a rate on each line"
|
||||
);
|
||||
}
|
||||
s.click(&n, button);
|
||||
let log = s.log.0.borrow();
|
||||
assert_eq!(log.len(), 2);
|
||||
assert!(log.iter().all(|cmd| matches!(cmd, Command::StartSpeedTest { network_id, peer: Some(peer) } if network_id == "network" && peer == "ben")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_press_explains_a_partial_result_without_requesting_another_test() {
|
||||
let s = Screen::new(360., true);
|
||||
let mut n = network();
|
||||
n.speed.peers.insert(
|
||||
"ben".into(),
|
||||
reading(SpeedPhase::Failed("Peer timed out".into())),
|
||||
);
|
||||
let draw = |time, events| s.frame_at(&n, Some(time), events);
|
||||
draw(0., vec![]);
|
||||
let pos = positions(&draw(0.1, vec![]), |s| s.contains("Retry"))[0];
|
||||
let touch = |phase| egui::Event::Touch {
|
||||
device_id: egui::TouchDeviceId(0),
|
||||
id: egui::TouchId(1),
|
||||
phase,
|
||||
pos,
|
||||
force: None,
|
||||
};
|
||||
let pointer = |pressed| egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
};
|
||||
draw(
|
||||
0.2,
|
||||
vec![
|
||||
touch(egui::TouchPhase::Start),
|
||||
egui::Event::PointerMoved(pos),
|
||||
pointer(true),
|
||||
],
|
||||
);
|
||||
draw(1.2, vec![]);
|
||||
let held = draw(1.3, vec![]);
|
||||
let tips = positions(&held, |text| {
|
||||
text.contains("Peer timed out")
|
||||
&& text.contains("at least 35.99 Mbit/s")
|
||||
&& text.contains("Path at start wg direct")
|
||||
});
|
||||
assert_eq!(tips.len(), 1);
|
||||
draw(
|
||||
1.4,
|
||||
vec![
|
||||
touch(egui::TouchPhase::End),
|
||||
pointer(false),
|
||||
egui::Event::PointerGone,
|
||||
],
|
||||
);
|
||||
assert!(s.log.0.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_batch_requires_an_online_capable_exit_and_stops_in_its_own_network() {
|
||||
let mut n = network();
|
||||
let s = Screen::new(360., true);
|
||||
s.frame(&n, vec![]);
|
||||
let start = positions(&s.frame(&n, vec![]), |s| s.contains("Test exits"))[0];
|
||||
n.peers[0].exit_node = false;
|
||||
s.frame(&n, vec![]);
|
||||
s.click(&n, start);
|
||||
assert!(s.log.0.borrow().is_empty());
|
||||
n.peers[0].exit_node = true;
|
||||
s.frame(&n, vec![]);
|
||||
s.click(&n, start);
|
||||
n.speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
|
||||
let batch = s.frame(&n, vec![]);
|
||||
assert!(!positions(&batch, |s| s.contains("0/1")).is_empty());
|
||||
s.click(&n, positions(&batch, |s| s.contains("Stop"))[0]);
|
||||
assert!(matches!(s.log.0.borrow().as_slice(), [
|
||||
Command::StartSpeedTest { network_id, peer: None },
|
||||
Command::StopSpeedTest { network_id: stopped },
|
||||
] if network_id == "network" && stopped == network_id));
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use tsunagi::agent::{DATA_CONNECTING, DATA_DISABLED};
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
pub(super) enum Channel {
|
||||
Ready,
|
||||
Idle,
|
||||
Waiting,
|
||||
Error,
|
||||
Offline,
|
||||
@@ -19,11 +20,9 @@ impl Device<'_> {
|
||||
Some(DATA_DISABLED) => Channel::Disabled,
|
||||
Some(DATA_CONNECTING) => Channel::Waiting,
|
||||
Some(_) => Channel::Error,
|
||||
None if self.overlay.is_some_and(|p| p.is_up())
|
||||
&& !matches!(self.path, None | Some(DataPathReport::None)) =>
|
||||
{
|
||||
Channel::Ready
|
||||
}
|
||||
None if matches!(self.path, None | Some(DataPathReport::None)) => Channel::Waiting,
|
||||
None if self.overlay.is_some_and(|p| p.idle) => Channel::Idle,
|
||||
None if self.overlay.is_some_and(|p| p.is_up()) => Channel::Ready,
|
||||
None => Channel::Waiting,
|
||||
}
|
||||
}
|
||||
@@ -31,6 +30,7 @@ impl Device<'_> {
|
||||
match self.channel() {
|
||||
Channel::Offline => "Offline · peer unreachable",
|
||||
Channel::Ready => "Ready · encrypted data channel available",
|
||||
Channel::Idle => "Idle · online, no recent IP traffic",
|
||||
Channel::Waiting => "Waiting for the encrypted data channel",
|
||||
Channel::Disabled => "Control only · data transports disabled locally",
|
||||
Channel::Error => self.data_error.unwrap_or("Data channel error"),
|
||||
@@ -41,6 +41,7 @@ impl Channel {
|
||||
pub(super) fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ready => "Ready",
|
||||
Self::Idle => "Idle",
|
||||
Self::Waiting => "Waiting",
|
||||
Self::Error => "Error",
|
||||
Self::Offline => "Offline",
|
||||
@@ -52,6 +53,8 @@ impl Channel {
|
||||
match (self, ui.visuals().dark_mode) {
|
||||
(Self::Ready, true) => Color32::from_rgb(100, 210, 136),
|
||||
(Self::Ready, false) => Color32::from_rgb(25, 120, 61),
|
||||
(Self::Idle, true) => Color32::from_rgb(145, 176, 200),
|
||||
(Self::Idle, false) => Color32::from_rgb(64, 99, 125),
|
||||
(Self::Waiting, true) => Color32::from_rgb(244, 190, 85),
|
||||
(Self::Waiting, false) => Color32::from_rgb(150, 94, 8),
|
||||
(Self::Error, true) => Color32::from_rgb(255, 129, 116),
|
||||
@@ -67,6 +70,7 @@ impl Channel {
|
||||
let color = self.color(ui);
|
||||
let glyph = match self {
|
||||
Self::Ready => icon::CHECK_CIRCLE,
|
||||
Self::Idle => icon::MOON,
|
||||
Self::Error => icon::WARNING,
|
||||
Self::Offline => icon::MINUS_CIRCLE,
|
||||
Self::Disabled => icon::PAUSE_CIRCLE,
|
||||
|
||||
@@ -29,6 +29,7 @@ fn keyboard_focus_explains_an_icon_and_the_shared_font_contains_the_status_glyph
|
||||
icon::WARNING,
|
||||
icon::MINUS_CIRCLE,
|
||||
icon::PAUSE_CIRCLE,
|
||||
icon::MOON,
|
||||
icon::SIGN_OUT,
|
||||
icon::FINGERPRINT,
|
||||
icon::HASH,
|
||||
@@ -163,6 +164,7 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
|
||||
("charlie", "error"),
|
||||
("delta", "offline"),
|
||||
("echo", "control only"),
|
||||
("foxtrot", "idle"),
|
||||
] {
|
||||
net.members.push(MemberReport {
|
||||
endpoint_id: id.into(),
|
||||
@@ -189,14 +191,24 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
|
||||
});
|
||||
}
|
||||
}
|
||||
net.overlay = Some(OverlayReport {
|
||||
peers: vec![OverlayPeerReport {
|
||||
endpoint_id: "alpha".into(),
|
||||
handshake_secs_ago: Some(2),
|
||||
tx_bytes: 2048,
|
||||
rx_bytes: 512,
|
||||
let mut overlay_peers = vec![OverlayPeerReport {
|
||||
endpoint_id: "alpha".into(),
|
||||
handshake_secs_ago: Some(2),
|
||||
tx_bytes: 2048,
|
||||
rx_bytes: 512,
|
||||
..Default::default()
|
||||
}];
|
||||
// Only the reachable peer with a healthy path may show Idle. A problem
|
||||
// or an offline observation takes precedence over quiet IP counters.
|
||||
overlay_peers.extend(["bravo", "charlie", "delta", "echo", "foxtrot"].map(|id| {
|
||||
OverlayPeerReport {
|
||||
endpoint_id: id.into(),
|
||||
idle: true,
|
||||
..Default::default()
|
||||
}],
|
||||
}
|
||||
}));
|
||||
net.overlay = Some(OverlayReport {
|
||||
peers: overlay_peers,
|
||||
..Default::default()
|
||||
});
|
||||
let draw = |size, time, events| {
|
||||
@@ -232,6 +244,7 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
|
||||
"bytes (TX / RX)",
|
||||
"2.0 kB / 512 B",
|
||||
"Ready",
|
||||
"Idle",
|
||||
"Waiting",
|
||||
"Error",
|
||||
"Offline",
|
||||
|
||||
@@ -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.4"
|
||||
version = "1.0.6"
|
||||
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.4" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" }
|
||||
iroh.workspace = true
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -32,7 +32,7 @@ use std::collections::{HashMap, VecDeque};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use boringtun::noise::{Tunn, TunnResult};
|
||||
use bytes::Bytes;
|
||||
@@ -41,7 +41,7 @@ use tokio::task::JoinHandle;
|
||||
|
||||
use tsunagi::dataplane::routing::{FlowId, flow::ip_flow};
|
||||
use tsunagi::dataplane::transport::{SharedLink, TransportError};
|
||||
use tsunagi::dataplane::{PacketSink, PluginError};
|
||||
use tsunagi::dataplane::{PacketSink, PluginContext, PluginError};
|
||||
use tsunagi::identity::NetworkId;
|
||||
|
||||
use crate::keys::{WgPublicKey, WgSecretKey};
|
||||
@@ -52,6 +52,11 @@ use crate::keys::{WgPublicKey, WgSecretKey};
|
||||
/// drives handshakes, rekeying and keepalives.
|
||||
const TIMER_INTERVAL: Duration = Duration::from_millis(250);
|
||||
|
||||
/// Start renewing the selected exit at WireGuard's normal rekey age. The
|
||||
/// current key can still carry data for a minute while its successor is agreed.
|
||||
const WARM_REKEY_AFTER: Duration = Duration::from_secs(120);
|
||||
const IDLE_AFTER: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Scratch space for one encapsulate or decapsulate call.
|
||||
const SCRATCH: usize = 4096;
|
||||
|
||||
@@ -60,10 +65,13 @@ const SCRATCH: usize = 4096;
|
||||
struct FlowTunnel {
|
||||
tunn: Tunn,
|
||||
queued: VecDeque<(FlowId, usize)>,
|
||||
/// First usable session or most recent IP payload. Keepalives and later
|
||||
/// handshakes leave this alone, including when the current key expires.
|
||||
last_activity: Option<Instant>,
|
||||
}
|
||||
|
||||
fn is_data(result: &TunnResult<'_>) -> bool {
|
||||
matches!(result, TunnResult::WriteToNetwork(bytes) if bytes.starts_with(&[4, 0, 0, 0]))
|
||||
fn carries_ip(frame: &[u8]) -> bool {
|
||||
frame.len() > crate::plugin::WIREGUARD_OVERHEAD as usize && frame.starts_with(&[4, 0, 0, 0])
|
||||
}
|
||||
|
||||
impl FlowTunnel {
|
||||
@@ -74,7 +82,11 @@ impl FlowTunnel {
|
||||
flow: FlowId,
|
||||
) -> (TunnResult<'a>, FlowId) {
|
||||
let result = self.tunn.encapsulate(packet, scratch);
|
||||
if is_data(&result) {
|
||||
if packet.is_empty() {
|
||||
return (result, 0);
|
||||
}
|
||||
if matches!(&result, TunnResult::WriteToNetwork(out) if carries_ip(out)) {
|
||||
self.last_activity = Some(Instant::now());
|
||||
return (result, flow);
|
||||
}
|
||||
// MAX_QUEUE_DEPTH in boringtun 0.7: the newest packet is dropped at 256.
|
||||
@@ -89,32 +101,83 @@ impl FlowTunnel {
|
||||
packet: &[u8],
|
||||
scratch: &'a mut [u8],
|
||||
) -> (TunnResult<'a>, FlowId, Option<usize>) {
|
||||
// Empty input asks BoringTun to drain its FIFO. Wait for a usable key
|
||||
// so a failed drain cannot reorder IP packets among queued keepalives.
|
||||
if packet.is_empty() && self.tunn.time_since_last_handshake().is_none() {
|
||||
return (TunnResult::Done, 0, None);
|
||||
}
|
||||
let result = self.tunn.decapsulate(None, packet, scratch);
|
||||
let (mut flow, mut plaintext_len) = (0, None);
|
||||
if packet.is_empty() {
|
||||
if is_data(&result) {
|
||||
if let Some((tag, len)) = self.queued.pop_front() {
|
||||
flow = tag;
|
||||
plaintext_len = Some(len);
|
||||
match &result {
|
||||
TunnResult::WriteToNetwork(out) if carries_ip(out) => {
|
||||
if let Some((tag, len)) = self.queued.pop_front() {
|
||||
flow = tag;
|
||||
plaintext_len = Some(len);
|
||||
}
|
||||
}
|
||||
} else if let Some(pending) = self.queued.pop_front() {
|
||||
// Without a session, draining pops the oldest IP packet and
|
||||
// encapsulate queues it again at the back.
|
||||
self.queued.push_back(pending);
|
||||
// An internal keepalive may occupy a slot in the bounded
|
||||
// FIFO. Discard tags for IP packets BoringTun could not queue.
|
||||
TunnResult::Done => self.queued.clear(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if matches!(
|
||||
result,
|
||||
TunnResult::WriteToTunnelV4(..) | TunnResult::WriteToTunnelV6(..)
|
||||
) || plaintext_len.is_some()
|
||||
|| (self.last_activity.is_none() && self.tunn.time_since_last_handshake().is_some())
|
||||
{
|
||||
self.last_activity = Some(Instant::now());
|
||||
}
|
||||
(result, flow, plaintext_len)
|
||||
}
|
||||
|
||||
fn update_timers<'a>(&mut self, scratch: &'a mut [u8]) -> TunnResult<'a> {
|
||||
let result = self.tunn.update_timers(scratch);
|
||||
if matches!(
|
||||
result,
|
||||
TunnResult::Err(boringtun::noise::errors::WireGuardError::ConnectionExpired)
|
||||
) {
|
||||
self.queued.clear();
|
||||
fn health(&self, now: Instant, keep_warm: bool) -> PeerHealth {
|
||||
let since_handshake = self.tunn.time_since_last_handshake();
|
||||
let idle = self.queued.is_empty()
|
||||
&& (!keep_warm || since_handshake.is_some())
|
||||
&& self
|
||||
.last_activity
|
||||
.is_some_and(|at| now.duration_since(at) >= IDLE_AFTER);
|
||||
PeerHealth {
|
||||
since_handshake,
|
||||
idle,
|
||||
}
|
||||
}
|
||||
|
||||
fn update_timers(
|
||||
&mut self,
|
||||
scratch: &mut [u8],
|
||||
refresh_after: Option<Duration>,
|
||||
) -> Option<usize> {
|
||||
match self.tunn.update_timers(scratch) {
|
||||
TunnResult::WriteToNetwork(out) => return Some(out.len()),
|
||||
TunnResult::Err(boringtun::noise::errors::WireGuardError::ConnectionExpired) => {
|
||||
if !self.queued.is_empty() {
|
||||
// BoringTun gave up on pending IP packets. Keep reporting
|
||||
// a waiting tunnel until a new session actually succeeds.
|
||||
self.last_activity = None;
|
||||
self.queued.clear();
|
||||
}
|
||||
}
|
||||
TunnResult::Err(err) => tracing::trace!(?err, "wireguard timer produced an error"),
|
||||
_ => {}
|
||||
}
|
||||
let after = refresh_after?;
|
||||
if self
|
||||
.tunn
|
||||
.time_since_last_handshake()
|
||||
.is_some_and(|age| age < after)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// An in-flight exchange and its retries remain under BoringTun's
|
||||
// timers. Asking without forcing never restarts one.
|
||||
match self.tunn.format_handshake_initiation(scratch, false) {
|
||||
TunnResult::WriteToNetwork(out) => Some(out.len()),
|
||||
_ => None,
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,15 +227,14 @@ pub struct PeerStats {
|
||||
/// Whether a peer's tunnel has completed a handshake.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct PeerHealth {
|
||||
/// Time since the last successful WireGuard handshake.
|
||||
///
|
||||
/// `None` means no handshake has completed yet, so the tunnel is not
|
||||
/// carrying traffic. This is reported as it is, never guessed.
|
||||
/// Age of the last handshake while a usable WireGuard session exists.
|
||||
pub since_handshake: Option<Duration>,
|
||||
/// A previously established tunnel with no recent or queued IP traffic.
|
||||
pub idle: bool,
|
||||
}
|
||||
|
||||
impl PeerHealth {
|
||||
/// Whether the tunnel has ever completed a handshake.
|
||||
/// Whether the tunnel currently has a usable session key.
|
||||
pub fn is_up(&self) -> bool {
|
||||
self.since_handshake.is_some()
|
||||
}
|
||||
@@ -202,17 +264,18 @@ impl std::fmt::Debug for Peer {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Peer {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(mut guard) = self.task.lock()
|
||||
&& let Some(task) = guard.take()
|
||||
impl Peer {
|
||||
fn stop_reader(&self) {
|
||||
if let Some(task) = self
|
||||
.task
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.take()
|
||||
{
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
fn stats(&self) -> PeerStats {
|
||||
PeerStats {
|
||||
counter_epoch: self.counters.epoch,
|
||||
@@ -227,14 +290,12 @@ impl Peer {
|
||||
}
|
||||
}
|
||||
|
||||
fn health(&self) -> PeerHealth {
|
||||
fn health(&self, keep_warm: bool) -> PeerHealth {
|
||||
let guard = match self.tunn.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
PeerHealth {
|
||||
since_handshake: guard.tunn.time_since_last_handshake(),
|
||||
}
|
||||
guard.health(Instant::now(), keep_warm)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,6 +320,7 @@ pub struct PeerSummary {
|
||||
|
||||
struct Inner {
|
||||
network: NetworkId,
|
||||
context: PluginContext,
|
||||
private_key: WgSecretKey,
|
||||
peers: RwLock<HashMap<WgPublicKey, Arc<Peer>>>,
|
||||
/// Where decrypted packets go.
|
||||
@@ -292,11 +354,20 @@ impl WireguardDevice {
|
||||
/// leave through the sink. Which address belongs to whom, and therefore
|
||||
/// where a packet should go, is decided above this.
|
||||
pub fn start(network: NetworkId, private_key: WgSecretKey, sink: Arc<dyn PacketSink>) -> Self {
|
||||
Self::start_with_context(network, private_key, PluginContext::with_sink(sink))
|
||||
}
|
||||
|
||||
pub(crate) fn start_with_context(
|
||||
network: NetworkId,
|
||||
private_key: WgSecretKey,
|
||||
context: PluginContext,
|
||||
) -> Self {
|
||||
let inner = Arc::new(Inner {
|
||||
network,
|
||||
private_key,
|
||||
peers: RwLock::new(HashMap::new()),
|
||||
sink,
|
||||
sink: context.packet_sink(),
|
||||
context,
|
||||
next_index: AtomicU32::new(1),
|
||||
});
|
||||
|
||||
@@ -336,7 +407,7 @@ impl WireguardDevice {
|
||||
let (result, selected_flow) = tunn.encapsulate(packet, &mut scratch, flow);
|
||||
match result {
|
||||
TunnResult::WriteToNetwork(out) => {
|
||||
Some((out.len(), selected_flow, out.starts_with(&[4, 0, 0, 0])))
|
||||
Some((out.len(), selected_flow, carries_ip(out)))
|
||||
}
|
||||
// No session yet, so nothing to send. Counted as dropped
|
||||
// rather than reported: the handshake is in flight and the
|
||||
@@ -394,6 +465,7 @@ impl WireguardDevice {
|
||||
tunn: Mutex::new(FlowTunnel {
|
||||
tunn,
|
||||
queued: VecDeque::new(),
|
||||
last_activity: None,
|
||||
}),
|
||||
link,
|
||||
counters: Arc::new(PeerCounters {
|
||||
@@ -408,7 +480,9 @@ impl WireguardDevice {
|
||||
*guard = Some(task);
|
||||
}
|
||||
|
||||
write_lock(&self.inner.peers).insert(public_key, Arc::clone(&peer));
|
||||
if let Some(old) = write_lock(&self.inner.peers).insert(public_key, Arc::clone(&peer)) {
|
||||
old.stop_reader();
|
||||
}
|
||||
|
||||
// Start the handshake now instead of waiting for the next timer tick,
|
||||
// so the tunnel is usable as soon as the link exists.
|
||||
@@ -418,21 +492,28 @@ impl WireguardDevice {
|
||||
|
||||
/// Removes a peer and stops its tunnel.
|
||||
pub fn remove_peer(&self, public_key: &WgPublicKey) {
|
||||
// Dropping it stops the task and closes the link; there is no route
|
||||
// to withdraw, because routes are not kept here.
|
||||
write_lock(&self.inner.peers).remove(public_key);
|
||||
if let Some(peer) = write_lock(&self.inner.peers).remove(public_key) {
|
||||
peer.stop_reader();
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes every peer whose key is not in `keep`.
|
||||
pub fn retain_peers(&self, keep: &[WgPublicKey]) {
|
||||
let stale: Vec<WgPublicKey> = read_lock(&self.inner.peers)
|
||||
.keys()
|
||||
.filter(|key| !keep.contains(key))
|
||||
.copied()
|
||||
.collect();
|
||||
for key in stale {
|
||||
self.remove_peer(&key);
|
||||
}
|
||||
self.retain_links(|_, key, _| keep.contains(key));
|
||||
}
|
||||
|
||||
pub(crate) fn retain_links(
|
||||
&self,
|
||||
keep: impl Fn(EndpointId, &WgPublicKey, &SharedLink) -> bool,
|
||||
) {
|
||||
write_lock(&self.inner.peers).retain(|key, peer| {
|
||||
let current = keep(peer.endpoint_id, key, &peer.link);
|
||||
if !current {
|
||||
// The reader owns an Arc to the peer while waiting on the link.
|
||||
peer.stop_reader();
|
||||
}
|
||||
current
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether a peer's tunnel exists.
|
||||
@@ -442,6 +523,7 @@ impl WireguardDevice {
|
||||
|
||||
/// A snapshot of every peer.
|
||||
pub fn peers(&self) -> Vec<PeerSummary> {
|
||||
let warm_peer = self.inner.context.warm_peer(self.inner.network);
|
||||
let mut peers: Vec<PeerSummary> = read_lock(&self.inner.peers)
|
||||
.values()
|
||||
.map(|peer| {
|
||||
@@ -453,7 +535,7 @@ impl WireguardDevice {
|
||||
endpoint_id: peer.endpoint_id,
|
||||
public_key: peer.public_key,
|
||||
overlay_address_v4: overlay_v4,
|
||||
health: peer.health(),
|
||||
health: peer.health(warm_peer == Some(peer.endpoint_id)),
|
||||
stats: peer.stats(),
|
||||
path: peer.link.path_description(),
|
||||
max_datagram: peer.link.max_datagram_size(),
|
||||
@@ -470,6 +552,7 @@ impl Drop for WireguardDevice {
|
||||
for task in &self.tasks {
|
||||
task.abort();
|
||||
}
|
||||
self.retain_peers(&[]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -546,14 +629,14 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
|
||||
// any packets that were queued while the session was coming up.
|
||||
let mut input: Option<&[u8]> = Some(&datagram);
|
||||
loop {
|
||||
let outcome = {
|
||||
let (outcome, drain_pending) = {
|
||||
let mut tunn = match peer.tunn.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
let (result, flow, plaintext_len) =
|
||||
tunn.decapsulate(input.unwrap_or(&[]), &mut scratch);
|
||||
match result {
|
||||
let outcome = match result {
|
||||
TunnResult::WriteToNetwork(out) => {
|
||||
Outcome::ToNetwork(out.len(), flow, plaintext_len)
|
||||
}
|
||||
@@ -567,7 +650,8 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
|
||||
tracing::trace!(?err, "wireguard decapsulation failed");
|
||||
Outcome::Failed
|
||||
}
|
||||
}
|
||||
};
|
||||
(outcome, input.is_some() && !tunn.queued.is_empty())
|
||||
};
|
||||
|
||||
match outcome {
|
||||
@@ -595,7 +679,6 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
|
||||
peer.counters
|
||||
.rx_bytes
|
||||
.fetch_add(len as u64, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
Outcome::Failed => {
|
||||
peer.counters
|
||||
@@ -603,8 +686,14 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
Outcome::Done => break,
|
||||
Outcome::Done => {}
|
||||
}
|
||||
// A responder can first confirm its key on an incoming keepalive
|
||||
// or IP packet. Flush waiting application traffic on that path too.
|
||||
if !drain_pending {
|
||||
break;
|
||||
}
|
||||
input = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -620,24 +709,20 @@ enum Outcome {
|
||||
async fn drive_timers(inner: Arc<Inner>) {
|
||||
let mut ticker = tokio::time::interval(TIMER_INTERVAL);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let mut scratch = vec![0u8; SCRATCH];
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
let warm_peer = inner.context.warm_peer(inner.network);
|
||||
let peers: Vec<Arc<Peer>> = read_lock(&inner.peers).values().cloned().collect();
|
||||
for peer in peers {
|
||||
let mut scratch = vec![0u8; SCRATCH];
|
||||
let len = {
|
||||
let mut tunn = match peer.tunn.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
match tunn.update_timers(&mut scratch) {
|
||||
TunnResult::WriteToNetwork(out) => Some(out.len()),
|
||||
TunnResult::Err(err) => {
|
||||
tracing::trace!(?err, "wireguard timer produced an error");
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
let refresh_after =
|
||||
(warm_peer == Some(peer.endpoint_id)).then_some(WARM_REKEY_AFTER);
|
||||
tunn.update_timers(&mut scratch, refresh_after)
|
||||
};
|
||||
if let Some(len) = len {
|
||||
send_to_peer(&peer, &scratch[..len]);
|
||||
@@ -662,6 +747,7 @@ mod flow_tests {
|
||||
None,
|
||||
),
|
||||
queued: VecDeque::new(),
|
||||
last_activity: None,
|
||||
}
|
||||
}
|
||||
fn wire(result: TunnResult<'_>) -> Vec<u8> {
|
||||
@@ -671,6 +757,123 @@ mod flow_tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn establish(a: &mut FlowTunnel, b: &mut FlowTunnel, scratch: &mut [u8]) {
|
||||
let hello = wire(a.tunn.format_handshake_initiation(scratch, false));
|
||||
let response = wire(b.decapsulate(&hello, scratch).0);
|
||||
let confirmation = wire(a.decapsulate(&response, scratch).0);
|
||||
let _ = b.decapsulate(&confirmation, scratch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_due_warm_tunnel_rekeys_and_the_old_key_carries_data_during_the_exchange() {
|
||||
let ak = WgSecretKey::from_bytes(&[1; 32]);
|
||||
let bk = WgSecretKey::from_bytes(&[2; 32]);
|
||||
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
|
||||
let mut scratch = [0u8; SCRATCH];
|
||||
establish(&mut a, &mut b, &mut scratch);
|
||||
assert!(a.update_timers(&mut scratch, None).is_none());
|
||||
assert!(
|
||||
a.update_timers(&mut scratch, Some(WARM_REKEY_AFTER))
|
||||
.is_none()
|
||||
);
|
||||
|
||||
// Make the renewal due now, then withhold its response. BoringTun still
|
||||
// owns both generations of keys and its normal retry timer.
|
||||
let len = a.update_timers(&mut scratch, Some(Duration::ZERO)).unwrap();
|
||||
let hello = scratch[..len].to_vec();
|
||||
assert_eq!(&hello[..4], &[1, 0, 0, 0]);
|
||||
assert!(
|
||||
a.update_timers(&mut scratch, Some(Duration::ZERO))
|
||||
.is_none()
|
||||
);
|
||||
let mut ip = [0u8; 20];
|
||||
ip[0] = 0x45;
|
||||
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
|
||||
for generation in 0..2 {
|
||||
ip[19] = generation;
|
||||
let ciphertext = wire(a.encapsulate(&ip, &mut scratch, 7).0);
|
||||
assert!(matches!(b.decapsulate(&ciphertext, &mut scratch).0,
|
||||
TunnResult::WriteToTunnelV4(bytes, _) if bytes == ip));
|
||||
if generation == 0 {
|
||||
let reply = wire(b.decapsulate(&hello, &mut scratch).0);
|
||||
let confirmation = wire(a.decapsulate(&reply, &mut scratch).0);
|
||||
let _ = b.decapsulate(&confirmation, &mut scratch);
|
||||
}
|
||||
}
|
||||
assert!(a.queued.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_survives_background_handshakes_but_never_hides_pending_ip_or_a_cold_exit() {
|
||||
let ak = WgSecretKey::from_bytes(&[1; 32]);
|
||||
let bk = WgSecretKey::from_bytes(&[2; 32]);
|
||||
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
|
||||
let mut scratch = [0u8; SCRATCH];
|
||||
assert!(!a.health(Instant::now() + IDLE_AFTER, false).idle);
|
||||
establish(&mut a, &mut b, &mut scratch);
|
||||
assert!(!a.health(Instant::now(), false).idle);
|
||||
let activity = (a.last_activity, b.last_activity);
|
||||
let idle_at = Instant::now() + IDLE_AFTER;
|
||||
assert!(a.health(idle_at, true).idle);
|
||||
establish(&mut a, &mut b, &mut scratch);
|
||||
assert_eq!((a.last_activity, b.last_activity), activity);
|
||||
assert!(a.health(idle_at, true).idle);
|
||||
assert!(b.health(idle_at, false).idle);
|
||||
|
||||
let mut ip = [0u8; 20];
|
||||
ip[0] = 0x45;
|
||||
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
|
||||
let ciphertext = wire(a.encapsulate(&ip, &mut scratch, 7).0);
|
||||
let _ = b.decapsulate(&ciphertext, &mut scratch);
|
||||
assert!(!a.health(Instant::now(), false).idle);
|
||||
assert!(!b.health(Instant::now(), false).idle);
|
||||
assert!(a.last_activity > activity.0 && b.last_activity > activity.1);
|
||||
|
||||
// Discard BoringTun's session keys to exercise an idle tunnel with no
|
||||
// usable key and the first IP packet that has to wait for a new one.
|
||||
a.tunn
|
||||
.set_static_private(ak.to_static_secret(), ak.public().into_x25519(), None);
|
||||
let idle_at = Instant::now() + IDLE_AFTER;
|
||||
assert!(a.health(idle_at, false).idle);
|
||||
assert!(!a.health(idle_at, true).idle);
|
||||
let _ = a.encapsulate(&ip, &mut scratch, 7);
|
||||
assert!(!a.health(idle_at, false).idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draining_a_queued_keepalive_preserves_ip_flow_tags_and_eventually_goes_idle() {
|
||||
let ak = WgSecretKey::from_bytes(&[1; 32]);
|
||||
let bk = WgSecretKey::from_bytes(&[2; 32]);
|
||||
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
|
||||
let mut scratch = [0u8; SCRATCH];
|
||||
// This is what BoringTun's persistent keepalive timer does with no key.
|
||||
let hello = wire(a.tunn.encapsulate(&[], &mut scratch));
|
||||
let mut ip = [0u8; 20];
|
||||
ip[0] = 0x45;
|
||||
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
|
||||
for flow in 1..=256 {
|
||||
let _ = a.encapsulate(&ip, &mut scratch, flow);
|
||||
}
|
||||
let reply = wire(b.decapsulate(&hello, &mut scratch).0);
|
||||
let _ = a.decapsulate(&reply, &mut scratch);
|
||||
let (keepalive, flow, bytes) = a.decapsulate(&[], &mut scratch);
|
||||
assert_eq!(
|
||||
wire(keepalive).len(),
|
||||
crate::plugin::WIREGUARD_OVERHEAD as usize
|
||||
);
|
||||
assert_eq!((flow, bytes), (0, None));
|
||||
for expected in 1..=255 {
|
||||
let (data, flow, bytes) = a.decapsulate(&[], &mut scratch);
|
||||
assert!(carries_ip(&wire(data)));
|
||||
assert_eq!((flow, bytes), (expected, Some(ip.len())));
|
||||
}
|
||||
assert!(matches!(
|
||||
a.decapsulate(&[], &mut scratch).0,
|
||||
TunnResult::Done
|
||||
));
|
||||
assert!(a.health(Instant::now() + IDLE_AFTER, false).idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flow_tags_survive_pending_queue_overflow_handshake_and_encryption() {
|
||||
let ak = WgSecretKey::from_bytes(&[1; 32]);
|
||||
@@ -716,7 +919,7 @@ mod flow_tests {
|
||||
TunnResult::Done
|
||||
));
|
||||
let (result, flow) = a.encapsulate(&packet, &mut scratch, 12345);
|
||||
assert!(is_data(&result));
|
||||
assert!(carries_ip(&wire(result)));
|
||||
assert_eq!(flow, 12345);
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,6 @@ use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use tsunagi::BoxFuture;
|
||||
use tsunagi::dataplane::PacketSink;
|
||||
use tsunagi::dataplane::transport::SharedLink;
|
||||
use tsunagi::dataplane::{IpPlugin, PluginCapability, PluginContext, PluginError};
|
||||
use tsunagi::identity::NetworkId;
|
||||
@@ -181,7 +180,6 @@ struct NetworkState {
|
||||
key: WgSecretKey,
|
||||
device: Option<Arc<WireguardDevice>>,
|
||||
announcements: HashMap<EndpointId, ValidatedAnnouncement>,
|
||||
links: HashMap<EndpointId, SharedLink>,
|
||||
/// What the network agreed, pushed in by the agent. Authoritative.
|
||||
allocations: HashMap<EndpointId, Ipv4Addr>,
|
||||
/// The range those allocations came from.
|
||||
@@ -191,17 +189,15 @@ struct NetworkState {
|
||||
#[derive(Debug, Default)]
|
||||
struct Shared {
|
||||
networks: HashMap<NetworkId, NetworkState>,
|
||||
// A channel can arrive before the network key is loaded. Keep the latest
|
||||
// handle here so a full notification queue only delays reconciliation.
|
||||
links: HashMap<(NetworkId, EndpointId), SharedLink>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Command {
|
||||
Prepare(NetworkId),
|
||||
Sync(NetworkId),
|
||||
Link {
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
link: SharedLink,
|
||||
},
|
||||
Teardown(NetworkId),
|
||||
Stop(oneshot::Sender<()>),
|
||||
}
|
||||
@@ -213,8 +209,6 @@ struct Worker {
|
||||
store: WgKeyStore,
|
||||
shared: Mutex<Shared>,
|
||||
context: OnceLock<PluginContext>,
|
||||
/// Where decrypted packets go, once the agent has attached one.
|
||||
sink: OnceLock<Arc<dyn PacketSink>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Worker {
|
||||
@@ -315,7 +309,6 @@ impl WireguardPlugin {
|
||||
store,
|
||||
shared: Mutex::new(Shared::default()),
|
||||
context: OnceLock::new(),
|
||||
sink: OnceLock::new(),
|
||||
});
|
||||
|
||||
let (commands, receiver) = mpsc::channel(64);
|
||||
@@ -352,7 +345,7 @@ impl WireguardPlugin {
|
||||
endpoint_id: *endpoint_id,
|
||||
public_key: announcement.public_key,
|
||||
overlay_address_v4: state.allocations.get(endpoint_id).copied(),
|
||||
has_link: state.links.contains_key(endpoint_id),
|
||||
has_link: shared.links.contains_key(&(network, *endpoint_id)),
|
||||
tunnel: tunnels.get(&announcement.public_key).cloned(),
|
||||
})
|
||||
.collect();
|
||||
@@ -444,7 +437,6 @@ impl Worker {
|
||||
key,
|
||||
device: None,
|
||||
announcements: HashMap::new(),
|
||||
links: HashMap::new(),
|
||||
allocations: HashMap::new(),
|
||||
ipv4_range: None,
|
||||
});
|
||||
@@ -473,13 +465,12 @@ impl Worker {
|
||||
}
|
||||
};
|
||||
|
||||
let sink = match self.sink.get() {
|
||||
Some(sink) => Arc::clone(sink),
|
||||
// Not attached to an agent: the protocol still runs, and its
|
||||
// packets have nowhere to go.
|
||||
None => Arc::new(tsunagi::dataplane::DiscardPackets) as Arc<dyn PacketSink>,
|
||||
};
|
||||
let device = Arc::new(WireguardDevice::start(network, key, sink));
|
||||
let context = self
|
||||
.context
|
||||
.get()
|
||||
.cloned()
|
||||
.unwrap_or_else(PluginContext::detached);
|
||||
let device = Arc::new(WireguardDevice::start_with_context(network, key, context));
|
||||
|
||||
let mut shared = self.lock_shared();
|
||||
if let Some(state) = shared.networks.get_mut(&network) {
|
||||
@@ -493,25 +484,34 @@ impl Worker {
|
||||
/// A peer gets a tunnel once both halves have arrived: its announcement,
|
||||
/// which says who it is, and a link, which says packets can reach it.
|
||||
fn sync(&self, network: NetworkId) {
|
||||
let mut shared = self.lock_shared();
|
||||
let Some(state) = shared.networks.get_mut(&network) else {
|
||||
let shared = self.lock_shared();
|
||||
let Some(state) = shared.networks.get(&network) else {
|
||||
return;
|
||||
};
|
||||
let Some(device) = state.device.clone() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let allocations = state.allocations.clone();
|
||||
let mut wanted: Vec<WgPublicKey> = Vec::new();
|
||||
// Carrier changes keep the same logical link. A new control session
|
||||
// gets a different link even when the peer advertises the same WG key.
|
||||
device.retain_links(|peer, key, installed| {
|
||||
state
|
||||
.announcements
|
||||
.get(&peer)
|
||||
.is_some_and(|a| a.public_key == *key)
|
||||
&& shared
|
||||
.links
|
||||
.get(&(network, peer))
|
||||
.is_some_and(|current| Arc::ptr_eq(installed, current) && !current.is_closed())
|
||||
});
|
||||
let mut too_small: Vec<(usize, usize)> = Vec::new();
|
||||
for (endpoint_id, announcement) in &state.announcements {
|
||||
let Some(link) = state.links.get(endpoint_id) else {
|
||||
let Some(link) = shared.links.get(&(network, *endpoint_id)) else {
|
||||
continue;
|
||||
};
|
||||
if link.is_closed() {
|
||||
continue;
|
||||
}
|
||||
wanted.push(announcement.public_key);
|
||||
if device.has_peer(&announcement.public_key) {
|
||||
continue;
|
||||
}
|
||||
@@ -528,7 +528,7 @@ impl Worker {
|
||||
// The address comes from the agreed signed state, not from
|
||||
// anything this peer said and not from a derivation: that is what
|
||||
// makes it survive the peer being away.
|
||||
let peer_v4 = allocations.get(endpoint_id).copied();
|
||||
let peer_v4 = state.allocations.get(endpoint_id).copied();
|
||||
|
||||
if let Err(err) = device.add_peer(
|
||||
*endpoint_id,
|
||||
@@ -540,8 +540,6 @@ impl Worker {
|
||||
tracing::debug!(%err, "cannot start a WireGuard tunnel");
|
||||
}
|
||||
}
|
||||
device.retain_peers(&wanted);
|
||||
|
||||
drop(shared);
|
||||
|
||||
for (available, needed) in too_small {
|
||||
@@ -602,21 +600,13 @@ async fn run(worker: Arc<Worker>, mut commands: mpsc::Receiver<Command>) {
|
||||
Command::Sync(network) => {
|
||||
pending.insert(network);
|
||||
}
|
||||
Command::Link { network, peer, link } => {
|
||||
{
|
||||
let mut shared = worker.lock_shared();
|
||||
if let Some(state) = shared.networks.get_mut(&network) {
|
||||
state.links.insert(peer, link);
|
||||
}
|
||||
}
|
||||
pending.insert(network);
|
||||
}
|
||||
Command::Teardown(network) => {
|
||||
pending.remove(&network);
|
||||
worker.teardown(network).await;
|
||||
continue;
|
||||
}
|
||||
Command::Stop(reply) => {
|
||||
worker.lock_shared().links.clear();
|
||||
for network in worker.known_networks() {
|
||||
worker.teardown(network).await;
|
||||
}
|
||||
@@ -668,7 +658,6 @@ impl IpPlugin for WireguardPlugin {
|
||||
if let Some(local) = context.local_endpoint_id() {
|
||||
let _ = self.worker.local_id.set(local);
|
||||
}
|
||||
let _ = self.worker.sink.set(context.packet_sink());
|
||||
let _ = self.worker.context.set(context);
|
||||
}
|
||||
|
||||
@@ -771,23 +760,23 @@ impl IpPlugin for WireguardPlugin {
|
||||
}
|
||||
|
||||
fn on_peer_link(&self, network: NetworkId, peer: EndpointId, link: SharedLink) {
|
||||
self.nudge(Command::Link {
|
||||
network,
|
||||
peer,
|
||||
link,
|
||||
});
|
||||
self.worker
|
||||
.lock_shared()
|
||||
.links
|
||||
.insert((network, peer), link);
|
||||
self.nudge(Command::Sync(network));
|
||||
}
|
||||
|
||||
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) {
|
||||
let removed = {
|
||||
let mut shared = self.worker.lock_shared();
|
||||
match shared.networks.get_mut(&network) {
|
||||
Some(state) => {
|
||||
let had_link = state.links.remove(&peer).is_some();
|
||||
state.announcements.remove(&peer).is_some() || had_link
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
let had_link = shared.links.remove(&(network, peer)).is_some();
|
||||
shared
|
||||
.networks
|
||||
.get_mut(&network)
|
||||
.and_then(|state| state.announcements.remove(&peer))
|
||||
.is_some()
|
||||
|| had_link
|
||||
};
|
||||
if removed {
|
||||
self.nudge(Command::Sync(network));
|
||||
@@ -795,6 +784,10 @@ impl IpPlugin for WireguardPlugin {
|
||||
}
|
||||
|
||||
fn on_network_deactivated(&self, network: NetworkId) {
|
||||
self.worker
|
||||
.lock_shared()
|
||||
.links
|
||||
.retain(|(net, _), _| *net != network);
|
||||
self.nudge(Command::Teardown(network));
|
||||
}
|
||||
|
||||
@@ -846,3 +839,58 @@ impl Drop for WireguardPlugin {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use tsunagi::dataplane::relay::RelayHub;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_burst_of_notifications_keeps_the_latest_logical_link() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let plugin = WireguardPlugin::open(WireguardConfig::new(dir.path()))
|
||||
.await
|
||||
.unwrap();
|
||||
let id = NetworkId::from_bytes([9; 32]);
|
||||
let local = iroh::SecretKey::from_bytes(&[1; 32]).public();
|
||||
let peer = iroh::SecretKey::from_bytes(&[2; 32]).public();
|
||||
let hub = RelayHub::new(id, local);
|
||||
let cap = PluginCapability {
|
||||
protocol: WIREGUARD_PROTOCOL.to_string(),
|
||||
version: crate::ANNOUNCEMENT_VERSION,
|
||||
enabled: true,
|
||||
data: WgAnnouncement::new(id, &WgSecretKey::generate().public())
|
||||
.encode()
|
||||
.unwrap(),
|
||||
};
|
||||
// No yield: the worker cannot drain notifications or reconcile between callbacks.
|
||||
for _ in 0..plugin.commands.max_capacity() {
|
||||
plugin.on_network_activated(id);
|
||||
}
|
||||
let first = hub.link(peer, WIREGUARD_PROTOCOL);
|
||||
plugin.on_peer_link(id, peer, first.clone());
|
||||
plugin.worker.prepare(id).await.unwrap();
|
||||
plugin.on_peer_capability(id, peer, &cap).unwrap();
|
||||
let epoch = || {
|
||||
plugin.worker.sync(id);
|
||||
plugin.overview(id).unwrap().peers[0]
|
||||
.tunnel
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.stats
|
||||
.counter_epoch
|
||||
};
|
||||
let original = epoch();
|
||||
plugin.on_peer_link(id, peer, first);
|
||||
assert_eq!(epoch(), original, "the same logical link keeps its session");
|
||||
|
||||
plugin.on_peer_gone(id, peer);
|
||||
hub.remove_peer(peer);
|
||||
plugin.on_peer_capability(id, peer, &cap).unwrap();
|
||||
plugin.on_peer_link(id, peer, hub.link(peer, WIREGUARD_PROTOCOL));
|
||||
assert_ne!(epoch(), original, "reconnect within one reconcile window");
|
||||
hub.close();
|
||||
plugin.shutdown().await;
|
||||
}
|
||||
}
|
||||
@@ -216,6 +216,65 @@ impl<'a> ExitNetwork<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_exit_keeps_serving_its_client_while_switching_its_own_upstream() {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let (name, secret) = network("independent-exits");
|
||||
let a = Node::spawn(&discovery, "client-a").await;
|
||||
let b = Node::spawn(&discovery, "gateway-b").await;
|
||||
let c = Node::spawn(&discovery, "upstream-c").await;
|
||||
let net = b.agent.join_network(&name, &secret).await.unwrap();
|
||||
b.overlay(net).await;
|
||||
b.agent.set_exit_offer(net, true).await.unwrap();
|
||||
a.agent.join_network(&name, &secret).await.unwrap();
|
||||
c.agent.join_network(&name, &secret).await.unwrap();
|
||||
c.agent.set_exit_offer(net, true).await.unwrap();
|
||||
wait_until("both exit offers have reached their clients", || async {
|
||||
let offers = |status: NetworkStatus, id| {
|
||||
status
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.endpoint_id == id && p.exit_node)
|
||||
};
|
||||
(offers(a.status(net).await, b.id()) && offers(b.status(net).await, c.id())).then_some(())
|
||||
})
|
||||
.await;
|
||||
tokio::join!(
|
||||
a.wait_for_tunnels(net, 2),
|
||||
b.wait_for_tunnels(net, 2),
|
||||
c.wait_for_tunnels(net, 2)
|
||||
);
|
||||
a.agent.set_exit_via(net, Some(b.id())).await.unwrap();
|
||||
let (at, bt, ct) = (a.tun().await, b.tun().await, c.tun().await);
|
||||
let (aa, ba) = (a.overlay(net).await, b.overlay(net).await);
|
||||
for (epoch, upstream) in [false, true, false, true].into_iter().enumerate() {
|
||||
b.agent
|
||||
.set_exit_via(net, upstream.then(|| c.id()))
|
||||
.await
|
||||
.unwrap();
|
||||
// A retains the same pair of endpoints before, during and after B uses C.
|
||||
let request = ipv4_packet(aa, INTERNET, &[epoch as u8]);
|
||||
at.push_from_os(request.clone());
|
||||
assert_eq!(next(&bt).await, request);
|
||||
if upstream {
|
||||
// Even a misrouted host packet from A cannot be carried a second time.
|
||||
bt.push_from_os(request);
|
||||
let own = ipv4_packet(ba, INTERNET, b"B to the same server");
|
||||
bt.push_from_os(own.clone());
|
||||
assert_eq!(next(&ct).await, own);
|
||||
let reply = ipv4_packet(INTERNET, ba, b"reply to B");
|
||||
ct.push_from_os(reply.clone());
|
||||
assert_eq!(next(&bt).await, reply);
|
||||
}
|
||||
let reply = ipv4_packet(INTERNET, aa, &[epoch as u8]);
|
||||
bt.push_from_os(reply.clone());
|
||||
assert_eq!(next(&at).await, reply);
|
||||
assert_eq!(a.status(net).await.exit_via, Some(b.id()));
|
||||
assert!(b.status(net).await.exit_offer);
|
||||
}
|
||||
let _ = tokio::join!(a.shutdown(), b.shutdown(), c.shutdown());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
@@ -310,22 +369,106 @@ async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() {
|
||||
live.peer.agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
|
||||
async fn shared_nodes() -> (Node, Node) {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let client = Node::open(TempDir::new().unwrap(), &discovery, "client", None).await;
|
||||
let dir = TempDir::new().unwrap();
|
||||
let config = tsunagi::testing::config_with(dir.path(), &discovery);
|
||||
let peer = Node::start(dir, "shared", config).await;
|
||||
(client, peer)
|
||||
}
|
||||
|
||||
async fn shared_networks<'a>(client: &Node, peer: &'a Node) -> [ExitNetwork<'a>; 2] {
|
||||
// Fixed credentials keep the two automatically derived /24s distinct.
|
||||
let mut meshes = Vec::new();
|
||||
for (name, secret) in [("shared-left", [1; 32]), ("shared-right", [2; 32])] {
|
||||
let join = |name, secret| {
|
||||
let credentials = (
|
||||
NetworkName::new(name).unwrap(),
|
||||
NetworkSecret::from_bytes(secret).unwrap(),
|
||||
);
|
||||
meshes.push(ExitNetwork::join(&client, &peer, credentials).await);
|
||||
}
|
||||
ExitNetwork::join(client, peer, credentials)
|
||||
};
|
||||
[
|
||||
join("shared-left", [1; 32]).await,
|
||||
join("shared-right", [2; 32]).await,
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "observes a full 180-second WireGuard key lifetime on real clocks"]
|
||||
async fn only_the_selected_exit_stays_keyed_through_idle_expiry() {
|
||||
let (client, peer) = shared_nodes().await;
|
||||
let [chosen, other] = shared_networks(&client, &peer).await;
|
||||
client
|
||||
.agent
|
||||
.set_exit_via(chosen.id, Some(peer.id()))
|
||||
.await
|
||||
.unwrap();
|
||||
let tunnel = |network| {
|
||||
client
|
||||
.plugin
|
||||
.overview(network)
|
||||
.unwrap()
|
||||
.peers
|
||||
.into_iter()
|
||||
.find(|p| p.endpoint_id == peer.id())
|
||||
.unwrap()
|
||||
.tunnel
|
||||
.unwrap()
|
||||
};
|
||||
let epoch = tunnel(chosen.id).stats.counter_epoch;
|
||||
let mut old_key_seen = false;
|
||||
tokio::time::timeout(Duration::from_secs(210), async {
|
||||
let mut poll = tokio::time::interval(Duration::from_millis(500));
|
||||
loop {
|
||||
poll.tick().await;
|
||||
let warm = tunnel(chosen.id);
|
||||
let cold = tunnel(other.id);
|
||||
assert_eq!(warm.stats.counter_epoch, epoch);
|
||||
let warm_age = warm
|
||||
.health
|
||||
.since_handshake
|
||||
.expect("usable exit key throughout idle");
|
||||
assert_eq!((warm.stats.tx_bytes, warm.stats.rx_bytes), (0, 0));
|
||||
assert_eq!((cold.stats.tx_bytes, cold.stats.rx_bytes), (0, 0));
|
||||
if cold
|
||||
.health
|
||||
.since_handshake
|
||||
.is_some_and(|age| age >= Duration::from_secs(150))
|
||||
{
|
||||
old_key_seen = true;
|
||||
}
|
||||
if old_key_seen && !cold.health.is_up() {
|
||||
assert!(
|
||||
warm_age < Duration::from_secs(90),
|
||||
"exit key renewed before expiry"
|
||||
);
|
||||
assert!(warm.health.idle && cold.health.idle);
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("unselected peer's unused session expired");
|
||||
|
||||
let packet = ipv4_packet(chosen.client_addr, INTERNET, b"first IP packet after idle");
|
||||
client.tun().await.push_from_os(packet.clone());
|
||||
assert_eq!(next(&chosen.peer_tun).await, packet);
|
||||
assert!(!tunnel(chosen.id).health.idle);
|
||||
client
|
||||
.agent
|
||||
.set_exit_via(other.id, Some(peer.id()))
|
||||
.await
|
||||
.unwrap();
|
||||
client.wait_for_tunnels(other.id, 1).await;
|
||||
assert!(tunnel(other.id).health.idle, "warming sends no IP payload");
|
||||
client.agent.shutdown().await;
|
||||
peer.agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
|
||||
let (client, peer) = shared_nodes().await;
|
||||
let meshes = shared_networks(&client, &peer).await;
|
||||
let tun = client.tun().await;
|
||||
for (chosen, other) in [(&meshes[0], &meshes[1]), (&meshes[1], &meshes[0])] {
|
||||
client
|
||||
@@ -515,3 +658,76 @@ async fn an_agent_that_is_not_offering_drops_a_members_internet_packets() {
|
||||
client.agent.shutdown().await;
|
||||
server.agent.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exit_speed_batch_runs_one_peer_at_a_time_and_stop_preserves_finished_results() {
|
||||
use tsunagi::ipc::SpeedPhase;
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let (name, secret) = network("exit-speed-batch");
|
||||
let a = Node::spawn(&discovery, "speed-client").await;
|
||||
let b = Node::spawn(&discovery, "exit-one").await;
|
||||
let c = Node::spawn(&discovery, "exit-two").await;
|
||||
let net = a.agent.join_network(&name, &secret).await.unwrap();
|
||||
for node in [&b, &c] {
|
||||
node.agent.join_network(&name, &secret).await.unwrap();
|
||||
node.agent.set_exit_offer(net, true).await.unwrap();
|
||||
}
|
||||
wait_until("two capable exit nodes", || async {
|
||||
let status = a.status(net).await;
|
||||
(status.peers.iter().filter(|p| p.exit_node).count() == 2
|
||||
&& status.speed.capable.len() == 2)
|
||||
.then_some(())
|
||||
})
|
||||
.await;
|
||||
a.wait_for_tunnels(net, 2).await;
|
||||
a.agent.start_speed_test(net, None, true).await.unwrap();
|
||||
let first = wait_until(
|
||||
"one exit is being tested and the next is queued",
|
||||
|| async {
|
||||
let speed = a.status(net).await.speed;
|
||||
assert!(
|
||||
speed
|
||||
.peers
|
||||
.values()
|
||||
.filter(|p| matches!(
|
||||
p.phase,
|
||||
SpeedPhase::Preparing | SpeedPhase::Download | SpeedPhase::Upload
|
||||
))
|
||||
.count()
|
||||
<= 1
|
||||
);
|
||||
let batch = speed.batch?;
|
||||
let (id, _) = speed
|
||||
.peers
|
||||
.iter()
|
||||
.find(|(_, p)| matches!(p.phase, SpeedPhase::Download | SpeedPhase::Upload))?;
|
||||
(batch.total == 2
|
||||
&& batch.done == 0
|
||||
&& speed.peers.values().any(|p| p.phase == SpeedPhase::Queued))
|
||||
.then(|| id.clone())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
wait_until(
|
||||
"the first result remains visible while the next exit is tested",
|
||||
|| async {
|
||||
let speed = a.status(net).await.speed;
|
||||
(speed.batch?.done == 1 && speed.peers.get(&first)?.phase == SpeedPhase::Done)
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
a.agent.stop_speed_test(net);
|
||||
let speed = a.status(net).await.speed;
|
||||
assert!(speed.batch.is_none());
|
||||
assert_eq!(speed.peers[&first].phase, SpeedPhase::Done);
|
||||
assert!(
|
||||
speed
|
||||
.peers
|
||||
.values()
|
||||
.any(|r| r.phase == SpeedPhase::Cancelled)
|
||||
);
|
||||
a.agent.shutdown().await;
|
||||
b.agent.shutdown().await;
|
||||
c.agent.shutdown().await;
|
||||
}
|
||||
@@ -1022,6 +1022,73 @@ async fn a_mesh_of_three_establishes_every_tunnel() {
|
||||
c.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_quick_reconnect_with_the_same_key_restores_packet_delivery() {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let (name, secret) = network("wg-quick-return");
|
||||
// Let the disconnect and the next link arrive in the same reconcile window.
|
||||
let a = WgAgent::spawn_with(&discovery, "ta", |config| {
|
||||
config.with_reconcile(Duration::from_secs(2), Duration::from_secs(60))
|
||||
})
|
||||
.await;
|
||||
let b = WgAgent::spawn(&discovery, "tb").await;
|
||||
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||
b.agent.join_network(&name, &secret).await.unwrap();
|
||||
a.wait_for_tunnels(id, 1).await;
|
||||
b.wait_for_tunnels(id, 1).await;
|
||||
let before = a.plugin.overview(id).unwrap().peers.remove(0);
|
||||
let epoch = before.tunnel.unwrap().stats.counter_epoch;
|
||||
|
||||
let mut events = a.agent.subscribe();
|
||||
b.agent.deactivate_network(id).await.unwrap();
|
||||
wait_event(&mut events, |event| match event {
|
||||
Event::PeerDisconnected { network, peer, .. }
|
||||
if *network == id && *peer == b.endpoint_id() =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
b.agent.activate_network(id).await.unwrap();
|
||||
wait_until(
|
||||
"the same WG key handshakes on the replacement channel",
|
||||
|| async {
|
||||
let overview = a.plugin.overview(id)?;
|
||||
let peer = overview
|
||||
.peers
|
||||
.iter()
|
||||
.find(|p| p.endpoint_id == b.endpoint_id())?;
|
||||
let tunnel = peer.tunnel.as_ref()?;
|
||||
(peer.public_key == before.public_key
|
||||
&& tunnel.stats.counter_epoch != epoch
|
||||
&& peer.is_up())
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
b.wait_for_tunnels(id, 1).await;
|
||||
|
||||
for (sender, receiver) in [(&a, &b), (&b, &a)] {
|
||||
let packet = ipv4_packet(
|
||||
sender.overlay(id).await,
|
||||
receiver.overlay(id).await,
|
||||
b"after reconnect",
|
||||
);
|
||||
sender.tun(id).await.push_from_os(packet.clone());
|
||||
let received = tokio::time::timeout(
|
||||
tsunagi::testing::DEADLINE,
|
||||
receiver.tun(id).await.pop_to_os(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(received, packet);
|
||||
}
|
||||
a.shutdown().await;
|
||||
b.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_departing_peer_loses_its_tunnel() {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
@@ -2051,3 +2118,105 @@ async fn vip_udp_reaches_another_backend_after_the_selected_agent_stops() {
|
||||
a.shutdown().await;
|
||||
alive.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn peer_speed_measures_both_wireguard_directions_and_can_be_repeated() {
|
||||
use tsunagi::ipc::SpeedPhase;
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let (name, secret) = network("wg-speed");
|
||||
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 remote = b.agent.endpoint_id();
|
||||
let key = remote.to_string();
|
||||
assert!(
|
||||
a.agent.start_speed_test(net, None, true).await.is_err(),
|
||||
"a non-exit peer is skipped by the batch"
|
||||
);
|
||||
let legacy = tsunagi::testing::TestAgent::spawn(&discovery)
|
||||
.await
|
||||
.unwrap();
|
||||
legacy.agent.join_network(&name, &secret).await.unwrap();
|
||||
wait_for_peers(&a.agent, net, 2).await;
|
||||
let status = a.agent.network_status(net).await.unwrap();
|
||||
assert!(
|
||||
!status
|
||||
.speed
|
||||
.capable
|
||||
.contains(&legacy.agent.endpoint_id().to_string())
|
||||
);
|
||||
assert!(
|
||||
a.agent
|
||||
.start_speed_test(net, Some(legacy.agent.endpoint_id()), true)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
b.agent.set_speed_test_metered(true);
|
||||
a.agent
|
||||
.start_speed_test(net, Some(remote), false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
a.agent
|
||||
.start_speed_test(net, Some(remote), false)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
wait_until("live receiver feedback during a peer test", || async {
|
||||
let s = a.agent.network_status(net).await.ok()?.speed;
|
||||
let p = s.peers.get(&key)?;
|
||||
(matches!(p.phase, SpeedPhase::Download | SpeedPhase::Upload) && p.bytes > 0).then_some(())
|
||||
})
|
||||
.await;
|
||||
let result = wait_until("both data directions have finished", || async {
|
||||
let s = a.agent.network_status(net).await.ok()?.speed;
|
||||
let p = s.peers.get(&key)?;
|
||||
(p.phase == SpeedPhase::Done).then(|| p.clone())
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
result.down.is_some_and(|r| r.bps > 0) && result.up.is_some_and(|r| r.bps > 0),
|
||||
"{result:?}"
|
||||
);
|
||||
assert!(
|
||||
result.bytes > 0 && result.bytes <= 16 * 1024 * 1024,
|
||||
"the responder's metered limit applies"
|
||||
);
|
||||
assert!(result.path.is_some());
|
||||
a.agent
|
||||
.start_speed_test(net, Some(remote), true)
|
||||
.await
|
||||
.unwrap();
|
||||
wait_until("the repeated download has a provisional rate", || async {
|
||||
let s = a.agent.network_status(net).await.ok()?.speed;
|
||||
let p = s.peers.get(&key)?;
|
||||
(p.phase == SpeedPhase::Download && p.down.is_some()).then_some(())
|
||||
})
|
||||
.await;
|
||||
a.agent.stop_speed_test(net);
|
||||
wait_until("a repeated test can be stopped", || async {
|
||||
let s = a.agent.network_status(net).await.ok()?.speed;
|
||||
let p = s.peers.get(&key)?;
|
||||
(p.phase == SpeedPhase::Cancelled && p.down.is_none() && p.up.is_none()).then_some(())
|
||||
})
|
||||
.await;
|
||||
// No diagnostic was delivered as application traffic on either host.
|
||||
let tun = b.tun(net).await;
|
||||
let src = a.overlay(net).await;
|
||||
let dst = b.overlay(net).await;
|
||||
let ordinary = ipv4_packet(src, dst, b"ordinary overlay application");
|
||||
a.tun(net).await.push_from_os(ordinary.clone());
|
||||
assert_eq!(
|
||||
tokio::time::timeout(tsunagi::testing::DEADLINE, tun.pop_to_os())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
ordinary
|
||||
);
|
||||
legacy.stop().await;
|
||||
a.shutdown().await;
|
||||
b.shutdown().await;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "1.0.4"
|
||||
version = "1.0.6"
|
||||
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.4" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" }
|
||||
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.4"
|
||||
version = "1.0.6"
|
||||
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.4" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4", features = ["tun-device", "dns-publish"] }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" }
|
||||
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" }
|
||||
iroh.workspace = true
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -1760,6 +1760,38 @@ impl tsunagi::ipc::ReportSource for AgentControl {
|
||||
})
|
||||
}
|
||||
|
||||
fn start_speed_test(
|
||||
&self,
|
||||
network_id: String,
|
||||
peer: Option<String>,
|
||||
metered: bool,
|
||||
) -> tsunagi::BoxFuture<'_, Result<(), String>> {
|
||||
Box::pin(async move {
|
||||
let network = network_id
|
||||
.parse()
|
||||
.map_err(|err| format!("invalid network id: {err}"))?;
|
||||
let peer = peer
|
||||
.as_deref()
|
||||
.map(str::parse::<EndpointId>)
|
||||
.transpose()
|
||||
.map_err(|err| format!("invalid endpoint id: {err}"))?;
|
||||
self.agent
|
||||
.start_speed_test(network, peer, metered)
|
||||
.await
|
||||
.map_err(|err| err.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
fn stop_speed_test(&self, network_id: String) -> tsunagi::BoxFuture<'_, Result<(), String>> {
|
||||
Box::pin(async move {
|
||||
let network = network_id
|
||||
.parse()
|
||||
.map_err(|err| format!("invalid network id: {err}"))?;
|
||||
self.agent.stop_speed_test(network);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn set_exit_node(
|
||||
&self,
|
||||
network_id: String,
|
||||
@@ -3884,12 +3916,17 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
|
||||
),
|
||||
Some(DataPathReport::None) | None => ("connected · no data path yet".to_string(), false),
|
||||
};
|
||||
let idle = data_path_good && row.data_error.is_none() && row.tunnel.is_some_and(|t| t.idle);
|
||||
let show_counters = tunnel_up || idle;
|
||||
|
||||
let mut detail = String::new();
|
||||
if let Some(v4) = row.overlay_address_v4 {
|
||||
detail.push_str(&format!("{v4:<15} "));
|
||||
}
|
||||
detail.push_str(&path);
|
||||
if idle {
|
||||
detail.push_str(" · idle");
|
||||
}
|
||||
if let Some(rtt) = row.data_rtt_ms {
|
||||
detail.push_str(&format!(" data RTT {rtt}ms"));
|
||||
}
|
||||
@@ -3906,7 +3943,7 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
|
||||
}
|
||||
detail.extend(taken);
|
||||
|
||||
let health = if !data_path_good || row.data_error.is_some() || (has_overlay && !tunnel_up) {
|
||||
let health = if !data_path_good || row.data_error.is_some() || (has_overlay && !show_counters) {
|
||||
Health::Degraded
|
||||
} else {
|
||||
Health::Good
|
||||
@@ -3916,12 +3953,12 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
|
||||
if let Some(reason) = row.data_error {
|
||||
out = out.with_note(reason.to_owned());
|
||||
}
|
||||
if !tunnel_up && let Some(path) = row.data_transport_detail {
|
||||
if !show_counters && let Some(path) = row.data_transport_detail {
|
||||
out = out.with_note(path.to_owned());
|
||||
}
|
||||
if let Some(tunnel) = row.tunnel {
|
||||
out = out.with_note(match tunnel.handshake_secs_ago {
|
||||
Some(_) => format!(
|
||||
out = out.with_note(if show_counters {
|
||||
format!(
|
||||
"tx {} rx {} · IP bytes ↑{} ↓{}{} · {}",
|
||||
tunnel.tx_packets,
|
||||
tunnel.rx_packets,
|
||||
@@ -3933,8 +3970,9 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
|
||||
String::new()
|
||||
},
|
||||
row.data_transport_detail.unwrap_or(&tunnel.path)
|
||||
),
|
||||
None => "encrypted data channel is not ready yet".into(),
|
||||
)
|
||||
} else {
|
||||
"encrypted data channel is not ready yet".into()
|
||||
});
|
||||
}
|
||||
out
|
||||
@@ -5037,12 +5075,16 @@ fn log_event(event: &Event) {
|
||||
}
|
||||
Event::PeerDisconnected {
|
||||
network,
|
||||
network_name,
|
||||
peer,
|
||||
hostname,
|
||||
reason,
|
||||
} => {
|
||||
tracing::info!(
|
||||
network = %network.fmt_short(),
|
||||
network_name = network_name.as_str(),
|
||||
peer = %peer.fmt_short(),
|
||||
hostname = hostname.as_deref().map(tracing::field::debug),
|
||||
"Peer disconnected: {reason}"
|
||||
);
|
||||
}
|
||||
@@ -5192,6 +5234,7 @@ mod status_tests {
|
||||
/// The situation that prompted this: one peer left and came back.
|
||||
fn network_after_a_peer_returned() -> NetworkReport {
|
||||
NetworkReport {
|
||||
speed: Default::default(),
|
||||
vips: Vec::new(),
|
||||
protocols: vec!["wg-quic".into()],
|
||||
auto_start: true,
|
||||
@@ -5773,6 +5816,36 @@ mod status_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_peer_keeps_its_counters_and_a_missing_route_is_still_degraded() {
|
||||
let mut network = network_after_a_peer_returned();
|
||||
let mut quiet = tunnel(ONLINE, None);
|
||||
quiet.idle = true;
|
||||
network.overlay = Some(overlay(vec![quiet]));
|
||||
for (path, health) in [
|
||||
(
|
||||
tsunagi::ipc::DataPathReport::Direct {
|
||||
transport: "wg".into(),
|
||||
},
|
||||
Health::Good,
|
||||
),
|
||||
(tsunagi::ipc::DataPathReport::None, Health::Degraded),
|
||||
] {
|
||||
network.peers[0].path = path.clone();
|
||||
network.members[1].path = path;
|
||||
let mut report = report::Report::new();
|
||||
report.push(network_section(&network, OWN, false));
|
||||
let text = report.render(false);
|
||||
assert_eq!(report.worst(), health, "{text}");
|
||||
if health == Health::Good {
|
||||
assert!(
|
||||
text.contains("idle") && text.contains("tx 32 rx 887"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_failures_with_nobody_connected_point_at_the_secret() {
|
||||
// The classic symptom of one member being given a different secret.
|
||||
|
||||
+25
-11
@@ -4,6 +4,11 @@ A member can offer itself as an **exit node** in a network. Other members can
|
||||
then send their default IPv4 internet traffic through it. Linux, macOS and
|
||||
Windows can offer or use an exit node. Android can use one.
|
||||
|
||||
An exit serves members through its own internet connection even while its local
|
||||
applications use another exit. If A selects B and B selects C, the same website
|
||||
sees B for requests from A and C for requests from B. Changing B’s selection
|
||||
keeps established connections from A on B’s original egress.
|
||||
|
||||
## Using it
|
||||
|
||||
The offering side, per network, off by default:
|
||||
@@ -12,8 +17,7 @@ The offering side, per network, off by default:
|
||||
tsng network exit-node <network> on # or off
|
||||
```
|
||||
|
||||
Rules are installed even when the kernel does not forward yet, and `status`
|
||||
says so. Turning forwarding on is left to you, on purpose:
|
||||
Linux and macOS report kernel forwarding in `status`. To enable it on Linux:
|
||||
|
||||
```sh
|
||||
sudo sysctl -w net.ipv4.ip_forward=1
|
||||
@@ -57,7 +61,13 @@ subnet is dropped locally. Offering an exit remains a per-network choice.
|
||||
lookup main` and `5206 uidrange <agent uid> lookup main` keep the agent's
|
||||
sockets and their replies outside the tunnel, before Tailscale's rules.
|
||||
`5290 lookup main suppress_prefixlength 0` preserves LAN and other specific
|
||||
routes, and `5300 lookup 29811` directs other traffic through the exit.
|
||||
routes, and `5300 iif lo lookup 29811` directs locally originated
|
||||
IPv4 traffic through the exit. Forwarded member packets and their SNAT
|
||||
replies carry the agent’s underlay bit, including during strict reverse-path
|
||||
checks. Their conntrack entries live independently of B’s exit selection.
|
||||
When the daemon runs as root, rule `5204` directs reverse lookups for
|
||||
authenticated replies to local exit-client connections back to the overlay
|
||||
using the independent packet-mark bit `0x20000000`.
|
||||
The exit table is `29811` (`0x7473`).
|
||||
- **Linux reverse-path filtering:** only the agent's dedicated UID is marked
|
||||
in mangle `OUTPUT`. Its own bit, `0x40000000`, is saved to conntrack and
|
||||
@@ -99,7 +109,9 @@ is built from `pf` and `route`. The agent runs as root there.
|
||||
|
||||
- **Offering:** a `pf` anchor `com.apple/tsunagi-exit-<interface>` (the stock
|
||||
`/etc/pf.conf` already evaluates `com.apple/*`) holds
|
||||
`nat on <egress> from <range> to any -> (<egress>)` and a `pass in` rule.
|
||||
`nat on <egress> from <range> to any -> (<egress>)` and tags packets entering from an offered range. A tagged packet that the
|
||||
kernel would forward back to the utun gets a PF `route-to` through the
|
||||
physical gateway. The physical NAT state is interface-bound.
|
||||
`pf` is enabled if it was off, and that reference is released when the rules
|
||||
go. Forwarding is only read: `sudo sysctl -w net.inet.ip.forwarding=1`, which
|
||||
macOS forgets at reboot. The egress is the default route's interface **at the
|
||||
@@ -122,13 +134,15 @@ is built from `pf` and `route`. The agent runs as root there.
|
||||
|
||||
## Windows
|
||||
|
||||
- **Offering:** each offered range gets a WinNAT object
|
||||
`tsunagi-exit:<interface>:<range>` (`New-NetNat`), removed with the offer, the
|
||||
network and the agent. Forwarding is read for the overlay interface and never
|
||||
changed; Windows forwards per interface, so enable it on the ones involved
|
||||
(`Get-NetIPInterface | Set-NetIPInterface -Forwarding Enabled`, administrator
|
||||
PowerShell). Some Windows versions allow one NAT per host; a second range then
|
||||
reports its own failure.
|
||||
- **Offering** uses IPv4 sockets bound to the physical adapter index and
|
||||
address (`IP_UNICAST_IF`). A bounded smoltcp stack handles the member-facing
|
||||
TCP connection and passes stream data and half-closes in both directions.
|
||||
Each UDP flow keeps its physical source port for two minutes of inactivity.
|
||||
ICMP echo uses a physically bound raw socket. Fragmented IPv4 datagrams are
|
||||
reassembled before transport processing and replies are split to the mesh
|
||||
MTU. Other IPv4 protocols and new connections above the shared limit of 256
|
||||
are dropped. Legacy Tsunagi WinNAT objects are cleaned up on startup. The
|
||||
Windows offer works with kernel IP forwarding disabled.
|
||||
- **Using:** Windows has no per-user routing, so the agent's own traffic is kept
|
||||
off the tunnel *by destination*. `0.0.0.0/1` and `128.0.0.0/1` go through the
|
||||
overlay interface; a `/32` route with metric 7373 (the marker for "ours")
|
||||
|
||||
@@ -211,6 +211,16 @@ atomic rollback. The CLI test starts two real agent processes and exercises
|
||||
offline cleanup by network and hostname through the control socket.
|
||||
Native tray rendering and physical screen sizing are not exercised automatically.
|
||||
|
||||
The three-agent exit test delivers A’s traffic to B before, during and after B
|
||||
chooses C, including both agents contacting the same address. The isolated Linux
|
||||
kernel test `serving_an_established_flow_while_switching_the_local_exit` uses
|
||||
network namespaces and keeps a real TCP connection open across both switches.
|
||||
On disposable macOS and Windows runners the native subnet workflow checks the
|
||||
same-destination split on two utuns or two Wintun adapters. Its macOS test
|
||||
requires IPv4 forwarding enabled. Windows userspace forwarding also has
|
||||
ordinary loopback tests for TCP resets, half-closes, UDP port stability and
|
||||
connection limits.
|
||||
|
||||
Linux exit-client unit tests cover preservation of foreign mark bits, matching
|
||||
only the agent's UID and locally owned TCP/UDP sockets, exact tagged cleanup,
|
||||
partial IPv6 failure and mark-aware strict kernel RPF validation. The ignored
|
||||
|
||||
@@ -238,6 +238,15 @@ modifying the source files. Corrupt legacy databases are hard errors. Old
|
||||
internal channel; contradictory values are rejected. Interface MTU is selected
|
||||
once with `--mtu`, independent of carrier selection.
|
||||
|
||||
The client renews the selected exit peer's session key at 120 seconds, even
|
||||
when no IP traffic is flowing. The current key can carry packets during the
|
||||
exchange. Changing the exit moves this behavior to the new network and peer.
|
||||
|
||||
The device list shows **Idle** after an established tunnel has had 30 seconds
|
||||
without IP traffic. Handshakes and keepalives do not restart this interval.
|
||||
Pending IP packets, a missing path, or a selected exit waiting for a usable
|
||||
key still show **Waiting**. A reported transport failure shows **Error**.
|
||||
|
||||
User traffic counters count original IP bytes once when the encrypted frame is
|
||||
accepted by the logical transport, and once when decrypted on receipt. They do
|
||||
not promise remote delivery. They exclude carrier overhead, handshakes,
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ let
|
||||
in
|
||||
rustPlatform.buildRustPackage {
|
||||
pname = if withTray then "tsunagi" else "tsunagi-cli";
|
||||
version = "1.0.4";
|
||||
version = "1.0.6";
|
||||
|
||||
src = lib.cleanSource ../.;
|
||||
cargoLock.lockFile = ../Cargo.lock;
|
||||
|
||||
Reference in new issue
Block a user