//! Serialized private sender: one small flight, one retry, bounded cleanup. //! An actual owned receiver establishes authority; snapshots cannot create it. use super::tcp_stream::{Stream, Snapshot as StreamSnapshot}; use super::tcp_handshake::Principal; use super::ipv4_fragments::Datagram; pub const CAPACITY: usize = 64; pub const MAX_RETRIES: u64 = 1; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u64)] pub enum Error { Principal = 1, State = 2, Capacity = 3, Clock = 4, Accounting = 5, Foreign = 6, Protocol = 7, Tuple = 8, Length = 9, Flags = 10, Checksum = 11, Acknowledgment = 12, Timeout = 13, Aborted = 14, Sequence = 15, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(C)] pub struct State { pub phase: u64, pub snd_una: u64, pub snd_nxt: u64, pub peer_window: u64, pub length: u64, pub operation: u64, pub attempt: u64, pub retries: u64, pub total_retries: u64, pub tx_completed: u64, pub acknowledged_bytes: u64, pub frequency: u64, pub rto: u64, pub deadline: u64, pub last_clock: u64, pub armed: u64, pub congestion_limit: u64, pub closed_reason: u64, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(C)] pub struct Snapshot { pub stream: StreamSnapshot, pub state: State, pub payload: [u8; CAPACITY] } /// Capability for one actual TX completion. Its fields and bytes are immutable. #[derive(Debug, PartialEq, Eq)] pub struct Transmission { identity: u64, operation: u64, attempt: u64, bytes: [u8; 20 + CAPACITY], length: usize, } impl Transmission { pub fn bytes(&self) -> &[u8] { &self.bytes[..self.length] } } #[repr(C)] pub struct Sender { stream: Stream, state: State, payload: [u8; CAPACITY] } fn sum(bytes: &[u8]) -> u32 { bytes.chunks(2).map(|b| (u32::from(b[0]) << 8) | u32::from(*b.get(1).unwrap_or(&0))).sum() } fn fold(mut n: u32) -> u16 { while n >> 16 != 0 { n = (n & 65535) + (n >> 16); } n as u16 } impl Sender { /// Frequency is a trusted monotonic clock's ticks per second. No RTT sample /// is taken from a retry; the backoff persists across application writes. pub fn new(stream: Stream, principal: Principal, frequency: u64) -> Result { let s = stream.snapshot(); if s.session.principal != principal { return Err(Error::Principal); } if s.session.phase != 4 || s.ready != 0 || s.buffered != 0 { return Err(Error::State); } if frequency == 0 || frequency > u64::MAX / 64 { return Err(Error::Clock); } Ok(Self { stream, state: State { phase: 0, snd_una: s.session.snd_nxt, snd_nxt: s.session.snd_nxt, peer_window: s.session.peer_window, length: 0, operation: 0, attempt: 0, retries: 0, total_retries: 0, tx_completed: 0, acknowledged_bytes: 0, frequency, rto: frequency, deadline: 0, last_clock: 0, armed: 0, congestion_limit: CAPACITY as u64, closed_reason: 0 }, payload: [0; CAPACITY] }) } pub fn snapshot(&self) -> Snapshot { Snapshot { stream: self.stream.snapshot(), state: self.state, payload: self.payload } } fn owner(&self, principal: Principal) -> Result<(), Error> { if self.stream.snapshot().session.principal != principal { return Err(Error::Principal); } if self.state.phase == 3 { return Err(Error::State); } Ok(()) } fn clock(&self, now: u64) -> Result<(), Error> { if now < self.state.last_clock { return Err(Error::Clock); } Ok(()) } fn transmission(&self) -> Transmission { let s = self.stream.snapshot().session; let mut b = [0u8; 20 + CAPACITY]; b[..2].copy_from_slice(&(s.local_port as u16).to_be_bytes()); b[2..4].copy_from_slice(&(s.remote_port as u16).to_be_bytes()); b[4..8].copy_from_slice(&(self.state.snd_una as u32).to_be_bytes()); b[8..12].copy_from_slice(&self.stream.next_sequence().to_be_bytes()); b[12] = 0x50; b[13] = 0x18; b[14..16].copy_from_slice(&self.stream.window().to_be_bytes()); let length = 20 + self.state.length as usize; b[20..length].copy_from_slice(&self.payload[..self.state.length as usize]); let c = !fold(sum(&(s.local as u32).to_be_bytes()) + sum(&(s.remote as u32).to_be_bytes()) + 6 + length as u32 + sum(&b[..length])); b[16..18].copy_from_slice(&c.to_be_bytes()); Transmission { identity: s.identity, operation: self.state.operation, attempt: self.state.attempt, bytes: b, length } } pub fn begin(&mut self, principal: Principal, payload: &[u8], now: u64) -> Result { self.owner(principal)?; self.clock(now)?; if self.state.phase != 0 { return Err(Error::State); } if payload.is_empty() || payload.len() > CAPACITY || payload.len() as u64 > self.state.peer_window { return Err(Error::Capacity); } let operation = self.state.operation.checked_add(1).ok_or(Error::Accounting)?; self.payload[..payload.len()].copy_from_slice(payload); self.state.length = payload.len() as u64; self.state.operation = operation; self.state.snd_nxt = (self.state.snd_una as u32).wrapping_add(payload.len() as u32) as u64; self.state.phase = 1; self.state.attempt = 1; self.state.retries = 0; self.state.last_clock = now; Ok(self.transmission()) } /// Driver calls this only after its device has completed the immutable TX. /// The transmission timeout starts here, never before a completed send. pub fn complete(&mut self, principal: Principal, sent: &Transmission, now: u64) -> Result<(), Error> { self.owner(principal)?; self.clock(now)?; if self.state.phase != 1 { return Err(Error::State); } if *sent != self.transmission() { return Err(Error::Foreign); } let deadline = now.checked_add(self.state.rto).ok_or(Error::Clock)?; let tx_completed = self.state.tx_completed.checked_add(1).ok_or(Error::Accounting)?; self.state.phase = 2; self.state.armed = 1; self.state.deadline = deadline; self.state.last_clock = now; self.state.tx_completed = tx_completed; Ok(()) } fn close(&mut self, reason: Error, now: u64) { self.payload.fill(0); self.state.phase = 3; self.state.length = 0; self.state.armed = 0; self.state.deadline = 0; self.state.rto = 0; self.state.peer_window = 0; self.state.congestion_limit = 0; self.state.last_clock = now; self.state.closed_reason = reason as u64; } pub fn abort(&mut self, principal: Principal, now: u64) -> Result<(), Error> { self.owner(principal)?; self.clock(now)?; self.close(Error::Aborted, now); Ok(()) } pub fn poll(&mut self, principal: Principal, now: u64) -> Result, Error> { self.owner(principal)?; self.clock(now)?; if self.state.phase != 2 || self.state.armed != 1 { return Err(Error::State); } if now < self.state.deadline { self.state.last_clock = now; return Ok(None); } if self.state.retries >= MAX_RETRIES { self.close(Error::Timeout, now); return Err(Error::Timeout); } let total_retries = self.state.total_retries.checked_add(1).ok_or(Error::Accounting)?; self.state.retries += 1; self.state.attempt += 1; self.state.total_retries = total_retries; // Bounded frequency makes 64 seconds representable; double without an // intermediate overflow. Never reset this backoff without a new RTT. self.state.rto = self.state.rto.saturating_mul(2).min(self.state.frequency * 64); self.state.phase = 1; self.state.armed = 0; self.state.deadline = 0; self.state.last_clock = now; Ok(Some(self.transmission())) } /// This private serialized adapter admits only a full cumulative ACK with /// no data/options. Partial ACKs and concurrent TX/ACK dispatch are outside /// its accepted scope. Refusals do not change payload, timer or sequence. pub fn acknowledge(&mut self, principal: Principal, datagram: Datagram<'_>, now: u64) -> Result { self.owner(principal)?; self.clock(now)?; if self.state.phase != 2 { return Err(Error::State); } let ip = datagram.packet(); let s = self.stream.snapshot().session; if ip.protocol() != 6 { return Err(Error::Protocol); } if u32::from_be_bytes(ip.source()) as u64 != s.remote || u32::from_be_bytes(ip.destination()) as u64 != s.local { return Err(Error::Tuple); } let b = datagram.payload(); if b.len() != 20 || b[12] >> 4 != 5 { return Err(Error::Length); } if u16::from_be_bytes([b[0],b[1]]) as u64 != s.remote_port || u16::from_be_bytes([b[2],b[3]]) as u64 != s.local_port { return Err(Error::Tuple); } if b[12] & 15 != 0 || b[13] != 0x10 || b[18] != 0 || b[19] != 0 { return Err(Error::Flags); } if fold(sum(&ip.source()) + sum(&ip.destination()) + 6 + 20 + sum(b)) != 65535 { return Err(Error::Checksum); } if u32::from_be_bytes(b[4..8].try_into().unwrap()) != self.stream.next_sequence() { return Err(Error::Sequence); } if u32::from_be_bytes(b[8..12].try_into().unwrap()) != self.state.snd_nxt as u32 { return Err(Error::Acknowledgment); } let n = self.state.length; let acknowledged = self.state.acknowledged_bytes.checked_add(n).ok_or(Error::Accounting)?; self.payload.fill(0); self.state.phase = 0; self.state.length = 0; self.state.snd_una = self.state.snd_nxt; self.state.acknowledged_bytes = acknowledged; self.state.peer_window = u16::from_be_bytes([b[14],b[15]]) as u64; self.state.armed = 0; self.state.deadline = 0; self.state.last_clock = now; Ok(n as usize) } } impl Sender { pub const fn os_k1895_physical_layout()->[u64;23] { use core::mem::{size_of,offset_of}; [size_of::()as u64,offset_of!(Self,stream)as u64,offset_of!(Self,state)as u64,offset_of!(Self,payload)as u64,size_of::()as u64, (offset_of!(Self,state)+offset_of!(State,phase))as u64,(offset_of!(Self,state)+offset_of!(State,snd_una))as u64,(offset_of!(Self,state)+offset_of!(State,snd_nxt))as u64,(offset_of!(Self,state)+offset_of!(State,peer_window))as u64,(offset_of!(Self,state)+offset_of!(State,length))as u64,(offset_of!(Self,state)+offset_of!(State,operation))as u64,(offset_of!(Self,state)+offset_of!(State,attempt))as u64,(offset_of!(Self,state)+offset_of!(State,retries))as u64,(offset_of!(Self,state)+offset_of!(State,total_retries))as u64,(offset_of!(Self,state)+offset_of!(State,tx_completed))as u64,(offset_of!(Self,state)+offset_of!(State,acknowledged_bytes))as u64,(offset_of!(Self,state)+offset_of!(State,frequency))as u64,(offset_of!(Self,state)+offset_of!(State,rto))as u64,(offset_of!(Self,state)+offset_of!(State,deadline))as u64,(offset_of!(Self,state)+offset_of!(State,last_clock))as u64,(offset_of!(Self,state)+offset_of!(State,armed))as u64,(offset_of!(Self,state)+offset_of!(State,congestion_limit))as u64,(offset_of!(Self,state)+offset_of!(State,closed_reason))as u64] }}