use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use std::time::Duration;
use crate::events::{Fault, LinkFault, RecordedEvent};
use crate::readiness::Deadline;
use crate::scope::{self, SimShared};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IpNet {
pub addr: IpAddr,
pub prefix: u8,
}
fn max_prefix(ip: IpAddr) -> u8 {
if ip.is_ipv4() { 32 } else { 128 }
}
fn mask_bits(ip: IpAddr, prefix: u8) -> u128 {
let width = max_prefix(ip) as u32;
let full: u128 = if width == 32 {
u32::MAX as u128
} else {
u128::MAX
};
if prefix == 0 {
0
} else {
full & !(full.checked_shr(prefix as u32).unwrap_or(0))
}
}
fn bits(ip: IpAddr) -> u128 {
match ip {
IpAddr::V4(v4) => u32::from(v4) as u128,
IpAddr::V6(v6) => u128::from(v6),
}
}
fn from_bits(like: IpAddr, value: u128) -> IpAddr {
match like {
IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::from(value as u32)),
IpAddr::V6(_) => IpAddr::V6(Ipv6Addr::from(value)),
}
}
impl IpNet {
#[track_caller]
pub fn new(addr: IpAddr, prefix: u8) -> Self {
assert!(
prefix <= max_prefix(addr),
"prefix /{prefix} is too long for {addr}"
);
IpNet { addr, prefix }
}
pub fn host(addr: IpAddr) -> Self {
IpNet {
addr,
prefix: max_prefix(addr),
}
}
pub fn network(&self) -> IpAddr {
from_bits(
self.addr,
bits(self.addr) & mask_bits(self.addr, self.prefix),
)
}
pub fn contains(&self, ip: IpAddr) -> bool {
if ip.is_ipv4() != self.addr.is_ipv4() {
return false;
}
let mask = mask_bits(ip, self.prefix);
bits(ip) & mask == bits(self.addr) & mask
}
pub fn broadcast(&self) -> Option<IpAddr> {
if !self.addr.is_ipv4() || self.prefix > 30 {
return None;
}
let host = !mask_bits(self.addr, self.prefix) & u32::MAX as u128;
Some(from_bits(self.addr, bits(self.addr) | host))
}
}
impl From<IpAddr> for IpNet {
fn from(addr: IpAddr) -> Self {
IpNet::host(addr)
}
}
impl From<Ipv4Addr> for IpNet {
fn from(addr: Ipv4Addr) -> Self {
IpNet::host(addr.into())
}
}
impl From<Ipv6Addr> for IpNet {
fn from(addr: Ipv6Addr) -> Self {
IpNet::host(addr.into())
}
}
impl fmt::Display for IpNet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}", self.addr, self.prefix)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseIpNetError(String);
impl fmt::Display for ParseIpNetError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid address/prefix {:?}", self.0)
}
}
impl std::error::Error for ParseIpNetError {}
impl FromStr for IpNet {
type Err = ParseIpNetError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let bad = || ParseIpNetError(s.to_string());
let (addr, prefix) = match s.split_once('/') {
Some((addr, prefix)) => (addr, Some(prefix)),
None => (s, None),
};
let addr: IpAddr = addr.parse().map_err(|_| bad())?;
let prefix = match prefix {
Some(p) => p.parse::<u8>().map_err(|_| bad())?,
None => max_prefix(addr),
};
if prefix > max_prefix(addr) {
return Err(bad());
}
Ok(IpNet { addr, prefix })
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct NicPolicy {
pub latency: Duration,
pub jitter: Duration,
pub loss_rate: f64,
pub duplicate_rate: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct NicSpec {
pub name: String,
pub index: Option<u32>,
pub addresses: Vec<IpNet>,
pub stations: Vec<IpAddr>,
pub mac: Option<[u8; 6]>,
pub mtu: u32,
pub admin_up: bool,
pub carrier: bool,
pub speed_mbps: Option<u32>,
pub physical_medium: Option<i32>,
pub policy: NicPolicy,
}
impl NicSpec {
pub fn new(name: impl Into<String>) -> Self {
NicSpec {
name: name.into(),
index: None,
addresses: Vec::new(),
stations: Vec::new(),
mac: None,
mtu: 1500,
admin_up: true,
carrier: true,
speed_mbps: Some(1000),
physical_medium: None,
policy: NicPolicy::default(),
}
}
pub fn address(mut self, net: impl Into<IpNet>) -> Self {
self.addresses.push(net.into());
self
}
pub fn station(mut self, ip: impl Into<IpAddr>) -> Self {
self.stations.push(ip.into());
self
}
pub fn index(mut self, index: u32) -> Self {
self.index = Some(index);
self
}
pub fn mtu(mut self, mtu: u32) -> Self {
self.mtu = mtu;
self
}
pub fn mac(mut self, mac: [u8; 6]) -> Self {
self.mac = Some(mac);
self
}
pub fn link(mut self, carrier: bool) -> Self {
self.carrier = carrier;
self
}
pub fn physical_medium(mut self, physical_medium: i32) -> Self {
self.physical_medium = Some(physical_medium);
self
}
pub fn policy(mut self, policy: NicPolicy) -> Self {
self.policy = policy;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Route {
pub dest: IpNet,
pub nic: String,
pub gateway: Option<IpAddr>,
pub src: Option<IpAddr>,
pub metric: u32,
}
impl Route {
pub fn new(dest: impl Into<IpNet>, nic: impl Into<String>) -> Self {
Route {
dest: dest.into(),
nic: nic.into(),
gateway: None,
src: None,
metric: 0,
}
}
pub fn gateway(mut self, gateway: impl Into<IpAddr>) -> Self {
self.gateway = Some(gateway.into());
self
}
pub fn src(mut self, src: impl Into<IpAddr>) -> Self {
self.src = Some(src.into());
self
}
pub fn metric(mut self, metric: u32) -> Self {
self.metric = metric;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteChoice {
pub nic: String,
pub index: u32,
pub src: Option<IpAddr>,
pub gateway: Option<IpAddr>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NicCounters {
pub rx_packets: u64,
pub tx_packets: u64,
pub rx_bytes: u64,
pub tx_bytes: u64,
pub rx_errors: u64,
pub tx_errors: u64,
pub rx_dropped: u64,
pub tx_dropped: u64,
pub multicast: u64,
pub tx_carrier_errors: u64,
pub rx_nohandler: u64,
}
#[derive(Debug, Clone)]
pub struct NicSnapshot {
pub index: u32,
pub spec: NicSpec,
pub counters: NicCounters,
pub loopback: bool,
}
impl NicSnapshot {
pub fn physical_medium(&self) -> i32 {
self.spec
.physical_medium
.unwrap_or(if self.loopback { 0 } else { 14 })
}
pub(crate) fn hw_addr(&self) -> [u8; 6] {
if self.loopback {
return [0; 6];
}
self.spec.mac.unwrap_or_else(|| {
let i = self.index.to_be_bytes();
[0x02, 0x00, i[0], i[1], i[2], i[3]]
})
}
pub(crate) fn running(&self) -> bool {
self.spec.admin_up && self.spec.carrier
}
}
#[cfg(unix)]
pub(crate) mod code {
pub(crate) const ENETUNREACH: i32 = libc::ENETUNREACH;
pub(crate) const EHOSTUNREACH: i32 = libc::EHOSTUNREACH;
pub(crate) const EADDRNOTAVAIL: i32 = libc::EADDRNOTAVAIL;
pub(crate) const ENETDOWN: i32 = libc::ENETDOWN;
pub(crate) const EACCES: i32 = libc::EACCES;
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) const EINVAL: i32 = libc::EINVAL;
}
#[cfg(windows)]
pub(crate) mod code {
pub(crate) const ENETUNREACH: i32 = 10051;
pub(crate) const EHOSTUNREACH: i32 = 10065;
pub(crate) const EADDRNOTAVAIL: i32 = 10049;
pub(crate) const ENETDOWN: i32 = 10050;
pub(crate) const EACCES: i32 = 10013;
#[allow(dead_code)]
pub(crate) const EINVAL: i32 = 10022;
}
fn loopback_spec() -> NicSpec {
let (name, mtu) = if cfg!(target_os = "linux") {
("lo", 65536)
} else if cfg!(target_os = "macos") {
("lo0", 16384)
} else {
("Loopback Pseudo-Interface 1", u32::MAX)
};
let mut spec = NicSpec::new(name).index(1).mtu(mtu);
spec.addresses = vec![
IpNet::new(Ipv4Addr::LOCALHOST.into(), 8),
IpNet::host(Ipv6Addr::LOCALHOST.into()),
];
spec.speed_mbps = None;
spec
}
struct LinkTransition {
at: Deadline,
carrier: bool,
#[cfg(windows)]
restart: Option<RestartTransition>,
}
#[cfg(windows)]
struct RestartTransition {
generation: Arc<Mutex<u64>>,
epoch: u64,
timer: Option<u64>,
}
pub(crate) struct LinkState {
name: String,
admin_up: AtomicBool,
carrier: AtomicBool,
removed: AtomicBool,
downs: Mutex<Vec<Duration>>,
#[cfg(target_os = "macos")]
delivery_holds: Mutex<Vec<(Duration, Option<Duration>)>>,
schedule: Mutex<VecDeque<LinkTransition>>,
shared: Weak<SimShared>,
}
impl LinkState {
fn new(spec: &NicSpec, shared: Weak<SimShared>) -> Self {
LinkState {
name: spec.name.clone(),
admin_up: AtomicBool::new(spec.admin_up),
carrier: AtomicBool::new(spec.carrier),
removed: AtomicBool::new(false),
downs: Mutex::default(),
#[cfg(target_os = "macos")]
delivery_holds: Mutex::new(if spec.admin_up && spec.carrier {
Vec::new()
} else {
vec![(Duration::ZERO, None)]
}),
schedule: Mutex::default(),
shared,
}
}
fn up(&self) -> bool {
self.admin_up.load(Ordering::Acquire) && self.carrier.load(Ordering::Acquire)
}
fn set(&self, admin: Option<bool>, carrier: Option<bool>, at: Duration) -> bool {
#[cfg(target_os = "macos")]
let mut holds = self.delivery_holds.lock().unwrap();
let was = self.up();
let mut changed = false;
if let Some(admin) = admin {
changed |= self.admin_up.swap(admin, Ordering::AcqRel) != admin;
}
if let Some(carrier) = carrier {
changed |= self.carrier.swap(carrier, Ordering::AcqRel) != carrier;
}
if was && !self.up() {
self.downs.lock().unwrap().push(at);
#[cfg(target_os = "macos")]
holds.push((at, None));
}
#[cfg(target_os = "macos")]
if !was
&& self.up()
&& let Some((_, until)) = holds.last_mut()
{
*until = Some(at);
}
changed
}
fn apply_due(&self) {
#[cfg(target_os = "macos")]
let shared = self.shared.upgrade();
#[cfg(target_os = "macos")]
let clock = shared.as_ref().and_then(|shared| shared.clock.as_deref());
let due: Vec<LinkTransition> = {
let mut schedule = self.schedule.lock().unwrap();
let mut due = Vec::new();
while schedule.front().is_some_and(|change| {
#[cfg(target_os = "macos")]
{
change.at.passed_on(clock)
}
#[cfg(not(target_os = "macos"))]
{
change.at.passed()
}
}) {
due.push(schedule.pop_front().expect("transition"));
}
due
};
for change in due {
#[cfg(windows)]
let generation = change
.restart
.as_ref()
.map(|restart| restart.generation.lock().unwrap_or_else(|e| e.into_inner()));
#[cfg(windows)]
if change
.restart
.as_ref()
.zip(generation.as_ref())
.is_some_and(|(restart, generation)| restart.epoch != **generation)
{
continue;
}
let (at, carrier) = (change.at, change.carrier);
let changed = self.set(None, Some(carrier), at.instant());
#[cfg(windows)]
drop(generation);
if changed && let Some(shared) = self.shared.upgrade() {
#[cfg(target_os = "macos")]
let ago = shared
.stamp()
.saturating_sub(at.timeline_at(shared.real_origin(), shared.clock.as_deref()));
#[cfg(not(target_os = "macos"))]
let ago = at.overdue();
shared.record_ago(
ago,
RecordedEvent::NicChanged {
nic: self.name.clone(),
admin_up: self.admin_up.load(Ordering::Acquire),
carrier,
},
);
}
}
}
pub(crate) fn usable(&self) -> bool {
self.apply_due();
self.up()
}
fn admin(&self) -> bool {
self.apply_due();
self.admin_up.load(Ordering::Acquire)
}
pub(crate) fn releases(&self) -> bool {
self.removed.load(Ordering::Acquire) || self.usable()
}
#[cfg(target_os = "macos")]
pub(crate) fn effective_arrival(&self, mut at: Deadline) -> Deadline {
self.apply_due();
for &(since, until) in self.delivery_holds.lock().unwrap().iter() {
if since > at.instant() {
break;
}
if let Some(until) = until
&& until > at.instant()
{
at = at.later(until.saturating_sub(at.instant()));
}
}
at
}
#[cfg(target_os = "macos")]
fn remove(&self, at: Duration) {
self.set(Some(false), Some(false), at);
let mut holds = self.delivery_holds.lock().unwrap();
if let Some((_, until)) = holds.last_mut() {
*until = Some(at);
}
self.removed.store(true, Ordering::Release);
}
pub(crate) fn epoch(&self) -> u64 {
self.apply_due();
self.downs.lock().unwrap().len() as u64
}
pub(crate) fn lost_in_flight(&self, epoch: u64, arrival: Duration) -> bool {
self.apply_due();
let downs = self.downs.lock().unwrap();
downs
.iter()
.skip(epoch as usize)
.any(|&down| down < arrival)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Origin {
Explicit,
Auto,
}
struct NicRec {
index: u32,
name: Arc<str>,
spec: NicSpec,
loopback: bool,
link: Arc<LinkState>,
counters: NicCounters,
origins: HashMap<IpAddr, Origin>,
}
impl NicRec {
fn snapshot(&self) -> NicSnapshot {
let mut spec = self.spec.clone();
spec.index = Some(self.index);
spec.admin_up = self.link.admin();
spec.carrier = self.link.carrier.load(Ordering::Acquire);
NicSnapshot {
index: self.index,
spec,
counters: self.counters,
loopback: self.loopback,
}
}
fn has_address(&self, ip: IpAddr) -> bool {
if self.loopback && ip.is_loopback() {
return true;
}
self.spec.addresses.iter().any(|net| net.addr == ip)
}
fn addresses_live(&self) -> bool {
!cfg!(windows) || self.link.usable()
}
fn routes_live(&self) -> bool {
if self.link.removed.load(Ordering::Acquire) {
return false;
}
if cfg!(windows) {
self.link.usable()
} else {
self.link.admin()
}
}
fn source_for(&self, dst: IpAddr) -> Option<IpAddr> {
let family = self
.spec
.addresses
.iter()
.filter(|net| net.addr.is_ipv4() == dst.is_ipv4());
let mut first = None;
for net in family {
if net.contains(dst) {
return Some(net.addr);
}
first.get_or_insert(net.addr);
}
first
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Dir {
Tx,
Rx,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Op {
Send,
Connect,
}
#[derive(Clone, Copy, Default)]
pub(crate) struct SockView {
pub(crate) local: Option<SocketAddr>,
pub(crate) device: Option<u32>,
pub(crate) mcast_if: Option<u32>,
}
#[derive(Clone)]
pub(crate) struct Path {
pub(crate) egress: u32,
pub(crate) name: Arc<str>,
pub(crate) src: IpAddr,
pub(crate) gateway: Option<IpAddr>,
pub(crate) link: Arc<LinkState>,
pub(crate) local: bool,
}
#[derive(Clone)]
pub(crate) enum Sender {
Host(Path),
Station(IpAddr),
}
impl Sender {
pub(crate) fn source(&self, local: SocketAddr) -> SocketAddr {
match self {
Sender::Host(path) if local.ip().is_unspecified() => {
SocketAddr::new(path.src, local.port())
}
_ => local,
}
}
pub(crate) fn connected_local(&self, local: SocketAddr) -> SocketAddr {
let src = self.source(local);
match (src.ip(), local) {
(IpAddr::V4(v4), SocketAddr::V6(_)) => {
SocketAddr::new(v4.to_ipv6_mapped().into(), local.port())
}
(IpAddr::V6(_), SocketAddr::V4(_)) => local,
_ => src,
}
}
pub(crate) fn egress_name(&self) -> Option<&str> {
match self {
Sender::Host(path) => Some(&path.name),
Sender::Station(_) => None,
}
}
}
pub(crate) struct Cand<Q> {
pub(crate) addr: SocketAddr,
pub(crate) endpoint: bool,
pub(crate) device: Option<u32>,
pub(crate) q: Q,
}
pub(crate) struct Copy<Q> {
pub(crate) q: Q,
pub(crate) delays: crate::netpolicy::Delays,
pub(crate) via: Option<(Arc<LinkState>, u64)>,
pub(crate) nic: Option<Arc<str>>,
#[cfg_attr(windows, allow(dead_code))]
pub(crate) mtu: Option<u32>,
}
#[derive(Clone, Copy)]
pub(crate) struct Wire {
pub(crate) src: SocketAddr,
pub(crate) dest: SocketAddr,
pub(crate) len: usize,
}
#[derive(Clone)]
pub(crate) struct Hop {
pub(crate) index: u32,
pub(crate) link: Arc<LinkState>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum DestKind {
Unicast,
Limited,
Directed(IpNet),
Multicast,
}
type Rank = (u8, bool, std::cmp::Reverse<u32>);
pub(crate) struct Topology {
nics: Vec<NicRec>,
routes: Vec<Route>,
open: bool,
sim0: Option<u32>,
shared: Weak<SimShared>,
}
impl Topology {
pub(crate) fn new(shared: Weak<SimShared>) -> Self {
let lo = loopback_spec();
let link = Arc::new(LinkState::new(&lo, shared.clone()));
Topology {
nics: vec![NicRec {
index: 1,
name: Arc::from(lo.name.as_str()),
origins: lo
.addresses
.iter()
.map(|n| (n.addr, Origin::Explicit))
.collect(),
spec: lo,
loopback: true,
link,
counters: NicCounters::default(),
}],
routes: Vec::new(),
open: true,
sim0: None,
shared,
}
}
fn lo(&self) -> &NicRec {
self.nics
.iter()
.find(|n| n.loopback)
.expect("loopback interface")
}
fn nic(&self, index: u32) -> Option<&NicRec> {
self.nics.iter().find(|n| n.index == index)
}
fn nic_mut(&mut self, index: u32) -> Option<&mut NicRec> {
self.nics.iter_mut().find(|n| n.index == index)
}
fn by_name(&self, name: &str) -> Option<&NicRec> {
self.nics.iter().find(|n| n.spec.name == name)
}
fn free_index(&self, from: u32) -> u32 {
(from..)
.find(|i| self.nic(*i).is_none())
.expect("a free interface index")
}
pub(crate) fn name_of(&self, index: u32) -> Option<String> {
self.nic(index).map(|n| n.spec.name.clone())
}
pub(crate) fn index_of(&self, name: &str) -> Option<u32> {
self.by_name(name).map(|n| n.index)
}
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn index_of_address(&self, ip: IpAddr) -> Option<u32> {
self.owner(ip).map(|n| n.index)
}
pub(crate) fn loopback_index(&self) -> u32 {
self.lo().index
}
pub(crate) fn segment_of(&self, ip: IpAddr) -> Option<u32> {
self.segment(ip)
}
pub(crate) fn wire_of(&self, index: u32) -> Option<(String, u32, bool)> {
self.nic(index)
.map(|n| (n.spec.name.clone(), n.spec.mtu, n.loopback))
}
pub(crate) fn mac_of(&self, ip: IpAddr) -> Option<[u8; 6]> {
let nic = self
.nics
.iter()
.find(|n| !n.loopback && n.has_address(ip))?;
Some(nic.spec.mac.unwrap_or_else(|| {
let i = nic.index.to_be_bytes();
[0x02, 0x00, i[0], i[1], i[2], i[3]]
}))
}
pub(crate) fn mtu_of(&self, index: u32) -> Option<u32> {
self.nic(index).map(|n| n.spec.mtu)
}
pub(crate) fn link_of(&self, index: u32) -> Option<Arc<LinkState>> {
self.nic(index).map(|n| n.link.clone())
}
fn insert(&mut self, mut spec: NicSpec, counters: NicCounters) -> io::Result<u32> {
if self.by_name(&spec.name).is_some() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("an interface named {} exists", spec.name),
));
}
let index = match spec.index {
Some(0) => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"interface index 0 is reserved",
));
}
Some(index) if self.nic(index).is_some() => {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("interface index {index} is taken"),
));
}
Some(index) => index,
None => self.free_index(2),
};
spec.index = Some(index);
if !spec.addresses.is_empty() {
self.open = false;
}
let link = Arc::new(LinkState::new(&spec, self.shared.clone()));
self.nics.push(NicRec {
index,
name: Arc::from(spec.name.as_str()),
origins: spec
.addresses
.iter()
.map(|n| (n.addr, Origin::Explicit))
.collect(),
spec,
loopback: false,
link,
counters,
});
self.nics.sort_by_key(|n| n.index);
Ok(index)
}
fn make_room(&mut self, index: u32) {
if self.lo().index == index {
let free = self.free_index(2).max(index + 1);
let free = (free..)
.find(|i| self.nic(*i).is_none())
.expect("free index");
if let Some(lo) = self.nics.iter_mut().find(|n| n.loopback) {
lo.index = free;
lo.spec.index = Some(free);
}
self.nics.sort_by_key(|n| n.index);
}
}
fn all_routes(&self) -> Vec<Route> {
let mut out = Vec::new();
for nic in self.nics.iter().filter(|n| !n.loopback) {
for net in &nic.spec.addresses {
if net.prefix < max_prefix(net.addr) {
out.push(Route {
dest: IpNet::new(net.network(), net.prefix),
nic: nic.spec.name.clone(),
gateway: None,
src: Some(net.addr),
metric: 0,
});
}
}
}
out.extend(self.routes.iter().cloned());
out
}
fn lpm(
&self,
dst: IpAddr,
usable: impl Fn(&NicRec) -> bool,
prefer: Option<u32>,
) -> Option<(Route, u32)> {
let mut best: Option<(Route, u32, Rank)> = None;
for route in self.all_routes() {
if !route.dest.contains(dst) {
continue;
}
let Some(nic) = self.by_name(&route.nic) else {
continue;
};
if !usable(nic) {
continue;
}
let key = (
route.dest.prefix,
prefer == Some(nic.index),
std::cmp::Reverse(route.metric),
);
if best.as_ref().is_none_or(|(_, _, k)| key > *k) {
best = Some((route, nic.index, key));
}
}
best.map(|(route, index, _)| (route, index))
}
fn owner(&self, ip: IpAddr) -> Option<&NicRec> {
self.nics.iter().find(|n| n.has_address(ip))
}
pub(crate) fn is_host(&self, ip: IpAddr) -> bool {
if ip.is_loopback() {
return true;
}
self.owner(ip).is_some_and(NicRec::addresses_live)
}
pub(crate) fn is_station_ip(&self, ip: IpAddr) -> bool {
self.nics.iter().any(|n| n.spec.stations.contains(&ip))
}
fn segment(&self, ip: IpAddr) -> Option<u32> {
if let Some(nic) = self.nics.iter().find(|n| n.spec.stations.contains(&ip)) {
return Some(nic.index);
}
self.lpm(ip, |n| !n.link.removed.load(Ordering::Acquire), None)
.map(|(_, index)| index)
}
fn dest_kind(&self, ip: IpAddr) -> DestKind {
if ip.is_multicast() {
return DestKind::Multicast;
}
if ip == IpAddr::V4(Ipv4Addr::BROADCAST) {
return DestKind::Limited;
}
for nic in &self.nics {
for net in &nic.spec.addresses {
if net.broadcast() == Some(ip) {
return DestKind::Directed(*net);
}
}
}
DestKind::Unicast
}
pub(crate) fn is_broadcast(&self, ip: IpAddr) -> bool {
matches!(
self.dest_kind(ip),
DestKind::Limited | DestKind::Directed(_)
)
}
fn fallback_source(&self, dst: IpAddr) -> IpAddr {
self.nics
.iter()
.filter(|n| !n.loopback && n.addresses_live())
.find_map(|n| n.source_for(dst))
.unwrap_or(match dst {
IpAddr::V4(_) => Ipv4Addr::LOCALHOST.into(),
IpAddr::V6(_) => Ipv6Addr::LOCALHOST.into(),
})
}
fn path(&self, nic: &NicRec, src: IpAddr, gateway: Option<IpAddr>, local: bool) -> Path {
Path {
egress: nic.index,
name: nic.name.clone(),
src,
gateway,
link: nic.link.clone(),
local,
}
}
fn no_route(op: Op, bound: bool) -> i32 {
if cfg!(target_os = "macos") && op == Op::Send && bound {
code::EHOSTUNREACH
} else {
code::ENETUNREACH
}
}
fn egress(&self, view: &SockView, dst: IpAddr, op: Op, dst_host: bool) -> Result<Path, i32> {
let bound = view
.local
.map(|l| l.ip())
.filter(|ip| !ip.is_unspecified() && !ip.is_multicast());
if dst_host {
let src = bound.unwrap_or(match dst {
IpAddr::V4(v4) if v4.is_loopback() => Ipv4Addr::LOCALHOST.into(),
other => other,
});
return Ok(self.path(self.lo(), src, None, true));
}
let owner = bound.and_then(|ip| self.owner(ip));
let src_from = |nic: &NicRec, route_src: Option<IpAddr>| {
bound
.or(route_src.filter(|s| s.is_ipv4() == dst.is_ipv4()))
.or_else(|| nic.source_for(dst))
.unwrap_or_else(|| self.fallback_source(dst))
};
let group = dst.is_multicast() || dst == IpAddr::V4(Ipv4Addr::BROADCAST);
if group
&& let Some(index) = view
.mcast_if
.filter(|_| dst.is_multicast())
.or(view.device)
.or_else(|| owner.map(|n| n.index))
{
let nic = self.nic(index).ok_or(code::ENETUNREACH)?;
return Ok(self.path(nic, src_from(nic, None), None, false));
}
if let Some(ip) = bound
&& ip.is_loopback()
&& !cfg!(windows)
{
return Err(if cfg!(target_os = "linux") {
code::EINVAL
} else {
code::EADDRNOTAVAIL
});
}
if cfg!(target_os = "macos") && owner.is_some_and(|n| !n.link.admin()) {
return Err(code::ENETDOWN);
}
if let Some(dev) = view
.device
.filter(|_| !(cfg!(windows) && dst.is_multicast()))
{
let nic = self.nic(dev).ok_or(code::ENETUNREACH)?;
let scoped = self.lpm(dst, |n| n.index == dev && n.routes_live(), None);
if cfg!(target_os = "macos") {
if !nic.link.admin() {
return Err(code::ENETDOWN);
}
let (route, _) = scoped.ok_or(code::ENETUNREACH)?;
return Ok(self.path(nic, src_from(nic, route.src), route.gateway, false));
}
if cfg!(windows) && !nic.routes_live() {
return Err(code::ENETUNREACH);
}
if !nic.link.admin() {
return Err(code::ENETUNREACH);
}
let (src, gateway) = match scoped {
Some((route, _)) => (src_from(nic, route.src), route.gateway),
None => (src_from(nic, None), None),
};
return Ok(self.path(nic, src, gateway, false));
}
let prefer = owner.map(|n| n.index);
let (mut route, mut index) = self
.lpm(dst, NicRec::routes_live, prefer)
.ok_or_else(|| Self::no_route(op, bound.is_some()))?;
if cfg!(windows) && bound.is_some() && prefer != Some(index) {
(route, index) = self
.lpm(dst, |n| n.routes_live() && Some(n.index) == prefer, None)
.ok_or(code::ENETUNREACH)?;
}
let nic = self.nic(index).expect("routed interface");
Ok(self.path(nic, src_from(nic, route.src), route.gateway, false))
}
pub(crate) fn account(&mut self, index: u32, dir: Dir, frame: usize, multicast: bool) {
let Some(nic) = self.nic_mut(index) else {
return;
};
let c = &mut nic.counters;
match dir {
Dir::Tx => {
c.tx_packets += 1;
c.tx_bytes += frame as u64;
}
Dir::Rx => {
c.rx_packets += 1;
c.rx_bytes += frame as u64;
if multicast {
c.multicast += 1;
}
}
}
}
fn count_carrier_drop(&mut self, index: u32) {
if let Some(nic) = self.nic_mut(index) {
nic.counters.tx_dropped += 1;
nic.counters.tx_carrier_errors += 1;
}
}
fn count_rx_drop(&mut self, index: u32) {
if let Some(nic) = self.nic_mut(index) {
nic.counters.rx_dropped += 1;
}
}
fn policy_of(&self, index: u32) -> Option<NicPolicy> {
self.nic(index)
.map(|n| n.spec.policy.clone())
.filter(|p| *p != NicPolicy::default())
}
fn claim(&mut self, ip: IpAddr) -> Result<(), i32> {
if ip.is_unspecified() || ip.is_multicast() || self.is_broadcast(ip) || self.is_host(ip) {
return Ok(());
}
if self.is_station_ip(ip) {
return Ok(());
}
if !self.open || self.owner(ip).is_some() {
return Err(code::EADDRNOTAVAIL);
}
let index = self
.sim0
.filter(|i| self.nic(*i).is_some())
.or_else(|| self.nics.iter().find(|n| !n.loopback).map(|n| n.index))
.unwrap_or(self.lo().index);
let nic = self.nic_mut(index).expect("interface");
nic.spec.addresses.push(IpNet::host(ip));
nic.origins.insert(ip, Origin::Auto);
Ok(())
}
pub(crate) fn presence(&self, ip: IpAddr, station: bool) -> Presence {
if self.is_host(ip) {
Presence::Host
} else if station || self.is_station_ip(ip) {
Presence::Station
} else if self.open {
Presence::Host
} else {
Presence::Absent
}
}
}
impl Topology {
fn syn_presence(&self, ip: IpAddr, station: bool) -> Presence {
if self.is_host(ip) {
Presence::Host
} else if station || self.is_station_ip(ip) {
Presence::Station
} else {
Presence::Absent
}
}
fn on_link(&self, ip: IpAddr) -> bool {
self.lpm(ip, NicRec::routes_live, None)
.is_some_and(|(route, _)| route.gateway.is_none() && route.dest.prefix > 0)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Presence {
Host,
Station,
Absent,
}
fn frame_len(ip: IpAddr, payload: usize) -> usize {
payload + if ip.is_ipv4() { 42 } else { 62 }
}
fn not_found(name: &str) -> io::Error {
io::Error::new(
io::ErrorKind::NotFound,
format!("no interface named {name}"),
)
}
#[derive(Default)]
struct After {
events: Vec<RecordedEvent>,
kick: bool,
}
impl SimShared {
pub(crate) fn settle_links(&self) {
let links: Vec<Arc<LinkState>> =
snare_interpose::real(|| self.topo().nics.iter().map(|n| n.link.clone()).collect());
for link in links {
link.apply_due();
}
}
pub(crate) fn syn_target(&self, ip: IpAddr, station: bool) -> (Presence, bool) {
snare_interpose::real(|| {
let topo = self.topo();
(topo.syn_presence(ip, station), topo.on_link(ip))
})
}
pub(crate) fn dest_is_host(&self, ip: IpAddr, station: bool) -> bool {
snare_interpose::real(|| {
let topo = self.topo();
topo.dest_kind(ip) == DestKind::Unicast && topo.presence(ip, station) == Presence::Host
})
}
pub(crate) fn icmp_one_way(
&self,
sender: &Sender,
dest: IpAddr,
station: bool,
) -> Option<Duration> {
snare_interpose::real(|| {
let topo = self.topo();
if topo.dest_kind(dest) != DestKind::Unicast
|| topo.presence(dest, station) == Presence::Absent
{
return None;
}
if let Sender::Host(path) = sender
&& !path.local
&& path.gateway.is_none()
&& topo.segment(dest).is_some_and(|seg| seg != path.egress)
{
return None;
}
Some(match sender {
Sender::Host(path) if !path.local => topo
.policy_of(path.egress)
.map_or(Duration::ZERO, |p| p.latency),
_ => Duration::ZERO,
})
})
}
pub(crate) fn count_unreceived(&self, dest: SocketAddr, station: bool) {
let ip = dest.ip();
let (kind, host) = snare_interpose::real(|| {
let topo = self.topo();
(
topo.dest_kind(ip),
topo.presence(ip, station) == Presence::Host,
)
});
let udp = self.stats.udp(ip);
match kind {
DestKind::Unicast if host => crate::netstats::bump(&udp.no_ports),
DestKind::Unicast => {}
DestKind::Multicast if !self.host_joined(ip) => {}
_ => crate::netstats::bump(&udp.ignored_multi),
}
}
pub(crate) fn host_joined(&self, group: IpAddr) -> bool {
snare_interpose::real(|| self.sockets.live_recs().iter().any(|rec| rec.joined(group)))
}
pub(crate) fn topo(&self) -> MutexGuard<'_, Topology> {
self.topology.lock().unwrap_or_else(|e| e.into_inner())
}
fn finish(&self, after: After) {
for event in after.events {
self.record(event);
}
if after.kick {
self.kick();
}
}
pub(crate) fn init_topology(
&self,
host_nics: Vec<(NicSpec, NicCounters)>,
host_routes: Vec<Route>,
nics: Vec<NicSpec>,
routes: Vec<Route>,
) {
snare_interpose::real(|| {
let mut topo = self.topo();
let host_declared = !host_nics.is_empty();
for (spec, counters) in host_nics {
if let Some(index) = spec.index {
topo.make_room(index);
}
let name = spec.name.clone();
if let Err(e) = topo.insert(spec, counters) {
panic!("host interface {name}: {e}");
}
}
for spec in nics {
let name = spec.name.clone();
if let Err(e) = topo.insert(spec, NicCounters::default()) {
panic!("interface {name}: {e}");
}
}
let default_nic = if host_declared {
topo.nics
.iter()
.find(|n| !n.loopback)
.map(|n| n.spec.name.clone())
} else {
let index = topo.free_index(2);
topo.insert(NicSpec::new("sim0").index(index), NicCounters::default())
.expect("sim0");
topo.sim0 = Some(index);
Some("sim0".to_string())
};
let explicit_default = host_routes.iter().any(|r| r.dest.prefix == 0);
if let Some(name) = default_nic.filter(|_| !explicit_default) {
topo.routes.push(
Route::new(IpNet::new(Ipv4Addr::UNSPECIFIED.into(), 0), name.clone())
.metric(100),
);
topo.routes.push(
Route::new(IpNet::new(Ipv6Addr::UNSPECIFIED.into(), 0), name).metric(100),
);
}
for route in host_routes.into_iter().chain(routes) {
assert!(
topo.by_name(&route.nic).is_some(),
"route to {} via unknown interface {}",
route.dest,
route.nic
);
topo.routes.push(route);
}
});
}
pub(crate) fn add_nic(&self, spec: NicSpec) -> io::Result<u32> {
let (index, after) = snare_interpose::real(|| {
let mut topo = self.topo();
let name = spec.name.clone();
let (admin_up, carrier) = (spec.admin_up, spec.carrier);
let index = topo.insert(spec, NicCounters::default())?;
let after = After {
events: vec![RecordedEvent::NicChanged {
nic: name,
admin_up,
carrier,
}],
kick: true,
};
io::Result::Ok((index, after))
})?;
self.finish(after);
Ok(index)
}
pub(crate) fn remove_nic(&self, name: &str) -> io::Result<()> {
let after = snare_interpose::real(|| {
let mut topo = self.topo();
let nic = topo.by_name(name).ok_or_else(|| not_found(name))?;
if nic.loopback {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"the loopback interface cannot be removed",
));
}
let index = nic.index;
let pos = topo
.nics
.iter()
.position(|n| n.index == index)
.expect("nic");
let rec = topo.nics.remove(pos);
topo.routes.retain(|r| r.nic != name);
if topo.sim0 == Some(index) {
topo.sim0 = None;
}
rec.link.apply_due();
rec.link.schedule.lock().unwrap().clear();
let now = Deadline::after(Duration::ZERO).instant();
#[cfg(target_os = "macos")]
rec.link.remove(now);
#[cfg(not(target_os = "macos"))]
{
rec.link.set(Some(false), Some(false), now);
rec.link.removed.store(true, Ordering::Release);
}
Ok(After {
events: vec![RecordedEvent::NicChanged {
nic: name.to_string(),
admin_up: false,
carrier: false,
}],
kick: true,
})
})?;
self.finish(after);
Ok(())
}
pub(crate) fn set_nic(&self, name: &str, change: impl FnOnce(&mut NicSpec)) -> io::Result<()> {
let after = snare_interpose::real(|| {
let mut topo = self.topo();
let index = topo.index_of(name).ok_or_else(|| not_found(name))?;
let mut spec = topo.nic(index).expect("nic").snapshot().spec;
change(&mut spec);
if spec.name != name || spec.index != Some(index) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"an interface's name and index cannot change",
));
}
let current = topo.nic(index).expect("nic");
if !current.loopback
&& spec
.addresses
.iter()
.any(|n| current.origins.get(&n.addr) != Some(&Origin::Auto))
{
topo.open = false;
}
let now = Deadline::after(Duration::ZERO).instant();
let nic = topo.nic_mut(index).expect("nic");
let changed = nic.link.set(Some(spec.admin_up), Some(spec.carrier), now);
let origins = std::mem::take(&mut nic.origins);
nic.origins = spec
.addresses
.iter()
.map(|n| {
(
n.addr,
origins.get(&n.addr).copied().unwrap_or(Origin::Explicit),
)
})
.collect();
let event = RecordedEvent::NicChanged {
nic: name.to_string(),
admin_up: spec.admin_up,
carrier: spec.carrier,
};
nic.spec = spec;
Ok(After {
events: changed.then_some(event).into_iter().collect(),
kick: true,
})
})?;
self.finish(after);
Ok(())
}
pub(crate) fn set_link(&self, name: &str, carrier: bool) -> io::Result<()> {
self.set_nic(name, |spec| spec.carrier = carrier)
}
pub(crate) fn schedule_link(
&self,
name: &str,
after: Duration,
carrier: bool,
) -> io::Result<()> {
let at = snare_interpose::real(|| {
let topo = self.topo();
let nic = topo.by_name(name).ok_or_else(|| not_found(name))?;
let at = Deadline::after(after);
let mut schedule = nic.link.schedule.lock().unwrap();
let pos = schedule
.iter()
.position(|change| change.at.instant() > at.instant())
.unwrap_or(schedule.len());
schedule.insert(
pos,
LinkTransition {
at,
carrier,
#[cfg(windows)]
restart: None,
},
);
io::Result::Ok(at)
})?;
snare_interpose::real(|| at.wake_waiters_then());
self.kick();
Ok(())
}
#[cfg(windows)]
pub(crate) fn adapter_link(
&self,
name: &str,
generation: &Arc<Mutex<u64>>,
epoch: u64,
restore: Option<Deadline>,
) -> io::Result<()> {
let timer = restore.and_then(|at| snare_interpose::real(|| at.arm()));
let result = snare_interpose::real(|| {
let topo = self.topo();
let nic = topo.by_name(name).ok_or_else(|| not_found(name))?;
nic.link.apply_due();
let current = generation.lock().unwrap_or_else(|e| e.into_inner());
if *current != epoch {
return Ok((
After {
events: Vec::new(),
kick: false,
},
Vec::new(),
false,
));
}
let mut schedule = nic.link.schedule.lock().unwrap();
let mut cancelled = Vec::new();
schedule.retain(|change| {
if let Some(restart) = &change.restart
&& Arc::ptr_eq(&restart.generation, generation)
{
cancelled.extend(restart.timer);
false
} else {
true
}
});
let pending = restore.filter(|at| !at.passed());
let carrier = restore.is_some() && pending.is_none();
let changed = nic.link.set(
None,
Some(carrier),
Deadline::after(Duration::ZERO).instant(),
);
if let Some(at) = pending {
let pos = schedule
.iter()
.position(|change| change.at.instant() > at.instant())
.unwrap_or(schedule.len());
schedule.insert(
pos,
LinkTransition {
at,
carrier: true,
restart: Some(RestartTransition {
generation: generation.clone(),
epoch,
timer,
}),
},
);
}
Ok((
After {
events: changed
.then(|| RecordedEvent::NicChanged {
nic: name.to_owned(),
admin_up: nic.link.admin_up.load(Ordering::Acquire),
carrier,
})
.into_iter()
.collect(),
kick: true,
},
cancelled,
pending.is_some(),
))
});
match result {
Ok((after, cancelled, armed)) => {
if let Some(clock) = &self.clock {
for timer in cancelled {
clock.unregister_event(timer);
}
if !armed && let Some(timer) = timer {
clock.unregister_event(timer);
}
}
self.finish(after);
Ok(())
}
Err(error) => {
if let Some(clock) = &self.clock
&& let Some(timer) = timer
{
clock.unregister_event(timer);
}
Err(error)
}
}
}
#[cfg(windows)]
pub(crate) fn cancel_adapter_link(&self, name: &str, generation: &Arc<Mutex<u64>>) {
let cancelled = snare_interpose::real(|| {
let topo = self.topo();
let Some(nic) = topo.by_name(name) else {
return Vec::new();
};
let mut schedule = nic.link.schedule.lock().unwrap();
let mut cancelled = Vec::new();
schedule.retain(|change| {
if let Some(restart) = &change.restart
&& Arc::ptr_eq(&restart.generation, generation)
{
cancelled.extend(restart.timer);
false
} else {
true
}
});
cancelled
});
if let Some(clock) = &self.clock {
for timer in cancelled {
clock.unregister_event(timer);
}
}
self.kick();
}
pub(crate) fn set_nic_policy(
&self,
name: &str,
change: impl FnOnce(&mut NicPolicy),
) -> io::Result<()> {
snare_interpose::real(|| {
let mut topo = self.topo();
let index = topo.index_of(name).ok_or_else(|| not_found(name))?;
change(&mut topo.nic_mut(index).expect("nic").spec.policy);
io::Result::Ok(())
})?;
self.kick();
Ok(())
}
pub(crate) fn set_nic_counters(
&self,
name: &str,
change: impl FnOnce(&mut NicCounters),
) -> io::Result<()> {
snare_interpose::real(|| {
let mut topo = self.topo();
let index = topo.index_of(name).ok_or_else(|| not_found(name))?;
change(&mut topo.nic_mut(index).expect("nic").counters);
Ok(())
})
}
pub(crate) fn nic(&self, name: &str) -> Option<NicSnapshot> {
snare_interpose::real(|| self.topo().by_name(name).map(NicRec::snapshot))
}
pub(crate) fn nics(&self) -> Vec<NicSnapshot> {
snare_interpose::real(|| self.topo().nics.iter().map(NicRec::snapshot).collect())
}
pub(crate) fn nic_counters(&self, name: &str) -> Option<NicCounters> {
snare_interpose::real(|| self.topo().by_name(name).map(|n| n.counters))
}
pub(crate) fn add_route(&self, route: Route) -> io::Result<()> {
snare_interpose::real(|| {
let mut topo = self.topo();
if topo.by_name(&route.nic).is_none() {
return Err(not_found(&route.nic));
}
topo.routes.push(route);
Ok(())
})?;
self.kick();
Ok(())
}
pub(crate) fn remove_route(&self, dest: IpNet) -> bool {
let removed = snare_interpose::real(|| {
let mut topo = self.topo();
let before = topo.routes.len();
topo.routes.retain(|r| r.dest != dest);
topo.routes.len() != before
});
if removed {
self.kick();
}
removed
}
pub(crate) fn set_default_route(&self, nic: Option<&str>) -> io::Result<()> {
snare_interpose::real(|| {
let mut topo = self.topo();
if let Some(name) = nic
&& topo.by_name(name).is_none()
{
return Err(not_found(name));
}
topo.routes.retain(|r| r.dest.prefix != 0);
if let Some(name) = nic {
topo.routes.push(
Route::new(IpNet::new(Ipv4Addr::UNSPECIFIED.into(), 0), name).metric(100),
);
topo.routes.push(
Route::new(IpNet::new(Ipv6Addr::UNSPECIFIED.into(), 0), name).metric(100),
);
}
Ok(())
})?;
self.kick();
Ok(())
}
pub(crate) fn routes(&self) -> Vec<Route> {
snare_interpose::real(|| self.topo().all_routes())
}
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub(crate) fn live_routes(&self) -> Vec<(Route, u32)> {
snare_interpose::real(|| {
let topo = self.topo();
topo.all_routes()
.into_iter()
.filter_map(|route| {
let nic = topo.by_name(&route.nic)?;
nic.routes_live().then_some((route, nic.index))
})
.collect()
})
}
pub(crate) fn route_lookup(&self, src: Option<IpAddr>, dst: IpAddr) -> io::Result<RouteChoice> {
snare_interpose::real(|| {
let topo = self.topo();
let view = SockView {
local: src.map(|ip| SocketAddr::new(ip, 0)),
..SockView::default()
};
let path = topo
.egress(&view, dst, Op::Connect, topo.is_host(dst))
.map_err(io::Error::from_raw_os_error)?;
Ok(RouteChoice {
nic: path.name.to_string(),
index: path.egress,
src: Some(path.src),
gateway: path.gateway,
})
})
}
pub(crate) fn claim_address(&self, ip: IpAddr) -> Result<(), i32> {
self.topo().claim(ip)
}
pub(crate) fn route_send(
&self,
view: &SockView,
dest: SocketAddr,
op: Op,
station: bool,
broadcast_ok: bool,
) -> Result<Sender, i32> {
let result = {
let topo = self.topo();
if let Some(local) = view.local.filter(|l| topo.is_station_ip(l.ip())) {
return Ok(Sender::Station(local.ip()));
}
let kind = topo.dest_kind(dest.ip());
if matches!(kind, DestKind::Limited | DestKind::Directed(_)) && !broadcast_ok {
return Err(code::EACCES);
}
let dst_host =
kind == DestKind::Unicast && topo.presence(dest.ip(), station) == Presence::Host;
topo.egress(view, dest.ip(), op, dst_host)
};
result.map(Sender::Host).inspect_err(|&errno| {
if [code::ENETUNREACH, code::EHOSTUNREACH, code::ENETDOWN].contains(&errno) {
self.record(RecordedEvent::Fault {
addr: Some(dest),
fault: Fault::Unreachable { errno },
});
}
})
}
pub(crate) fn tcp_hop(&self, sender: &Sender, dest: IpAddr) -> Option<Hop> {
match sender {
Sender::Host(path) if path.local => None,
Sender::Host(path) => Some(Hop {
index: path.egress,
link: path.link.clone(),
}),
Sender::Station(_) => {
let topo = self.topo();
let index = topo.segment(dest)?;
Some(Hop {
index,
link: topo.link_of(index)?,
})
}
}
}
pub(crate) fn hop_name(&self, hop: Option<&Hop>) -> Option<String> {
let topo = self.topo();
topo.name_of(hop.map_or(topo.loopback_index(), |h| h.index))
}
pub(crate) fn hop_delay(&self, hop: Option<&Hop>) -> Duration {
let Some(policy) = hop.and_then(|hop| self.topo().policy_of(hop.index)) else {
return Duration::ZERO;
};
policy.latency + self.policies.jitter(policy.jitter)
}
#[cfg(windows)]
pub(crate) fn account_tcp(
&self,
hop: Option<&Hop>,
from_client: bool,
len: usize,
dest: IpAddr,
cut: (bool, bool),
) {
self.account_tcp_mss(hop, from_client, len, dest, cut, None);
}
pub(crate) fn account_tcp_mss(
&self,
hop: Option<&Hop>,
from_client: bool,
len: usize,
dest: IpAddr,
cut: (bool, bool),
mss: Option<usize>,
) {
if len == 0 {
return;
}
let v6 = dest.is_ipv6();
let mut topo = self.topo();
let mss_of =
|index: u32| topo.mtu_of(index).unwrap_or(1500).saturating_sub(40).max(1) as usize;
let segs = len
.div_ceil(mss.unwrap_or_else(|| mss_of(hop.map_or(topo.lo().index, |h| h.index))))
as u64;
let tcp = self.stats.tcp(dest);
if cut.0 {
tcp.out_segs
.fetch_add(segs, std::sync::atomic::Ordering::Relaxed);
}
if cut.1 {
tcp.in_segs
.fetch_add(segs, std::sync::atomic::Ordering::Relaxed);
}
let (index, dirs): (u32, &[Dir]) = match hop {
Some(hop) if !hop.link.usable() => return,
Some(hop) if from_client => (hop.index, &[Dir::Tx]),
Some(hop) => (hop.index, &[Dir::Rx]),
None => (topo.lo().index, &[Dir::Tx, Dir::Rx]),
};
let mss = mss.unwrap_or_else(|| mss_of(index));
let header = if v6 { 74 } else { 54 };
let mut left = len;
while left > 0 {
let seg = left.min(mss);
for dir in dirs {
topo.account(index, *dir, seg + header, false);
}
left -= seg;
}
}
pub(crate) fn fan_out<Q>(
&self,
sender: &Sender,
wire: Wire,
station: bool,
cands: Vec<Cand<Q>>,
tx: bool,
) -> Vec<Copy<Q>> {
let dest = wire.dest;
let mut topo = self.topo();
let dip = dest.ip();
let kind = topo.dest_kind(dip);
let mut cands: Vec<Cand<Q>> = cands
.into_iter()
.filter(|c| c.addr.port() == dest.port() && c.addr.is_ipv4() == dest.is_ipv4())
.collect();
let mut chosen: Vec<Cand<Q>> = match kind {
DestKind::Unicast => match cands.iter().position(|c| c.addr == dest) {
Some(i) => {
cands.swap(0, i);
cands.truncate(1);
cands
}
None if topo.presence(dip, station) == Presence::Host => cands
.into_iter()
.filter(|c| c.addr.ip().is_unspecified())
.collect(),
None => Vec::new(),
},
DestKind::Limited | DestKind::Multicast => cands,
DestKind::Directed(net) => cands
.into_iter()
.filter(|c| {
let ip = c.addr.ip();
let station = c.endpoint || topo.is_station_ip(ip);
ip.is_unspecified() || ip == dip || (station && net.contains(ip))
})
.collect(),
};
chosen.sort_by_key(|c| (c.addr.port(), c.addr.ip()));
let mut out = Vec::new();
self.fan_out_selected(&mut topo, sender, wire, kind, chosen, tx, |copy| {
out.push(copy)
});
out
}
#[cfg(unix)]
pub(crate) fn fan_out_one<Q>(
&self,
sender: &Sender,
wire: Wire,
station: bool,
cand: Option<Cand<Q>>,
tx: bool,
) -> Option<Copy<Q>> {
let mut topo = self.topo();
let dest = wire.dest;
let dip = dest.ip();
let kind = topo.dest_kind(dip);
let chosen = cand.filter(|c| {
if c.addr.port() != dest.port() || c.addr.is_ipv4() != dest.is_ipv4() {
return false;
}
match kind {
DestKind::Unicast => {
c.addr == dest
|| (c.addr.ip().is_unspecified()
&& topo.presence(dip, station) == Presence::Host)
}
DestKind::Limited | DestKind::Multicast => true,
DestKind::Directed(net) => {
let ip = c.addr.ip();
let station = c.endpoint || topo.is_station_ip(ip);
ip.is_unspecified() || ip == dip || (station && net.contains(ip))
}
}
});
let mut out = None;
self.fan_out_selected(&mut topo, sender, wire, kind, chosen, tx, |copy| {
out = Some(copy)
});
out
}
#[allow(clippy::too_many_arguments)]
fn fan_out_selected<Q>(
&self,
topo: &mut Topology,
sender: &Sender,
wire: Wire,
kind: DestKind,
chosen: impl IntoIterator<Item = Cand<Q>>,
tx: bool,
mut emit: impl FnMut(Copy<Q>),
) {
let Wire { src, dest, len } = wire;
let dip = dest.ip();
let multicast = kind == DestKind::Multicast;
let lo = topo.lo().index;
let frame = frame_len(dip, len);
let sender_up = match sender {
Sender::Host(path) if path.local => {
if tx {
topo.account(lo, Dir::Tx, frame, false);
}
true
}
Sender::Host(path) => {
let up = path.link.usable();
if tx && up {
topo.account(path.egress, Dir::Tx, frame, false);
} else if tx {
topo.count_carrier_drop(path.egress);
self.record(RecordedEvent::Fault {
addr: Some(dest),
fault: Fault::LinkDown {
nic: path.name.to_string(),
},
});
}
up
}
Sender::Station(_) => true,
};
for c in chosen {
let ip = c.addr.ip();
let rcpt_host = if c.endpoint {
topo.is_host(ip)
} else {
!topo.is_station_ip(ip)
};
let (crossing, ingress) = match sender {
Sender::Host(path) if rcpt_host => {
(None, Some(if path.local { lo } else { path.egress }))
}
Sender::Host(path) if path.local => (None, None),
Sender::Host(path) => {
let elsewhere = topo.segment(ip).is_some_and(|seg| seg != path.egress);
if !sender_up || elsewhere {
continue;
}
(Some(path.egress), None)
}
Sender::Station(sip) => {
let sender_host = topo.is_host(*sip);
match (sender_host, rcpt_host) {
(true, true) => (None, Some(lo)),
(true, false) => (topo.segment(ip), None),
(false, true) => {
let seg = topo.segment(*sip);
(seg, seg)
}
(false, false) => (topo.segment(*sip), None),
}
}
};
let egress = match sender {
Sender::Host(path) if path.local => Some(lo),
Sender::Host(path) => Some(path.egress),
Sender::Station(_) => None,
};
let mtu = [egress, crossing, ingress]
.into_iter()
.flatten()
.filter_map(|index| topo.mtu_of(index))
.min();
let mut via = None;
let mut policy = None;
if let Some(index) = crossing {
let Some(link) = topo.link_of(index) else {
continue;
};
if !link.usable() {
if rcpt_host {
topo.count_rx_drop(index);
}
continue;
}
via = Some((link.clone(), link.epoch()));
policy = topo.policy_of(index);
}
if rcpt_host && !cfg!(windows) && c.device.is_some() && c.device != ingress {
continue;
}
if rcpt_host
&& cfg!(windows)
&& !ip.is_unspecified()
&& let Some(ingress) = ingress.filter(|i| *i != lo)
&& topo.owner(ip).map(|n| n.index) != Some(ingress)
{
continue;
}
let (mut delays, faults) = self.policies.link_deliveries(policy.as_ref(), c.addr, len);
let held = self
.policies
.held_until_pair(src, dest, c.addr)
.map(|until| until.remaining());
if let Some(held) = held {
for delay in &mut delays {
*delay = (*delay).max(held);
}
}
for fault in faults {
self.record(RecordedEvent::Link {
from: src,
to: c.addr,
len,
fault,
});
}
let nic = match ingress.filter(|_| rcpt_host) {
Some(index) => {
for _ in &delays {
topo.account(index, Dir::Rx, frame, multicast);
}
topo.nic(index).map(|nic| nic.name.clone())
}
None => None,
};
emit(Copy {
q: c.q,
delays,
via,
nic,
mtu,
});
}
}
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
pub(crate) fn raw_send(&self, index: u32, len: usize) -> Result<bool, i32> {
let mut topo = self.topo();
let Some(nic) = topo.nic(index) else {
return Ok(true);
};
if cfg!(target_os = "linux") && !nic.link.admin() {
return Err(code::ENETDOWN);
}
if len > nic.spec.mtu as usize + 14 {
#[cfg(unix)]
return Err(libc::EMSGSIZE);
#[cfg(windows)]
return Err(10040);
}
if !nic.link.usable() {
topo.count_carrier_drop(index);
return Ok(false);
}
topo.account(index, Dir::Tx, len, false);
Ok(true)
}
}
impl crate::netpolicy::Policies {
pub(crate) fn link_deliveries(
&self,
nic: Option<&NicPolicy>,
to: SocketAddr,
len: usize,
) -> (crate::netpolicy::Delays, Vec<LinkFault>) {
let Some(nic) = nic else {
let (delays, fault) = self.deliveries(to, len);
return (delays, fault.into_iter().collect());
};
if nic.loss_rate > 0.0 && self.unit() < nic.loss_rate {
return (crate::netpolicy::Delays::default(), vec![LinkFault::Lost]);
}
let mut faults = Vec::new();
let copies = if nic.duplicate_rate > 0.0 && self.unit() < nic.duplicate_rate {
faults.push(LinkFault::Duplicated);
2
} else {
1
};
let base: crate::netpolicy::Delays = (0..copies)
.map(|_| nic.latency + self.jitter(nic.jitter))
.collect();
let mut delays = crate::netpolicy::Delays::default();
for first in base {
let (more, fault) = self.deliveries(to, len);
faults.extend(fault);
delays.extend(more.into_iter().map(|d| first + d));
}
(delays, faults)
}
}
#[track_caller]
pub fn add_nic(spec: NicSpec) -> io::Result<u32> {
scope::here().add_nic(spec)
}
#[track_caller]
pub fn remove_nic(name: &str) -> io::Result<()> {
scope::here().remove_nic(name)
}
#[track_caller]
pub fn set_nic(name: &str, change: impl FnOnce(&mut NicSpec)) -> io::Result<()> {
scope::here().set_nic(name, change)
}
#[track_caller]
pub fn set_link(name: &str, carrier: bool) -> io::Result<()> {
scope::here().set_link(name, carrier)
}
#[track_caller]
pub fn schedule_link(name: &str, after: Duration, carrier: bool) -> io::Result<()> {
scope::here().schedule_link(name, after, carrier)
}
#[track_caller]
pub fn set_nic_policy(name: &str, change: impl FnOnce(&mut NicPolicy)) -> io::Result<()> {
scope::here().set_nic_policy(name, change)
}
#[track_caller]
pub fn set_nic_counters(name: &str, change: impl FnOnce(&mut NicCounters)) -> io::Result<()> {
scope::here().set_nic_counters(name, change)
}
#[track_caller]
pub fn nic(name: &str) -> Option<NicSnapshot> {
scope::here().nic(name)
}
#[track_caller]
pub fn nics() -> Vec<NicSnapshot> {
scope::here().nics()
}
#[track_caller]
pub fn nic_counters(name: &str) -> Option<NicCounters> {
scope::here().nic_counters(name)
}
#[track_caller]
pub fn add_route(route: Route) -> io::Result<()> {
scope::here().add_route(route)
}
#[track_caller]
pub fn remove_route(dest: IpNet) -> bool {
scope::here().remove_route(dest)
}
#[track_caller]
pub fn set_default_route(nic: Option<&str>) -> io::Result<()> {
scope::here().set_default_route(nic)
}
#[track_caller]
pub fn routes() -> Vec<Route> {
scope::here().routes()
}
#[track_caller]
pub fn route_lookup(src: Option<IpAddr>, dst: IpAddr) -> io::Result<RouteChoice> {
scope::here().route_lookup(src, dst)
}
#[cfg(unix)]
pub(crate) mod sockopt {
use std::ffi::c_int;
use std::net::Ipv4Addr;
use crate::scope::SimShared;
use crate::sockets::SockRec;
#[cfg(target_os = "linux")]
const SO_BINDTODEVICE: c_int = 25;
#[cfg(target_os = "linux")]
const SO_BINDTOIFINDEX: c_int = 62;
#[cfg(target_os = "macos")]
const IP_BOUND_IF: c_int = 25;
#[cfg(target_os = "macos")]
const IPV6_BOUND_IF: c_int = 125;
#[cfg(target_os = "linux")]
const IP_MULTICAST_ALL: c_int = 49;
#[cfg(target_os = "linux")]
const IPV6_MULTICAST_ALL: c_int = 29;
fn read_int(val: *const u8, len: u32) -> Option<c_int> {
if val.is_null() || (len as usize) < size_of::<c_int>() {
return None;
}
Some(unsafe { val.cast::<c_int>().read_unaligned() })
}
pub(crate) unsafe fn set(
shared: &SimShared,
rec: &SockRec,
level: c_int,
name: c_int,
val: *const u8,
len: u32,
) -> Option<Result<(), c_int>> {
#[cfg(target_os = "linux")]
if level == libc::SOL_SOCKET
&& (name == SO_BINDTODEVICE || name == SO_BINDTOIFINDEX)
&& rec.state().device.is_some()
&& !shared.sys.has_cap(crate::limits::CAP_NET_RAW)
{
return Some(Err(libc::EPERM));
}
#[cfg(target_os = "linux")]
if level == libc::SOL_SOCKET && name == SO_BINDTODEVICE {
let bytes = if val.is_null() {
&[][..]
} else {
unsafe { std::slice::from_raw_parts(val, len as usize) }
};
let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
let Ok(dev) = std::str::from_utf8(&bytes[..end]) else {
return Some(Err(libc::EINVAL));
};
if dev.is_empty() {
rec.state().device = None;
return Some(Ok(()));
}
let Some(index) = shared.topo().index_of(dev) else {
return Some(Err(libc::ENODEV));
};
rec.state().device = Some((index, dev.to_string()));
return Some(Ok(()));
}
#[cfg(target_os = "linux")]
if level == libc::SOL_SOCKET && name == SO_BINDTOIFINDEX {
let Some(index) = read_int(val, len) else {
return Some(Err(libc::EINVAL));
};
return Some(bind_index(shared, rec, index, libc::ENODEV));
}
#[cfg(target_os = "macos")]
if (level == libc::IPPROTO_IP && name == IP_BOUND_IF)
|| (level == libc::IPPROTO_IPV6 && name == IPV6_BOUND_IF)
{
let Some(index) = read_int(val, len) else {
return Some(Err(libc::EINVAL));
};
return Some(bind_index(shared, rec, index, libc::ENXIO));
}
if level == libc::IPPROTO_IP && name == libc::IP_MULTICAST_IF {
if val.is_null() || len < 4 {
return Some(Err(libc::EINVAL));
}
let bytes = unsafe { std::slice::from_raw_parts(val, len as usize) };
let by_index = (cfg!(target_os = "linux") && bytes.len() >= 12)
.then(|| c_int::from_ne_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]))
.filter(|i| *i > 0);
let addr_at = if cfg!(target_os = "linux") && bytes.len() >= 12 {
4
} else {
0
};
let addr = Ipv4Addr::new(
bytes[addr_at],
bytes[addr_at + 1],
bytes[addr_at + 2],
bytes[addr_at + 3],
);
let topo = shared.topo();
let nic = match by_index {
Some(index) => topo.name_of(index as u32).map(|n| (index as u32, n)),
None if addr.is_unspecified() => {
drop(topo);
rec.state().mcast_if = None;
return Some(Ok(()));
}
None => topo
.owner(addr.into())
.map(|n| (n.index, n.spec.name.clone())),
};
drop(topo);
let Some(nic) = nic else {
return Some(Err(libc::EADDRNOTAVAIL));
};
rec.state().mcast_if = Some(nic);
return Some(Ok(()));
}
if level == libc::IPPROTO_IPV6 && name == libc::IPV6_MULTICAST_IF {
let Some(index) = read_int(val, len) else {
return Some(Err(libc::EINVAL));
};
if index == 0 {
rec.state().mcast_if = None;
return Some(Ok(()));
}
let Some(nic) = shared.topo().name_of(index as u32) else {
return Some(Err(libc::ENXIO));
};
rec.state().mcast_if = Some((index as u32, nic));
return Some(Ok(()));
}
#[cfg(target_os = "linux")]
if level == libc::IPPROTO_IP && name == IP_MULTICAST_ALL {
let v = match len {
_ if val.is_null() || len == 0 => return Some(Err(libc::EINVAL)),
1..4 => c_int::from(unsafe { *val }),
_ => read_int(val, len).unwrap_or_default(),
};
if v != 0 && v != 1 {
return Some(Err(libc::EINVAL));
}
rec.state().dgram.mc_all = v == 1;
return Some(Ok(()));
}
#[cfg(target_os = "linux")]
if level == libc::IPPROTO_IPV6 && name == IPV6_MULTICAST_ALL {
let Some(v) = read_int(val, len) else {
return Some(Err(libc::EINVAL));
};
rec.state().dgram.mc6_all = v != 0;
return Some(Ok(()));
}
let _ = (shared, rec, val, len);
None
}
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
fn bind_index(
shared: &SimShared,
rec: &SockRec,
index: c_int,
unknown: c_int,
) -> Result<(), c_int> {
if index == 0 {
rec.state().device = None;
return Ok(());
}
let Some(name) = u32::try_from(index)
.ok()
.and_then(|i| shared.topo().name_of(i))
else {
return Err(unknown);
};
rec.state().device = Some((index as u32, name));
Ok(())
}
pub(crate) unsafe fn get(
rec: &SockRec,
level: c_int,
name: c_int,
val: *mut u8,
len: *mut u32,
) -> Option<()> {
#[cfg(target_os = "linux")]
if level == libc::SOL_SOCKET && name == SO_BINDTODEVICE {
let dev = rec.state().device.clone();
if !val.is_null() && !len.is_null() {
let cap = unsafe { *len } as usize;
let bytes = dev.map(|(_, n)| n.into_bytes()).unwrap_or_default();
let n = if bytes.is_empty() {
0
} else {
(bytes.len() + 1).min(cap)
};
unsafe {
std::ptr::write_bytes(val, 0, n);
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
val,
n.saturating_sub(1).min(bytes.len()),
);
*len = n as u32;
}
}
return Some(());
}
let index = |dev: Option<(u32, String)>| dev.map_or(0, |(i, _)| i as c_int);
#[cfg(target_os = "linux")]
let value = (level == libc::SOL_SOCKET && name == SO_BINDTOIFINDEX)
.then(|| index(rec.state().device.clone()));
#[cfg(target_os = "macos")]
let value = ((level == libc::IPPROTO_IP && name == IP_BOUND_IF)
|| (level == libc::IPPROTO_IPV6 && name == IPV6_BOUND_IF))
.then(|| index(rec.state().device.clone()));
#[cfg(target_os = "linux")]
let value = value.or_else(|| {
let dgram = rec.state().dgram;
match (level, name) {
(libc::IPPROTO_IP, IP_MULTICAST_ALL) => Some(dgram.mc_all as c_int),
(libc::IPPROTO_IPV6, IPV6_MULTICAST_ALL) => Some(dgram.mc6_all as c_int),
_ => None,
}
});
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let value: Option<c_int> = None;
let value = value.or_else(|| {
(level == libc::IPPROTO_IPV6 && name == libc::IPV6_MULTICAST_IF)
.then(|| index(rec.state().mcast_if.clone()))
})?;
unsafe { crate::fabric::write_opt(value, val, len) };
Some(())
}
}
#[cfg(unix)]
pub(crate) mod frag {
use std::ffi::c_int;
use std::net::{IpAddr, SocketAddr};
use crate::scope::SimShared;
use crate::sockets::SockRec;
use super::Sender;
#[cfg(target_os = "linux")]
const IP_MTU_DISCOVER: c_int = 10;
#[cfg(target_os = "linux")]
const IPV6_MTU_DISCOVER: c_int = 23;
#[cfg(target_os = "macos")]
const IP_DONTFRAG: c_int = 28;
const IPV6_DONTFRAG: c_int = 62;
#[cfg(target_os = "linux")]
const PMTUDISC_OMIT: c_int = 5;
const PMTUDISC_NO_FRAG: std::ops::RangeInclusive<u8> = 2..=4;
const UDP_HEADER: usize = 8;
const IPV4_HEADER: usize = 20;
const IPV6_HEADER: usize = 40;
#[cfg(target_os = "linux")]
fn wrong_family(set: bool) -> c_int {
if set {
libc::ENOPROTOOPT
} else {
libc::EOPNOTSUPP
}
}
#[cfg(target_os = "linux")]
fn read_ip_int(val: *const u8, len: u32) -> c_int {
if val.is_null() || len == 0 {
return 0;
}
if (len as usize) < size_of::<c_int>() {
return c_int::from(unsafe { *val });
}
unsafe { val.cast::<c_int>().read_unaligned() }
}
fn read_full_int(val: *const u8, len: u32) -> Option<c_int> {
if val.is_null() || (len as usize) < size_of::<c_int>() {
return None;
}
Some(unsafe { val.cast::<c_int>().read_unaligned() })
}
#[cfg(target_os = "linux")]
pub(crate) unsafe fn set(
rec: &SockRec,
v6: bool,
level: c_int,
name: c_int,
val: *const u8,
len: u32,
) -> Option<Result<(), c_int>> {
match (level, name) {
(libc::IPPROTO_IP, IP_MTU_DISCOVER) => {
let mode = read_ip_int(val, len);
if !(0..=PMTUDISC_OMIT).contains(&mode) {
return Some(Err(libc::EINVAL));
}
rec.state().frag.pmtudisc = mode as u8;
Some(Ok(()))
}
(libc::IPPROTO_IPV6, IPV6_MTU_DISCOVER | IPV6_DONTFRAG) if !v6 => {
Some(Err(wrong_family(true)))
}
(libc::IPPROTO_IPV6, IPV6_MTU_DISCOVER) => match read_full_int(val, len) {
Some(mode) if (0..=PMTUDISC_OMIT).contains(&mode) => {
rec.state().frag.pmtudisc6 = mode as u8;
Some(Ok(()))
}
_ => Some(Err(libc::EINVAL)),
},
(libc::IPPROTO_IPV6, IPV6_DONTFRAG) => {
rec.state().frag.dontfrag6 = read_full_int(val, len).unwrap_or(0) != 0;
Some(Ok(()))
}
_ => None,
}
}
#[cfg(target_os = "macos")]
pub(crate) unsafe fn set(
rec: &SockRec,
v6: bool,
level: c_int,
name: c_int,
val: *const u8,
len: u32,
) -> Option<Result<(), c_int>> {
let ipv6 = match (level, name) {
(libc::IPPROTO_IP, IP_DONTFRAG) if !v6 => false,
(libc::IPPROTO_IPV6, IPV6_DONTFRAG) if v6 => true,
(libc::IPPROTO_IP, IP_DONTFRAG) | (libc::IPPROTO_IPV6, IPV6_DONTFRAG) => {
return Some(Err(libc::EINVAL));
}
_ => return None,
};
let Some(on) = read_full_int(val, len) else {
return Some(Err(libc::EINVAL));
};
let mut state = rec.state();
if ipv6 {
state.frag.dontfrag6 = on != 0;
} else {
state.frag.dontfrag = on != 0;
}
Some(Ok(()))
}
pub(crate) unsafe fn get(
rec: &SockRec,
v6: bool,
level: c_int,
name: c_int,
val: *mut u8,
len: *mut u32,
) -> Option<Result<(), c_int>> {
let frag = rec.state().frag;
#[cfg(target_os = "linux")]
let value = match (level, name) {
(libc::IPPROTO_IP, IP_MTU_DISCOVER) => c_int::from(frag.pmtudisc),
(libc::IPPROTO_IPV6, IPV6_MTU_DISCOVER | IPV6_DONTFRAG) if !v6 => {
return Some(Err(wrong_family(false)));
}
(libc::IPPROTO_IPV6, IPV6_MTU_DISCOVER) => c_int::from(frag.pmtudisc6),
(libc::IPPROTO_IPV6, IPV6_DONTFRAG) => c_int::from(frag.dontfrag6),
_ => return None,
};
#[cfg(target_os = "macos")]
let value = match (level, name) {
(libc::IPPROTO_IP, IP_DONTFRAG) if !v6 => c_int::from(frag.dontfrag),
(libc::IPPROTO_IPV6, IPV6_DONTFRAG) if v6 => c_int::from(frag.dontfrag6),
(libc::IPPROTO_IP, IP_DONTFRAG) | (libc::IPPROTO_IPV6, IPV6_DONTFRAG) => {
return Some(Err(libc::EINVAL));
}
_ => return None,
};
unsafe { write_int(value, val, len) };
Some(Ok(()))
}
unsafe fn write_int(value: c_int, val: *mut u8, len: *mut u32) {
if val.is_null() || len.is_null() {
return;
}
let cap = unsafe { *len } as usize;
let n = size_of::<c_int>().min(cap);
let n = if cfg!(target_os = "linux") && n < size_of::<c_int>() {
n.min(1)
} else {
n
};
let bytes = if cfg!(target_os = "linux") && n == 1 {
[value as u8, 0, 0, 0]
} else {
value.to_ne_bytes()
};
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), val, n);
*len = n as u32;
}
}
fn no_frag(rec: &SockRec, v6: bool, dest: SocketAddr) -> (bool, usize) {
let frag = rec.state().frag;
let v4_dest = match dest.ip() {
IpAddr::V4(_) => true,
IpAddr::V6(ip) => ip.to_ipv4_mapped().is_some(),
};
let headers = UDP_HEADER + if v4_dest { IPV4_HEADER } else { IPV6_HEADER };
let keep_whole = if cfg!(target_os = "linux") {
if v4_dest {
PMTUDISC_NO_FRAG.contains(&frag.pmtudisc)
} else {
PMTUDISC_NO_FRAG.contains(&frag.pmtudisc6) || frag.dontfrag6
}
} else if v6 {
frag.dontfrag6
} else {
frag.dontfrag
};
(keep_whole, headers)
}
pub(crate) fn check_send(
shared: &SimShared,
rec: &SockRec,
v6: bool,
sender: &Sender,
dest: SocketAddr,
len: usize,
) -> Result<(), c_int> {
let Sender::Host(path) = sender else {
return Ok(());
};
let (keep_whole, headers) = no_frag(rec, v6, dest);
if !keep_whole {
return Ok(());
}
let Some(mtu) = shared.nic(&path.name).map(|nic| nic.spec.mtu as usize) else {
return Ok(());
};
if len.saturating_add(headers) > mtu {
return Err(libc::EMSGSIZE);
}
Ok(())
}
}