Keep concurrent overlays working and select faster data carriers

A second subnet on macOS could send with the first utun alias. Reconcile and verify each owned subnet route with its actual source, retry partially applied plans and expose host errors to clients. On Windows verify the alias and prefix on the intended adapter. Do not restart underlay sockets when the only network change is a local overlay address.

Compare mutually enabled carriers using authenticated data probes while the incumbent carries traffic. The dialler coordinates a generation-scoped decision after a sustained median RTT improvement. Old peers retain ordered fallback. Local IPC moves to v24 to report data RTT and the physical path independently of control RTT. The mesh wire versions, keys and saved network settings stay compatible.

Validated formatting, workspace Clippy and the workspace test suite on macOS, including bidirectional dual-network traffic and a live TLS-to-QUIC switch on loopback. Added focused native CI tests for macOS and Windows. The elevated utun test requires administrative access unavailable on the development host.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-24 23:55:55 +02:00
1 parent 8d107cf0e9
commit 27e29cf8a7
34 files changed
+1569 -253

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
name: Native subnet source selection
on:
push:
branches: [master]
paths:
- '.github/workflows/subnet-source.yml'
- 'crates/tsunagi-core/src/overlay/provision/macos.rs'
- 'crates/tsunagi-core/src/overlay/provision/windows.rs'
- 'crates/tsunagi-core/src/overlay/provision/mod.rs'
- 'crates/tsunagi-core/src/overlay/provision/factory.rs'
- 'crates/tsunagi-core/src/net.rs'
workflow_dispatch:
permissions:
contents: read
jobs:
source:
if: github.server_url == 'https://github.com'
runs-on: ${{ matrix.os }}
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
include:
- os: macos-latest
test: overlay::provision::macos::tests::unbound_sockets_choose_each_networks_source_on_one_real_utun
- os: windows-latest
test: overlay::provision::windows::tests::two_windows_subnets_choose_their_own_source_and_survive_removal
env:
TEST_NAME: ${{ matrix.test }}
CARGO_PROFILE_TEST_DEBUG: '0'
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build and locate the native test
shell: pwsh
run: |
$artifacts = @(cargo test --locked -p tsunagi-core --lib --features tun-device --no-run --message-format=json-render-diagnostics |
ForEach-Object { ConvertFrom-Json -InputObject $_ } |
Where-Object { $_.reason -eq 'compiler-artifact' -and $_.target.name -eq 'tsunagi' -and $_.profile.test -and $_.executable })
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if ($artifacts.Count -ne 1) { throw "Expected one core test binary, found $($artifacts.Count)" }
$binary = $artifacts[0].executable
$tests = @(& $binary --ignored --exact $env:TEST_NAME --list)
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 source selection on a real utun
if: runner.os == 'macOS'
shell: bash
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
- name: Verify source selection on a real Wintun adapter
if: runner.os == 'Windows'
shell: pwsh
run: |
$zip = Join-Path $env:RUNNER_TEMP 'wintun.zip'
Invoke-WebRequest -Uri https://www.wintun.net/builds/wintun-0.14.1.zip -OutFile $zip
# This is the signed Wintun distribution pinned by the Windows installer.
if ((Get-FileHash $zip -Algorithm SHA256).Hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') {
throw 'Unexpected Wintun archive checksum'
}
$directory = Join-Path $env:RUNNER_TEMP 'wintun-dl'
Expand-Archive -Path $zip -DestinationPath $directory
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
+8 -3
View File
@@ -122,7 +122,7 @@ The tray does the same with a checkbox. An exit node sees everything you send
through it, so use only members you trust.
[Details and per-OS notes](docs/exit-node.md).
The default data transport order is `wg,awg,wg-quic,tcp-tls`. AWG negotiates a
The initial data transport order is `wg,awg,wg-quic,tcp-tls` by default. AWG negotiates a
fresh masking profile and outer keys for each pair connection attempt, including
reentry after fallback. Sustained data loss triggers switching independently of
the iroh control connection. [Configuration and limits](docs/amnezia.md).
@@ -132,14 +132,19 @@ Change a network's protocol selection without editing its service or restarting:
```sh
tsng protocols # available protocols and settings
tsng protocols home # this device's choice for home
tsng protocols home awg,wg-quic # prefer AWG, retain QUIC as fallback
tsng protocols home awg,wg-quic # enable AWG and QUIC, try AWG first
tsng protocols home none # control plane only
```
Exact network names, full ids and unique id prefixes work here. The choice is
local to this device, saved per network and applied immediately; an offline
change applies on the next start. In the tray, expand **data transports** on a network
tile to toggle protocols or change their preference order. Adjacent peers need a common external transport at the same wire version.
tile to enable transports and set their initial preference order. 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.
`tsng status` and the tray show the direct data link's measured RTT separately
from the control connection's RTT. A mesh relay's first-hop RTT cannot measure
the round trip to the destination.
Selection applies to this device's incoming and outgoing data links; control and
discovery are independent. A relay's next hop may use a different transport.
Every pair uses one internal WireGuard cipher, hidden from these controls.
+3 -1
View File
@@ -178,8 +178,10 @@ pub async fn report(
dns: &crate::dns::Resolver,
) -> tsunagi::Result<StatusReport> {
let status = agent.status().await?;
let overlay = agent.overlay();
Ok(StatusReport {
networks: tsunagi_runtime::report::networks(&status, agent.overlay().as_ref(), wg),
networks: tsunagi_runtime::report::networks(&status, overlay.as_ref(), wg),
overlay_config_error: overlay.and_then(|state| state.address_error),
dns: Some(dns.refresh(&status.networks)),
endpoint_id: status.endpoint_id.to_string(),
hostname: status.hostname,
+4 -1
View File
@@ -135,7 +135,9 @@ impl Inner {
.await
{
Ok(interface) => {
self.adapter.exclude_interface(interface.name());
if interface.on_host() {
self.adapter.exclude_interface(interface.name());
}
for carrier in &self.config.carriers {
carrier.on_interface_ready(interface.name());
}
@@ -643,6 +645,7 @@ impl Agent {
on_host: interface.on_host(),
mtu: interface.mtu(),
addresses: interface.wanted_addresses(),
address_error: interface.address_error(),
counters: interface.counters(),
broadcast_rules: interface.broadcast_rules(),
})
+61 -20
View File
@@ -39,6 +39,8 @@ use super::status::{
NetworkStatus, PeerStatus,
};
mod selection;
/// An inbound connection that already passed the handshake.
#[derive(Debug)]
pub(crate) struct InboundSession {
@@ -327,6 +329,7 @@ struct Runtime {
/// peer, which outlives any particular path.
links: HashMap<(EndpointId, String), Arc<HealthLink>>,
pending_health: HashMap<(EndpointId, String), HealthSettings>,
comparisons: HashMap<EndpointId, selection::Schedule>,
last_failed_protocol: HashMap<EndpointId, String>,
/// Every data link of this network, and what is reached through what.
hub: Arc<crate::dataplane::relay::RelayHub>,
@@ -450,6 +453,7 @@ impl Runtime {
dial_results_rx,
links: HashMap::new(),
pending_health: HashMap::new(),
comparisons: HashMap::new(),
last_failed_protocol: HashMap::new(),
hub,
reachable: HashMap::new(),
@@ -2024,24 +2028,29 @@ impl Runtime {
}
}
for (peer, protocol) in dead {
let reason = self
.links
.remove(&(peer, protocol.clone()))
.map(|link| {
let reason = link
.failure_reason()
.unwrap_or_else(|| "link closed".into());
link.close();
reason
})
.unwrap_or_else(|| "link closed".into());
let Some(link) = self.links.remove(&(peer, protocol.clone())) else {
continue;
};
let planned = self
.comparisons
.get(&peer)
.is_some_and(|s| s.retiring(link.profile_id()));
let reason = if planned {
"retired after carrier comparison".into()
} else {
let reason = link
.failure_reason()
.unwrap_or_else(|| "link closed".into());
self.data_errors
.insert(peer, format!("{protocol}: {reason}"));
self.record_protocol_failure(peer, &protocol);
reason
};
link.close();
// Only the direct path is gone. Whether the peer is still
// reachable through somebody is decided below; the protocol's
// link stays either way.
self.hub.clear_direct(peer, &protocol);
self.data_errors
.insert(peer, format!("{protocol}: {reason}"));
self.record_protocol_failure(peer, &protocol);
self.emit(Event::DataLinkDown {
network: self.network_id,
peer,
@@ -2050,10 +2059,8 @@ impl Runtime {
});
}
// Choose the highest priority mutually supported protocol for each peer.
// If a direct data link is already open or opening, do not dial another.
// If a protocol recently failed, fall back to other mutually supported
// protocols according to backoff cooldown.
// Foreground recovery always precedes optional comparisons.
self.review_comparisons();
let now = std::time::Instant::now();
let mut wanted: Vec<(EndpointId, String)> = Vec::new();
for session in self.sessions.values() {
@@ -2108,6 +2115,8 @@ impl Runtime {
}
}
let trial = self.next_comparison(&served, now);
wanted.extend(trial.iter().cloned());
for (peer, protocol) in wanted {
let key = (peer, protocol.clone());
if self.links.contains_key(&key) || self.opening.contains(&key) {
@@ -2119,6 +2128,7 @@ impl Runtime {
let transport = Arc::clone(&transport);
let network = self.network_id;
let shutdown = self.shutdown.clone();
let background = trial.as_ref() == Some(&key);
self.next_link_attempt = self.next_link_attempt.wrapping_add(1);
let generation = self.next_link_attempt;
self.link_attempts.insert(key.clone(), generation);
@@ -2126,8 +2136,16 @@ impl Runtime {
let result = tokio::select! {
biased;
_ = shutdown.wait() => Err("network deactivated".to_string()),
result = transport.open(network, peer, &protocol) => {
result.map_err(|err| err.to_string())
result = async {
let dial = transport.open(network, peer, &protocol);
if background {
tokio::time::timeout(Duration::from_secs(30), dial).await
.map_err(|_| "carrier comparison timed out".to_owned())?
} else {
dial.await
}.map_err(|err| err.to_string())
} => {
result
}
};
let _ = results
@@ -2475,6 +2493,10 @@ impl Runtime {
self.pending_health.remove(&key)
};
let link = HealthLink::new(link, self.local_id, settings);
if let Some(primary) = self.hub.direct_kinds(peer).first() {
self.hub.prefer_direct(peer, primary);
}
self.link_installed(peer);
let path = link.path_description();
let max_datagram = link.max_datagram_size();
if let Some(old) = self.links.insert(key, Arc::clone(&link)) {
@@ -2512,6 +2534,7 @@ impl Runtime {
/// Retire only the data plane; authenticated membership and topology remain.
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
self.comparisons.remove(&peer);
self.data_errors.remove(&peer);
self.link_attempts.retain(|(id, _), _| *id != peer);
self.opening.retain(|(id, _)| *id != peer);
@@ -2661,6 +2684,9 @@ impl Runtime {
reason,
});
}
if self.params.carriers.len() > 1 {
capabilities.push(selection::capability());
}
capabilities.truncate(self.params.limits.max_capabilities);
self.local_capabilities = capabilities
.iter()
@@ -2802,6 +2828,10 @@ impl Runtime {
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
match &message {
ControlMessage::Transport { protocol, payload } => {
if protocol == selection::PROTOCOL {
self.receive_choice(peer, payload.as_bytes());
return;
}
if protocol == "link-health" {
// Only the elected initiator supplies a profile, for an enabled,
// mutually supported physical protocol in this authenticated session.
@@ -3079,6 +3109,7 @@ impl Runtime {
.iter()
.filter(|cap| {
cap.enabled
&& cap.protocol != selection::PROTOCOL
&& self
.params
.tunnel
@@ -3106,7 +3137,17 @@ impl Runtime {
.values()
.map(|session| {
let snapshot = snapshot_connection(&session.conn);
let selected = self
.hub
.direct_kinds(session.peer)
.into_iter()
.next()
.and_then(|kind| self.links.get(&(session.peer, kind)));
PeerStatus {
data_rtt: selected
.and_then(|link| link.quality())
.map(|quality| quality.rtt),
data_transport_detail: selected.map(|link| link.path_description()),
broadcast: session.broadcast,
exit_node: session.exit_node,
endpoint_id: session.peer,
@@ -0,0 +1,334 @@
//! Compare one alternative per peer while normal traffic stays on the incumbent.
//! The elected dialler chooses for both directions. Each decision names the
//! exact two health profiles, so delayed messages cannot retire a reopened link.
use super::{ControlMessage, EndpointId, Event, PacketLink, PluginCapability, Runtime};
use crate::dataplane::transport::{LinkQuality, TransportPayload};
use std::time::{Duration, Instant};
pub(super) const PROTOCOL: &str = "link-choice";
const RETRY: Duration = Duration::from_secs(3);
const NEXT_TRIAL: Duration = Duration::from_secs(120);
const MIN_WINDOW: Duration = Duration::from_secs(6);
const MAX_WINDOW: Duration = Duration::from_secs(18);
pub(super) fn capability() -> PluginCapability {
PluginCapability {
protocol: PROTOCOL.into(),
version: 1,
enabled: true,
data: Vec::new(),
}
}
fn supports_choice(caps: &[PluginCapability]) -> bool {
caps.iter()
.any(|c| c.enabled && c.protocol == PROTOCOL && c.version == 1)
}
fn better(current: &LinkQuality, alternative: &LinkQuality) -> bool {
let gain = current.rtt.saturating_sub(alternative.rtt);
current.samples >= 5
&& alternative.samples >= 5
&& alternative.losses == 0
&& gain >= (current.rtt / 5).max(Duration::from_millis(5))
}
/// Fixed-size identifiers from the two privately negotiated health profiles.
/// The responder echoes this value after accepting a decision.
#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct Choice {
keep: [u8; 16],
retire: [u8; 16],
}
struct Trial {
protocol: String,
started: Instant,
decision: Option<Choice>,
retry_at: Instant,
}
pub(super) struct Schedule {
next: Instant,
cursor: usize,
trial: Option<Trial>,
}
impl Schedule {
/// The responder can close the losing link before its acknowledgement
/// arrives. Only an exact generation match makes this a planned closure.
pub(super) fn retiring(&self, profile: Option<[u8; 16]>) -> bool {
self.trial
.as_ref()
.and_then(|trial| trial.decision)
.is_some_and(|choice| Some(choice.retire) == profile)
}
}
impl Runtime {
pub(super) fn link_installed(&mut self, peer: EndpointId) {
if self.local_id.as_bytes() >= peer.as_bytes() || self.params.carriers.len() < 2 {
return;
}
let now = Instant::now();
let jitter = (peer.as_bytes()[0] ^ self.network_id.as_bytes()[0]) % 6;
let schedule = self.comparisons.entry(peer).or_insert(Schedule {
next: now + Duration::from_secs(12 + u64::from(jitter)),
cursor: 0,
trial: None,
});
if let Some(trial) = &mut schedule.trial {
// Any replacement invalidates an outstanding decision naming the
// previous pair of profiles. Compare both current links afresh.
trial.decision = None;
trial.started = now;
trial.retry_at = now;
}
}
/// At most two alternatives per network are opened or measured at once.
/// Waiting for a peer to acknowledge a decision uses no measurement slot. Old peers
/// keep the original single-carrier behaviour without a wire upgrade.
pub(super) fn next_comparison(
&mut self,
served: &[(String, u16)],
now: Instant,
) -> Option<(EndpointId, String)> {
if !supports_choice(&self.local_capabilities)
|| self
.comparisons
.values()
.filter_map(|s| s.trial.as_ref())
.filter(|trial| trial.decision.is_none())
.count()
>= 2
{
return None;
}
let (peer, index) =
self.comparisons
.iter()
.filter_map(|(peer, schedule)| {
if schedule.next > now
|| schedule.trial.is_some()
|| self.no_direct_data(*peer)
|| self.opening.iter().any(|(id, _)| id == peer)
{
return None;
}
let session = self.sessions.get(peer)?;
if !supports_choice(&session.capabilities)
|| self.hub.direct_kinds(*peer).len() != 1
{
return None;
}
let index = (0..served.len())
.map(|n| (n + schedule.cursor) % served.len())
.find(|i| {
let (name, version) = &served[*i];
let key = (*peer, name.clone());
!self.links.contains_key(&key)
&& self
.protocol_dial_states
.get(&key)
.is_none_or(|s| s.cooldown_until <= now)
&& session.capabilities.iter().any(|c| {
c.enabled && &c.protocol == name && &c.version == version
})
})?;
Some((schedule.next, *peer, index))
})
.min()
.map(|(_, peer, index)| (peer, index))?;
let schedule = self.comparisons.get_mut(&peer)?;
let protocol = served[index].0.clone();
schedule.cursor = index + 1;
schedule.trial = Some(Trial {
protocol: protocol.clone(),
started: now,
decision: None,
retry_at: now,
});
Some((peer, protocol))
}
fn finish_comparison(&mut self, peer: EndpointId) {
if let Some(schedule) = self.comparisons.get_mut(&peer) {
schedule.trial = None;
schedule.next = Instant::now() + NEXT_TRIAL;
}
}
pub(super) fn review_comparisons(&mut self) {
let peers: Vec<_> = self
.comparisons
.iter()
.filter(|(_, s)| s.trial.is_some())
.map(|(peer, _)| *peer)
.collect();
for peer in peers {
self.review_trial(peer);
}
}
fn review_trial(&mut self, peer: EndpointId) {
let Some(trial) = self.comparisons.get(&peer).and_then(|s| s.trial.as_ref()) else {
return;
};
let key = (peer, trial.protocol.clone());
if self.opening.contains(&key) {
return;
}
let kinds = self.hub.direct_kinds(peer);
if kinds.len() < 2 || !self.links.contains_key(&key) {
self.finish_comparison(peer);
return;
}
let now = Instant::now();
if now < trial.retry_at {
return;
}
let choice = if let Some(choice) = trial.decision {
choice
} else {
let Some(other) = kinds.iter().find(|kind| **kind != trial.protocol) else {
return;
};
let Some(current) = self.links.get(&(peer, other.clone())) else {
return;
};
let Some(candidate) = self.links.get(&key) else {
return;
};
let age = now.duration_since(trial.started);
if age < MIN_WINDOW {
return;
}
let measured = current
.quality()
.zip(candidate.quality())
.filter(|(a, b)| a.samples >= 5 && b.samples >= 5);
if measured.is_none() && age < MAX_WINDOW {
return;
}
let promote = measured.is_some_and(|(a, b)| better(&a, &b));
let (winner, loser) = if promote {
(candidate, current)
} else {
(current, candidate)
};
let (Some(keep), Some(retire)) = (winner.profile_id(), loser.profile_id()) else {
return;
};
self.hub
.prefer_direct(peer, if promote { &trial.protocol } else { other });
Choice { keep, retire }
};
if let Some(trial) = self
.comparisons
.get_mut(&peer)
.and_then(|s| s.trial.as_mut())
{
trial.decision = Some(choice);
trial.retry_at = now + RETRY;
}
self.send_choice(peer, choice);
}
fn send_choice(&mut self, peer: EndpointId, choice: Choice) {
if let Ok(bytes) = postcard::to_stdvec(&choice) {
let _ = self.send_to(
peer,
ControlMessage::Transport {
protocol: PROTOCOL.into(),
payload: TransportPayload::new(bytes),
},
);
}
}
pub(super) fn receive_choice(&mut self, peer: EndpointId, payload: &[u8]) {
if payload.len() != 32 {
return;
}
let Ok(choice) = postcard::from_bytes::<Choice>(payload) else {
return;
};
if choice.keep == choice.retire
|| !supports_choice(&self.local_capabilities)
|| !self
.sessions
.get(&peer)
.is_some_and(|s| supports_choice(&s.capabilities))
{
return;
}
let dialler = self.local_id.as_bytes() < peer.as_bytes();
if dialler
&& self
.comparisons
.get(&peer)
.and_then(|s| s.trial.as_ref())
.and_then(|t| t.decision)
!= Some(choice)
{
return;
}
let find = |profile| {
self.links
.iter()
.find(|((id, _), link)| {
*id == peer && !link.is_closed() && link.profile_id() == Some(profile)
})
.map(|((_, kind), _)| kind.clone())
};
let Some(winner) = find(choice.keep) else {
return;
};
let loser = find(choice.retire);
self.hub.prefer_direct(peer, &winner);
if let Some(kind) = loser {
self.hub.clear_direct(peer, &kind);
if let Some(link) = self.links.remove(&(peer, kind.clone())) {
link.close();
self.emit(Event::DataLinkDown {
network: self.network_id,
peer,
protocol: kind,
reason: format!("carrier comparison kept {winner}"),
});
}
}
if dialler {
self.finish_comparison(peer);
} else {
self.send_choice(peer, choice);
}
self.announce_reach(false);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn measurement(ms: u64, samples: usize, losses: usize) -> LinkQuality {
LinkQuality {
rtt: Duration::from_millis(ms),
samples,
losses,
observed_at: Instant::now(),
}
}
#[test]
fn promote_only_a_sampled_reliable_and_materially_faster_path() {
let current = measurement(350, 20, 1);
assert!(better(&current, &measurement(60, 6, 0)));
assert!(!better(&current, &measurement(60, 1, 0)));
assert!(!better(&current, &measurement(60, 6, 2)));
assert!(!better(&measurement(61, 20, 0), &measurement(59, 10, 0)));
assert!(!better(&measurement(10, 20, 0), &measurement(7, 10, 0)));
assert!(!better(&measurement(8, 2, 0), &measurement(1, 6, 0)));
}
}
+6
View File
@@ -51,6 +51,8 @@ pub struct OverlayStatus {
pub mtu: u32,
/// The addresses it should be carrying.
pub addresses: Vec<crate::overlay::Cidr>,
/// Last error applying addresses or subnet routes on the shared interface.
pub address_error: Option<String>,
/// What has happened on it.
pub counters: crate::overlay::Counters,
/// The route and firewall allowance installed for LAN broadcast, when
@@ -168,6 +170,10 @@ pub struct PeerStatus {
pub transport: TransportKind,
/// RTT of the selected path, when iroh reported one.
pub rtt: Option<Duration>,
/// Recent RTT of the selected direct data link, measured by authenticated probes.
pub data_rtt: Option<Duration>,
/// The selected direct data carrier's own description of its underlying path.
pub data_transport_detail: Option<String>,
/// Per-connection counters.
pub connection: ConnectionCounters,
/// Control messages sent on this session.
+31 -1
View File
@@ -208,6 +208,7 @@ struct State {
/// Transport kinds, best first. A neighbour with several links is
/// reached over the first of these it has.
priority: Vec<String>,
preferred: HashMap<PeerId, String>,
graph: HashMap<PeerId, Vec<PeerId>>,
members: HashSet<PeerId>,
raw: HashMap<PeerId, Vec<RawLink>>,
@@ -229,7 +230,14 @@ impl State {
.get(peer)
.map(|links| links.iter().collect())
.unwrap_or_default();
links.sort_by_key(|raw| (self.rank(&raw.kind), raw.kind.clone()));
let preferred = self.preferred.get(peer);
links.sort_by_key(|raw| {
(
preferred != Some(&raw.kind),
self.rank(&raw.kind),
&raw.kind,
)
});
links
}
@@ -326,6 +334,7 @@ impl RelayHub {
tally: tally.clone(),
}),
priority: Vec::new(),
preferred: HashMap::new(),
graph: HashMap::new(),
members: HashSet::new(),
raw: HashMap::new(),
@@ -350,6 +359,23 @@ impl RelayHub {
}
}
/// Selects an already open carrier for this neighbour. The existing
/// immutable forwarding snapshot handles packet delivery and fallback.
pub(crate) fn prefer_direct(&self, peer: EndpointId, kind: &str) {
let mut state = self.state();
let id = peer.as_bytes();
if state.preferred.get(id).map(String::as_str) != Some(kind)
&& state.raw.get(id).is_some_and(|links| {
links
.iter()
.any(|raw| raw.kind == kind && !raw.link.is_closed())
})
{
state.preferred.insert(*id, kind.to_owned());
state.publish();
}
}
/// Wakes the control loop promptly when a transport reader ends.
pub async fn changed(&self) {
self.changed.notified().await;
@@ -477,6 +503,9 @@ impl RelayHub {
/// Removes one physical link without tearing down end-to-end protocol state.
pub fn clear_direct(&self, peer: EndpointId, kind: &str) {
let mut state = self.state();
if state.preferred.get(peer.as_bytes()).map(String::as_str) == Some(kind) {
state.preferred.remove(peer.as_bytes());
}
let mut changed = false;
if let Some(links) = state.raw.get_mut(peer.as_bytes()) {
if let Some(position) = links.iter().position(|known| known.kind == kind) {
@@ -495,6 +524,7 @@ impl RelayHub {
/// Retires data channels without removing an authenticated peer's topology.
pub fn clear_peer_links(&self, peer: EndpointId) {
let mut state = self.state();
state.preferred.remove(peer.as_bytes());
if let Some(links) = state.raw.remove(peer.as_bytes()) {
for raw in links {
raw.link.close();
@@ -20,6 +20,32 @@ fn tag() -> u64 {
envelope::protocol_tag("ip")
}
#[tokio::test]
async fn measuring_an_alternative_preserves_the_active_link_until_promotion() {
let hub = RelayHub::new(network(), peer(1));
hub.set_priority(vec!["first".into(), "second".into()]);
let first = Wire::new(2, true);
let second = Wire::new(2, true);
hub.set_direct(peer(2), "second", second.clone());
hub.prefer_direct(peer(2), "second");
hub.set_direct(peer(2), "first", first.clone());
let logical = hub.link(peer(2), "ip");
logical.send(Bytes::from_static(b"while testing")).unwrap();
assert_eq!(second.take().len(), 1);
assert!(first.take().is_empty());
hub.prefer_direct(peer(2), "first");
logical
.send(Bytes::from_static(b"after switching"))
.unwrap();
assert_eq!(first.take().len(), 1);
first.dead.store(true, Ordering::Relaxed);
logical.send(Bytes::from_static(b"fallback")).unwrap();
assert_eq!(second.take().len(), 1);
hub.clear_direct(peer(2), "first");
hub.set_direct(peer(2), "first", Wire::new(2, true));
assert!(Arc::ptr_eq(&logical, &hub.link(peer(2), "ip")));
}
#[derive(Debug)]
struct Wire {
peer: EndpointId,
@@ -1,6 +1,6 @@
//! Authenticated probes of the actual data link, independent of control RTT.
//! Keys are negotiated privately for each physical link. No fixed wire magic.
use super::{PacketLink, SharedLink, TransportError};
use super::{LinkQuality, PacketLink, SharedLink, TransportError};
use crate::{BoxFuture, NetworkId};
use bytes::Bytes;
use hmac::{Hmac, KeyInit, Mac};
@@ -32,40 +32,74 @@ impl std::fmt::Debug for Settings {
}
struct Samples {
pending: VecDeque<(u64, Instant)>,
recent: VecDeque<bool>,
recent: VecDeque<Option<Duration>>,
last_reply: Option<Instant>,
}
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
const WINDOW: usize = 20;
impl Samples {
fn new() -> Self {
Self {
pending: VecDeque::new(),
recent: VecDeque::new(),
last_reply: None,
}
}
fn sent(&mut self, seq: u64, now: Instant) {
self.pending.push_back((seq, now));
}
fn acknowledge(&mut self, seq: u64) {
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq) {
self.pending.remove(i);
self.recent.push_back(true);
fn record(&mut self, rtt: Option<Duration>) {
if self.recent.len() == WINDOW {
self.recent.pop_front();
}
self.recent.push_back(rtt);
}
fn acknowledge(&mut self, seq: u64, now: Instant) {
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq)
&& let Some((_, sent)) = self.pending.remove(i)
{
let rtt = now.saturating_duration_since(sent);
let success = rtt < PROBE_TIMEOUT;
self.record(success.then_some(rtt));
if success {
self.last_reply = Some(now);
}
}
}
fn expire(&mut self, now: Instant) {
while self
.pending
.front()
.is_some_and(|(_, at)| now.duration_since(*at) >= Duration::from_secs(3))
.is_some_and(|(_, at)| now.duration_since(*at) >= PROBE_TIMEOUT)
{
self.pending.pop_front();
self.recent.push_back(false);
}
while self.recent.len() > 20 {
self.recent.pop_front();
self.record(None);
}
}
fn degraded(&self) -> bool {
self.recent.len() >= 15
&& self.recent.iter().filter(|ok| !**ok).count() * 100 >= self.recent.len() * 60
&& self.recent.iter().filter(|rtt| rtt.is_none()).count() * 100
>= self.recent.len() * 60
}
fn quality(&self) -> Option<LinkQuality> {
let observed_at = self.last_reply?;
let mut delays = [Duration::ZERO; WINDOW];
let mut samples = 0;
for rtt in self.recent.iter().flatten() {
delays[samples] = *rtt;
samples += 1;
}
if samples == 0 {
return None;
}
delays[..samples].sort_unstable();
let rtt = (delays[(samples - 1) / 2] + delays[samples / 2]) / 2;
Some(LinkQuality {
rtt,
samples,
losses: self.recent.len() - samples,
observed_at,
})
}
}
/// A monitored physical link. It forwards application bytes unchanged.
@@ -75,6 +109,7 @@ pub(crate) struct HealthLink {
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
stop: watch::Sender<bool>,
reason: Mutex<Option<String>>,
quality: Mutex<Option<([u8; 16], LinkQuality)>>,
}
impl std::fmt::Debug for HealthLink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -99,6 +134,7 @@ impl HealthLink {
rx: tokio::sync::Mutex::new(rx),
stop,
reason: Mutex::new(None),
quality: Mutex::new(None),
});
let weak = Arc::downgrade(&link);
let mut stopped = link.stop.subscribe();
@@ -117,6 +153,7 @@ impl HealthLink {
let Some(link)=weak.upgrade()else{break;};let Some(settings)=lock(&link.settings).clone()else{continue;};
if marker != Some(settings.marker) { marker = Some(settings.marker); samples = Samples::new(); since = None; }
let start=*since.get_or_insert_with(Instant::now);let now=Instant::now();samples.expire(now);
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
if now.duration_since(start)>=Duration::from_secs(20) && samples.degraded() {
*lock(&link.reason)=Some("data delivery checks: at least 60% loss over the last 20 probes".into());break;
}
@@ -132,7 +169,10 @@ impl HealthLink {
if let Some(settings)=settings && packet.starts_with(&settings.marker) {
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));}
else if kind==2 {samples.acknowledge(seq);}
else if kind==2 && marker == Some(settings.marker) {
samples.acknowledge(seq, Instant::now());
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
}
}
} else {let _=tx.try_send(packet);}
}
@@ -149,6 +189,11 @@ impl HealthLink {
pub(crate) fn configure(&self, settings: Settings) {
*lock(&self.settings) = Some(settings);
}
pub(crate) fn profile_id(&self) -> Option<[u8; 16]> {
lock(&self.settings)
.as_ref()
.map(|settings| settings.marker)
}
}
fn probe(settings: &Settings, sender: EndpointId, kind: u8, seq: u64, size: usize) -> Bytes {
let mut bytes = vec![0; size.max(57)];
@@ -236,6 +281,15 @@ impl PacketLink for HealthLink {
.clone()
.or_else(|| self.raw.failure_reason())
}
fn quality(&self) -> Option<LinkQuality> {
if self.is_closed() {
return None;
}
let current = self.profile_id()?;
lock(&self.quality)
.filter(|(profile, quality)| *profile == current && quality.is_fresh(Instant::now()))
.map(|(_, quality)| quality)
}
fn path_description(&self) -> String {
self.raw.path_description()
}
@@ -251,6 +305,35 @@ impl Drop for HealthLink {
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn quality_uses_matched_fresh_replies_and_keeps_losses_in_the_window() {
let mut samples = Samples::new();
let start = Instant::now();
assert!(samples.quality().is_none());
for (seq, delay) in [(1, 10), (2, 30), (3, 250)] {
samples.sent(seq, start);
samples.acknowledge(seq, start + Duration::from_millis(delay));
}
samples.acknowledge(1, start + Duration::from_secs(1));
samples.sent(4, start);
samples.expire(start + Duration::from_secs(3));
samples.acknowledge(4, start + Duration::from_secs(4));
let measured = samples.quality().unwrap();
assert_eq!(measured.rtt, Duration::from_millis(30));
assert_eq!((measured.samples, measured.losses), (3, 1));
assert!(measured.is_fresh(start + Duration::from_secs(4)));
assert!(!measured.is_fresh(start + Duration::from_secs(6)));
for seq in 5..25 {
let sent = start + Duration::from_secs(seq);
samples.sent(seq, sent);
samples.acknowledge(seq, sent + Duration::from_millis(80));
}
let recovered = samples.quality().unwrap();
assert_eq!(recovered.rtt, Duration::from_millis(80));
assert_eq!((recovered.samples, recovered.losses), (20, 0));
}
#[test]
fn no_false_failure_before_window_but_persistent_loss_is_detected() {
let mut samples = Samples::new();
@@ -258,7 +341,7 @@ mod tests {
for seq in 0..20 {
samples.sent(seq, now);
if seq % 5 == 0 {
samples.acknowledge(seq);
samples.acknowledge(seq, now);
}
}
assert!(!samples.degraded());
@@ -266,7 +349,7 @@ mod tests {
assert!(samples.degraded());
for seq in 20..40 {
samples.sent(seq, now);
samples.acknowledge(seq);
samples.acknowledge(seq, now);
}
samples.expire(now + Duration::from_secs(4));
assert!(!samples.degraded());
@@ -37,6 +37,7 @@ pub mod carrier;
pub use carrier::{DataCarrier, SharedCarrier};
use std::sync::Arc;
use std::time::{Duration, Instant};
use bytes::Bytes;
use iroh::EndpointId;
@@ -73,6 +74,25 @@ pub enum TransportError {
Other(String),
}
/// Recent observations from authenticated round trips over a physical data link.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkQuality {
/// Median round-trip time of successful probes in the window.
pub rtt: Duration,
/// Successful probes in the window.
pub samples: usize,
/// Timed-out probes in the same window.
pub losses: usize,
/// Receipt time of the latest successful probe.
pub observed_at: Instant,
}
impl LinkQuality {
pub(crate) fn is_fresh(&self, now: Instant) -> bool {
now.saturating_duration_since(self.observed_at) <= Duration::from_secs(5)
}
}
/// An authenticated datagram channel to one peer, for one plugin protocol.
///
/// Dropping the link closes it.
@@ -125,6 +145,11 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
None
}
/// Fresh measurements from this physical link's own authenticated probes.
fn quality(&self) -> Option<LinkQuality> {
None
}
/// A short description of the path in use, for diagnostics.
///
/// Reports what the transport actually knows. It must not invent a value.
+8 -2
View File
@@ -614,6 +614,8 @@ pub struct LeftReport {
/// Everything the agent is doing, in one snapshot.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusReport {
/// Last error applying the shared overlay interface's host addresses and routes.
pub overlay_config_error: Option<String>,
/// Data-plane protocols this agent can enable at runtime.
pub available_protocols: Vec<ProtocolReport>,
/// This device's persistent endpoint id.
@@ -837,8 +839,12 @@ pub struct PeerReport {
/// How the connection reaches the peer: `direct`, `relay` or `unknown`,
/// as the transport reports it.
pub transport: String,
/// Round-trip time in milliseconds, when a path is selected.
/// Round-trip time of the control connection in milliseconds.
pub rtt_ms: Option<u64>,
/// Fresh median RTT of the selected direct data link, in milliseconds.
pub data_rtt_ms: Option<u64>,
/// Underlying path reported by the selected direct data carrier.
pub data_transport_detail: Option<String>,
/// The peer offers itself as an exit node in this network.
pub exit_node: bool,
/// How packets reach it.
@@ -1135,7 +1141,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', 23]);
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 24]);
/// Reads one request off an accepted stream, answers it, writes the response.
///
+113 -11
View File
@@ -222,16 +222,13 @@ fn local_addr_string(addr: &iroh::endpoint::LocalTransportAddr) -> Option<String
#[derive(Debug, Clone)]
pub struct EndpointAdapter {
endpoint: Endpoint,
owned_interface: Arc<std::sync::RwLock<String>>,
owned_interface: Arc<std::sync::OnceLock<String>>,
}
impl EndpointAdapter {
/// Excludes the real name after interface creation (macOS assigns utunN).
pub(crate) fn exclude_interface(&self, name: &str) {
*self
.owned_interface
.write()
.unwrap_or_else(|p| p.into_inner()) = name.to_lowercase();
let _ = self.owned_interface.set(name.to_owned());
}
/// Binds an endpoint according to `config`, reusing the persistent device key.
@@ -250,16 +247,40 @@ impl EndpointAdapter {
TransportPolicy::N0Defaults => builder.preset(presets::N0),
};
let owned_interface =
Arc::new(std::sync::RwLock::new(config.interface_name.to_lowercase()));
let owned_interface = Arc::new(std::sync::OnceLock::<String>::new());
{
let monitor_interface = Arc::clone(&owned_interface);
#[cfg(windows)]
let adapter_id = std::sync::OnceLock::<String>::new();
builder = builder.network_change_filter(move |previous, current| {
let Some(name) = monitor_interface.get() else {
return true;
};
// Wintun gives us its friendly name. netwatch keys Windows
// interfaces by GUID. Enumeration can lag adapter creation,
// so cache a successful lookup and retry a miss on later events.
#[cfg(windows)]
let Some(name) = adapter_id.get().or_else(|| {
let id = netdev::get_interfaces()
.into_iter()
.find(|iface| {
iface
.friendly_name
.as_deref()
.is_some_and(|alias| alias.eq_ignore_ascii_case(name))
})?
.name;
Some(adapter_id.get_or_init(|| id))
}) else {
return true;
};
!only_owned_interface_changed(previous, current, name)
});
let interface_filter = Arc::clone(&owned_interface);
let requested = config.interface_name.clone();
let factory = config.tun_factory.clone();
let filter = iroh::address_lookup::AddrFilter::new(move |addrs| {
let owned_interface = interface_filter
.read()
.unwrap_or_else(|p| p.into_inner())
.clone();
let owned_interface = interface_filter.get().unwrap_or(&requested).to_lowercase();
let mut overlay_ips = std::collections::HashSet::new();
if let Some(factory) = &factory {
overlay_ips.extend(factory.assigned_addresses());
@@ -493,3 +514,84 @@ impl EndpointAdapter {
self.endpoint.close().await;
}
}
/// netwatch treats every new unicast prefix as a link change. A second overlay
/// prefix on the same TUN cannot affect the paths carrying those tunnels.
pub(crate) fn only_owned_interface_changed(
previous: &netwatch::netmon::State,
current: &netwatch::netmon::State,
name: &str,
) -> bool {
if previous.default_route_interface != current.default_route_interface
|| current.default_route_interface.as_deref() == Some(name)
|| previous.last_unsuspend != current.last_unsuspend
|| previous.is_expensive != current.is_expensive
{
return false;
}
// Interface equality in netwatch covers identity and flags. Compare
// addresses separately, including family, prefix and IPv6 address flags.
let same_interface = |a: &netwatch::interfaces::Interface,
b: &netwatch::interfaces::Interface| {
a == b && a.addrs().eq(b.addrs())
};
let old_tun = previous.interfaces.get(name);
let new_tun = current.interfaces.get(name);
match (old_tun, new_tun) {
(None, None) => return false,
(Some(a), Some(b)) if same_interface(a, b) => return false,
_ => {}
}
// have_v4, have_v6 and local_addresses are derived from these interfaces
// and can all change when only the TUN changes.
let old_count = previous.interfaces.len() - usize::from(old_tun.is_some());
let new_count = current.interfaces.len() - usize::from(new_tun.is_some());
old_count == new_count
&& previous.interfaces.iter().all(|(iface, old)| {
iface == name
|| current
.interfaces
.get(iface)
.is_some_and(|new| same_interface(old, new))
})
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use netwatch::netmon::State;
#[test]
fn tun_address_changes_leave_existing_underlay_connections_alone() {
let before = State::fake();
let mut after = before.clone();
// netwatch keys interfaces by their OS name. Its fixture provides a
// unicast address, precisely the kind of change it classifies as major.
let tun = State::fake().interfaces.remove("wifi0").unwrap();
let address = tun.addrs().next().unwrap().addr();
after.interfaces.insert("utun7".into(), tun);
after.local_addresses.regular.push(address);
assert!(after.is_major_change(&before));
assert!(only_owned_interface_changed(&before, &after, "utun7"));
assert!(only_owned_interface_changed(&after, &before, "utun7"));
assert!(!only_owned_interface_changed(&before, &after, "utun6"));
// An update to the real underlay can arrive in the same notification.
let mut lost_wifi = after.clone();
lost_wifi.interfaces.remove("wifi0");
assert!(!only_owned_interface_changed(&before, &lost_wifi, "utun7"));
let mut changed_route = after.clone();
changed_route.default_route_interface = Some("utun7".to_owned());
assert!(!only_owned_interface_changed(
&before,
&changed_route,
"utun7"
));
let mut resumed = after;
resumed.last_unsuspend = Some(std::time::Instant::now().into());
assert!(!only_owned_interface_changed(&before, &resumed, "utun7"));
}
}
+112 -14
View File
@@ -153,9 +153,7 @@ pub struct Interface {
routes: Arc<RoutingTable>,
carrier: Arc<dyn PacketCarrier>,
tally: Arc<Tally>,
/// What was last applied to the host, so an unchanged table is not
/// re-applied on every pass.
applied: std::sync::Mutex<Vec<Cidr>>,
addresses: std::sync::Mutex<AddressState>,
task: std::sync::Mutex<Option<JoinHandle<()>>>,
vip_task: std::sync::Mutex<Option<JoinHandle<()>>>,
sync_lock: Arc<tokio::sync::Mutex<()>>,
@@ -171,6 +169,13 @@ pub struct Interface {
underlay: std::sync::Mutex<std::collections::HashMap<NetworkId, Underlay>>,
}
/// Addresses and subnet routes are applied together. A partial change
/// invalidates the cached plan until the whole interface reconciles again.
struct AddressState {
applied: Option<Vec<Cidr>>,
last_error: Option<String>,
}
/// Underlay destinations one network's runtime currently depends on.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct Underlay {
@@ -336,7 +341,10 @@ impl Interface {
routes,
carrier,
tally,
applied: std::sync::Mutex::new(Vec::new()),
addresses: std::sync::Mutex::new(AddressState {
applied: Some(Vec::new()),
last_error: None,
}),
task: std::sync::Mutex::new(Some(task)),
vip_task: std::sync::Mutex::new(Some(vip_task)),
sync_lock: Arc::new(tokio::sync::Mutex::new(())),
@@ -700,13 +708,13 @@ impl Interface {
let _guard = self.sync_lock.lock().await;
let wanted = self.wanted_addresses();
{
let applied = match self.applied.lock() {
Ok(guard) => guard.clone(),
Err(poisoned) => poisoned.into_inner().clone(),
};
if applied == wanted {
let mut addresses = self.addresses.lock().unwrap_or_else(|e| e.into_inner());
if addresses.applied.as_ref() == Some(&wanted) {
return Ok(());
}
// A failed or cancelled reconfiguration can leave some aliases or
// routes installed. Even a return to the previous plan must retry.
addresses.applied = None;
}
// Every address this agent holds, in every network it is in. The
@@ -717,12 +725,25 @@ impl Interface {
addresses: wanted.clone(),
mtu: self.mtu,
};
self.factory.reconfigure(request).await?;
match self.applied.lock() {
Ok(mut guard) => *guard = wanted,
Err(poisoned) => *poisoned.into_inner() = wanted,
let result = self.factory.reconfigure(request).await;
let mut addresses = self.addresses.lock().unwrap_or_else(|e| e.into_inner());
match &result {
Ok(()) => {
addresses.applied = Some(wanted);
addresses.last_error = None;
}
Err(err) => addresses.last_error = Some(format!("{}: {err}", self.name)),
}
Ok(())
result
}
/// Last error applying the shared interface's addresses and subnet routes.
pub fn address_error(&self) -> Option<String> {
self.addresses
.lock()
.unwrap_or_else(|e| e.into_inner())
.last_error
.clone()
}
/// The interface name the operating system gave.
@@ -1244,6 +1265,83 @@ mod tests {
);
}
#[tokio::test]
async fn dropping_a_network_after_partial_provisioning_removes_its_alias() {
#[derive(Debug, Default)]
struct PartialFactory {
devices: MemoryTunFactory,
addresses: std::sync::Mutex<Vec<Cidr>>,
}
impl TunFactory for PartialFactory {
fn name(&self) -> &str {
"partial"
}
fn on_host(&self) -> bool {
false
}
fn create<'a>(
&'a self,
request: TunRequest,
) -> crate::BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
self.devices.create(request)
}
fn reconfigure<'a>(
&'a self,
request: TunRequest,
) -> crate::BoxFuture<'a, Result<(), OverlayError>> {
Box::pin(async move {
let mut host = self.addresses.lock().unwrap();
*host = request.addresses;
if !host.is_empty() {
return Err(OverlayError::Unavailable("subnet route failed".into()));
}
Ok(())
})
}
}
let routes = Arc::new(RoutingTable::new());
let network = network("partial");
routes
.set_network(
network,
NetworkRoutes {
local: Some(addr(1)),
range: Some("10.13.37.0/24".parse().unwrap()),
..NetworkRoutes::default()
},
)
.unwrap();
let factory = Arc::new(PartialFactory::default());
let interface = Interface::start(
factory.clone(),
"tsunpartial",
1280,
routes.clone(),
Arc::new(Recorder::default()),
)
.await
.unwrap();
assert!(interface.address_error().is_none());
assert!(interface.sync_addresses().await.is_err());
assert!(
interface
.address_error()
.unwrap()
.contains("subnet route failed")
);
assert_eq!(factory.addresses.lock().unwrap().len(), 1);
routes.remove_network(network);
interface.sync_addresses().await.unwrap();
assert!(interface.address_error().is_none());
assert!(factory.addresses.lock().unwrap().is_empty());
interface.remove().await;
}
#[tokio::test]
async fn the_wanted_addresses_follow_the_table() {
let (interface, _device, routes, _carrier, id) = interface(false).await;
+221 -106
View File
@@ -39,7 +39,8 @@
//! `getifaddrs`. An interface is matched by its real `utunN` name, which only
//! matters on reconfiguration: the first create always makes a fresh device.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use netdev::ipnet::IpNet;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use crate::BoxFuture;
@@ -115,7 +116,7 @@ impl InterfaceProvisioner for UtunProvisioner {
if self.is_ours(&plan.name) {
let current = observe(&plan.name).await;
let changes = plan_changes(&current, plan, true)?;
configure(&plan.name, &changes).await?;
configure(&plan.name, &changes, &plan.addresses).await?;
return Ok(Provisioned {
changes,
device: None,
@@ -136,7 +137,7 @@ impl InterfaceProvisioner for UtunProvisioner {
// A failure here leaves an interface that exists but cannot carry
// traffic. Drop the device so the utun closes, and report, rather
// than leave a trap behind.
if let Err(err) = configure(&real, &changes).await {
if let Err(err) = configure(&real, &changes, &plan.addresses).await {
drop(device);
return Err(err);
}
@@ -225,28 +226,25 @@ async fn observe(name: &str) -> InterfaceState {
}
/// Applies MTU, link state, addresses and the on-link routes they imply.
async fn configure(name: &str, changes: &super::Changes) -> Result<(), OverlayError> {
async fn configure(
name: &str,
changes: &super::Changes,
wanted: &[Cidr],
) -> Result<(), OverlayError> {
if let Some(mtu) = changes.set_mtu {
set_mtu(name, mtu).await?;
}
for cidr in &changes.remove {
// Best effort: an address that is already gone is the outcome wanted.
if let Err(err) = address_del(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not remove address");
}
if let Err(err) = route_del(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not remove route");
let network = subnet(*cidr)?;
if !is_host_route(*cidr)
&& matches!(subnet_route(network).await?, SubnetRoute::Present { interface, .. } if interface == name)
{
run("/sbin/route", route_args("delete", name, network)).await?;
}
address_del(name, *cidr).await?;
}
for cidr in &changes.add {
address_add(name, *cidr).await?;
// The subnet route makes the whole overlay range reach the interface;
// a point-to-point utun does not install one from the address alone. A
// host address (/32 or /128) needs none. Best effort: a route that is
// already there is the outcome wanted.
if let Err(err) = route_add(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not add route");
}
}
if changes.bring_up {
// Best effort: a utun with a descriptor open is up already, and a
@@ -255,31 +253,22 @@ async fn configure(name: &str, changes: &super::Changes) -> Result<(), OverlayEr
tracing::debug!(interface = %name, %err, "could not enable the interface");
}
}
Ok(())
}
/// The network address of a CIDR, with the host bits cleared.
fn network_of(cidr: Cidr) -> IpAddr {
match cidr.addr {
IpAddr::V4(addr) => {
let bits = u32::from(addr);
let mask = if cidr.prefix_len == 0 {
0
} else {
u32::MAX << (32 - u32::from(cidr.prefix_len))
};
IpAddr::V4(Ipv4Addr::from(bits & mask))
}
IpAddr::V6(addr) => {
let bits = u128::from(addr);
let mask = if cidr.prefix_len == 0 {
0
} else {
u128::MAX << (128 - u32::from(cidr.prefix_len))
};
IpAddr::V6(Ipv6Addr::from(bits & mask))
// An alias may already be present after a partial reconcile, or its old
// subnet route may still select the first alias on this utun.
let mut result = Ok(());
for &cidr in wanted {
if !is_host_route(cidr) {
// Finish the other networks even when one subnet conflicts.
let update = ensure_subnet_route(name, subnet(cidr)?).await;
result = result.and(update);
}
}
result
}
fn subnet(cidr: Cidr) -> Result<IpNet, OverlayError> {
IpNet::new(cidr.addr, cidr.prefix_len)
.map_err(|err| OverlayError::Unavailable(format!("invalid overlay prefix {cidr}: {err}")))
}
/// Whether a CIDR is a single host address, which needs no subnet route.
@@ -326,40 +315,26 @@ fn address_del_args(name: &str, cidr: Cidr) -> Vec<String> {
]
}
/// The `route` arguments that point a CIDR's subnet at the interface.
fn route_add_args(name: &str, cidr: Cidr) -> Vec<String> {
let family = match cidr.addr {
fn route_args(command: &str, name: &str, subnet: IpNet) -> Vec<String> {
let family = match subnet.addr() {
IpAddr::V4(_) => "-inet",
IpAddr::V6(_) => "-inet6",
};
vec![
"-q".into(),
let mut args = vec![
if command == "get" { "-v" } else { "-q" }.into(),
"-n".into(),
"add".into(),
command.into(),
family.into(),
"-net".into(),
format!("{}/{}", network_of(cidr), cidr.prefix_len),
"-interface".into(),
name.into(),
]
}
/// The `route` arguments that remove that subnet route.
fn route_del_args(name: &str, cidr: Cidr) -> Vec<String> {
let family = match cidr.addr {
IpAddr::V4(_) => "-inet",
IpAddr::V6(_) => "-inet6",
};
vec![
"-q".into(),
"-n".into(),
"delete".into(),
family.into(),
"-net".into(),
format!("{}/{}", network_of(cidr), cidr.prefix_len),
"-interface".into(),
name.into(),
]
subnet.trunc().to_string(),
];
if command != "get" {
args.extend(["-interface".into(), name.into()]);
}
if matches!(command, "add" | "change") {
args.extend(["-ifa".into(), subnet.addr().to_string()]);
}
args
}
async fn address_add(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
@@ -370,18 +345,92 @@ async fn address_del(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
ifconfig(address_del_args(name, cidr)).await
}
async fn route_add(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
if is_host_route(cidr) {
return Ok(());
}
route(route_add_args(name, cidr)).await
#[derive(Debug, Eq, PartialEq)]
enum SubnetRoute {
Absent,
Present { interface: String, source: IpAddr },
}
async fn route_del(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
if is_host_route(cidr) {
return Ok(());
impl SubnetRoute {
fn action(&self, name: &str, subnet: IpNet) -> Result<Option<&'static str>, OverlayError> {
match self {
Self::Absent => Ok(Some("add")),
Self::Present { interface, .. } if interface != name => {
Err(OverlayError::Unavailable(format!(
"route for {}/{} belongs to {interface}; cannot install it on {name}",
subnet.network(),
subnet.prefix_len()
)))
}
Self::Present { source, .. } if *source == subnet.addr() => Ok(None),
Self::Present { .. } => Ok(Some("change")),
}
}
route(route_del_args(name, cidr)).await
}
// A verbose RTM_GET prints two sockaddr lists (request and reply). In the
// kernel's reply IFA follows the variable-width link address of the interface.
fn parse_subnet_route(output: &str, subnet: IpNet) -> Result<SubnetRoute, OverlayError> {
let invalid =
|| OverlayError::Unavailable(format!("could not read the kernel route for {subnet}"));
let field = |key: &str| {
output
.lines()
.find_map(|line| line.trim().strip_prefix(key).map(str::trim))
};
let destination = field("destination:").ok_or_else(invalid)?;
let matches = |text: &str, expected: IpAddr| {
text.parse::<IpAddr>() == Ok(expected) || (text == "default" && expected.is_unspecified())
};
if !matches(destination, subnet.network())
|| !field("mask:").is_some_and(|mask| matches(mask, subnet.netmask()))
{
return Ok(SubnetRoute::Absent);
}
let interface = field("interface:").ok_or_else(invalid)?;
let (_, reply) = output.rsplit_once("sockaddrs:").ok_or_else(invalid)?;
let (fields, addresses) = reply.trim().split_once('\n').ok_or_else(invalid)?;
let after = fields
.trim()
.trim_matches(['<', '>'])
.split(',')
.rev()
.position(|field| field == "IFA")
.ok_or_else(invalid)?;
let source = addresses
.split_whitespace()
.rev()
.nth(after)
.and_then(|ip| ip.parse().ok())
.ok_or_else(invalid)?;
Ok(SubnetRoute::Present {
interface: interface.into(),
source,
})
}
async fn subnet_route(subnet: IpNet) -> Result<SubnetRoute, OverlayError> {
match run("/sbin/route", route_args("get", "", subnet)).await {
Ok(output) => parse_subnet_route(&output, subnet),
Err(OverlayError::Unavailable(message)) if message.ends_with("not in table") => {
Ok(SubnetRoute::Absent)
}
Err(err) => Err(err),
}
}
async fn ensure_subnet_route(name: &str, subnet: IpNet) -> Result<(), OverlayError> {
if let Some(command) = subnet_route(subnet).await?.action(name, subnet)? {
run("/sbin/route", route_args(command, name, subnet)).await?;
let observed = subnet_route(subnet).await?;
if observed.action(name, subnet)?.is_some() {
return Err(OverlayError::Unavailable(format!(
"route for {subnet} on {name} did not select source {} (observed {observed:?})",
subnet.addr()
)));
}
}
Ok(())
}
async fn set_mtu(name: &str, mtu: u32) -> Result<(), OverlayError> {
@@ -394,27 +443,26 @@ async fn set_up(name: &str) -> Result<(), OverlayError> {
/// Runs `/sbin/ifconfig`, turning a non-zero exit into an error with its text.
async fn ifconfig(args: Vec<String>) -> Result<(), OverlayError> {
run("/sbin/ifconfig", args).await
}
/// Runs `/sbin/route`, turning a non-zero exit into an error with its text.
async fn route(args: Vec<String>) -> Result<(), OverlayError> {
run("/sbin/route", args).await
run("/sbin/ifconfig", args).await.map(|_| ())
}
/// Runs a system tool by absolute path, so nothing on `PATH` can stand in for
/// it, and turns a non-zero exit into an error carrying what it said.
async fn run(program: &'static str, args: Vec<String>) -> Result<(), OverlayError> {
async fn run(program: &'static str, args: Vec<String>) -> Result<String, OverlayError> {
let display = format!("{program} {}", args.join(" "));
let output = tokio::task::spawn_blocking(move || {
std::process::Command::new(program).args(&args).output()
std::process::Command::new(program)
.env("LC_ALL", "C")
.args(&args)
.output()
})
.await
.map_err(|err| OverlayError::Other(format!("could not run {display}: {err}")))?
.map_err(|err| OverlayError::Unavailable(format!("could not run {display}: {err}")))?;
if output.status.success() {
return Ok(());
// Darwin route can exit successfully after a routing-socket write failed.
if output.status.success() && (program != "/sbin/route" || output.stderr.is_empty()) {
return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
}
let message = {
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -439,6 +487,7 @@ mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::net::{Ipv4Addr, Ipv6Addr};
fn v4(last: u8, prefix: u8) -> Cidr {
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, 13, 37, last)), prefix).unwrap()
@@ -476,8 +525,8 @@ mod tests {
}
#[test]
fn a_subnet_route_points_the_masked_network_at_the_interface() {
let args = route_add_args("utun5", v4(69, 24));
fn a_subnet_route_names_its_own_overlay_source() {
let args = route_args("add", "utun5", subnet(v4(69, 24)).unwrap());
assert_eq!(
args,
vec![
@@ -488,11 +537,93 @@ mod tests {
"-net",
"10.13.37.0/24",
"-interface",
"utun5"
"utun5",
"-ifa",
"10.13.37.69"
]
);
}
#[test]
fn a_wrong_source_is_repaired_only_on_the_owned_interface() {
let cidr = subnet(v4(69, 24)).unwrap();
let observed = "destination: 10.13.37.0\n mask: 255.255.255.0\n interface: utun5\n\
sockaddrs: <DST,GATEWAY,NETMASK,IFP,IFA>\n 10.13.37.0 index: 20 255.255.255.0 index: 20 utun5 10.99.0.2\n";
let route = parse_subnet_route(observed, cidr).unwrap();
assert_eq!(route.action("utun5", cidr).unwrap(), Some("change"));
assert!(route.action("utun9", cidr).is_err());
let corrected = observed.replace("10.99.0.2", "10.13.37.69");
assert_eq!(
parse_subnet_route(&corrected, cidr)
.unwrap()
.action("utun5", cidr)
.unwrap(),
None
);
assert!(parse_subnet_route(&observed.replace(",IFA>", ">"), cidr).is_err());
assert!(parse_subnet_route("", cidr).is_err());
let broader = observed.replace("255.255.255.0", "255.255.0.0");
assert_eq!(
parse_subnet_route(&broader, cidr).unwrap(),
SubnetRoute::Absent
);
}
#[tokio::test]
#[ignore = "requires root and creates a temporary macOS utun with two subnet routes"]
async fn unbound_sockets_choose_each_networks_source_on_one_real_utun() {
let provisioner = UtunProvisioner::new().unwrap();
let first = Cidr::new("198.18.251.1".parse().unwrap(), 30).unwrap();
let second = Cidr::new("198.19.251.1".parse().unwrap(), 30).unwrap();
let created = provisioner
.reconcile(&InterfacePlan::new("tsuntest", 1280, vec![first]))
.await
.unwrap();
let device = created.device.unwrap();
let plan = InterfacePlan::new(device.name(), 1280, vec![first, second]);
let before = netwatch::netmon::State::new().await;
provisioner.reconcile(&plan).await.unwrap();
let after = netwatch::netmon::State::new().await;
assert!(crate::net::only_owned_interface_changed(
&before,
&after,
device.name()
));
for (peer, expected) in [("198.18.251.2", first), ("198.19.251.2", second)] {
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
socket
.connect((peer.parse::<Ipv4Addr>().unwrap(), 9))
.unwrap();
assert_eq!(socket.local_addr().unwrap().ip(), expected.addr);
}
// Simulate a route left by an earlier release, with both aliases still present.
let second_subnet = subnet(second).unwrap();
let mut stale = route_args("change", device.name(), second_subnet);
*stale.last_mut().unwrap() = first.addr.to_string();
run("/sbin/route", stale).await.unwrap();
assert_eq!(
subnet_route(second_subnet)
.await
.unwrap()
.action(device.name(), second_subnet)
.unwrap(),
Some("change")
);
provisioner.reconcile(&plan).await.unwrap();
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
socket.connect(("198.19.251.2", 9)).unwrap();
assert_eq!(socket.local_addr().unwrap().ip(), second.addr);
provisioner
.reconcile(&InterfacePlan::new(device.name(), 1280, vec![first]))
.await
.unwrap();
assert_eq!(
subnet_route(second_subnet).await.unwrap(),
SubnetRoute::Absent
);
provisioner.remove(device.name()).await.unwrap();
}
#[test]
fn a_host_address_installs_no_subnet_route() {
assert!(is_host_route(v4(69, 32)));
@@ -501,22 +632,6 @@ mod tests {
assert!(!is_host_route(v6(1, 64)));
}
#[test]
fn the_network_address_clears_the_host_bits() {
assert_eq!(
network_of(v4(69, 24)),
IpAddr::V4(Ipv4Addr::new(10, 13, 37, 0))
);
assert_eq!(
network_of(Cidr::new(IpAddr::V4(Ipv4Addr::new(10, 13, 37, 69)), 16).unwrap()),
IpAddr::V4(Ipv4Addr::new(10, 13, 0, 0))
);
assert_eq!(
network_of(v6(0x1234, 64)),
IpAddr::V6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 0))
);
}
#[test]
fn link_local_addresses_are_not_ours_to_manage() {
assert!(is_link_local(IpAddr::V6(Ipv6Addr::new(
@@ -131,10 +131,14 @@ impl InterfaceProvisioner for WintunProvisioner {
};
for cidr in flush.iter().chain(changes.remove.iter()) {
// Best effort: an address that is already gone is the outcome
// wanted, and refusing to start over one is not worth it.
if let Err(err) = address_del(&plan.name, *cidr).await {
tracing::debug!(interface = %plan.name, %cidr, %err, "could not remove address");
if let Err(err) = address_del(&plan.name, *cidr).await
&& observe(&plan.name)
.await
.addresses
.iter()
.any(|a| a.addr == cidr.addr)
{
return Err(err);
}
}
@@ -262,11 +266,12 @@ async fn configure(plan: &InterfacePlan, changes: &super::Changes) -> Result<(),
set_mtu(&plan.name, mtu).await?;
}
for cidr in &changes.add {
if let Err(err) = address_add(&plan.name, *cidr).await {
let err_str = err.to_string();
if !err_str.contains("already exists") && !err_str.contains("0x80071392") {
return Err(err);
}
// An already-installed alias is idempotent, including on localized
// Windows. A duplicate on a different adapter cannot satisfy the plan.
if let Err(err) = address_add(&plan.name, *cidr).await
&& !observe(&plan.name).await.addresses.contains(cidr)
{
return Err(err);
}
}
if changes.bring_up {
@@ -300,6 +305,7 @@ fn address_add_args(name: &str, cidr: Cidr) -> Vec<String> {
format!("address={addr}"),
format!("mask={}", ipv4_mask(cidr.prefix_len)),
"store=active".into(),
"skipassource=false".into(),
],
IpAddr::V6(addr) => vec![
"interface".into(),
@@ -466,6 +472,70 @@ mod tests {
assert!(args.contains(&"name=tsun0".to_string()));
assert!(args.contains(&"address=10.13.37.69".to_string()));
assert!(args.contains(&"mask=255.255.255.0".to_string()));
assert!(args.contains(&"skipassource=false".to_string()));
}
#[tokio::test]
#[ignore = "requires an elevated Windows host with Wintun"]
async fn two_windows_subnets_choose_their_own_source_and_survive_removal() {
let addresses = [
(
Ipv4Addr::new(198, 18, 251, 1),
Ipv4Addr::new(198, 18, 251, 2),
),
(
Ipv4Addr::new(198, 19, 251, 1),
Ipv4Addr::new(198, 19, 251, 2),
),
];
for iface in netdev::get_interfaces() {
for prefix in iface.ipv4 {
assert!(
addresses.iter().all(|(ip, destination)| {
!prefix.contains(ip) && !prefix.contains(destination)
}),
"test subnets already in use"
);
}
}
let adapter = format!("tsun-test-{:08x}", rand::random::<u32>());
let provisioner = WintunProvisioner::new().unwrap();
let cidrs: Vec<_> = addresses
.iter()
.map(|(ip, _)| Cidr::new((*ip).into(), 30).unwrap())
.collect();
let mut device = None;
for wanted in [&cidrs[..1], &cidrs[..], &cidrs[1..], &cidrs[..]] {
let plan = InterfacePlan::new(&adapter, 1280, wanted.to_vec());
let result = provisioner.reconcile(&plan).await.unwrap();
if let Some(created) = result.device {
assert!(device.replace(created).is_none());
}
// Allow the Windows address to finish duplicate address detection.
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
let ready = addresses
.iter()
.filter(|(ip, _)| wanted.iter().any(|c| c.addr == IpAddr::V4(*ip)))
.all(|(ip, destination)| {
std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
.and_then(|socket| {
socket.connect((*destination, 9))?;
socket.local_addr()
})
.is_ok_and(|source| source.ip() == IpAddr::V4(*ip))
});
if ready {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
})
.await
.expect("Windows selected the wrong source");
assert_eq!(observe(&adapter).await.addresses, plan.addresses);
}
provisioner.remove(&adapter).await.unwrap();
}
#[test]
+2
View File
@@ -107,6 +107,8 @@ pub fn networks(
hostname: peer.hostname.clone(),
transport: peer.transport.to_string(),
rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64),
data_rtt_ms: peer.data_rtt.map(|rtt| rtt.as_millis() as u64),
data_transport_detail: peer.data_transport_detail.clone(),
exit_node: peer.exit_node,
path: data_path_report(&peer.data_path),
})
+1 -1
View File
@@ -78,7 +78,7 @@ fn colour_of(health: Health) -> [u8; 3] {
match health {
Health::Disconnected => DARK_RED,
Health::Connected => BLUE,
Health::RangeConflict => [0xd9, 0x91, 0x20],
Health::RangeConflict | Health::InterfaceError => [0xd9, 0x91, 0x20],
Health::ExitNode => GREEN,
}
}
+15
View File
@@ -22,6 +22,8 @@ pub(crate) enum Health {
Disconnected,
/// Connected, nothing out of the ordinary.
Connected,
/// The shared host interface could not apply its addresses or routes.
InterfaceError,
/// At least one configured network is blocked by an overlapping active range.
RangeConflict,
/// This device's traffic leaves through an exit node, and that works.
@@ -35,6 +37,9 @@ impl Health {
let Some(report) = report else {
return Self::Disconnected;
};
if report.overlay_config_error.is_some() {
return Self::InterfaceError;
}
if report
.networks
.iter()
@@ -65,6 +70,7 @@ impl Health {
match self {
Self::Disconnected => "tsunagi: not connected",
Self::Connected => "tsunagi: connected",
Self::InterfaceError => "tsunagi: overlay interface configuration failed",
Self::RangeConflict => "tsunagi: network range conflict; open to switch networks",
Self::ExitNode => "tsunagi: using an exit node",
}
@@ -118,6 +124,15 @@ mod tests {
}
}
#[test]
fn a_host_interface_error_is_visible_even_with_connected_peers() {
let mut status = report(vec![network(2, ExitReport::default())]);
status.overlay_config_error = Some("utun5: could not install subnet route".into());
assert_eq!(Health::of(Some(&status)), Health::InterfaceError);
status.overlay_config_error = None;
assert_eq!(Health::of(Some(&status)), Health::Connected);
}
#[test]
fn overlapping_networks_are_visible_even_while_other_peers_are_connected() {
let mut blocked = NetworkReport {
+35 -31
View File
@@ -52,6 +52,8 @@ struct Device<'a> {
data_error: Option<&'a str>,
address: Option<String>,
control_rtt_ms: Option<u64>,
data_rtt_ms: Option<u64>,
data_transport_detail: Option<&'a str>,
overlay: Option<&'a OverlayPeerReport>,
/// It is connected and offers to be an exit node.
exit_node: bool,
@@ -438,14 +440,9 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
.map(|id| {
let overlay = overlay_peers.iter().find(|p| p.endpoint_id == id);
let member = network.members.iter().find(|m| m.endpoint_id == id);
let online = member.is_some_and(|m| m.online)
|| network.peers.iter().any(|p| p.endpoint_id == id);
let path = network
.peers
.iter()
.find(|p| p.endpoint_id == id)
.map(|p| &p.path)
.or_else(|| member.map(|m| &m.path));
let peer = network.peers.iter().find(|p| p.endpoint_id == id);
let online = member.is_some_and(|m| m.online) || peer.is_some();
let path = peer.map(|p| &p.path).or_else(|| member.map(|m| &m.path));
let via_name = match path {
Some(DataPathReport::Relayed { via, .. }) => Some(exit::name_of(network, via)),
_ => None,
@@ -465,25 +462,15 @@ fn devices<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<Device<'a>> {
hostname,
copy: hostname.map(|h| format!("{h}.{}", network.name)),
id,
data_error: network
.peers
.iter()
.find(|p| p.endpoint_id == id)
.and_then(|p| p.data_error.as_deref()),
data_error: peer.and_then(|p| p.data_error.as_deref()),
address: overlay
.and_then(|p| p.address.clone())
.or_else(|| member.and_then(|m| m.overlay_address_v4.clone())),
control_rtt_ms: network
.peers
.iter()
.find(|p| p.endpoint_id == id)
.and_then(|p| p.rtt_ms),
control_rtt_ms: peer.and_then(|p| p.rtt_ms),
data_rtt_ms: peer.and_then(|p| p.data_rtt_ms),
data_transport_detail: peer.and_then(|p| p.data_transport_detail.as_deref()),
overlay,
exit_node: online
&& network
.peers
.iter()
.any(|p| p.endpoint_id == id && p.exit_node),
exit_node: peer.is_some_and(|p| p.exit_node),
in_use: network.exit.via.as_deref() == Some(id),
}
})
@@ -501,7 +488,7 @@ const COLUMN_HEADERS: [&str; 10] = [
"device",
"exit",
"data",
"RTT",
"RTT data / control",
"address",
"data path",
"pkts",
@@ -647,7 +634,7 @@ fn device_table(
let (path, _) = data_path_text(device.path, device.via_name.as_deref(), device.online);
for (column, text) in [
(2, "waiting".to_owned()),
(3, rtt_text(device.control_rtt_ms)),
(3, rtt_pair(device)),
(4, device.address.clone().unwrap_or_default()),
(5, path),
] {
@@ -728,8 +715,9 @@ fn device_table(
1 => exit_cell(ui, device, network_id, confirm),
2 => tunnel_cell(ui, device),
3 => {
ui.label(rtt_text(device.control_rtt_ms))
.on_hover_text("Control-connection round-trip time.");
ui.label(rtt_pair(device)).on_hover_text(
"Median authenticated direct data-link RTT / selected control-connection RTT. A dash means there is no current measurement.",
);
}
4 => match &device.address {
Some(address) => format::copy_field(ui, address, address),
@@ -791,11 +779,18 @@ fn device_table(
);
}
/// Control RTT is independent of the hidden internal cipher's handshake age.
fn rtt_text(rtt: Option<u64>) -> String {
rtt.map_or_else(|| "—".into(), |value| format!("{value} ms"))
}
fn rtt_pair(device: &Device<'_>) -> String {
format!(
"{} / {}",
rtt_text(device.data_rtt_ms),
rtt_text(device.control_rtt_ms)
)
}
fn tunnel_cell(ui: &mut egui::Ui, device: &Device<'_>) {
let ready = device.overlay.is_some_and(|peer| peer.is_up())
&& !matches!(device.path, None | Some(DataPathReport::None));
@@ -855,7 +850,9 @@ fn data_path_cell(ui: &mut egui::Ui, device: &Device<'_>) {
)
};
response.on_hover_text(match device.path {
Some(DataPathReport::Direct { .. }) => "Direct transport; no mesh relay.",
Some(DataPathReport::Direct { .. }) => device
.data_transport_detail
.unwrap_or("Direct link to this member."),
Some(DataPathReport::Relayed { .. }) => "Traffic forwarded through another device.",
_ if device.online => "Control connected; data transport unavailable.",
_ => "Unreachable.",
@@ -1110,6 +1107,8 @@ mod tests {
data_error: None,
endpoint_id: "peer".into(),
rtt_ms: Some(27),
data_rtt_ms: Some(203),
data_transport_detail: Some("relay via relay.example".into()),
..Default::default()
}],
overlay: Some(OverlayReport {
@@ -1125,6 +1124,11 @@ mod tests {
};
let rows = devices(&network, "own");
assert_eq!(rtt_text(rows[0].control_rtt_ms), "27 ms");
assert_eq!(rtt_text(rows[0].data_rtt_ms), "203 ms");
assert_eq!(
rows[0].data_transport_detail,
Some("relay via relay.example")
);
assert_eq!(rtt_text(None), "—");
}
@@ -1231,8 +1235,8 @@ mod tests {
let mut texts = Vec::new();
collect_text(&shapes, &mut texts);
for (label, next_column) in [
("RTT".to_string(), "address"),
(rtt_text(Some(12_345)), "address"),
("RTT data / control".to_string(), "address"),
(rtt_pair(&rows[0]), "address"),
(format!("{packets}/{}", packets + 1), "bytes"),
(format!("{}/{}", packets * 2, (packets + 1) * 2), "bytes"),
] {
+12 -2
View File
@@ -35,7 +35,7 @@ pub(super) fn roster(
let size = egui::vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 8.0);
ui.spacing_mut().item_spacing.y = 1.0;
let (header, _) = ui.allocate_exact_size(size, egui::Sense::hover());
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "RTT"]) {
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "Data RTT"]) {
ui.painter().text(
header.left_center() + egui::vec2(x, 0.),
egui::Align2::LEFT_CENTER,
@@ -73,7 +73,7 @@ pub(super) fn roster(
);
}
let name = member.name();
let rtt = rtt_text(member.control_rtt_ms);
let rtt = rtt_text(member.data_rtt_ms);
let labels = [
name.as_str(),
member.address.as_deref().unwrap_or("—"),
@@ -148,6 +148,16 @@ fn details(
ui.label(path);
tunnel_cell(ui, member);
});
if member.online {
if let Some(path) = member.data_transport_detail {
ui.label(path);
}
ui.label(format!(
"Data RTT {} · Control RTT {}",
rtt_text(member.data_rtt_ms),
rtt_text(member.control_rtt_ms)
));
}
if let Some(error) = member.data_error {
ui.colored_label(AMBER, error);
}
+4 -3
View File
@@ -18,7 +18,7 @@ pub fn choose_exit(ui: &mut Ui, network: &NetworkReport, own: &str) -> Option<Ex
let muted = ui.visuals().weak_text_color();
for (x, label) in [
(columns.name, "Exit node"),
(columns.rtt, "RTT"),
(columns.rtt, "Data RTT"),
(columns.path, "Path"),
] {
ui.painter().text(
@@ -83,7 +83,7 @@ pub fn choose_exit(ui: &mut Ui, network: &NetworkReport, own: &str) -> Option<Ex
peer: Some(candidate.id),
name: &name,
address: candidate.address.as_deref(),
rtt: candidate.control_rtt_ms,
rtt: candidate.data_rtt_ms,
path,
transport,
selected: candidate.in_use,
@@ -224,7 +224,8 @@ mod tests {
network.peers.push(PeerReport {
endpoint_id: id.into(),
hostname: Some(name.into()),
rtt_ms: Some(37),
data_rtt_ms: Some(37),
rtt_ms: Some(142),
path: DataPathReport::Direct {
transport: "wg".into(),
},
+4 -1
View File
@@ -105,6 +105,9 @@ pub fn draw_header(
"cache unavailable",
);
}
if let Some(error) = &report.overlay_config_error {
ui.colored_label(BAD, format!("Shared overlay interface {error}"));
}
}
/// One compact network tile.
@@ -278,7 +281,7 @@ fn draw_protocols(
egui::CollapsingHeader::new(format!("data transports {summary}"))
.id_salt(("protocols", &network.network_id))
.show(ui, |ui| {
ui.weak("Preference order; changes apply immediately and are saved.");
ui.weak("Order sets the first choice. Peers that support link comparison can switch to a faster enabled transport.");
let mut selected = network.protocols.clone();
let mut changed = false;
ui.add_enabled_ui(!agent.busy(), |ui| {
+139 -11
View File
@@ -8,6 +8,8 @@ use std::{
time::Duration,
};
use tempfile::TempDir;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tsunagi::dataplane::transport::{DataCarrier, PacketTransport, SharedLink, TransportError};
use tsunagi::discovery::SharedMemoryDiscovery;
use tsunagi::overlay::{MemoryTun, MemoryTunFactory};
@@ -64,11 +66,11 @@ impl Node {
protocol: &str,
ports: Arc<std::sync::Mutex<Vec<(EndpointId, u16)>>>,
) -> Self {
Self::configured(discovery, protocol, ports, true).await
Self::configured(discovery, &[protocol], ports, true).await
}
async fn configured(
discovery: &SharedMemoryDiscovery,
protocol: &str,
protocols: &[&str],
ports: Arc<std::sync::Mutex<Vec<(EndpointId, u16)>>>,
register_transport: bool,
) -> Self {
@@ -89,6 +91,7 @@ impl Node {
let config = config_with(root.path(), discovery)
.with_interface(Arc::new(tuns.clone()), "carrier-test", 1280)
.with_tunnel(tunnel.clone());
let protocol = protocols[0];
let (agent, accept) = if protocol == "wg" {
let transport =
UdpTransport::wireguard(identity.endpoint_id(), Ipv4Addr::LOCALHOST, None);
@@ -120,13 +123,15 @@ impl Node {
inner: transport.clone(),
ports,
});
let agent = Agent::spawn(
config
.with_carrier(carrier)
.with_custom_transport(protocol, custom),
)
.await
.unwrap();
let mut config = config
.with_carrier(carrier)
.with_custom_transport(protocol, custom);
if protocols.contains(&"wg-quic") {
config = config.with_carrier(Arc::new(
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
));
}
let agent = Agent::spawn(config).await.unwrap();
let incoming = agent.clone();
let accept = tokio::spawn(async move {
transport
@@ -162,12 +167,135 @@ impl Node {
}
}
// Real TLS bytes flow through this loopback proxy. Delay one direction so
// authenticated probes can distinguish two otherwise healthy carriers.
async fn delayed_tcp_listener(port: u16) -> (u16, tokio::task::JoinHandle<()>) {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let local_port = listener.local_addr().unwrap().port();
let task = tokio::spawn(async move {
let mut streams = tokio::task::JoinSet::new();
while let Ok((client, _)) = listener.accept().await {
streams.spawn(async move {
let server = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).await?;
let (mut from_client, mut to_client) = client.into_split();
let (mut from_server, mut to_server) = server.into_split();
let delayed = async {
let mut buffer = [0; 8192];
loop {
let n = from_client.read(&mut buffer).await?;
if n == 0 {
return Ok::<(), std::io::Error>(());
}
tokio::time::sleep(Duration::from_millis(85)).await;
to_server.write_all(&buffer[..n]).await?;
}
};
tokio::select! {
res = delayed => res,
res = tokio::io::copy(&mut from_server, &mut to_client) => res.map(|_| ()),
}
});
}
});
(local_port, task)
}
#[tokio::test]
async fn data_flows_over_the_incumbent_while_a_faster_carrier_is_measured_and_promoted() {
use tsunagi::agent::{DataPath, Event};
let discovery = SharedMemoryDiscovery::new();
let ports = Arc::default();
let protocols = ["tcp-tls", "wg-quic"];
let a = Node::configured(&discovery, &protocols, Arc::clone(&ports), true).await;
let b = Node::configured(&discovery, &protocols, Arc::clone(&ports), true).await;
let mut proxies = Vec::new();
let registered = ports.lock().unwrap().clone();
for (peer, port) in registered {
let (proxy_port, task) = delayed_tcp_listener(port).await;
proxies.push(task);
ports
.lock()
.unwrap()
.iter_mut()
.find(|(id, _)| *id == peer)
.unwrap()
.1 = proxy_port;
}
let mut events = a.agent.subscribe();
let (name, secret) = network("measured-carrier");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
let observations = |node: &Node| {
let overview = node.tunnel.overview(id)?;
let tunnel = overview.peers.first()?.tunnel.as_ref()?;
tunnel.health.is_up().then_some(tunnel.stats.counter_epoch)
};
let epochs = wait_until(
"both endpoints have a single established cipher",
|| async { Some((observations(&a)?, observations(&b)?)) },
)
.await;
let selected = |protocol: &str, status: &tsunagi::NetworkStatus| {
matches!(status.peers.first().map(|p| &p.data_path),
Some(DataPath::Direct { transport }) if transport == protocol)
};
async fn deliver(source: &Node, destination: &Node, id: NetworkId, tag: u8) {
let mut packet = vec![0; 32];
packet[0] = 0x45;
packet[2..4].copy_from_slice(&32_u16.to_be_bytes());
packet[8] = 64;
packet[9] = 253;
packet[12..16].copy_from_slice(&source.addr(id).octets());
packet[16..20].copy_from_slice(&destination.addr(id).octets());
packet[20] = tag;
let packet = Bytes::from(packet);
source.tun().push_from_os(packet.clone());
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), destination.tun().pop_to_os())
.await
.unwrap()
.unwrap(),
packet
);
}
tokio::time::timeout(Duration::from_secs(60), async {
wait_until("slow TLS data-link probes are visible", || async {
let status = a.agent.network_status(id).await.ok()?;
(selected("tcp-tls", &status) && status.peers.first()?.data_rtt? >= Duration::from_millis(75)).then_some(())
}).await;
deliver(&a, &b, id, 1).await;
tsunagi::testing::wait_event(&mut events, |event| {
matches!(event, Event::DataLinkUp { network, protocol, .. } if *network == id && protocol == "wg-quic").then_some(())
}).await;
for (source, dest) in [(&a, &b), (&b, &a)] {
assert!(selected("tcp-tls", &source.agent.network_status(id).await.unwrap()));
deliver(source, dest, id, 2).await;
}
wait_until("both endpoints use the faster measured data link", || async {
let left = a.agent.network_status(id).await.ok()?;
let right = b.agent.network_status(id).await.ok()?;
(selected("wg-quic", &left) && selected("wg-quic", &right)).then_some(())
}).await;
for (source, dest) in [(&a, &b), (&b, &a)] {
deliver(source, dest, id, 3).await;
}
assert_eq!((observations(&a), observations(&b)), (Some(epochs.0), Some(epochs.1)));
}).await.expect("comparison must finish with traffic on the existing tunnel");
a.agent.shutdown().await;
b.agent.shutdown().await;
a.accept.abort();
b.accept.abort();
for proxy in proxies {
proxy.abort();
}
}
#[tokio::test]
async fn missing_native_transport_cannot_silently_turn_wireguard_into_quic() {
let discovery = SharedMemoryDiscovery::new();
let ports = Arc::default();
let a = Node::configured(&discovery, "wg", Arc::clone(&ports), false).await;
let b = Node::configured(&discovery, "wg", ports, false).await;
let a = Node::configured(&discovery, &["wg"], Arc::clone(&ports), false).await;
let b = Node::configured(&discovery, &["wg"], ports, false).await;
let (name, secret) = network("no-disguised-quic-fallback");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
@@ -42,6 +42,8 @@ fn source(agent: Agent, plugin: Arc<WireguardPlugin>) -> Arc<dyn tsunagi::ipc::R
hostname: peer.hostname.clone(),
transport: format!("{:?}", peer.transport),
rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64),
data_rtt_ms: peer.data_rtt.map(|rtt| rtt.as_millis() as u64),
data_transport_detail: peer.data_transport_detail.clone(),
exit_node: peer.exit_node,
path: Default::default(),
})
+19
View File
@@ -1133,6 +1133,25 @@ async fn two_networks_share_one_interface_with_keys_and_ranges_of_their_own() {
"the other overlay must see nothing"
);
for (network, local, remote) in [(alpha, hub_alpha, &left), (beta, hub_beta, &right)] {
let address = remote.overlay(network).await;
for (sender, source, receiver, destination) in [
(&hub, local, remote, address),
(remote, address, &hub, local),
] {
let packet = ipv4_packet(source, destination, network.as_bytes());
sender.tun(network).await.push_from_os(packet.clone());
let received = tokio::time::timeout(
tsunagi::testing::DEADLINE,
receiver.tun(network).await.pop_to_os(),
)
.await
.expect("bidirectional traffic on both networks")
.unwrap();
assert_eq!(received, packet);
}
}
hub.shutdown().await;
left.shutdown().await;
right.shutdown().await;
+47 -8
View File
@@ -106,7 +106,7 @@ struct DnsArgs {
#[derive(Debug, Args)]
#[command(
after_help = "Examples:\n tsng protocols\n tsng protocols home\n tsng protocols home awg,wg-quic\n tsng protocols home none\n\nThe selection is local to this device, saved per network and applied immediately.\nThe choice governs local incoming and outgoing data links only.
Adjacent peers need a common external transport; control and discovery are independent."
The order sets the first choice. Peers that support link comparison can switch to a faster mutually enabled transport."
)]
struct ProtocolsArgs {
#[command(flatten)]
@@ -116,7 +116,7 @@ struct ProtocolsArgs {
control_socket: Option<PathBuf>,
/// Network's exact name, id or unique id prefix.
network: Option<String>,
/// Replace the selection, best first: awg,wg-quic; none disables data traffic.
/// Replace the enabled transports in initial preference order. Use none for control only.
#[arg(value_name = "LIST", requires = "network")]
protocols: Option<String>,
}
@@ -486,7 +486,7 @@ struct UpArgs {
#[arg(long, help_heading = "System")]
no_tun: bool,
/// Initial protocol selection for networks without a saved choice, best first.
/// Enabled transports in initial preference order for networks without a saved choice.
///
/// A pair of peers uses one they both have at the same wire version. A
/// peer with none in common keeps its control plane and gets no data
@@ -1995,7 +1995,7 @@ async fn protocols_command(args: ProtocolsArgs) -> Result<(), Box<dyn std::error
None => network.protocols.clone(),
};
println!(
"protocols {} for `{}` ({}) · preference order",
"protocols {} for `{}` ({}) · initial preference order",
if protocols.is_empty() {
"none".into()
} else {
@@ -2624,8 +2624,11 @@ async fn exit_node_command(args: ExitNodeArgs) -> Result<(), Box<dyn std::error:
any = true;
let in_use = network.exit.via.as_deref() == Some(peer.endpoint_id.as_str());
let mut detail = format!("network {}", network.name);
if let Some(rtt) = peer.data_rtt_ms {
detail.push_str(&format!(" · data RTT {rtt}ms"));
}
if let Some(rtt) = peer.rtt_ms {
detail.push_str(&format!(" · rtt {rtt}ms"));
detail.push_str(&format!(" · control RTT {rtt}ms"));
}
if in_use {
detail.push_str(" · IN USE");
@@ -3239,6 +3242,13 @@ async fn status(args: StatusArgs) -> Result<(), Box<dyn std::error::Error>> {
Row::new(Health::Degraded, "cache", "unavailable")
.with_note("disposable: the agent runs, rediscovering what it cached")
});
if let Some(error) = &report.overlay_config_error {
agent.push(Row::new(
Health::Degraded,
"shared overlay interface",
error,
));
}
}
Observed::Stored {
why,
@@ -3398,6 +3408,8 @@ struct MemberRow<'a> {
/// that control connection reaches the peer.
transport: Option<&'a str>,
rtt_ms: Option<u64>,
data_rtt_ms: Option<u64>,
data_transport_detail: Option<&'a str>,
overlay_address_v4: Option<&'a str>,
tunnel: Option<&'a tsunagi::ipc::OverlayPeerReport>,
failed_dials: u32,
@@ -3440,6 +3452,8 @@ fn member_rows<'a>(network: &'a tsunagi::ipc::NetworkReport, own_id: &str) -> Ve
name_taken: None,
transport: None,
rtt_ms: None,
data_rtt_ms: None,
data_transport_detail: None,
overlay_address_v4: None,
tunnel: None,
failed_dials: 0,
@@ -3469,6 +3483,8 @@ fn member_rows<'a>(network: &'a tsunagi::ipc::NetworkReport, own_id: &str) -> Ve
row.path = Some(&peer.path);
row.transport = Some(&peer.transport);
row.rtt_ms = peer.rtt_ms;
row.data_rtt_ms = peer.data_rtt_ms;
row.data_transport_detail = peer.data_transport_detail.as_deref();
row.data_error = peer.data_error.as_deref();
}
if let Some(overlay) = &network.overlay {
@@ -3873,11 +3889,14 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
detail.push_str(&format!("{v4:<15} "));
}
detail.push_str(&path);
if let Some(rtt) = row.data_rtt_ms {
detail.push_str(&format!(" data RTT {rtt}ms"));
}
if let Some(transport) = row.transport {
detail.push_str(&format!(" · control path {}", transport.to_lowercase()));
}
if let Some(rtt) = row.rtt_ms {
detail.push_str(&format!(" rtt {rtt}ms"));
detail.push_str(&format!(" control RTT {rtt}ms"));
}
if row.exit_in_use {
detail.push_str(" · your exit node");
@@ -3896,6 +3915,9 @@ 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 {
out = out.with_note(path.to_owned());
}
if let Some(tunnel) = row.tunnel {
out = out.with_note(match tunnel.handshake_secs_ago {
Some(_) => format!(
@@ -3909,7 +3931,7 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
} else {
String::new()
},
tunnel.path
row.data_transport_detail.unwrap_or(&tunnel.path)
),
None => "encrypted data channel is not ready yet".into(),
});
@@ -4707,7 +4729,7 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
println!(" endpoint id {}", agent.endpoint_id());
println!(" hostname {}", agent.hostname());
println!(
" protocols {} (priority order)",
" protocols {} (initial preference order)",
protocol_names.join(", ")
);
// What this device belongs to is a separate question from whether its
@@ -4839,6 +4861,7 @@ async fn build_report(
let networks = tsunagi_runtime::report::networks(&status, overlay.as_ref(), wireguard);
StatusReport {
overlay_config_error: overlay.and_then(|state| state.address_error),
available_protocols: PROTOCOLS
.iter()
.map(|p| tsunagi::ipc::ProtocolReport {
@@ -5179,6 +5202,8 @@ mod status_tests {
hostname: Some("music".into()),
transport: "direct".into(),
rtt_ms: Some(24),
data_rtt_ms: None,
data_transport_detail: None,
exit_node: false,
path: tsunagi::ipc::DataPathReport::Direct {
transport: "wg".into(),
@@ -5709,6 +5734,20 @@ mod status_tests {
assert!(out.render(false).contains("control path relay"));
}
#[test]
fn data_and_control_latency_are_reported_separately_before_tunnel_traffic() {
let mut network = network_after_a_peer_returned();
network.overlay = None;
network.peers[0].data_rtt_ms = Some(203);
network.peers[0].data_transport_detail = Some("relay via relay.example".into());
let mut out = report::Report::new();
out.push(network_section(&network, OWN, false));
let text = out.render(false);
assert!(text.contains("data RTT 203ms"), "{text}");
assert!(text.contains("control RTT 24ms"), "{text}");
assert!(text.contains("relay via relay.example"), "{text}");
}
#[test]
fn a_tunnel_that_never_handshook_is_flagged_while_the_peer_is_connected() {
let mut network = network_after_a_peer_returned();
+3 -2
View File
@@ -120,9 +120,10 @@ carrier change. Status and the tray show the actual external transport or relay
route and data readiness. There is no user-selectable internal cipher.
The internal capability is `wireguard-e2e` v4; external `wg` and `awg` use v2,
`wg-quic` v1 and `tcp-tls` v2. All members must upgrade together. Control ALPN
`wg-quic` v1 and `tcp-tls` v2, as in 1.0.1. Control ALPN
`tsunagi/ctrl/8`, discovery, membership and signed state are unchanged. The data
ALPN is `tsunagi/data/6`; the relay envelope format is unchanged. Local IPC is v23,
ALPN is `tsunagi/data/6`; the relay envelope format is unchanged. Automatic
carrier comparisons are optional on the mesh wire. Local IPC is v24,
so agent, CLI and tray must match. Historical `wg-quic/wireguard.sqlite` is the
canonical internal key store. Missing keys are imported transactionally from
`wg` then `awg`, without replacing an existing canonical key or modifying a
+9
View File
@@ -162,6 +162,15 @@ channel is declined, which is an ordinary outcome rather than an error.
Only one side dials — the one with the smaller endpoint id — so two agents
never open two channels for the same thing.
The optional `link-choice` v1 capability lets this dialler compare a second
mutually enabled carrier. An authenticated `Transport` message named
`link-choice` contains two 16-byte identifiers from the private link-health
profiles, in keep/retire order. The responder selects the surviving carrier
and echoes the decision. The dialler keeps accepting traffic on the former
carrier until confirmation or closure. Choices apply to one peer and network
and expire with the link generations. Peers without the capability use the
original carrier negotiation.
Packets ride as QUIC **datagrams**: unreliable and unordered, which is what a
tunnelled protocol wants, and free of the head-of-line blocking a stream would
add. `max_datagram` negotiates the reassembled payload limit (at most 65536
+22 -5
View File
@@ -18,9 +18,11 @@ Each authenticated control session advertises that peer's own direct data
links. There is one table for each network, whatever protocols run over it: a
link is a way to reach a neighbour, while the single internal protocol is an
end-to-end tunnel to a peer. The envelope names the protocol, so the two are independent. A neighbour
reached over several kinds of transport (UDP, TCP, QUIC datagrams) is sent to
over the best open one, in the order the protocols were configured, and over
the next if that one fails or cannot carry the frame. Every authenticated
reached over several kinds of transport (UDP, TCP, QUIC datagrams) receives
traffic over the selected link. Another open link can carry the frame if
the selected link fails or its MTU is too small. The configured order
selects the initial link. Peers with automatic carrier selection can then
prefer a faster measured link for that neighbour. Every authenticated
member enters the graph; a member in the middle needs no protocol in common
with either end, only a link to each. A snapshot refreshes on the maintenance
interval, expires after 90 seconds, and is withdrawn when the session ends.
@@ -33,7 +35,7 @@ capability and independent of the selected external protocols. The tunnel is
created when a member and its key are known; its logical link survives temporary
loss of all physical paths. Carrier selection changes, automatic fallback and
shorter routes keep the same keys, interface and counters. The lower endpoint
id still chooses the mutually enabled external carrier in its preference order.
id chooses among the mutually enabled external carriers.
A relayed AWG first hop can lead to a QUIC next hop: the user's choice governs
this device's adjacent links, while the inner ciphertext stays unchanged.
An existing TCP connection continues after transient loss if its own timeout
@@ -100,6 +102,20 @@ Logical peer links and end-to-end encryption state survive these changes.
## Carrier health and switching
Two peers advertising `link-choice` v1 automatically compare carriers. The
lower endpoint id opens one alternative while the established carrier keeps
serving traffic. At most two comparisons start concurrently per network. Each
peer pair rotates through its alternatives, with a two-minute interval after
a trial. A failed active link still triggers immediate fallback.
The measurements use authenticated round trips over the data carrier. After
at least six seconds and five successful probes on each link, the alternative
must have zero observed loss in its window and a median RTT improvement of
at least 20% and 5 ms. Otherwise traffic stays on the incumbent. The agents
coordinate retirement over their authenticated control session. An older peer
continues using the configured order and failure recovery. One enabled carrier
restricts the pair to that carrier.
Carrier setup failures and persistent encrypted delivery loss advance the
initiator's ordered fallback cycle. Logical end-to-end links survive while
physical links are retired explicitly. The AWG carrier negotiates a fresh
@@ -127,4 +143,5 @@ end-to-end network latency or VPN throughput; encryption, fragmentation,
sockets, congestion and scheduling contribute separately.
Wire compatibility: control ALPN `tsunagi/ctrl/8`, data ALPN `tsunagi/data/6`.
Upgrade every participant together; saved identities and network state persist.
Version 1.0.2 interoperates with 1.0.1 peers using these wire versions.
Saved identities and network state persist.
+6 -2
View File
@@ -50,7 +50,8 @@ boringtun, with an in-memory TUN device so none of it needs privileges. It
covers real IPv6 packets travelling both ways through a tunnel, a three-agent
mesh, a peer that sends from an address it does not own being dropped, packets
for unowned addresses being counted rather than broadcast, a departing peer
losing its tunnel, two networks keeping separate interfaces and keys, restart
losing its tunnel, two networks exchanging traffic in both directions over one
shared interface with separate addresses and keys, restart
keeping the WireGuard identity, shutdown removing every interface, a forged
overlay claim being rejected, and the core carrying the payload without
interpreting it.
@@ -257,7 +258,10 @@ histories. These are headless egui checks, not native desktop screenshots.
`tsunagi-wg-quic/tests/carriers.rs` uses the same internal WireGuard plugin over
real ordinary WG UDP and TCP/TLS, with loopback address selection and memory
TUNs. Exact original IP byte/packet counts exclude health probes and encryption
overhead. The AWG suite connects AWG-only and QUIC-only endpoints through a
overhead. An artificial delay on a real TCP/TLS link exercises automatic
selection of a faster QUIC carrier. Both endpoints exchange packets across the
transition and retain their original encrypted tunnels. The AWG suite connects
AWG-only and QUIC-only endpoints through a
mixed relay. One real smoltcp TCP connection stays established through relay →
direct QUIC → a dropped packet with all local carriers off → AWG relay; both
middle TUNs and endpoint keys are checked. This exercises a real userspace TCP
+10
View File
@@ -58,3 +58,13 @@ wire formats are unchanged. The rootless real-endpoint regression is
`crates/tsunagi-core/tests/iroh_candidates.rs`; overlay subnet filtering for
introductions is also covered in the core. This prevents the recursive path;
it does not prove the historical cause of any particular high byte counter.
## Changes to the owned overlay interface
The optional `Builder::network_change_filter` receives consecutive netwatch
snapshots before iroh rechecks paths and rebinds sockets. Tsunagi suppresses
events caused solely by its own TUN. Adding a second network can then add an
address to the shared interface while the first network keeps its UDP sockets.
Physical interface changes, default-route changes and resume events still
reach iroh. The watcher advances its baseline even for a skipped event.
Keep this behaviour when updating the vendored dependency.
+21 -1
View File
@@ -127,7 +127,7 @@ pub use crate::{net_report::NetReportConfig, portmapper::PortmapperConfig};
/// new [`EndpointId`].
///
/// To create the [`Endpoint`] call [`Builder::bind`].
#[derive(Debug)]
#[derive(derive_more::Debug)]
pub struct Builder {
secret_key: Option<SecretKey>,
alpn_protocols: Vec<Vec<u8>>,
@@ -139,6 +139,8 @@ pub struct Builder {
/// [`Builder::address_lookup`].
addr_filter: Option<AddrFilter>,
direct_addr_filter: Option<AddrFilter>,
#[debug(skip)]
network_change_filter: Option<socket::NetworkChangeFilter>,
proxy_url: Option<Url>,
ca_tls_config: Option<CaTlsConfig>,
#[cfg(not(wasm_browser))]
@@ -208,6 +210,7 @@ impl Builder {
address_lookup_user_data: Default::default(),
addr_filter: None,
direct_addr_filter: None,
network_change_filter: None,
proxy_url: None,
ca_tls_config: None,
#[cfg(not(wasm_browser))]
@@ -274,6 +277,7 @@ impl Builder {
let sock_opts = socket::Options {
direct_addr_filter: self.direct_addr_filter,
network_change_filter: self.network_change_filter,
transports: self.transports,
secret_key,
address_lookup_user_data: self.address_lookup_user_data,
@@ -636,6 +640,22 @@ impl Builder {
self
}
/// Filters OS network changes before rechecking paths and rebinding transports.
///
/// Return false only when the change cannot affect this endpoint's underlay,
/// for example when an application adds an address to its own overlay interface.
/// The next change is compared with the latest snapshot even if this one is ignored.
pub fn network_change_filter(
mut self,
filter: impl Fn(&netwatch::netmon::State, &netwatch::netmon::State) -> bool
+ Send
+ Sync
+ 'static,
) -> Self {
self.network_change_filter = Some(Box::new(filter));
self
}
/// Clears the address filter, allowing all addresses to be published.
///
/// This removes any filter previously set via [`Self::addr_filter`], including
+18 -3
View File
@@ -157,10 +157,15 @@ impl From<mpsc::error::SendError<RemoteStateMessage>> for RemoteStateActorStoppe
}
}
pub(crate) type NetworkChangeFilter =
Box<dyn Fn(&netmon::State, &netmon::State) -> bool + Send + Sync>;
/// Contains options for `Socket::listen`.
#[derive(derive_more::Debug)]
pub(crate) struct Options {
pub(crate) direct_addr_filter: Option<address_lookup::AddrFilter>,
#[debug(skip)]
pub(crate) network_change_filter: Option<NetworkChangeFilter>,
/// The configuration for the different transports.
pub(crate) transports: Vec<TransportConfig>,
@@ -883,6 +888,7 @@ impl EndpointInner {
let Options {
direct_addr_filter,
network_change_filter,
secret_key,
transports: transport_configs,
address_lookup_user_data,
@@ -1093,6 +1099,7 @@ impl EndpointInner {
periodic_re_stun_timer: new_re_stun_timer(false),
network_monitor,
local_interfaces_watcher,
network_change_filter,
direct_addr_update_state,
transports_network_change,
direct_addr_done_rx,
@@ -1475,6 +1482,7 @@ struct Actor {
network_monitor: netmon::Monitor,
/// Watcher for changes to the local network interfaces, IP addresses and routes.
local_interfaces_watcher: n0_watcher::Direct<netmon::State>,
network_change_filter: Option<NetworkChangeFilter>,
transports_network_change: transports::NetworkChangeSender,
/// Indicates the direct addr update state.
direct_addr_update_state: DirectAddrUpdateState,
@@ -1608,14 +1616,19 @@ impl Actor {
self.sock.metrics.socket.actor_tick_other.inc();
continue;
};
let is_major = state.is_major_change(&current_netmon_state);
let previous = std::mem::replace(&mut current_netmon_state, state);
if let Some(filter) = &self.network_change_filter
&& !filter(&previous, &current_netmon_state)
{
continue;
}
let is_major = current_netmon_state.is_major_change(&previous);
event!(
target: "iroh::_events::link_change",
Level::DEBUG,
?state,
state = ?current_netmon_state,
is_major
);
current_netmon_state = state;
self.sock.metrics.socket.actor_link_change.inc();
self.handle_network_change(is_major);
}
@@ -2192,6 +2205,7 @@ mod tests {
static_config,
configured_addrs: Default::default(),
direct_addr_filter: None,
network_change_filter: None,
}
}
@@ -2609,6 +2623,7 @@ mod tests {
static_config,
configured_addrs: Default::default(),
direct_addr_filter: None,
network_change_filter: None,
};
let sock = EndpointInner::bind(opts).await?;
Ok(sock)