//! Owned 512-byte receive window for the established, one-way TCP subset. use super::ipv4_fragments::Datagram; use super::tcp_handshake::{Principal, Session, Snapshot as SessionSnapshot}; pub const CAPACITY: usize = 512; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u64)] pub enum Error { Principal = 1, State = 2, Protocol = 3, Tuple = 4, Length = 5, Options = 6, Flags = 7, Checksum = 8, Acknowledgment = 9, Window = 10, Conflict = 11, Empty = 12, Capacity = 13, Copy = 14, Accounting = 15, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(C)] pub struct Snapshot { pub session: SessionSnapshot, pub data: [u8; CAPACITY], pub present: [u8; CAPACITY], pub base: u64, pub head: u64, pub ready: u64, pub buffered: u64, pub segments: u64, pub duplicates: u64, pub out_of_order: u64, pub received_bytes: u64, pub delivered_bytes: u64, pub reads: u64, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Arrival { pub new_bytes: usize, pub duplicate_bytes: usize, pub trimmed_bytes: usize, pub ready: usize, pub next_sequence: u32, pub window: u16, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Receipt { pub length: usize, pub hash: u64, pub next_sequence: u32, pub window: u16, } /// Owns the actual Session, rather than trusting a caller-manufactured snapshot. /// There is no clone or mutable session accessor: one session has one receiver. #[repr(C)] pub struct Stream { session: Session, data: [u8; CAPACITY], present: [u8; CAPACITY], base: u64, head: u64, ready: u64, buffered: u64, segments: u64, duplicates: u64, out_of_order: u64, received_bytes: u64, delivered_bytes: u64, reads: u64, } 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 } pub fn byte_hash(bytes: &[u8]) -> u64 { bytes.iter().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)) } impl Stream { pub fn new(session: Session, principal: Principal) -> Result { let s = session.snapshot(); if s.principal != principal { return Err(Error::Principal); } if s.phase != 4 || s.tx_completed != 2 || s.accepted != 1 { return Err(Error::State); } Ok(Self { session, data: [0; CAPACITY], present: [0; CAPACITY], base: s.rcv_nxt, head: 0, ready: 0, buffered: 0, segments: 0, duplicates: 0, out_of_order: 0, received_bytes: 0, delivered_bytes: 0, reads: 0 }) } pub fn snapshot(&self) -> Snapshot { Snapshot { session: self.session.snapshot(), data: self.data, present: self.present, base: self.base, head: self.head, ready: self.ready, buffered: self.buffered, segments: self.segments, duplicates: self.duplicates, out_of_order: self.out_of_order, received_bytes: self.received_bytes, delivered_bytes: self.delivered_bytes, reads: self.reads } } fn owner(&self, principal: Principal) -> Result { let s = self.session.snapshot(); if s.principal != principal { return Err(Error::Principal); } if s.phase != 4 { return Err(Error::State); } Ok(s) } pub fn next_sequence(&self) -> u32 { (self.base as u32).wrapping_add(self.ready as u32) } pub fn window(&self) -> u16 { (CAPACITY as u64 - self.ready) as u16 } fn arrival(&self, new_bytes: usize, duplicate_bytes: usize, trimmed_bytes: usize) -> Arrival { Arrival { new_bytes, duplicate_bytes, trimmed_bytes, ready: self.ready as usize, next_sequence: self.next_sequence(), window: self.window() } } pub fn ingest(&mut self, principal: Principal, datagram: Datagram<'_>) -> Result { let s = self.owner(principal)?; let ip = datagram.packet(); 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.len() > 1480 { 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); } let header = (b[12] >> 4) as usize * 4; if header < 20 || header > b.len() { return Err(Error::Length); } if header != 20 { return Err(Error::Options); } if b[12] & 15 != 0 || !matches!(b[13], 0x10 | 0x18) || b[18] != 0 || b[19] != 0 { return Err(Error::Flags); } if fold(sum(&ip.source()) + sum(&ip.destination()) + 6 + b.len() as u32 + sum(b)) != 65535 { return Err(Error::Checksum); } // This receive-only endpoint has sent no application data after its SYN. if u32::from_be_bytes(b[8..12].try_into().unwrap()) != s.snd_nxt as u32 { return Err(Error::Acknowledgment); } let sequence = u32::from_be_bytes(b[4..8].try_into().unwrap()); let payload = &b[20..]; if payload.is_empty() { let offset = sequence.wrapping_sub(self.next_sequence()); if (self.window() == 0 && offset != 0) || (self.window() != 0 && offset >= u32::from(self.window())) { return Err(Error::Window); } return Ok(self.arrival(0, 0, 0)); } // Payload/window lengths are far below half the sequence space. Signed // modular distance also handles segments overlapping either window edge. let offset = i64::from(sequence.wrapping_sub(self.base as u32) as i32); let start = offset.max(0); let end = (offset + payload.len() as i64).min(CAPACITY as i64); if end <= start { return Err(Error::Window); } let mut new_bytes = 0usize; let mut duplicate_bytes = 0usize; // Validate all overlap and accounting before any payload/state write. for logical in start..end { let index = (self.head as usize + logical as usize) % CAPACITY; let byte = payload[(logical - offset) as usize]; if self.present[index] == 1 { if self.data[index] != byte { return Err(Error::Conflict); } duplicate_bytes += 1; } else { new_bytes += 1; } } let segments = self.segments.checked_add(1).ok_or(Error::Accounting)?; let duplicates = self.duplicates.checked_add(u64::from(new_bytes == 0)).ok_or(Error::Accounting)?; let out_of_order = self.out_of_order.checked_add(u64::from(new_bytes != 0 && start > self.ready as i64)).ok_or(Error::Accounting)?; let received_bytes = self.received_bytes.checked_add(new_bytes as u64).ok_or(Error::Accounting)?; for logical in start..end { let index = (self.head as usize + logical as usize) % CAPACITY; self.data[index] = payload[(logical - offset) as usize]; self.present[index] = 1; } self.buffered += new_bytes as u64; self.segments = segments; self.duplicates = duplicates; self.out_of_order = out_of_order; self.received_bytes = received_bytes; while self.ready < CAPACITY as u64 && self.present[(self.head as usize + self.ready as usize) % CAPACITY] == 1 { self.ready += 1; } Ok(self.arrival(new_bytes, duplicate_bytes, payload.len() - (end - start) as usize)) } /// Copy validates the whole destination before writing. A failed copy leaves /// the complete stream unchanged. Reads may be shorter than available data. pub fn read(&mut self, principal: Principal, capacity: usize, copy: impl FnOnce(&[u8]) -> Result<(), ()>) -> Result { self.owner(principal)?; if capacity == 0 { return Err(Error::Capacity); } if self.ready == 0 { return Err(Error::Empty); } let n = capacity.min(self.ready as usize); let reads = self.reads.checked_add(1).ok_or(Error::Accounting)?; let delivered_bytes = self.delivered_bytes.checked_add(n as u64).ok_or(Error::Accounting)?; let mut bytes = [0u8; CAPACITY]; for (i, byte) in bytes[..n].iter_mut().enumerate() { *byte = self.data[(self.head as usize + i) % CAPACITY]; } copy(&bytes[..n]).map_err(|_| Error::Copy)?; for i in 0..n { let at = (self.head as usize + i) % CAPACITY; self.data[at] = 0; self.present[at] = 0; } self.head = (self.head + n as u64) % CAPACITY as u64; self.base = (self.base as u32).wrapping_add(n as u32) as u64; self.ready -= n as u64; self.buffered -= n as u64; self.reads = reads; self.delivered_bytes = delivered_bytes; Ok(Receipt { length: n, hash: byte_hash(&bytes[..n]), next_sequence: self.next_sequence(), window: self.window() }) } /// Generates a cumulative ACK. The privileged adapter separately proves its /// actual TX completion and retains DMA ownership until the device is done. pub fn acknowledgment(&self, principal: Principal) -> Result<[u8; 20], Error> { let s = self.owner(principal)?; let mut b = [0u8; 20]; 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(&(s.snd_nxt as u32).to_be_bytes()); b[8..12].copy_from_slice(&self.next_sequence().to_be_bytes()); b[12] = 0x50; b[13] = 0x10; b[14..16].copy_from_slice(&self.window().to_be_bytes()); let checksum = !fold(sum(&(s.local as u32).to_be_bytes()) + sum(&(s.remote as u32).to_be_bytes()) + 6 + 20 + sum(&b)); b[16..18].copy_from_slice(&checksum.to_be_bytes()); Ok(b) } } impl Stream { pub const fn os_k1890_physical_layout()->[u64;14] { use core::mem::{size_of,offset_of}; [size_of::()as u64,offset_of!(Self,session)as u64, offset_of!(Self,data)as u64,offset_of!(Self,present)as u64, offset_of!(Self,base)as u64,offset_of!(Self,head)as u64, offset_of!(Self,ready)as u64,offset_of!(Self,buffered)as u64, offset_of!(Self,segments)as u64,offset_of!(Self,duplicates)as u64, offset_of!(Self,out_of_order)as u64,offset_of!(Self,received_bytes)as u64, offset_of!(Self,delivered_bytes)as u64,offset_of!(Self,reads)as u64] }}