1 // Heads up! Before working on this file you should read, at least, RFC 793 and
2 // the parts of RFC 1122 that discuss TCP. Consult RFC 7414 when implementing
3 // a new feature.
4 
5 use core::fmt::Display;
6 #[cfg(feature = "async")]
7 use core::task::Waker;
8 use core::{cmp, fmt, mem};
9 
10 #[cfg(feature = "async")]
11 use crate::socket::WakerRegistration;
12 use crate::socket::{Context, PollAt};
13 use crate::storage::{Assembler, RingBuffer};
14 use crate::time::{Duration, Instant};
15 use crate::wire::{
16     IpAddress, IpEndpoint, IpListenEndpoint, IpProtocol, IpRepr, TcpControl, TcpRepr, TcpSeqNumber,
17     TCP_HEADER_LEN,
18 };
19 
20 macro_rules! tcp_trace {
21     ($($arg:expr),*) => (net_log!(trace, $($arg),*));
22 }
23 
24 /// Error returned by [`Socket::listen`]
25 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
26 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
27 pub enum ListenError {
28     InvalidState,
29     Unaddressable,
30 }
31 
32 /// Error returned by [`Socket::connect`]
33 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
34 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
35 pub enum ConnectError {
36     InvalidState,
37     Unaddressable,
38 }
39 
40 /// Error returned by [`Socket::send`]
41 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
42 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
43 pub enum SendError {
44     InvalidState,
45 }
46 
47 /// Error returned by [`Socket::recv`]
48 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
49 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
50 pub enum RecvError {
51     InvalidState,
52     Finished,
53 }
54 
55 /// A TCP socket ring buffer.
56 pub type SocketBuffer<'a> = RingBuffer<'a, u8>;
57 
58 /// The state of a TCP socket, according to [RFC 793].
59 ///
60 /// [RFC 793]: https://tools.ietf.org/html/rfc793
61 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
62 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
63 pub enum State {
64     Closed,
65     Listen,
66     SynSent,
67     SynReceived,
68     Established,
69     FinWait1,
70     FinWait2,
71     CloseWait,
72     Closing,
73     LastAck,
74     TimeWait,
75 }
76 
77 impl fmt::Display for State {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result78     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79         match *self {
80             State::Closed => write!(f, "CLOSED"),
81             State::Listen => write!(f, "LISTEN"),
82             State::SynSent => write!(f, "SYN-SENT"),
83             State::SynReceived => write!(f, "SYN-RECEIVED"),
84             State::Established => write!(f, "ESTABLISHED"),
85             State::FinWait1 => write!(f, "FIN-WAIT-1"),
86             State::FinWait2 => write!(f, "FIN-WAIT-2"),
87             State::CloseWait => write!(f, "CLOSE-WAIT"),
88             State::Closing => write!(f, "CLOSING"),
89             State::LastAck => write!(f, "LAST-ACK"),
90             State::TimeWait => write!(f, "TIME-WAIT"),
91         }
92     }
93 }
94 
95 // Conservative initial RTT estimate.
96 const RTTE_INITIAL_RTT: u32 = 300;
97 const RTTE_INITIAL_DEV: u32 = 100;
98 
99 // Minimum "safety margin" for the RTO that kicks in when the
100 // variance gets very low.
101 const RTTE_MIN_MARGIN: u32 = 5;
102 
103 const RTTE_MIN_RTO: u32 = 10;
104 const RTTE_MAX_RTO: u32 = 10000;
105 
106 #[derive(Debug, Clone, Copy)]
107 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
108 struct RttEstimator {
109     // Using u32 instead of Duration to save space (Duration is i64)
110     rtt: u32,
111     deviation: u32,
112     timestamp: Option<(Instant, TcpSeqNumber)>,
113     max_seq_sent: Option<TcpSeqNumber>,
114     rto_count: u8,
115 }
116 
117 impl Default for RttEstimator {
default() -> Self118     fn default() -> Self {
119         Self {
120             rtt: RTTE_INITIAL_RTT,
121             deviation: RTTE_INITIAL_DEV,
122             timestamp: None,
123             max_seq_sent: None,
124             rto_count: 0,
125         }
126     }
127 }
128 
129 impl RttEstimator {
retransmission_timeout(&self) -> Duration130     fn retransmission_timeout(&self) -> Duration {
131         let margin = RTTE_MIN_MARGIN.max(self.deviation * 4);
132         let ms = (self.rtt + margin).clamp(RTTE_MIN_RTO, RTTE_MAX_RTO);
133         Duration::from_millis(ms as u64)
134     }
135 
sample(&mut self, new_rtt: u32)136     fn sample(&mut self, new_rtt: u32) {
137         // "Congestion Avoidance and Control", Van Jacobson, Michael J. Karels, 1988
138         self.rtt = (self.rtt * 7 + new_rtt + 7) / 8;
139         let diff = (self.rtt as i32 - new_rtt as i32).unsigned_abs();
140         self.deviation = (self.deviation * 3 + diff + 3) / 4;
141 
142         self.rto_count = 0;
143 
144         let rto = self.retransmission_timeout().total_millis();
145         tcp_trace!(
146             "rtte: sample={:?} rtt={:?} dev={:?} rto={:?}",
147             new_rtt,
148             self.rtt,
149             self.deviation,
150             rto
151         );
152     }
153 
on_send(&mut self, timestamp: Instant, seq: TcpSeqNumber)154     fn on_send(&mut self, timestamp: Instant, seq: TcpSeqNumber) {
155         if self
156             .max_seq_sent
157             .map(|max_seq_sent| seq > max_seq_sent)
158             .unwrap_or(true)
159         {
160             self.max_seq_sent = Some(seq);
161             if self.timestamp.is_none() {
162                 self.timestamp = Some((timestamp, seq));
163                 tcp_trace!("rtte: sampling at seq={:?}", seq);
164             }
165         }
166     }
167 
on_ack(&mut self, timestamp: Instant, seq: TcpSeqNumber)168     fn on_ack(&mut self, timestamp: Instant, seq: TcpSeqNumber) {
169         if let Some((sent_timestamp, sent_seq)) = self.timestamp {
170             if seq >= sent_seq {
171                 self.sample((timestamp - sent_timestamp).total_millis() as u32);
172                 self.timestamp = None;
173             }
174         }
175     }
176 
on_retransmit(&mut self)177     fn on_retransmit(&mut self) {
178         if self.timestamp.is_some() {
179             tcp_trace!("rtte: abort sampling due to retransmit");
180         }
181         self.timestamp = None;
182         self.rto_count = self.rto_count.saturating_add(1);
183         if self.rto_count >= 3 {
184             // This happens in 2 scenarios:
185             // - The RTT is higher than the initial estimate
186             // - The network conditions change, suddenly making the RTT much higher
187             // In these cases, the estimator can get stuck, because it can't sample because
188             // all packets sent would incur a retransmit. To avoid this, force an estimate
189             // increase if we see 3 consecutive retransmissions without any successful sample.
190             self.rto_count = 0;
191             self.rtt = RTTE_MAX_RTO.min(self.rtt * 2);
192             let rto = self.retransmission_timeout().total_millis();
193             tcp_trace!(
194                 "rtte: too many retransmissions, increasing: rtt={:?} dev={:?} rto={:?}",
195                 self.rtt,
196                 self.deviation,
197                 rto
198             );
199         }
200     }
201 }
202 
203 #[derive(Debug, Clone, Copy, PartialEq)]
204 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
205 enum Timer {
206     Idle {
207         keep_alive_at: Option<Instant>,
208     },
209     Retransmit {
210         expires_at: Instant,
211         delay: Duration,
212     },
213     FastRetransmit,
214     Close {
215         expires_at: Instant,
216     },
217 }
218 
219 const ACK_DELAY_DEFAULT: Duration = Duration::from_millis(10);
220 const CLOSE_DELAY: Duration = Duration::from_millis(10_000);
221 
222 impl Timer {
new() -> Timer223     fn new() -> Timer {
224         Timer::Idle {
225             keep_alive_at: None,
226         }
227     }
228 
should_keep_alive(&self, timestamp: Instant) -> bool229     fn should_keep_alive(&self, timestamp: Instant) -> bool {
230         match *self {
231             Timer::Idle {
232                 keep_alive_at: Some(keep_alive_at),
233             } if timestamp >= keep_alive_at => true,
234             _ => false,
235         }
236     }
237 
should_retransmit(&self, timestamp: Instant) -> Option<Duration>238     fn should_retransmit(&self, timestamp: Instant) -> Option<Duration> {
239         match *self {
240             Timer::Retransmit { expires_at, delay } if timestamp >= expires_at => {
241                 Some(timestamp - expires_at + delay)
242             }
243             Timer::FastRetransmit => Some(Duration::from_millis(0)),
244             _ => None,
245         }
246     }
247 
should_close(&self, timestamp: Instant) -> bool248     fn should_close(&self, timestamp: Instant) -> bool {
249         match *self {
250             Timer::Close { expires_at } if timestamp >= expires_at => true,
251             _ => false,
252         }
253     }
254 
poll_at(&self) -> PollAt255     fn poll_at(&self) -> PollAt {
256         match *self {
257             Timer::Idle {
258                 keep_alive_at: Some(keep_alive_at),
259             } => PollAt::Time(keep_alive_at),
260             Timer::Idle {
261                 keep_alive_at: None,
262             } => PollAt::Ingress,
263             Timer::Retransmit { expires_at, .. } => PollAt::Time(expires_at),
264             Timer::FastRetransmit => PollAt::Now,
265             Timer::Close { expires_at } => PollAt::Time(expires_at),
266         }
267     }
268 
set_for_idle(&mut self, timestamp: Instant, interval: Option<Duration>)269     fn set_for_idle(&mut self, timestamp: Instant, interval: Option<Duration>) {
270         *self = Timer::Idle {
271             keep_alive_at: interval.map(|interval| timestamp + interval),
272         }
273     }
274 
set_keep_alive(&mut self)275     fn set_keep_alive(&mut self) {
276         if let Timer::Idle { keep_alive_at } = self {
277             if keep_alive_at.is_none() {
278                 *keep_alive_at = Some(Instant::from_millis(0))
279             }
280         }
281     }
282 
rewind_keep_alive(&mut self, timestamp: Instant, interval: Option<Duration>)283     fn rewind_keep_alive(&mut self, timestamp: Instant, interval: Option<Duration>) {
284         if let Timer::Idle { keep_alive_at } = self {
285             *keep_alive_at = interval.map(|interval| timestamp + interval)
286         }
287     }
288 
set_for_retransmit(&mut self, timestamp: Instant, delay: Duration)289     fn set_for_retransmit(&mut self, timestamp: Instant, delay: Duration) {
290         match *self {
291             Timer::Idle { .. } | Timer::FastRetransmit { .. } => {
292                 *self = Timer::Retransmit {
293                     expires_at: timestamp + delay,
294                     delay,
295                 }
296             }
297             Timer::Retransmit { expires_at, delay } if timestamp >= expires_at => {
298                 *self = Timer::Retransmit {
299                     expires_at: timestamp + delay,
300                     delay: delay * 2,
301                 }
302             }
303             Timer::Retransmit { .. } => (),
304             Timer::Close { .. } => (),
305         }
306     }
307 
set_for_fast_retransmit(&mut self)308     fn set_for_fast_retransmit(&mut self) {
309         *self = Timer::FastRetransmit
310     }
311 
set_for_close(&mut self, timestamp: Instant)312     fn set_for_close(&mut self, timestamp: Instant) {
313         *self = Timer::Close {
314             expires_at: timestamp + CLOSE_DELAY,
315         }
316     }
317 
is_retransmit(&self) -> bool318     fn is_retransmit(&self) -> bool {
319         match *self {
320             Timer::Retransmit { .. } | Timer::FastRetransmit => true,
321             _ => false,
322         }
323     }
324 }
325 
326 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
327 enum AckDelayTimer {
328     Idle,
329     Waiting(Instant),
330     Immediate,
331 }
332 
333 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
334 #[cfg_attr(feature = "defmt", derive(defmt::Format))]
335 struct Tuple {
336     local: IpEndpoint,
337     remote: IpEndpoint,
338 }
339 
340 impl Display for Tuple {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result341     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342         write!(f, "{}:{}", self.local, self.remote)
343     }
344 }
345 
346 /// A Transmission Control Protocol socket.
347 ///
348 /// A TCP socket may passively listen for connections or actively connect to another endpoint.
349 /// Note that, for listening sockets, there is no "backlog"; to be able to simultaneously
350 /// accept several connections, as many sockets must be allocated, or any new connection
351 /// attempts will be reset.
352 #[derive(Debug)]
353 pub struct Socket<'a> {
354     state: State,
355     timer: Timer,
356     rtte: RttEstimator,
357     assembler: Assembler,
358     rx_buffer: SocketBuffer<'a>,
359     rx_fin_received: bool,
360     tx_buffer: SocketBuffer<'a>,
361     /// Interval after which, if no inbound packets are received, the connection is aborted.
362     timeout: Option<Duration>,
363     /// Interval at which keep-alive packets will be sent.
364     keep_alive: Option<Duration>,
365     /// The time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
366     hop_limit: Option<u8>,
367     /// Address passed to listen(). Listen address is set when listen() is called and
368     /// used every time the socket is reset back to the LISTEN state.
369     listen_endpoint: IpListenEndpoint,
370     /// Current 4-tuple (local and remote endpoints).
371     tuple: Option<Tuple>,
372     /// The sequence number corresponding to the beginning of the transmit buffer.
373     /// I.e. an ACK(local_seq_no+n) packet removes n bytes from the transmit buffer.
374     local_seq_no: TcpSeqNumber,
375     /// The sequence number corresponding to the beginning of the receive buffer.
376     /// I.e. userspace reading n bytes adds n to remote_seq_no.
377     remote_seq_no: TcpSeqNumber,
378     /// The last sequence number sent.
379     /// I.e. in an idle socket, local_seq_no+tx_buffer.len().
380     remote_last_seq: TcpSeqNumber,
381     /// The last acknowledgement number sent.
382     /// I.e. in an idle socket, remote_seq_no+rx_buffer.len().
383     remote_last_ack: Option<TcpSeqNumber>,
384     /// The last window length sent.
385     remote_last_win: u16,
386     /// The sending window scaling factor advertised to remotes which support RFC 1323.
387     /// It is zero if the window <= 64KiB and/or the remote does not support it.
388     remote_win_shift: u8,
389     /// The remote window size, relative to local_seq_no
390     /// I.e. we're allowed to send octets until local_seq_no+remote_win_len
391     remote_win_len: usize,
392     /// The receive window scaling factor for remotes which support RFC 1323, None if unsupported.
393     remote_win_scale: Option<u8>,
394     /// Whether or not the remote supports selective ACK as described in RFC 2018.
395     remote_has_sack: bool,
396     /// The maximum number of data octets that the remote side may receive.
397     remote_mss: usize,
398     /// The timestamp of the last packet received.
399     remote_last_ts: Option<Instant>,
400     /// The sequence number of the last packet received, used for sACK
401     local_rx_last_seq: Option<TcpSeqNumber>,
402     /// The ACK number of the last packet received.
403     local_rx_last_ack: Option<TcpSeqNumber>,
404     /// The number of packets received directly after
405     /// each other which have the same ACK number.
406     local_rx_dup_acks: u8,
407 
408     /// Duration for Delayed ACK. If None no ACKs will be delayed.
409     ack_delay: Option<Duration>,
410     /// Delayed ack timer. If set, packets containing exclusively
411     /// ACK or window updates (ie, no data) won't be sent until expiry.
412     ack_delay_timer: AckDelayTimer,
413 
414     /// Used for rate-limiting: No more challenge ACKs will be sent until this instant.
415     challenge_ack_timer: Instant,
416 
417     /// Nagle's Algorithm enabled.
418     nagle: bool,
419 
420     #[cfg(feature = "async")]
421     rx_waker: WakerRegistration,
422     #[cfg(feature = "async")]
423     tx_waker: WakerRegistration,
424 }
425 
426 const DEFAULT_MSS: usize = 536;
427 
428 impl<'a> Socket<'a> {
429     #[allow(unused_comparisons)] // small usize platforms always pass rx_capacity check
430     /// Create a socket using the given buffers.
new<T>(rx_buffer: T, tx_buffer: T) -> Socket<'a> where T: Into<SocketBuffer<'a>>,431     pub fn new<T>(rx_buffer: T, tx_buffer: T) -> Socket<'a>
432     where
433         T: Into<SocketBuffer<'a>>,
434     {
435         let (rx_buffer, tx_buffer) = (rx_buffer.into(), tx_buffer.into());
436         let rx_capacity = rx_buffer.capacity();
437 
438         // From RFC 1323:
439         // [...] the above constraints imply that 2 * the max window size must be less
440         // than 2**31 [...] Thus, the shift count must be limited to 14 (which allows
441         // windows of 2**30 = 1 Gbyte).
442         if rx_capacity > (1 << 30) {
443             panic!("receiving buffer too large, cannot exceed 1 GiB")
444         }
445         let rx_cap_log2 = mem::size_of::<usize>() * 8 - rx_capacity.leading_zeros() as usize;
446 
447         Socket {
448             state: State::Closed,
449             timer: Timer::new(),
450             rtte: RttEstimator::default(),
451             assembler: Assembler::new(),
452             tx_buffer,
453             rx_buffer,
454             rx_fin_received: false,
455             timeout: None,
456             keep_alive: None,
457             hop_limit: None,
458             listen_endpoint: IpListenEndpoint::default(),
459             tuple: None,
460             local_seq_no: TcpSeqNumber::default(),
461             remote_seq_no: TcpSeqNumber::default(),
462             remote_last_seq: TcpSeqNumber::default(),
463             remote_last_ack: None,
464             remote_last_win: 0,
465             remote_win_len: 0,
466             remote_win_shift: rx_cap_log2.saturating_sub(16) as u8,
467             remote_win_scale: None,
468             remote_has_sack: false,
469             remote_mss: DEFAULT_MSS,
470             remote_last_ts: None,
471             local_rx_last_ack: None,
472             local_rx_last_seq: None,
473             local_rx_dup_acks: 0,
474             ack_delay: Some(ACK_DELAY_DEFAULT),
475             ack_delay_timer: AckDelayTimer::Idle,
476             challenge_ack_timer: Instant::from_secs(0),
477             nagle: true,
478 
479             #[cfg(feature = "async")]
480             rx_waker: WakerRegistration::new(),
481             #[cfg(feature = "async")]
482             tx_waker: WakerRegistration::new(),
483         }
484     }
485 
486     /// Register a waker for receive operations.
487     ///
488     /// The waker is woken on state changes that might affect the return value
489     /// of `recv` method calls, such as receiving data, or the socket closing.
490     ///
491     /// Notes:
492     ///
493     /// - Only one waker can be registered at a time. If another waker was previously registered,
494     ///   it is overwritten and will no longer be woken.
495     /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
496     /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `recv` has
497     ///   necessarily changed.
498     #[cfg(feature = "async")]
register_recv_waker(&mut self, waker: &Waker)499     pub fn register_recv_waker(&mut self, waker: &Waker) {
500         self.rx_waker.register(waker)
501     }
502 
503     /// Register a waker for send operations.
504     ///
505     /// The waker is woken on state changes that might affect the return value
506     /// of `send` method calls, such as space becoming available in the transmit
507     /// buffer, or the socket closing.
508     ///
509     /// Notes:
510     ///
511     /// - Only one waker can be registered at a time. If another waker was previously registered,
512     ///   it is overwritten and will no longer be woken.
513     /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
514     /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `send` has
515     ///   necessarily changed.
516     #[cfg(feature = "async")]
register_send_waker(&mut self, waker: &Waker)517     pub fn register_send_waker(&mut self, waker: &Waker) {
518         self.tx_waker.register(waker)
519     }
520 
521     /// Return the timeout duration.
522     ///
523     /// See also the [set_timeout](#method.set_timeout) method.
timeout(&self) -> Option<Duration>524     pub fn timeout(&self) -> Option<Duration> {
525         self.timeout
526     }
527 
528     /// Return the ACK delay duration.
529     ///
530     /// See also the [set_ack_delay](#method.set_ack_delay) method.
ack_delay(&self) -> Option<Duration>531     pub fn ack_delay(&self) -> Option<Duration> {
532         self.ack_delay
533     }
534 
535     /// Return whether Nagle's Algorithm is enabled.
536     ///
537     /// See also the [set_nagle_enabled](#method.set_nagle_enabled) method.
nagle_enabled(&self) -> bool538     pub fn nagle_enabled(&self) -> bool {
539         self.nagle
540     }
541 
542     /// Return the current window field value, including scaling according to RFC 1323.
543     ///
544     /// Used in internal calculations as well as packet generation.
545     ///
546     #[inline]
scaled_window(&self) -> u16547     fn scaled_window(&self) -> u16 {
548         cmp::min(
549             self.rx_buffer.window() >> self.remote_win_shift as usize,
550             (1 << 16) - 1,
551         ) as u16
552     }
553 
554     /// Set the timeout duration.
555     ///
556     /// A socket with a timeout duration set will abort the connection if either of the following
557     /// occurs:
558     ///
559     ///   * After a [connect](#method.connect) call, the remote endpoint does not respond within
560     ///     the specified duration;
561     ///   * After establishing a connection, there is data in the transmit buffer and the remote
562     ///     endpoint exceeds the specified duration between any two packets it sends;
563     ///   * After enabling [keep-alive](#method.set_keep_alive), the remote endpoint exceeds
564     ///     the specified duration between any two packets it sends.
set_timeout(&mut self, duration: Option<Duration>)565     pub fn set_timeout(&mut self, duration: Option<Duration>) {
566         self.timeout = duration
567     }
568 
569     /// Set the ACK delay duration.
570     ///
571     /// By default, the ACK delay is set to 10ms.
set_ack_delay(&mut self, duration: Option<Duration>)572     pub fn set_ack_delay(&mut self, duration: Option<Duration>) {
573         self.ack_delay = duration
574     }
575 
576     /// Enable or disable Nagle's Algorithm.
577     ///
578     /// Also known as "tinygram prevention". By default, it is enabled.
579     /// Disabling it is equivalent to Linux's TCP_NODELAY flag.
580     ///
581     /// When enabled, Nagle's Algorithm prevents sending segments smaller than MSS if
582     /// there is data in flight (sent but not acknowledged). In other words, it ensures
583     /// at most only one segment smaller than MSS is in flight at a time.
584     ///
585     /// It ensures better network utilization by preventing sending many very small packets,
586     /// at the cost of increased latency in some situations, particularly when the remote peer
587     /// has ACK delay enabled.
set_nagle_enabled(&mut self, enabled: bool)588     pub fn set_nagle_enabled(&mut self, enabled: bool) {
589         self.nagle = enabled
590     }
591 
592     /// Return the keep-alive interval.
593     ///
594     /// See also the [set_keep_alive](#method.set_keep_alive) method.
keep_alive(&self) -> Option<Duration>595     pub fn keep_alive(&self) -> Option<Duration> {
596         self.keep_alive
597     }
598 
599     /// Set the keep-alive interval.
600     ///
601     /// An idle socket with a keep-alive interval set will transmit a "keep-alive ACK" packet
602     /// every time it receives no communication during that interval. As a result, three things
603     /// may happen:
604     ///
605     ///   * The remote endpoint is fine and answers with an ACK packet.
606     ///   * The remote endpoint has rebooted and answers with an RST packet.
607     ///   * The remote endpoint has crashed and does not answer.
608     ///
609     /// The keep-alive functionality together with the timeout functionality allows to react
610     /// to these error conditions.
set_keep_alive(&mut self, interval: Option<Duration>)611     pub fn set_keep_alive(&mut self, interval: Option<Duration>) {
612         self.keep_alive = interval;
613         if self.keep_alive.is_some() {
614             // If the connection is idle and we've just set the option, it would not take effect
615             // until the next packet, unless we wind up the timer explicitly.
616             self.timer.set_keep_alive();
617         }
618     }
619 
620     /// Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
621     ///
622     /// See also the [set_hop_limit](#method.set_hop_limit) method
hop_limit(&self) -> Option<u8>623     pub fn hop_limit(&self) -> Option<u8> {
624         self.hop_limit
625     }
626 
627     /// Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
628     ///
629     /// A socket without an explicitly set hop limit value uses the default [IANA recommended]
630     /// value (64).
631     ///
632     /// # Panics
633     ///
634     /// This function panics if a hop limit value of 0 is given. See [RFC 1122 § 3.2.1.7].
635     ///
636     /// [IANA recommended]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml
637     /// [RFC 1122 § 3.2.1.7]: https://tools.ietf.org/html/rfc1122#section-3.2.1.7
set_hop_limit(&mut self, hop_limit: Option<u8>)638     pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
639         // A host MUST NOT send a datagram with a hop limit value of 0
640         if let Some(0) = hop_limit {
641             panic!("the time-to-live value of a packet must not be zero")
642         }
643 
644         self.hop_limit = hop_limit
645     }
646 
647     /// Return the local endpoint, or None if not connected.
648     #[inline]
local_endpoint(&self) -> Option<IpEndpoint>649     pub fn local_endpoint(&self) -> Option<IpEndpoint> {
650         Some(self.tuple?.local)
651     }
652 
653     /// Return the remote endpoint, or None if not connected.
654     #[inline]
remote_endpoint(&self) -> Option<IpEndpoint>655     pub fn remote_endpoint(&self) -> Option<IpEndpoint> {
656         Some(self.tuple?.remote)
657     }
658 
659     /// Return the connection state, in terms of the TCP state machine.
660     #[inline]
state(&self) -> State661     pub fn state(&self) -> State {
662         self.state
663     }
664 
reset(&mut self)665     fn reset(&mut self) {
666         let rx_cap_log2 =
667             mem::size_of::<usize>() * 8 - self.rx_buffer.capacity().leading_zeros() as usize;
668 
669         self.state = State::Closed;
670         self.timer = Timer::new();
671         self.rtte = RttEstimator::default();
672         self.assembler = Assembler::new();
673         self.tx_buffer.clear();
674         self.rx_buffer.clear();
675         self.rx_fin_received = false;
676         self.listen_endpoint = IpListenEndpoint::default();
677         self.tuple = None;
678         self.local_seq_no = TcpSeqNumber::default();
679         self.remote_seq_no = TcpSeqNumber::default();
680         self.remote_last_seq = TcpSeqNumber::default();
681         self.remote_last_ack = None;
682         self.remote_last_win = 0;
683         self.remote_win_len = 0;
684         self.remote_win_scale = None;
685         self.remote_win_shift = rx_cap_log2.saturating_sub(16) as u8;
686         self.remote_mss = DEFAULT_MSS;
687         self.remote_last_ts = None;
688         self.ack_delay_timer = AckDelayTimer::Idle;
689         self.challenge_ack_timer = Instant::from_secs(0);
690 
691         #[cfg(feature = "async")]
692         {
693             self.rx_waker.wake();
694             self.tx_waker.wake();
695         }
696     }
697 
698     /// Start listening on the given endpoint.
699     ///
700     /// This function returns `Err(Error::Illegal)` if the socket was already open
701     /// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
702     /// if the port in the given endpoint is zero.
listen<T>(&mut self, local_endpoint: T) -> Result<(), ListenError> where T: Into<IpListenEndpoint>,703     pub fn listen<T>(&mut self, local_endpoint: T) -> Result<(), ListenError>
704     where
705         T: Into<IpListenEndpoint>,
706     {
707         let local_endpoint = local_endpoint.into();
708         if local_endpoint.port == 0 {
709             return Err(ListenError::Unaddressable);
710         }
711 
712         if self.is_open() {
713             return Err(ListenError::InvalidState);
714         }
715 
716         self.reset();
717         self.listen_endpoint = local_endpoint;
718         self.tuple = None;
719         self.set_state(State::Listen);
720         Ok(())
721     }
722 
723     /// Connect to a given endpoint.
724     ///
725     /// The local port must be provided explicitly. Assuming `fn get_ephemeral_port() -> u16`
726     /// allocates a port between 49152 and 65535, a connection may be established as follows:
727     ///
728     /// ```no_run
729     /// # #[cfg(all(
730     /// #     feature = "medium-ethernet",
731     /// #     feature = "proto-ipv4",
732     /// # ))]
733     /// # {
734     /// # use smoltcp::socket::tcp::{Socket, SocketBuffer};
735     /// # use smoltcp::iface::Interface;
736     /// # use smoltcp::wire::IpAddress;
737     /// #
738     /// # fn get_ephemeral_port() -> u16 {
739     /// #     49152
740     /// # }
741     /// #
742     /// # let mut socket = Socket::new(
743     /// #     SocketBuffer::new(vec![0; 1200]),
744     /// #     SocketBuffer::new(vec![0; 1200])
745     /// # );
746     /// #
747     /// # let mut iface: Interface = todo!();
748     /// #
749     /// socket.connect(
750     ///     iface.context(),
751     ///     (IpAddress::v4(10, 0, 0, 1), 80),
752     ///     get_ephemeral_port()
753     /// ).unwrap();
754     /// # }
755     /// ```
756     ///
757     /// The local address may optionally be provided.
758     ///
759     /// This function returns an error if the socket was open; see [is_open](#method.is_open).
760     /// It also returns an error if the local or remote port is zero, or if the remote address
761     /// is unspecified.
connect<T, U>( &mut self, cx: &mut Context, remote_endpoint: T, local_endpoint: U, ) -> Result<(), ConnectError> where T: Into<IpEndpoint>, U: Into<IpListenEndpoint>,762     pub fn connect<T, U>(
763         &mut self,
764         cx: &mut Context,
765         remote_endpoint: T,
766         local_endpoint: U,
767     ) -> Result<(), ConnectError>
768     where
769         T: Into<IpEndpoint>,
770         U: Into<IpListenEndpoint>,
771     {
772         let remote_endpoint: IpEndpoint = remote_endpoint.into();
773         let local_endpoint: IpListenEndpoint = local_endpoint.into();
774 
775         if self.is_open() {
776             return Err(ConnectError::InvalidState);
777         }
778         if remote_endpoint.port == 0 || remote_endpoint.addr.is_unspecified() {
779             return Err(ConnectError::Unaddressable);
780         }
781         if local_endpoint.port == 0 {
782             return Err(ConnectError::Unaddressable);
783         }
784 
785         // If local address is not provided, choose it automatically.
786         let local_endpoint = IpEndpoint {
787             addr: match local_endpoint.addr {
788                 Some(addr) => {
789                     if addr.is_unspecified() {
790                         return Err(ConnectError::Unaddressable);
791                     }
792                     addr
793                 }
794                 None => cx
795                     .get_source_address(remote_endpoint.addr)
796                     .ok_or(ConnectError::Unaddressable)?,
797             },
798             port: local_endpoint.port,
799         };
800 
801         if local_endpoint.addr.version() != remote_endpoint.addr.version() {
802             return Err(ConnectError::Unaddressable);
803         }
804 
805         self.reset();
806         self.tuple = Some(Tuple {
807             local: local_endpoint,
808             remote: remote_endpoint,
809         });
810         self.set_state(State::SynSent);
811 
812         let seq = Self::random_seq_no(cx);
813         self.local_seq_no = seq;
814         self.remote_last_seq = seq;
815         Ok(())
816     }
817 
818     #[cfg(test)]
random_seq_no(_cx: &mut Context) -> TcpSeqNumber819     fn random_seq_no(_cx: &mut Context) -> TcpSeqNumber {
820         TcpSeqNumber(10000)
821     }
822 
823     #[cfg(not(test))]
random_seq_no(cx: &mut Context) -> TcpSeqNumber824     fn random_seq_no(cx: &mut Context) -> TcpSeqNumber {
825         TcpSeqNumber(cx.rand().rand_u32() as i32)
826     }
827 
828     /// Close the transmit half of the full-duplex connection.
829     ///
830     /// Note that there is no corresponding function for the receive half of the full-duplex
831     /// connection; only the remote end can close it. If you no longer wish to receive any
832     /// data and would like to reuse the socket right away, use [abort](#method.abort).
close(&mut self)833     pub fn close(&mut self) {
834         match self.state {
835             // In the LISTEN state there is no established connection.
836             State::Listen => self.set_state(State::Closed),
837             // In the SYN-SENT state the remote endpoint is not yet synchronized and, upon
838             // receiving an RST, will abort the connection.
839             State::SynSent => self.set_state(State::Closed),
840             // In the SYN-RECEIVED, ESTABLISHED and CLOSE-WAIT states the transmit half
841             // of the connection is open, and needs to be explicitly closed with a FIN.
842             State::SynReceived | State::Established => self.set_state(State::FinWait1),
843             State::CloseWait => self.set_state(State::LastAck),
844             // In the FIN-WAIT-1, FIN-WAIT-2, CLOSING, LAST-ACK, TIME-WAIT and CLOSED states,
845             // the transmit half of the connection is already closed, and no further
846             // action is needed.
847             State::FinWait1
848             | State::FinWait2
849             | State::Closing
850             | State::TimeWait
851             | State::LastAck
852             | State::Closed => (),
853         }
854     }
855 
856     /// Aborts the connection, if any.
857     ///
858     /// This function instantly closes the socket. One reset packet will be sent to the remote
859     /// endpoint.
860     ///
861     /// In terms of the TCP state machine, the socket may be in any state and is moved to
862     /// the `CLOSED` state.
abort(&mut self)863     pub fn abort(&mut self) {
864         self.set_state(State::Closed);
865     }
866 
867     /// Return whether the socket is passively listening for incoming connections.
868     ///
869     /// In terms of the TCP state machine, the socket must be in the `LISTEN` state.
870     #[inline]
is_listening(&self) -> bool871     pub fn is_listening(&self) -> bool {
872         match self.state {
873             State::Listen => true,
874             _ => false,
875         }
876     }
877 
878     /// Return whether the socket is open.
879     ///
880     /// This function returns true if the socket will process incoming or dispatch outgoing
881     /// packets. Note that this does not mean that it is possible to send or receive data through
882     /// the socket; for that, use [can_send](#method.can_send) or [can_recv](#method.can_recv).
883     ///
884     /// In terms of the TCP state machine, the socket must not be in the `CLOSED`
885     /// or `TIME-WAIT` states.
886     #[inline]
is_open(&self) -> bool887     pub fn is_open(&self) -> bool {
888         match self.state {
889             State::Closed => false,
890             State::TimeWait => false,
891             _ => true,
892         }
893     }
894 
895     /// Return whether a connection is active.
896     ///
897     /// This function returns true if the socket is actively exchanging packets with
898     /// a remote endpoint. Note that this does not mean that it is possible to send or receive
899     /// data through the socket; for that, use [can_send](#method.can_send) or
900     /// [can_recv](#method.can_recv).
901     ///
902     /// If a connection is established, [abort](#method.close) will send a reset to
903     /// the remote endpoint.
904     ///
905     /// In terms of the TCP state machine, the socket must not be in the `CLOSED`, `TIME-WAIT`,
906     /// or `LISTEN` state.
907     #[inline]
is_active(&self) -> bool908     pub fn is_active(&self) -> bool {
909         match self.state {
910             State::Closed => false,
911             State::TimeWait => false,
912             State::Listen => false,
913             _ => true,
914         }
915     }
916 
917     /// Return whether the transmit half of the full-duplex connection is open.
918     ///
919     /// This function returns true if it's possible to send data and have it arrive
920     /// to the remote endpoint. However, it does not make any guarantees about the state
921     /// of the transmit buffer, and even if it returns true, [send](#method.send) may
922     /// not be able to enqueue any octets.
923     ///
924     /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED` or
925     /// `CLOSE-WAIT` state.
926     #[inline]
may_send(&self) -> bool927     pub fn may_send(&self) -> bool {
928         match self.state {
929             State::Established => true,
930             // In CLOSE-WAIT, the remote endpoint has closed our receive half of the connection
931             // but we still can transmit indefinitely.
932             State::CloseWait => true,
933             _ => false,
934         }
935     }
936 
937     /// Return whether the receive half of the full-duplex connection is open.
938     ///
939     /// This function returns true if it's possible to receive data from the remote endpoint.
940     /// It will return true while there is data in the receive buffer, and if there isn't,
941     /// as long as the remote endpoint has not closed the connection.
942     ///
943     /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED`,
944     /// `FIN-WAIT-1`, or `FIN-WAIT-2` state, or have data in the receive buffer instead.
945     #[inline]
may_recv(&self) -> bool946     pub fn may_recv(&self) -> bool {
947         match self.state {
948             State::Established => true,
949             // In FIN-WAIT-1/2, we have closed our transmit half of the connection but
950             // we still can receive indefinitely.
951             State::FinWait1 | State::FinWait2 => true,
952             // If we have something in the receive buffer, we can receive that.
953             _ if !self.rx_buffer.is_empty() => true,
954             _ => false,
955         }
956     }
957 
958     /// Check whether the transmit half of the full-duplex connection is open
959     /// (see [may_send](#method.may_send)), and the transmit buffer is not full.
960     #[inline]
can_send(&self) -> bool961     pub fn can_send(&self) -> bool {
962         if !self.may_send() {
963             return false;
964         }
965 
966         !self.tx_buffer.is_full()
967     }
968 
969     /// Return the maximum number of bytes inside the recv buffer.
970     #[inline]
recv_capacity(&self) -> usize971     pub fn recv_capacity(&self) -> usize {
972         self.rx_buffer.capacity()
973     }
974 
975     /// Return the maximum number of bytes inside the transmit buffer.
976     #[inline]
send_capacity(&self) -> usize977     pub fn send_capacity(&self) -> usize {
978         self.tx_buffer.capacity()
979     }
980 
981     /// Check whether the receive half of the full-duplex connection buffer is open
982     /// (see [may_recv](#method.may_recv)), and the receive buffer is not empty.
983     #[inline]
can_recv(&self) -> bool984     pub fn can_recv(&self) -> bool {
985         if !self.may_recv() {
986             return false;
987         }
988 
989         !self.rx_buffer.is_empty()
990     }
991 
send_impl<'b, F, R>(&'b mut self, f: F) -> Result<R, SendError> where F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R),992     fn send_impl<'b, F, R>(&'b mut self, f: F) -> Result<R, SendError>
993     where
994         F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R),
995     {
996         if !self.may_send() {
997             return Err(SendError::InvalidState);
998         }
999 
1000         // The connection might have been idle for a long time, and so remote_last_ts
1001         // would be far in the past. Unless we clear it here, we'll abort the connection
1002         // down over in dispatch() by erroneously detecting it as timed out.
1003         if self.tx_buffer.is_empty() {
1004             self.remote_last_ts = None
1005         }
1006 
1007         let _old_length = self.tx_buffer.len();
1008         let (size, result) = f(&mut self.tx_buffer);
1009         if size > 0 {
1010             #[cfg(any(test, feature = "verbose"))]
1011             tcp_trace!(
1012                 "tx buffer: enqueueing {} octets (now {})",
1013                 size,
1014                 _old_length + size
1015             );
1016         }
1017         Ok(result)
1018     }
1019 
1020     /// Call `f` with the largest contiguous slice of octets in the transmit buffer,
1021     /// and enqueue the amount of elements returned by `f`.
1022     ///
1023     /// This function returns `Err(Error::Illegal)` if the transmit half of
1024     /// the connection is not open; see [may_send](#method.may_send).
send<'b, F, R>(&'b mut self, f: F) -> Result<R, SendError> where F: FnOnce(&'b mut [u8]) -> (usize, R),1025     pub fn send<'b, F, R>(&'b mut self, f: F) -> Result<R, SendError>
1026     where
1027         F: FnOnce(&'b mut [u8]) -> (usize, R),
1028     {
1029         self.send_impl(|tx_buffer| tx_buffer.enqueue_many_with(f))
1030     }
1031 
1032     /// Enqueue a sequence of octets to be sent, and fill it from a slice.
1033     ///
1034     /// This function returns the amount of octets actually enqueued, which is limited
1035     /// by the amount of free space in the transmit buffer; down to zero.
1036     ///
1037     /// See also [send](#method.send).
send_slice(&mut self, data: &[u8]) -> Result<usize, SendError>1038     pub fn send_slice(&mut self, data: &[u8]) -> Result<usize, SendError> {
1039         self.send_impl(|tx_buffer| {
1040             let size = tx_buffer.enqueue_slice(data);
1041             (size, size)
1042         })
1043     }
1044 
recv_error_check(&mut self) -> Result<(), RecvError>1045     fn recv_error_check(&mut self) -> Result<(), RecvError> {
1046         // We may have received some data inside the initial SYN, but until the connection
1047         // is fully open we must not dequeue any data, as it may be overwritten by e.g.
1048         // another (stale) SYN. (We do not support TCP Fast Open.)
1049         if !self.may_recv() {
1050             if self.rx_fin_received {
1051                 return Err(RecvError::Finished);
1052             }
1053             return Err(RecvError::InvalidState);
1054         }
1055 
1056         Ok(())
1057     }
1058 
recv_impl<'b, F, R>(&'b mut self, f: F) -> Result<R, RecvError> where F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R),1059     fn recv_impl<'b, F, R>(&'b mut self, f: F) -> Result<R, RecvError>
1060     where
1061         F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R),
1062     {
1063         self.recv_error_check()?;
1064 
1065         let _old_length = self.rx_buffer.len();
1066         let (size, result) = f(&mut self.rx_buffer);
1067         self.remote_seq_no += size;
1068         if size > 0 {
1069             #[cfg(any(test, feature = "verbose"))]
1070             tcp_trace!(
1071                 "rx buffer: dequeueing {} octets (now {})",
1072                 size,
1073                 _old_length - size
1074             );
1075         }
1076         Ok(result)
1077     }
1078 
1079     /// Call `f` with the largest contiguous slice of octets in the receive buffer,
1080     /// and dequeue the amount of elements returned by `f`.
1081     ///
1082     /// This function errors if the receive half of the connection is not open.
1083     ///
1084     /// If the receive half has been gracefully closed (with a FIN packet), `Err(Error::Finished)`
1085     /// is returned. In this case, the previously received data is guaranteed to be complete.
1086     ///
1087     /// In all other cases, `Err(Error::Illegal)` is returned and previously received data (if any)
1088     /// may be incomplete (truncated).
recv<'b, F, R>(&'b mut self, f: F) -> Result<R, RecvError> where F: FnOnce(&'b mut [u8]) -> (usize, R),1089     pub fn recv<'b, F, R>(&'b mut self, f: F) -> Result<R, RecvError>
1090     where
1091         F: FnOnce(&'b mut [u8]) -> (usize, R),
1092     {
1093         self.recv_impl(|rx_buffer| rx_buffer.dequeue_many_with(f))
1094     }
1095 
1096     /// Dequeue a sequence of received octets, and fill a slice from it.
1097     ///
1098     /// This function returns the amount of octets actually dequeued, which is limited
1099     /// by the amount of occupied space in the receive buffer; down to zero.
1100     ///
1101     /// See also [recv](#method.recv).
recv_slice(&mut self, data: &mut [u8]) -> Result<usize, RecvError>1102     pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize, RecvError> {
1103         self.recv_impl(|rx_buffer| {
1104             let size = rx_buffer.dequeue_slice(data);
1105             (size, size)
1106         })
1107     }
1108 
1109     /// Peek at a sequence of received octets without removing them from
1110     /// the receive buffer, and return a pointer to it.
1111     ///
1112     /// This function otherwise behaves identically to [recv](#method.recv).
peek(&mut self, size: usize) -> Result<&[u8], RecvError>1113     pub fn peek(&mut self, size: usize) -> Result<&[u8], RecvError> {
1114         self.recv_error_check()?;
1115 
1116         let buffer = self.rx_buffer.get_allocated(0, size);
1117         if !buffer.is_empty() {
1118             #[cfg(any(test, feature = "verbose"))]
1119             tcp_trace!("rx buffer: peeking at {} octets", buffer.len());
1120         }
1121         Ok(buffer)
1122     }
1123 
1124     /// Peek at a sequence of received octets without removing them from
1125     /// the receive buffer, and fill a slice from it.
1126     ///
1127     /// This function otherwise behaves identically to [recv_slice](#method.recv_slice).
peek_slice(&mut self, data: &mut [u8]) -> Result<usize, RecvError>1128     pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<usize, RecvError> {
1129         let buffer = self.peek(data.len())?;
1130         let data = &mut data[..buffer.len()];
1131         data.copy_from_slice(buffer);
1132         Ok(buffer.len())
1133     }
1134 
1135     /// Return the amount of octets queued in the transmit buffer.
1136     ///
1137     /// Note that the Berkeley sockets interface does not have an equivalent of this API.
send_queue(&self) -> usize1138     pub fn send_queue(&self) -> usize {
1139         self.tx_buffer.len()
1140     }
1141 
1142     /// Return the amount of octets queued in the receive buffer. This value can be larger than
1143     /// the slice read by the next `recv` or `peek` call because it includes all queued octets,
1144     /// and not only the octets that may be returned as a contiguous slice.
1145     ///
1146     /// Note that the Berkeley sockets interface does not have an equivalent of this API.
recv_queue(&self) -> usize1147     pub fn recv_queue(&self) -> usize {
1148         self.rx_buffer.len()
1149     }
1150 
set_state(&mut self, state: State)1151     fn set_state(&mut self, state: State) {
1152         if self.state != state {
1153             tcp_trace!("state={}=>{}", self.state, state);
1154         }
1155 
1156         self.state = state;
1157 
1158         #[cfg(feature = "async")]
1159         {
1160             // Wake all tasks waiting. Even if we haven't received/sent data, this
1161             // is needed because return values of functions may change depending on the state.
1162             // For example, a pending read has to fail with an error if the socket is closed.
1163             self.rx_waker.wake();
1164             self.tx_waker.wake();
1165         }
1166     }
1167 
reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>)1168     pub(crate) fn reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
1169         let reply_repr = TcpRepr {
1170             src_port: repr.dst_port,
1171             dst_port: repr.src_port,
1172             control: TcpControl::None,
1173             seq_number: TcpSeqNumber(0),
1174             ack_number: None,
1175             window_len: 0,
1176             window_scale: None,
1177             max_seg_size: None,
1178             sack_permitted: false,
1179             sack_ranges: [None, None, None],
1180             payload: &[],
1181         };
1182         let ip_reply_repr = IpRepr::new(
1183             ip_repr.dst_addr(),
1184             ip_repr.src_addr(),
1185             IpProtocol::Tcp,
1186             reply_repr.buffer_len(),
1187             64,
1188         );
1189         (ip_reply_repr, reply_repr)
1190     }
1191 
rst_reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>)1192     pub(crate) fn rst_reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
1193         debug_assert!(repr.control != TcpControl::Rst);
1194 
1195         let (ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
1196 
1197         // See https://www.snellman.net/blog/archive/2016-02-01-tcp-rst/ for explanation
1198         // of why we sometimes send an RST and sometimes an RST|ACK
1199         reply_repr.control = TcpControl::Rst;
1200         reply_repr.seq_number = repr.ack_number.unwrap_or_default();
1201         if repr.control == TcpControl::Syn && repr.ack_number.is_none() {
1202             reply_repr.ack_number = Some(repr.seq_number + repr.segment_len());
1203         }
1204 
1205         (ip_reply_repr, reply_repr)
1206     }
1207 
ack_reply(&mut self, ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>)1208     fn ack_reply(&mut self, ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
1209         let (mut ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
1210 
1211         // From RFC 793:
1212         // [...] an empty acknowledgment segment containing the current send-sequence number
1213         // and an acknowledgment indicating the next sequence number expected
1214         // to be received.
1215         reply_repr.seq_number = self.remote_last_seq;
1216         reply_repr.ack_number = Some(self.remote_seq_no + self.rx_buffer.len());
1217         self.remote_last_ack = reply_repr.ack_number;
1218 
1219         // From RFC 1323:
1220         // The window field [...] of every outgoing segment, with the exception of SYN
1221         // segments, is right-shifted by [advertised scale value] bits[...]
1222         reply_repr.window_len = self.scaled_window();
1223         self.remote_last_win = reply_repr.window_len;
1224 
1225         // If the remote supports selective acknowledgement, add the option to the outgoing
1226         // segment.
1227         if self.remote_has_sack {
1228             net_debug!("sending sACK option with current assembler ranges");
1229 
1230             // RFC 2018: The first SACK block (i.e., the one immediately following the kind and
1231             // length fields in the option) MUST specify the contiguous block of data containing
1232             // the segment which triggered this ACK, unless that segment advanced the
1233             // Acknowledgment Number field in the header.
1234             reply_repr.sack_ranges[0] = None;
1235 
1236             if let Some(last_seg_seq) = self.local_rx_last_seq.map(|s| s.0 as u32) {
1237                 reply_repr.sack_ranges[0] = self
1238                     .assembler
1239                     .iter_data(reply_repr.ack_number.map(|s| s.0 as usize).unwrap_or(0))
1240                     .map(|(left, right)| (left as u32, right as u32))
1241                     .find(|(left, right)| *left <= last_seg_seq && *right >= last_seg_seq);
1242             }
1243 
1244             if reply_repr.sack_ranges[0].is_none() {
1245                 // The matching segment was removed from the assembler, meaning the acknowledgement
1246                 // number has advanced, or there was no previous sACK.
1247                 //
1248                 // While the RFC says we SHOULD keep a list of reported sACK ranges, and iterate
1249                 // through those, that is currently infeasible. Instead, we offer the range with
1250                 // the lowest sequence number (if one exists) to hint at what segments would
1251                 // most quickly advance the acknowledgement number.
1252                 reply_repr.sack_ranges[0] = self
1253                     .assembler
1254                     .iter_data(reply_repr.ack_number.map(|s| s.0 as usize).unwrap_or(0))
1255                     .map(|(left, right)| (left as u32, right as u32))
1256                     .next();
1257             }
1258         }
1259 
1260         // Since the sACK option may have changed the length of the payload, update that.
1261         ip_reply_repr.set_payload_len(reply_repr.buffer_len());
1262         (ip_reply_repr, reply_repr)
1263     }
1264 
challenge_ack_reply( &mut self, cx: &mut Context, ip_repr: &IpRepr, repr: &TcpRepr, ) -> Option<(IpRepr, TcpRepr<'static>)>1265     fn challenge_ack_reply(
1266         &mut self,
1267         cx: &mut Context,
1268         ip_repr: &IpRepr,
1269         repr: &TcpRepr,
1270     ) -> Option<(IpRepr, TcpRepr<'static>)> {
1271         if cx.now() < self.challenge_ack_timer {
1272             return None;
1273         }
1274 
1275         // Rate-limit to 1 per second max.
1276         self.challenge_ack_timer = cx.now() + Duration::from_secs(1);
1277 
1278         return Some(self.ack_reply(ip_repr, repr));
1279     }
1280 
accepts(&self, _cx: &mut Context, ip_repr: &IpRepr, repr: &TcpRepr) -> bool1281     pub(crate) fn accepts(&self, _cx: &mut Context, ip_repr: &IpRepr, repr: &TcpRepr) -> bool {
1282         if self.state == State::Closed {
1283             return false;
1284         }
1285 
1286         // If we're still listening for SYNs and the packet has an ACK, it cannot
1287         // be destined to this socket, but another one may well listen on the same
1288         // local endpoint.
1289         if self.state == State::Listen && repr.ack_number.is_some() {
1290             return false;
1291         }
1292 
1293         if let Some(tuple) = &self.tuple {
1294             // Reject packets not matching the 4-tuple
1295             ip_repr.dst_addr() == tuple.local.addr
1296                 && repr.dst_port == tuple.local.port
1297                 && ip_repr.src_addr() == tuple.remote.addr
1298                 && repr.src_port == tuple.remote.port
1299         } else {
1300             // We're listening, reject packets not matching the listen endpoint.
1301             let addr_ok = match self.listen_endpoint.addr {
1302                 Some(addr) => ip_repr.dst_addr() == addr,
1303                 None => true,
1304             };
1305             addr_ok && repr.dst_port != 0 && repr.dst_port == self.listen_endpoint.port
1306         }
1307     }
1308 
process( &mut self, cx: &mut Context, ip_repr: &IpRepr, repr: &TcpRepr, ) -> Option<(IpRepr, TcpRepr<'static>)>1309     pub(crate) fn process(
1310         &mut self,
1311         cx: &mut Context,
1312         ip_repr: &IpRepr,
1313         repr: &TcpRepr,
1314     ) -> Option<(IpRepr, TcpRepr<'static>)> {
1315         debug_assert!(self.accepts(cx, ip_repr, repr));
1316 
1317         // Consider how much the sequence number space differs from the transmit buffer space.
1318         let (sent_syn, sent_fin) = match self.state {
1319             // In SYN-SENT or SYN-RECEIVED, we've just sent a SYN.
1320             State::SynSent | State::SynReceived => (true, false),
1321             // In FIN-WAIT-1, LAST-ACK, or CLOSING, we've just sent a FIN.
1322             State::FinWait1 | State::LastAck | State::Closing => (false, true),
1323             // In all other states we've already got acknowledgements for
1324             // all of the control flags we sent.
1325             _ => (false, false),
1326         };
1327         let control_len = (sent_syn as usize) + (sent_fin as usize);
1328 
1329         // Reject unacceptable acknowledgements.
1330         match (self.state, repr.control, repr.ack_number) {
1331             // An RST received in response to initial SYN is acceptable if it acknowledges
1332             // the initial SYN.
1333             (State::SynSent, TcpControl::Rst, None) => {
1334                 net_debug!("unacceptable RST (expecting RST|ACK) in response to initial SYN");
1335                 return None;
1336             }
1337             (State::SynSent, TcpControl::Rst, Some(ack_number)) => {
1338                 if ack_number != self.local_seq_no + 1 {
1339                     net_debug!("unacceptable RST|ACK in response to initial SYN");
1340                     return None;
1341                 }
1342             }
1343             // Any other RST need only have a valid sequence number.
1344             (_, TcpControl::Rst, _) => (),
1345             // The initial SYN cannot contain an acknowledgement.
1346             (State::Listen, _, None) => (),
1347             // This case is handled in `accepts()`.
1348             (State::Listen, _, Some(_)) => unreachable!(),
1349             // Every packet after the initial SYN must be an acknowledgement.
1350             (_, _, None) => {
1351                 net_debug!("expecting an ACK");
1352                 return None;
1353             }
1354             // SYN|ACK in the SYN-SENT state must have the exact ACK number.
1355             (State::SynSent, TcpControl::Syn, Some(ack_number)) => {
1356                 if ack_number != self.local_seq_no + 1 {
1357                     net_debug!("unacceptable SYN|ACK in response to initial SYN");
1358                     return Some(Self::rst_reply(ip_repr, repr));
1359                 }
1360             }
1361             // ACKs in the SYN-SENT state are invalid.
1362             (State::SynSent, TcpControl::None, Some(ack_number)) => {
1363                 // If the sequence number matches, ignore it instead of RSTing.
1364                 // I'm not sure why, I think it may be a workaround for broken TCP
1365                 // servers, or a defense against reordering. Either way, if Linux
1366                 // does it, we do too.
1367                 if ack_number == self.local_seq_no + 1 {
1368                     net_debug!(
1369                         "expecting a SYN|ACK, received an ACK with the right ack_number, ignoring."
1370                     );
1371                     return None;
1372                 }
1373 
1374                 net_debug!(
1375                     "expecting a SYN|ACK, received an ACK with the wrong ack_number, sending RST."
1376                 );
1377                 return Some(Self::rst_reply(ip_repr, repr));
1378             }
1379             // Anything else in the SYN-SENT state is invalid.
1380             (State::SynSent, _, _) => {
1381                 net_debug!("expecting a SYN|ACK");
1382                 return None;
1383             }
1384             // ACK in the SYN-RECEIVED state must have the exact ACK number, or we RST it.
1385             (State::SynReceived, _, Some(ack_number)) => {
1386                 if ack_number != self.local_seq_no + 1 {
1387                     net_debug!("unacceptable ACK in response to SYN|ACK");
1388                     return Some(Self::rst_reply(ip_repr, repr));
1389                 }
1390             }
1391             // Every acknowledgement must be for transmitted but unacknowledged data.
1392             (_, _, Some(ack_number)) => {
1393                 let unacknowledged = self.tx_buffer.len() + control_len;
1394 
1395                 // Acceptable ACK range (both inclusive)
1396                 let mut ack_min = self.local_seq_no;
1397                 let ack_max = self.local_seq_no + unacknowledged;
1398 
1399                 // If we have sent a SYN, it MUST be acknowledged.
1400                 if sent_syn {
1401                     ack_min += 1;
1402                 }
1403 
1404                 if ack_number < ack_min {
1405                     net_debug!(
1406                         "duplicate ACK ({} not in {}...{})",
1407                         ack_number,
1408                         ack_min,
1409                         ack_max
1410                     );
1411                     return None;
1412                 }
1413 
1414                 if ack_number > ack_max {
1415                     net_debug!(
1416                         "unacceptable ACK ({} not in {}...{})",
1417                         ack_number,
1418                         ack_min,
1419                         ack_max
1420                     );
1421                     return self.challenge_ack_reply(cx, ip_repr, repr);
1422                 }
1423             }
1424         }
1425 
1426         let window_start = self.remote_seq_no + self.rx_buffer.len();
1427         let window_end = self.remote_seq_no + self.rx_buffer.capacity();
1428         let segment_start = repr.seq_number;
1429         let segment_end = repr.seq_number + repr.segment_len();
1430 
1431         let payload_offset;
1432         match self.state {
1433             // In LISTEN and SYN-SENT states, we have not yet synchronized with the remote end.
1434             State::Listen | State::SynSent => payload_offset = 0,
1435             // In all other states, segments must occupy a valid portion of the receive window.
1436             _ => {
1437                 let mut segment_in_window = true;
1438 
1439                 if window_start == window_end && segment_start != segment_end {
1440                     net_debug!(
1441                         "non-zero-length segment with zero receive window, will only send an ACK"
1442                     );
1443                     segment_in_window = false;
1444                 }
1445 
1446                 if segment_start == segment_end && segment_end == window_start - 1 {
1447                     net_debug!("received a keep-alive or window probe packet, will send an ACK");
1448                     segment_in_window = false;
1449                 } else if !((window_start <= segment_start && segment_start <= window_end)
1450                     && (window_start <= segment_end && segment_end <= window_end))
1451                 {
1452                     net_debug!(
1453                         "segment not in receive window ({}..{} not intersecting {}..{}), will send challenge ACK",
1454                         segment_start,
1455                         segment_end,
1456                         window_start,
1457                         window_end
1458                     );
1459                     segment_in_window = false;
1460                 }
1461 
1462                 if segment_in_window {
1463                     // We've checked that segment_start >= window_start above.
1464                     payload_offset = segment_start - window_start;
1465                     self.local_rx_last_seq = Some(repr.seq_number);
1466                 } else {
1467                     // If we're in the TIME-WAIT state, restart the TIME-WAIT timeout, since
1468                     // the remote end may not have realized we've closed the connection.
1469                     if self.state == State::TimeWait {
1470                         self.timer.set_for_close(cx.now());
1471                     }
1472 
1473                     return self.challenge_ack_reply(cx, ip_repr, repr);
1474                 }
1475             }
1476         }
1477 
1478         // Compute the amount of acknowledged octets, removing the SYN and FIN bits
1479         // from the sequence space.
1480         let mut ack_len = 0;
1481         let mut ack_of_fin = false;
1482         let mut ack_all = false;
1483         if repr.control != TcpControl::Rst {
1484             if let Some(ack_number) = repr.ack_number {
1485                 // Sequence number corresponding to the first byte in `tx_buffer`.
1486                 // This normally equals `local_seq_no`, but is 1 higher if we have sent a SYN,
1487                 // as the SYN occupies 1 sequence number "before" the data.
1488                 let tx_buffer_start_seq = self.local_seq_no + (sent_syn as usize);
1489 
1490                 if ack_number >= tx_buffer_start_seq {
1491                     ack_len = ack_number - tx_buffer_start_seq;
1492 
1493                     // We could've sent data before the FIN, so only remove FIN from the sequence
1494                     // space if all of that data is acknowledged.
1495                     if sent_fin && self.tx_buffer.len() + 1 == ack_len {
1496                         ack_len -= 1;
1497                         tcp_trace!("received ACK of FIN");
1498                         ack_of_fin = true;
1499                     }
1500 
1501                     ack_all = self.remote_last_seq == ack_number
1502                 }
1503 
1504                 self.rtte.on_ack(cx.now(), ack_number);
1505             }
1506         }
1507 
1508         // Disregard control flags we don't care about or shouldn't act on yet.
1509         let mut control = repr.control;
1510         control = control.quash_psh();
1511 
1512         // If a FIN is received at the end of the current segment but the start of the segment
1513         // is not at the start of the receive window, disregard this FIN.
1514         if control == TcpControl::Fin && window_start != segment_start {
1515             control = TcpControl::None;
1516         }
1517 
1518         // Validate and update the state.
1519         match (self.state, control) {
1520             // RSTs are not accepted in the LISTEN state.
1521             (State::Listen, TcpControl::Rst) => return None,
1522 
1523             // RSTs in SYN-RECEIVED flip the socket back to the LISTEN state.
1524             (State::SynReceived, TcpControl::Rst) => {
1525                 tcp_trace!("received RST");
1526                 self.tuple = None;
1527                 self.set_state(State::Listen);
1528                 return None;
1529             }
1530 
1531             // RSTs in any other state close the socket.
1532             (_, TcpControl::Rst) => {
1533                 tcp_trace!("received RST");
1534                 self.set_state(State::Closed);
1535                 self.tuple = None;
1536                 return None;
1537             }
1538 
1539             // SYN packets in the LISTEN state change it to SYN-RECEIVED.
1540             (State::Listen, TcpControl::Syn) => {
1541                 tcp_trace!("received SYN");
1542                 if let Some(max_seg_size) = repr.max_seg_size {
1543                     if max_seg_size == 0 {
1544                         tcp_trace!("received SYNACK with zero MSS, ignoring");
1545                         return None;
1546                     }
1547                     self.remote_mss = max_seg_size as usize
1548                 }
1549 
1550                 self.tuple = Some(Tuple {
1551                     local: IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port),
1552                     remote: IpEndpoint::new(ip_repr.src_addr(), repr.src_port),
1553                 });
1554                 self.local_seq_no = Self::random_seq_no(cx);
1555                 self.remote_seq_no = repr.seq_number + 1;
1556                 self.remote_last_seq = self.local_seq_no;
1557                 self.remote_has_sack = repr.sack_permitted;
1558                 self.remote_win_scale = repr.window_scale;
1559                 // Remote doesn't support window scaling, don't do it.
1560                 if self.remote_win_scale.is_none() {
1561                     self.remote_win_shift = 0;
1562                 }
1563                 self.set_state(State::SynReceived);
1564                 self.timer.set_for_idle(cx.now(), self.keep_alive);
1565             }
1566 
1567             // ACK packets in the SYN-RECEIVED state change it to ESTABLISHED.
1568             (State::SynReceived, TcpControl::None) => {
1569                 self.set_state(State::Established);
1570                 self.timer.set_for_idle(cx.now(), self.keep_alive);
1571             }
1572 
1573             // FIN packets in the SYN-RECEIVED state change it to CLOSE-WAIT.
1574             // It's not obvious from RFC 793 that this is permitted, but
1575             // 7th and 8th steps in the "SEGMENT ARRIVES" event describe this behavior.
1576             (State::SynReceived, TcpControl::Fin) => {
1577                 self.remote_seq_no += 1;
1578                 self.rx_fin_received = true;
1579                 self.set_state(State::CloseWait);
1580                 self.timer.set_for_idle(cx.now(), self.keep_alive);
1581             }
1582 
1583             // SYN|ACK packets in the SYN-SENT state change it to ESTABLISHED.
1584             (State::SynSent, TcpControl::Syn) => {
1585                 tcp_trace!("received SYN|ACK");
1586                 if let Some(max_seg_size) = repr.max_seg_size {
1587                     if max_seg_size == 0 {
1588                         tcp_trace!("received SYNACK with zero MSS, ignoring");
1589                         return None;
1590                     }
1591                     self.remote_mss = max_seg_size as usize;
1592                 }
1593 
1594                 self.remote_seq_no = repr.seq_number + 1;
1595                 self.remote_last_seq = self.local_seq_no + 1;
1596                 self.remote_last_ack = Some(repr.seq_number);
1597                 self.remote_win_scale = repr.window_scale;
1598                 // Remote doesn't support window scaling, don't do it.
1599                 if self.remote_win_scale.is_none() {
1600                     self.remote_win_shift = 0;
1601                 }
1602 
1603                 self.set_state(State::Established);
1604                 self.timer.set_for_idle(cx.now(), self.keep_alive);
1605             }
1606 
1607             // ACK packets in ESTABLISHED state reset the retransmit timer,
1608             // except for duplicate ACK packets which preserve it.
1609             (State::Established, TcpControl::None) => {
1610                 if !self.timer.is_retransmit() || ack_all {
1611                     self.timer.set_for_idle(cx.now(), self.keep_alive);
1612                 }
1613             }
1614 
1615             // FIN packets in ESTABLISHED state indicate the remote side has closed.
1616             (State::Established, TcpControl::Fin) => {
1617                 self.remote_seq_no += 1;
1618                 self.rx_fin_received = true;
1619                 self.set_state(State::CloseWait);
1620                 self.timer.set_for_idle(cx.now(), self.keep_alive);
1621             }
1622 
1623             // ACK packets in FIN-WAIT-1 state change it to FIN-WAIT-2, if we've already
1624             // sent everything in the transmit buffer. If not, they reset the retransmit timer.
1625             (State::FinWait1, TcpControl::None) => {
1626                 if ack_of_fin {
1627                     self.set_state(State::FinWait2);
1628                 }
1629                 if ack_all {
1630                     self.timer.set_for_idle(cx.now(), self.keep_alive);
1631                 }
1632             }
1633 
1634             // FIN packets in FIN-WAIT-1 state change it to CLOSING, or to TIME-WAIT
1635             // if they also acknowledge our FIN.
1636             (State::FinWait1, TcpControl::Fin) => {
1637                 self.remote_seq_no += 1;
1638                 self.rx_fin_received = true;
1639                 if ack_of_fin {
1640                     self.set_state(State::TimeWait);
1641                     self.timer.set_for_close(cx.now());
1642                 } else {
1643                     self.set_state(State::Closing);
1644                     self.timer.set_for_idle(cx.now(), self.keep_alive);
1645                 }
1646             }
1647 
1648             // Data packets in FIN-WAIT-2 reset the idle timer.
1649             (State::FinWait2, TcpControl::None) => {
1650                 self.timer.set_for_idle(cx.now(), self.keep_alive);
1651             }
1652 
1653             // FIN packets in FIN-WAIT-2 state change it to TIME-WAIT.
1654             (State::FinWait2, TcpControl::Fin) => {
1655                 self.remote_seq_no += 1;
1656                 self.rx_fin_received = true;
1657                 self.set_state(State::TimeWait);
1658                 self.timer.set_for_close(cx.now());
1659             }
1660 
1661             // ACK packets in CLOSING state change it to TIME-WAIT.
1662             (State::Closing, TcpControl::None) => {
1663                 if ack_of_fin {
1664                     self.set_state(State::TimeWait);
1665                     self.timer.set_for_close(cx.now());
1666                 } else {
1667                     self.timer.set_for_idle(cx.now(), self.keep_alive);
1668                 }
1669             }
1670 
1671             // ACK packets in CLOSE-WAIT state reset the retransmit timer.
1672             (State::CloseWait, TcpControl::None) => {
1673                 self.timer.set_for_idle(cx.now(), self.keep_alive);
1674             }
1675 
1676             // ACK packets in LAST-ACK state change it to CLOSED.
1677             (State::LastAck, TcpControl::None) => {
1678                 if ack_of_fin {
1679                     // Clear the remote endpoint, or we'll send an RST there.
1680                     self.set_state(State::Closed);
1681                     self.tuple = None;
1682                 } else {
1683                     self.timer.set_for_idle(cx.now(), self.keep_alive);
1684                 }
1685             }
1686 
1687             _ => {
1688                 net_debug!("unexpected packet {}", repr);
1689                 return None;
1690             }
1691         }
1692 
1693         // Update remote state.
1694         self.remote_last_ts = Some(cx.now());
1695 
1696         // RFC 1323: The window field (SEG.WND) in the header of every incoming segment, with the
1697         // exception of SYN segments, is left-shifted by Snd.Wind.Scale bits before updating SND.WND.
1698         let scale = match repr.control {
1699             TcpControl::Syn => 0,
1700             _ => self.remote_win_scale.unwrap_or(0),
1701         };
1702         self.remote_win_len = (repr.window_len as usize) << (scale as usize);
1703 
1704         if ack_len > 0 {
1705             // Dequeue acknowledged octets.
1706             debug_assert!(self.tx_buffer.len() >= ack_len);
1707             tcp_trace!(
1708                 "tx buffer: dequeueing {} octets (now {})",
1709                 ack_len,
1710                 self.tx_buffer.len() - ack_len
1711             );
1712             self.tx_buffer.dequeue_allocated(ack_len);
1713 
1714             // There's new room available in tx_buffer, wake the waiting task if any.
1715             #[cfg(feature = "async")]
1716             self.tx_waker.wake();
1717         }
1718 
1719         if let Some(ack_number) = repr.ack_number {
1720             // TODO: When flow control is implemented,
1721             // refractor the following block within that implementation
1722 
1723             // Detect and react to duplicate ACKs by:
1724             // 1. Check if duplicate ACK and change self.local_rx_dup_acks accordingly
1725             // 2. If exactly 3 duplicate ACKs received, set for fast retransmit
1726             // 3. Update the last received ACK (self.local_rx_last_ack)
1727             match self.local_rx_last_ack {
1728                 // Duplicate ACK if payload empty and ACK doesn't move send window ->
1729                 // Increment duplicate ACK count and set for retransmit if we just received
1730                 // the third duplicate ACK
1731                 Some(last_rx_ack)
1732                     if repr.payload.is_empty()
1733                         && last_rx_ack == ack_number
1734                         && ack_number < self.remote_last_seq =>
1735                 {
1736                     // Increment duplicate ACK count
1737                     self.local_rx_dup_acks = self.local_rx_dup_acks.saturating_add(1);
1738 
1739                     net_debug!(
1740                         "received duplicate ACK for seq {} (duplicate nr {}{})",
1741                         ack_number,
1742                         self.local_rx_dup_acks,
1743                         if self.local_rx_dup_acks == u8::max_value() {
1744                             "+"
1745                         } else {
1746                             ""
1747                         }
1748                     );
1749 
1750                     if self.local_rx_dup_acks == 3 {
1751                         self.timer.set_for_fast_retransmit();
1752                         net_debug!("started fast retransmit");
1753                     }
1754                 }
1755                 // No duplicate ACK -> Reset state and update last received ACK
1756                 _ => {
1757                     if self.local_rx_dup_acks > 0 {
1758                         self.local_rx_dup_acks = 0;
1759                         net_debug!("reset duplicate ACK count");
1760                     }
1761                     self.local_rx_last_ack = Some(ack_number);
1762                 }
1763             };
1764             // We've processed everything in the incoming segment, so advance the local
1765             // sequence number past it.
1766             self.local_seq_no = ack_number;
1767             // During retransmission, if an earlier segment got lost but later was
1768             // successfully received, self.local_seq_no can move past self.remote_last_seq.
1769             // Do not attempt to retransmit the latter segments; not only this is pointless
1770             // in theory but also impossible in practice, since they have been already
1771             // deallocated from the buffer.
1772             if self.remote_last_seq < self.local_seq_no {
1773                 self.remote_last_seq = self.local_seq_no
1774             }
1775         }
1776 
1777         let payload_len = repr.payload.len();
1778         if payload_len == 0 {
1779             return None;
1780         }
1781 
1782         let assembler_was_empty = self.assembler.is_empty();
1783 
1784         // Try adding payload octets to the assembler.
1785         let Ok(contig_len) = self.assembler.add_then_remove_front(payload_offset, payload_len) else {
1786             net_debug!(
1787                 "assembler: too many holes to add {} octets at offset {}",
1788                 payload_len,
1789                 payload_offset
1790             );
1791             return None;
1792         };
1793 
1794         // Place payload octets into the buffer.
1795         tcp_trace!(
1796             "rx buffer: receiving {} octets at offset {}",
1797             payload_len,
1798             payload_offset
1799         );
1800         let len_written = self
1801             .rx_buffer
1802             .write_unallocated(payload_offset, repr.payload);
1803         debug_assert!(len_written == payload_len);
1804 
1805         if contig_len != 0 {
1806             // Enqueue the contiguous data octets in front of the buffer.
1807             tcp_trace!(
1808                 "rx buffer: enqueueing {} octets (now {})",
1809                 contig_len,
1810                 self.rx_buffer.len() + contig_len
1811             );
1812             self.rx_buffer.enqueue_unallocated(contig_len);
1813 
1814             // There's new data in rx_buffer, notify waiting task if any.
1815             #[cfg(feature = "async")]
1816             self.rx_waker.wake();
1817         }
1818 
1819         if !self.assembler.is_empty() {
1820             // Print the ranges recorded in the assembler.
1821             tcp_trace!("assembler: {}", self.assembler);
1822         }
1823 
1824         // Handle delayed acks
1825         if let Some(ack_delay) = self.ack_delay {
1826             if self.ack_to_transmit() || self.window_to_update() {
1827                 self.ack_delay_timer = match self.ack_delay_timer {
1828                     AckDelayTimer::Idle => {
1829                         tcp_trace!("starting delayed ack timer");
1830 
1831                         AckDelayTimer::Waiting(cx.now() + ack_delay)
1832                     }
1833                     // RFC1122 says "in a stream of full-sized segments there SHOULD be an ACK
1834                     // for at least every second segment".
1835                     // For now, we send an ACK every second received packet, full-sized or not.
1836                     AckDelayTimer::Waiting(_) => {
1837                         tcp_trace!("delayed ack timer already started, forcing expiry");
1838                         AckDelayTimer::Immediate
1839                     }
1840                     AckDelayTimer::Immediate => {
1841                         tcp_trace!("delayed ack timer already force-expired");
1842                         AckDelayTimer::Immediate
1843                     }
1844                 };
1845             }
1846         }
1847 
1848         // Per RFC 5681, we should send an immediate ACK when either:
1849         //  1) an out-of-order segment is received, or
1850         //  2) a segment arrives that fills in all or part of a gap in sequence space.
1851         if !self.assembler.is_empty() || !assembler_was_empty {
1852             // Note that we change the transmitter state here.
1853             // This is fine because smoltcp assumes that it can always transmit zero or one
1854             // packets for every packet it receives.
1855             tcp_trace!("ACKing incoming segment");
1856             Some(self.ack_reply(ip_repr, repr))
1857         } else {
1858             None
1859         }
1860     }
1861 
timed_out(&self, timestamp: Instant) -> bool1862     fn timed_out(&self, timestamp: Instant) -> bool {
1863         match (self.remote_last_ts, self.timeout) {
1864             (Some(remote_last_ts), Some(timeout)) => timestamp >= remote_last_ts + timeout,
1865             (_, _) => false,
1866         }
1867     }
1868 
seq_to_transmit(&self, cx: &mut Context) -> bool1869     fn seq_to_transmit(&self, cx: &mut Context) -> bool {
1870         let ip_header_len = match self.tuple.unwrap().local.addr {
1871             #[cfg(feature = "proto-ipv4")]
1872             IpAddress::Ipv4(_) => crate::wire::IPV4_HEADER_LEN,
1873             #[cfg(feature = "proto-ipv6")]
1874             IpAddress::Ipv6(_) => crate::wire::IPV6_HEADER_LEN,
1875         };
1876 
1877         // Max segment size we're able to send due to MTU limitations.
1878         let local_mss = cx.ip_mtu() - ip_header_len - TCP_HEADER_LEN;
1879 
1880         // The effective max segment size, taking into account our and remote's limits.
1881         let effective_mss = local_mss.min(self.remote_mss);
1882 
1883         // Have we sent data that hasn't been ACKed yet?
1884         let data_in_flight = self.remote_last_seq != self.local_seq_no;
1885 
1886         // If we want to send a SYN and we haven't done so, do it!
1887         if matches!(self.state, State::SynSent | State::SynReceived) && !data_in_flight {
1888             return true;
1889         }
1890 
1891         // max sequence number we can send.
1892         let max_send_seq =
1893             self.local_seq_no + core::cmp::min(self.remote_win_len, self.tx_buffer.len());
1894 
1895         // Max amount of octets we can send.
1896         let max_send = if max_send_seq >= self.remote_last_seq {
1897             max_send_seq - self.remote_last_seq
1898         } else {
1899             0
1900         };
1901 
1902         // Can we send at least 1 octet?
1903         let mut can_send = max_send != 0;
1904         // Can we send at least 1 full segment?
1905         let can_send_full = max_send >= effective_mss;
1906 
1907         // Do we have to send a FIN?
1908         let want_fin = match self.state {
1909             State::FinWait1 => true,
1910             State::Closing => true,
1911             State::LastAck => true,
1912             _ => false,
1913         };
1914 
1915         // If we're applying the Nagle algorithm we don't want to send more
1916         // until one of:
1917         // * There's no data in flight
1918         // * We can send a full packet
1919         // * We have all the data we'll ever send (we're closing send)
1920         if self.nagle && data_in_flight && !can_send_full && !want_fin {
1921             can_send = false;
1922         }
1923 
1924         // Can we actually send the FIN? We can send it if:
1925         // 1. We have unsent data that fits in the remote window.
1926         // 2. We have no unsent data.
1927         // This condition matches only if #2, because #1 is already covered by can_data and we're ORing them.
1928         let can_fin = want_fin && self.remote_last_seq == self.local_seq_no + self.tx_buffer.len();
1929 
1930         can_send || can_fin
1931     }
1932 
delayed_ack_expired(&self, timestamp: Instant) -> bool1933     fn delayed_ack_expired(&self, timestamp: Instant) -> bool {
1934         match self.ack_delay_timer {
1935             AckDelayTimer::Idle => true,
1936             AckDelayTimer::Waiting(t) => t <= timestamp,
1937             AckDelayTimer::Immediate => true,
1938         }
1939     }
1940 
ack_to_transmit(&self) -> bool1941     fn ack_to_transmit(&self) -> bool {
1942         if let Some(remote_last_ack) = self.remote_last_ack {
1943             remote_last_ack < self.remote_seq_no + self.rx_buffer.len()
1944         } else {
1945             false
1946         }
1947     }
1948 
window_to_update(&self) -> bool1949     fn window_to_update(&self) -> bool {
1950         match self.state {
1951             State::SynSent
1952             | State::SynReceived
1953             | State::Established
1954             | State::FinWait1
1955             | State::FinWait2 => self.scaled_window() > self.remote_last_win,
1956             _ => false,
1957         }
1958     }
1959 
dispatch<F, E>(&mut self, cx: &mut Context, emit: F) -> Result<(), E> where F: FnOnce(&mut Context, (IpRepr, TcpRepr)) -> Result<(), E>,1960     pub(crate) fn dispatch<F, E>(&mut self, cx: &mut Context, emit: F) -> Result<(), E>
1961     where
1962         F: FnOnce(&mut Context, (IpRepr, TcpRepr)) -> Result<(), E>,
1963     {
1964         if self.tuple.is_none() {
1965             return Ok(());
1966         }
1967 
1968         if self.remote_last_ts.is_none() {
1969             // We get here in exactly two cases:
1970             //  1) This socket just transitioned into SYN-SENT.
1971             //  2) This socket had an empty transmit buffer and some data was added there.
1972             // Both are similar in that the socket has been quiet for an indefinite
1973             // period of time, it isn't anymore, and the local endpoint is talking.
1974             // So, we start counting the timeout not from the last received packet
1975             // but from the first transmitted one.
1976             self.remote_last_ts = Some(cx.now());
1977         }
1978 
1979         // Check if any state needs to be changed because of a timer.
1980         if self.timed_out(cx.now()) {
1981             // If a timeout expires, we should abort the connection.
1982             net_debug!("timeout exceeded");
1983             self.set_state(State::Closed);
1984         } else if !self.seq_to_transmit(cx) {
1985             if let Some(retransmit_delta) = self.timer.should_retransmit(cx.now()) {
1986                 // If a retransmit timer expired, we should resend data starting at the last ACK.
1987                 net_debug!("retransmitting at t+{}", retransmit_delta);
1988 
1989                 // Rewind "last sequence number sent", as if we never
1990                 // had sent them. This will cause all data in the queue
1991                 // to be sent again.
1992                 self.remote_last_seq = self.local_seq_no;
1993 
1994                 // Clear the `should_retransmit` state. If we can't retransmit right
1995                 // now for whatever reason (like zero window), this avoids an
1996                 // infinite polling loop where `poll_at` returns `Now` but `dispatch`
1997                 // can't actually do anything.
1998                 self.timer.set_for_idle(cx.now(), self.keep_alive);
1999 
2000                 // Inform RTTE, so that it can avoid bogus measurements.
2001                 self.rtte.on_retransmit();
2002             }
2003         }
2004 
2005         // Decide whether we're sending a packet.
2006         if self.seq_to_transmit(cx) {
2007             // If we have data to transmit and it fits into partner's window, do it.
2008             tcp_trace!("outgoing segment will send data or flags");
2009         } else if self.ack_to_transmit() && self.delayed_ack_expired(cx.now()) {
2010             // If we have data to acknowledge, do it.
2011             tcp_trace!("outgoing segment will acknowledge");
2012         } else if self.window_to_update() && self.delayed_ack_expired(cx.now()) {
2013             // If we have window length increase to advertise, do it.
2014             tcp_trace!("outgoing segment will update window");
2015         } else if self.state == State::Closed {
2016             // If we need to abort the connection, do it.
2017             tcp_trace!("outgoing segment will abort connection");
2018         } else if self.timer.should_keep_alive(cx.now()) {
2019             // If we need to transmit a keep-alive packet, do it.
2020             tcp_trace!("keep-alive timer expired");
2021         } else if self.timer.should_close(cx.now()) {
2022             // If we have spent enough time in the TIME-WAIT state, close the socket.
2023             tcp_trace!("TIME-WAIT timer expired");
2024             self.reset();
2025             return Ok(());
2026         } else {
2027             return Ok(());
2028         }
2029 
2030         // NOTE(unwrap): we check tuple is not None the first thing in this function.
2031         let tuple = self.tuple.unwrap();
2032 
2033         // Construct the lowered IP representation.
2034         // We might need this to calculate the MSS, so do it early.
2035         let mut ip_repr = IpRepr::new(
2036             tuple.local.addr,
2037             tuple.remote.addr,
2038             IpProtocol::Tcp,
2039             0,
2040             self.hop_limit.unwrap_or(64),
2041         );
2042 
2043         // Construct the basic TCP representation, an empty ACK packet.
2044         // We'll adjust this to be more specific as needed.
2045         let mut repr = TcpRepr {
2046             src_port: tuple.local.port,
2047             dst_port: tuple.remote.port,
2048             control: TcpControl::None,
2049             seq_number: self.remote_last_seq,
2050             ack_number: Some(self.remote_seq_no + self.rx_buffer.len()),
2051             window_len: self.scaled_window(),
2052             window_scale: None,
2053             max_seg_size: None,
2054             sack_permitted: false,
2055             sack_ranges: [None, None, None],
2056             payload: &[],
2057         };
2058 
2059         match self.state {
2060             // We transmit an RST in the CLOSED state. If we ended up in the CLOSED state
2061             // with a specified endpoint, it means that the socket was aborted.
2062             State::Closed => {
2063                 repr.control = TcpControl::Rst;
2064             }
2065 
2066             // We never transmit anything in the LISTEN state.
2067             State::Listen => return Ok(()),
2068 
2069             // We transmit a SYN in the SYN-SENT state.
2070             // We transmit a SYN|ACK in the SYN-RECEIVED state.
2071             State::SynSent | State::SynReceived => {
2072                 repr.control = TcpControl::Syn;
2073                 // window len must NOT be scaled in SYNs.
2074                 repr.window_len = self.rx_buffer.window().min((1 << 16) - 1) as u16;
2075                 if self.state == State::SynSent {
2076                     repr.ack_number = None;
2077                     repr.window_scale = Some(self.remote_win_shift);
2078                     repr.sack_permitted = true;
2079                 } else {
2080                     repr.sack_permitted = self.remote_has_sack;
2081                     repr.window_scale = self.remote_win_scale.map(|_| self.remote_win_shift);
2082                 }
2083             }
2084 
2085             // We transmit data in all states where we may have data in the buffer,
2086             // or the transmit half of the connection is still open.
2087             State::Established
2088             | State::FinWait1
2089             | State::Closing
2090             | State::CloseWait
2091             | State::LastAck => {
2092                 // Extract as much data as the remote side can receive in this packet
2093                 // from the transmit buffer.
2094 
2095                 // Right edge of window, ie the max sequence number we're allowed to send.
2096                 let win_right_edge = self.local_seq_no + self.remote_win_len;
2097 
2098                 // Max amount of octets we're allowed to send according to the remote window.
2099                 let win_limit = if win_right_edge >= self.remote_last_seq {
2100                     win_right_edge - self.remote_last_seq
2101                 } else {
2102                     // This can happen if we've sent some data and later the remote side
2103                     // has shrunk its window so that data is no longer inside the window.
2104                     // This should be very rare and is strongly discouraged by the RFCs,
2105                     // but it does happen in practice.
2106                     // http://www.tcpipguide.com/free/t_TCPWindowManagementIssues.htm
2107                     0
2108                 };
2109 
2110                 // Maximum size we're allowed to send. This can be limited by 3 factors:
2111                 // 1. remote window
2112                 // 2. MSS the remote is willing to accept, probably determined by their MTU
2113                 // 3. MSS we can send, determined by our MTU.
2114                 let size = win_limit
2115                     .min(self.remote_mss)
2116                     .min(cx.ip_mtu() - ip_repr.header_len() - TCP_HEADER_LEN);
2117 
2118                 let offset = self.remote_last_seq - self.local_seq_no;
2119                 repr.payload = self.tx_buffer.get_allocated(offset, size);
2120 
2121                 // If we've sent everything we had in the buffer, follow it with the PSH or FIN
2122                 // flags, depending on whether the transmit half of the connection is open.
2123                 if offset + repr.payload.len() == self.tx_buffer.len() {
2124                     match self.state {
2125                         State::FinWait1 | State::LastAck | State::Closing => {
2126                             repr.control = TcpControl::Fin
2127                         }
2128                         State::Established | State::CloseWait if !repr.payload.is_empty() => {
2129                             repr.control = TcpControl::Psh
2130                         }
2131                         _ => (),
2132                     }
2133                 }
2134             }
2135 
2136             // In FIN-WAIT-2 and TIME-WAIT states we may only transmit ACKs for incoming data or FIN
2137             State::FinWait2 | State::TimeWait => {}
2138         }
2139 
2140         // There might be more than one reason to send a packet. E.g. the keep-alive timer
2141         // has expired, and we also have data in transmit buffer. Since any packet that occupies
2142         // sequence space will elicit an ACK, we only need to send an explicit packet if we
2143         // couldn't fill the sequence space with anything.
2144         let is_keep_alive;
2145         if self.timer.should_keep_alive(cx.now()) && repr.is_empty() {
2146             repr.seq_number = repr.seq_number - 1;
2147             repr.payload = b"\x00"; // RFC 1122 says we should do this
2148             is_keep_alive = true;
2149         } else {
2150             is_keep_alive = false;
2151         }
2152 
2153         // Trace a summary of what will be sent.
2154         if is_keep_alive {
2155             tcp_trace!("sending a keep-alive");
2156         } else if !repr.payload.is_empty() {
2157             tcp_trace!(
2158                 "tx buffer: sending {} octets at offset {}",
2159                 repr.payload.len(),
2160                 self.remote_last_seq - self.local_seq_no
2161             );
2162         }
2163         if repr.control != TcpControl::None || repr.payload.is_empty() {
2164             let flags = match (repr.control, repr.ack_number) {
2165                 (TcpControl::Syn, None) => "SYN",
2166                 (TcpControl::Syn, Some(_)) => "SYN|ACK",
2167                 (TcpControl::Fin, Some(_)) => "FIN|ACK",
2168                 (TcpControl::Rst, Some(_)) => "RST|ACK",
2169                 (TcpControl::Psh, Some(_)) => "PSH|ACK",
2170                 (TcpControl::None, Some(_)) => "ACK",
2171                 _ => "<unreachable>",
2172             };
2173             tcp_trace!("sending {}", flags);
2174         }
2175 
2176         if repr.control == TcpControl::Syn {
2177             // Fill the MSS option. See RFC 6691 for an explanation of this calculation.
2178             let max_segment_size = cx.ip_mtu() - ip_repr.header_len() - TCP_HEADER_LEN;
2179             repr.max_seg_size = Some(max_segment_size as u16);
2180         }
2181 
2182         // Actually send the packet. If this succeeds, it means the packet is in
2183         // the device buffer, and its transmission is imminent. If not, we might have
2184         // a number of problems, e.g. we need neighbor discovery.
2185         //
2186         // Bailing out if the packet isn't placed in the device buffer allows us
2187         // to not waste time waiting for the retransmit timer on packets that we know
2188         // for sure will not be successfully transmitted.
2189         ip_repr.set_payload_len(repr.buffer_len());
2190         emit(cx, (ip_repr, repr))?;
2191 
2192         // We've sent something, whether useful data or a keep-alive packet, so rewind
2193         // the keep-alive timer.
2194         self.timer.rewind_keep_alive(cx.now(), self.keep_alive);
2195 
2196         // Reset delayed-ack timer
2197         match self.ack_delay_timer {
2198             AckDelayTimer::Idle => {}
2199             AckDelayTimer::Waiting(_) => {
2200                 tcp_trace!("stop delayed ack timer")
2201             }
2202             AckDelayTimer::Immediate => {
2203                 tcp_trace!("stop delayed ack timer (was force-expired)")
2204             }
2205         }
2206         self.ack_delay_timer = AckDelayTimer::Idle;
2207 
2208         // Leave the rest of the state intact if sending a keep-alive packet, since those
2209         // carry a fake segment.
2210         if is_keep_alive {
2211             return Ok(());
2212         }
2213 
2214         // We've sent a packet successfully, so we can update the internal state now.
2215         self.remote_last_seq = repr.seq_number + repr.segment_len();
2216         self.remote_last_ack = repr.ack_number;
2217         self.remote_last_win = repr.window_len;
2218 
2219         if repr.segment_len() > 0 {
2220             self.rtte
2221                 .on_send(cx.now(), repr.seq_number + repr.segment_len());
2222         }
2223 
2224         if !self.seq_to_transmit(cx) && repr.segment_len() > 0 {
2225             // If we've transmitted all data we could (and there was something at all,
2226             // data or flag, to transmit, not just an ACK), wind up the retransmit timer.
2227             self.timer
2228                 .set_for_retransmit(cx.now(), self.rtte.retransmission_timeout());
2229         }
2230 
2231         if self.state == State::Closed {
2232             // When aborting a connection, forget about it after sending a single RST packet.
2233             self.tuple = None;
2234         }
2235 
2236         Ok(())
2237     }
2238 
2239     #[allow(clippy::if_same_then_else)]
poll_at(&self, cx: &mut Context) -> PollAt2240     pub(crate) fn poll_at(&self, cx: &mut Context) -> PollAt {
2241         // The logic here mirrors the beginning of dispatch() closely.
2242         if self.tuple.is_none() {
2243             // No one to talk to, nothing to transmit.
2244             PollAt::Ingress
2245         } else if self.remote_last_ts.is_none() {
2246             // Socket stopped being quiet recently, we need to acquire a timestamp.
2247             PollAt::Now
2248         } else if self.state == State::Closed {
2249             // Socket was aborted, we have an RST packet to transmit.
2250             PollAt::Now
2251         } else if self.seq_to_transmit(cx) {
2252             // We have a data or flag packet to transmit.
2253             PollAt::Now
2254         } else {
2255             let want_ack = self.ack_to_transmit() || self.window_to_update();
2256 
2257             let delayed_ack_poll_at = match (want_ack, self.ack_delay_timer) {
2258                 (false, _) => PollAt::Ingress,
2259                 (true, AckDelayTimer::Idle) => PollAt::Now,
2260                 (true, AckDelayTimer::Waiting(t)) => PollAt::Time(t),
2261                 (true, AckDelayTimer::Immediate) => PollAt::Now,
2262             };
2263 
2264             let timeout_poll_at = match (self.remote_last_ts, self.timeout) {
2265                 // If we're transmitting or retransmitting data, we need to poll at the moment
2266                 // when the timeout would expire.
2267                 (Some(remote_last_ts), Some(timeout)) => PollAt::Time(remote_last_ts + timeout),
2268                 // Otherwise we have no timeout.
2269                 (_, _) => PollAt::Ingress,
2270             };
2271 
2272             // We wait for the earliest of our timers to fire.
2273             *[self.timer.poll_at(), timeout_poll_at, delayed_ack_poll_at]
2274                 .iter()
2275                 .min()
2276                 .unwrap_or(&PollAt::Ingress)
2277         }
2278     }
2279 }
2280 
2281 impl<'a> fmt::Write for Socket<'a> {
write_str(&mut self, slice: &str) -> fmt::Result2282     fn write_str(&mut self, slice: &str) -> fmt::Result {
2283         let slice = slice.as_bytes();
2284         if self.send_slice(slice) == Ok(slice.len()) {
2285             Ok(())
2286         } else {
2287             Err(fmt::Error)
2288         }
2289     }
2290 }
2291 
2292 #[cfg(test)]
2293 mod test {
2294     use super::*;
2295     use crate::wire::IpRepr;
2296     use core::i32;
2297     use std::ops::{Deref, DerefMut};
2298     use std::vec::Vec;
2299 
2300     // =========================================================================================//
2301     // Constants
2302     // =========================================================================================//
2303 
2304     const LOCAL_PORT: u16 = 80;
2305     const REMOTE_PORT: u16 = 49500;
2306     const LISTEN_END: IpListenEndpoint = IpListenEndpoint {
2307         addr: None,
2308         port: LOCAL_PORT,
2309     };
2310     const LOCAL_END: IpEndpoint = IpEndpoint {
2311         addr: LOCAL_ADDR.into_address(),
2312         port: LOCAL_PORT,
2313     };
2314     const REMOTE_END: IpEndpoint = IpEndpoint {
2315         addr: REMOTE_ADDR.into_address(),
2316         port: REMOTE_PORT,
2317     };
2318     const TUPLE: Tuple = Tuple {
2319         local: LOCAL_END,
2320         remote: REMOTE_END,
2321     };
2322     const LOCAL_SEQ: TcpSeqNumber = TcpSeqNumber(10000);
2323     const REMOTE_SEQ: TcpSeqNumber = TcpSeqNumber(-10001);
2324 
2325     cfg_if::cfg_if! {
2326         if #[cfg(feature = "proto-ipv4")] {
2327             use crate::wire::Ipv4Address as IpvXAddress;
2328             use crate::wire::Ipv4Repr as IpvXRepr;
2329             use IpRepr::Ipv4 as IpReprIpvX;
2330 
2331             const LOCAL_ADDR: IpvXAddress = IpvXAddress([192, 168, 1, 1]);
2332             const REMOTE_ADDR: IpvXAddress = IpvXAddress([192, 168, 1, 2]);
2333             const OTHER_ADDR: IpvXAddress = IpvXAddress([192, 168, 1, 3]);
2334 
2335             const BASE_MSS: u16 = 1460;
2336         } else {
2337             use crate::wire::Ipv6Address as IpvXAddress;
2338             use crate::wire::Ipv6Repr as IpvXRepr;
2339             use IpRepr::Ipv6 as IpReprIpvX;
2340 
2341             const LOCAL_ADDR: IpvXAddress = IpvXAddress([
2342                 0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2343             ]);
2344             const REMOTE_ADDR: IpvXAddress = IpvXAddress([
2345                 0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
2346             ]);
2347             const OTHER_ADDR: IpvXAddress = IpvXAddress([
2348                 0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3,
2349             ]);
2350 
2351             const BASE_MSS: u16 = 1440;
2352         }
2353     }
2354 
2355     const SEND_IP_TEMPL: IpRepr = IpReprIpvX(IpvXRepr {
2356         src_addr: LOCAL_ADDR,
2357         dst_addr: REMOTE_ADDR,
2358         next_header: IpProtocol::Tcp,
2359         payload_len: 20,
2360         hop_limit: 64,
2361     });
2362     const SEND_TEMPL: TcpRepr<'static> = TcpRepr {
2363         src_port: REMOTE_PORT,
2364         dst_port: LOCAL_PORT,
2365         control: TcpControl::None,
2366         seq_number: TcpSeqNumber(0),
2367         ack_number: Some(TcpSeqNumber(0)),
2368         window_len: 256,
2369         window_scale: None,
2370         max_seg_size: None,
2371         sack_permitted: false,
2372         sack_ranges: [None, None, None],
2373         payload: &[],
2374     };
2375     const _RECV_IP_TEMPL: IpRepr = IpReprIpvX(IpvXRepr {
2376         src_addr: LOCAL_ADDR,
2377         dst_addr: REMOTE_ADDR,
2378         next_header: IpProtocol::Tcp,
2379         payload_len: 20,
2380         hop_limit: 64,
2381     });
2382     const RECV_TEMPL: TcpRepr<'static> = TcpRepr {
2383         src_port: LOCAL_PORT,
2384         dst_port: REMOTE_PORT,
2385         control: TcpControl::None,
2386         seq_number: TcpSeqNumber(0),
2387         ack_number: Some(TcpSeqNumber(0)),
2388         window_len: 64,
2389         window_scale: None,
2390         max_seg_size: None,
2391         sack_permitted: false,
2392         sack_ranges: [None, None, None],
2393         payload: &[],
2394     };
2395 
2396     // =========================================================================================//
2397     // Helper functions
2398     // =========================================================================================//
2399 
2400     struct TestSocket {
2401         socket: Socket<'static>,
2402         cx: Context,
2403     }
2404 
2405     impl Deref for TestSocket {
2406         type Target = Socket<'static>;
deref(&self) -> &Self::Target2407         fn deref(&self) -> &Self::Target {
2408             &self.socket
2409         }
2410     }
2411 
2412     impl DerefMut for TestSocket {
deref_mut(&mut self) -> &mut Self::Target2413         fn deref_mut(&mut self) -> &mut Self::Target {
2414             &mut self.socket
2415         }
2416     }
2417 
send( socket: &mut TestSocket, timestamp: Instant, repr: &TcpRepr, ) -> Option<TcpRepr<'static>>2418     fn send(
2419         socket: &mut TestSocket,
2420         timestamp: Instant,
2421         repr: &TcpRepr,
2422     ) -> Option<TcpRepr<'static>> {
2423         socket.cx.set_now(timestamp);
2424 
2425         let ip_repr = IpReprIpvX(IpvXRepr {
2426             src_addr: REMOTE_ADDR,
2427             dst_addr: LOCAL_ADDR,
2428             next_header: IpProtocol::Tcp,
2429             payload_len: repr.buffer_len(),
2430             hop_limit: 64,
2431         });
2432         net_trace!("send: {}", repr);
2433 
2434         assert!(socket.socket.accepts(&mut socket.cx, &ip_repr, repr));
2435 
2436         match socket.socket.process(&mut socket.cx, &ip_repr, repr) {
2437             Some((_ip_repr, repr)) => {
2438                 net_trace!("recv: {}", repr);
2439                 Some(repr)
2440             }
2441             None => None,
2442         }
2443     }
2444 
recv<F>(socket: &mut TestSocket, timestamp: Instant, mut f: F) where F: FnMut(Result<TcpRepr, ()>),2445     fn recv<F>(socket: &mut TestSocket, timestamp: Instant, mut f: F)
2446     where
2447         F: FnMut(Result<TcpRepr, ()>),
2448     {
2449         socket.cx.set_now(timestamp);
2450 
2451         let mut sent = 0;
2452         let result = socket
2453             .socket
2454             .dispatch(&mut socket.cx, |_, (ip_repr, tcp_repr)| {
2455                 assert_eq!(ip_repr.next_header(), IpProtocol::Tcp);
2456                 assert_eq!(ip_repr.src_addr(), LOCAL_ADDR.into());
2457                 assert_eq!(ip_repr.dst_addr(), REMOTE_ADDR.into());
2458                 assert_eq!(ip_repr.payload_len(), tcp_repr.buffer_len());
2459 
2460                 net_trace!("recv: {}", tcp_repr);
2461                 sent += 1;
2462                 Ok(f(Ok(tcp_repr)))
2463             });
2464         match result {
2465             Ok(()) => assert_eq!(sent, 1, "Exactly one packet should be sent"),
2466             Err(e) => f(Err(e)),
2467         }
2468     }
2469 
recv_nothing(socket: &mut TestSocket, timestamp: Instant)2470     fn recv_nothing(socket: &mut TestSocket, timestamp: Instant) {
2471         socket.cx.set_now(timestamp);
2472 
2473         let result: Result<(), ()> = socket
2474             .socket
2475             .dispatch(&mut socket.cx, |_, (_ip_repr, _tcp_repr)| {
2476                 panic!("Should not send a packet")
2477             });
2478 
2479         assert_eq!(result, Ok(()))
2480     }
2481 
2482     macro_rules! send {
2483         ($socket:ident, $repr:expr) =>
2484             (send!($socket, time 0, $repr));
2485         ($socket:ident, $repr:expr, $result:expr) =>
2486             (send!($socket, time 0, $repr, $result));
2487         ($socket:ident, time $time:expr, $repr:expr) =>
2488             (send!($socket, time $time, $repr, None));
2489         ($socket:ident, time $time:expr, $repr:expr, $result:expr) =>
2490             (assert_eq!(send(&mut $socket, Instant::from_millis($time), &$repr), $result));
2491     }
2492 
2493     macro_rules! recv {
2494         ($socket:ident, [$( $repr:expr ),*]) => ({
2495             $( recv!($socket, Ok($repr)); )*
2496             recv_nothing!($socket)
2497         });
2498         ($socket:ident, $result:expr) =>
2499             (recv!($socket, time 0, $result));
2500         ($socket:ident, time $time:expr, $result:expr) =>
2501             (recv(&mut $socket, Instant::from_millis($time), |result| {
2502                 // Most of the time we don't care about the PSH flag.
2503                 let result = result.map(|mut repr| {
2504                     repr.control = repr.control.quash_psh();
2505                     repr
2506                 });
2507                 assert_eq!(result, $result)
2508             }));
2509         ($socket:ident, time $time:expr, $result:expr, exact) =>
2510             (recv(&mut $socket, Instant::from_millis($time), |repr| assert_eq!(repr, $result)));
2511     }
2512 
2513     macro_rules! recv_nothing {
2514         ($socket:ident) => (recv_nothing!($socket, time 0));
2515         ($socket:ident, time $time:expr) => (recv_nothing(&mut $socket, Instant::from_millis($time)));
2516     }
2517 
2518     macro_rules! sanity {
2519         ($socket1:expr, $socket2:expr) => {{
2520             let (s1, s2) = ($socket1, $socket2);
2521             assert_eq!(s1.state, s2.state, "state");
2522             assert_eq!(s1.tuple, s2.tuple, "tuple");
2523             assert_eq!(s1.local_seq_no, s2.local_seq_no, "local_seq_no");
2524             assert_eq!(s1.remote_seq_no, s2.remote_seq_no, "remote_seq_no");
2525             assert_eq!(s1.remote_last_seq, s2.remote_last_seq, "remote_last_seq");
2526             assert_eq!(s1.remote_last_ack, s2.remote_last_ack, "remote_last_ack");
2527             assert_eq!(s1.remote_last_win, s2.remote_last_win, "remote_last_win");
2528             assert_eq!(s1.remote_win_len, s2.remote_win_len, "remote_win_len");
2529             assert_eq!(s1.timer, s2.timer, "timer");
2530         }};
2531     }
2532 
socket() -> TestSocket2533     fn socket() -> TestSocket {
2534         socket_with_buffer_sizes(64, 64)
2535     }
2536 
socket_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TestSocket2537     fn socket_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TestSocket {
2538         let rx_buffer = SocketBuffer::new(vec![0; rx_len]);
2539         let tx_buffer = SocketBuffer::new(vec![0; tx_len]);
2540         let mut socket = Socket::new(rx_buffer, tx_buffer);
2541         socket.set_ack_delay(None);
2542         let cx = Context::mock();
2543         TestSocket { socket, cx }
2544     }
2545 
socket_syn_received_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TestSocket2546     fn socket_syn_received_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TestSocket {
2547         let mut s = socket_with_buffer_sizes(tx_len, rx_len);
2548         s.state = State::SynReceived;
2549         s.tuple = Some(TUPLE);
2550         s.local_seq_no = LOCAL_SEQ;
2551         s.remote_seq_no = REMOTE_SEQ + 1;
2552         s.remote_last_seq = LOCAL_SEQ;
2553         s.remote_win_len = 256;
2554         s
2555     }
2556 
socket_syn_received() -> TestSocket2557     fn socket_syn_received() -> TestSocket {
2558         socket_syn_received_with_buffer_sizes(64, 64)
2559     }
2560 
socket_syn_sent_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TestSocket2561     fn socket_syn_sent_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TestSocket {
2562         let mut s = socket_with_buffer_sizes(tx_len, rx_len);
2563         s.state = State::SynSent;
2564         s.tuple = Some(TUPLE);
2565         s.local_seq_no = LOCAL_SEQ;
2566         s.remote_last_seq = LOCAL_SEQ;
2567         s
2568     }
2569 
socket_syn_sent() -> TestSocket2570     fn socket_syn_sent() -> TestSocket {
2571         socket_syn_sent_with_buffer_sizes(64, 64)
2572     }
2573 
socket_established_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TestSocket2574     fn socket_established_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TestSocket {
2575         let mut s = socket_syn_received_with_buffer_sizes(tx_len, rx_len);
2576         s.state = State::Established;
2577         s.local_seq_no = LOCAL_SEQ + 1;
2578         s.remote_last_seq = LOCAL_SEQ + 1;
2579         s.remote_last_ack = Some(REMOTE_SEQ + 1);
2580         s.remote_last_win = 64;
2581         s
2582     }
2583 
socket_established() -> TestSocket2584     fn socket_established() -> TestSocket {
2585         socket_established_with_buffer_sizes(64, 64)
2586     }
2587 
socket_fin_wait_1() -> TestSocket2588     fn socket_fin_wait_1() -> TestSocket {
2589         let mut s = socket_established();
2590         s.state = State::FinWait1;
2591         s
2592     }
2593 
socket_fin_wait_2() -> TestSocket2594     fn socket_fin_wait_2() -> TestSocket {
2595         let mut s = socket_fin_wait_1();
2596         s.state = State::FinWait2;
2597         s.local_seq_no = LOCAL_SEQ + 1 + 1;
2598         s.remote_last_seq = LOCAL_SEQ + 1 + 1;
2599         s
2600     }
2601 
socket_closing() -> TestSocket2602     fn socket_closing() -> TestSocket {
2603         let mut s = socket_fin_wait_1();
2604         s.state = State::Closing;
2605         s.remote_last_seq = LOCAL_SEQ + 1 + 1;
2606         s.remote_seq_no = REMOTE_SEQ + 1 + 1;
2607         s
2608     }
2609 
socket_time_wait(from_closing: bool) -> TestSocket2610     fn socket_time_wait(from_closing: bool) -> TestSocket {
2611         let mut s = socket_fin_wait_2();
2612         s.state = State::TimeWait;
2613         s.remote_seq_no = REMOTE_SEQ + 1 + 1;
2614         if from_closing {
2615             s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
2616         }
2617         s.timer = Timer::Close {
2618             expires_at: Instant::from_secs(1) + CLOSE_DELAY,
2619         };
2620         s
2621     }
2622 
socket_close_wait() -> TestSocket2623     fn socket_close_wait() -> TestSocket {
2624         let mut s = socket_established();
2625         s.state = State::CloseWait;
2626         s.remote_seq_no = REMOTE_SEQ + 1 + 1;
2627         s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
2628         s
2629     }
2630 
socket_last_ack() -> TestSocket2631     fn socket_last_ack() -> TestSocket {
2632         let mut s = socket_close_wait();
2633         s.state = State::LastAck;
2634         s
2635     }
2636 
socket_recved() -> TestSocket2637     fn socket_recved() -> TestSocket {
2638         let mut s = socket_established();
2639         send!(
2640             s,
2641             TcpRepr {
2642                 seq_number: REMOTE_SEQ + 1,
2643                 ack_number: Some(LOCAL_SEQ + 1),
2644                 payload: &b"abcdef"[..],
2645                 ..SEND_TEMPL
2646             }
2647         );
2648         recv!(
2649             s,
2650             [TcpRepr {
2651                 seq_number: LOCAL_SEQ + 1,
2652                 ack_number: Some(REMOTE_SEQ + 1 + 6),
2653                 window_len: 58,
2654                 ..RECV_TEMPL
2655             }]
2656         );
2657         s
2658     }
2659 
2660     // =========================================================================================//
2661     // Tests for the CLOSED state.
2662     // =========================================================================================//
2663     #[test]
test_closed_reject()2664     fn test_closed_reject() {
2665         let mut s = socket();
2666         assert_eq!(s.state, State::Closed);
2667 
2668         let tcp_repr = TcpRepr {
2669             control: TcpControl::Syn,
2670             ..SEND_TEMPL
2671         };
2672         assert!(!s.socket.accepts(&mut s.cx, &SEND_IP_TEMPL, &tcp_repr));
2673     }
2674 
2675     #[test]
test_closed_reject_after_listen()2676     fn test_closed_reject_after_listen() {
2677         let mut s = socket();
2678         s.listen(LOCAL_END).unwrap();
2679         s.close();
2680 
2681         let tcp_repr = TcpRepr {
2682             control: TcpControl::Syn,
2683             ..SEND_TEMPL
2684         };
2685         assert!(!s.socket.accepts(&mut s.cx, &SEND_IP_TEMPL, &tcp_repr));
2686     }
2687 
2688     #[test]
test_closed_close()2689     fn test_closed_close() {
2690         let mut s = socket();
2691         s.close();
2692         assert_eq!(s.state, State::Closed);
2693     }
2694 
2695     // =========================================================================================//
2696     // Tests for the LISTEN state.
2697     // =========================================================================================//
socket_listen() -> TestSocket2698     fn socket_listen() -> TestSocket {
2699         let mut s = socket();
2700         s.state = State::Listen;
2701         s.listen_endpoint = LISTEN_END;
2702         s
2703     }
2704 
2705     #[test]
test_listen_sack_option()2706     fn test_listen_sack_option() {
2707         let mut s = socket_listen();
2708         send!(
2709             s,
2710             TcpRepr {
2711                 control: TcpControl::Syn,
2712                 seq_number: REMOTE_SEQ,
2713                 ack_number: None,
2714                 sack_permitted: false,
2715                 ..SEND_TEMPL
2716             }
2717         );
2718         assert!(!s.remote_has_sack);
2719         recv!(
2720             s,
2721             [TcpRepr {
2722                 control: TcpControl::Syn,
2723                 seq_number: LOCAL_SEQ,
2724                 ack_number: Some(REMOTE_SEQ + 1),
2725                 max_seg_size: Some(BASE_MSS),
2726                 ..RECV_TEMPL
2727             }]
2728         );
2729 
2730         let mut s = socket_listen();
2731         send!(
2732             s,
2733             TcpRepr {
2734                 control: TcpControl::Syn,
2735                 seq_number: REMOTE_SEQ,
2736                 ack_number: None,
2737                 sack_permitted: true,
2738                 ..SEND_TEMPL
2739             }
2740         );
2741         assert!(s.remote_has_sack);
2742         recv!(
2743             s,
2744             [TcpRepr {
2745                 control: TcpControl::Syn,
2746                 seq_number: LOCAL_SEQ,
2747                 ack_number: Some(REMOTE_SEQ + 1),
2748                 max_seg_size: Some(BASE_MSS),
2749                 sack_permitted: true,
2750                 ..RECV_TEMPL
2751             }]
2752         );
2753     }
2754 
2755     #[test]
test_listen_syn_win_scale_buffers()2756     fn test_listen_syn_win_scale_buffers() {
2757         for (buffer_size, shift_amt) in &[
2758             (64, 0),
2759             (128, 0),
2760             (1024, 0),
2761             (65535, 0),
2762             (65536, 1),
2763             (65537, 1),
2764             (131071, 1),
2765             (131072, 2),
2766             (524287, 3),
2767             (524288, 4),
2768             (655350, 4),
2769             (1048576, 5),
2770         ] {
2771             let mut s = socket_with_buffer_sizes(64, *buffer_size);
2772             s.state = State::Listen;
2773             s.listen_endpoint = LISTEN_END;
2774             assert_eq!(s.remote_win_shift, *shift_amt);
2775             send!(
2776                 s,
2777                 TcpRepr {
2778                     control: TcpControl::Syn,
2779                     seq_number: REMOTE_SEQ,
2780                     ack_number: None,
2781                     window_scale: Some(0),
2782                     ..SEND_TEMPL
2783                 }
2784             );
2785             assert_eq!(s.remote_win_shift, *shift_amt);
2786             recv!(
2787                 s,
2788                 [TcpRepr {
2789                     control: TcpControl::Syn,
2790                     seq_number: LOCAL_SEQ,
2791                     ack_number: Some(REMOTE_SEQ + 1),
2792                     max_seg_size: Some(BASE_MSS),
2793                     window_scale: Some(*shift_amt),
2794                     window_len: cmp::min(*buffer_size, 65535) as u16,
2795                     ..RECV_TEMPL
2796                 }]
2797             );
2798         }
2799     }
2800 
2801     #[test]
test_listen_sanity()2802     fn test_listen_sanity() {
2803         let mut s = socket();
2804         s.listen(LOCAL_PORT).unwrap();
2805         sanity!(s, socket_listen());
2806     }
2807 
2808     #[test]
test_listen_validation()2809     fn test_listen_validation() {
2810         let mut s = socket();
2811         assert_eq!(s.listen(0), Err(ListenError::Unaddressable));
2812     }
2813 
2814     #[test]
test_listen_twice()2815     fn test_listen_twice() {
2816         let mut s = socket();
2817         assert_eq!(s.listen(80), Ok(()));
2818         assert_eq!(s.listen(80), Err(ListenError::InvalidState));
2819     }
2820 
2821     #[test]
test_listen_syn()2822     fn test_listen_syn() {
2823         let mut s = socket_listen();
2824         send!(
2825             s,
2826             TcpRepr {
2827                 control: TcpControl::Syn,
2828                 seq_number: REMOTE_SEQ,
2829                 ack_number: None,
2830                 ..SEND_TEMPL
2831             }
2832         );
2833         sanity!(s, socket_syn_received());
2834     }
2835 
2836     #[test]
test_listen_syn_reject_ack()2837     fn test_listen_syn_reject_ack() {
2838         let mut s = socket_listen();
2839 
2840         let tcp_repr = TcpRepr {
2841             control: TcpControl::Syn,
2842             seq_number: REMOTE_SEQ,
2843             ack_number: Some(LOCAL_SEQ),
2844             ..SEND_TEMPL
2845         };
2846         assert!(!s.socket.accepts(&mut s.cx, &SEND_IP_TEMPL, &tcp_repr));
2847 
2848         assert_eq!(s.state, State::Listen);
2849     }
2850 
2851     #[test]
test_listen_rst()2852     fn test_listen_rst() {
2853         let mut s = socket_listen();
2854         send!(
2855             s,
2856             TcpRepr {
2857                 control: TcpControl::Rst,
2858                 seq_number: REMOTE_SEQ,
2859                 ack_number: None,
2860                 ..SEND_TEMPL
2861             }
2862         );
2863         assert_eq!(s.state, State::Listen);
2864     }
2865 
2866     #[test]
test_listen_close()2867     fn test_listen_close() {
2868         let mut s = socket_listen();
2869         s.close();
2870         assert_eq!(s.state, State::Closed);
2871     }
2872 
2873     // =========================================================================================//
2874     // Tests for the SYN-RECEIVED state.
2875     // =========================================================================================//
2876 
2877     #[test]
test_syn_received_ack()2878     fn test_syn_received_ack() {
2879         let mut s = socket_syn_received();
2880         recv!(
2881             s,
2882             [TcpRepr {
2883                 control: TcpControl::Syn,
2884                 seq_number: LOCAL_SEQ,
2885                 ack_number: Some(REMOTE_SEQ + 1),
2886                 max_seg_size: Some(BASE_MSS),
2887                 ..RECV_TEMPL
2888             }]
2889         );
2890         send!(
2891             s,
2892             TcpRepr {
2893                 seq_number: REMOTE_SEQ + 1,
2894                 ack_number: Some(LOCAL_SEQ + 1),
2895                 ..SEND_TEMPL
2896             }
2897         );
2898         assert_eq!(s.state, State::Established);
2899         sanity!(s, socket_established());
2900     }
2901 
2902     #[test]
test_syn_received_ack_too_low()2903     fn test_syn_received_ack_too_low() {
2904         let mut s = socket_syn_received();
2905         recv!(
2906             s,
2907             [TcpRepr {
2908                 control: TcpControl::Syn,
2909                 seq_number: LOCAL_SEQ,
2910                 ack_number: Some(REMOTE_SEQ + 1),
2911                 max_seg_size: Some(BASE_MSS),
2912                 ..RECV_TEMPL
2913             }]
2914         );
2915         send!(
2916             s,
2917             TcpRepr {
2918                 seq_number: REMOTE_SEQ + 1,
2919                 ack_number: Some(LOCAL_SEQ), // wrong
2920                 ..SEND_TEMPL
2921             },
2922             Some(TcpRepr {
2923                 control: TcpControl::Rst,
2924                 seq_number: LOCAL_SEQ,
2925                 ack_number: None,
2926                 window_len: 0,
2927                 ..RECV_TEMPL
2928             })
2929         );
2930         assert_eq!(s.state, State::SynReceived);
2931     }
2932 
2933     #[test]
test_syn_received_ack_too_high()2934     fn test_syn_received_ack_too_high() {
2935         let mut s = socket_syn_received();
2936         recv!(
2937             s,
2938             [TcpRepr {
2939                 control: TcpControl::Syn,
2940                 seq_number: LOCAL_SEQ,
2941                 ack_number: Some(REMOTE_SEQ + 1),
2942                 max_seg_size: Some(BASE_MSS),
2943                 ..RECV_TEMPL
2944             }]
2945         );
2946         send!(
2947             s,
2948             TcpRepr {
2949                 seq_number: REMOTE_SEQ + 1,
2950                 ack_number: Some(LOCAL_SEQ + 2), // wrong
2951                 ..SEND_TEMPL
2952             },
2953             Some(TcpRepr {
2954                 control: TcpControl::Rst,
2955                 seq_number: LOCAL_SEQ + 2,
2956                 ack_number: None,
2957                 window_len: 0,
2958                 ..RECV_TEMPL
2959             })
2960         );
2961         assert_eq!(s.state, State::SynReceived);
2962     }
2963 
2964     #[test]
test_syn_received_fin()2965     fn test_syn_received_fin() {
2966         let mut s = socket_syn_received();
2967         recv!(
2968             s,
2969             [TcpRepr {
2970                 control: TcpControl::Syn,
2971                 seq_number: LOCAL_SEQ,
2972                 ack_number: Some(REMOTE_SEQ + 1),
2973                 max_seg_size: Some(BASE_MSS),
2974                 ..RECV_TEMPL
2975             }]
2976         );
2977         send!(
2978             s,
2979             TcpRepr {
2980                 control: TcpControl::Fin,
2981                 seq_number: REMOTE_SEQ + 1,
2982                 ack_number: Some(LOCAL_SEQ + 1),
2983                 payload: &b"abcdef"[..],
2984                 ..SEND_TEMPL
2985             }
2986         );
2987         recv!(
2988             s,
2989             [TcpRepr {
2990                 seq_number: LOCAL_SEQ + 1,
2991                 ack_number: Some(REMOTE_SEQ + 1 + 6 + 1),
2992                 window_len: 58,
2993                 ..RECV_TEMPL
2994             }]
2995         );
2996         assert_eq!(s.state, State::CloseWait);
2997 
2998         let mut s2 = socket_close_wait();
2999         s2.remote_last_ack = Some(REMOTE_SEQ + 1 + 6 + 1);
3000         s2.remote_last_win = 58;
3001         sanity!(s, s2);
3002     }
3003 
3004     #[test]
test_syn_received_rst()3005     fn test_syn_received_rst() {
3006         let mut s = socket_syn_received();
3007         s.listen_endpoint = LISTEN_END;
3008         recv!(
3009             s,
3010             [TcpRepr {
3011                 control: TcpControl::Syn,
3012                 seq_number: LOCAL_SEQ,
3013                 ack_number: Some(REMOTE_SEQ + 1),
3014                 max_seg_size: Some(BASE_MSS),
3015                 ..RECV_TEMPL
3016             }]
3017         );
3018         send!(
3019             s,
3020             TcpRepr {
3021                 control: TcpControl::Rst,
3022                 seq_number: REMOTE_SEQ + 1,
3023                 ack_number: Some(LOCAL_SEQ),
3024                 ..SEND_TEMPL
3025             }
3026         );
3027         assert_eq!(s.state, State::Listen);
3028         assert_eq!(s.listen_endpoint, LISTEN_END);
3029         assert_eq!(s.tuple, None);
3030     }
3031 
3032     #[test]
test_syn_received_no_window_scaling()3033     fn test_syn_received_no_window_scaling() {
3034         let mut s = socket_listen();
3035         send!(
3036             s,
3037             TcpRepr {
3038                 control: TcpControl::Syn,
3039                 seq_number: REMOTE_SEQ,
3040                 ack_number: None,
3041                 ..SEND_TEMPL
3042             }
3043         );
3044         assert_eq!(s.state(), State::SynReceived);
3045         assert_eq!(s.tuple, Some(TUPLE));
3046         recv!(
3047             s,
3048             [TcpRepr {
3049                 control: TcpControl::Syn,
3050                 seq_number: LOCAL_SEQ,
3051                 ack_number: Some(REMOTE_SEQ + 1),
3052                 max_seg_size: Some(BASE_MSS),
3053                 window_scale: None,
3054                 ..RECV_TEMPL
3055             }]
3056         );
3057         send!(
3058             s,
3059             TcpRepr {
3060                 seq_number: REMOTE_SEQ + 1,
3061                 ack_number: Some(LOCAL_SEQ + 1),
3062                 window_scale: None,
3063                 ..SEND_TEMPL
3064             }
3065         );
3066         assert_eq!(s.remote_win_shift, 0);
3067         assert_eq!(s.remote_win_scale, None);
3068     }
3069 
3070     #[test]
test_syn_received_window_scaling()3071     fn test_syn_received_window_scaling() {
3072         for scale in 0..14 {
3073             let mut s = socket_listen();
3074             send!(
3075                 s,
3076                 TcpRepr {
3077                     control: TcpControl::Syn,
3078                     seq_number: REMOTE_SEQ,
3079                     ack_number: None,
3080                     window_scale: Some(scale),
3081                     ..SEND_TEMPL
3082                 }
3083             );
3084             assert_eq!(s.state(), State::SynReceived);
3085             assert_eq!(s.tuple, Some(TUPLE));
3086             recv!(
3087                 s,
3088                 [TcpRepr {
3089                     control: TcpControl::Syn,
3090                     seq_number: LOCAL_SEQ,
3091                     ack_number: Some(REMOTE_SEQ + 1),
3092                     max_seg_size: Some(BASE_MSS),
3093                     window_scale: Some(0),
3094                     ..RECV_TEMPL
3095                 }]
3096             );
3097             send!(
3098                 s,
3099                 TcpRepr {
3100                     seq_number: REMOTE_SEQ + 1,
3101                     ack_number: Some(LOCAL_SEQ + 1),
3102                     window_scale: None,
3103                     ..SEND_TEMPL
3104                 }
3105             );
3106             assert_eq!(s.remote_win_scale, Some(scale));
3107         }
3108     }
3109 
3110     #[test]
test_syn_received_close()3111     fn test_syn_received_close() {
3112         let mut s = socket_syn_received();
3113         s.close();
3114         assert_eq!(s.state, State::FinWait1);
3115     }
3116 
3117     // =========================================================================================//
3118     // Tests for the SYN-SENT state.
3119     // =========================================================================================//
3120 
3121     #[test]
test_connect_validation()3122     fn test_connect_validation() {
3123         let mut s = socket();
3124         assert_eq!(
3125             s.socket
3126                 .connect(&mut s.cx, REMOTE_END, (IpvXAddress::UNSPECIFIED, 0)),
3127             Err(ConnectError::Unaddressable)
3128         );
3129         assert_eq!(
3130             s.socket
3131                 .connect(&mut s.cx, REMOTE_END, (IpvXAddress::UNSPECIFIED, 1024)),
3132             Err(ConnectError::Unaddressable)
3133         );
3134         assert_eq!(
3135             s.socket
3136                 .connect(&mut s.cx, (IpvXAddress::UNSPECIFIED, 0), LOCAL_END),
3137             Err(ConnectError::Unaddressable)
3138         );
3139         s.socket
3140             .connect(&mut s.cx, REMOTE_END, LOCAL_END)
3141             .expect("Connect failed with valid parameters");
3142         assert_eq!(s.tuple, Some(TUPLE));
3143     }
3144 
3145     #[test]
test_connect()3146     fn test_connect() {
3147         let mut s = socket();
3148         s.local_seq_no = LOCAL_SEQ;
3149         s.socket
3150             .connect(&mut s.cx, REMOTE_END, LOCAL_END.port)
3151             .unwrap();
3152         assert_eq!(s.tuple, Some(TUPLE));
3153         recv!(
3154             s,
3155             [TcpRepr {
3156                 control: TcpControl::Syn,
3157                 seq_number: LOCAL_SEQ,
3158                 ack_number: None,
3159                 max_seg_size: Some(BASE_MSS),
3160                 window_scale: Some(0),
3161                 sack_permitted: true,
3162                 ..RECV_TEMPL
3163             }]
3164         );
3165         send!(
3166             s,
3167             TcpRepr {
3168                 control: TcpControl::Syn,
3169                 seq_number: REMOTE_SEQ,
3170                 ack_number: Some(LOCAL_SEQ + 1),
3171                 max_seg_size: Some(BASE_MSS - 80),
3172                 window_scale: Some(0),
3173                 ..SEND_TEMPL
3174             }
3175         );
3176         assert_eq!(s.tuple, Some(TUPLE));
3177     }
3178 
3179     #[test]
test_connect_unspecified_local()3180     fn test_connect_unspecified_local() {
3181         let mut s = socket();
3182         assert_eq!(s.socket.connect(&mut s.cx, REMOTE_END, 80), Ok(()));
3183     }
3184 
3185     #[test]
test_connect_specified_local()3186     fn test_connect_specified_local() {
3187         let mut s = socket();
3188         assert_eq!(
3189             s.socket.connect(&mut s.cx, REMOTE_END, (REMOTE_ADDR, 80)),
3190             Ok(())
3191         );
3192     }
3193 
3194     #[test]
test_connect_twice()3195     fn test_connect_twice() {
3196         let mut s = socket();
3197         assert_eq!(s.socket.connect(&mut s.cx, REMOTE_END, 80), Ok(()));
3198         assert_eq!(
3199             s.socket.connect(&mut s.cx, REMOTE_END, 80),
3200             Err(ConnectError::InvalidState)
3201         );
3202     }
3203 
3204     #[test]
test_syn_sent_sanity()3205     fn test_syn_sent_sanity() {
3206         let mut s = socket();
3207         s.local_seq_no = LOCAL_SEQ;
3208         s.socket.connect(&mut s.cx, REMOTE_END, LOCAL_END).unwrap();
3209         sanity!(s, socket_syn_sent());
3210     }
3211 
3212     #[test]
test_syn_sent_syn_ack()3213     fn test_syn_sent_syn_ack() {
3214         let mut s = socket_syn_sent();
3215         recv!(
3216             s,
3217             [TcpRepr {
3218                 control: TcpControl::Syn,
3219                 seq_number: LOCAL_SEQ,
3220                 ack_number: None,
3221                 max_seg_size: Some(BASE_MSS),
3222                 window_scale: Some(0),
3223                 sack_permitted: true,
3224                 ..RECV_TEMPL
3225             }]
3226         );
3227         send!(
3228             s,
3229             TcpRepr {
3230                 control: TcpControl::Syn,
3231                 seq_number: REMOTE_SEQ,
3232                 ack_number: Some(LOCAL_SEQ + 1),
3233                 max_seg_size: Some(BASE_MSS - 80),
3234                 window_scale: Some(0),
3235                 ..SEND_TEMPL
3236             }
3237         );
3238         recv!(
3239             s,
3240             [TcpRepr {
3241                 seq_number: LOCAL_SEQ + 1,
3242                 ack_number: Some(REMOTE_SEQ + 1),
3243                 ..RECV_TEMPL
3244             }]
3245         );
3246         recv_nothing!(s, time 1000);
3247         assert_eq!(s.state, State::Established);
3248         sanity!(s, socket_established());
3249     }
3250 
3251     #[test]
test_syn_sent_syn_ack_not_incremented()3252     fn test_syn_sent_syn_ack_not_incremented() {
3253         let mut s = socket_syn_sent();
3254         recv!(
3255             s,
3256             [TcpRepr {
3257                 control: TcpControl::Syn,
3258                 seq_number: LOCAL_SEQ,
3259                 ack_number: None,
3260                 max_seg_size: Some(BASE_MSS),
3261                 window_scale: Some(0),
3262                 sack_permitted: true,
3263                 ..RECV_TEMPL
3264             }]
3265         );
3266         send!(
3267             s,
3268             TcpRepr {
3269                 control: TcpControl::Syn,
3270                 seq_number: REMOTE_SEQ,
3271                 ack_number: Some(LOCAL_SEQ), // WRONG
3272                 max_seg_size: Some(BASE_MSS - 80),
3273                 window_scale: Some(0),
3274                 ..SEND_TEMPL
3275             },
3276             Some(TcpRepr {
3277                 control: TcpControl::Rst,
3278                 seq_number: LOCAL_SEQ,
3279                 ack_number: None,
3280                 window_len: 0,
3281                 ..RECV_TEMPL
3282             })
3283         );
3284         assert_eq!(s.state, State::SynSent);
3285     }
3286 
3287     #[test]
test_syn_sent_rst()3288     fn test_syn_sent_rst() {
3289         let mut s = socket_syn_sent();
3290         send!(
3291             s,
3292             TcpRepr {
3293                 control: TcpControl::Rst,
3294                 seq_number: REMOTE_SEQ,
3295                 ack_number: Some(LOCAL_SEQ + 1),
3296                 ..SEND_TEMPL
3297             }
3298         );
3299         assert_eq!(s.state, State::Closed);
3300     }
3301 
3302     #[test]
test_syn_sent_rst_no_ack()3303     fn test_syn_sent_rst_no_ack() {
3304         let mut s = socket_syn_sent();
3305         send!(
3306             s,
3307             TcpRepr {
3308                 control: TcpControl::Rst,
3309                 seq_number: REMOTE_SEQ,
3310                 ack_number: None,
3311                 ..SEND_TEMPL
3312             }
3313         );
3314         assert_eq!(s.state, State::SynSent);
3315     }
3316 
3317     #[test]
test_syn_sent_rst_bad_ack()3318     fn test_syn_sent_rst_bad_ack() {
3319         let mut s = socket_syn_sent();
3320         send!(
3321             s,
3322             TcpRepr {
3323                 control: TcpControl::Rst,
3324                 seq_number: REMOTE_SEQ,
3325                 ack_number: Some(TcpSeqNumber(1234)),
3326                 ..SEND_TEMPL
3327             }
3328         );
3329         assert_eq!(s.state, State::SynSent);
3330     }
3331 
3332     #[test]
test_syn_sent_bad_ack()3333     fn test_syn_sent_bad_ack() {
3334         let mut s = socket_syn_sent();
3335         recv!(
3336             s,
3337             [TcpRepr {
3338                 control: TcpControl::Syn,
3339                 seq_number: LOCAL_SEQ,
3340                 ack_number: None,
3341                 max_seg_size: Some(BASE_MSS),
3342                 window_scale: Some(0),
3343                 sack_permitted: true,
3344                 ..RECV_TEMPL
3345             }]
3346         );
3347         send!(
3348             s,
3349             TcpRepr {
3350                 control: TcpControl::None, // Unexpected
3351                 seq_number: REMOTE_SEQ,
3352                 ack_number: Some(LOCAL_SEQ + 1), // Correct
3353                 ..SEND_TEMPL
3354             }
3355         );
3356 
3357         // It should trigger no response and change no state
3358         recv!(s, []);
3359         assert_eq!(s.state, State::SynSent);
3360     }
3361 
3362     #[test]
test_syn_sent_bad_ack_seq_1()3363     fn test_syn_sent_bad_ack_seq_1() {
3364         let mut s = socket_syn_sent();
3365         recv!(
3366             s,
3367             [TcpRepr {
3368                 control: TcpControl::Syn,
3369                 seq_number: LOCAL_SEQ,
3370                 ack_number: None,
3371                 max_seg_size: Some(BASE_MSS),
3372                 window_scale: Some(0),
3373                 sack_permitted: true,
3374                 ..RECV_TEMPL
3375             }]
3376         );
3377         send!(
3378             s,
3379             TcpRepr {
3380                 control: TcpControl::None,
3381                 seq_number: REMOTE_SEQ,
3382                 ack_number: Some(LOCAL_SEQ), // WRONG
3383                 ..SEND_TEMPL
3384             },
3385             Some(TcpRepr {
3386                 control: TcpControl::Rst,
3387                 seq_number: LOCAL_SEQ, // matching the ack_number of the unexpected ack
3388                 ack_number: None,
3389                 window_len: 0,
3390                 ..RECV_TEMPL
3391             })
3392         );
3393 
3394         // It should trigger a RST, and change no state
3395         assert_eq!(s.state, State::SynSent);
3396     }
3397 
3398     #[test]
test_syn_sent_bad_ack_seq_2()3399     fn test_syn_sent_bad_ack_seq_2() {
3400         let mut s = socket_syn_sent();
3401         recv!(
3402             s,
3403             [TcpRepr {
3404                 control: TcpControl::Syn,
3405                 seq_number: LOCAL_SEQ,
3406                 ack_number: None,
3407                 max_seg_size: Some(BASE_MSS),
3408                 window_scale: Some(0),
3409                 sack_permitted: true,
3410                 ..RECV_TEMPL
3411             }]
3412         );
3413         send!(
3414             s,
3415             TcpRepr {
3416                 control: TcpControl::None,
3417                 seq_number: REMOTE_SEQ,
3418                 ack_number: Some(LOCAL_SEQ + 123456), // WRONG
3419                 ..SEND_TEMPL
3420             },
3421             Some(TcpRepr {
3422                 control: TcpControl::Rst,
3423                 seq_number: LOCAL_SEQ + 123456, // matching the ack_number of the unexpected ack
3424                 ack_number: None,
3425                 window_len: 0,
3426                 ..RECV_TEMPL
3427             })
3428         );
3429 
3430         // It should trigger a RST, and change no state
3431         assert_eq!(s.state, State::SynSent);
3432     }
3433 
3434     #[test]
test_syn_sent_close()3435     fn test_syn_sent_close() {
3436         let mut s = socket();
3437         s.close();
3438         assert_eq!(s.state, State::Closed);
3439     }
3440 
3441     #[test]
test_syn_sent_win_scale_buffers()3442     fn test_syn_sent_win_scale_buffers() {
3443         for (buffer_size, shift_amt) in &[
3444             (64, 0),
3445             (128, 0),
3446             (1024, 0),
3447             (65535, 0),
3448             (65536, 1),
3449             (65537, 1),
3450             (131071, 1),
3451             (131072, 2),
3452             (524287, 3),
3453             (524288, 4),
3454             (655350, 4),
3455             (1048576, 5),
3456         ] {
3457             let mut s = socket_with_buffer_sizes(64, *buffer_size);
3458             s.local_seq_no = LOCAL_SEQ;
3459             assert_eq!(s.remote_win_shift, *shift_amt);
3460             s.socket.connect(&mut s.cx, REMOTE_END, LOCAL_END).unwrap();
3461             recv!(
3462                 s,
3463                 [TcpRepr {
3464                     control: TcpControl::Syn,
3465                     seq_number: LOCAL_SEQ,
3466                     ack_number: None,
3467                     max_seg_size: Some(BASE_MSS),
3468                     window_scale: Some(*shift_amt),
3469                     window_len: cmp::min(*buffer_size, 65535) as u16,
3470                     sack_permitted: true,
3471                     ..RECV_TEMPL
3472                 }]
3473             );
3474         }
3475     }
3476 
3477     #[test]
test_syn_sent_syn_ack_no_window_scaling()3478     fn test_syn_sent_syn_ack_no_window_scaling() {
3479         let mut s = socket_syn_sent_with_buffer_sizes(1048576, 1048576);
3480         recv!(
3481             s,
3482             [TcpRepr {
3483                 control: TcpControl::Syn,
3484                 seq_number: LOCAL_SEQ,
3485                 ack_number: None,
3486                 max_seg_size: Some(BASE_MSS),
3487                 // scaling does NOT apply to the window value in SYN packets
3488                 window_len: 65535,
3489                 window_scale: Some(5),
3490                 sack_permitted: true,
3491                 ..RECV_TEMPL
3492             }]
3493         );
3494         assert_eq!(s.remote_win_shift, 5);
3495         send!(
3496             s,
3497             TcpRepr {
3498                 control: TcpControl::Syn,
3499                 seq_number: REMOTE_SEQ,
3500                 ack_number: Some(LOCAL_SEQ + 1),
3501                 max_seg_size: Some(BASE_MSS - 80),
3502                 window_scale: None,
3503                 window_len: 42,
3504                 ..SEND_TEMPL
3505             }
3506         );
3507         assert_eq!(s.state, State::Established);
3508         assert_eq!(s.remote_win_shift, 0);
3509         assert_eq!(s.remote_win_scale, None);
3510         assert_eq!(s.remote_win_len, 42);
3511     }
3512 
3513     #[test]
test_syn_sent_syn_ack_window_scaling()3514     fn test_syn_sent_syn_ack_window_scaling() {
3515         let mut s = socket_syn_sent();
3516         recv!(
3517             s,
3518             [TcpRepr {
3519                 control: TcpControl::Syn,
3520                 seq_number: LOCAL_SEQ,
3521                 ack_number: None,
3522                 max_seg_size: Some(BASE_MSS),
3523                 window_scale: Some(0),
3524                 sack_permitted: true,
3525                 ..RECV_TEMPL
3526             }]
3527         );
3528         send!(
3529             s,
3530             TcpRepr {
3531                 control: TcpControl::Syn,
3532                 seq_number: REMOTE_SEQ,
3533                 ack_number: Some(LOCAL_SEQ + 1),
3534                 max_seg_size: Some(BASE_MSS - 80),
3535                 window_scale: Some(7),
3536                 window_len: 42,
3537                 ..SEND_TEMPL
3538             }
3539         );
3540         assert_eq!(s.state, State::Established);
3541         assert_eq!(s.remote_win_scale, Some(7));
3542         // scaling does NOT apply to the window value in SYN packets
3543         assert_eq!(s.remote_win_len, 42);
3544     }
3545 
3546     // =========================================================================================//
3547     // Tests for the ESTABLISHED state.
3548     // =========================================================================================//
3549 
3550     #[test]
test_established_recv()3551     fn test_established_recv() {
3552         let mut s = socket_established();
3553         send!(
3554             s,
3555             TcpRepr {
3556                 seq_number: REMOTE_SEQ + 1,
3557                 ack_number: Some(LOCAL_SEQ + 1),
3558                 payload: &b"abcdef"[..],
3559                 ..SEND_TEMPL
3560             }
3561         );
3562         recv!(
3563             s,
3564             [TcpRepr {
3565                 seq_number: LOCAL_SEQ + 1,
3566                 ack_number: Some(REMOTE_SEQ + 1 + 6),
3567                 window_len: 58,
3568                 ..RECV_TEMPL
3569             }]
3570         );
3571         assert_eq!(s.rx_buffer.dequeue_many(6), &b"abcdef"[..]);
3572     }
3573 
setup_rfc2018_cases() -> (TestSocket, Vec<u8>)3574     fn setup_rfc2018_cases() -> (TestSocket, Vec<u8>) {
3575         // This is a utility function used by the tests for RFC 2018 cases. It configures a socket
3576         // in a particular way suitable for those cases.
3577         //
3578         // RFC 2018: Assume the left window edge is 5000 and that the data transmitter sends [...]
3579         // segments, each containing 500 data bytes.
3580         let mut s = socket_established_with_buffer_sizes(4000, 4000);
3581         s.remote_has_sack = true;
3582 
3583         // create a segment that is 500 bytes long
3584         let mut segment: Vec<u8> = Vec::with_capacity(500);
3585 
3586         // move the last ack to 5000 by sending ten of them
3587         for _ in 0..50 {
3588             segment.extend_from_slice(b"abcdefghij")
3589         }
3590         for offset in (0..5000).step_by(500) {
3591             send!(
3592                 s,
3593                 TcpRepr {
3594                     seq_number: REMOTE_SEQ + 1 + offset,
3595                     ack_number: Some(LOCAL_SEQ + 1),
3596                     payload: &segment,
3597                     ..SEND_TEMPL
3598                 }
3599             );
3600             recv!(
3601                 s,
3602                 [TcpRepr {
3603                     seq_number: LOCAL_SEQ + 1,
3604                     ack_number: Some(REMOTE_SEQ + 1 + offset + 500),
3605                     window_len: 3500,
3606                     ..RECV_TEMPL
3607                 }]
3608             );
3609             s.recv(|data| {
3610                 assert_eq!(data.len(), 500);
3611                 assert_eq!(data, segment.as_slice());
3612                 (500, ())
3613             })
3614             .unwrap();
3615         }
3616         assert_eq!(s.remote_last_win, 3500);
3617         (s, segment)
3618     }
3619 
3620     #[test]
test_established_rfc2018_cases()3621     fn test_established_rfc2018_cases() {
3622         // This test case verifies the exact scenarios described on pages 8-9 of RFC 2018. Please
3623         // ensure its behavior does not deviate from those scenarios.
3624 
3625         let (mut s, segment) = setup_rfc2018_cases();
3626         // RFC 2018:
3627         //
3628         // Case 2: The first segment is dropped but the remaining 7 are received.
3629         //
3630         // Upon receiving each of the last seven packets, the data receiver will return a TCP ACK
3631         // segment that acknowledges sequence number 5000 and contains a SACK option specifying one
3632         // block of queued data:
3633         //
3634         //   Triggering   ACK      Left Edge  Right Edge
3635         //   Segment
3636         //
3637         //   5000         (lost)
3638         //   5500         5000     5500       6000
3639         //   6000         5000     5500       6500
3640         //   6500         5000     5500       7000
3641         //   7000         5000     5500       7500
3642         //   7500         5000     5500       8000
3643         //   8000         5000     5500       8500
3644         //   8500         5000     5500       9000
3645         //
3646         for offset in (500..3500).step_by(500) {
3647             send!(
3648                 s,
3649                 TcpRepr {
3650                     seq_number: REMOTE_SEQ + 1 + offset + 5000,
3651                     ack_number: Some(LOCAL_SEQ + 1),
3652                     payload: &segment,
3653                     ..SEND_TEMPL
3654                 },
3655                 Some(TcpRepr {
3656                     seq_number: LOCAL_SEQ + 1,
3657                     ack_number: Some(REMOTE_SEQ + 1 + 5000),
3658                     window_len: 4000,
3659                     sack_ranges: [
3660                         Some((
3661                             REMOTE_SEQ.0 as u32 + 1 + 5500,
3662                             REMOTE_SEQ.0 as u32 + 1 + 5500 + offset as u32
3663                         )),
3664                         None,
3665                         None
3666                     ],
3667                     ..RECV_TEMPL
3668                 })
3669             );
3670         }
3671     }
3672 
3673     #[test]
test_established_sliding_window_recv()3674     fn test_established_sliding_window_recv() {
3675         let mut s = socket_established();
3676         // Update our scaling parameters for a TCP with a scaled buffer.
3677         assert_eq!(s.rx_buffer.len(), 0);
3678         s.rx_buffer = SocketBuffer::new(vec![0; 262143]);
3679         s.assembler = Assembler::new();
3680         s.remote_win_scale = Some(0);
3681         s.remote_last_win = 65535;
3682         s.remote_win_shift = 2;
3683 
3684         // Create a TCP segment that will mostly fill an IP frame.
3685         let mut segment: Vec<u8> = Vec::with_capacity(1400);
3686         for _ in 0..100 {
3687             segment.extend_from_slice(b"abcdefghijklmn")
3688         }
3689         assert_eq!(segment.len(), 1400);
3690 
3691         // Send the frame
3692         send!(
3693             s,
3694             TcpRepr {
3695                 seq_number: REMOTE_SEQ + 1,
3696                 ack_number: Some(LOCAL_SEQ + 1),
3697                 payload: &segment,
3698                 ..SEND_TEMPL
3699             }
3700         );
3701 
3702         // Ensure that the received window size is shifted right by 2.
3703         recv!(
3704             s,
3705             [TcpRepr {
3706                 seq_number: LOCAL_SEQ + 1,
3707                 ack_number: Some(REMOTE_SEQ + 1 + 1400),
3708                 window_len: 65185,
3709                 ..RECV_TEMPL
3710             }]
3711         );
3712     }
3713 
3714     #[test]
test_established_send()3715     fn test_established_send() {
3716         let mut s = socket_established();
3717         // First roundtrip after establishing.
3718         s.send_slice(b"abcdef").unwrap();
3719         recv!(
3720             s,
3721             [TcpRepr {
3722                 seq_number: LOCAL_SEQ + 1,
3723                 ack_number: Some(REMOTE_SEQ + 1),
3724                 payload: &b"abcdef"[..],
3725                 ..RECV_TEMPL
3726             }]
3727         );
3728         assert_eq!(s.tx_buffer.len(), 6);
3729         send!(
3730             s,
3731             TcpRepr {
3732                 seq_number: REMOTE_SEQ + 1,
3733                 ack_number: Some(LOCAL_SEQ + 1 + 6),
3734                 ..SEND_TEMPL
3735             }
3736         );
3737         assert_eq!(s.tx_buffer.len(), 0);
3738         // Second roundtrip.
3739         s.send_slice(b"foobar").unwrap();
3740         recv!(
3741             s,
3742             [TcpRepr {
3743                 seq_number: LOCAL_SEQ + 1 + 6,
3744                 ack_number: Some(REMOTE_SEQ + 1),
3745                 payload: &b"foobar"[..],
3746                 ..RECV_TEMPL
3747             }]
3748         );
3749         send!(
3750             s,
3751             TcpRepr {
3752                 seq_number: REMOTE_SEQ + 1,
3753                 ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
3754                 ..SEND_TEMPL
3755             }
3756         );
3757         assert_eq!(s.tx_buffer.len(), 0);
3758     }
3759 
3760     #[test]
test_established_send_no_ack_send()3761     fn test_established_send_no_ack_send() {
3762         let mut s = socket_established();
3763         s.set_nagle_enabled(false);
3764         s.send_slice(b"abcdef").unwrap();
3765         recv!(
3766             s,
3767             [TcpRepr {
3768                 seq_number: LOCAL_SEQ + 1,
3769                 ack_number: Some(REMOTE_SEQ + 1),
3770                 payload: &b"abcdef"[..],
3771                 ..RECV_TEMPL
3772             }]
3773         );
3774         s.send_slice(b"foobar").unwrap();
3775         recv!(
3776             s,
3777             [TcpRepr {
3778                 seq_number: LOCAL_SEQ + 1 + 6,
3779                 ack_number: Some(REMOTE_SEQ + 1),
3780                 payload: &b"foobar"[..],
3781                 ..RECV_TEMPL
3782             }]
3783         );
3784     }
3785 
3786     #[test]
test_established_send_buf_gt_win()3787     fn test_established_send_buf_gt_win() {
3788         let mut data = [0; 32];
3789         for (i, elem) in data.iter_mut().enumerate() {
3790             *elem = i as u8
3791         }
3792 
3793         let mut s = socket_established();
3794         s.remote_win_len = 16;
3795         s.send_slice(&data[..]).unwrap();
3796         recv!(
3797             s,
3798             [TcpRepr {
3799                 seq_number: LOCAL_SEQ + 1,
3800                 ack_number: Some(REMOTE_SEQ + 1),
3801                 payload: &data[0..16],
3802                 ..RECV_TEMPL
3803             }]
3804         );
3805     }
3806 
3807     #[test]
test_established_send_window_shrink()3808     fn test_established_send_window_shrink() {
3809         let mut s = socket_established();
3810 
3811         // 6 octets fit on the remote side's window, so we send them.
3812         s.send_slice(b"abcdef").unwrap();
3813         recv!(
3814             s,
3815             [TcpRepr {
3816                 seq_number: LOCAL_SEQ + 1,
3817                 ack_number: Some(REMOTE_SEQ + 1),
3818                 payload: &b"abcdef"[..],
3819                 ..RECV_TEMPL
3820             }]
3821         );
3822         assert_eq!(s.tx_buffer.len(), 6);
3823 
3824         println!(
3825             "local_seq_no={} remote_win_len={} remote_last_seq={}",
3826             s.local_seq_no, s.remote_win_len, s.remote_last_seq
3827         );
3828 
3829         // - Peer doesn't ack them yet
3830         // - Sends data so we need to reply with an ACK
3831         // - ...AND and sends a window announcement that SHRINKS the window, so data we've
3832         //   previously sent is now outside the window. Yes, this is allowed by TCP.
3833         send!(
3834             s,
3835             TcpRepr {
3836                 seq_number: REMOTE_SEQ + 1,
3837                 ack_number: Some(LOCAL_SEQ + 1),
3838                 window_len: 3,
3839                 payload: &b"xyzxyz"[..],
3840                 ..SEND_TEMPL
3841             }
3842         );
3843         assert_eq!(s.tx_buffer.len(), 6);
3844 
3845         println!(
3846             "local_seq_no={} remote_win_len={} remote_last_seq={}",
3847             s.local_seq_no, s.remote_win_len, s.remote_last_seq
3848         );
3849 
3850         // More data should not get sent since it doesn't fit in the window
3851         s.send_slice(b"foobar").unwrap();
3852         recv!(
3853             s,
3854             [TcpRepr {
3855                 seq_number: LOCAL_SEQ + 1 + 6,
3856                 ack_number: Some(REMOTE_SEQ + 1 + 6),
3857                 window_len: 64 - 6,
3858                 ..RECV_TEMPL
3859             }]
3860         );
3861     }
3862 
3863     #[test]
test_established_send_wrap()3864     fn test_established_send_wrap() {
3865         let mut s = socket_established();
3866         let local_seq_start = TcpSeqNumber(i32::MAX - 1);
3867         s.local_seq_no = local_seq_start + 1;
3868         s.remote_last_seq = local_seq_start + 1;
3869         s.send_slice(b"abc").unwrap();
3870         recv!(s, time 1000, Ok(TcpRepr {
3871             seq_number: local_seq_start + 1,
3872             ack_number: Some(REMOTE_SEQ + 1),
3873             payload:    &b"abc"[..],
3874             ..RECV_TEMPL
3875         }));
3876     }
3877 
3878     #[test]
test_established_no_ack()3879     fn test_established_no_ack() {
3880         let mut s = socket_established();
3881         send!(
3882             s,
3883             TcpRepr {
3884                 seq_number: REMOTE_SEQ + 1,
3885                 ack_number: None,
3886                 ..SEND_TEMPL
3887             }
3888         );
3889     }
3890 
3891     #[test]
test_established_bad_ack()3892     fn test_established_bad_ack() {
3893         let mut s = socket_established();
3894         // Already acknowledged data.
3895         send!(
3896             s,
3897             TcpRepr {
3898                 seq_number: REMOTE_SEQ + 1,
3899                 ack_number: Some(TcpSeqNumber(LOCAL_SEQ.0 - 1)),
3900                 ..SEND_TEMPL
3901             }
3902         );
3903         assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
3904         // Data not yet transmitted.
3905         send!(
3906             s,
3907             TcpRepr {
3908                 seq_number: REMOTE_SEQ + 1,
3909                 ack_number: Some(LOCAL_SEQ + 10),
3910                 ..SEND_TEMPL
3911             },
3912             Some(TcpRepr {
3913                 seq_number: LOCAL_SEQ + 1,
3914                 ack_number: Some(REMOTE_SEQ + 1),
3915                 ..RECV_TEMPL
3916             })
3917         );
3918         assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
3919     }
3920 
3921     #[test]
test_established_bad_seq()3922     fn test_established_bad_seq() {
3923         let mut s = socket_established();
3924         // Data outside of receive window.
3925         send!(
3926             s,
3927             TcpRepr {
3928                 seq_number: REMOTE_SEQ + 1 + 256,
3929                 ack_number: Some(LOCAL_SEQ + 1),
3930                 ..SEND_TEMPL
3931             },
3932             Some(TcpRepr {
3933                 seq_number: LOCAL_SEQ + 1,
3934                 ack_number: Some(REMOTE_SEQ + 1),
3935                 ..RECV_TEMPL
3936             })
3937         );
3938         assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
3939 
3940         // Challenge ACKs are rate-limited, we don't get a second one immediately.
3941         send!(
3942             s,
3943             time 100,
3944             TcpRepr {
3945                 seq_number: REMOTE_SEQ + 1 + 256,
3946                 ack_number: Some(LOCAL_SEQ + 1),
3947                 ..SEND_TEMPL
3948             }
3949         );
3950 
3951         // If we wait a bit, we do get a new one.
3952         send!(
3953             s,
3954             time 2000,
3955             TcpRepr {
3956                 seq_number: REMOTE_SEQ + 1 + 256,
3957                 ack_number: Some(LOCAL_SEQ + 1),
3958                 ..SEND_TEMPL
3959             },
3960             Some(TcpRepr {
3961                 seq_number: LOCAL_SEQ + 1,
3962                 ack_number: Some(REMOTE_SEQ + 1),
3963                 ..RECV_TEMPL
3964             })
3965         );
3966         assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
3967     }
3968 
3969     #[test]
test_established_fin()3970     fn test_established_fin() {
3971         let mut s = socket_established();
3972         send!(
3973             s,
3974             TcpRepr {
3975                 control: TcpControl::Fin,
3976                 seq_number: REMOTE_SEQ + 1,
3977                 ack_number: Some(LOCAL_SEQ + 1),
3978                 ..SEND_TEMPL
3979             }
3980         );
3981         recv!(
3982             s,
3983             [TcpRepr {
3984                 seq_number: LOCAL_SEQ + 1,
3985                 ack_number: Some(REMOTE_SEQ + 1 + 1),
3986                 ..RECV_TEMPL
3987             }]
3988         );
3989         assert_eq!(s.state, State::CloseWait);
3990         sanity!(s, socket_close_wait());
3991     }
3992 
3993     #[test]
test_established_fin_after_missing()3994     fn test_established_fin_after_missing() {
3995         let mut s = socket_established();
3996         send!(
3997             s,
3998             TcpRepr {
3999                 control: TcpControl::Fin,
4000                 seq_number: REMOTE_SEQ + 1 + 6,
4001                 ack_number: Some(LOCAL_SEQ + 1),
4002                 payload: &b"123456"[..],
4003                 ..SEND_TEMPL
4004             },
4005             Some(TcpRepr {
4006                 seq_number: LOCAL_SEQ + 1,
4007                 ack_number: Some(REMOTE_SEQ + 1),
4008                 ..RECV_TEMPL
4009             })
4010         );
4011         assert_eq!(s.state, State::Established);
4012         send!(
4013             s,
4014             TcpRepr {
4015                 seq_number: REMOTE_SEQ + 1,
4016                 ack_number: Some(LOCAL_SEQ + 1),
4017                 payload: &b"abcdef"[..],
4018                 ..SEND_TEMPL
4019             },
4020             Some(TcpRepr {
4021                 seq_number: LOCAL_SEQ + 1,
4022                 ack_number: Some(REMOTE_SEQ + 1 + 6 + 6),
4023                 window_len: 52,
4024                 ..RECV_TEMPL
4025             })
4026         );
4027         assert_eq!(s.state, State::Established);
4028     }
4029 
4030     #[test]
test_established_send_fin()4031     fn test_established_send_fin() {
4032         let mut s = socket_established();
4033         s.send_slice(b"abcdef").unwrap();
4034         send!(
4035             s,
4036             TcpRepr {
4037                 control: TcpControl::Fin,
4038                 seq_number: REMOTE_SEQ + 1,
4039                 ack_number: Some(LOCAL_SEQ + 1),
4040                 ..SEND_TEMPL
4041             }
4042         );
4043         assert_eq!(s.state, State::CloseWait);
4044         recv!(
4045             s,
4046             [TcpRepr {
4047                 seq_number: LOCAL_SEQ + 1,
4048                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4049                 payload: &b"abcdef"[..],
4050                 ..RECV_TEMPL
4051             }]
4052         );
4053     }
4054 
4055     #[test]
test_established_rst()4056     fn test_established_rst() {
4057         let mut s = socket_established();
4058         send!(
4059             s,
4060             TcpRepr {
4061                 control: TcpControl::Rst,
4062                 seq_number: REMOTE_SEQ + 1,
4063                 ack_number: Some(LOCAL_SEQ + 1),
4064                 ..SEND_TEMPL
4065             }
4066         );
4067         assert_eq!(s.state, State::Closed);
4068     }
4069 
4070     #[test]
test_established_rst_no_ack()4071     fn test_established_rst_no_ack() {
4072         let mut s = socket_established();
4073         send!(
4074             s,
4075             TcpRepr {
4076                 control: TcpControl::Rst,
4077                 seq_number: REMOTE_SEQ + 1,
4078                 ack_number: None,
4079                 ..SEND_TEMPL
4080             }
4081         );
4082         assert_eq!(s.state, State::Closed);
4083     }
4084 
4085     #[test]
test_established_close()4086     fn test_established_close() {
4087         let mut s = socket_established();
4088         s.close();
4089         assert_eq!(s.state, State::FinWait1);
4090         sanity!(s, socket_fin_wait_1());
4091     }
4092 
4093     #[test]
test_established_abort()4094     fn test_established_abort() {
4095         let mut s = socket_established();
4096         s.abort();
4097         assert_eq!(s.state, State::Closed);
4098         recv!(
4099             s,
4100             [TcpRepr {
4101                 control: TcpControl::Rst,
4102                 seq_number: LOCAL_SEQ + 1,
4103                 ack_number: Some(REMOTE_SEQ + 1),
4104                 ..RECV_TEMPL
4105             }]
4106         );
4107     }
4108 
4109     #[test]
test_established_rst_bad_seq()4110     fn test_established_rst_bad_seq() {
4111         let mut s = socket_established();
4112         send!(
4113             s,
4114             TcpRepr {
4115                 control: TcpControl::Rst,
4116                 seq_number: REMOTE_SEQ, // Wrong seq
4117                 ack_number: None,
4118                 ..SEND_TEMPL
4119             },
4120             Some(TcpRepr {
4121                 seq_number: LOCAL_SEQ + 1,
4122                 ack_number: Some(REMOTE_SEQ + 1),
4123                 ..RECV_TEMPL
4124             })
4125         );
4126 
4127         assert_eq!(s.state, State::Established);
4128 
4129         // Send something to advance seq by 1
4130         send!(
4131             s,
4132             TcpRepr {
4133                 seq_number: REMOTE_SEQ + 1, // correct seq
4134                 ack_number: Some(LOCAL_SEQ + 1),
4135                 payload: &b"a"[..],
4136                 ..SEND_TEMPL
4137             }
4138         );
4139 
4140         // Send wrong rst again, check that the challenge ack is correctly updated
4141         // The ack number must be updated even if we don't call dispatch on the socket
4142         // See https://github.com/smoltcp-rs/smoltcp/issues/338
4143         send!(
4144             s,
4145             time 2000,
4146             TcpRepr {
4147                 control: TcpControl::Rst,
4148                 seq_number: REMOTE_SEQ, // Wrong seq
4149                 ack_number: None,
4150                 ..SEND_TEMPL
4151             },
4152             Some(TcpRepr {
4153                 seq_number: LOCAL_SEQ + 1,
4154                 ack_number: Some(REMOTE_SEQ + 2), // this has changed
4155                 window_len: 63,
4156                 ..RECV_TEMPL
4157             })
4158         );
4159     }
4160 
4161     // =========================================================================================//
4162     // Tests for the FIN-WAIT-1 state.
4163     // =========================================================================================//
4164 
4165     #[test]
test_fin_wait_1_fin_ack()4166     fn test_fin_wait_1_fin_ack() {
4167         let mut s = socket_fin_wait_1();
4168         recv!(
4169             s,
4170             [TcpRepr {
4171                 control: TcpControl::Fin,
4172                 seq_number: LOCAL_SEQ + 1,
4173                 ack_number: Some(REMOTE_SEQ + 1),
4174                 ..RECV_TEMPL
4175             }]
4176         );
4177         send!(
4178             s,
4179             TcpRepr {
4180                 seq_number: REMOTE_SEQ + 1,
4181                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4182                 ..SEND_TEMPL
4183             }
4184         );
4185         assert_eq!(s.state, State::FinWait2);
4186         sanity!(s, socket_fin_wait_2());
4187     }
4188 
4189     #[test]
test_fin_wait_1_fin_fin()4190     fn test_fin_wait_1_fin_fin() {
4191         let mut s = socket_fin_wait_1();
4192         recv!(
4193             s,
4194             [TcpRepr {
4195                 control: TcpControl::Fin,
4196                 seq_number: LOCAL_SEQ + 1,
4197                 ack_number: Some(REMOTE_SEQ + 1),
4198                 ..RECV_TEMPL
4199             }]
4200         );
4201         send!(
4202             s,
4203             TcpRepr {
4204                 control: TcpControl::Fin,
4205                 seq_number: REMOTE_SEQ + 1,
4206                 ack_number: Some(LOCAL_SEQ + 1),
4207                 ..SEND_TEMPL
4208             }
4209         );
4210         assert_eq!(s.state, State::Closing);
4211         sanity!(s, socket_closing());
4212     }
4213 
4214     #[test]
test_fin_wait_1_fin_with_data_queued()4215     fn test_fin_wait_1_fin_with_data_queued() {
4216         let mut s = socket_established();
4217         s.remote_win_len = 6;
4218         s.send_slice(b"abcdef123456").unwrap();
4219         s.close();
4220         recv!(
4221             s,
4222             Ok(TcpRepr {
4223                 seq_number: LOCAL_SEQ + 1,
4224                 ack_number: Some(REMOTE_SEQ + 1),
4225                 payload: &b"abcdef"[..],
4226                 ..RECV_TEMPL
4227             })
4228         );
4229         send!(
4230             s,
4231             TcpRepr {
4232                 seq_number: REMOTE_SEQ + 1,
4233                 ack_number: Some(LOCAL_SEQ + 1 + 6),
4234                 ..SEND_TEMPL
4235             }
4236         );
4237         assert_eq!(s.state, State::FinWait1);
4238     }
4239 
4240     #[test]
test_fin_wait_1_recv()4241     fn test_fin_wait_1_recv() {
4242         let mut s = socket_fin_wait_1();
4243         send!(
4244             s,
4245             TcpRepr {
4246                 seq_number: REMOTE_SEQ + 1,
4247                 ack_number: Some(LOCAL_SEQ + 1),
4248                 payload: &b"abc"[..],
4249                 ..SEND_TEMPL
4250             }
4251         );
4252         assert_eq!(s.state, State::FinWait1);
4253         s.recv(|data| {
4254             assert_eq!(data, b"abc");
4255             (3, ())
4256         })
4257         .unwrap();
4258     }
4259 
4260     #[test]
test_fin_wait_1_close()4261     fn test_fin_wait_1_close() {
4262         let mut s = socket_fin_wait_1();
4263         s.close();
4264         assert_eq!(s.state, State::FinWait1);
4265     }
4266 
4267     // =========================================================================================//
4268     // Tests for the FIN-WAIT-2 state.
4269     // =========================================================================================//
4270 
4271     #[test]
test_fin_wait_2_fin()4272     fn test_fin_wait_2_fin() {
4273         let mut s = socket_fin_wait_2();
4274         send!(s, time 1_000, TcpRepr {
4275             control: TcpControl::Fin,
4276             seq_number: REMOTE_SEQ + 1,
4277             ack_number: Some(LOCAL_SEQ + 1 + 1),
4278             ..SEND_TEMPL
4279         });
4280         assert_eq!(s.state, State::TimeWait);
4281         sanity!(s, socket_time_wait(false));
4282     }
4283 
4284     #[test]
test_fin_wait_2_recv()4285     fn test_fin_wait_2_recv() {
4286         let mut s = socket_fin_wait_2();
4287         send!(
4288             s,
4289             TcpRepr {
4290                 seq_number: REMOTE_SEQ + 1,
4291                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4292                 payload: &b"abc"[..],
4293                 ..SEND_TEMPL
4294             }
4295         );
4296         assert_eq!(s.state, State::FinWait2);
4297         s.recv(|data| {
4298             assert_eq!(data, b"abc");
4299             (3, ())
4300         })
4301         .unwrap();
4302         recv!(
4303             s,
4304             [TcpRepr {
4305                 seq_number: LOCAL_SEQ + 1 + 1,
4306                 ack_number: Some(REMOTE_SEQ + 1 + 3),
4307                 ..RECV_TEMPL
4308             }]
4309         );
4310     }
4311 
4312     #[test]
test_fin_wait_2_close()4313     fn test_fin_wait_2_close() {
4314         let mut s = socket_fin_wait_2();
4315         s.close();
4316         assert_eq!(s.state, State::FinWait2);
4317     }
4318 
4319     // =========================================================================================//
4320     // Tests for the CLOSING state.
4321     // =========================================================================================//
4322 
4323     #[test]
test_closing_ack_fin()4324     fn test_closing_ack_fin() {
4325         let mut s = socket_closing();
4326         recv!(
4327             s,
4328             [TcpRepr {
4329                 seq_number: LOCAL_SEQ + 1 + 1,
4330                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4331                 ..RECV_TEMPL
4332             }]
4333         );
4334         send!(s, time 1_000, TcpRepr {
4335             seq_number: REMOTE_SEQ + 1 + 1,
4336             ack_number: Some(LOCAL_SEQ + 1 + 1),
4337             ..SEND_TEMPL
4338         });
4339         assert_eq!(s.state, State::TimeWait);
4340         sanity!(s, socket_time_wait(true));
4341     }
4342 
4343     #[test]
test_closing_close()4344     fn test_closing_close() {
4345         let mut s = socket_closing();
4346         s.close();
4347         assert_eq!(s.state, State::Closing);
4348     }
4349 
4350     // =========================================================================================//
4351     // Tests for the TIME-WAIT state.
4352     // =========================================================================================//
4353 
4354     #[test]
test_time_wait_from_fin_wait_2_ack()4355     fn test_time_wait_from_fin_wait_2_ack() {
4356         let mut s = socket_time_wait(false);
4357         recv!(
4358             s,
4359             [TcpRepr {
4360                 seq_number: LOCAL_SEQ + 1 + 1,
4361                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4362                 ..RECV_TEMPL
4363             }]
4364         );
4365     }
4366 
4367     #[test]
test_time_wait_from_closing_no_ack()4368     fn test_time_wait_from_closing_no_ack() {
4369         let mut s = socket_time_wait(true);
4370         recv!(s, []);
4371     }
4372 
4373     #[test]
test_time_wait_close()4374     fn test_time_wait_close() {
4375         let mut s = socket_time_wait(false);
4376         s.close();
4377         assert_eq!(s.state, State::TimeWait);
4378     }
4379 
4380     #[test]
test_time_wait_retransmit()4381     fn test_time_wait_retransmit() {
4382         let mut s = socket_time_wait(false);
4383         recv!(
4384             s,
4385             [TcpRepr {
4386                 seq_number: LOCAL_SEQ + 1 + 1,
4387                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4388                 ..RECV_TEMPL
4389             }]
4390         );
4391         send!(s, time 5_000, TcpRepr {
4392             control: TcpControl::Fin,
4393             seq_number: REMOTE_SEQ + 1,
4394             ack_number: Some(LOCAL_SEQ + 1 + 1),
4395             ..SEND_TEMPL
4396         }, Some(TcpRepr {
4397             seq_number: LOCAL_SEQ + 1 + 1,
4398             ack_number: Some(REMOTE_SEQ + 1 + 1),
4399             ..RECV_TEMPL
4400         }));
4401         assert_eq!(
4402             s.timer,
4403             Timer::Close {
4404                 expires_at: Instant::from_secs(5) + CLOSE_DELAY
4405             }
4406         );
4407     }
4408 
4409     #[test]
test_time_wait_timeout()4410     fn test_time_wait_timeout() {
4411         let mut s = socket_time_wait(false);
4412         recv!(
4413             s,
4414             [TcpRepr {
4415                 seq_number: LOCAL_SEQ + 1 + 1,
4416                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4417                 ..RECV_TEMPL
4418             }]
4419         );
4420         assert_eq!(s.state, State::TimeWait);
4421         recv_nothing!(s, time 60_000);
4422         assert_eq!(s.state, State::Closed);
4423     }
4424 
4425     // =========================================================================================//
4426     // Tests for the CLOSE-WAIT state.
4427     // =========================================================================================//
4428 
4429     #[test]
test_close_wait_ack()4430     fn test_close_wait_ack() {
4431         let mut s = socket_close_wait();
4432         s.send_slice(b"abcdef").unwrap();
4433         recv!(
4434             s,
4435             [TcpRepr {
4436                 seq_number: LOCAL_SEQ + 1,
4437                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4438                 payload: &b"abcdef"[..],
4439                 ..RECV_TEMPL
4440             }]
4441         );
4442         send!(
4443             s,
4444             TcpRepr {
4445                 seq_number: REMOTE_SEQ + 1 + 1,
4446                 ack_number: Some(LOCAL_SEQ + 1 + 6),
4447                 ..SEND_TEMPL
4448             }
4449         );
4450     }
4451 
4452     #[test]
test_close_wait_close()4453     fn test_close_wait_close() {
4454         let mut s = socket_close_wait();
4455         s.close();
4456         assert_eq!(s.state, State::LastAck);
4457         sanity!(s, socket_last_ack());
4458     }
4459 
4460     // =========================================================================================//
4461     // Tests for the LAST-ACK state.
4462     // =========================================================================================//
4463     #[test]
test_last_ack_fin_ack()4464     fn test_last_ack_fin_ack() {
4465         let mut s = socket_last_ack();
4466         recv!(
4467             s,
4468             [TcpRepr {
4469                 control: TcpControl::Fin,
4470                 seq_number: LOCAL_SEQ + 1,
4471                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4472                 ..RECV_TEMPL
4473             }]
4474         );
4475         assert_eq!(s.state, State::LastAck);
4476         send!(
4477             s,
4478             TcpRepr {
4479                 seq_number: REMOTE_SEQ + 1 + 1,
4480                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4481                 ..SEND_TEMPL
4482             }
4483         );
4484         assert_eq!(s.state, State::Closed);
4485     }
4486 
4487     #[test]
test_last_ack_ack_not_of_fin()4488     fn test_last_ack_ack_not_of_fin() {
4489         let mut s = socket_last_ack();
4490         recv!(
4491             s,
4492             [TcpRepr {
4493                 control: TcpControl::Fin,
4494                 seq_number: LOCAL_SEQ + 1,
4495                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4496                 ..RECV_TEMPL
4497             }]
4498         );
4499         assert_eq!(s.state, State::LastAck);
4500 
4501         // ACK received that doesn't ack the FIN: socket should stay in LastAck.
4502         send!(
4503             s,
4504             TcpRepr {
4505                 seq_number: REMOTE_SEQ + 1 + 1,
4506                 ack_number: Some(LOCAL_SEQ + 1),
4507                 ..SEND_TEMPL
4508             }
4509         );
4510         assert_eq!(s.state, State::LastAck);
4511 
4512         // ACK received of fin: socket should change to Closed.
4513         send!(
4514             s,
4515             TcpRepr {
4516                 seq_number: REMOTE_SEQ + 1 + 1,
4517                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4518                 ..SEND_TEMPL
4519             }
4520         );
4521         assert_eq!(s.state, State::Closed);
4522     }
4523 
4524     #[test]
test_last_ack_close()4525     fn test_last_ack_close() {
4526         let mut s = socket_last_ack();
4527         s.close();
4528         assert_eq!(s.state, State::LastAck);
4529     }
4530 
4531     // =========================================================================================//
4532     // Tests for transitioning through multiple states.
4533     // =========================================================================================//
4534 
4535     #[test]
test_listen()4536     fn test_listen() {
4537         let mut s = socket();
4538         s.listen(LISTEN_END).unwrap();
4539         assert_eq!(s.state, State::Listen);
4540     }
4541 
4542     #[test]
test_three_way_handshake()4543     fn test_three_way_handshake() {
4544         let mut s = socket_listen();
4545         send!(
4546             s,
4547             TcpRepr {
4548                 control: TcpControl::Syn,
4549                 seq_number: REMOTE_SEQ,
4550                 ack_number: None,
4551                 ..SEND_TEMPL
4552             }
4553         );
4554         assert_eq!(s.state(), State::SynReceived);
4555         assert_eq!(s.tuple, Some(TUPLE));
4556         recv!(
4557             s,
4558             [TcpRepr {
4559                 control: TcpControl::Syn,
4560                 seq_number: LOCAL_SEQ,
4561                 ack_number: Some(REMOTE_SEQ + 1),
4562                 max_seg_size: Some(BASE_MSS),
4563                 ..RECV_TEMPL
4564             }]
4565         );
4566         send!(
4567             s,
4568             TcpRepr {
4569                 seq_number: REMOTE_SEQ + 1,
4570                 ack_number: Some(LOCAL_SEQ + 1),
4571                 ..SEND_TEMPL
4572             }
4573         );
4574         assert_eq!(s.state(), State::Established);
4575         assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
4576         assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
4577     }
4578 
4579     #[test]
test_remote_close()4580     fn test_remote_close() {
4581         let mut s = socket_established();
4582         send!(
4583             s,
4584             TcpRepr {
4585                 control: TcpControl::Fin,
4586                 seq_number: REMOTE_SEQ + 1,
4587                 ack_number: Some(LOCAL_SEQ + 1),
4588                 ..SEND_TEMPL
4589             }
4590         );
4591         assert_eq!(s.state, State::CloseWait);
4592         recv!(
4593             s,
4594             [TcpRepr {
4595                 seq_number: LOCAL_SEQ + 1,
4596                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4597                 ..RECV_TEMPL
4598             }]
4599         );
4600         s.close();
4601         assert_eq!(s.state, State::LastAck);
4602         recv!(
4603             s,
4604             [TcpRepr {
4605                 control: TcpControl::Fin,
4606                 seq_number: LOCAL_SEQ + 1,
4607                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4608                 ..RECV_TEMPL
4609             }]
4610         );
4611         send!(
4612             s,
4613             TcpRepr {
4614                 seq_number: REMOTE_SEQ + 1 + 1,
4615                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4616                 ..SEND_TEMPL
4617             }
4618         );
4619         assert_eq!(s.state, State::Closed);
4620     }
4621 
4622     #[test]
test_local_close()4623     fn test_local_close() {
4624         let mut s = socket_established();
4625         s.close();
4626         assert_eq!(s.state, State::FinWait1);
4627         recv!(
4628             s,
4629             [TcpRepr {
4630                 control: TcpControl::Fin,
4631                 seq_number: LOCAL_SEQ + 1,
4632                 ack_number: Some(REMOTE_SEQ + 1),
4633                 ..RECV_TEMPL
4634             }]
4635         );
4636         send!(
4637             s,
4638             TcpRepr {
4639                 seq_number: REMOTE_SEQ + 1,
4640                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4641                 ..SEND_TEMPL
4642             }
4643         );
4644         assert_eq!(s.state, State::FinWait2);
4645         send!(
4646             s,
4647             TcpRepr {
4648                 control: TcpControl::Fin,
4649                 seq_number: REMOTE_SEQ + 1,
4650                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4651                 ..SEND_TEMPL
4652             }
4653         );
4654         assert_eq!(s.state, State::TimeWait);
4655         recv!(
4656             s,
4657             [TcpRepr {
4658                 seq_number: LOCAL_SEQ + 1 + 1,
4659                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4660                 ..RECV_TEMPL
4661             }]
4662         );
4663     }
4664 
4665     #[test]
test_simultaneous_close()4666     fn test_simultaneous_close() {
4667         let mut s = socket_established();
4668         s.close();
4669         assert_eq!(s.state, State::FinWait1);
4670         recv!(
4671             s,
4672             [TcpRepr {
4673                 // due to reordering, this is logically located...
4674                 control: TcpControl::Fin,
4675                 seq_number: LOCAL_SEQ + 1,
4676                 ack_number: Some(REMOTE_SEQ + 1),
4677                 ..RECV_TEMPL
4678             }]
4679         );
4680         send!(
4681             s,
4682             TcpRepr {
4683                 control: TcpControl::Fin,
4684                 seq_number: REMOTE_SEQ + 1,
4685                 ack_number: Some(LOCAL_SEQ + 1),
4686                 ..SEND_TEMPL
4687             }
4688         );
4689         assert_eq!(s.state, State::Closing);
4690         recv!(
4691             s,
4692             [TcpRepr {
4693                 seq_number: LOCAL_SEQ + 1 + 1,
4694                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4695                 ..RECV_TEMPL
4696             }]
4697         );
4698         // ... at this point
4699         send!(
4700             s,
4701             TcpRepr {
4702                 seq_number: REMOTE_SEQ + 1 + 1,
4703                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4704                 ..SEND_TEMPL
4705             }
4706         );
4707         assert_eq!(s.state, State::TimeWait);
4708         recv!(s, []);
4709     }
4710 
4711     #[test]
test_simultaneous_close_combined_fin_ack()4712     fn test_simultaneous_close_combined_fin_ack() {
4713         let mut s = socket_established();
4714         s.close();
4715         assert_eq!(s.state, State::FinWait1);
4716         recv!(
4717             s,
4718             [TcpRepr {
4719                 control: TcpControl::Fin,
4720                 seq_number: LOCAL_SEQ + 1,
4721                 ack_number: Some(REMOTE_SEQ + 1),
4722                 ..RECV_TEMPL
4723             }]
4724         );
4725         send!(
4726             s,
4727             TcpRepr {
4728                 control: TcpControl::Fin,
4729                 seq_number: REMOTE_SEQ + 1,
4730                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4731                 ..SEND_TEMPL
4732             }
4733         );
4734         assert_eq!(s.state, State::TimeWait);
4735         recv!(
4736             s,
4737             [TcpRepr {
4738                 seq_number: LOCAL_SEQ + 1 + 1,
4739                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4740                 ..RECV_TEMPL
4741             }]
4742         );
4743     }
4744 
4745     #[test]
test_simultaneous_close_raced()4746     fn test_simultaneous_close_raced() {
4747         let mut s = socket_established();
4748         s.close();
4749         assert_eq!(s.state, State::FinWait1);
4750 
4751         // Socket receives FIN before it has a chance to send its own FIN
4752         send!(
4753             s,
4754             TcpRepr {
4755                 control: TcpControl::Fin,
4756                 seq_number: REMOTE_SEQ + 1,
4757                 ack_number: Some(LOCAL_SEQ + 1),
4758                 ..SEND_TEMPL
4759             }
4760         );
4761         assert_eq!(s.state, State::Closing);
4762 
4763         // FIN + ack-of-FIN
4764         recv!(
4765             s,
4766             [TcpRepr {
4767                 control: TcpControl::Fin,
4768                 seq_number: LOCAL_SEQ + 1,
4769                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4770                 ..RECV_TEMPL
4771             }]
4772         );
4773         assert_eq!(s.state, State::Closing);
4774 
4775         send!(
4776             s,
4777             TcpRepr {
4778                 seq_number: REMOTE_SEQ + 1 + 1,
4779                 ack_number: Some(LOCAL_SEQ + 1 + 1),
4780                 ..SEND_TEMPL
4781             }
4782         );
4783         assert_eq!(s.state, State::TimeWait);
4784         recv!(s, []);
4785     }
4786 
4787     #[test]
test_simultaneous_close_raced_with_data()4788     fn test_simultaneous_close_raced_with_data() {
4789         let mut s = socket_established();
4790         s.send_slice(b"abcdef").unwrap();
4791         s.close();
4792         assert_eq!(s.state, State::FinWait1);
4793 
4794         // Socket receives FIN before it has a chance to send its own data+FIN
4795         send!(
4796             s,
4797             TcpRepr {
4798                 control: TcpControl::Fin,
4799                 seq_number: REMOTE_SEQ + 1,
4800                 ack_number: Some(LOCAL_SEQ + 1),
4801                 ..SEND_TEMPL
4802             }
4803         );
4804         assert_eq!(s.state, State::Closing);
4805 
4806         // data + FIN + ack-of-FIN
4807         recv!(
4808             s,
4809             [TcpRepr {
4810                 control: TcpControl::Fin,
4811                 seq_number: LOCAL_SEQ + 1,
4812                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4813                 payload: &b"abcdef"[..],
4814                 ..RECV_TEMPL
4815             }]
4816         );
4817         assert_eq!(s.state, State::Closing);
4818 
4819         send!(
4820             s,
4821             TcpRepr {
4822                 seq_number: REMOTE_SEQ + 1 + 1,
4823                 ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
4824                 ..SEND_TEMPL
4825             }
4826         );
4827         assert_eq!(s.state, State::TimeWait);
4828         recv!(s, []);
4829     }
4830 
4831     #[test]
test_fin_with_data()4832     fn test_fin_with_data() {
4833         let mut s = socket_established();
4834         s.send_slice(b"abcdef").unwrap();
4835         s.close();
4836         recv!(
4837             s,
4838             [TcpRepr {
4839                 control: TcpControl::Fin,
4840                 seq_number: LOCAL_SEQ + 1,
4841                 ack_number: Some(REMOTE_SEQ + 1),
4842                 payload: &b"abcdef"[..],
4843                 ..RECV_TEMPL
4844             }]
4845         )
4846     }
4847 
4848     #[test]
test_mutual_close_with_data_1()4849     fn test_mutual_close_with_data_1() {
4850         let mut s = socket_established();
4851         s.send_slice(b"abcdef").unwrap();
4852         s.close();
4853         assert_eq!(s.state, State::FinWait1);
4854         recv!(
4855             s,
4856             [TcpRepr {
4857                 control: TcpControl::Fin,
4858                 seq_number: LOCAL_SEQ + 1,
4859                 ack_number: Some(REMOTE_SEQ + 1),
4860                 payload: &b"abcdef"[..],
4861                 ..RECV_TEMPL
4862             }]
4863         );
4864         send!(
4865             s,
4866             TcpRepr {
4867                 control: TcpControl::Fin,
4868                 seq_number: REMOTE_SEQ + 1,
4869                 ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
4870                 ..SEND_TEMPL
4871             }
4872         );
4873     }
4874 
4875     #[test]
test_mutual_close_with_data_2()4876     fn test_mutual_close_with_data_2() {
4877         let mut s = socket_established();
4878         s.send_slice(b"abcdef").unwrap();
4879         s.close();
4880         assert_eq!(s.state, State::FinWait1);
4881         recv!(
4882             s,
4883             [TcpRepr {
4884                 control: TcpControl::Fin,
4885                 seq_number: LOCAL_SEQ + 1,
4886                 ack_number: Some(REMOTE_SEQ + 1),
4887                 payload: &b"abcdef"[..],
4888                 ..RECV_TEMPL
4889             }]
4890         );
4891         send!(
4892             s,
4893             TcpRepr {
4894                 seq_number: REMOTE_SEQ + 1,
4895                 ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
4896                 ..SEND_TEMPL
4897             }
4898         );
4899         assert_eq!(s.state, State::FinWait2);
4900         send!(
4901             s,
4902             TcpRepr {
4903                 control: TcpControl::Fin,
4904                 seq_number: REMOTE_SEQ + 1,
4905                 ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
4906                 ..SEND_TEMPL
4907             }
4908         );
4909         recv!(
4910             s,
4911             [TcpRepr {
4912                 seq_number: LOCAL_SEQ + 1 + 6 + 1,
4913                 ack_number: Some(REMOTE_SEQ + 1 + 1),
4914                 ..RECV_TEMPL
4915             }]
4916         );
4917         assert_eq!(s.state, State::TimeWait);
4918     }
4919 
4920     // =========================================================================================//
4921     // Tests for retransmission on packet loss.
4922     // =========================================================================================//
4923 
4924     #[test]
test_duplicate_seq_ack()4925     fn test_duplicate_seq_ack() {
4926         let mut s = socket_recved();
4927         // remote retransmission
4928         send!(
4929             s,
4930             TcpRepr {
4931                 seq_number: REMOTE_SEQ + 1,
4932                 ack_number: Some(LOCAL_SEQ + 1),
4933                 payload: &b"abcdef"[..],
4934                 ..SEND_TEMPL
4935             },
4936             Some(TcpRepr {
4937                 seq_number: LOCAL_SEQ + 1,
4938                 ack_number: Some(REMOTE_SEQ + 1 + 6),
4939                 window_len: 58,
4940                 ..RECV_TEMPL
4941             })
4942         );
4943     }
4944 
4945     #[test]
test_data_retransmit()4946     fn test_data_retransmit() {
4947         let mut s = socket_established();
4948         s.send_slice(b"abcdef").unwrap();
4949         recv!(s, time 1000, Ok(TcpRepr {
4950             seq_number: LOCAL_SEQ + 1,
4951             ack_number: Some(REMOTE_SEQ + 1),
4952             payload:    &b"abcdef"[..],
4953             ..RECV_TEMPL
4954         }));
4955         recv_nothing!(s, time 1050);
4956         recv!(s, time 2000, Ok(TcpRepr {
4957             seq_number: LOCAL_SEQ + 1,
4958             ack_number: Some(REMOTE_SEQ + 1),
4959             payload:    &b"abcdef"[..],
4960             ..RECV_TEMPL
4961         }));
4962     }
4963 
4964     #[test]
test_data_retransmit_bursts()4965     fn test_data_retransmit_bursts() {
4966         let mut s = socket_established();
4967         s.remote_mss = 6;
4968         s.send_slice(b"abcdef012345").unwrap();
4969 
4970         recv!(s, time 0, Ok(TcpRepr {
4971             control:    TcpControl::None,
4972             seq_number: LOCAL_SEQ + 1,
4973             ack_number: Some(REMOTE_SEQ + 1),
4974             payload:    &b"abcdef"[..],
4975             ..RECV_TEMPL
4976         }), exact);
4977         recv!(s, time 0, Ok(TcpRepr {
4978             control:    TcpControl::Psh,
4979             seq_number: LOCAL_SEQ + 1 + 6,
4980             ack_number: Some(REMOTE_SEQ + 1),
4981             payload:    &b"012345"[..],
4982             ..RECV_TEMPL
4983         }), exact);
4984         recv_nothing!(s, time 0);
4985 
4986         recv_nothing!(s, time 50);
4987 
4988         recv!(s, time 1000, Ok(TcpRepr {
4989             control:    TcpControl::None,
4990             seq_number: LOCAL_SEQ + 1,
4991             ack_number: Some(REMOTE_SEQ + 1),
4992             payload:    &b"abcdef"[..],
4993             ..RECV_TEMPL
4994         }), exact);
4995         recv!(s, time 1500, Ok(TcpRepr {
4996             control:    TcpControl::Psh,
4997             seq_number: LOCAL_SEQ + 1 + 6,
4998             ack_number: Some(REMOTE_SEQ + 1),
4999             payload:    &b"012345"[..],
5000             ..RECV_TEMPL
5001         }), exact);
5002         recv_nothing!(s, time 1550);
5003     }
5004 
5005     #[test]
test_data_retransmit_bursts_half_ack()5006     fn test_data_retransmit_bursts_half_ack() {
5007         let mut s = socket_established();
5008         s.remote_mss = 6;
5009         s.send_slice(b"abcdef012345").unwrap();
5010 
5011         recv!(s, time 0, Ok(TcpRepr {
5012             control:    TcpControl::None,
5013             seq_number: LOCAL_SEQ + 1,
5014             ack_number: Some(REMOTE_SEQ + 1),
5015             payload:    &b"abcdef"[..],
5016             ..RECV_TEMPL
5017         }), exact);
5018         recv!(s, time 0, Ok(TcpRepr {
5019             control:    TcpControl::Psh,
5020             seq_number: LOCAL_SEQ + 1 + 6,
5021             ack_number: Some(REMOTE_SEQ + 1),
5022             payload:    &b"012345"[..],
5023             ..RECV_TEMPL
5024         }), exact);
5025         // Acknowledge the first packet
5026         send!(s, time 5, TcpRepr {
5027             seq_number: REMOTE_SEQ + 1,
5028             ack_number: Some(LOCAL_SEQ + 1 + 6),
5029             window_len: 6,
5030             ..SEND_TEMPL
5031         });
5032         // The second packet should be re-sent.
5033         recv!(s, time 1500, Ok(TcpRepr {
5034             control:    TcpControl::Psh,
5035             seq_number: LOCAL_SEQ + 1 + 6,
5036             ack_number: Some(REMOTE_SEQ + 1),
5037             payload:    &b"012345"[..],
5038             ..RECV_TEMPL
5039         }), exact);
5040 
5041         recv_nothing!(s, time 1550);
5042     }
5043 
5044     #[test]
test_data_retransmit_bursts_half_ack_close()5045     fn test_data_retransmit_bursts_half_ack_close() {
5046         let mut s = socket_established();
5047         s.remote_mss = 6;
5048         s.send_slice(b"abcdef012345").unwrap();
5049         s.close();
5050 
5051         recv!(s, time 0, Ok(TcpRepr {
5052             control:    TcpControl::None,
5053             seq_number: LOCAL_SEQ + 1,
5054             ack_number: Some(REMOTE_SEQ + 1),
5055             payload:    &b"abcdef"[..],
5056             ..RECV_TEMPL
5057         }), exact);
5058         recv!(s, time 0, Ok(TcpRepr {
5059             control:    TcpControl::Fin,
5060             seq_number: LOCAL_SEQ + 1 + 6,
5061             ack_number: Some(REMOTE_SEQ + 1),
5062             payload:    &b"012345"[..],
5063             ..RECV_TEMPL
5064         }), exact);
5065         // Acknowledge the first packet
5066         send!(s, time 5, TcpRepr {
5067             seq_number: REMOTE_SEQ + 1,
5068             ack_number: Some(LOCAL_SEQ + 1 + 6),
5069             window_len: 6,
5070             ..SEND_TEMPL
5071         });
5072         // The second packet should be re-sent.
5073         recv!(s, time 1500, Ok(TcpRepr {
5074             control:    TcpControl::Fin,
5075             seq_number: LOCAL_SEQ + 1 + 6,
5076             ack_number: Some(REMOTE_SEQ + 1),
5077             payload:    &b"012345"[..],
5078             ..RECV_TEMPL
5079         }), exact);
5080 
5081         recv_nothing!(s, time 1550);
5082     }
5083 
5084     #[test]
test_send_data_after_syn_ack_retransmit()5085     fn test_send_data_after_syn_ack_retransmit() {
5086         let mut s = socket_syn_received();
5087         recv!(s, time 50, Ok(TcpRepr {
5088             control:    TcpControl::Syn,
5089             seq_number: LOCAL_SEQ,
5090             ack_number: Some(REMOTE_SEQ + 1),
5091             max_seg_size: Some(BASE_MSS),
5092             ..RECV_TEMPL
5093         }));
5094         recv!(s, time 750, Ok(TcpRepr { // retransmit
5095             control:    TcpControl::Syn,
5096             seq_number: LOCAL_SEQ,
5097             ack_number: Some(REMOTE_SEQ + 1),
5098             max_seg_size: Some(BASE_MSS),
5099             ..RECV_TEMPL
5100         }));
5101         send!(
5102             s,
5103             TcpRepr {
5104                 seq_number: REMOTE_SEQ + 1,
5105                 ack_number: Some(LOCAL_SEQ + 1),
5106                 ..SEND_TEMPL
5107             }
5108         );
5109         assert_eq!(s.state(), State::Established);
5110         s.send_slice(b"abcdef").unwrap();
5111         recv!(
5112             s,
5113             [TcpRepr {
5114                 seq_number: LOCAL_SEQ + 1,
5115                 ack_number: Some(REMOTE_SEQ + 1),
5116                 payload: &b"abcdef"[..],
5117                 ..RECV_TEMPL
5118             }]
5119         )
5120     }
5121 
5122     #[test]
test_established_retransmit_for_dup_ack()5123     fn test_established_retransmit_for_dup_ack() {
5124         let mut s = socket_established();
5125         // Duplicate ACKs do not replace the retransmission timer
5126         s.send_slice(b"abc").unwrap();
5127         recv!(s, time 1000, Ok(TcpRepr {
5128             seq_number: LOCAL_SEQ + 1,
5129             ack_number: Some(REMOTE_SEQ + 1),
5130             payload:    &b"abc"[..],
5131             ..RECV_TEMPL
5132         }));
5133         // Retransmit timer is on because all data was sent
5134         assert_eq!(s.tx_buffer.len(), 3);
5135         // ACK nothing new
5136         send!(
5137             s,
5138             TcpRepr {
5139                 seq_number: REMOTE_SEQ + 1,
5140                 ack_number: Some(LOCAL_SEQ + 1),
5141                 ..SEND_TEMPL
5142             }
5143         );
5144         // Retransmit
5145         recv!(s, time 4000, Ok(TcpRepr {
5146             seq_number: LOCAL_SEQ + 1,
5147             ack_number: Some(REMOTE_SEQ + 1),
5148             payload:    &b"abc"[..],
5149             ..RECV_TEMPL
5150         }));
5151     }
5152 
5153     #[test]
test_established_retransmit_reset_after_ack()5154     fn test_established_retransmit_reset_after_ack() {
5155         let mut s = socket_established();
5156         s.remote_win_len = 6;
5157         s.send_slice(b"abcdef").unwrap();
5158         s.send_slice(b"123456").unwrap();
5159         s.send_slice(b"ABCDEF").unwrap();
5160         recv!(s, time 1000, Ok(TcpRepr {
5161             seq_number: LOCAL_SEQ + 1,
5162             ack_number: Some(REMOTE_SEQ + 1),
5163             payload:    &b"abcdef"[..],
5164             ..RECV_TEMPL
5165         }));
5166         send!(s, time 1005, TcpRepr {
5167             seq_number: REMOTE_SEQ + 1,
5168             ack_number: Some(LOCAL_SEQ + 1 + 6),
5169             window_len: 6,
5170             ..SEND_TEMPL
5171         });
5172         recv!(s, time 1010, Ok(TcpRepr {
5173             seq_number: LOCAL_SEQ + 1 + 6,
5174             ack_number: Some(REMOTE_SEQ + 1),
5175             payload:    &b"123456"[..],
5176             ..RECV_TEMPL
5177         }));
5178         send!(s, time 1015, TcpRepr {
5179             seq_number: REMOTE_SEQ + 1,
5180             ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
5181             window_len: 6,
5182             ..SEND_TEMPL
5183         });
5184         recv!(s, time 1020, Ok(TcpRepr {
5185             seq_number: LOCAL_SEQ + 1 + 6 + 6,
5186             ack_number: Some(REMOTE_SEQ + 1),
5187             payload:    &b"ABCDEF"[..],
5188             ..RECV_TEMPL
5189         }));
5190     }
5191 
5192     #[test]
test_established_queue_during_retransmission()5193     fn test_established_queue_during_retransmission() {
5194         let mut s = socket_established();
5195         s.remote_mss = 6;
5196         s.send_slice(b"abcdef123456ABCDEF").unwrap();
5197         recv!(s, time 1000, Ok(TcpRepr {
5198             seq_number: LOCAL_SEQ + 1,
5199             ack_number: Some(REMOTE_SEQ + 1),
5200             payload:    &b"abcdef"[..],
5201             ..RECV_TEMPL
5202         })); // this one is dropped
5203         recv!(s, time 1005, Ok(TcpRepr {
5204             seq_number: LOCAL_SEQ + 1 + 6,
5205             ack_number: Some(REMOTE_SEQ + 1),
5206             payload:    &b"123456"[..],
5207             ..RECV_TEMPL
5208         })); // this one is received
5209         recv!(s, time 1010, Ok(TcpRepr {
5210             seq_number: LOCAL_SEQ + 1 + 6 + 6,
5211             ack_number: Some(REMOTE_SEQ + 1),
5212             payload:    &b"ABCDEF"[..],
5213             ..RECV_TEMPL
5214         })); // also dropped
5215         recv!(s, time 2000, Ok(TcpRepr {
5216             seq_number: LOCAL_SEQ + 1,
5217             ack_number: Some(REMOTE_SEQ + 1),
5218             payload:    &b"abcdef"[..],
5219             ..RECV_TEMPL
5220         })); // retransmission
5221         send!(s, time 2005, TcpRepr {
5222             seq_number: REMOTE_SEQ + 1,
5223             ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
5224             ..SEND_TEMPL
5225         }); // acknowledgement of both segments
5226         recv!(s, time 2010, Ok(TcpRepr {
5227             seq_number: LOCAL_SEQ + 1 + 6 + 6,
5228             ack_number: Some(REMOTE_SEQ + 1),
5229             payload:    &b"ABCDEF"[..],
5230             ..RECV_TEMPL
5231         })); // retransmission of only unacknowledged data
5232     }
5233 
5234     #[test]
test_close_wait_retransmit_reset_after_ack()5235     fn test_close_wait_retransmit_reset_after_ack() {
5236         let mut s = socket_close_wait();
5237         s.remote_win_len = 6;
5238         s.send_slice(b"abcdef").unwrap();
5239         s.send_slice(b"123456").unwrap();
5240         s.send_slice(b"ABCDEF").unwrap();
5241         recv!(s, time 1000, Ok(TcpRepr {
5242             seq_number: LOCAL_SEQ + 1,
5243             ack_number: Some(REMOTE_SEQ + 1 + 1),
5244             payload:    &b"abcdef"[..],
5245             ..RECV_TEMPL
5246         }));
5247         send!(s, time 1005, TcpRepr {
5248             seq_number: REMOTE_SEQ + 1 + 1,
5249             ack_number: Some(LOCAL_SEQ + 1 + 6),
5250             window_len: 6,
5251             ..SEND_TEMPL
5252         });
5253         recv!(s, time 1010, Ok(TcpRepr {
5254             seq_number: LOCAL_SEQ + 1 + 6,
5255             ack_number: Some(REMOTE_SEQ + 1 + 1),
5256             payload:    &b"123456"[..],
5257             ..RECV_TEMPL
5258         }));
5259         send!(s, time 1015, TcpRepr {
5260             seq_number: REMOTE_SEQ + 1 + 1,
5261             ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
5262             window_len: 6,
5263             ..SEND_TEMPL
5264         });
5265         recv!(s, time 1020, Ok(TcpRepr {
5266             seq_number: LOCAL_SEQ + 1 + 6 + 6,
5267             ack_number: Some(REMOTE_SEQ + 1 + 1),
5268             payload:    &b"ABCDEF"[..],
5269             ..RECV_TEMPL
5270         }));
5271     }
5272 
5273     #[test]
test_fin_wait_1_retransmit_reset_after_ack()5274     fn test_fin_wait_1_retransmit_reset_after_ack() {
5275         let mut s = socket_established();
5276         s.remote_win_len = 6;
5277         s.send_slice(b"abcdef").unwrap();
5278         s.send_slice(b"123456").unwrap();
5279         s.send_slice(b"ABCDEF").unwrap();
5280         s.close();
5281         recv!(s, time 1000, Ok(TcpRepr {
5282             seq_number: LOCAL_SEQ + 1,
5283             ack_number: Some(REMOTE_SEQ + 1),
5284             payload:    &b"abcdef"[..],
5285             ..RECV_TEMPL
5286         }));
5287         send!(s, time 1005, TcpRepr {
5288             seq_number: REMOTE_SEQ + 1,
5289             ack_number: Some(LOCAL_SEQ + 1 + 6),
5290             window_len: 6,
5291             ..SEND_TEMPL
5292         });
5293         recv!(s, time 1010, Ok(TcpRepr {
5294             seq_number: LOCAL_SEQ + 1 + 6,
5295             ack_number: Some(REMOTE_SEQ + 1),
5296             payload:    &b"123456"[..],
5297             ..RECV_TEMPL
5298         }));
5299         send!(s, time 1015, TcpRepr {
5300             seq_number: REMOTE_SEQ + 1,
5301             ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
5302             window_len: 6,
5303             ..SEND_TEMPL
5304         });
5305         recv!(s, time 1020, Ok(TcpRepr {
5306             control:    TcpControl::Fin,
5307             seq_number: LOCAL_SEQ + 1 + 6 + 6,
5308             ack_number: Some(REMOTE_SEQ + 1),
5309             payload:    &b"ABCDEF"[..],
5310             ..RECV_TEMPL
5311         }));
5312     }
5313 
5314     #[test]
test_fast_retransmit_after_triple_duplicate_ack()5315     fn test_fast_retransmit_after_triple_duplicate_ack() {
5316         let mut s = socket_established();
5317         s.remote_mss = 6;
5318 
5319         // Normal ACK of previously recived segment
5320         send!(s, time 0, TcpRepr {
5321             seq_number: REMOTE_SEQ + 1,
5322             ack_number: Some(LOCAL_SEQ + 1),
5323             ..SEND_TEMPL
5324         });
5325 
5326         // Send a long string of text divided into several packets
5327         // because of previously received "window_len"
5328         s.send_slice(b"xxxxxxyyyyyywwwwwwzzzzzz").unwrap();
5329         // This packet is lost
5330         recv!(s, time 1000, Ok(TcpRepr {
5331             seq_number: LOCAL_SEQ + 1,
5332             ack_number: Some(REMOTE_SEQ + 1),
5333             payload:    &b"xxxxxx"[..],
5334             ..RECV_TEMPL
5335         }));
5336         recv!(s, time 1005, Ok(TcpRepr {
5337             seq_number: LOCAL_SEQ + 1 + 6,
5338             ack_number: Some(REMOTE_SEQ + 1),
5339             payload:    &b"yyyyyy"[..],
5340             ..RECV_TEMPL
5341         }));
5342         recv!(s, time 1010, Ok(TcpRepr {
5343             seq_number: LOCAL_SEQ + 1 + (6 * 2),
5344             ack_number: Some(REMOTE_SEQ + 1),
5345             payload:    &b"wwwwww"[..],
5346             ..RECV_TEMPL
5347         }));
5348         recv!(s, time 1015, Ok(TcpRepr {
5349             seq_number: LOCAL_SEQ + 1 + (6 * 3),
5350             ack_number: Some(REMOTE_SEQ + 1),
5351             payload:    &b"zzzzzz"[..],
5352             ..RECV_TEMPL
5353         }));
5354 
5355         // First duplicate ACK
5356         send!(s, time 1050, TcpRepr {
5357             seq_number: REMOTE_SEQ + 1,
5358             ack_number: Some(LOCAL_SEQ + 1),
5359             ..SEND_TEMPL
5360         });
5361         // Second duplicate ACK
5362         send!(s, time 1055, TcpRepr {
5363             seq_number: REMOTE_SEQ + 1,
5364             ack_number: Some(LOCAL_SEQ + 1),
5365             ..SEND_TEMPL
5366         });
5367         // Third duplicate ACK
5368         // Should trigger a fast retransmit of dropped packet
5369         send!(s, time 1060, TcpRepr {
5370             seq_number: REMOTE_SEQ + 1,
5371             ack_number: Some(LOCAL_SEQ + 1),
5372             ..SEND_TEMPL
5373         });
5374 
5375         // Fast retransmit packet
5376         recv!(s, time 1100, Ok(TcpRepr {
5377             seq_number: LOCAL_SEQ + 1,
5378             ack_number: Some(REMOTE_SEQ + 1),
5379             payload:    &b"xxxxxx"[..],
5380             ..RECV_TEMPL
5381         }));
5382 
5383         recv!(s, time 1105, Ok(TcpRepr {
5384             seq_number: LOCAL_SEQ + 1 + 6,
5385             ack_number: Some(REMOTE_SEQ + 1),
5386             payload:    &b"yyyyyy"[..],
5387             ..RECV_TEMPL
5388         }));
5389         recv!(s, time 1110, Ok(TcpRepr {
5390             seq_number: LOCAL_SEQ + 1 + (6 * 2),
5391             ack_number: Some(REMOTE_SEQ + 1),
5392             payload:    &b"wwwwww"[..],
5393             ..RECV_TEMPL
5394         }));
5395         recv!(s, time 1115, Ok(TcpRepr {
5396             seq_number: LOCAL_SEQ + 1 + (6 * 3),
5397             ack_number: Some(REMOTE_SEQ + 1),
5398             payload:    &b"zzzzzz"[..],
5399             ..RECV_TEMPL
5400         }));
5401 
5402         // After all was send out, enter *normal* retransmission,
5403         // don't stay in fast retransmission.
5404         assert!(match s.timer {
5405             Timer::Retransmit { expires_at, .. } => expires_at > Instant::from_millis(1115),
5406             _ => false,
5407         });
5408 
5409         // ACK all received segments
5410         send!(s, time 1120, TcpRepr {
5411             seq_number: REMOTE_SEQ + 1,
5412             ack_number: Some(LOCAL_SEQ + 1 + (6 * 4)),
5413             ..SEND_TEMPL
5414         });
5415     }
5416 
5417     #[test]
test_fast_retransmit_duplicate_detection_with_data()5418     fn test_fast_retransmit_duplicate_detection_with_data() {
5419         let mut s = socket_established();
5420 
5421         s.send_slice(b"abc").unwrap(); // This is lost
5422         recv!(s, time 1000, Ok(TcpRepr {
5423             seq_number: LOCAL_SEQ + 1,
5424             ack_number: Some(REMOTE_SEQ + 1),
5425             payload:    &b"abc"[..],
5426             ..RECV_TEMPL
5427         }));
5428 
5429         // Normal ACK of previously received segment
5430         send!(
5431             s,
5432             TcpRepr {
5433                 seq_number: REMOTE_SEQ + 1,
5434                 ack_number: Some(LOCAL_SEQ + 1),
5435                 ..SEND_TEMPL
5436             }
5437         );
5438         // First duplicate
5439         send!(
5440             s,
5441             TcpRepr {
5442                 seq_number: REMOTE_SEQ + 1,
5443                 ack_number: Some(LOCAL_SEQ + 1),
5444                 ..SEND_TEMPL
5445             }
5446         );
5447         // Second duplicate
5448         send!(
5449             s,
5450             TcpRepr {
5451                 seq_number: REMOTE_SEQ + 1,
5452                 ack_number: Some(LOCAL_SEQ + 1),
5453                 ..SEND_TEMPL
5454             }
5455         );
5456 
5457         assert_eq!(s.local_rx_dup_acks, 2, "duplicate ACK counter is not set");
5458 
5459         // This packet has content, hence should not be detected
5460         // as a duplicate ACK and should reset the duplicate ACK count
5461         send!(
5462             s,
5463             TcpRepr {
5464                 seq_number: REMOTE_SEQ + 1,
5465                 ack_number: Some(LOCAL_SEQ + 1),
5466                 payload: &b"xxxxxx"[..],
5467                 ..SEND_TEMPL
5468             }
5469         );
5470 
5471         recv!(
5472             s,
5473             [TcpRepr {
5474                 seq_number: LOCAL_SEQ + 1 + 3,
5475                 ack_number: Some(REMOTE_SEQ + 1 + 6),
5476                 window_len: 58,
5477                 ..RECV_TEMPL
5478             }]
5479         );
5480 
5481         assert_eq!(
5482             s.local_rx_dup_acks, 0,
5483             "duplicate ACK counter is not reset when receiving data"
5484         );
5485     }
5486 
5487     #[test]
test_fast_retransmit_duplicate_detection()5488     fn test_fast_retransmit_duplicate_detection() {
5489         let mut s = socket_established();
5490         s.remote_mss = 6;
5491 
5492         // Normal ACK of previously received segment
5493         send!(s, time 0, TcpRepr {
5494             seq_number: REMOTE_SEQ + 1,
5495             ack_number: Some(LOCAL_SEQ + 1),
5496             ..SEND_TEMPL
5497         });
5498 
5499         // First duplicate, should not be counted as there is nothing to resend
5500         send!(s, time 0, TcpRepr {
5501             seq_number: REMOTE_SEQ + 1,
5502             ack_number: Some(LOCAL_SEQ + 1),
5503             ..SEND_TEMPL
5504         });
5505 
5506         assert_eq!(
5507             s.local_rx_dup_acks, 0,
5508             "duplicate ACK counter is set but wound not transmit data"
5509         );
5510 
5511         // Send a long string of text divided into several packets
5512         // because of small remote_mss
5513         s.send_slice(b"xxxxxxyyyyyywwwwwwzzzzzz").unwrap();
5514 
5515         // This packet is reordered in network
5516         recv!(s, time 1000, Ok(TcpRepr {
5517             seq_number: LOCAL_SEQ + 1,
5518             ack_number: Some(REMOTE_SEQ + 1),
5519             payload:    &b"xxxxxx"[..],
5520             ..RECV_TEMPL
5521         }));
5522         recv!(s, time 1005, Ok(TcpRepr {
5523             seq_number: LOCAL_SEQ + 1 + 6,
5524             ack_number: Some(REMOTE_SEQ + 1),
5525             payload:    &b"yyyyyy"[..],
5526             ..RECV_TEMPL
5527         }));
5528         recv!(s, time 1010, Ok(TcpRepr {
5529             seq_number: LOCAL_SEQ + 1 + (6 * 2),
5530             ack_number: Some(REMOTE_SEQ + 1),
5531             payload:    &b"wwwwww"[..],
5532             ..RECV_TEMPL
5533         }));
5534         recv!(s, time 1015, Ok(TcpRepr {
5535             seq_number: LOCAL_SEQ + 1 + (6 * 3),
5536             ack_number: Some(REMOTE_SEQ + 1),
5537             payload:    &b"zzzzzz"[..],
5538             ..RECV_TEMPL
5539         }));
5540 
5541         // First duplicate ACK
5542         send!(s, time 1050, TcpRepr {
5543             seq_number: REMOTE_SEQ + 1,
5544             ack_number: Some(LOCAL_SEQ + 1),
5545             ..SEND_TEMPL
5546         });
5547         // Second duplicate ACK
5548         send!(s, time 1055, TcpRepr {
5549             seq_number: REMOTE_SEQ + 1,
5550             ack_number: Some(LOCAL_SEQ + 1),
5551             ..SEND_TEMPL
5552         });
5553         // Reordered packet arrives which should reset duplicate ACK count
5554         send!(s, time 1060, TcpRepr {
5555             seq_number: REMOTE_SEQ + 1,
5556             ack_number: Some(LOCAL_SEQ + 1 + (6 * 3)),
5557             ..SEND_TEMPL
5558         });
5559 
5560         assert_eq!(
5561             s.local_rx_dup_acks, 0,
5562             "duplicate ACK counter is not reset when receiving ACK which updates send window"
5563         );
5564 
5565         // ACK all received segments
5566         send!(s, time 1120, TcpRepr {
5567             seq_number: REMOTE_SEQ + 1,
5568             ack_number: Some(LOCAL_SEQ + 1 + (6 * 4)),
5569             ..SEND_TEMPL
5570         });
5571     }
5572 
5573     #[test]
test_fast_retransmit_dup_acks_counter()5574     fn test_fast_retransmit_dup_acks_counter() {
5575         let mut s = socket_established();
5576 
5577         s.send_slice(b"abc").unwrap(); // This is lost
5578         recv!(s, time 0, Ok(TcpRepr {
5579             seq_number: LOCAL_SEQ + 1,
5580             ack_number: Some(REMOTE_SEQ + 1),
5581             payload:    &b"abc"[..],
5582             ..RECV_TEMPL
5583         }));
5584 
5585         send!(s, time 0, TcpRepr {
5586             seq_number: REMOTE_SEQ + 1,
5587             ack_number: Some(LOCAL_SEQ + 1),
5588             ..SEND_TEMPL
5589         });
5590 
5591         // A lot of retransmits happen here
5592         s.local_rx_dup_acks = u8::max_value() - 1;
5593 
5594         // Send 3 more ACKs, which could overflow local_rx_dup_acks,
5595         // but intended behaviour is that we saturate the bounds
5596         // of local_rx_dup_acks
5597         send!(s, time 0, TcpRepr {
5598             seq_number: REMOTE_SEQ + 1,
5599             ack_number: Some(LOCAL_SEQ + 1),
5600             ..SEND_TEMPL
5601         });
5602         send!(s, time 0, TcpRepr {
5603             seq_number: REMOTE_SEQ + 1,
5604             ack_number: Some(LOCAL_SEQ + 1),
5605             ..SEND_TEMPL
5606         });
5607         send!(s, time 0, TcpRepr {
5608             seq_number: REMOTE_SEQ + 1,
5609             ack_number: Some(LOCAL_SEQ + 1),
5610             ..SEND_TEMPL
5611         });
5612         assert_eq!(
5613             s.local_rx_dup_acks,
5614             u8::max_value(),
5615             "duplicate ACK count should not overflow but saturate"
5616         );
5617     }
5618 
5619     #[test]
test_fast_retransmit_zero_window()5620     fn test_fast_retransmit_zero_window() {
5621         let mut s = socket_established();
5622 
5623         send!(s, time 1000, TcpRepr {
5624             seq_number: REMOTE_SEQ + 1,
5625             ack_number: Some(LOCAL_SEQ + 1),
5626             ..SEND_TEMPL
5627         });
5628 
5629         s.send_slice(b"abc").unwrap();
5630 
5631         recv!(s, time 0, Ok(TcpRepr {
5632             seq_number: LOCAL_SEQ + 1,
5633             ack_number: Some(REMOTE_SEQ + 1),
5634             payload:    &b"abc"[..],
5635             ..RECV_TEMPL
5636         }));
5637 
5638         // 3 dup acks
5639         send!(s, time 1050, TcpRepr {
5640             seq_number: REMOTE_SEQ + 1,
5641             ack_number: Some(LOCAL_SEQ + 1),
5642             ..SEND_TEMPL
5643         });
5644         send!(s, time 1050, TcpRepr {
5645             seq_number: REMOTE_SEQ + 1,
5646             ack_number: Some(LOCAL_SEQ + 1),
5647             ..SEND_TEMPL
5648         });
5649         send!(s, time 1050, TcpRepr {
5650             seq_number: REMOTE_SEQ + 1,
5651             ack_number: Some(LOCAL_SEQ + 1),
5652             window_len: 0, // boom
5653             ..SEND_TEMPL
5654         });
5655 
5656         // even though we're in "fast retransmit", we shouldn't
5657         // force-send anything because the remote's window is full.
5658         recv_nothing!(s);
5659     }
5660 
5661     // =========================================================================================//
5662     // Tests for window management.
5663     // =========================================================================================//
5664 
5665     #[test]
test_maximum_segment_size()5666     fn test_maximum_segment_size() {
5667         let mut s = socket_listen();
5668         s.tx_buffer = SocketBuffer::new(vec![0; 32767]);
5669         send!(
5670             s,
5671             TcpRepr {
5672                 control: TcpControl::Syn,
5673                 seq_number: REMOTE_SEQ,
5674                 ack_number: None,
5675                 max_seg_size: Some(1000),
5676                 ..SEND_TEMPL
5677             }
5678         );
5679         recv!(
5680             s,
5681             [TcpRepr {
5682                 control: TcpControl::Syn,
5683                 seq_number: LOCAL_SEQ,
5684                 ack_number: Some(REMOTE_SEQ + 1),
5685                 max_seg_size: Some(BASE_MSS),
5686                 ..RECV_TEMPL
5687             }]
5688         );
5689         send!(
5690             s,
5691             TcpRepr {
5692                 seq_number: REMOTE_SEQ + 1,
5693                 ack_number: Some(LOCAL_SEQ + 1),
5694                 window_len: 32767,
5695                 ..SEND_TEMPL
5696             }
5697         );
5698         s.send_slice(&[0; 1200][..]).unwrap();
5699         recv!(
5700             s,
5701             Ok(TcpRepr {
5702                 seq_number: LOCAL_SEQ + 1,
5703                 ack_number: Some(REMOTE_SEQ + 1),
5704                 payload: &[0; 1000][..],
5705                 ..RECV_TEMPL
5706             })
5707         );
5708     }
5709 
5710     #[test]
test_close_wait_no_window_update()5711     fn test_close_wait_no_window_update() {
5712         let mut s = socket_established();
5713         send!(
5714             s,
5715             TcpRepr {
5716                 control: TcpControl::Fin,
5717                 seq_number: REMOTE_SEQ + 1,
5718                 ack_number: Some(LOCAL_SEQ + 1),
5719                 payload: &[1, 2, 3, 4],
5720                 ..SEND_TEMPL
5721             }
5722         );
5723         assert_eq!(s.state, State::CloseWait);
5724 
5725         // we ack the FIN, with the reduced window size.
5726         recv!(
5727             s,
5728             Ok(TcpRepr {
5729                 seq_number: LOCAL_SEQ + 1,
5730                 ack_number: Some(REMOTE_SEQ + 6),
5731                 window_len: 60,
5732                 ..RECV_TEMPL
5733             })
5734         );
5735 
5736         let rx_buf = &mut [0; 32];
5737         assert_eq!(s.recv_slice(rx_buf), Ok(4));
5738 
5739         // check that we do NOT send a window update even if it has changed.
5740         recv_nothing!(s);
5741     }
5742 
5743     #[test]
test_time_wait_no_window_update()5744     fn test_time_wait_no_window_update() {
5745         let mut s = socket_fin_wait_2();
5746         send!(
5747             s,
5748             TcpRepr {
5749                 control: TcpControl::Fin,
5750                 seq_number: REMOTE_SEQ + 1,
5751                 ack_number: Some(LOCAL_SEQ + 2),
5752                 payload: &[1, 2, 3, 4],
5753                 ..SEND_TEMPL
5754             }
5755         );
5756         assert_eq!(s.state, State::TimeWait);
5757 
5758         // we ack the FIN, with the reduced window size.
5759         recv!(
5760             s,
5761             Ok(TcpRepr {
5762                 seq_number: LOCAL_SEQ + 2,
5763                 ack_number: Some(REMOTE_SEQ + 6),
5764                 window_len: 60,
5765                 ..RECV_TEMPL
5766             })
5767         );
5768 
5769         let rx_buf = &mut [0; 32];
5770         assert_eq!(s.recv_slice(rx_buf), Ok(4));
5771 
5772         // check that we do NOT send a window update even if it has changed.
5773         recv_nothing!(s);
5774     }
5775 
5776     // =========================================================================================//
5777     // Tests for flow control.
5778     // =========================================================================================//
5779 
5780     #[test]
test_psh_transmit()5781     fn test_psh_transmit() {
5782         let mut s = socket_established();
5783         s.remote_mss = 6;
5784         s.send_slice(b"abcdef").unwrap();
5785         s.send_slice(b"123456").unwrap();
5786         recv!(s, time 0, Ok(TcpRepr {
5787             control:    TcpControl::None,
5788             seq_number: LOCAL_SEQ + 1,
5789             ack_number: Some(REMOTE_SEQ + 1),
5790             payload:    &b"abcdef"[..],
5791             ..RECV_TEMPL
5792         }), exact);
5793         recv!(s, time 0, Ok(TcpRepr {
5794             control:    TcpControl::Psh,
5795             seq_number: LOCAL_SEQ + 1 + 6,
5796             ack_number: Some(REMOTE_SEQ + 1),
5797             payload:    &b"123456"[..],
5798             ..RECV_TEMPL
5799         }), exact);
5800     }
5801 
5802     #[test]
test_psh_receive()5803     fn test_psh_receive() {
5804         let mut s = socket_established();
5805         send!(
5806             s,
5807             TcpRepr {
5808                 control: TcpControl::Psh,
5809                 seq_number: REMOTE_SEQ + 1,
5810                 ack_number: Some(LOCAL_SEQ + 1),
5811                 payload: &b"abcdef"[..],
5812                 ..SEND_TEMPL
5813             }
5814         );
5815         recv!(
5816             s,
5817             [TcpRepr {
5818                 seq_number: LOCAL_SEQ + 1,
5819                 ack_number: Some(REMOTE_SEQ + 1 + 6),
5820                 window_len: 58,
5821                 ..RECV_TEMPL
5822             }]
5823         );
5824     }
5825 
5826     #[test]
test_zero_window_ack()5827     fn test_zero_window_ack() {
5828         let mut s = socket_established();
5829         s.rx_buffer = SocketBuffer::new(vec![0; 6]);
5830         s.assembler = Assembler::new();
5831         send!(
5832             s,
5833             TcpRepr {
5834                 seq_number: REMOTE_SEQ + 1,
5835                 ack_number: Some(LOCAL_SEQ + 1),
5836                 payload: &b"abcdef"[..],
5837                 ..SEND_TEMPL
5838             }
5839         );
5840         recv!(
5841             s,
5842             [TcpRepr {
5843                 seq_number: LOCAL_SEQ + 1,
5844                 ack_number: Some(REMOTE_SEQ + 1 + 6),
5845                 window_len: 0,
5846                 ..RECV_TEMPL
5847             }]
5848         );
5849         send!(
5850             s,
5851             TcpRepr {
5852                 seq_number: REMOTE_SEQ + 1 + 6,
5853                 ack_number: Some(LOCAL_SEQ + 1),
5854                 payload: &b"123456"[..],
5855                 ..SEND_TEMPL
5856             },
5857             Some(TcpRepr {
5858                 seq_number: LOCAL_SEQ + 1,
5859                 ack_number: Some(REMOTE_SEQ + 1 + 6),
5860                 window_len: 0,
5861                 ..RECV_TEMPL
5862             })
5863         );
5864     }
5865 
5866     #[test]
test_zero_window_ack_on_window_growth()5867     fn test_zero_window_ack_on_window_growth() {
5868         let mut s = socket_established();
5869         s.rx_buffer = SocketBuffer::new(vec![0; 6]);
5870         s.assembler = Assembler::new();
5871         send!(
5872             s,
5873             TcpRepr {
5874                 seq_number: REMOTE_SEQ + 1,
5875                 ack_number: Some(LOCAL_SEQ + 1),
5876                 payload: &b"abcdef"[..],
5877                 ..SEND_TEMPL
5878             }
5879         );
5880         recv!(
5881             s,
5882             [TcpRepr {
5883                 seq_number: LOCAL_SEQ + 1,
5884                 ack_number: Some(REMOTE_SEQ + 1 + 6),
5885                 window_len: 0,
5886                 ..RECV_TEMPL
5887             }]
5888         );
5889         recv_nothing!(s, time 0);
5890         s.recv(|buffer| {
5891             assert_eq!(&buffer[..3], b"abc");
5892             (3, ())
5893         })
5894         .unwrap();
5895         recv!(s, time 0, Ok(TcpRepr {
5896             seq_number: LOCAL_SEQ + 1,
5897             ack_number: Some(REMOTE_SEQ + 1 + 6),
5898             window_len: 3,
5899             ..RECV_TEMPL
5900         }));
5901         recv_nothing!(s, time 0);
5902         s.recv(|buffer| {
5903             assert_eq!(buffer, b"def");
5904             (buffer.len(), ())
5905         })
5906         .unwrap();
5907         recv!(s, time 0, Ok(TcpRepr {
5908             seq_number: LOCAL_SEQ + 1,
5909             ack_number: Some(REMOTE_SEQ + 1 + 6),
5910             window_len: 6,
5911             ..RECV_TEMPL
5912         }));
5913     }
5914 
5915     #[test]
test_fill_peer_window()5916     fn test_fill_peer_window() {
5917         let mut s = socket_established();
5918         s.remote_mss = 6;
5919         s.send_slice(b"abcdef123456!@#$%^").unwrap();
5920         recv!(
5921             s,
5922             [
5923                 TcpRepr {
5924                     seq_number: LOCAL_SEQ + 1,
5925                     ack_number: Some(REMOTE_SEQ + 1),
5926                     payload: &b"abcdef"[..],
5927                     ..RECV_TEMPL
5928                 },
5929                 TcpRepr {
5930                     seq_number: LOCAL_SEQ + 1 + 6,
5931                     ack_number: Some(REMOTE_SEQ + 1),
5932                     payload: &b"123456"[..],
5933                     ..RECV_TEMPL
5934                 },
5935                 TcpRepr {
5936                     seq_number: LOCAL_SEQ + 1 + 6 + 6,
5937                     ack_number: Some(REMOTE_SEQ + 1),
5938                     payload: &b"!@#$%^"[..],
5939                     ..RECV_TEMPL
5940                 }
5941             ]
5942         );
5943     }
5944 
5945     #[test]
test_announce_window_after_read()5946     fn test_announce_window_after_read() {
5947         let mut s = socket_established();
5948         s.rx_buffer = SocketBuffer::new(vec![0; 6]);
5949         s.assembler = Assembler::new();
5950         send!(
5951             s,
5952             TcpRepr {
5953                 seq_number: REMOTE_SEQ + 1,
5954                 ack_number: Some(LOCAL_SEQ + 1),
5955                 payload: &b"abc"[..],
5956                 ..SEND_TEMPL
5957             }
5958         );
5959         recv!(
5960             s,
5961             [TcpRepr {
5962                 seq_number: LOCAL_SEQ + 1,
5963                 ack_number: Some(REMOTE_SEQ + 1 + 3),
5964                 window_len: 3,
5965                 ..RECV_TEMPL
5966             }]
5967         );
5968         // Test that `dispatch` updates `remote_last_win`
5969         assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
5970         s.recv(|buffer| (buffer.len(), ())).unwrap();
5971         assert!(s.window_to_update());
5972         recv!(
5973             s,
5974             [TcpRepr {
5975                 seq_number: LOCAL_SEQ + 1,
5976                 ack_number: Some(REMOTE_SEQ + 1 + 3),
5977                 window_len: 6,
5978                 ..RECV_TEMPL
5979             }]
5980         );
5981         assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
5982         // Provoke immediate ACK to test that `process` updates `remote_last_win`
5983         send!(
5984             s,
5985             TcpRepr {
5986                 seq_number: REMOTE_SEQ + 1 + 6,
5987                 ack_number: Some(LOCAL_SEQ + 1),
5988                 payload: &b"def"[..],
5989                 ..SEND_TEMPL
5990             },
5991             Some(TcpRepr {
5992                 seq_number: LOCAL_SEQ + 1,
5993                 ack_number: Some(REMOTE_SEQ + 1 + 3),
5994                 window_len: 6,
5995                 ..RECV_TEMPL
5996             })
5997         );
5998         send!(
5999             s,
6000             TcpRepr {
6001                 seq_number: REMOTE_SEQ + 1 + 3,
6002                 ack_number: Some(LOCAL_SEQ + 1),
6003                 payload: &b"abc"[..],
6004                 ..SEND_TEMPL
6005             },
6006             Some(TcpRepr {
6007                 seq_number: LOCAL_SEQ + 1,
6008                 ack_number: Some(REMOTE_SEQ + 1 + 9),
6009                 window_len: 0,
6010                 ..RECV_TEMPL
6011             })
6012         );
6013         assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
6014         s.recv(|buffer| (buffer.len(), ())).unwrap();
6015         assert!(s.window_to_update());
6016     }
6017 
6018     // =========================================================================================//
6019     // Tests for timeouts.
6020     // =========================================================================================//
6021 
6022     #[test]
test_listen_timeout()6023     fn test_listen_timeout() {
6024         let mut s = socket_listen();
6025         s.set_timeout(Some(Duration::from_millis(100)));
6026         assert_eq!(s.socket.poll_at(&mut s.cx), PollAt::Ingress);
6027     }
6028 
6029     #[test]
test_connect_timeout()6030     fn test_connect_timeout() {
6031         let mut s = socket();
6032         s.local_seq_no = LOCAL_SEQ;
6033         s.socket
6034             .connect(&mut s.cx, REMOTE_END, LOCAL_END.port)
6035             .unwrap();
6036         s.set_timeout(Some(Duration::from_millis(100)));
6037         recv!(s, time 150, Ok(TcpRepr {
6038             control:    TcpControl::Syn,
6039             seq_number: LOCAL_SEQ,
6040             ack_number: None,
6041             max_seg_size: Some(BASE_MSS),
6042             window_scale: Some(0),
6043             sack_permitted: true,
6044             ..RECV_TEMPL
6045         }));
6046         assert_eq!(s.state, State::SynSent);
6047         assert_eq!(
6048             s.socket.poll_at(&mut s.cx),
6049             PollAt::Time(Instant::from_millis(250))
6050         );
6051         recv!(s, time 250, Ok(TcpRepr {
6052             control:    TcpControl::Rst,
6053             seq_number: LOCAL_SEQ + 1,
6054             ack_number: Some(TcpSeqNumber(0)),
6055             window_scale: None,
6056             ..RECV_TEMPL
6057         }));
6058         assert_eq!(s.state, State::Closed);
6059     }
6060 
6061     #[test]
test_established_timeout()6062     fn test_established_timeout() {
6063         let mut s = socket_established();
6064         s.set_timeout(Some(Duration::from_millis(1000)));
6065         recv_nothing!(s, time 250);
6066         assert_eq!(
6067             s.socket.poll_at(&mut s.cx),
6068             PollAt::Time(Instant::from_millis(1250))
6069         );
6070         s.send_slice(b"abcdef").unwrap();
6071         assert_eq!(s.socket.poll_at(&mut s.cx), PollAt::Now);
6072         recv!(s, time 255, Ok(TcpRepr {
6073             seq_number: LOCAL_SEQ + 1,
6074             ack_number: Some(REMOTE_SEQ + 1),
6075             payload:    &b"abcdef"[..],
6076             ..RECV_TEMPL
6077         }));
6078         assert_eq!(
6079             s.socket.poll_at(&mut s.cx),
6080             PollAt::Time(Instant::from_millis(955))
6081         );
6082         recv!(s, time 955, Ok(TcpRepr {
6083             seq_number: LOCAL_SEQ + 1,
6084             ack_number: Some(REMOTE_SEQ + 1),
6085             payload:    &b"abcdef"[..],
6086             ..RECV_TEMPL
6087         }));
6088         assert_eq!(
6089             s.socket.poll_at(&mut s.cx),
6090             PollAt::Time(Instant::from_millis(1255))
6091         );
6092         recv!(s, time 1255, Ok(TcpRepr {
6093             control:    TcpControl::Rst,
6094             seq_number: LOCAL_SEQ + 1 + 6,
6095             ack_number: Some(REMOTE_SEQ + 1),
6096             ..RECV_TEMPL
6097         }));
6098         assert_eq!(s.state, State::Closed);
6099     }
6100 
6101     #[test]
test_established_keep_alive_timeout()6102     fn test_established_keep_alive_timeout() {
6103         let mut s = socket_established();
6104         s.set_keep_alive(Some(Duration::from_millis(50)));
6105         s.set_timeout(Some(Duration::from_millis(100)));
6106         recv!(s, time 100, Ok(TcpRepr {
6107             seq_number: LOCAL_SEQ,
6108             ack_number: Some(REMOTE_SEQ + 1),
6109             payload:    &[0],
6110             ..RECV_TEMPL
6111         }));
6112         recv_nothing!(s, time 100);
6113         assert_eq!(
6114             s.socket.poll_at(&mut s.cx),
6115             PollAt::Time(Instant::from_millis(150))
6116         );
6117         send!(s, time 105, TcpRepr {
6118             seq_number: REMOTE_SEQ + 1,
6119             ack_number: Some(LOCAL_SEQ + 1),
6120             ..SEND_TEMPL
6121         });
6122         assert_eq!(
6123             s.socket.poll_at(&mut s.cx),
6124             PollAt::Time(Instant::from_millis(155))
6125         );
6126         recv!(s, time 155, Ok(TcpRepr {
6127             seq_number: LOCAL_SEQ,
6128             ack_number: Some(REMOTE_SEQ + 1),
6129             payload:    &[0],
6130             ..RECV_TEMPL
6131         }));
6132         recv_nothing!(s, time 155);
6133         assert_eq!(
6134             s.socket.poll_at(&mut s.cx),
6135             PollAt::Time(Instant::from_millis(205))
6136         );
6137         recv_nothing!(s, time 200);
6138         recv!(s, time 205, Ok(TcpRepr {
6139             control:    TcpControl::Rst,
6140             seq_number: LOCAL_SEQ + 1,
6141             ack_number: Some(REMOTE_SEQ + 1),
6142             ..RECV_TEMPL
6143         }));
6144         recv_nothing!(s, time 205);
6145         assert_eq!(s.state, State::Closed);
6146     }
6147 
6148     #[test]
test_fin_wait_1_timeout()6149     fn test_fin_wait_1_timeout() {
6150         let mut s = socket_fin_wait_1();
6151         s.set_timeout(Some(Duration::from_millis(1000)));
6152         recv!(s, time 100, Ok(TcpRepr {
6153             control:    TcpControl::Fin,
6154             seq_number: LOCAL_SEQ + 1,
6155             ack_number: Some(REMOTE_SEQ + 1),
6156             ..RECV_TEMPL
6157         }));
6158         recv!(s, time 1100, Ok(TcpRepr {
6159             control:    TcpControl::Rst,
6160             seq_number: LOCAL_SEQ + 1 + 1,
6161             ack_number: Some(REMOTE_SEQ + 1),
6162             ..RECV_TEMPL
6163         }));
6164         assert_eq!(s.state, State::Closed);
6165     }
6166 
6167     #[test]
test_last_ack_timeout()6168     fn test_last_ack_timeout() {
6169         let mut s = socket_last_ack();
6170         s.set_timeout(Some(Duration::from_millis(1000)));
6171         recv!(s, time 100, Ok(TcpRepr {
6172             control:    TcpControl::Fin,
6173             seq_number: LOCAL_SEQ + 1,
6174             ack_number: Some(REMOTE_SEQ + 1 + 1),
6175             ..RECV_TEMPL
6176         }));
6177         recv!(s, time 1100, Ok(TcpRepr {
6178             control:    TcpControl::Rst,
6179             seq_number: LOCAL_SEQ + 1 + 1,
6180             ack_number: Some(REMOTE_SEQ + 1 + 1),
6181             ..RECV_TEMPL
6182         }));
6183         assert_eq!(s.state, State::Closed);
6184     }
6185 
6186     #[test]
test_closed_timeout()6187     fn test_closed_timeout() {
6188         let mut s = socket_established();
6189         s.set_timeout(Some(Duration::from_millis(200)));
6190         s.remote_last_ts = Some(Instant::from_millis(100));
6191         s.abort();
6192         assert_eq!(s.socket.poll_at(&mut s.cx), PollAt::Now);
6193         recv!(s, time 100, Ok(TcpRepr {
6194             control:    TcpControl::Rst,
6195             seq_number: LOCAL_SEQ + 1,
6196             ack_number: Some(REMOTE_SEQ + 1),
6197             ..RECV_TEMPL
6198         }));
6199         assert_eq!(s.socket.poll_at(&mut s.cx), PollAt::Ingress);
6200     }
6201 
6202     // =========================================================================================//
6203     // Tests for keep-alive.
6204     // =========================================================================================//
6205 
6206     #[test]
test_responds_to_keep_alive()6207     fn test_responds_to_keep_alive() {
6208         let mut s = socket_established();
6209         send!(
6210             s,
6211             TcpRepr {
6212                 seq_number: REMOTE_SEQ,
6213                 ack_number: Some(LOCAL_SEQ + 1),
6214                 ..SEND_TEMPL
6215             },
6216             Some(TcpRepr {
6217                 seq_number: LOCAL_SEQ + 1,
6218                 ack_number: Some(REMOTE_SEQ + 1),
6219                 ..RECV_TEMPL
6220             })
6221         );
6222     }
6223 
6224     #[test]
test_sends_keep_alive()6225     fn test_sends_keep_alive() {
6226         let mut s = socket_established();
6227         s.set_keep_alive(Some(Duration::from_millis(100)));
6228 
6229         // drain the forced keep-alive packet
6230         assert_eq!(s.socket.poll_at(&mut s.cx), PollAt::Now);
6231         recv!(s, time 0, Ok(TcpRepr {
6232             seq_number: LOCAL_SEQ,
6233             ack_number: Some(REMOTE_SEQ + 1),
6234             payload:    &[0],
6235             ..RECV_TEMPL
6236         }));
6237 
6238         assert_eq!(
6239             s.socket.poll_at(&mut s.cx),
6240             PollAt::Time(Instant::from_millis(100))
6241         );
6242         recv_nothing!(s, time 95);
6243         recv!(s, time 100, Ok(TcpRepr {
6244             seq_number: LOCAL_SEQ,
6245             ack_number: Some(REMOTE_SEQ + 1),
6246             payload:    &[0],
6247             ..RECV_TEMPL
6248         }));
6249 
6250         assert_eq!(
6251             s.socket.poll_at(&mut s.cx),
6252             PollAt::Time(Instant::from_millis(200))
6253         );
6254         recv_nothing!(s, time 195);
6255         recv!(s, time 200, Ok(TcpRepr {
6256             seq_number: LOCAL_SEQ,
6257             ack_number: Some(REMOTE_SEQ + 1),
6258             payload:    &[0],
6259             ..RECV_TEMPL
6260         }));
6261 
6262         send!(s, time 250, TcpRepr {
6263             seq_number: REMOTE_SEQ + 1,
6264             ack_number: Some(LOCAL_SEQ + 1),
6265             ..SEND_TEMPL
6266         });
6267         assert_eq!(
6268             s.socket.poll_at(&mut s.cx),
6269             PollAt::Time(Instant::from_millis(350))
6270         );
6271         recv_nothing!(s, time 345);
6272         recv!(s, time 350, Ok(TcpRepr {
6273             seq_number: LOCAL_SEQ,
6274             ack_number: Some(REMOTE_SEQ + 1),
6275             payload:    &b"\x00"[..],
6276             ..RECV_TEMPL
6277         }));
6278     }
6279 
6280     // =========================================================================================//
6281     // Tests for time-to-live configuration.
6282     // =========================================================================================//
6283 
6284     #[test]
test_set_hop_limit()6285     fn test_set_hop_limit() {
6286         let mut s = socket_syn_received();
6287 
6288         s.set_hop_limit(Some(0x2a));
6289         assert_eq!(
6290             s.socket.dispatch(&mut s.cx, |_, (ip_repr, _)| {
6291                 assert_eq!(ip_repr.hop_limit(), 0x2a);
6292                 Ok::<_, ()>(())
6293             }),
6294             Ok(())
6295         );
6296 
6297         // assert that user-configurable settings are kept,
6298         // see https://github.com/smoltcp-rs/smoltcp/issues/601.
6299         s.reset();
6300         assert_eq!(s.hop_limit(), Some(0x2a));
6301     }
6302 
6303     #[test]
6304     #[should_panic(expected = "the time-to-live value of a packet must not be zero")]
test_set_hop_limit_zero()6305     fn test_set_hop_limit_zero() {
6306         let mut s = socket_syn_received();
6307         s.set_hop_limit(Some(0));
6308     }
6309 
6310     // =========================================================================================//
6311     // Tests for reassembly.
6312     // =========================================================================================//
6313 
6314     #[test]
test_out_of_order()6315     fn test_out_of_order() {
6316         let mut s = socket_established();
6317         send!(
6318             s,
6319             TcpRepr {
6320                 seq_number: REMOTE_SEQ + 1 + 3,
6321                 ack_number: Some(LOCAL_SEQ + 1),
6322                 payload: &b"def"[..],
6323                 ..SEND_TEMPL
6324             },
6325             Some(TcpRepr {
6326                 seq_number: LOCAL_SEQ + 1,
6327                 ack_number: Some(REMOTE_SEQ + 1),
6328                 ..RECV_TEMPL
6329             })
6330         );
6331         s.recv(|buffer| {
6332             assert_eq!(buffer, b"");
6333             (buffer.len(), ())
6334         })
6335         .unwrap();
6336         send!(
6337             s,
6338             TcpRepr {
6339                 seq_number: REMOTE_SEQ + 1,
6340                 ack_number: Some(LOCAL_SEQ + 1),
6341                 payload: &b"abcdef"[..],
6342                 ..SEND_TEMPL
6343             },
6344             Some(TcpRepr {
6345                 seq_number: LOCAL_SEQ + 1,
6346                 ack_number: Some(REMOTE_SEQ + 1 + 6),
6347                 window_len: 58,
6348                 ..RECV_TEMPL
6349             })
6350         );
6351         s.recv(|buffer| {
6352             assert_eq!(buffer, b"abcdef");
6353             (buffer.len(), ())
6354         })
6355         .unwrap();
6356     }
6357 
6358     #[test]
test_buffer_wraparound_rx()6359     fn test_buffer_wraparound_rx() {
6360         let mut s = socket_established();
6361         s.rx_buffer = SocketBuffer::new(vec![0; 6]);
6362         s.assembler = Assembler::new();
6363         send!(
6364             s,
6365             TcpRepr {
6366                 seq_number: REMOTE_SEQ + 1,
6367                 ack_number: Some(LOCAL_SEQ + 1),
6368                 payload: &b"abc"[..],
6369                 ..SEND_TEMPL
6370             }
6371         );
6372         s.recv(|buffer| {
6373             assert_eq!(buffer, b"abc");
6374             (buffer.len(), ())
6375         })
6376         .unwrap();
6377         send!(
6378             s,
6379             TcpRepr {
6380                 seq_number: REMOTE_SEQ + 1 + 3,
6381                 ack_number: Some(LOCAL_SEQ + 1),
6382                 payload: &b"defghi"[..],
6383                 ..SEND_TEMPL
6384             }
6385         );
6386         let mut data = [0; 6];
6387         assert_eq!(s.recv_slice(&mut data[..]), Ok(6));
6388         assert_eq!(data, &b"defghi"[..]);
6389     }
6390 
6391     #[test]
test_buffer_wraparound_tx()6392     fn test_buffer_wraparound_tx() {
6393         let mut s = socket_established();
6394         s.set_nagle_enabled(false);
6395 
6396         s.tx_buffer = SocketBuffer::new(vec![b'.'; 9]);
6397         assert_eq!(s.send_slice(b"xxxyyy"), Ok(6));
6398         assert_eq!(s.tx_buffer.dequeue_many(3), &b"xxx"[..]);
6399         assert_eq!(s.tx_buffer.len(), 3);
6400 
6401         // "abcdef" not contiguous in tx buffer
6402         assert_eq!(s.send_slice(b"abcdef"), Ok(6));
6403         recv!(
6404             s,
6405             Ok(TcpRepr {
6406                 seq_number: LOCAL_SEQ + 1,
6407                 ack_number: Some(REMOTE_SEQ + 1),
6408                 payload: &b"yyyabc"[..],
6409                 ..RECV_TEMPL
6410             })
6411         );
6412         recv!(
6413             s,
6414             Ok(TcpRepr {
6415                 seq_number: LOCAL_SEQ + 1 + 6,
6416                 ack_number: Some(REMOTE_SEQ + 1),
6417                 payload: &b"def"[..],
6418                 ..RECV_TEMPL
6419             })
6420         );
6421     }
6422 
6423     // =========================================================================================//
6424     // Tests for graceful vs ungraceful rx close
6425     // =========================================================================================//
6426 
6427     #[test]
test_rx_close_fin()6428     fn test_rx_close_fin() {
6429         let mut s = socket_established();
6430         send!(
6431             s,
6432             TcpRepr {
6433                 control: TcpControl::Fin,
6434                 seq_number: REMOTE_SEQ + 1,
6435                 ack_number: Some(LOCAL_SEQ + 1),
6436                 payload: &b"abc"[..],
6437                 ..SEND_TEMPL
6438             }
6439         );
6440         s.recv(|data| {
6441             assert_eq!(data, b"abc");
6442             (3, ())
6443         })
6444         .unwrap();
6445         assert_eq!(s.recv(|_| (0, ())), Err(RecvError::Finished));
6446     }
6447 
6448     #[test]
test_rx_close_fin_in_fin_wait_1()6449     fn test_rx_close_fin_in_fin_wait_1() {
6450         let mut s = socket_fin_wait_1();
6451         send!(
6452             s,
6453             TcpRepr {
6454                 control: TcpControl::Fin,
6455                 seq_number: REMOTE_SEQ + 1,
6456                 ack_number: Some(LOCAL_SEQ + 1),
6457                 payload: &b"abc"[..],
6458                 ..SEND_TEMPL
6459             }
6460         );
6461         assert_eq!(s.state, State::Closing);
6462         s.recv(|data| {
6463             assert_eq!(data, b"abc");
6464             (3, ())
6465         })
6466         .unwrap();
6467         assert_eq!(s.recv(|_| (0, ())), Err(RecvError::Finished));
6468     }
6469 
6470     #[test]
test_rx_close_fin_in_fin_wait_2()6471     fn test_rx_close_fin_in_fin_wait_2() {
6472         let mut s = socket_fin_wait_2();
6473         send!(
6474             s,
6475             TcpRepr {
6476                 control: TcpControl::Fin,
6477                 seq_number: REMOTE_SEQ + 1,
6478                 ack_number: Some(LOCAL_SEQ + 1 + 1),
6479                 payload: &b"abc"[..],
6480                 ..SEND_TEMPL
6481             }
6482         );
6483         assert_eq!(s.state, State::TimeWait);
6484         s.recv(|data| {
6485             assert_eq!(data, b"abc");
6486             (3, ())
6487         })
6488         .unwrap();
6489         assert_eq!(s.recv(|_| (0, ())), Err(RecvError::Finished));
6490     }
6491 
6492     #[test]
test_rx_close_fin_with_hole()6493     fn test_rx_close_fin_with_hole() {
6494         let mut s = socket_established();
6495         send!(
6496             s,
6497             TcpRepr {
6498                 seq_number: REMOTE_SEQ + 1,
6499                 ack_number: Some(LOCAL_SEQ + 1),
6500                 payload: &b"abc"[..],
6501                 ..SEND_TEMPL
6502             }
6503         );
6504         send!(
6505             s,
6506             TcpRepr {
6507                 control: TcpControl::Fin,
6508                 seq_number: REMOTE_SEQ + 1 + 6,
6509                 ack_number: Some(LOCAL_SEQ + 1),
6510                 payload: &b"ghi"[..],
6511                 ..SEND_TEMPL
6512             },
6513             Some(TcpRepr {
6514                 seq_number: LOCAL_SEQ + 1,
6515                 ack_number: Some(REMOTE_SEQ + 1 + 3),
6516                 window_len: 61,
6517                 ..RECV_TEMPL
6518             })
6519         );
6520         s.recv(|data| {
6521             assert_eq!(data, b"abc");
6522             (3, ())
6523         })
6524         .unwrap();
6525         s.recv(|data| {
6526             assert_eq!(data, b"");
6527             (0, ())
6528         })
6529         .unwrap();
6530         send!(
6531             s,
6532             TcpRepr {
6533                 control: TcpControl::Rst,
6534                 seq_number: REMOTE_SEQ + 1 + 9,
6535                 ack_number: Some(LOCAL_SEQ + 1),
6536                 ..SEND_TEMPL
6537             }
6538         );
6539         // Error must be `Illegal` even if we've received a FIN,
6540         // because we are missing data.
6541         assert_eq!(s.recv(|_| (0, ())), Err(RecvError::InvalidState));
6542     }
6543 
6544     #[test]
test_rx_close_rst()6545     fn test_rx_close_rst() {
6546         let mut s = socket_established();
6547         send!(
6548             s,
6549             TcpRepr {
6550                 seq_number: REMOTE_SEQ + 1,
6551                 ack_number: Some(LOCAL_SEQ + 1),
6552                 payload: &b"abc"[..],
6553                 ..SEND_TEMPL
6554             }
6555         );
6556         send!(
6557             s,
6558             TcpRepr {
6559                 control: TcpControl::Rst,
6560                 seq_number: REMOTE_SEQ + 1 + 3,
6561                 ack_number: Some(LOCAL_SEQ + 1),
6562                 ..SEND_TEMPL
6563             }
6564         );
6565         s.recv(|data| {
6566             assert_eq!(data, b"abc");
6567             (3, ())
6568         })
6569         .unwrap();
6570         assert_eq!(s.recv(|_| (0, ())), Err(RecvError::InvalidState));
6571     }
6572 
6573     #[test]
test_rx_close_rst_with_hole()6574     fn test_rx_close_rst_with_hole() {
6575         let mut s = socket_established();
6576         send!(
6577             s,
6578             TcpRepr {
6579                 seq_number: REMOTE_SEQ + 1,
6580                 ack_number: Some(LOCAL_SEQ + 1),
6581                 payload: &b"abc"[..],
6582                 ..SEND_TEMPL
6583             }
6584         );
6585         send!(
6586             s,
6587             TcpRepr {
6588                 seq_number: REMOTE_SEQ + 1 + 6,
6589                 ack_number: Some(LOCAL_SEQ + 1),
6590                 payload: &b"ghi"[..],
6591                 ..SEND_TEMPL
6592             },
6593             Some(TcpRepr {
6594                 seq_number: LOCAL_SEQ + 1,
6595                 ack_number: Some(REMOTE_SEQ + 1 + 3),
6596                 window_len: 61,
6597                 ..RECV_TEMPL
6598             })
6599         );
6600         send!(
6601             s,
6602             TcpRepr {
6603                 control: TcpControl::Rst,
6604                 seq_number: REMOTE_SEQ + 1 + 9,
6605                 ack_number: Some(LOCAL_SEQ + 1),
6606                 ..SEND_TEMPL
6607             }
6608         );
6609         s.recv(|data| {
6610             assert_eq!(data, b"abc");
6611             (3, ())
6612         })
6613         .unwrap();
6614         assert_eq!(s.recv(|_| (0, ())), Err(RecvError::InvalidState));
6615     }
6616 
6617     // =========================================================================================//
6618     // Tests for delayed ACK
6619     // =========================================================================================//
6620 
6621     #[test]
test_delayed_ack()6622     fn test_delayed_ack() {
6623         let mut s = socket_established();
6624         s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
6625         send!(
6626             s,
6627             TcpRepr {
6628                 seq_number: REMOTE_SEQ + 1,
6629                 ack_number: Some(LOCAL_SEQ + 1),
6630                 payload: &b"abc"[..],
6631                 ..SEND_TEMPL
6632             }
6633         );
6634 
6635         // No ACK is immediately sent.
6636         recv_nothing!(s);
6637 
6638         // After 10ms, it is sent.
6639         recv!(s, time 11, Ok(TcpRepr {
6640             seq_number: LOCAL_SEQ + 1,
6641             ack_number: Some(REMOTE_SEQ + 1 + 3),
6642             window_len: 61,
6643             ..RECV_TEMPL
6644         }));
6645     }
6646 
6647     #[test]
test_delayed_ack_win()6648     fn test_delayed_ack_win() {
6649         let mut s = socket_established();
6650         s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
6651         send!(
6652             s,
6653             TcpRepr {
6654                 seq_number: REMOTE_SEQ + 1,
6655                 ack_number: Some(LOCAL_SEQ + 1),
6656                 payload: &b"abc"[..],
6657                 ..SEND_TEMPL
6658             }
6659         );
6660 
6661         // Reading the data off the buffer should cause a window update.
6662         s.recv(|data| {
6663             assert_eq!(data, b"abc");
6664             (3, ())
6665         })
6666         .unwrap();
6667 
6668         // However, no ACK or window update is immediately sent.
6669         recv_nothing!(s);
6670 
6671         // After 10ms, it is sent.
6672         recv!(s, time 11, Ok(TcpRepr {
6673             seq_number: LOCAL_SEQ + 1,
6674             ack_number: Some(REMOTE_SEQ + 1 + 3),
6675             ..RECV_TEMPL
6676         }));
6677     }
6678 
6679     #[test]
test_delayed_ack_reply()6680     fn test_delayed_ack_reply() {
6681         let mut s = socket_established();
6682         s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
6683         send!(
6684             s,
6685             TcpRepr {
6686                 seq_number: REMOTE_SEQ + 1,
6687                 ack_number: Some(LOCAL_SEQ + 1),
6688                 payload: &b"abc"[..],
6689                 ..SEND_TEMPL
6690             }
6691         );
6692 
6693         s.recv(|data| {
6694             assert_eq!(data, b"abc");
6695             (3, ())
6696         })
6697         .unwrap();
6698 
6699         s.send_slice(&b"xyz"[..]).unwrap();
6700 
6701         // Writing data to the socket causes ACK to not be delayed,
6702         // because it is immediately sent with the data.
6703         recv!(
6704             s,
6705             Ok(TcpRepr {
6706                 seq_number: LOCAL_SEQ + 1,
6707                 ack_number: Some(REMOTE_SEQ + 1 + 3),
6708                 payload: &b"xyz"[..],
6709                 ..RECV_TEMPL
6710             })
6711         );
6712     }
6713 
6714     #[test]
test_delayed_ack_every_second_packet()6715     fn test_delayed_ack_every_second_packet() {
6716         let mut s = socket_established();
6717         s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
6718         send!(
6719             s,
6720             TcpRepr {
6721                 seq_number: REMOTE_SEQ + 1,
6722                 ack_number: Some(LOCAL_SEQ + 1),
6723                 payload: &b"abc"[..],
6724                 ..SEND_TEMPL
6725             }
6726         );
6727 
6728         // No ACK is immediately sent.
6729         recv_nothing!(s);
6730 
6731         send!(
6732             s,
6733             TcpRepr {
6734                 seq_number: REMOTE_SEQ + 1 + 3,
6735                 ack_number: Some(LOCAL_SEQ + 1),
6736                 payload: &b"def"[..],
6737                 ..SEND_TEMPL
6738             }
6739         );
6740 
6741         // Every 2nd packet, ACK is sent without delay.
6742         recv!(
6743             s,
6744             Ok(TcpRepr {
6745                 seq_number: LOCAL_SEQ + 1,
6746                 ack_number: Some(REMOTE_SEQ + 1 + 6),
6747                 window_len: 58,
6748                 ..RECV_TEMPL
6749             })
6750         );
6751     }
6752 
6753     #[test]
test_delayed_ack_three_packets()6754     fn test_delayed_ack_three_packets() {
6755         let mut s = socket_established();
6756         s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
6757         send!(
6758             s,
6759             TcpRepr {
6760                 seq_number: REMOTE_SEQ + 1,
6761                 ack_number: Some(LOCAL_SEQ + 1),
6762                 payload: &b"abc"[..],
6763                 ..SEND_TEMPL
6764             }
6765         );
6766 
6767         // No ACK is immediately sent.
6768         recv_nothing!(s);
6769 
6770         send!(
6771             s,
6772             TcpRepr {
6773                 seq_number: REMOTE_SEQ + 1 + 3,
6774                 ack_number: Some(LOCAL_SEQ + 1),
6775                 payload: &b"def"[..],
6776                 ..SEND_TEMPL
6777             }
6778         );
6779 
6780         send!(
6781             s,
6782             TcpRepr {
6783                 seq_number: REMOTE_SEQ + 1 + 6,
6784                 ack_number: Some(LOCAL_SEQ + 1),
6785                 payload: &b"ghi"[..],
6786                 ..SEND_TEMPL
6787             }
6788         );
6789 
6790         // Every 2nd (or more) packet, ACK is sent without delay.
6791         recv!(
6792             s,
6793             Ok(TcpRepr {
6794                 seq_number: LOCAL_SEQ + 1,
6795                 ack_number: Some(REMOTE_SEQ + 1 + 9),
6796                 window_len: 55,
6797                 ..RECV_TEMPL
6798             })
6799         );
6800     }
6801 
6802     // =========================================================================================//
6803     // Tests for Nagle's Algorithm
6804     // =========================================================================================//
6805 
6806     #[test]
test_nagle()6807     fn test_nagle() {
6808         let mut s = socket_established();
6809         s.remote_mss = 6;
6810 
6811         s.send_slice(b"abcdef").unwrap();
6812         recv!(
6813             s,
6814             [TcpRepr {
6815                 seq_number: LOCAL_SEQ + 1,
6816                 ack_number: Some(REMOTE_SEQ + 1),
6817                 payload: &b"abcdef"[..],
6818                 ..RECV_TEMPL
6819             }]
6820         );
6821 
6822         // If there's data in flight, full segments get sent.
6823         s.send_slice(b"foobar").unwrap();
6824         recv!(
6825             s,
6826             [TcpRepr {
6827                 seq_number: LOCAL_SEQ + 1 + 6,
6828                 ack_number: Some(REMOTE_SEQ + 1),
6829                 payload: &b"foobar"[..],
6830                 ..RECV_TEMPL
6831             }]
6832         );
6833 
6834         s.send_slice(b"aaabbbccc").unwrap();
6835         // If there's data in flight, not-full segments don't get sent.
6836         recv!(
6837             s,
6838             [TcpRepr {
6839                 seq_number: LOCAL_SEQ + 1 + 6 + 6,
6840                 ack_number: Some(REMOTE_SEQ + 1),
6841                 payload: &b"aaabbb"[..],
6842                 ..RECV_TEMPL
6843             }]
6844         );
6845 
6846         // Data gets ACKd, so there's no longer data in flight
6847         send!(
6848             s,
6849             TcpRepr {
6850                 seq_number: REMOTE_SEQ + 1,
6851                 ack_number: Some(LOCAL_SEQ + 1 + 6 + 6 + 6),
6852                 ..SEND_TEMPL
6853             }
6854         );
6855 
6856         // Now non-full segment gets sent.
6857         recv!(
6858             s,
6859             [TcpRepr {
6860                 seq_number: LOCAL_SEQ + 1 + 6 + 6 + 6,
6861                 ack_number: Some(REMOTE_SEQ + 1),
6862                 payload: &b"ccc"[..],
6863                 ..RECV_TEMPL
6864             }]
6865         );
6866     }
6867 
6868     #[test]
test_final_packet_in_stream_doesnt_wait_for_nagle()6869     fn test_final_packet_in_stream_doesnt_wait_for_nagle() {
6870         let mut s = socket_established();
6871         s.remote_mss = 6;
6872         s.send_slice(b"abcdef0").unwrap();
6873         s.socket.close();
6874 
6875         recv!(s, time 0, Ok(TcpRepr {
6876             control:    TcpControl::None,
6877             seq_number: LOCAL_SEQ + 1,
6878             ack_number: Some(REMOTE_SEQ + 1),
6879             payload:    &b"abcdef"[..],
6880             ..RECV_TEMPL
6881         }), exact);
6882         recv!(s, time 0, Ok(TcpRepr {
6883             control:    TcpControl::Fin,
6884             seq_number: LOCAL_SEQ + 1 + 6,
6885             ack_number: Some(REMOTE_SEQ + 1),
6886             payload:    &b"0"[..],
6887             ..RECV_TEMPL
6888         }), exact);
6889     }
6890 
6891     // =========================================================================================//
6892     // Tests for packet filtering.
6893     // =========================================================================================//
6894 
6895     #[test]
test_doesnt_accept_wrong_port()6896     fn test_doesnt_accept_wrong_port() {
6897         let mut s = socket_established();
6898         s.rx_buffer = SocketBuffer::new(vec![0; 6]);
6899         s.assembler = Assembler::new();
6900 
6901         let tcp_repr = TcpRepr {
6902             seq_number: REMOTE_SEQ + 1,
6903             ack_number: Some(LOCAL_SEQ + 1),
6904             dst_port: LOCAL_PORT + 1,
6905             ..SEND_TEMPL
6906         };
6907         assert!(!s.socket.accepts(&mut s.cx, &SEND_IP_TEMPL, &tcp_repr));
6908 
6909         let tcp_repr = TcpRepr {
6910             seq_number: REMOTE_SEQ + 1,
6911             ack_number: Some(LOCAL_SEQ + 1),
6912             src_port: REMOTE_PORT + 1,
6913             ..SEND_TEMPL
6914         };
6915         assert!(!s.socket.accepts(&mut s.cx, &SEND_IP_TEMPL, &tcp_repr));
6916     }
6917 
6918     #[test]
test_doesnt_accept_wrong_ip()6919     fn test_doesnt_accept_wrong_ip() {
6920         let mut s = socket_established();
6921 
6922         let tcp_repr = TcpRepr {
6923             seq_number: REMOTE_SEQ + 1,
6924             ack_number: Some(LOCAL_SEQ + 1),
6925             payload: &b"abcdef"[..],
6926             ..SEND_TEMPL
6927         };
6928 
6929         let ip_repr = IpReprIpvX(IpvXRepr {
6930             src_addr: REMOTE_ADDR,
6931             dst_addr: LOCAL_ADDR,
6932             next_header: IpProtocol::Tcp,
6933             payload_len: tcp_repr.buffer_len(),
6934             hop_limit: 64,
6935         });
6936         assert!(s.socket.accepts(&mut s.cx, &ip_repr, &tcp_repr));
6937 
6938         let ip_repr_wrong_src = IpReprIpvX(IpvXRepr {
6939             src_addr: OTHER_ADDR,
6940             dst_addr: LOCAL_ADDR,
6941             next_header: IpProtocol::Tcp,
6942             payload_len: tcp_repr.buffer_len(),
6943             hop_limit: 64,
6944         });
6945         assert!(!s.socket.accepts(&mut s.cx, &ip_repr_wrong_src, &tcp_repr));
6946 
6947         let ip_repr_wrong_dst = IpReprIpvX(IpvXRepr {
6948             src_addr: REMOTE_ADDR,
6949             dst_addr: OTHER_ADDR,
6950             next_header: IpProtocol::Tcp,
6951             payload_len: tcp_repr.buffer_len(),
6952             hop_limit: 64,
6953         });
6954         assert!(!s.socket.accepts(&mut s.cx, &ip_repr_wrong_dst, &tcp_repr));
6955     }
6956 
6957     // =========================================================================================//
6958     // Timer tests
6959     // =========================================================================================//
6960 
6961     #[test]
test_timer_retransmit()6962     fn test_timer_retransmit() {
6963         const RTO: Duration = Duration::from_millis(100);
6964         let mut r = Timer::new();
6965         assert_eq!(r.should_retransmit(Instant::from_secs(1)), None);
6966         r.set_for_retransmit(Instant::from_millis(1000), RTO);
6967         assert_eq!(r.should_retransmit(Instant::from_millis(1000)), None);
6968         assert_eq!(r.should_retransmit(Instant::from_millis(1050)), None);
6969         assert_eq!(
6970             r.should_retransmit(Instant::from_millis(1101)),
6971             Some(Duration::from_millis(101))
6972         );
6973         r.set_for_retransmit(Instant::from_millis(1101), RTO);
6974         assert_eq!(r.should_retransmit(Instant::from_millis(1101)), None);
6975         assert_eq!(r.should_retransmit(Instant::from_millis(1150)), None);
6976         assert_eq!(r.should_retransmit(Instant::from_millis(1200)), None);
6977         assert_eq!(
6978             r.should_retransmit(Instant::from_millis(1301)),
6979             Some(Duration::from_millis(300))
6980         );
6981         r.set_for_idle(Instant::from_millis(1301), None);
6982         assert_eq!(r.should_retransmit(Instant::from_millis(1350)), None);
6983     }
6984 
6985     #[test]
test_rtt_estimator()6986     fn test_rtt_estimator() {
6987         let mut r = RttEstimator::default();
6988 
6989         let rtos = &[
6990             751, 766, 755, 731, 697, 656, 613, 567, 523, 484, 445, 411, 378, 350, 322, 299, 280,
6991             261, 243, 229, 215, 206, 197, 188,
6992         ];
6993 
6994         for &rto in rtos {
6995             r.sample(100);
6996             assert_eq!(r.retransmission_timeout(), Duration::from_millis(rto));
6997         }
6998     }
6999 }
7000