use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6};
use std::num::NonZeroU32;
use std::time::Duration;
use socket2::{Domain, Socket, Type};
use tokio::net::{TcpSocket, TcpStream, UdpSocket};
use crate::logging::info;
use crate::system::descriptors;
use crate::system::interface::{Link, LinkAddress};
#[cfg(any(windows, test))]
mod syn_retries;
mod allowance;
pub(crate) use allowance::PathAllowance;
#[cfg(test)]
pub(crate) use allowance::UNMEASURED_PATH_WAIT;
#[cfg(test)]
pub(crate) mod dialled {
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{LazyLock, Mutex};
static DIALLED: LazyLock<Mutex<HashMap<SocketAddr, usize>>> = LazyLock::new(Mutex::default);
pub(super) fn note(addr: SocketAddr) {
*DIALLED.lock().unwrap().entry(addr).or_default() += 1;
}
pub(crate) fn to(addr: SocketAddr) -> usize {
DIALLED.lock().unwrap().get(&addr).copied().unwrap_or(0)
}
static REFUSED: LazyLock<Mutex<HashMap<SocketAddr, (i32, usize)>>> =
LazyLock::new(Mutex::default);
#[cfg(unix)]
pub(crate) fn refuse(addr: SocketAddr, code: i32, times: usize) {
REFUSED.lock().unwrap().insert(addr, (code, times));
}
pub(super) fn refusal(addr: SocketAddr) -> Option<std::io::Error> {
let mut refused = REFUSED.lock().unwrap();
let (code, times) = refused.get_mut(&addr).filter(|(_, times)| *times > 0)?;
*times -= 1;
Some(std::io::Error::from_raw_os_error(*code))
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct Shaping {
pub(crate) source_port: Option<u16>,
pub(crate) hop_limit: Option<u8>,
}
impl Shaping {
pub(crate) fn is_active(self) -> bool {
self.source_port.is_some() || self.hop_limit.is_some()
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct ForcedSources {
pins: Vec<Pin>,
held: Vec<LinkAddress>,
}
impl ForcedSources {
pub(crate) fn new(forced: &[IpAddr]) -> Self {
if forced.is_empty() {
return Self::default();
}
let sources = Self::with_links(forced, &crate::system::interface::interfaces_or_none());
for pin in &sources.pins {
match pin.interface {
Some(index) => info!(
verbosity = 1,
"connections to routed targets leave from {} on interface {index}", pin.source
),
None => info!(
verbosity = 1,
"no interface holds {}, so connections forced to it will fail", pin.source
),
}
}
sources
}
fn with_links(forced: &[IpAddr], links: &[Link]) -> Self {
let mut pins: Vec<Pin> = Vec::new();
for &source in forced {
if pins
.iter()
.any(|pin| pin.source.is_ipv4() == source.is_ipv4())
{
continue;
}
let interface = links
.iter()
.find(|link| link.addresses().iter().any(|held| held.address() == source))
.and_then(|link| NonZeroU32::new(link.index()));
pins.push(Pin { source, interface });
}
let held = links
.iter()
.filter(|link| link.is_up() && !link.is_loopback())
.flat_map(|link| link.addresses().iter().copied())
.collect();
Self { pins, held }
}
pub(crate) fn toward(&self, target: IpAddr) -> Egress {
let Some(pin) = self
.pins
.iter()
.find(|pin| pin.source.is_ipv4() == target.is_ipv4())
else {
return Egress::KERNEL;
};
let reached_directly = target.is_loopback()
|| matches!(target, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some()
|| v6.is_unicast_link_local())
|| self.held.iter().any(|held| held.contains(&target));
if reached_directly {
return Egress::KERNEL;
}
Egress { pin: Some(*pin) }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Egress {
pin: Option<Pin>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Pin {
source: IpAddr,
interface: Option<NonZeroU32>,
}
impl Egress {
pub(crate) const KERNEL: Self = Self { pin: None };
pub(crate) async fn connect_timed(
self,
addr: SocketAddr,
timeout: Duration,
) -> io::Result<TcpStream> {
descriptors::patiently(descriptors::patience(), || async move {
tokio::time::timeout(timeout, self.connect_shaped(addr, Shaping::default()))
.await
.unwrap_or_else(|_elapsed| Err(io::ErrorKind::TimedOut.into()))
})
.await
}
pub(crate) async fn connect_shaped(
self,
addr: SocketAddr,
shaping: Shaping,
) -> io::Result<TcpStream> {
#[cfg(test)]
dialled::note(addr);
if self.tcp_is_plain(shaping) {
return TcpStream::connect(addr).await;
}
let socket = self.socket(addr.ip(), Protocol::Tcp, shaping)?;
socket.set_nonblocking(true)?;
TcpSocket::from_std_stream(std::net::TcpStream::from(socket))
.connect(addr)
.await
}
pub(crate) fn start_connect(
self,
addr: SocketAddr,
shaping: Shaping,
) -> io::Result<Connecting> {
#[cfg(test)]
{
dialled::note(addr);
if let Some(refused) = dialled::refusal(addr) {
return Err(refused);
}
}
let socket = self.socket(addr.ip(), Protocol::Tcp, shaping)?;
socket.set_nonblocking(true)?;
match socket.connect(&addr.into()) {
Ok(()) => {}
#[cfg(unix)]
Err(e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}
Err(e)
if matches!(
e.kind(),
io::ErrorKind::InvalidInput | io::ErrorKind::AddrInUse
) && socket
.local_addr()
.ok()
.and_then(|local| local.as_socket())
.is_some_and(|local| local.port() == addr.port()) =>
{
return Err(io::Error::other(MetItself));
}
Err(e)
if matches!(
e.kind(),
io::ErrorKind::AddrInUse | io::ErrorKind::AddrNotAvailable
) && shaping.source_port.is_some() =>
{
return Err(SourcePortHeld::error(shaping, e, Holder::Closing));
}
#[cfg(target_os = "linux")]
Err(e) if matches!(e.raw_os_error(), Some(libc::EACCES | libc::EINVAL)) => {
return Err(io::Error::new(io::ErrorKind::HostUnreachable, e));
}
Err(e) => return Err(e),
}
Ok(Connecting {
stream: TcpStream::from_std(std::net::TcpStream::from(socket))?,
})
}
pub(crate) fn connect_within(
self,
addr: SocketAddr,
timeout: Duration,
patience: Duration,
) -> io::Result<std::net::TcpStream> {
descriptors::patiently_blocking(patience, || {
#[cfg(test)]
dialled::note(addr);
if self.tcp_is_plain(Shaping::default()) {
return std::net::TcpStream::connect_timeout(&addr, timeout);
}
let socket = self.socket(addr.ip(), Protocol::Tcp, Shaping::default())?;
socket.connect_timeout(&addr.into(), timeout)?;
Ok(socket.into())
})
}
pub(crate) async fn udp(self, peer: IpAddr, patience: Duration) -> io::Result<UdpSocket> {
descriptors::patiently(patience, || self.udp_shaped(peer, Shaping::default())).await
}
pub(crate) async fn udp_shaped(self, peer: IpAddr, shaping: Shaping) -> io::Result<UdpSocket> {
if self.pin.is_none() && !shaping.is_active() {
return UdpSocket::bind(wildcard(peer, 0)).await;
}
let socket = self.socket(peer, Protocol::Udp, shaping)?;
socket.set_nonblocking(true)?;
UdpSocket::from_std(std::net::UdpSocket::from(socket))
}
pub(crate) fn udp_blocking(
self,
peer: IpAddr,
patience: Duration,
) -> io::Result<std::net::UdpSocket> {
descriptors::patiently_blocking(patience, || {
if self.pin.is_none() {
return std::net::UdpSocket::bind(wildcard(peer, 0));
}
Ok(self.socket(peer, Protocol::Udp, Shaping::default())?.into())
})
}
fn tcp_is_plain(self, shaping: Shaping) -> bool {
self.pin.is_none() && !shaping.is_active() && cfg!(not(windows))
}
fn socket(self, target: IpAddr, protocol: Protocol, shaping: Shaping) -> io::Result<Socket> {
let domain = match target {
IpAddr::V4(_) => Domain::IPV4,
IpAddr::V6(_) => Domain::IPV6,
};
let socket = match protocol {
Protocol::Tcp => Socket::new(domain, Type::STREAM, Some(socket2::Protocol::TCP))?,
Protocol::Udp => Socket::new(domain, Type::DGRAM, Some(socket2::Protocol::UDP))?,
};
if let Some(hops) = shaping.hop_limit {
match target {
IpAddr::V4(_) => socket.set_ttl_v4(hops.into())?,
IpAddr::V6(_) => socket.set_unicast_hops_v6(hops.into())?,
}
}
if shaping.source_port.is_some() {
socket.set_reuse_address(true)?;
#[cfg(unix)]
socket.set_reuse_port(true)?;
}
#[cfg(windows)]
if protocol == Protocol::Tcp {
syn_retries::limit(&socket, target);
}
let port = shaping.source_port.unwrap_or(0);
let bound = match self.pin {
Some(pin) => pin.bind(&socket, target, port),
None if protocol == Protocol::Udp || shaping.source_port.is_some() => {
socket.bind(&wildcard(target, port).into())
}
None => Ok(()),
};
match bound {
Err(e) if e.kind() == io::ErrorKind::AddrInUse && shaping.source_port.is_some() => {
Err(SourcePortHeld::error(shaping, e, Holder::Socket))
}
Err(e) => Err(e),
Ok(()) => Ok(socket),
}
}
}
#[derive(Debug)]
pub(crate) struct SourcePortHeld {
pub(crate) port: u16,
pub(crate) holder: Holder,
cause: io::Error,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Holder {
Closing,
Socket,
}
impl SourcePortHeld {
fn error(shaping: Shaping, cause: io::Error, holder: Holder) -> io::Error {
let kind = cause.kind();
io::Error::new(
kind,
Self {
port: shaping.source_port.unwrap_or_default(),
holder,
cause,
},
)
}
pub(crate) fn of(error: &io::Error) -> Option<&Self> {
error.get_ref()?.downcast_ref::<Self>()
}
}
impl std::fmt::Display for SourcePortHeld {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "source port {} in use: {}", self.port, self.cause)
}
}
impl std::error::Error for SourcePortHeld {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.cause)
}
}
#[derive(Debug)]
pub(crate) struct Connecting {
stream: TcpStream,
}
impl Connecting {
pub(crate) async fn finish(self) -> io::Result<TcpStream> {
self.stream.writable().await?;
if let Some(error) = self.stream.take_error()? {
return Err(error);
}
if self.stream.local_addr()? == self.stream.peer_addr()? {
return Err(io::Error::other(MetItself));
}
Ok(self.stream)
}
}
#[derive(Debug)]
struct MetItself;
impl std::fmt::Display for MetItself {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("the connect was given its target's port as its source and reached itself")
}
}
impl std::error::Error for MetItself {}
pub(crate) fn met_itself(error: &io::Error) -> bool {
error.get_ref().is_some_and(|inner| inner.is::<MetItself>())
}
impl Pin {
fn bind(self, socket: &Socket, target: IpAddr, port: u16) -> io::Result<()> {
if self.source.is_ipv4() != target.is_ipv4() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("a connection to {target} cannot leave from {}", self.source),
));
}
#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
match self.source {
IpAddr::V4(_) => socket.bind_device_by_index_v4(self.interface)?,
IpAddr::V6(_) => socket.bind_device_by_index_v6(self.interface)?,
}
let address = match self.source {
IpAddr::V4(v4) => SocketAddr::from((v4, port)),
IpAddr::V6(v6) => {
let scope = match (v6.is_unicast_link_local(), self.interface) {
(true, Some(index)) => index.get(),
_ => 0,
};
SocketAddr::V6(SocketAddrV6::new(v6, port, 0, scope))
}
};
socket.bind(&address.into())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Protocol {
Tcp,
Udp,
}
fn wildcard(family: IpAddr, port: u16) -> SocketAddr {
match family {
IpAddr::V4(_) => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), port),
IpAddr::V6(_) => SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), port),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::loopback::{accept_from_this_process, from_this_process};
#[cfg(unix)]
const CONNECT_TO: &str = "ZOND_TEST_CONNECT_TO";
#[cfg(unix)]
#[tokio::test]
async fn the_dial_count_moves_for_this_processs_connections_alone() {
let silent = crate::testing::loopback::SilentPort::open();
let addr = silent.addr();
let path = format!(
"{}::connect_once_and_close",
module_path!().split_once("::").expect("a crate path").1
);
let elsewhere = std::process::Command::new(std::env::current_exe().unwrap())
.args([path.as_str(), "--exact", "--ignored", "--test-threads=1"])
.env(CONNECT_TO, addr.to_string())
.output()
.expect("another process runs");
let said = String::from_utf8_lossy(&elsewhere.stdout);
assert!(
elsewhere.status.success() && said.contains("1 passed"),
"the other process connected to nothing:\n{said}"
);
assert_eq!(
dialled::to(addr),
0,
"another process's connection was counted"
);
let connected = Egress::KERNEL
.connect_timed(addr, Duration::from_secs(30))
.await
.expect("connects to loopback");
drop(connected);
assert_eq!(
dialled::to(addr),
1,
"a connection this process closed at once was not counted"
);
}
#[cfg(unix)]
#[test]
#[ignore = "the connector another test runs in a process of its own"]
fn connect_once_and_close() {
if let Ok(to) = std::env::var(CONNECT_TO) {
let to: SocketAddr = to.parse().expect("an address");
drop(std::net::TcpStream::connect(to).expect("connects to loopback"));
}
}
#[test]
fn a_socket_binds_the_family_of_its_target() {
assert!(wildcard(IpAddr::V4(Ipv4Addr::LOCALHOST), 0).is_ipv4());
assert!(wildcard(IpAddr::V6(Ipv6Addr::LOCALHOST), 0).is_ipv6());
}
#[test]
fn an_unshaped_connect_is_left_to_the_kernel_except_on_windows() {
assert_eq!(
Egress::KERNEL.tcp_is_plain(Shaping::default()),
cfg!(not(windows))
);
assert!(!Egress::KERNEL.tcp_is_plain(Shaping {
source_port: Some(53),
hop_limit: None,
}));
assert!(!Egress::KERNEL.tcp_is_plain(Shaping {
source_port: None,
hop_limit: Some(12),
}));
let pinned = Egress {
pin: Some(Pin {
source: v4(192, 0, 2, 10),
interface: NonZeroU32::new(2),
}),
};
assert!(
!pinned.tcp_is_plain(Shaping::default()),
"a pinned connection was left to the kernel, which would source it"
);
}
#[tokio::test]
async fn a_shaped_connect_pins_its_source_port_and_hop_limit() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("a loopback listener");
let addr = listener.local_addr().expect("its address");
const PINNED: u16 = 40_517;
const HOPS: u8 = 9;
let shaping = Shaping {
source_port: Some(PINNED),
hop_limit: Some(HOPS),
};
let accept = tokio::spawn(async move {
let accepted = accept_from_this_process(&listener).await?;
let peer = accepted.peer_addr()?;
std::io::Result::Ok((accepted, peer))
});
let stream = Egress::KERNEL
.connect_shaped(addr, shaping)
.await
.expect("the shaped connect completes");
let (_accepted, peer) = accept
.await
.expect("the accept task joins")
.expect("an accept");
assert_eq!(
peer.port(),
PINNED,
"the SYN left from the pinned source port"
);
assert_eq!(
stream.ttl().expect("the socket's hop limit"),
u32::from(HOPS),
"the SYN carried the chosen hop limit"
);
}
#[tokio::test]
async fn a_shaped_udp_socket_pins_its_source_port() {
let server = UdpSocket::bind("127.0.0.1:0")
.await
.expect("a loopback server");
let server_addr = server.local_addr().expect("its address");
const PINNED: u16 = 40_619;
let shaping = Shaping {
source_port: Some(PINNED),
hop_limit: None,
};
let socket = Egress::KERNEL
.udp_shaped(IpAddr::V4(Ipv4Addr::LOCALHOST), shaping)
.await
.expect("a shaped UDP socket");
socket
.connect(server_addr)
.await
.expect("addressing the peer");
socket.send(b"probe").await.expect("sending the probe");
let mut buf = [0u8; 8];
let (_read, from) = server
.recv_from(&mut buf)
.await
.expect("the datagram arrives");
assert_eq!(
from.port(),
PINNED,
"the datagram left from the pinned source port"
);
}
#[test]
fn a_blocking_connect_reaches_a_listener_in_either_family() {
for ip in [
IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V6(Ipv6Addr::LOCALHOST),
] {
let listener = std::net::TcpListener::bind((ip, 0)).expect("a loopback listener");
let addr = listener.local_addr().expect("its address");
let stream = Egress::KERNEL
.connect_within(addr, Duration::from_secs(1), descriptors::PATIENCE)
.expect("the connect completes");
assert_eq!(stream.peer_addr().expect("a peer"), addr, "{ip}");
}
}
fn v4(a: u8, b: u8, c: u8, d: u8) -> IpAddr {
IpAddr::V4(Ipv4Addr::new(a, b, c, d))
}
fn v6(text: &str) -> IpAddr {
text.parse().expect("an IPv6 literal")
}
fn pinned(source: IpAddr, interface: u32) -> Egress {
Egress {
pin: Some(Pin {
source,
interface: NonZeroU32::new(interface),
}),
}
}
fn laptop() -> Vec<Link> {
use crate::system::interface::LinkKind;
vec![
Link::new("lo", 1)
.with_kind(LinkKind::Loopback)
.with_link_up(true)
.with_addresses(vec![LinkAddress::new(v4(127, 0, 0, 1), 8)]),
Link::new("eth0", 2).with_link_up(true).with_addresses(vec![
LinkAddress::new(v4(192, 0, 2, 10), 24),
LinkAddress::new(v6("2001:db8:1::10"), 64),
]),
Link::new("wg0", 5)
.with_link_up(true)
.with_addresses(vec![LinkAddress::new(v4(198, 51, 100, 2), 24)]),
Link::new("eth9", 9).with_addresses(vec![LinkAddress::new(v4(203, 0, 113, 1), 24)]),
]
}
#[test]
fn a_forced_source_carries_only_what_no_link_here_reaches_directly() {
let sources =
ForcedSources::with_links(&[v4(192, 0, 2, 10), v6("2001:db8:1::10")], &laptop());
let lan_v4 = pinned(v4(192, 0, 2, 10), 2);
let lan_v6 = pinned(v6("2001:db8:1::10"), 2);
for (target, expected, why) in [
(v4(198, 18, 0, 1), lan_v4, "a routed target"),
(v6("2001:db8:ffff::1"), lan_v6, "a routed IPv6 target"),
(
v4(203, 0, 113, 50),
lan_v4,
"a target in the prefix of a link that is down",
),
(v4(192, 0, 2, 77), Egress::KERNEL, "a neighbour on the LAN"),
(v4(192, 0, 2, 10), Egress::KERNEL, "this host's own address"),
(
v4(198, 51, 100, 1),
Egress::KERNEL,
"a peer inside the tunnel",
),
(v4(127, 0, 0, 1), Egress::KERNEL, "IPv4 loopback"),
(v6("::1"), Egress::KERNEL, "IPv6 loopback"),
(
v6("::ffff:198.18.0.1"),
Egress::KERNEL,
"an IPv4 host written inside IPv6",
),
(v6("fe80::1"), Egress::KERNEL, "a link-local neighbour"),
] {
assert_eq!(sources.toward(target), expected, "{why}: {target}");
}
}
#[test]
fn a_forced_source_speaks_for_its_own_family_only() {
let only_v4 = ForcedSources::with_links(&[v4(192, 0, 2, 10)], &laptop());
assert_eq!(only_v4.toward(v6("2001:db8:ffff::1")), Egress::KERNEL);
let only_v6 = ForcedSources::with_links(&[v6("2001:db8:1::10")], &laptop());
assert_eq!(only_v6.toward(v4(198, 18, 0, 1)), Egress::KERNEL);
let two = ForcedSources::with_links(&[v4(192, 0, 2, 10), v4(198, 51, 100, 2)], &laptop());
assert_eq!(two.toward(v4(198, 18, 0, 1)), pinned(v4(192, 0, 2, 10), 2));
assert_eq!(
ForcedSources::with_links(&[], &laptop()).toward(v4(198, 18, 0, 1)),
Egress::KERNEL
);
}
#[test]
fn a_connection_is_pinned_exactly_where_the_plan_pinned_its_probe() {
use crate::model::ip::set::IpSet;
use crate::system::interface::{interfaces, map_ips_to_interfaces_forced};
let Some(held) = interfaces()
.expect("this machine's interfaces")
.into_iter()
.filter(|link| link.is_up() && !link.is_loopback())
.flat_map(|link| link.addresses().to_vec())
.find(|held| {
matches!(held.address(), IpAddr::V4(a) if !a.is_loopback() && !a.is_link_local())
&& held.prefix() <= 30
})
else {
return;
};
let forced = held.address();
let IpAddr::V4(own) = forced else {
unreachable!("filtered to IPv4 above");
};
let neighbour = [1u32, 2]
.into_iter()
.map(|offset| {
let network = u32::from(own) & (u32::MAX << (32 - held.prefix()));
IpAddr::V4(Ipv4Addr::from(network + offset))
})
.find(|candidate| *candidate != forced)
.expect("a /30 or wider holds a second address");
let sources = ForcedSources::new(&[forced]);
for target in [
v4(198, 18, 0, 1),
v4(127, 0, 0, 1),
forced,
neighbour,
v6("::ffff:198.18.0.1"),
] {
let mut set = IpSet::new();
set.insert(target);
let planned = map_ips_to_interfaces_forced(set, &[forced])
.routed
.iter()
.any(|routed| routed.target == target && routed.source == forced);
assert_eq!(
sources.toward(target).pin.is_some(),
planned,
"{target}: the plan {} its probe to {forced}",
if planned { "pinned" } else { "did not pin" }
);
}
}
#[tokio::test]
async fn a_source_this_host_does_not_hold_fails_the_connection_rather_than_moving_it() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("a loopback listener");
let addr = listener.local_addr().expect("its address");
let sources = ForcedSources::with_links(&[v4(192, 0, 2, 99)], &laptop());
let egress = sources.toward(v4(198, 18, 0, 1));
assert_eq!(egress, pinned(v4(192, 0, 2, 99), 0));
assert!(
egress
.connect_timed(addr, crate::config::limits::CONNECT_PROBE_TIMEOUT)
.await
.is_err(),
"a connection forced to an address this host does not hold went out anyway"
);
}
fn loopback_pin() -> (Egress, u32) {
let lo = crate::system::interface::interfaces()
.expect("this machine's interfaces")
.into_iter()
.find(Link::is_loopback)
.expect("a loopback interface");
let second = lo
.addresses()
.iter()
.map(LinkAddress::address)
.find(|address| address.is_ipv4() && *address != v4(127, 0, 0, 1));
let source = if cfg!(target_os = "linux") {
v4(127, 0, 0, 2)
} else {
second.unwrap_or(v4(127, 0, 0, 1))
};
(pinned(source, lo.index()), lo.index())
}
#[tokio::test]
async fn a_pinned_connection_leaves_from_its_source_and_by_its_interface() {
let (egress, index) = loopback_pin();
let source = egress.pin.expect("a pin").source;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("a loopback listener");
let addr = listener.local_addr().expect("its address");
let accept = tokio::spawn(async move {
let from = async || {
let accepted = accept_from_this_process(&listener).await?;
accepted.peer_addr()
};
let first = from().await.expect("the pinned connection");
let second = from().await.expect("the plain connection");
(first, second)
});
let within = crate::config::limits::CONNECT_PROBE_TIMEOUT;
let pinned = egress
.connect_timed(addr, within)
.await
.expect("the pinned connect");
let plain = Egress::KERNEL
.connect_timed(addr, within)
.await
.expect("the plain connect");
let (first, second) = accept.await.expect("the accept task joins");
assert_eq!(first.ip(), source, "the pinned connection's source");
assert_eq!(
second.ip(),
v4(127, 0, 0, 1),
"the plain connection's source"
);
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
{
let bound = |stream: &TcpStream| {
socket2::SockRef::from(stream)
.device_index_v4()
.expect("the socket's interface")
};
assert_eq!(bound(&pinned), NonZeroU32::new(index));
assert_eq!(bound(&plain), None);
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
let _ = (pinned, plain, index);
}
#[tokio::test]
async fn a_pinned_datagram_and_blocking_connection_leave_from_the_source() {
let (egress, _) = loopback_pin();
let source = egress.pin.expect("a pin").source;
let server = UdpSocket::bind("127.0.0.1:0").await.expect("a UDP server");
let server_addr = server.local_addr().expect("its address");
let socket = egress
.udp(server_addr.ip(), descriptors::PATIENCE)
.await
.expect("a pinned socket");
socket
.connect(server_addr)
.await
.expect("addressing the peer");
socket.send(b"probe").await.expect("sending");
let mut buf = [0u8; 8];
let (_, from) = crate::testing::loopback::recv_from_this_process(&server, &mut buf)
.await
.expect("the datagram");
assert_eq!(from.ip(), source, "the datagram's source");
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a listener");
let addr = listener.local_addr().expect("its address");
let handle = std::thread::spawn(move || {
let accepted = from_this_process(&listener).next().expect("an accept");
let peer = accepted.peer_addr()?;
std::io::Result::Ok((accepted, peer))
});
let _stream = egress
.connect_within(addr, Duration::from_secs(1), descriptors::PATIENCE)
.expect("the blocking connect");
let (_accepted, from) = handle.join().expect("the accept joins").expect("an accept");
assert_eq!(from.ip(), source, "the blocking connection's source");
}
}