Skip to main content

iphone_cli/tcp/
adapter.rs

1//! Core TCP state machine.
2//!
3//! [`Adapter`] owns the underlying transport and manages all TCP connections.
4//! It is the entry point for both usage patterns exposed by this crate:
5//!
6//! - **Single-task use**:  keep the `Adapter` directly and open streams with
7//!   [`crate::tcp::stream::AdapterStream::connect`].
8//! - **Multi-task use**: call [`Adapter::to_async_handle`] to move the adapter
9//!   into a background task and obtain an [`crate::tcp::handle::AdapterHandle`] that
10//!   can be shared across threads.
11//!
12//! See the [crate-level documentation](crate) for a full comparison.
13
14use std::{
15    collections::{HashMap, VecDeque},
16    io::ErrorKind,
17    net::IpAddr,
18    sync::Arc,
19};
20
21use std::path::Path;
22
23use crate::tcp::time::Instant;
24use tokio::io::{AsyncReadExt, AsyncWriteExt};
25use tracing::{debug, trace, warn};
26
27use crate::tcp::packets::{Ipv4Packet, Ipv6Packet, ProtocolNumber, TcpFlags, TcpPacket, UdpPacket};
28use crate::tcp::{PcapLog, ReadWrite, packets::IpParseError};
29
30/// A received UDP datagram, addressed from `peer_ip:source_port` to the local
31/// `destination_port`. UDP is connectionless, so there is no socket state
32/// beyond the set of bound local ports.
33#[derive(Debug, Clone)]
34pub struct UdpDatagram {
35    pub source_port: u16,
36    pub destination_port: u16,
37    pub data: Vec<u8>,
38}
39
40/// Maximum number of retransmission attempts before a connection is killed.
41///
42/// iphone-cli: 6 instead of 5, and a first timeout of 500 ms instead of 200
43/// (below). Upstream gives a connection up after 12.6 s without an
44/// acknowledgement. This stack runs inside a tunnel that is itself a TCP
45/// stream to the phone, so nothing is ever lost on the way, only held up:
46/// when the phone's Wi-Fi stalls for longer than that, upstream closes
47/// connections that would have gone on working (seen 2026-11-11: "timed out
48/// after 5 retransmissions" on the accessibility connection over Wi-Fi).
49/// With these values a connection lasts 63.5 s without an acknowledgement.
50const MAX_RETRIES: u32 = 6;
51
52/// Initial retransmission timeout in milliseconds. Doubles on each retry.
53const INITIAL_RTO_MS: u64 = 500;
54
55const OUR_WSCALE: u8 = 8;
56
57/// Default cap on bytes in flight per connection, in bytes. Overridden via
58/// [`Adapter::set_send_window`].
59const DEFAULT_SEND_WINDOW: usize = 1 << 20; // 1 MiB
60
61// ---------------------------------------------------------------------------
62// Unacknowledged segment tracking
63// ---------------------------------------------------------------------------
64
65#[derive(Debug, Clone)]
66struct UnackedSegment {
67    seq: u32,
68    data: Arc<[u8]>,
69    sent_at: Instant,
70    retries: u32,
71}
72
73impl UnackedSegment {
74    fn rto(&self) -> std::time::Duration {
75        // 0.5, 1, 2, 4, 8, 16, 32 s (capped)
76        std::time::Duration::from_millis(INITIAL_RTO_MS << self.retries.min(6))
77    }
78
79    fn is_timed_out(&self) -> bool {
80        self.sent_at.elapsed() >= self.rto()
81    }
82}
83
84// ---------------------------------------------------------------------------
85// Connection state
86// ---------------------------------------------------------------------------
87
88#[derive(Debug, Clone)]
89struct ConnectionState {
90    /// Next sequence number we will send.
91    seq: u32,
92    /// Next sequence number we expect from the peer (= what we put in ACK field).
93    ack: u32,
94    host_port: u16,
95    peer_port: u16,
96    read_buffer: Vec<u8>,
97    write_buffer: VecDeque<u8>,
98    status: ConnectionStatus,
99    /// Segments we have sent but not yet received an ACK for, in send order.
100    unacked: VecDeque<UnackedSegment>,
101    bytes_in_flight: usize,
102    peer_window: u32,
103    peer_wscale: Option<u8>,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
107pub(crate) enum ConnectionStatus {
108    WaitingForSyn,
109    Connected,
110    Error(ErrorKind),
111}
112
113impl ConnectionState {
114    fn new(host_port: u16, peer_port: u16) -> Self {
115        Self {
116            seq: rand::random(),
117            ack: 0,
118            host_port,
119            peer_port,
120            read_buffer: Vec::new(),
121            write_buffer: VecDeque::new(),
122            status: ConnectionStatus::WaitingForSyn,
123            unacked: VecDeque::new(),
124            bytes_in_flight: 0,
125            peer_window: 0,
126            peer_wscale: None,
127        }
128    }
129}
130
131// ---------------------------------------------------------------------------
132// Sequence number helpers (wrapping arithmetic)
133// ---------------------------------------------------------------------------
134
135/// Returns true if `a < b` in TCP sequence-number space.
136#[inline]
137fn seq_lt(a: u32, b: u32) -> bool {
138    (b.wrapping_sub(a) as i32) > 0
139}
140
141/// Returns true if `a <= b` in TCP sequence-number space.
142#[inline]
143fn seq_lte(a: u32, b: u32) -> bool {
144    (b.wrapping_sub(a) as i32) >= 0
145}
146
147// ---------------------------------------------------------------------------
148// Adapter
149// ---------------------------------------------------------------------------
150
151/// A userspace TCP stack backed by an arbitrary [`crate::tcp::ReadWrite`] transport.
152///
153/// `Adapter` drives the TCP state machine: it sends and receives raw IPv4/IPv6
154/// packets over `peer`, maintains per-connection state, and implements
155/// stop-and-wait retransmission.
156///
157/// # Lifecycle
158///
159/// 1. Construct with [`Adapter::new`], supplying the framed transport and the
160///    local/remote IP addresses.
161/// 2. Open connections with [`crate::tcp::stream::AdapterStream::connect`] **or** call
162///    [`Adapter::to_async_handle`] to get a thread-safe [`crate::tcp::handle::AdapterHandle`].
163/// 3. Optionally enable PCAP logging with [`Adapter::pcap`].
164///
165/// See the [crate-level documentation](crate) for a full comparison of both
166/// usage patterns.
167/// Default MSS: IPv6 min MTU (1280) minus headers.
168const DEFAULT_MSS: usize = 1280 - 40 - 20;
169
170#[derive(Debug)]
171pub struct Adapter {
172    peer: Box<dyn ReadWrite>,
173    host_ip: IpAddr,
174    peer_ip: IpAddr,
175    states: HashMap<u16, ConnectionState>,
176    dropped: Vec<u16>,
177    read_buf: [u8; 65536],
178    bytes_in_buf: usize,
179    pcap: Option<PcapLog>,
180    /// Maximum Segment Size for TCP data (payload only, no headers).
181    mss: usize,
182    send_window: usize,
183    udp_sockets: HashMap<u16, VecDeque<UdpDatagram>>,
184    /// IP packets waiting to be written to `peer`, oldest first. Writes go
185    /// through here because the adapter's futures are raced in `select!`s and
186    /// may be dropped at any await: a cancelled `write_all` would leave a
187    /// partial IP packet on the transport and desync the peer's framing.
188    outbox: VecDeque<Vec<u8>>,
189    /// How much of `outbox.front()` has already been written.
190    outbox_offset: usize,
191}
192
193impl Adapter {
194    pub fn new(peer: Box<dyn ReadWrite>, host_ip: IpAddr, peer_ip: IpAddr) -> Self {
195        Self {
196            peer,
197            host_ip,
198            peer_ip,
199            states: HashMap::new(),
200            dropped: Vec::new(),
201            read_buf: [0u8; 65536],
202            bytes_in_buf: 0,
203            pcap: None,
204            mss: DEFAULT_MSS,
205            send_window: DEFAULT_SEND_WINDOW,
206            udp_sockets: HashMap::new(),
207            outbox: VecDeque::new(),
208            outbox_offset: 0,
209        }
210    }
211
212    /// Set the Maximum Segment Size (MSS) for outbound TCP segments.
213    ///
214    /// This should be `MTU - 40 (IPv6 header) - 20 (TCP header)` for the
215    /// tunnel you are using. Defaults to 1220 (based on IPv6 min MTU 1280).
216    pub fn set_mss(&mut self, mss: usize) -> &mut Self {
217        self.mss = mss;
218        self
219    }
220
221    pub fn set_send_window(&mut self, window: usize) -> &mut Self {
222        self.send_window = window;
223        self
224    }
225
226    /// The local (host) IP address of this tunnel endpoint.
227    pub fn host_ip(&self) -> IpAddr {
228        self.host_ip
229    }
230
231    /// The remote (peer/device) IP address of this tunnel endpoint.
232    pub fn peer_ip(&self) -> IpAddr {
233        self.peer_ip
234    }
235
236    /// Wraps this adapter in a thread-safe handle.
237    pub fn to_async_handle(self) -> crate::tcp::handle::AdapterHandle {
238        crate::tcp::handle::AdapterHandle::new(self)
239    }
240
241    // -----------------------------------------------------------------------
242    // Public API
243    // -----------------------------------------------------------------------
244
245    pub(crate) async fn connect(&mut self, port: u16) -> Result<u16, std::io::Error> {
246        let host_port = loop {
247            let p: u16 = rand::random();
248            if !self.states.contains_key(&p) {
249                break p;
250            }
251        };
252        let state = ConnectionState::new(host_port, port);
253        self.states.insert(host_port, state);
254
255        // Send initial SYN.
256        self.send_syn(host_port).await?;
257
258        // Wait for SYN-ACK, retransmitting the SYN on timeout.
259        let start = Instant::now();
260        let mut last_syn = Instant::now();
261        loop {
262            self.process_tcp_packet().await?;
263
264            if let Some(s) = self.states.get(&host_port) {
265                match s.status {
266                    ConnectionStatus::Connected => break,
267                    ConnectionStatus::Error(e) => {
268                        self.states.remove(&host_port);
269                        return Err(std::io::Error::new(e, "failed to connect"));
270                    }
271                    ConnectionStatus::WaitingForSyn => {
272                        if start.elapsed() > std::time::Duration::from_secs(10) {
273                            self.states.remove(&host_port);
274                            return Err(std::io::Error::new(ErrorKind::TimedOut, "SYN timed out"));
275                        }
276                        // Retransmit SYN every INITIAL_RTO_MS * 2^retry ms.
277                        if last_syn.elapsed() >= std::time::Duration::from_millis(INITIAL_RTO_MS) {
278                            debug!("retransmitting SYN for port {host_port}");
279                            self.send_syn(host_port).await?;
280                            last_syn = Instant::now();
281                        }
282                    }
283                }
284            }
285        }
286
287        Ok(host_port)
288    }
289
290        pub async fn pcap(&mut self, path: impl AsRef<Path>) -> Result<(), std::io::Error> {
291        let mut file = tokio::fs::File::create(path).await?;
292        file.write_all(&0xa1b2c3d4_u32.to_le_bytes()).await?;
293        file.write_all(&2_u16.to_le_bytes()).await?;
294        file.write_all(&4_u16.to_le_bytes()).await?;
295        file.write_all(&0_i32.to_le_bytes()).await?;
296        file.write_all(&0_u32.to_le_bytes()).await?;
297        file.write_all(&(u16::MAX as u32).to_le_bytes()).await?;
298        file.write_all(&101_u32.to_le_bytes()).await?;
299        self.pcap = Some(std::sync::Arc::new(tokio::sync::Mutex::new(file)));
300        Ok(())
301    }
302
303    pub(crate) async fn close(&mut self, host_port: u16) -> Result<(), std::io::Error> {
304        if let Some(state) = self.states.remove(&host_port) {
305            let tcp = TcpPacket::create(
306                self.host_ip,
307                self.peer_ip,
308                state.host_port,
309                state.peer_port,
310                state.seq,
311                state.ack,
312                TcpFlags {
313                    fin: true,
314                    ack: true,
315                    ..Default::default()
316                },
317                u16::MAX - 1,
318                &[],
319                &[],
320            );
321            let ip = self.ip_wrap(&tcp);
322            self.log_packet(&ip)?;
323            self.send_packet(ip).await?;
324            Ok(())
325        } else {
326            Err(std::io::Error::new(
327                ErrorKind::NotConnected,
328                "not connected",
329            ))
330        }
331    }
332
333    /// Reset the connection: the peer drops it at once, unlike a FIN, which
334    /// a peer that never reads does not notice.
335    pub(crate) async fn abort(&mut self, host_port: u16) -> Result<(), std::io::Error> {
336        let Some(state) = self.states.remove(&host_port) else {
337            return Err(std::io::Error::new(ErrorKind::NotConnected, "not connected"));
338        };
339        let tcp = TcpPacket::create(
340            self.host_ip,
341            self.peer_ip,
342            state.host_port,
343            state.peer_port,
344            state.seq,
345            state.ack,
346            TcpFlags {
347                rst: true,
348                ack: true,
349                ..Default::default()
350            },
351            0,
352            &[],
353            &[],
354        );
355        let ip = self.ip_wrap(&tcp);
356        self.log_packet(&ip)?;
357        self.send_packet(ip).await
358    }
359
360    pub(crate) fn connection_drop(&mut self, host_port: u16) {
361        self.dropped.push(host_port);
362    }
363
364    pub(crate) fn queue_send(
365        &mut self,
366        payload: &[u8],
367        host_port: u16,
368    ) -> Result<(), std::io::Error> {
369        match self.states.get_mut(&host_port) {
370            Some(s) => {
371                s.write_buffer.extend(payload.iter().copied());
372                Ok(())
373            }
374            None => Err(std::io::Error::new(
375                ErrorKind::NotConnected,
376                "not connected",
377            )),
378        }
379    }
380
381    pub(crate) fn uncache(
382        &mut self,
383        to_copy: usize,
384        host_port: u16,
385    ) -> Result<Vec<u8>, std::io::Error> {
386        match self.states.get_mut(&host_port) {
387            Some(s) => {
388                let n = to_copy.min(s.read_buffer.len());
389                let out = s.read_buffer[..n].to_vec();
390                s.read_buffer.drain(..n);
391                Ok(out)
392            }
393            None => Err(std::io::Error::new(
394                ErrorKind::NotConnected,
395                "not connected",
396            )),
397        }
398    }
399
400    pub(crate) fn uncache_all(&mut self, host_port: u16) -> Result<Vec<u8>, std::io::Error> {
401        match self.states.get_mut(&host_port) {
402            Some(s) => {
403                let out = std::mem::take(&mut s.read_buffer);
404                Ok(out)
405            }
406            None => Err(std::io::Error::new(
407                ErrorKind::NotConnected,
408                "not connected",
409            )),
410        }
411    }
412
413    pub(crate) fn cache_read(
414        &mut self,
415        payload: &[u8],
416        host_port: u16,
417    ) -> Result<(), std::io::Error> {
418        match self.states.get_mut(&host_port) {
419            Some(s) => {
420                s.read_buffer.extend_from_slice(payload);
421                Ok(())
422            }
423            None => Err(std::io::Error::new(
424                ErrorKind::NotConnected,
425                "not connected",
426            )),
427        }
428    }
429
430    pub(crate) fn get_status(&self, host_port: u16) -> Result<ConnectionStatus, std::io::Error> {
431        match self.states.get(&host_port) {
432            Some(s) => Ok(s.status.clone()),
433            None => Err(std::io::Error::new(
434                ErrorKind::NotConnected,
435                "not connected",
436            )),
437        }
438    }
439
440    pub(crate) async fn recv(&mut self, host_port: u16) -> Result<Vec<u8>, std::io::Error> {
441        loop {
442            if let Some(state) = self.states.get_mut(&host_port) {
443                if !state.read_buffer.is_empty() {
444                    return Ok(std::mem::take(&mut state.read_buffer));
445                }
446                if let ConnectionStatus::Error(e) = state.status {
447                    return Err(std::io::Error::new(e, "socket io error"));
448                }
449            } else {
450                return Err(std::io::Error::new(
451                    ErrorKind::NotConnected,
452                    "not connected",
453                ));
454            }
455            self.process_tcp_packet().await?;
456        }
457    }
458
459    /// Queue an IP packet and write out as much of the outbox as possible.
460    async fn send_packet(&mut self, ip: Vec<u8>) -> Result<(), std::io::Error> {
461        self.outbox.push_back(ip);
462        self.flush_outbox().await
463    }
464
465    /// Write queued packets to the transport. Cancel safe: each `write` either
466    /// completes and is recorded in `outbox_offset`, or writes nothing.
467    async fn flush_outbox(&mut self) -> Result<(), std::io::Error> {
468        if self.outbox.is_empty() {
469            return Ok(());
470        }
471        while let Some(packet) = self.outbox.front() {
472            let n = self.peer.write(&packet[self.outbox_offset..]).await?;
473            if n == 0 {
474                return Err(std::io::Error::new(
475                    ErrorKind::WriteZero,
476                    "transport accepted no bytes",
477                ));
478            }
479            self.outbox_offset += n;
480            if self.outbox_offset == packet.len() {
481                self.outbox.pop_front();
482                self.outbox_offset = 0;
483            }
484        }
485        self.peer.flush().await
486    }
487
488    // -----------------------------------------------------------------------
489    // Flush / retransmit
490    // -----------------------------------------------------------------------
491
492    /// Returns true if any connection has unacked segments in flight, pending write-buffer bytes,
493    /// or connections waiting for SYN-ACK.
494    #[inline]
495    pub(crate) fn has_pending_work(&self) -> bool {
496        !self.dropped.is_empty()
497            || !self.outbox.is_empty()
498            || self.states.values().any(|s| {
499                !s.unacked.is_empty()
500                    || !s.write_buffer.is_empty()
501                    || matches!(s.status, ConnectionStatus::WaitingForSyn)
502            })
503    }
504
505    /// Drain pending write-buffer data into outbound segments, up to the
506    /// effective send window (`min(send_window, peer_window)`), then check
507    /// for timed-out retransmissions.
508    pub(crate) async fn write_buffer_flush(&mut self) -> Result<(), std::io::Error> {
509        // Finish writing anything a cancelled flush left behind first.
510        self.flush_outbox().await?;
511        // Check retransmissions first so a timed-out connection is marked before
512        // we attempt to send new data on it.
513        self.check_retransmissions().await?;
514
515        let host_ports: Vec<u16> = self.states.keys().cloned().collect();
516        for hp in host_ports {
517            // Inner loop: keep peeling off MSS-sized chunks until either the
518            // write buffer is empty or the window is full.
519            loop {
520                let chunk: Arc<[u8]> = {
521                    let Some(state) = self.states.get(&hp) else {
522                        break;
523                    };
524                    if state.write_buffer.is_empty() {
525                        break;
526                    }
527                    let cap = self.send_window.min(state.peer_window as usize);
528                    if state.bytes_in_flight >= cap {
529                        break;
530                    }
531                    let remaining = cap - state.bytes_in_flight;
532                    let n = state.write_buffer.len().min(self.mss).min(remaining);
533                    if n == 0 {
534                        break;
535                    }
536                    let v: Vec<u8> = state.write_buffer.iter().take(n).copied().collect();
537                    Arc::from(v)
538                };
539
540                let chunk_len = chunk.len();
541                if self.psh(chunk, hp).await.is_err() {
542                    break;
543                }
544                if let Some(state) = self.states.get_mut(&hp) {
545                    state.write_buffer.drain(..chunk_len);
546                }
547            }
548        }
549
550        // Reap connections that were dropped while we had the lock.
551        let dropped: Vec<u16> = std::mem::take(&mut self.dropped);
552        for hp in dropped {
553            if self.states.contains_key(&hp) {
554                self.close(hp).await.ok();
555            }
556        }
557
558        Ok(())
559    }
560
561    /// Check every connection for timed-out unacked segments. Retransmit the
562    /// oldest in-flight segment with exponential back-off; kill the connection
563    /// after MAX_RETRIES. Head-only retransmit suffices because TCP's
564    /// cumulative ACK semantics cause the peer to ACK everything they have
565    /// once the missing piece arrives.
566    async fn check_retransmissions(&mut self) -> Result<(), std::io::Error> {
567        let host_ports: Vec<u16> = self.states.keys().cloned().collect();
568
569        for hp in host_ports {
570            // Decide what to do before borrowing mutably.
571            enum Action {
572                Kill,
573                Retransmit { seq: u32, data: Arc<[u8]> },
574                None,
575            }
576
577            let action = match self.states.get(&hp) {
578                Some(state) => match state.unacked.front() {
579                    Some(seg) if seg.is_timed_out() => {
580                        if seg.retries >= MAX_RETRIES {
581                            Action::Kill
582                        } else {
583                            Action::Retransmit {
584                                seq: seg.seq,
585                                data: seg.data.clone(),
586                            }
587                        }
588                    }
589                    _ => Action::None,
590                },
591                None => Action::None,
592            };
593
594            match action {
595                Action::Kill => {
596                    warn!("hp={hp} timed out after {MAX_RETRIES} retransmissions; closing");
597                    if let Some(state) = self.states.get_mut(&hp) {
598                        state.status = ConnectionStatus::Error(ErrorKind::TimedOut);
599                        // Nothing will be sent on this connection again. Leaving the
600                        // segments queued would kill it again on every check and keep
601                        // reporting pending work forever.
602                        state.unacked.clear();
603                        state.bytes_in_flight = 0;
604                        state.write_buffer.clear();
605                    }
606                }
607                Action::Retransmit { seq, data } => {
608                    debug!("retransmitting {} bytes for hp={hp}", data.len());
609
610                    // Bump retry counter before the await so it's visible even if we're cancelled.
611                    if let Some(state) = self.states.get_mut(&hp)
612                        && let Some(seg) = state.unacked.front_mut()
613                    {
614                        seg.retries += 1;
615                        seg.sent_at = Instant::now();
616                    }
617
618                    let ip = {
619                        let Some(state) = self.states.get(&hp) else {
620                            continue;
621                        };
622                        let tcp = TcpPacket::create(
623                            self.host_ip,
624                            self.peer_ip,
625                            state.host_port,
626                            state.peer_port,
627                            seq,
628                            state.ack,
629                            TcpFlags {
630                                psh: true,
631                                ack: true,
632                                ..Default::default()
633                            },
634                            u16::MAX - 1,
635                            &[],
636                            &data,
637                        );
638                        self.ip_wrap(&tcp)
639                    };
640
641                    self.log_packet(&ip)?;
642                    self.send_packet(ip).await?;
643                }
644                Action::None => {}
645            }
646        }
647
648        Ok(())
649    }
650
651    // -----------------------------------------------------------------------
652    // Packet processing
653    // -----------------------------------------------------------------------
654
655    pub(crate) async fn process_tcp_packet(&mut self) -> Result<(), std::io::Error> {
656        tokio::select! {
657            ip_packet = self.read_ip_packet() => {
658                let (protocol, payload) = ip_packet?;
659                match protocol {
660                    p if p == ProtocolNumber::Tcp as u8 => {
661                        self.process_tcp_packet_from_payload(&payload).await
662                    }
663                    p if p == ProtocolNumber::Udp as u8 => {
664                        self.process_udp_packet(&payload);
665                        Ok(())
666                    }
667                    _ => Ok(()),
668                }
669            }
670            // Short timeout so retransmissions fire in the AdapterStream case
671            // (the AdapterHandle has a 1ms tick that calls write_buffer_flush directly).
672            _ = crate::tcp::time::sleep(std::time::Duration::from_millis(500)) => {
673                self.check_retransmissions().await
674            }
675        }
676    }
677
678    /// Parse an inbound UDP datagram and queue it if its destination port is
679    /// bound
680    fn process_udp_packet(&mut self, payload: &[u8]) {
681        let udp = match UdpPacket::parse(payload) {
682            Ok(u) => u,
683            Err(_) => return,
684        };
685        if let Some(queue) = self.udp_sockets.get_mut(&udp.destination_port) {
686            trace!(
687                "udp {} bytes -> local port {}",
688                udp.payload.len(),
689                udp.destination_port
690            );
691            queue.push_back(UdpDatagram {
692                source_port: udp.source_port,
693                destination_port: udp.destination_port,
694                data: udp.payload,
695            });
696        }
697    }
698
699    /// Bind a local UDP port so inbound datagrams to it are queued
700    pub(crate) fn bind_udp(&mut self, port: u16) -> u16 {
701        let port = if port == 0 {
702            loop {
703                let p: u16 = rand::random();
704                if p >= 1024 && !self.udp_sockets.contains_key(&p) {
705                    break p;
706                }
707            }
708        } else {
709            port
710        };
711        self.udp_sockets.entry(port).or_default();
712        port
713    }
714
715    pub(crate) fn unbind_udp(&mut self, port: u16) {
716        self.udp_sockets.remove(&port);
717    }
718
719    /// Send a UDP datagram from `source_port` to the peer's `destination_port`.
720    pub(crate) async fn send_udp(
721        &mut self,
722        source_port: u16,
723        destination_port: u16,
724        data: &[u8],
725    ) -> Result<(), std::io::Error> {
726        let udp = UdpPacket::create(
727            self.host_ip,
728            self.peer_ip,
729            source_port,
730            destination_port,
731            data,
732        );
733        let ip = self.ip_wrap_proto(&udp, ProtocolNumber::Udp);
734        self.log_packet(&ip)?;
735        self.send_packet(ip).await
736    }
737
738    /// Drain all queued inbound UDP datagrams across every bound port.
739    pub(crate) fn udp_drain(&mut self) -> Vec<UdpDatagram> {
740        let mut out = Vec::new();
741        for queue in self.udp_sockets.values_mut() {
742            out.extend(queue.drain(..));
743        }
744        out
745    }
746
747    pub(crate) async fn process_tcp_packet_from_payload(
748        &mut self,
749        payload: &[u8],
750    ) -> Result<(), std::io::Error> {
751        let res = TcpPacket::parse(payload)?;
752        let mut ack_me = None;
753
754        if let Some(state) = self.states.get_mut(&res.destination_port) {
755            // ------------------------------------------------------------------
756            // ACK processing: advance the unacked window.
757            // The peer's acknowledgment_number is the next seq they expect from us,
758            // so any segment with (seg.seq + seg.len) <= ack_num has been received.
759            // ------------------------------------------------------------------
760            if res.flags.ack {
761                let ack_num = res.acknowledgment_number;
762                while let Some(seg) = state.unacked.front() {
763                    let seg_end = seg.seq.wrapping_add(seg.data.len() as u32);
764                    if seq_lte(seg_end, ack_num) {
765                        let popped = state.unacked.pop_front().unwrap();
766                        state.bytes_in_flight =
767                            state.bytes_in_flight.saturating_sub(popped.data.len());
768                    } else {
769                        break;
770                    }
771                }
772            }
773
774            // Update peer's advertised receive window
775            if !(res.flags.syn) {
776                let shift = state.peer_wscale.unwrap_or(0);
777                state.peer_window = (res.window_size as u32) << shift;
778            }
779
780            // ------------------------------------------------------------------
781            // RST: hard close.
782            // ------------------------------------------------------------------
783            if res.flags.rst {
784                warn!("RST on hp={}", res.destination_port);
785                state.status = ConnectionStatus::Error(ErrorKind::ConnectionReset);
786                return Ok(());
787            }
788
789            match state.status {
790                ConnectionStatus::WaitingForSyn => {
791                    // We expect a SYN-ACK.
792                    if res.flags.syn && res.flags.ack {
793                        // SYN-ACK: peer's SYN consumes one seq number.
794                        state.ack = res.sequence_number.wrapping_add(1);
795                        // Our SYN consumed one sequence number on our side.
796                        state.seq = state.seq.wrapping_add(1);
797                        state.status = ConnectionStatus::Connected;
798                        state.peer_wscale = crate::tcp::packets::parse_window_scale(&res.options);
799                        let shift = state.peer_wscale.unwrap_or(0);
800                        state.peer_window = (res.window_size as u32) << shift;
801                        ack_me = Some(res.destination_port);
802                    }
803                    // Anything else while waiting for SYN-ACK is ignored.
804                }
805
806                ConnectionStatus::Connected => {
807                    // ----------------------------------------------------------
808                    // Keep-alive probe: seq == RCV.NXT - 1, no payload.
809                    // Just re-ACK without changing state.
810                    // ----------------------------------------------------------
811                    let is_keepalive = res.payload.is_empty()
812                        && !res.flags.fin
813                        && res.sequence_number.wrapping_add(1) == state.ack;
814
815                    let seg_end = res.sequence_number.wrapping_add(res.payload.len() as u32);
816
817                    if is_keepalive {
818                        debug!("keep-alive on hp={}", res.destination_port);
819                        ack_me = Some(res.destination_port);
820                    } else if !res.payload.is_empty() {
821                        // ------------------------------------------------------
822                        // Data segment: enforce in-order delivery.
823                        // ------------------------------------------------------
824                        if seq_lte(res.sequence_number, state.ack) && seq_lt(state.ack, seg_end) {
825                            let skip = state.ack.wrapping_sub(res.sequence_number) as usize;
826                            if skip > 0 {
827                                debug!(
828                                    "overlapping data seq={} expected={} hp={}",
829                                    res.sequence_number, state.ack, res.destination_port
830                                );
831                            }
832                            state.read_buffer.extend(&res.payload[skip..]);
833                            state.ack = seg_end;
834                        } else if seq_lt(res.sequence_number, state.ack) {
835                            // Duplicate (already received): re-ACK, don't buffer.
836                            debug!(
837                                "duplicate data seq={} expected={} hp={}",
838                                res.sequence_number, state.ack, res.destination_port
839                            );
840                        } else {
841                            debug!(
842                                "out-of-order seq={} expected={} hp={}",
843                                res.sequence_number, state.ack, res.destination_port
844                            );
845                        }
846                        ack_me = Some(res.destination_port);
847                    }
848
849                    if res.flags.fin {
850                        if seg_end == state.ack {
851                            state.ack = state.ack.wrapping_add(1);
852                            state.status = ConnectionStatus::Error(ErrorKind::UnexpectedEof);
853                        }
854                        ack_me = Some(res.destination_port);
855                    }
856                }
857
858                ConnectionStatus::Error(_) => {
859                    // Connection is already dead; ignore everything.
860                    trace!(
861                        "packet received on errored connection hp={}",
862                        res.destination_port
863                    );
864                }
865            }
866        }
867
868        if let Some(hp) = ack_me {
869            self.ack(hp).await?;
870        }
871        Ok(())
872    }
873
874    // -----------------------------------------------------------------------
875    // Low-level send helpers
876    // -----------------------------------------------------------------------
877
878    async fn send_syn(&mut self, host_port: u16) -> Result<(), std::io::Error> {
879        let Some(state) = self.states.get(&host_port) else {
880            return Err(std::io::Error::new(
881                ErrorKind::NotConnected,
882                "not connected",
883            ));
884        };
885        // Advertise window scaling so the peer can scale its window field.
886        let wscale = crate::tcp::packets::window_scale_option(OUR_WSCALE);
887        let tcp = TcpPacket::create(
888            self.host_ip,
889            self.peer_ip,
890            state.host_port,
891            state.peer_port,
892            state.seq,
893            0,
894            TcpFlags {
895                syn: true,
896                ..Default::default()
897            },
898            u16::MAX - 1,
899            &wscale,
900            &[],
901        );
902        let ip = self.ip_wrap(&tcp);
903        self.log_packet(&ip)?;
904        self.send_packet(ip).await
905    }
906
907    async fn ack(&mut self, host_port: u16) -> Result<(), std::io::Error> {
908        let Some(state) = self.states.get(&host_port) else {
909            return Err(std::io::Error::new(
910                ErrorKind::NotConnected,
911                "not connected",
912            ));
913        };
914        let tcp = TcpPacket::create(
915            self.host_ip,
916            self.peer_ip,
917            state.host_port,
918            state.peer_port,
919            state.seq,
920            state.ack,
921            TcpFlags {
922                ack: true,
923                ..Default::default()
924            },
925            u16::MAX - 1,
926            &[],
927            &[],
928        );
929        let ip = self.ip_wrap(&tcp);
930        let _ = state;
931        self.log_packet(&ip)?;
932        self.send_packet(ip).await
933    }
934
935    /// Send a PSH segment and record it in the unacked queue.
936    async fn psh(&mut self, data: Arc<[u8]>, host_port: u16) -> Result<(), std::io::Error> {
937        let Some(state) = self.states.get(&host_port) else {
938            return Err(std::io::Error::new(
939                ErrorKind::NotConnected,
940                "not connected",
941            ));
942        };
943        if let ConnectionStatus::Error(e) = state.status {
944            return Err(std::io::Error::new(e, "socket error"));
945        }
946        trace!("psh {} bytes on hp={host_port}", data.len());
947        let seq = state.seq;
948        let tcp = TcpPacket::create(
949            self.host_ip,
950            self.peer_ip,
951            state.host_port,
952            state.peer_port,
953            seq,
954            state.ack,
955            TcpFlags {
956                psh: true,
957                ack: true,
958                ..Default::default()
959            },
960            u16::MAX - 1,
961            &[],
962            &data,
963        );
964        let ip = self.ip_wrap(&tcp);
965        let _ = state;
966
967        // Record the segment before the await: the packet is queued either way, so
968        // a cancelled flush must not leave it to be sent again under a stale seq.
969        if let Some(state) = self.states.get_mut(&host_port) {
970            let len = data.len();
971            state.bytes_in_flight += len;
972            state.unacked.push_back(UnackedSegment {
973                seq,
974                data,
975                sent_at: Instant::now(),
976                retries: 0,
977            });
978            state.seq = state.seq.wrapping_add(len as u32);
979        }
980
981        self.log_packet(&ip)?;
982        self.send_packet(ip).await
983    }
984
985    async fn read_ip_packet(&mut self) -> Result<(u8, Vec<u8>), std::io::Error> {
986        self.write_buffer_flush().await?;
987        loop {
988            let parsed = match self.host_ip {
989                IpAddr::V4(_) => Self::try_parse_v4(&self.read_buf[..self.bytes_in_buf]),
990                IpAddr::V6(_) => {
991                    match Ipv6Packet::parse(&self.read_buf[..self.bytes_in_buf], &self.pcap) {
992                        IpParseError::Ok {
993                            packet,
994                            bytes_consumed,
995                        } => IpParseError::Ok {
996                            packet: (packet.next_header, packet.payload),
997                            bytes_consumed,
998                        },
999                        IpParseError::NotEnough => IpParseError::NotEnough,
1000                        IpParseError::Invalid => IpParseError::Invalid,
1001                    }
1002                }
1003            };
1004            match parsed {
1005                IpParseError::Ok {
1006                    packet,
1007                    bytes_consumed,
1008                } => {
1009                    if let Some(pcap) = &self.pcap
1010                        && matches!(self.host_ip, IpAddr::V4(_))
1011                    {
1012                        crate::tcp::log_packet(pcap, &self.read_buf[..bytes_consumed]);
1013                    }
1014
1015                    self.read_buf
1016                        .copy_within(bytes_consumed..self.bytes_in_buf, 0);
1017                    self.bytes_in_buf -= bytes_consumed;
1018                    return Ok(packet);
1019                }
1020                IpParseError::NotEnough => {}
1021                IpParseError::Invalid => {
1022                    let kind = if matches!(self.host_ip, IpAddr::V4(_)) {
1023                        "invalid IPv4 packet"
1024                    } else {
1025                        "invalid IPv6 packet"
1026                    };
1027                    return Err(std::io::Error::new(ErrorKind::InvalidData, kind));
1028                }
1029            }
1030            let n = self
1031                .peer
1032                .read(&mut self.read_buf[self.bytes_in_buf..])
1033                .await?;
1034            if n == 0 {
1035                return Err(std::io::Error::new(
1036                    ErrorKind::UnexpectedEof,
1037                    "transport closed",
1038                ));
1039            }
1040            self.bytes_in_buf += n;
1041        }
1042    }
1043
1044    /// Inspect the buffer for a complete IPv4 packet. Returns `(protocol,
1045    /// payload)` and the number of bytes consumed.
1046    fn try_parse_v4(buf: &[u8]) -> IpParseError<(u8, Vec<u8>)> {
1047        if buf.len() < 20 {
1048            return IpParseError::NotEnough;
1049        }
1050        if (buf[0] >> 4) != 4 {
1051            return IpParseError::Invalid;
1052        }
1053        let ihl_bytes = ((buf[0] & 0x0F) as usize) * 4;
1054        let total_length = u16::from_be_bytes([buf[2], buf[3]]) as usize;
1055        if ihl_bytes < 20 || total_length < ihl_bytes {
1056            return IpParseError::Invalid;
1057        }
1058        if buf.len() < total_length {
1059            return IpParseError::NotEnough;
1060        }
1061        let packet = match Ipv4Packet::parse(&buf[..total_length]) {
1062            Some(p) => p,
1063            None => return IpParseError::Invalid,
1064        };
1065        IpParseError::Ok {
1066            packet: (packet.protocol, packet.payload),
1067            bytes_consumed: total_length,
1068        }
1069    }
1070
1071    fn log_packet(&self, packet: &[u8]) -> Result<(), std::io::Error> {
1072        if let Some(file) = &self.pcap {
1073            crate::tcp::log_packet(file, packet);
1074        }
1075        Ok(())
1076    }
1077
1078    fn ip_wrap(&self, packet: &[u8]) -> Vec<u8> {
1079        self.ip_wrap_proto(packet, ProtocolNumber::Tcp)
1080    }
1081
1082    fn ip_wrap_proto(&self, packet: &[u8], protocol: ProtocolNumber) -> Vec<u8> {
1083        match (self.host_ip, self.peer_ip) {
1084            (IpAddr::V4(src), IpAddr::V4(dst)) => {
1085                Ipv4Packet::create(src, dst, protocol, 255, packet)
1086            }
1087            (IpAddr::V6(src), IpAddr::V6(dst)) => {
1088                Ipv6Packet::create(src, dst, protocol, 255, packet)
1089            }
1090            _ => panic!("host_ip and peer_ip must be the same IP version"),
1091        }
1092    }
1093}
1094
1095// ---------------------------------------------------------------------------
1096// Tests
1097// ---------------------------------------------------------------------------
1098
1099#[cfg(test)]
1100mod tests {
1101    use super::*;
1102    use crate::tcp::packets::{IpParseError, ProtocolNumber, TcpFlags, TcpPacket};
1103    use std::net::{IpAddr, Ipv6Addr};
1104    use std::pin::Pin;
1105    use std::task::{Context, Poll};
1106    use std::time::Duration;
1107    use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, DuplexStream, ReadBuf};
1108
1109    const HOST_IP: Ipv6Addr = Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 1);
1110    const PEER_IP: Ipv6Addr = Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 2);
1111    const PEER_PORT: u16 = 80;
1112    /// Peer's initial sequence number
1113    const PEER_ISN: u32 = 5000;
1114
1115    // ------------------------------------------------------------------
1116    // Test transport
1117    // ------------------------------------------------------------------
1118
1119    struct TestTransport(DuplexStream);
1120
1121    impl std::fmt::Debug for TestTransport {
1122        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1123            write!(f, "TestTransport")
1124        }
1125    }
1126
1127    impl AsyncRead for TestTransport {
1128        fn poll_read(
1129            mut self: Pin<&mut Self>,
1130            cx: &mut Context<'_>,
1131            buf: &mut ReadBuf<'_>,
1132        ) -> Poll<std::io::Result<()>> {
1133            Pin::new(&mut self.0).poll_read(cx, buf)
1134        }
1135    }
1136
1137    impl AsyncWrite for TestTransport {
1138        fn poll_write(
1139            mut self: Pin<&mut Self>,
1140            cx: &mut Context<'_>,
1141            buf: &[u8],
1142        ) -> Poll<std::io::Result<usize>> {
1143            Pin::new(&mut self.0).poll_write(cx, buf)
1144        }
1145        fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
1146            Pin::new(&mut self.0).poll_flush(cx)
1147        }
1148        fn poll_shutdown(
1149            mut self: Pin<&mut Self>,
1150            cx: &mut Context<'_>,
1151        ) -> Poll<std::io::Result<()>> {
1152            Pin::new(&mut self.0).poll_shutdown(cx)
1153        }
1154    }
1155
1156    // ------------------------------------------------------------------
1157    // Packet helpers
1158    // ------------------------------------------------------------------
1159
1160    /// Build a raw TCP segment (not IP-wrapped) from PEER→adapter.
1161    fn tcp_seg(dst_port: u16, seq: u32, ack_num: u32, flags: TcpFlags, payload: &[u8]) -> Vec<u8> {
1162        tcp_seg_with_opts(dst_port, seq, ack_num, flags, &[], payload)
1163    }
1164
1165    fn tcp_seg_with_opts(
1166        dst_port: u16,
1167        seq: u32,
1168        ack_num: u32,
1169        flags: TcpFlags,
1170        options: &[u8],
1171        payload: &[u8],
1172    ) -> Vec<u8> {
1173        TcpPacket::create(
1174            IpAddr::V6(PEER_IP),
1175            IpAddr::V6(HOST_IP),
1176            PEER_PORT,
1177            dst_port,
1178            seq,
1179            ack_num,
1180            flags,
1181            u16::MAX - 1,
1182            options,
1183            payload,
1184        )
1185    }
1186
1187    /// Build an IPv6-wrapped TCP packet from PEER→adapter (for injection into transport).
1188    fn peer_ipv6_pkt(
1189        dst_port: u16,
1190        seq: u32,
1191        ack_num: u32,
1192        flags: TcpFlags,
1193        payload: &[u8],
1194    ) -> Vec<u8> {
1195        let tcp = tcp_seg(dst_port, seq, ack_num, flags, payload);
1196        crate::tcp::packets::Ipv6Packet::create(PEER_IP, HOST_IP, ProtocolNumber::Tcp, 255, &tcp)
1197    }
1198
1199    /// Read one complete IPv6 packet the adapter wrote to the transport.
1200    async fn read_pkt(reader: &mut (impl AsyncRead + Unpin)) -> TcpPacket {
1201        let mut hdr = [0u8; 40];
1202        reader.read_exact(&mut hdr).await.unwrap();
1203        let plen = u16::from_be_bytes([hdr[4], hdr[5]]) as usize;
1204        let mut rest = vec![0u8; plen];
1205        reader.read_exact(&mut rest).await.unwrap();
1206        let mut full = hdr.to_vec();
1207        full.extend_from_slice(&rest);
1208        let ip = match crate::tcp::packets::Ipv6Packet::parse(&full, &None) {
1209            IpParseError::Ok { packet, .. } => packet,
1210            _ => panic!("not a valid IPv6 packet from adapter"),
1211        };
1212        TcpPacket::parse(&ip.payload).unwrap()
1213    }
1214
1215    // ------------------------------------------------------------------
1216    // Handshake helper
1217    // ------------------------------------------------------------------
1218
1219    /// Drive the adapter's `connect` and the test-peer response concurrently.
1220    /// Returns the host port the adapter chose.
1221    async fn handshake(
1222        adapter: &mut Adapter,
1223        test_rx: &mut (impl AsyncRead + Unpin),
1224        test_tx: &mut (impl AsyncWrite + Unpin),
1225    ) -> u16 {
1226        let (hp_result, peer_hp) = tokio::join!(adapter.connect(PEER_PORT), async {
1227            // Read the SYN the adapter sends immediately on connect().
1228            let syn = read_pkt(test_rx).await;
1229            assert!(syn.flags.syn, "first packet from adapter should be SYN");
1230            let hp = syn.source_port;
1231
1232            // Send SYN-ACK.
1233            test_tx
1234                .write_all(&peer_ipv6_pkt(
1235                    hp,
1236                    PEER_ISN,
1237                    syn.sequence_number.wrapping_add(1),
1238                    TcpFlags {
1239                        syn: true,
1240                        ack: true,
1241                        ..Default::default()
1242                    },
1243                    &[],
1244                ))
1245                .await
1246                .unwrap();
1247
1248            // Consume the ACK the adapter sends to complete the handshake.
1249            let ack = read_pkt(test_rx).await;
1250            assert!(
1251                ack.flags.ack,
1252                "adapter should send ACK to complete handshake"
1253            );
1254
1255            hp
1256        });
1257        let hp = hp_result.expect("connect failed");
1258        assert_eq!(hp, peer_hp);
1259        hp
1260    }
1261
1262    // ------------------------------------------------------------------
1263    // Tests
1264    // ------------------------------------------------------------------
1265
1266    /// After the RTO elapses without an ACK, the same segment is retransmitted
1267    /// with the same sequence number.
1268    #[tokio::test]
1269    async fn retransmit_fires_after_rto() {
1270        tokio::time::pause();
1271
1272        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1273        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1274        let mut adapter = Adapter::new(
1275            Box::new(TestTransport(adapter_end)),
1276            IpAddr::V6(HOST_IP),
1277            IpAddr::V6(PEER_IP),
1278        );
1279
1280        let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await;
1281
1282        // Queue and flush data; the adapter sends a PSH segment.
1283        adapter.queue_send(b"hello", hp).unwrap();
1284        adapter.write_buffer_flush().await.unwrap();
1285
1286        let psh1 = read_pkt(&mut test_rx).await;
1287        assert_eq!(psh1.payload, b"hello");
1288        let original_seq = psh1.sequence_number;
1289
1290        // Advance past the initial RTO without ACKing.
1291        tokio::time::advance(Duration::from_millis(INITIAL_RTO_MS + 1)).await;
1292        adapter.write_buffer_flush().await.unwrap();
1293
1294        // The adapter should retransmit the same segment.
1295        let psh2 = read_pkt(&mut test_rx).await;
1296        assert_eq!(
1297            psh2.payload, b"hello",
1298            "retransmit payload must match original"
1299        );
1300        assert_eq!(
1301            psh2.sequence_number, original_seq,
1302            "retransmit must reuse the original sequence number"
1303        );
1304    }
1305
1306    /// Advancing through all retry intervals marks the connection as
1307    /// `Error(TimedOut)` once MAX_RETRIES is exhausted.
1308    #[tokio::test]
1309    async fn connection_killed_after_max_retries() {
1310        tokio::time::pause();
1311
1312        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1313        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1314        let mut adapter = Adapter::new(
1315            Box::new(TestTransport(adapter_end)),
1316            IpAddr::V6(HOST_IP),
1317            IpAddr::V6(PEER_IP),
1318        );
1319
1320        let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await;
1321
1322        adapter.queue_send(b"data", hp).unwrap();
1323        adapter.write_buffer_flush().await.unwrap();
1324        read_pkt(&mut test_rx).await; // initial send
1325
1326        // Drive through MAX_RETRIES retransmits (each with its doubled RTO),
1327        // then one more check which should kill the connection.
1328        for i in 0..=MAX_RETRIES {
1329            let rto = Duration::from_millis(INITIAL_RTO_MS << i.min(6));
1330            tokio::time::advance(rto + Duration::from_millis(1)).await;
1331            adapter.write_buffer_flush().await.unwrap();
1332
1333            if i < MAX_RETRIES {
1334                // Drain the retransmit so the duplex buffer doesn't fill up.
1335                read_pkt(&mut test_rx).await;
1336            }
1337            // On the final iteration the connection is killed instead of retransmitting.
1338        }
1339
1340        assert_eq!(
1341            adapter.get_status(hp).unwrap(),
1342            ConnectionStatus::Error(ErrorKind::TimedOut),
1343            "connection should be Error(TimedOut) after exhausting retries"
1344        );
1345    }
1346
1347    #[tokio::test]
1348    async fn ack_clears_unacked_queue() {
1349        tokio::time::pause();
1350
1351        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1352        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1353        let mut adapter = Adapter::new(
1354            Box::new(TestTransport(adapter_end)),
1355            IpAddr::V6(HOST_IP),
1356            IpAddr::V6(PEER_IP),
1357        );
1358        adapter.set_send_window(5);
1359
1360        let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await;
1361
1362        adapter.queue_send(b"first", hp).unwrap();
1363        adapter.write_buffer_flush().await.unwrap();
1364        let psh1 = read_pkt(&mut test_rx).await;
1365        assert_eq!(psh1.payload, b"first");
1366
1367        // Queue second chunk; window is full, must be held.
1368        adapter.queue_send(b"secnd", hp).unwrap();
1369        adapter.write_buffer_flush().await.unwrap();
1370
1371        // Nothing should appear on the wire yet.
1372        let nothing = tokio::time::timeout(Duration::from_millis(10), read_pkt(&mut test_rx)).await;
1373        assert!(
1374            nothing.is_err(),
1375            "second chunk must not be sent while window is full"
1376        );
1377
1378        // ACK the first chunk (ack = psh1.seq + len).
1379        let peer_ack_num = psh1.sequence_number.wrapping_add(psh1.payload.len() as u32);
1380        adapter
1381            .process_tcp_packet_from_payload(&tcp_seg(
1382                hp,
1383                PEER_ISN + 1,
1384                peer_ack_num,
1385                TcpFlags {
1386                    ack: true,
1387                    ..Default::default()
1388                },
1389                &[],
1390            ))
1391            .await
1392            .unwrap();
1393
1394        // ACK frees window; second chunk goes out on the next flush.
1395        adapter.write_buffer_flush().await.unwrap();
1396        let psh2 = read_pkt(&mut test_rx).await;
1397        assert_eq!(psh2.payload, b"secnd");
1398        assert_eq!(
1399            psh2.sequence_number, peer_ack_num,
1400            "second segment starts where first left off"
1401        );
1402    }
1403
1404    /// With a window larger than `mss`, multiple segments go out back-to-back
1405    /// before any ACK is received.
1406    #[tokio::test]
1407    async fn sliding_window_sends_multiple_segments() {
1408        tokio::time::pause();
1409
1410        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1411        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1412        let mut adapter = Adapter::new(
1413            Box::new(TestTransport(adapter_end)),
1414            IpAddr::V6(HOST_IP),
1415            IpAddr::V6(PEER_IP),
1416        );
1417        adapter.set_mss(10);
1418        adapter.set_send_window(40); // 4 segments worth.
1419
1420        let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await;
1421
1422        adapter.queue_send(&[b'x'; 35], hp).unwrap();
1423        adapter.write_buffer_flush().await.unwrap();
1424
1425        let mut total = 0;
1426        for _ in 0..4 {
1427            let pkt = read_pkt(&mut test_rx).await;
1428            total += pkt.payload.len();
1429        }
1430        assert_eq!(total, 35, "all 35 bytes should be on the wire pre-ACK");
1431    }
1432
1433    /// `send_window` caps how much can be in flight; data past the cap waits.
1434    #[tokio::test]
1435    async fn send_window_caps_in_flight_bytes() {
1436        tokio::time::pause();
1437
1438        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1439        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1440        let mut adapter = Adapter::new(
1441            Box::new(TestTransport(adapter_end)),
1442            IpAddr::V6(HOST_IP),
1443            IpAddr::V6(PEER_IP),
1444        );
1445        adapter.set_mss(10);
1446        adapter.set_send_window(20);
1447
1448        let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await;
1449
1450        adapter.queue_send(&[b'x'; 50], hp).unwrap();
1451        adapter.write_buffer_flush().await.unwrap();
1452
1453        // First 20 bytes go out as two 10-byte segments.
1454        let p1 = read_pkt(&mut test_rx).await;
1455        let p2 = read_pkt(&mut test_rx).await;
1456        assert_eq!(p1.payload.len() + p2.payload.len(), 20);
1457
1458        // The next 30 bytes are blocked behind the window.
1459        let blocked = tokio::time::timeout(Duration::from_millis(10), read_pkt(&mut test_rx)).await;
1460        assert!(blocked.is_err(), "must not exceed send_window before ACK");
1461    }
1462
1463    /// Our outbound SYN advertises the Window Scale option (RFC 7323).
1464    #[tokio::test]
1465    async fn syn_advertises_window_scale() {
1466        tokio::time::pause();
1467
1468        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1469        let (mut test_rx, _test_tx) = tokio::io::split(test_end);
1470        let mut adapter = Adapter::new(
1471            Box::new(TestTransport(adapter_end)),
1472            IpAddr::V6(HOST_IP),
1473            IpAddr::V6(PEER_IP),
1474        );
1475
1476        // Drive connect() far enough that the SYN hits the wire.
1477        let connect_fut = adapter.connect(PEER_PORT);
1478        let (_unused, syn) = tokio::join!(connect_fut, async { read_pkt(&mut test_rx).await });
1479
1480        assert!(syn.flags.syn, "first packet must be SYN");
1481        let shift =
1482            crate::tcp::packets::parse_window_scale(&syn.options).expect("SYN should include WSopt");
1483        assert_eq!(shift, OUR_WSCALE, "advertised wscale should match constant");
1484    }
1485
1486    /// When the peer's SYN-ACK includes a window scale, subsequent window
1487    /// advertisements are interpreted as `field << peer_wscale`.
1488    #[tokio::test]
1489    async fn peer_window_scale_is_honored() {
1490        tokio::time::pause();
1491
1492        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1493        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1494        let mut adapter = Adapter::new(
1495            Box::new(TestTransport(adapter_end)),
1496            IpAddr::V6(HOST_IP),
1497            IpAddr::V6(PEER_IP),
1498        );
1499        adapter.set_mss(10);
1500        adapter.set_send_window(1 << 20); // effectively unlimited from our side.
1501
1502        let peer_wscale = 4u8;
1503        let peer_raw_window = 2u16; // scaled: 2 << 4 = 32 bytes.
1504
1505        // Drive connect() while we manually act as the peer.
1506        let (hp_result, peer_hp) = tokio::join!(adapter.connect(PEER_PORT), async {
1507            let syn = read_pkt(&mut test_rx).await;
1508            assert!(syn.flags.syn);
1509            let hp = syn.source_port;
1510
1511            // SYN-ACK with WSopt and a tiny scaled window.
1512            let wscale_opt = crate::tcp::packets::window_scale_option(peer_wscale);
1513            let tcp = TcpPacket::create(
1514                IpAddr::V6(PEER_IP),
1515                IpAddr::V6(HOST_IP),
1516                PEER_PORT,
1517                hp,
1518                PEER_ISN,
1519                syn.sequence_number.wrapping_add(1),
1520                TcpFlags {
1521                    syn: true,
1522                    ack: true,
1523                    ..Default::default()
1524                },
1525                peer_raw_window,
1526                &wscale_opt,
1527                &[],
1528            );
1529            let ip = crate::tcp::packets::Ipv6Packet::create(
1530                PEER_IP,
1531                HOST_IP,
1532                ProtocolNumber::Tcp,
1533                255,
1534                &tcp,
1535            );
1536            test_tx.write_all(&ip).await.unwrap();
1537
1538            // Consume the adapter's ACK.
1539            let _ack = read_pkt(&mut test_rx).await;
1540            hp
1541        });
1542        let hp = hp_result.expect("connect failed");
1543        assert_eq!(hp, peer_hp);
1544
1545        // Try to send 100 bytes. With peer_window=32 and mss=10, we expect
1546        // 3 full segments (30 bytes) plus one short segment (2 bytes) = 32
1547        // bytes on the wire; the remaining 68 bytes must be held.
1548        adapter.queue_send(&[b'a'; 100], hp).unwrap();
1549        adapter.write_buffer_flush().await.unwrap();
1550
1551        let mut sent = 0;
1552        while sent < 32 {
1553            let p = read_pkt(&mut test_rx).await;
1554            sent += p.payload.len();
1555            assert!(sent <= 32, "must never exceed peer_window={}", 32);
1556        }
1557        assert_eq!(sent, 32);
1558
1559        let blocked = tokio::time::timeout(Duration::from_millis(10), read_pkt(&mut test_rx)).await;
1560        assert!(blocked.is_err(), "must not exceed peer's scaled window");
1561    }
1562
1563    #[tokio::test]
1564    async fn out_of_order_packet_dropped() {
1565        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1566        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1567        let mut adapter = Adapter::new(
1568            Box::new(TestTransport(adapter_end)),
1569            IpAddr::V6(HOST_IP),
1570            IpAddr::V6(PEER_IP),
1571        );
1572
1573        let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await;
1574
1575        // After handshake the adapter expects seq = PEER_ISN + 1 from the peer.
1576        // Send seq = PEER_ISN + 100
1577        adapter
1578            .process_tcp_packet_from_payload(&tcp_seg(
1579                hp,
1580                PEER_ISN + 100,
1581                0,
1582                TcpFlags {
1583                    psh: true,
1584                    ack: true,
1585                    ..Default::default()
1586                },
1587                b"ooo",
1588            ))
1589            .await
1590            .unwrap();
1591
1592        // No data should have been buffered.
1593        let buffered = adapter.uncache_all(hp).unwrap();
1594        assert!(
1595            buffered.is_empty(),
1596            "out-of-order data must not be buffered"
1597        );
1598
1599        // A duplicate ACK for what we do have tells the peer about the gap.
1600        let dup_ack = read_pkt(&mut test_rx).await;
1601        assert!(dup_ack.flags.ack);
1602        assert_eq!(
1603            dup_ack.acknowledgment_number,
1604            PEER_ISN + 1,
1605            "out-of-order packet must be answered with a duplicate ACK"
1606        );
1607    }
1608
1609    #[tokio::test]
1610    async fn abort_sends_a_reset_and_forgets_the_connection() {
1611        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1612        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1613        let mut adapter = Adapter::new(
1614            Box::new(TestTransport(adapter_end)),
1615            IpAddr::V6(HOST_IP),
1616            IpAddr::V6(PEER_IP),
1617        );
1618        let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await;
1619        let data_seq = PEER_ISN + 1;
1620        adapter
1621            .process_tcp_packet_from_payload(&tcp_seg(hp, data_seq, 0, TcpFlags { psh: true, ack: true, ..Default::default() }, b"log"))
1622            .await
1623            .unwrap();
1624        let _ack = read_pkt(&mut test_rx).await;
1625
1626        adapter.abort(hp).await.unwrap();
1627        let rst = read_pkt(&mut test_rx).await;
1628        assert!(rst.flags.rst && !rst.flags.fin, "an abort resets rather than closes");
1629        assert_eq!(rst.source_port, hp);
1630        assert_eq!(rst.acknowledgment_number, data_seq + 3, "the reset acknowledges what was read");
1631        assert!(adapter.abort(hp).await.is_err(), "the connection is gone after the reset");
1632    }
1633
1634    /// Connect through the async handle, answering as the peer.
1635    async fn handle_connect(
1636        handle: &mut crate::tcp::handle::AdapterHandle,
1637        test_rx: &mut (impl AsyncRead + Unpin),
1638        test_tx: &mut (impl AsyncWrite + Unpin),
1639    ) -> (crate::tcp::handle::StreamHandle, u16) {
1640        let (stream, hp) = tokio::join!(handle.connect(PEER_PORT), async {
1641            let syn = read_pkt(test_rx).await;
1642            let syn_ack = TcpFlags { syn: true, ack: true, ..Default::default() };
1643            test_tx
1644                .write_all(&peer_ipv6_pkt(syn.source_port, PEER_ISN, syn.sequence_number.wrapping_add(1), syn_ack, &[]))
1645                .await
1646                .unwrap();
1647            let _ack = read_pkt(test_rx).await;
1648            syn.source_port
1649        });
1650        (stream.expect("connect failed"), hp)
1651    }
1652
1653    async fn nothing_more(test_rx: &mut (impl AsyncRead + Unpin)) -> bool {
1654        tokio::time::timeout(Duration::from_millis(300), read_pkt(test_rx)).await.is_err()
1655    }
1656
1657    #[tokio::test]
1658    async fn a_stream_marked_reset_on_drop_resets_once_and_sends_no_fin() {
1659        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1660        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1661        let mut handle =
1662            Adapter::new(Box::new(TestTransport(adapter_end)), IpAddr::V6(HOST_IP), IpAddr::V6(PEER_IP)).to_async_handle();
1663        let (mut stream, hp) = handle_connect(&mut handle, &mut test_rx, &mut test_tx).await;
1664        let mut reset = stream.reset_on_drop();
1665
1666        drop(stream);
1667        let rst = read_pkt(&mut test_rx).await;
1668        assert!(rst.flags.rst && !rst.flags.fin, "a dropped stream marked reset-on-drop resets");
1669        assert_eq!(rst.source_port, hp);
1670        tokio::time::timeout(Duration::from_secs(1), reset.sent()).await.expect("resolves once the reset is out");
1671        reset.now();
1672        assert!(nothing_more(&mut test_rx).await, "no FIN and no second reset");
1673    }
1674
1675    #[tokio::test]
1676    async fn a_stream_reset_early_sends_nothing_when_dropped() {
1677        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1678        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1679        let mut handle =
1680            Adapter::new(Box::new(TestTransport(adapter_end)), IpAddr::V6(HOST_IP), IpAddr::V6(PEER_IP)).to_async_handle();
1681        let (mut stream, hp) = handle_connect(&mut handle, &mut test_rx, &mut test_tx).await;
1682        let reset = stream.reset_on_drop();
1683
1684        reset.now();
1685        let rst = read_pkt(&mut test_rx).await;
1686        assert!(rst.flags.rst && rst.source_port == hp, "the reset goes out before the stream is dropped");
1687        drop(stream);
1688        assert!(nothing_more(&mut test_rx).await, "the drop sends neither a FIN nor a second reset");
1689    }
1690
1691    #[tokio::test]
1692    async fn a_dropped_stream_still_closes_with_a_fin() {
1693        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1694        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1695        let mut handle =
1696            Adapter::new(Box::new(TestTransport(adapter_end)), IpAddr::V6(HOST_IP), IpAddr::V6(PEER_IP)).to_async_handle();
1697        let (stream, _) = handle_connect(&mut handle, &mut test_rx, &mut test_tx).await;
1698
1699        drop(stream);
1700        let fin = read_pkt(&mut test_rx).await;
1701        assert!(fin.flags.fin && !fin.flags.rst, "an unmarked stream closes");
1702        assert!(nothing_more(&mut test_rx).await, "and is not reset after");
1703    }
1704
1705    /// A duplicate segment (seq < expected, already received) is re-ACKed but
1706    /// its payload is not buffered a second time.
1707    #[tokio::test]
1708    async fn duplicate_packet_reacked_not_buffered() {
1709        let (adapter_end, test_end) = tokio::io::duplex(1 << 16);
1710        let (mut test_rx, mut test_tx) = tokio::io::split(test_end);
1711        let mut adapter = Adapter::new(
1712            Box::new(TestTransport(adapter_end)),
1713            IpAddr::V6(HOST_IP),
1714            IpAddr::V6(PEER_IP),
1715        );
1716
1717        let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await;
1718
1719        // Inject the expected data packet.
1720        let data_seq = PEER_ISN + 1;
1721        adapter
1722            .process_tcp_packet_from_payload(&tcp_seg(
1723                hp,
1724                data_seq,
1725                0,
1726                TcpFlags {
1727                    psh: true,
1728                    ack: true,
1729                    ..Default::default()
1730                },
1731                b"hi",
1732            ))
1733            .await
1734            .unwrap();
1735
1736        // Consume the ACK for the first delivery.
1737        let ack1 = read_pkt(&mut test_rx).await;
1738        assert!(ack1.flags.ack);
1739        assert_eq!(
1740            ack1.acknowledgment_number,
1741            data_seq.wrapping_add(2),
1742            "ACK should cover both bytes"
1743        );
1744
1745        // Drain the read buffer so we can check it is not doubled.
1746        let first_read = adapter.uncache_all(hp).unwrap();
1747        assert_eq!(first_read, b"hi");
1748
1749        // Re-inject the same segment (peer retransmit / duplicate).
1750        adapter
1751            .process_tcp_packet_from_payload(&tcp_seg(
1752                hp,
1753                data_seq,
1754                0,
1755                TcpFlags {
1756                    psh: true,
1757                    ack: true,
1758                    ..Default::default()
1759                },
1760                b"hi",
1761            ))
1762            .await
1763            .unwrap();
1764
1765        // Should get a re-ACK with the same acknowledgment number.
1766        let ack2 = read_pkt(&mut test_rx).await;
1767        assert!(ack2.flags.ack);
1768        assert_eq!(
1769            ack2.acknowledgment_number, ack1.acknowledgment_number,
1770            "re-ACK must use same ack number as original"
1771        );
1772
1773        // Data must NOT have been buffered again.
1774        let second_read = adapter.uncache_all(hp).unwrap();
1775        assert!(
1776            second_read.is_empty(),
1777            "duplicate payload must not be re-buffered"
1778        );
1779    }
1780}