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

+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]