//! Private active close with a two-entry custody table and explicit 2*MSL. use super::tcp_retransmit::{Sender, Snapshot as SenderSnapshot}; use super::tcp_handshake::{Principal, Tuple}; use super::ipv4_fragments::Datagram; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u64)] pub enum Error { Principal=1, State=2, Clock=3, Accounting=4, Foreign=5, Protocol=6, Tuple=7, Length=8, Flags=9, Checksum=10, Sequence=11, Acknowledgment=12, Busy=13, Capacity=14 } #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(C)] pub struct Entry { pub generation:u64, pub session:u64, pub principal:Principal, pub local:u64, pub remote:u64, pub local_port:u64, pub remote_port:u64, pub state:u64, pub deadline:u64, } impl Entry { const EMPTY:Self=Self { generation:0,session:0,principal:Principal{table:0,slot:0,generation:0},local:0,remote:0,local_port:0,remote_port:0,state:0,deadline:0 }; } #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(C)] pub struct TableSnapshot { pub identity:u64, pub next_generation:u64, pub entries:[Entry;2] } #[repr(C)] pub struct Table { state:TableSnapshot } #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(C)] struct Lease { table:u64, slot:u64, generation:u64, session:u64 } fn identity()->Result{ use core::sync::atomic::{AtomicU64,Ordering};static NEXT:AtomicU64=AtomicU64::new(1); NEXT.try_update(Ordering::Relaxed,Ordering::Relaxed,|v|v.checked_add(1)).map_err(|_|Error::Accounting) } impl Table { pub fn new()->Result{Ok(Self{state:TableSnapshot{identity:identity()?,next_generation:1,entries:[Entry::EMPTY;2]}})} pub fn snapshot(&self)->TableSnapshot{self.state} /// Admission query is meaningful only for callers using this same private /// table before an open; it is not a system-wide TCP tuple registry. pub fn available(&self,tuple:Tuple)->bool{ !self.state.entries.iter().any(|e|e.state!=0&&e.local==u32::from_be_bytes(tuple.local())as u64&&e.remote==u32::from_be_bytes(tuple.remote())as u64&&e.local_port==tuple.local_port()as u64&&e.remote_port==tuple.remote_port()as u64) } fn claim(&mut self,s:&SenderSnapshot)->Result{ let h=s.stream.session; if self.state.entries.iter().any(|e|e.state!=0&&e.local==h.local&&e.remote==h.remote&&e.local_port==h.local_port&&e.remote_port==h.remote_port){return Err(Error::Busy);} let slot=self.state.entries.iter().position(|e|e.state==0).ok_or(Error::Capacity)?; let generation=self.state.next_generation;let next=generation.checked_add(1).ok_or(Error::Accounting)?; self.state.entries[slot]=Entry{generation,session:h.identity,principal:h.principal,local:h.local,remote:h.remote,local_port:h.local_port,remote_port:h.remote_port,state:1,deadline:0};self.state.next_generation=next; Ok(Lease{table:self.state.identity,slot:slot as u64,generation,session:h.identity}) } fn validate(&self,lease:Lease)->Result<(),Error>{ if lease.table!=self.state.identity{return Err(Error::Foreign);} let e=self.state.entries.get(lease.slot as usize).ok_or(Error::Foreign)?; if e.state==0||e.generation!=lease.generation||e.session!=lease.session{return Err(Error::Foreign);}Ok(()) } fn timewait(&mut self,lease:Lease,deadline:u64){let e=&mut self.state.entries[lease.slot as usize];e.state=2;e.deadline=deadline;} fn release(&mut self,lease:Lease){self.state.entries[lease.slot as usize]=Entry{generation:lease.generation,..Entry::EMPTY};} } #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(C)] pub struct State { pub phase:u64, pub snd_nxt:u64, pub rcv_nxt:u64, pub fin_sequence:u64, pub tx_completed:u64, pub accepted_acks:u64, pub accepted_fins:u64, pub accepted_resets:u64, pub controls:u64, pub frequency:u64, pub msl_seconds:u64, pub timewait_ticks:u64, pub deadline:u64, pub last_clock:u64, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(C)] pub struct Snapshot { pub sender:SenderSnapshot, pub state:State, pub table:u64, pub slot:u64, pub generation:u64, pub session:u64 } #[derive(Debug, PartialEq, Eq)] pub struct Control { lease:Lease, serial:u64, kind:u64, bytes:[u8;20] } impl Control { pub fn bytes(&self)->&[u8;20]{&self.bytes} } /// Owns an idle sender, so its previously acknowledged send sequence and actual /// receiver cannot be substituted with caller-created historical metadata. #[repr(C)] pub struct Closing { sender:Sender, state:State, lease:Lease } fn sum(b:&[u8])->u32{b.chunks(2).map(|p|(u32::from(p[0])<<8)|u32::from(*p.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 Closing { pub fn new(sender:Sender,principal:Principal,table:&mut Table,msl_seconds:u64,now:u64)->Result{ let s=sender.snapshot();if s.stream.session.principal!=principal{return Err(Error::Principal);} if s.state.phase!=0||s.state.armed!=0||s.state.length!=0||s.state.snd_una!=s.state.snd_nxt{return Err(Error::State);} if msl_seconds==0||nowSnapshot{Snapshot{sender:self.sender.snapshot(),state:self.state,table:self.lease.table,slot:self.lease.slot,generation:self.lease.generation,session:self.lease.session}} fn check(&self,p:Principal,table:&Table,now:u64)->Result<(),Error>{ if p!=self.sender.snapshot().stream.session.principal{return Err(Error::Principal);} if self.state.phase>=6{return Err(Error::State);}table.validate(self.lease)?; if nowControl{ let s=self.sender.snapshot().stream.session;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(&(if kind==1{self.state.fin_sequence}else{self.state.snd_nxt}as u32).to_be_bytes());b[8..12].copy_from_slice(&(self.state.rcv_nxt as u32).to_be_bytes()); b[12]=0x50;b[13]=if kind==1{0x11}else{0x10};b[14..16].copy_from_slice(&512u16.to_be_bytes()); let c=!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(&c.to_be_bytes()); Control{lease:self.lease,serial:self.state.controls,kind,bytes:b} } pub fn begin(&mut self,p:Principal,table:&Table,now:u64)->Result{ self.check(p,table,now)?;if self.state.phase!=0{return Err(Error::State);} let n=self.state.controls.checked_add(1).ok_or(Error::Accounting)?; self.state.controls=n;self.state.phase=1;self.state.last_clock=now;Ok(self.packet(1)) } pub fn complete(&mut self,p:Principal,table:&mut Table,control:&Control,now:u64)->Result<(),Error>{ self.check(p,table,now)?;let kind=match self.state.phase{1=>1,4=>2,_=>return Err(Error::State)}; if *control!=self.packet(kind){return Err(Error::Foreign);} let count=self.state.tx_completed.checked_add(1).ok_or(Error::Accounting)?; let deadline=if kind==2{now.checked_add(self.state.timewait_ticks).ok_or(Error::Clock)?}else{0}; if kind==1{self.state.snd_nxt=(self.state.snd_nxt as u32).wrapping_add(1)as u64;self.state.phase=2;}else{self.state.phase=5;self.state.deadline=deadline;table.timewait(self.lease,deadline);} self.state.tx_completed=count;self.state.last_clock=now;Ok(()) } pub fn receive(&mut self,p:Principal,table:&mut Table,datagram:Datagram<'_>,now:u64)->Result,Error>{ self.check(p,table,now)?;let ip=datagram.packet();let h=self.sender.snapshot().stream.session; if ip.protocol()!=6{return Err(Error::Protocol);} if u32::from_be_bytes(ip.source())as u64!=h.remote||u32::from_be_bytes(ip.destination())as u64!=h.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!=h.remote_port||u16::from_be_bytes([b[2],b[3]])as u64!=h.local_port{return Err(Error::Tuple);} if b[12]&15!=0||!matches!(b[13],0x10|0x11|0x04|0x14)||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);} let seq=u32::from_be_bytes(b[4..8].try_into().unwrap());let ack=u32::from_be_bytes(b[8..12].try_into().unwrap());let flags=b[13]; let duplicate=flags==0x11&&self.state.phase==5; let want=if duplicate{(self.state.rcv_nxt as u32).wrapping_sub(1)}else{self.state.rcv_nxt as u32}; if seq!=want{return Err(Error::Sequence);}if flags&0x10!=0&&ack!=self.state.snd_nxt as u32{return Err(Error::Acknowledgment);} if flags&4!=0{ if !matches!(self.state.phase,0|2|3){return Err(Error::State);}let n=self.state.accepted_resets.checked_add(1).ok_or(Error::Accounting)?; table.release(self.lease);self.state.accepted_resets=n;self.state.phase=7;self.state.deadline=0;self.state.last_clock=now;return Ok(None); } if flags==0x10{ if self.state.phase!=2{return Err(Error::State);}let n=self.state.accepted_acks.checked_add(1).ok_or(Error::Accounting)?; self.state.accepted_acks=n;self.state.phase=3;self.state.last_clock=now;return Ok(None); } if !matches!(self.state.phase,2|3|5){return Err(Error::State);} let fins=self.state.accepted_fins.checked_add(1).ok_or(Error::Accounting)?;let controls=self.state.controls.checked_add(1).ok_or(Error::Accounting)?; let acks=self.state.accepted_acks.checked_add(u64::from(self.state.phase==2)).ok_or(Error::Accounting)?; self.state.accepted_fins=fins;self.state.accepted_acks=acks;self.state.controls=controls; if !duplicate{self.state.rcv_nxt=(self.state.rcv_nxt as u32).wrapping_add(1)as u64;} self.state.phase=4;self.state.last_clock=now;Ok(Some(self.packet(2))) } pub fn poll(&mut self,p:Principal,table:&mut Table,now:u64)->Result{ self.check(p,table,now)?;if self.state.phase!=5{return Err(Error::State);} if now[u64;24]{use core::mem::{size_of,offset_of};[size_of::()as u64,offset_of!(Self,sender)as u64,offset_of!(Self,state)as u64,offset_of!(Self,lease)as u64,size_of::()as u64,size_of::()as u64,(offset_of!(Self,state)+offset_of!(State,phase))as u64,(offset_of!(Self,state)+offset_of!(State,snd_nxt))as u64,(offset_of!(Self,state)+offset_of!(State,rcv_nxt))as u64,(offset_of!(Self,state)+offset_of!(State,fin_sequence))as u64,(offset_of!(Self,state)+offset_of!(State,tx_completed))as u64,(offset_of!(Self,state)+offset_of!(State,accepted_acks))as u64,(offset_of!(Self,state)+offset_of!(State,accepted_fins))as u64,(offset_of!(Self,state)+offset_of!(State,accepted_resets))as u64,(offset_of!(Self,state)+offset_of!(State,controls))as u64,(offset_of!(Self,state)+offset_of!(State,frequency))as u64,(offset_of!(Self,state)+offset_of!(State,msl_seconds))as u64,(offset_of!(Self,state)+offset_of!(State,timewait_ticks))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,lease)+offset_of!(Lease,table))as u64,(offset_of!(Self,lease)+offset_of!(Lease,slot))as u64,(offset_of!(Self,lease)+offset_of!(Lease,generation))as u64,(offset_of!(Self,lease)+offset_of!(Lease,session))as u64]}} impl Table {pub const fn os_k1900_physical_layout()->[u64;14]{use core::mem::{size_of,offset_of};[size_of::()as u64,offset_of!(TableSnapshot,identity)as u64,offset_of!(TableSnapshot,next_generation)as u64,offset_of!(TableSnapshot,entries)as u64,size_of::()as u64,offset_of!(Entry,generation)as u64,offset_of!(Entry,session)as u64,offset_of!(Entry,principal)as u64,offset_of!(Entry,local)as u64,offset_of!(Entry,remote)as u64,offset_of!(Entry,local_port)as u64,offset_of!(Entry,remote_port)as u64,offset_of!(Entry,state)as u64,offset_of!(Entry,deadline)as u64]}}