Skip to main content

netstack3_tcp/
socket.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Defines how TCP state machines are used for TCP sockets.
6//!
7//! TCP state machine implemented in the parent module aims to only implement
8//! RFC 793 which lacks posix semantics.
9//!
10//! To actually support posix-style sockets:
11//! We would need two kinds of active sockets, listeners/connections (or
12//! server sockets/client sockets; both are not very accurate terms, the key
13//! difference is that the former has only local addresses but the later has
14//! remote addresses in addition). [`Connection`]s are backed by a state
15//! machine, however the state can be in any state. [`Listener`]s don't have
16//! state machines, but they create [`Connection`]s that are backed by
17//! [`State::Listen`] an incoming SYN and keep track of whether the connection
18//! is established.
19
20pub(crate) mod accept_queue;
21pub(crate) mod demux;
22pub(crate) mod diagnostics;
23pub(crate) mod generators;
24
25use alloc::vec::Vec;
26use core::convert::Infallible as Never;
27use core::fmt::{self, Debug};
28use core::marker::PhantomData;
29use core::num::{NonZeroU16, NonZeroUsize};
30use core::ops::{Deref, DerefMut, RangeInclusive};
31
32use assert_matches::assert_matches;
33use derivative::Derivative;
34use lock_order::lock::{OrderedLockAccess, OrderedLockRef};
35use log::{debug, error, trace};
36use net_types::ip::{
37    GenericOverIp, Ip, IpAddr, IpAddress, IpVersion, IpVersionMarker, Ipv4, Ipv4Addr, Ipv6,
38    Ipv6Addr,
39};
40use net_types::{
41    AddrAndPortFormatter, AddrAndZone, MulticastAddress as _, SpecifiedAddr, ZonedAddr,
42};
43use netstack3_base::socket::{
44    self, AddrIsMappedError, AddrVec, Bound, ConnAddr, ConnIpAddr, DualStackListenerIpAddr,
45    DualStackLocalIp, DualStackRemoteIp, DualStackTuple, EitherStack, IncompatibleError,
46    InsertError, Inserter, ListenerAddr, ListenerAddrInfo, ListenerIpAddr, MaybeDualStack,
47    NotDualStackCapableError, RemoveResult, SetDualStackEnabledError, ShutdownType, SocketCookie,
48    SocketDeviceUpdate, SocketDeviceUpdateNotAllowedError, SocketIpAddr, SocketIpExt,
49    SocketMapAddrSpec, SocketMapAddrStateSpec, SocketMapAddrStateUpdateSharingSpec,
50    SocketMapConflictPolicy, SocketMapStateSpec, SocketMapUpdateSharingPolicy,
51    SocketZonedAddrExt as _, UpdateSharingError,
52};
53use netstack3_base::socketmap::{IterShadows as _, SocketMap};
54use netstack3_base::sync::RwLock;
55use netstack3_base::{
56    AnyDevice, BidirectionalConverter as _, ContextPair, Control, CoreTimerContext,
57    CoreTxMetadataContext, CtxPair, DeferredResourceRemovalContext, DeviceIdContext,
58    EitherDeviceId, ExistsError, HandleableTimer, IcmpErrorCode, Inspector, InspectorDeviceExt,
59    InspectorExt, InstantBindingsTypes, InstantContext as _, IpDeviceAddr, IpExt,
60    IpSocketPropertiesMatcher, LocalAddressError, Mark, MarkDomain, Marks, MatcherBindingsTypes,
61    Mss, OwnedOrRefsBidirectionalConverter, PortAllocImpl, ReferenceNotifiersExt as _,
62    RemoveResourceResult, ResourceCounterContext as _, RngContext, Segment, SeqNum,
63    SettingsContext, StrongDeviceIdentifier, TimerBindingsTypes, TimerContext,
64    TxMetadataBindingsTypes, WeakDeviceIdentifier, ZonedAddressError,
65};
66use netstack3_filter::{FilterIpExt, SocketOpsFilterBindingContext, Tuple};
67use netstack3_hashmap::{HashMap, hash_map};
68use netstack3_ip::socket::{
69    DeviceIpSocketHandler, IpSock, IpSockCreateAndSendError, IpSockCreationError, IpSocketArgs,
70    IpSocketHandler,
71};
72use netstack3_ip::{
73    self as ip, BaseTransportIpContext, IpLayerIpExt, SocketMetadata, TransportIpContext,
74};
75use netstack3_trace::{TraceResourceId, trace_duration};
76use packet_formats::ip::IpProto;
77use smallvec::{SmallVec, smallvec};
78use thiserror::Error;
79
80use crate::internal::base::{
81    BufferSizes, BuffersRefMut, ConnectionError, SocketOptions, TcpIpSockOptions,
82    TcpSocketTxMetadata,
83};
84use crate::internal::buffer::{Buffer, IntoBuffers, ReceiveBuffer, SendBuffer};
85use crate::internal::counters::{
86    self, CombinedTcpCounters, TcpCounterContext, TcpCountersRefs, TcpCountersWithSocket,
87};
88use crate::internal::settings::TcpSettings;
89use crate::internal::socket::accept_queue::{AcceptQueue, ListenerNotifier};
90use crate::internal::socket::demux::tcp_serialize_segment;
91use crate::internal::socket::diagnostics::{TcpSocketDiagnostics, TcpSocketStateForMatching};
92
93use crate::internal::socket::generators::{IsnGenerator, TimestampOffsetGenerator};
94use crate::internal::state::info::TcpSocketInfo;
95use crate::internal::state::{
96    CloseError, CloseReason, Closed, Initial, NewlyClosed, ShouldRetransmit, State,
97    StateMachineDebugId, Takeable, TakeableRef,
98};
99
100/// A marker trait for dual-stack socket features.
101///
102/// This trait acts as a marker for [`DualStackBaseIpExt`] for both `Self` and
103/// `Self::OtherVersion`.
104pub trait DualStackIpExt:
105    DualStackBaseIpExt + netstack3_base::socket::DualStackIpExt<OtherVersion: DualStackBaseIpExt>
106{
107}
108
109impl<I> DualStackIpExt for I where
110    I: DualStackBaseIpExt
111        + netstack3_base::socket::DualStackIpExt<OtherVersion: DualStackBaseIpExt>
112{
113}
114
115/// A dual stack IP extension trait for TCP.
116pub trait DualStackBaseIpExt:
117    netstack3_base::socket::DualStackIpExt + SocketIpExt + IpLayerIpExt
118{
119    /// For `Ipv4`, this is [`EitherStack<TcpSocketId<Ipv4, _, _>, TcpSocketId<Ipv6, _, _>>`],
120    /// and for `Ipv6` it is just `TcpSocketId<Ipv6>`.
121    type DemuxSocketId<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>: SpecSocketId;
122
123    /// The type for a connection, for [`Ipv4`], this will be just the single
124    /// stack version of the connection state and the connection address. For
125    /// [`Ipv6`], this will be a `EitherStack`.
126    type ConnectionAndAddr<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>: Send + Sync + Debug;
127
128    /// The type for the address that the listener is listening on. This should
129    /// be just [`ListenerIpAddr`] for [`Ipv4`], but a [`DualStackListenerIpAddr`]
130    /// for [`Ipv6`].
131    type ListenerIpAddr: Send + Sync + Debug + Clone;
132
133    /// The type for the original destination address of a connection. For
134    /// [`Ipv4`], this is always an [`Ipv4Addr`], and for [`Ipv6`], it is an
135    /// [`EitherStack<Ipv6Addr, Ipv4Addr>`].
136    type OriginalDstAddr;
137
138    /// IP options unique to a particular IP version.
139    type DualStackIpOptions: Send + Sync + Debug + Default + Clone + Copy;
140
141    /// Determines which stack the demux socket ID belongs to and converts
142    /// (by reference) to a dual stack TCP socket ID.
143    fn as_dual_stack_ip_socket<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
144        id: &Self::DemuxSocketId<D, BT>,
145    ) -> EitherStack<&TcpSocketId<Self, D, BT>, &TcpSocketId<Self::OtherVersion, D, BT>>
146    where
147        Self::OtherVersion: DualStackBaseIpExt;
148
149    /// Determines which stack the demux socket ID belongs to and converts
150    /// (by value) to a dual stack TCP socket ID.
151    fn into_dual_stack_ip_socket<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
152        id: Self::DemuxSocketId<D, BT>,
153    ) -> EitherStack<TcpSocketId<Self, D, BT>, TcpSocketId<Self::OtherVersion, D, BT>>
154    where
155        Self::OtherVersion: DualStackBaseIpExt;
156
157    /// Turns a [`TcpSocketId`] of the current stack into the demuxer ID.
158    fn into_demux_socket_id<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
159        id: TcpSocketId<Self, D, BT>,
160    ) -> Self::DemuxSocketId<D, BT>
161    where
162        Self::OtherVersion: DualStackBaseIpExt;
163
164    fn get_conn_info<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
165        conn_and_addr: &Self::ConnectionAndAddr<D, BT>,
166    ) -> ConnectionInfo<Self::Addr, D>;
167    fn get_accept_queue_mut<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
168        conn_and_addr: &mut Self::ConnectionAndAddr<D, BT>,
169    ) -> &mut Option<
170        AcceptQueue<
171            TcpSocketId<Self, D, BT>,
172            BT::ReturnedBuffers,
173            BT::ListenerNotifierOrProvidedBuffers,
174        >,
175    >
176    where
177        Self::OtherVersion: DualStackBaseIpExt;
178    fn get_defunct<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
179        conn_and_addr: &Self::ConnectionAndAddr<D, BT>,
180    ) -> bool;
181    fn get_state<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
182        conn_and_addr: &Self::ConnectionAndAddr<D, BT>,
183    ) -> &State<BT::Instant, BT::ReceiveBuffer, BT::SendBuffer, BT::ListenerNotifierOrProvidedBuffers>;
184    fn get_bound_info<D: WeakDeviceIdentifier>(
185        listener_addr: &ListenerAddr<Self::ListenerIpAddr, D>,
186    ) -> BoundInfo<Self::Addr, D>;
187
188    fn destroy_socket_with_demux_id<
189        CC: TcpContext<Self, BC> + TcpContext<Self::OtherVersion, BC>,
190        BC: TcpBindingsContext<CC::DeviceId>,
191    >(
192        core_ctx: &mut CC,
193        bindings_ctx: &mut BC,
194        demux_id: Self::DemuxSocketId<CC::WeakDeviceId, BC>,
195    ) where
196        Self::OtherVersion: DualStackBaseIpExt;
197
198    /// Take the original destination of the socket's connection and return an
199    /// address that is always in this socket's stack. For [`Ipv4`], this is a
200    /// no-op, but for [`Ipv6`] it may require mapping a dual-stack IPv4 address
201    /// into the IPv6 address space.
202    fn get_original_dst(addr: Self::OriginalDstAddr) -> Self::Addr;
203}
204
205impl DualStackBaseIpExt for Ipv4 {
206    type DemuxSocketId<D: WeakDeviceIdentifier, BT: TcpBindingsTypes> =
207        EitherStack<TcpSocketId<Ipv4, D, BT>, TcpSocketId<Ipv6, D, BT>>;
208    type ConnectionAndAddr<D: WeakDeviceIdentifier, BT: TcpBindingsTypes> =
209        (Connection<Ipv4, Ipv4, D, BT>, ConnAddr<ConnIpAddr<Ipv4Addr, NonZeroU16, NonZeroU16>, D>);
210    type ListenerIpAddr = ListenerIpAddr<Ipv4Addr, NonZeroU16>;
211    type OriginalDstAddr = Ipv4Addr;
212    type DualStackIpOptions = ();
213
214    fn as_dual_stack_ip_socket<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
215        id: &Self::DemuxSocketId<D, BT>,
216    ) -> EitherStack<&TcpSocketId<Self, D, BT>, &TcpSocketId<Self::OtherVersion, D, BT>> {
217        match id {
218            EitherStack::ThisStack(id) => EitherStack::ThisStack(id),
219            EitherStack::OtherStack(id) => EitherStack::OtherStack(id),
220        }
221    }
222    fn into_dual_stack_ip_socket<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
223        id: Self::DemuxSocketId<D, BT>,
224    ) -> EitherStack<TcpSocketId<Self, D, BT>, TcpSocketId<Self::OtherVersion, D, BT>> {
225        id
226    }
227    fn into_demux_socket_id<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
228        id: TcpSocketId<Self, D, BT>,
229    ) -> Self::DemuxSocketId<D, BT> {
230        EitherStack::ThisStack(id)
231    }
232    fn get_conn_info<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
233        (_conn, addr): &Self::ConnectionAndAddr<D, BT>,
234    ) -> ConnectionInfo<Self::Addr, D> {
235        addr.clone().into()
236    }
237    fn get_accept_queue_mut<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
238        (conn, _addr): &mut Self::ConnectionAndAddr<D, BT>,
239    ) -> &mut Option<
240        AcceptQueue<
241            TcpSocketId<Self, D, BT>,
242            BT::ReturnedBuffers,
243            BT::ListenerNotifierOrProvidedBuffers,
244        >,
245    > {
246        &mut conn.accept_queue
247    }
248    fn get_defunct<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
249        (conn, _addr): &Self::ConnectionAndAddr<D, BT>,
250    ) -> bool {
251        conn.defunct
252    }
253    fn get_state<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
254        (conn, _addr): &Self::ConnectionAndAddr<D, BT>,
255    ) -> &State<BT::Instant, BT::ReceiveBuffer, BT::SendBuffer, BT::ListenerNotifierOrProvidedBuffers>
256    {
257        &conn.state
258    }
259    fn get_bound_info<D: WeakDeviceIdentifier>(
260        listener_addr: &ListenerAddr<Self::ListenerIpAddr, D>,
261    ) -> BoundInfo<Self::Addr, D> {
262        listener_addr.clone().into()
263    }
264
265    fn destroy_socket_with_demux_id<
266        CC: TcpContext<Self, BC> + TcpContext<Self::OtherVersion, BC>,
267        BC: TcpBindingsContext<CC::DeviceId>,
268    >(
269        core_ctx: &mut CC,
270        bindings_ctx: &mut BC,
271        demux_id: Self::DemuxSocketId<CC::WeakDeviceId, BC>,
272    ) {
273        match demux_id {
274            EitherStack::ThisStack(id) => destroy_socket(core_ctx, bindings_ctx, id),
275            EitherStack::OtherStack(id) => destroy_socket(core_ctx, bindings_ctx, id),
276        }
277    }
278
279    fn get_original_dst(addr: Self::OriginalDstAddr) -> Self::Addr {
280        addr
281    }
282}
283
284/// Socket options that are accessible on IPv6 sockets.
285#[derive(Derivative, Debug, Clone, Copy, PartialEq, Eq)]
286#[derivative(Default)]
287pub struct Ipv6Options {
288    /// True if this socket has dual stack enabled.
289    #[derivative(Default(value = "true"))]
290    pub dual_stack_enabled: bool,
291}
292
293impl DualStackBaseIpExt for Ipv6 {
294    type DemuxSocketId<D: WeakDeviceIdentifier, BT: TcpBindingsTypes> = TcpSocketId<Ipv6, D, BT>;
295    type ConnectionAndAddr<D: WeakDeviceIdentifier, BT: TcpBindingsTypes> = EitherStack<
296        (Connection<Ipv6, Ipv6, D, BT>, ConnAddr<ConnIpAddr<Ipv6Addr, NonZeroU16, NonZeroU16>, D>),
297        (Connection<Ipv6, Ipv4, D, BT>, ConnAddr<ConnIpAddr<Ipv4Addr, NonZeroU16, NonZeroU16>, D>),
298    >;
299    type DualStackIpOptions = Ipv6Options;
300    type ListenerIpAddr = DualStackListenerIpAddr<Ipv6Addr, NonZeroU16>;
301    type OriginalDstAddr = EitherStack<Ipv6Addr, Ipv4Addr>;
302
303    fn as_dual_stack_ip_socket<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
304        id: &Self::DemuxSocketId<D, BT>,
305    ) -> EitherStack<&TcpSocketId<Self, D, BT>, &TcpSocketId<Self::OtherVersion, D, BT>> {
306        EitherStack::ThisStack(id)
307    }
308    fn into_dual_stack_ip_socket<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
309        id: Self::DemuxSocketId<D, BT>,
310    ) -> EitherStack<TcpSocketId<Self, D, BT>, TcpSocketId<Self::OtherVersion, D, BT>> {
311        EitherStack::ThisStack(id)
312    }
313
314    fn into_demux_socket_id<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
315        id: TcpSocketId<Self, D, BT>,
316    ) -> Self::DemuxSocketId<D, BT> {
317        id
318    }
319    fn get_conn_info<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
320        conn_and_addr: &Self::ConnectionAndAddr<D, BT>,
321    ) -> ConnectionInfo<Self::Addr, D> {
322        match conn_and_addr {
323            EitherStack::ThisStack((_conn, addr)) => addr.clone().into(),
324            EitherStack::OtherStack((
325                _conn,
326                ConnAddr {
327                    ip:
328                        ConnIpAddr { local: (local_ip, local_port), remote: (remote_ip, remote_port) },
329                    device,
330                },
331            )) => ConnectionInfo {
332                local_addr: SocketAddr {
333                    ip: maybe_zoned(local_ip.addr().to_ipv6_mapped(), device),
334                    port: *local_port,
335                },
336                remote_addr: SocketAddr {
337                    ip: maybe_zoned(remote_ip.addr().to_ipv6_mapped(), device),
338                    port: *remote_port,
339                },
340                device: device.clone(),
341            },
342        }
343    }
344    fn get_accept_queue_mut<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
345        conn_and_addr: &mut Self::ConnectionAndAddr<D, BT>,
346    ) -> &mut Option<
347        AcceptQueue<
348            TcpSocketId<Self, D, BT>,
349            BT::ReturnedBuffers,
350            BT::ListenerNotifierOrProvidedBuffers,
351        >,
352    > {
353        match conn_and_addr {
354            EitherStack::ThisStack((conn, _addr)) => &mut conn.accept_queue,
355            EitherStack::OtherStack((conn, _addr)) => &mut conn.accept_queue,
356        }
357    }
358    fn get_defunct<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
359        conn_and_addr: &Self::ConnectionAndAddr<D, BT>,
360    ) -> bool {
361        match conn_and_addr {
362            EitherStack::ThisStack((conn, _addr)) => conn.defunct,
363            EitherStack::OtherStack((conn, _addr)) => conn.defunct,
364        }
365    }
366    fn get_state<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
367        conn_and_addr: &Self::ConnectionAndAddr<D, BT>,
368    ) -> &State<BT::Instant, BT::ReceiveBuffer, BT::SendBuffer, BT::ListenerNotifierOrProvidedBuffers>
369    {
370        match conn_and_addr {
371            EitherStack::ThisStack((conn, _addr)) => &conn.state,
372            EitherStack::OtherStack((conn, _addr)) => &conn.state,
373        }
374    }
375    fn get_bound_info<D: WeakDeviceIdentifier>(
376        ListenerAddr { ip, device }: &ListenerAddr<Self::ListenerIpAddr, D>,
377    ) -> BoundInfo<Self::Addr, D> {
378        match ip {
379            DualStackListenerIpAddr::ThisStack(ip) => {
380                ListenerAddr { ip: ip.clone(), device: device.clone() }.into()
381            }
382            DualStackListenerIpAddr::OtherStack(ListenerIpAddr {
383                addr,
384                identifier: local_port,
385            }) => BoundInfo {
386                addr: Some(maybe_zoned(
387                    addr.map(|a| a.addr()).unwrap_or(Ipv4::UNSPECIFIED_ADDRESS).to_ipv6_mapped(),
388                    &device,
389                )),
390                port: *local_port,
391                device: device.clone(),
392            },
393            DualStackListenerIpAddr::BothStacks(local_port) => {
394                BoundInfo { addr: None, port: *local_port, device: device.clone() }
395            }
396        }
397    }
398
399    fn destroy_socket_with_demux_id<
400        CC: TcpContext<Self, BC> + TcpContext<Self::OtherVersion, BC>,
401        BC: TcpBindingsContext<CC::DeviceId>,
402    >(
403        core_ctx: &mut CC,
404        bindings_ctx: &mut BC,
405        demux_id: Self::DemuxSocketId<CC::WeakDeviceId, BC>,
406    ) {
407        destroy_socket(core_ctx, bindings_ctx, demux_id)
408    }
409
410    fn get_original_dst(addr: Self::OriginalDstAddr) -> Self::Addr {
411        match addr {
412            EitherStack::ThisStack(addr) => addr,
413            EitherStack::OtherStack(addr) => *addr.to_ipv6_mapped(),
414        }
415    }
416}
417
418/// Timer ID for TCP connections.
419#[derive(Derivative, GenericOverIp)]
420#[generic_over_ip()]
421#[derivative(
422    Clone(bound = ""),
423    Eq(bound = ""),
424    PartialEq(bound = ""),
425    Hash(bound = ""),
426    Debug(bound = "")
427)]
428#[allow(missing_docs)]
429pub enum TcpTimerId<D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
430    V4(WeakTcpSocketId<Ipv4, D, BT>),
431    V6(WeakTcpSocketId<Ipv6, D, BT>),
432}
433
434impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
435    From<WeakTcpSocketId<I, D, BT>> for TcpTimerId<D, BT>
436{
437    fn from(f: WeakTcpSocketId<I, D, BT>) -> Self {
438        I::map_ip(f, TcpTimerId::V4, TcpTimerId::V6)
439    }
440}
441
442/// Bindings types for TCP.
443///
444/// The relationship between buffers  is as follows:
445///
446/// The Bindings will receive the `ReturnedBuffers` so that it can: 1. give the
447/// application a handle to read/write data; 2. Observe whatever signal required
448/// from the application so that it can inform Core. The peer end of returned
449/// handle will be held by the state machine inside the netstack. Specialized
450/// receive/send buffers will be derived from `ProvidedBuffers` from Bindings.
451///
452/// +-------------------------------+
453/// |       +--------------+        |
454/// |       |   returned   |        |
455/// |       |    buffers   |        |
456/// |       +------+-------+        |
457/// |              |     application|
458/// +--------------+----------------+
459///                |
460/// +--------------+----------------+
461/// |              |        netstack|
462/// |   +---+------+-------+---+    |
463/// |   |   |  provided    |   |    |
464/// |   | +-+-  buffers   -+-+ |    |
465/// |   +-+-+--------------+-+-+    |
466/// |     v                  v      |
467/// |receive buffer     send buffer |
468/// +-------------------------------+
469
470pub trait TcpBindingsTypes:
471    InstantBindingsTypes + TimerBindingsTypes + TxMetadataBindingsTypes + MatcherBindingsTypes + 'static
472{
473    /// Receive buffer used by TCP.
474    type ReceiveBuffer: ReceiveBuffer + Send + Sync;
475    /// Send buffer used by TCP.
476    type SendBuffer: SendBuffer + Send + Sync;
477    /// The object that will be returned by the state machine when a passive
478    /// open connection becomes established. The bindings can use this object
479    /// to read/write bytes from/into the created buffers.
480    type ReturnedBuffers: Debug + Send + Sync;
481    /// The extra information provided by the Bindings that implements platform
482    /// dependent behaviors. It serves as a [`ListenerNotifier`] if the socket
483    /// was used as a listener and it will be used to provide buffers if used
484    /// to establish connections.
485    type ListenerNotifierOrProvidedBuffers: Debug
486        + IntoBuffers<Self::ReceiveBuffer, Self::SendBuffer>
487        + ListenerNotifier
488        + Send
489        + Sync;
490
491    /// Creates new buffers and returns the object that Bindings need to
492    /// read/write from/into the created buffers.
493    fn new_passive_open_buffers(
494        buffer_sizes: BufferSizes,
495    ) -> (Self::ReceiveBuffer, Self::SendBuffer, Self::ReturnedBuffers);
496}
497
498/// The bindings context for TCP.
499///
500/// TCP timers are scoped by weak device IDs.
501pub trait TcpBindingsContext<D>:
502    Sized
503    + DeferredResourceRemovalContext
504    + TimerContext
505    + RngContext
506    + TcpBindingsTypes
507    + SocketOpsFilterBindingContext<D>
508    + SettingsContext<TcpSettings>
509{
510}
511
512impl<D, BC> TcpBindingsContext<D> for BC where
513    BC: Sized
514        + DeferredResourceRemovalContext
515        + TimerContext
516        + RngContext
517        + TcpBindingsTypes
518        + SocketOpsFilterBindingContext<D>
519        + SettingsContext<TcpSettings>
520{
521}
522
523/// The core execution context abstracting demux state access for TCP.
524pub trait TcpDemuxContext<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>:
525    TcpCoreTimerContext<I, D, BT>
526{
527    /// The inner IP transport context.
528    type IpTransportCtx<'a>: TransportIpContext<I, BT, DeviceId = D::Strong, WeakDeviceId = D>
529        + DeviceIpSocketHandler<I, BT>
530        + TcpCoreTimerContext<I, D, BT>;
531
532    /// Calls `f` with non-mutable access to the demux state.
533    fn with_demux<O, F: FnOnce(&DemuxState<I, D, BT>) -> O>(&mut self, cb: F) -> O;
534
535    /// Calls `f` with mutable access to the demux state.
536    fn with_demux_mut<O, F: FnOnce(&mut DemuxState<I, D, BT>) -> O>(&mut self, cb: F) -> O;
537}
538
539/// Provides access to the current stack of the context.
540///
541/// This is useful when dealing with logic that applies to the current stack
542/// but we want to be version agnostic: we have different associated types for
543/// single-stack and dual-stack contexts, we can use this function to turn them
544/// into the same type that only provides access to the current version of the
545/// stack and trims down access to `I::OtherVersion`.
546pub trait AsThisStack<T> {
547    /// Get the this stack version of the context.
548    fn as_this_stack(&mut self) -> &mut T;
549}
550
551impl<T> AsThisStack<T> for T {
552    fn as_this_stack(&mut self) -> &mut T {
553        self
554    }
555}
556
557/// A marker traits for all traits used to access TCP socket.
558pub trait TcpSocketContext<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>:
559    TcpCounterContext<I, D, BT> + CoreTxMetadataContext<TcpSocketTxMetadata<I, D, BT>, BT>
560{
561}
562
563impl<CC, I, D, BC> TcpSocketContext<I, D, BC> for CC
564where
565    I: DualStackIpExt,
566    D: WeakDeviceIdentifier,
567    BC: TcpBindingsTypes,
568    CC: TcpCounterContext<I, D, BC> + CoreTxMetadataContext<TcpSocketTxMetadata<I, D, BC>, BC>,
569{
570}
571
572/// A shortcut for the `CoreTimerContext` required by TCP.
573pub trait TcpCoreTimerContext<I: DualStackIpExt, D: WeakDeviceIdentifier, BC: TcpBindingsTypes>:
574    CoreTimerContext<WeakTcpSocketId<I, D, BC>, BC>
575{
576}
577
578impl<CC, I, D, BC> TcpCoreTimerContext<I, D, BC> for CC
579where
580    I: DualStackIpExt,
581    D: WeakDeviceIdentifier,
582    BC: TcpBindingsTypes,
583    CC: CoreTimerContext<WeakTcpSocketId<I, D, BC>, BC>,
584{
585}
586
587/// A marker trait for all dual stack conversions in [`TcpContext`].
588pub trait DualStackConverter<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>:
589    OwnedOrRefsBidirectionalConverter<
590        I::ConnectionAndAddr<D, BT>,
591        EitherStack<
592            (
593                Connection<I, I, D, BT>,
594                ConnAddr<ConnIpAddr<<I as Ip>::Addr, NonZeroU16, NonZeroU16>, D>,
595            ),
596            (
597                Connection<I, I::OtherVersion, D, BT>,
598                ConnAddr<ConnIpAddr<<I::OtherVersion as Ip>::Addr, NonZeroU16, NonZeroU16>, D>,
599            ),
600        >,
601    > + OwnedOrRefsBidirectionalConverter<
602        I::ListenerIpAddr,
603        DualStackListenerIpAddr<I::Addr, NonZeroU16>,
604    > + OwnedOrRefsBidirectionalConverter<
605        ListenerAddr<I::ListenerIpAddr, D>,
606        ListenerAddr<DualStackListenerIpAddr<I::Addr, NonZeroU16>, D>,
607    > + OwnedOrRefsBidirectionalConverter<
608        I::OriginalDstAddr,
609        EitherStack<I::Addr, <I::OtherVersion as Ip>::Addr>,
610    >
611{
612}
613
614impl<I, D, BT, O> DualStackConverter<I, D, BT> for O
615where
616    I: DualStackIpExt,
617    D: WeakDeviceIdentifier,
618    BT: TcpBindingsTypes,
619    O: OwnedOrRefsBidirectionalConverter<
620            I::ConnectionAndAddr<D, BT>,
621            EitherStack<
622                (
623                    Connection<I, I, D, BT>,
624                    ConnAddr<ConnIpAddr<<I as Ip>::Addr, NonZeroU16, NonZeroU16>, D>,
625                ),
626                (
627                    Connection<I, I::OtherVersion, D, BT>,
628                    ConnAddr<ConnIpAddr<<I::OtherVersion as Ip>::Addr, NonZeroU16, NonZeroU16>, D>,
629                ),
630            >,
631        > + OwnedOrRefsBidirectionalConverter<
632            I::ListenerIpAddr,
633            DualStackListenerIpAddr<I::Addr, NonZeroU16>,
634        > + OwnedOrRefsBidirectionalConverter<
635            ListenerAddr<I::ListenerIpAddr, D>,
636            ListenerAddr<DualStackListenerIpAddr<I::Addr, NonZeroU16>, D>,
637        > + OwnedOrRefsBidirectionalConverter<
638            I::OriginalDstAddr,
639            EitherStack<I::Addr, <I::OtherVersion as Ip>::Addr>,
640        >,
641{
642}
643
644/// A marker trait for all single stack conversions in [`TcpContext`].
645pub trait SingleStackConverter<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>:
646    OwnedOrRefsBidirectionalConverter<
647        I::ConnectionAndAddr<D, BT>,
648        (Connection<I, I, D, BT>, ConnAddr<ConnIpAddr<<I as Ip>::Addr, NonZeroU16, NonZeroU16>, D>),
649    > + OwnedOrRefsBidirectionalConverter<I::ListenerIpAddr, ListenerIpAddr<I::Addr, NonZeroU16>>
650    + OwnedOrRefsBidirectionalConverter<
651        ListenerAddr<I::ListenerIpAddr, D>,
652        ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, D>,
653    > + OwnedOrRefsBidirectionalConverter<I::OriginalDstAddr, I::Addr>
654{
655}
656
657impl<I, D, BT, O> SingleStackConverter<I, D, BT> for O
658where
659    I: DualStackIpExt,
660    D: WeakDeviceIdentifier,
661    BT: TcpBindingsTypes,
662    O: OwnedOrRefsBidirectionalConverter<
663            I::ConnectionAndAddr<D, BT>,
664            (
665                Connection<I, I, D, BT>,
666                ConnAddr<ConnIpAddr<<I as Ip>::Addr, NonZeroU16, NonZeroU16>, D>,
667            ),
668        > + OwnedOrRefsBidirectionalConverter<I::ListenerIpAddr, ListenerIpAddr<I::Addr, NonZeroU16>>
669        + OwnedOrRefsBidirectionalConverter<
670            ListenerAddr<I::ListenerIpAddr, D>,
671            ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, D>,
672        > + OwnedOrRefsBidirectionalConverter<I::OriginalDstAddr, I::Addr>,
673{
674}
675
676/// Core context for TCP.
677pub trait TcpContext<I: DualStackIpExt, BC: TcpBindingsTypes>:
678    TcpDemuxContext<I, Self::WeakDeviceId, BC>
679    + IpSocketHandler<I, BC>
680    + TcpSocketContext<I, Self::WeakDeviceId, BC>
681{
682    /// The core context for the current version of the IP protocol. This is
683    /// used to be version agnostic when the operation is on the current stack.
684    type ThisStackIpTransportAndDemuxCtx<'a>: TransportIpContext<I, BC, DeviceId = Self::DeviceId, WeakDeviceId = Self::WeakDeviceId>
685        + DeviceIpSocketHandler<I, BC>
686        + TcpDemuxContext<I, Self::WeakDeviceId, BC>
687        + TcpSocketContext<I, Self::WeakDeviceId, BC>;
688
689    /// The core context that will give access to this version of the IP layer.
690    type SingleStackIpTransportAndDemuxCtx<'a>: TransportIpContext<I, BC, DeviceId = Self::DeviceId, WeakDeviceId = Self::WeakDeviceId>
691        + DeviceIpSocketHandler<I, BC>
692        + TcpDemuxContext<I, Self::WeakDeviceId, BC>
693        + AsThisStack<Self::ThisStackIpTransportAndDemuxCtx<'a>>
694        + TcpSocketContext<I, Self::WeakDeviceId, BC>;
695
696    /// A collection of type assertions that must be true in the single stack
697    /// version, associated types and concrete types must unify and we can
698    /// inspect types by converting them into the concrete types.
699    type SingleStackConverter: SingleStackConverter<I, Self::WeakDeviceId, BC>;
700
701    /// The core context that will give access to both versions of the IP layer.
702    type DualStackIpTransportAndDemuxCtx<'a>: TransportIpContext<I, BC, DeviceId = Self::DeviceId, WeakDeviceId = Self::WeakDeviceId>
703        + DeviceIpSocketHandler<I, BC>
704        + TcpDemuxContext<I, Self::WeakDeviceId, BC>
705        + TransportIpContext<
706            I::OtherVersion,
707            BC,
708            DeviceId = Self::DeviceId,
709            WeakDeviceId = Self::WeakDeviceId,
710        > + DeviceIpSocketHandler<I::OtherVersion, BC>
711        + TcpDemuxContext<I::OtherVersion, Self::WeakDeviceId, BC>
712        + TcpDualStackContext<I, Self::WeakDeviceId, BC>
713        + AsThisStack<Self::ThisStackIpTransportAndDemuxCtx<'a>>
714        + TcpSocketContext<I, Self::WeakDeviceId, BC>
715        + TcpCounterContext<I::OtherVersion, Self::WeakDeviceId, BC>;
716
717    /// A collection of type assertions that must be true in the dual stack
718    /// version, associated types and concrete types must unify and we can
719    /// inspect types by converting them into the concrete types.
720    type DualStackConverter: DualStackConverter<I, Self::WeakDeviceId, BC>;
721
722    /// Calls the function with mutable access to the set with all TCP sockets.
723    fn with_all_sockets_mut<O, F: FnOnce(&mut TcpSocketSet<I, Self::WeakDeviceId, BC>) -> O>(
724        &mut self,
725        cb: F,
726    ) -> O;
727
728    /// Calls the callback once for each currently installed socket.
729    fn for_each_socket<
730        F: FnMut(&TcpSocketId<I, Self::WeakDeviceId, BC>, &TcpSocketState<I, Self::WeakDeviceId, BC>),
731    >(
732        &mut self,
733        cb: F,
734    );
735
736    /// Calls the function with access to the socket state,
737    /// ISN & Timestamp Offset generators, and Transport + Demux context.
738    fn with_socket_mut_generators_transport_demux<
739        O,
740        F: for<'a> FnOnce(
741            MaybeDualStack<
742                (&'a mut Self::DualStackIpTransportAndDemuxCtx<'a>, Self::DualStackConverter),
743                (&'a mut Self::SingleStackIpTransportAndDemuxCtx<'a>, Self::SingleStackConverter),
744            >,
745            &mut TcpSocketState<I, Self::WeakDeviceId, BC>,
746            &IsnGenerator<BC::Instant>,
747            &TimestampOffsetGenerator<BC::Instant>,
748        ) -> O,
749    >(
750        &mut self,
751        id: &TcpSocketId<I, Self::WeakDeviceId, BC>,
752        cb: F,
753    ) -> O;
754
755    /// Calls the function with immutable access to the socket state.
756    fn with_socket<O, F: FnOnce(&TcpSocketState<I, Self::WeakDeviceId, BC>) -> O>(
757        &mut self,
758        id: &TcpSocketId<I, Self::WeakDeviceId, BC>,
759        cb: F,
760    ) -> O {
761        self.with_socket_and_converter(id, |socket_state, _converter| cb(socket_state))
762    }
763
764    /// Calls the function with the immutable reference to the socket state and
765    /// a converter to inspect.
766    fn with_socket_and_converter<
767        O,
768        F: FnOnce(
769            &TcpSocketState<I, Self::WeakDeviceId, BC>,
770            MaybeDualStack<Self::DualStackConverter, Self::SingleStackConverter>,
771        ) -> O,
772    >(
773        &mut self,
774        id: &TcpSocketId<I, Self::WeakDeviceId, BC>,
775        cb: F,
776    ) -> O;
777
778    /// Calls the function with access to the socket state and Transport + Demux
779    /// context.
780    fn with_socket_mut_transport_demux<
781        O,
782        F: for<'a> FnOnce(
783            MaybeDualStack<
784                (&'a mut Self::DualStackIpTransportAndDemuxCtx<'a>, Self::DualStackConverter),
785                (&'a mut Self::SingleStackIpTransportAndDemuxCtx<'a>, Self::SingleStackConverter),
786            >,
787            &mut TcpSocketState<I, Self::WeakDeviceId, BC>,
788        ) -> O,
789    >(
790        &mut self,
791        id: &TcpSocketId<I, Self::WeakDeviceId, BC>,
792        cb: F,
793    ) -> O {
794        self.with_socket_mut_generators_transport_demux(
795            id,
796            |ctx, socket_state, _isn, _timestamp_offset| cb(ctx, socket_state),
797        )
798    }
799
800    /// Calls the function with mutable access to the socket state.
801    fn with_socket_mut<O, F: FnOnce(&mut TcpSocketState<I, Self::WeakDeviceId, BC>) -> O>(
802        &mut self,
803        id: &TcpSocketId<I, Self::WeakDeviceId, BC>,
804        cb: F,
805    ) -> O {
806        self.with_socket_mut_generators_transport_demux(
807            id,
808            |_ctx, socket_state, _isn, _timestamp_offset| cb(socket_state),
809        )
810    }
811
812    /// Calls the function with the mutable reference to the socket state and a
813    /// converter to inspect.
814    fn with_socket_mut_and_converter<
815        O,
816        F: FnOnce(
817            &mut TcpSocketState<I, Self::WeakDeviceId, BC>,
818            MaybeDualStack<Self::DualStackConverter, Self::SingleStackConverter>,
819        ) -> O,
820    >(
821        &mut self,
822        id: &TcpSocketId<I, Self::WeakDeviceId, BC>,
823        cb: F,
824    ) -> O {
825        self.with_socket_mut_generators_transport_demux(
826            id,
827            |ctx, socket_state, _isn, _timestamp_offset| {
828                let converter = match ctx {
829                    MaybeDualStack::NotDualStack((_core_ctx, converter)) => {
830                        MaybeDualStack::NotDualStack(converter)
831                    }
832                    MaybeDualStack::DualStack((_core_ctx, converter)) => {
833                        MaybeDualStack::DualStack(converter)
834                    }
835                };
836                cb(socket_state, converter)
837            },
838        )
839    }
840}
841
842/// A ZST that helps convert IPv6 socket IDs into IPv4 demux IDs.
843#[derive(Clone, Copy)]
844pub struct Ipv6SocketIdToIpv4DemuxIdConverter;
845
846/// This trait allows us to work around the life-time issue when we need to
847/// convert an IPv6 socket ID into an IPv4 demux ID without holding on the
848/// a dual-stack CoreContext.
849pub trait DualStackDemuxIdConverter<I: DualStackIpExt>: 'static + Clone + Copy {
850    /// Turns a [`TcpSocketId`] into the demuxer ID of the other stack.
851    fn convert<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
852        &self,
853        id: TcpSocketId<I, D, BT>,
854    ) -> <I::OtherVersion as DualStackBaseIpExt>::DemuxSocketId<D, BT>;
855}
856
857impl DualStackDemuxIdConverter<Ipv6> for Ipv6SocketIdToIpv4DemuxIdConverter {
858    fn convert<D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
859        &self,
860        id: TcpSocketId<Ipv6, D, BT>,
861    ) -> <Ipv4 as DualStackBaseIpExt>::DemuxSocketId<D, BT> {
862        EitherStack::OtherStack(id)
863    }
864}
865
866/// A provider of dualstack socket functionality required by TCP sockets.
867pub trait TcpDualStackContext<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
868    /// The inner IP transport context,
869    type DualStackIpTransportCtx<'a>: TransportIpContext<I, BT, DeviceId = D::Strong, WeakDeviceId = D>
870        + DeviceIpSocketHandler<I, BT>
871        + TcpCoreTimerContext<I, D, BT>
872        + TransportIpContext<I::OtherVersion, BT, DeviceId = D::Strong, WeakDeviceId = D>
873        + DeviceIpSocketHandler<I::OtherVersion, BT>
874        + TcpCoreTimerContext<I::OtherVersion, D, BT>;
875
876    /// Gets a converter to get the demux socket ID for the other stack.
877    fn other_demux_id_converter(&self) -> impl DualStackDemuxIdConverter<I>;
878
879    /// Turns a [`TcpSocketId`] into the demuxer ID of the other stack.
880    fn into_other_demux_socket_id(
881        &self,
882        id: TcpSocketId<I, D, BT>,
883    ) -> <I::OtherVersion as DualStackBaseIpExt>::DemuxSocketId<D, BT> {
884        self.other_demux_id_converter().convert(id)
885    }
886
887    /// Returns a dual stack tuple with both demux identifiers for `id`.
888    fn dual_stack_demux_id(
889        &self,
890        id: TcpSocketId<I, D, BT>,
891    ) -> DualStackTuple<I, DemuxSocketId<I, D, BT>> {
892        let this_id = DemuxSocketId::<I, _, _>(I::into_demux_socket_id(id.clone()));
893        let other_id = DemuxSocketId::<I::OtherVersion, _, _>(self.into_other_demux_socket_id(id));
894        DualStackTuple::new(this_id, other_id)
895    }
896
897    /// Gets the enabled state of dual stack operations on the given socket.
898    fn dual_stack_enabled(&self, ip_options: &I::DualStackIpOptions) -> bool;
899    /// Sets the enabled state of dual stack operations on the given socket.
900    fn set_dual_stack_enabled(&self, ip_options: &mut I::DualStackIpOptions, value: bool);
901
902    /// Calls `cb` with mutable access to both demux states.
903    fn with_both_demux_mut<
904        O,
905        F: FnOnce(&mut DemuxState<I, D, BT>, &mut DemuxState<I::OtherVersion, D, BT>) -> O,
906    >(
907        &mut self,
908        cb: F,
909    ) -> O;
910}
911
912/// Socket address includes the ip address and the port number.
913#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, GenericOverIp)]
914#[generic_over_ip(A, IpAddress)]
915pub struct SocketAddr<A: IpAddress, D> {
916    /// The IP component of the address.
917    pub ip: ZonedAddr<SpecifiedAddr<A>, D>,
918    /// The port component of the address.
919    pub port: NonZeroU16,
920}
921
922impl<A: IpAddress, D> From<SocketAddr<A, D>>
923    for IpAddr<SocketAddr<Ipv4Addr, D>, SocketAddr<Ipv6Addr, D>>
924{
925    fn from(addr: SocketAddr<A, D>) -> IpAddr<SocketAddr<Ipv4Addr, D>, SocketAddr<Ipv6Addr, D>> {
926        <A::Version as Ip>::map_ip_in(addr, |i| IpAddr::V4(i), |i| IpAddr::V6(i))
927    }
928}
929
930impl<A: IpAddress, D> SocketAddr<A, D> {
931    /// Maps the [`SocketAddr`]'s zone type.
932    pub fn map_zone<Y>(self, f: impl FnOnce(D) -> Y) -> SocketAddr<A, Y> {
933        let Self { ip, port } = self;
934        SocketAddr { ip: ip.map_zone(f), port }
935    }
936}
937
938impl<A: IpAddress, D: fmt::Display> fmt::Display for SocketAddr<A, D> {
939    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
940        let Self { ip, port } = self;
941        let formatter = AddrAndPortFormatter::<_, _, A::Version>::new(
942            ip.as_ref().map_addr(core::convert::AsRef::<A>::as_ref),
943            port,
944        );
945        formatter.fmt(f)
946    }
947}
948
949/// Uninstantiable type used to implement [`SocketMapAddrSpec`] for TCP
950pub(crate) enum TcpPortSpec {}
951
952impl SocketMapAddrSpec for TcpPortSpec {
953    type RemoteIdentifier = NonZeroU16;
954    type LocalIdentifier = NonZeroU16;
955}
956
957/// An implementation of [`IpTransportContext`] for TCP.
958pub enum TcpIpTransportContext {}
959
960/// This trait is only used as a marker for the identifier that
961/// [`TcpSocketSpec`] keeps in the socket map. This is effectively only
962/// implemented for [`TcpSocketId`] but defining a trait effectively reduces the
963/// number of type parameters percolating down to the socket map types since
964/// they only really care about the identifier's behavior.
965pub trait SpecSocketId: Clone + Eq + PartialEq + Debug + 'static {}
966impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> SpecSocketId
967    for TcpSocketId<I, D, BT>
968{
969}
970
971impl<A: SpecSocketId, B: SpecSocketId> SpecSocketId for EitherStack<A, B> {}
972
973/// Uninstantiatable type for implementing [`SocketMapStateSpec`].
974struct TcpSocketSpec<I, D, BT>(PhantomData<(I, D, BT)>, Never);
975
976impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> SocketMapStateSpec
977    for TcpSocketSpec<I, D, BT>
978{
979    type ListenerId = I::DemuxSocketId<D, BT>;
980    type ConnId = I::DemuxSocketId<D, BT>;
981
982    type ListenerSharingState = ListenerSharingState;
983    type ConnSharingState = SharingState;
984    type AddrVecTag = AddrVecTag;
985
986    type ListenerAddrState = ListenerAddrState<Self::ListenerId>;
987    type ConnAddrState = ConnAddrState<Self::ConnId>;
988
989    fn listener_tag(
990        ListenerAddrInfo { has_device, specified_addr: _ }: ListenerAddrInfo,
991        state: &Self::ListenerAddrState,
992    ) -> Self::AddrVecTag {
993        let (sharing, state) = match state {
994            ListenerAddrState::ExclusiveBound(_) => {
995                (SharingState::Exclusive, SocketTagState::Bound)
996            }
997            ListenerAddrState::ExclusiveListener(_) => {
998                (SharingState::Exclusive, SocketTagState::Listener)
999            }
1000            ListenerAddrState::Shared { listener, bound: _ } => (
1001                SharingState::ReuseAddress,
1002                match listener {
1003                    Some(_) => SocketTagState::Listener,
1004                    None => SocketTagState::Bound,
1005                },
1006            ),
1007        };
1008        AddrVecTag { sharing, state, has_device }
1009    }
1010
1011    fn connected_tag(has_device: bool, state: &Self::ConnAddrState) -> Self::AddrVecTag {
1012        let ConnAddrState { sharing, id: _ } = state;
1013        AddrVecTag { sharing: *sharing, has_device, state: SocketTagState::Conn }
1014    }
1015}
1016
1017#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1018struct AddrVecTag {
1019    sharing: SharingState,
1020    state: SocketTagState,
1021    has_device: bool,
1022}
1023
1024#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1025enum SocketTagState {
1026    Conn,
1027    Listener,
1028    Bound,
1029}
1030
1031#[derive(Debug)]
1032enum ListenerAddrState<S> {
1033    ExclusiveBound(S),
1034    ExclusiveListener(S),
1035    Shared { listener: Option<S>, bound: SmallVec<[S; 1]> },
1036}
1037
1038#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1039pub struct ListenerSharingState {
1040    pub(crate) sharing: SharingState,
1041    pub(crate) listening: bool,
1042}
1043
1044enum ListenerAddrInserter<'a, S> {
1045    Listener(&'a mut Option<S>),
1046    Bound(&'a mut SmallVec<[S; 1]>),
1047}
1048
1049impl<'a, S> Inserter<S> for ListenerAddrInserter<'a, S> {
1050    fn insert(self, id: S) {
1051        match self {
1052            Self::Listener(o) => *o = Some(id),
1053            Self::Bound(b) => b.push(id),
1054        }
1055    }
1056}
1057
1058impl<S: SpecSocketId> SocketMapAddrStateSpec for ListenerAddrState<S> {
1059    type SharingState = ListenerSharingState;
1060    type Id = S;
1061    type Inserter<'a> = ListenerAddrInserter<'a, S>;
1062
1063    fn new(new_sharing_state: &Self::SharingState, id: Self::Id) -> Self {
1064        let ListenerSharingState { sharing, listening } = new_sharing_state;
1065        match sharing {
1066            SharingState::Exclusive => match listening {
1067                true => Self::ExclusiveListener(id),
1068                false => Self::ExclusiveBound(id),
1069            },
1070            SharingState::ReuseAddress => {
1071                let (listener, bound) =
1072                    if *listening { (Some(id), Default::default()) } else { (None, smallvec![id]) };
1073                Self::Shared { listener, bound }
1074            }
1075        }
1076    }
1077
1078    fn contains_id(&self, id: &Self::Id) -> bool {
1079        match self {
1080            Self::ExclusiveBound(x) | Self::ExclusiveListener(x) => id == x,
1081            Self::Shared { listener, bound } => {
1082                listener.as_ref().is_some_and(|x| id == x) || bound.contains(id)
1083            }
1084        }
1085    }
1086
1087    fn could_insert(
1088        &self,
1089        new_sharing_state: &Self::SharingState,
1090    ) -> Result<(), IncompatibleError> {
1091        match self {
1092            Self::ExclusiveBound(_) | Self::ExclusiveListener(_) => Err(IncompatibleError),
1093            Self::Shared { listener, bound: _ } => {
1094                let ListenerSharingState { listening: _, sharing } = new_sharing_state;
1095                match sharing {
1096                    SharingState::Exclusive => Err(IncompatibleError),
1097                    SharingState::ReuseAddress => match listener {
1098                        Some(_) => Err(IncompatibleError),
1099                        None => Ok(()),
1100                    },
1101                }
1102            }
1103        }
1104    }
1105
1106    fn remove_by_id(&mut self, id: Self::Id) -> RemoveResult {
1107        match self {
1108            Self::ExclusiveBound(b) => {
1109                assert_eq!(*b, id);
1110                RemoveResult::IsLast
1111            }
1112            Self::ExclusiveListener(l) => {
1113                assert_eq!(*l, id);
1114                RemoveResult::IsLast
1115            }
1116            Self::Shared { listener, bound } => {
1117                match listener {
1118                    Some(l) if *l == id => {
1119                        *listener = None;
1120                    }
1121                    Some(_) | None => {
1122                        let index = bound.iter().position(|b| *b == id).expect("invalid socket ID");
1123                        let _: S = bound.swap_remove(index);
1124                    }
1125                };
1126                match (listener, bound.is_empty()) {
1127                    (Some(_), _) => RemoveResult::Success,
1128                    (None, false) => RemoveResult::Success,
1129                    (None, true) => RemoveResult::IsLast,
1130                }
1131            }
1132        }
1133    }
1134
1135    fn try_get_inserter<'a, 'b>(
1136        &'b mut self,
1137        new_sharing_state: &'a Self::SharingState,
1138    ) -> Result<Self::Inserter<'b>, IncompatibleError> {
1139        match self {
1140            Self::ExclusiveBound(_) | Self::ExclusiveListener(_) => Err(IncompatibleError),
1141            Self::Shared { listener, bound } => {
1142                let ListenerSharingState { listening, sharing } = new_sharing_state;
1143                match sharing {
1144                    SharingState::Exclusive => Err(IncompatibleError),
1145                    SharingState::ReuseAddress => {
1146                        match listener {
1147                            Some(_) => {
1148                                // Always fail to insert if there is already a
1149                                // listening socket.
1150                                Err(IncompatibleError)
1151                            }
1152                            None => Ok(match listening {
1153                                true => ListenerAddrInserter::Listener(listener),
1154                                false => ListenerAddrInserter::Bound(bound),
1155                            }),
1156                        }
1157                    }
1158                }
1159            }
1160        }
1161    }
1162}
1163
1164impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
1165    SocketMapUpdateSharingPolicy<
1166        ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, D>,
1167        ListenerSharingState,
1168        I,
1169        D,
1170        TcpPortSpec,
1171    > for TcpSocketSpec<I, D, BT>
1172{
1173    fn allows_sharing_update(
1174        socketmap: &SocketMap<AddrVec<I, D, TcpPortSpec>, Bound<Self>>,
1175        addr: &ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, D>,
1176        ListenerSharingState{listening: old_listening, sharing: old_sharing}: &ListenerSharingState,
1177        ListenerSharingState{listening: new_listening, sharing: new_sharing}: &ListenerSharingState,
1178    ) -> Result<(), UpdateSharingError> {
1179        let ListenerAddr { device, ip } = addr;
1180        match (old_listening, new_listening) {
1181            (true, false) => (), // Changing a listener to bound is always okay.
1182            (true, true) | (false, false) => (), // No change
1183            (false, true) => {
1184                // Upgrading a bound socket to a listener requires no other listeners on similar
1185                // addresses. This boils down to checking for listeners on either
1186                //   1. addresses that this address shadows, or
1187                //   2. addresses that shadow this address.
1188
1189                // First, check for condition (1).
1190                let addr = AddrVec::Listen(addr.clone());
1191                for a in addr.iter_shadows() {
1192                    if let Some(s) = socketmap.get(&a) {
1193                        match s {
1194                            Bound::Conn(c) => {
1195                                unreachable!("found conn state {c:?} at listener addr {a:?}")
1196                            }
1197                            Bound::Listen(l) => match l {
1198                                ListenerAddrState::ExclusiveListener(_)
1199                                | ListenerAddrState::ExclusiveBound(_) => {
1200                                    return Err(UpdateSharingError);
1201                                }
1202                                ListenerAddrState::Shared { listener, bound: _ } => {
1203                                    match listener {
1204                                        Some(_) => {
1205                                            return Err(UpdateSharingError);
1206                                        }
1207                                        None => (),
1208                                    }
1209                                }
1210                            },
1211                        }
1212                    }
1213                }
1214
1215                // Next, check for condition (2).
1216                if socketmap.descendant_counts(&ListenerAddr { device: None, ip: *ip }.into()).any(
1217                    |(AddrVecTag { state, has_device: _, sharing: _ }, _): &(_, NonZeroUsize)| {
1218                        match state {
1219                            SocketTagState::Conn | SocketTagState::Bound => false,
1220                            SocketTagState::Listener => true,
1221                        }
1222                    },
1223                ) {
1224                    return Err(UpdateSharingError);
1225                }
1226            }
1227        }
1228
1229        match (old_sharing, new_sharing) {
1230            (SharingState::Exclusive, SharingState::Exclusive)
1231            | (SharingState::ReuseAddress, SharingState::ReuseAddress)
1232            | (SharingState::Exclusive, SharingState::ReuseAddress) => (),
1233            (SharingState::ReuseAddress, SharingState::Exclusive) => {
1234                // Linux allows this, but it introduces inconsistent socket
1235                // state: if some sockets were allowed to bind because they all
1236                // had SO_REUSEADDR set, then allowing clearing SO_REUSEADDR on
1237                // one of them makes the state inconsistent. We only allow this
1238                // if it doesn't introduce inconsistencies.
1239                let root_addr = ListenerAddr {
1240                    device: None,
1241                    ip: ListenerIpAddr { addr: None, identifier: ip.identifier },
1242                };
1243
1244                let conflicts = match device {
1245                    // If the socket doesn't have a device, it conflicts with
1246                    // any listeners that shadow it or that it shadows.
1247                    None => {
1248                        socketmap.descendant_counts(&addr.clone().into()).any(
1249                            |(AddrVecTag { has_device: _, sharing: _, state }, _)| match state {
1250                                SocketTagState::Conn => false,
1251                                SocketTagState::Bound | SocketTagState::Listener => true,
1252                            },
1253                        ) || (addr != &root_addr && socketmap.get(&root_addr.into()).is_some())
1254                    }
1255                    Some(_) => {
1256                        // If the socket has a device, it will indirectly
1257                        // conflict with a listener that doesn't have a device
1258                        // that is either on the same address or the unspecified
1259                        // address (on the same port).
1260                        socketmap.descendant_counts(&root_addr.into()).any(
1261                            |(AddrVecTag { has_device, sharing: _, state }, _)| match state {
1262                                SocketTagState::Conn => false,
1263                                SocketTagState::Bound | SocketTagState::Listener => !has_device,
1264                            },
1265                        )
1266                        // Detect a conflict with a shadower (which must also
1267                        // have a device) on the same address or on a specific
1268                        // address if this socket is on the unspecified address.
1269                        || socketmap.descendant_counts(&addr.clone().into()).any(
1270                            |(AddrVecTag { has_device: _, sharing: _, state }, _)| match state {
1271                                SocketTagState::Conn => false,
1272                                SocketTagState::Bound | SocketTagState::Listener => true,
1273                            },
1274                        )
1275                    }
1276                };
1277
1278                if conflicts {
1279                    return Err(UpdateSharingError);
1280                }
1281            }
1282        }
1283
1284        Ok(())
1285    }
1286}
1287
1288impl<S: SpecSocketId> SocketMapAddrStateUpdateSharingSpec for ListenerAddrState<S> {
1289    fn try_update_sharing(
1290        &mut self,
1291        id: Self::Id,
1292        ListenerSharingState{listening: new_listening, sharing: new_sharing}: &Self::SharingState,
1293    ) -> Result<(), IncompatibleError> {
1294        match self {
1295            Self::ExclusiveBound(i) | Self::ExclusiveListener(i) => {
1296                assert_eq!(i, &id);
1297                *self = match new_sharing {
1298                    SharingState::Exclusive => match new_listening {
1299                        true => Self::ExclusiveListener(id),
1300                        false => Self::ExclusiveBound(id),
1301                    },
1302                    SharingState::ReuseAddress => {
1303                        let (listener, bound) = match new_listening {
1304                            true => (Some(id), Default::default()),
1305                            false => (None, smallvec![id]),
1306                        };
1307                        Self::Shared { listener, bound }
1308                    }
1309                };
1310                Ok(())
1311            }
1312            Self::Shared { listener, bound } => {
1313                if listener.as_ref() == Some(&id) {
1314                    match new_sharing {
1315                        SharingState::Exclusive => {
1316                            if bound.is_empty() {
1317                                *self = match new_listening {
1318                                    true => Self::ExclusiveListener(id),
1319                                    false => Self::ExclusiveBound(id),
1320                                };
1321                                Ok(())
1322                            } else {
1323                                Err(IncompatibleError)
1324                            }
1325                        }
1326                        SharingState::ReuseAddress => match new_listening {
1327                            true => Ok(()), // no-op
1328                            false => {
1329                                bound.push(id);
1330                                *listener = None;
1331                                Ok(())
1332                            }
1333                        },
1334                    }
1335                } else {
1336                    let index = bound
1337                        .iter()
1338                        .position(|b| b == &id)
1339                        .expect("ID is neither listener nor bound");
1340                    if *new_listening && listener.is_some() {
1341                        return Err(IncompatibleError);
1342                    }
1343                    match new_sharing {
1344                        SharingState::Exclusive => {
1345                            if bound.len() > 1 {
1346                                return Err(IncompatibleError);
1347                            } else {
1348                                *self = match new_listening {
1349                                    true => Self::ExclusiveListener(id),
1350                                    false => Self::ExclusiveBound(id),
1351                                };
1352                                Ok(())
1353                            }
1354                        }
1355                        SharingState::ReuseAddress => {
1356                            match new_listening {
1357                                false => Ok(()), // no-op
1358                                true => {
1359                                    let _: S = bound.swap_remove(index);
1360                                    *listener = Some(id);
1361                                    Ok(())
1362                                }
1363                            }
1364                        }
1365                    }
1366                }
1367            }
1368        }
1369    }
1370}
1371
1372#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1373pub enum SharingState {
1374    Exclusive,
1375    ReuseAddress,
1376}
1377
1378impl Default for SharingState {
1379    fn default() -> Self {
1380        Self::Exclusive
1381    }
1382}
1383
1384impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
1385    SocketMapConflictPolicy<
1386        ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, D>,
1387        ListenerSharingState,
1388        I,
1389        D,
1390        TcpPortSpec,
1391    > for TcpSocketSpec<I, D, BT>
1392{
1393    fn check_insert_conflicts(
1394        sharing: &ListenerSharingState,
1395        addr: &ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, D>,
1396        socketmap: &SocketMap<AddrVec<I, D, TcpPortSpec>, Bound<Self>>,
1397    ) -> Result<(), InsertError> {
1398        let addr = AddrVec::Listen(addr.clone());
1399        let ListenerSharingState { listening: _, sharing } = sharing;
1400        // Check if any shadow address is present, specifically, if
1401        // there is an any-listener with the same port.
1402        for a in addr.iter_shadows() {
1403            if let Some(s) = socketmap.get(&a) {
1404                match s {
1405                    Bound::Conn(c) => unreachable!("found conn state {c:?} at listener addr {a:?}"),
1406                    Bound::Listen(l) => match l {
1407                        ListenerAddrState::ExclusiveListener(_)
1408                        | ListenerAddrState::ExclusiveBound(_) => {
1409                            return Err(InsertError::ShadowAddrExists);
1410                        }
1411                        ListenerAddrState::Shared { listener, bound: _ } => match sharing {
1412                            SharingState::Exclusive => return Err(InsertError::ShadowAddrExists),
1413                            SharingState::ReuseAddress => match listener {
1414                                Some(_) => return Err(InsertError::ShadowAddrExists),
1415                                None => (),
1416                            },
1417                        },
1418                    },
1419                }
1420            }
1421        }
1422
1423        // Check if shadower exists. Note: Listeners do conflict with existing
1424        // connections, unless the listeners and connections have sharing
1425        // enabled.
1426        for (tag, _count) in socketmap.descendant_counts(&addr) {
1427            let AddrVecTag { sharing: tag_sharing, has_device: _, state: _ } = tag;
1428            match (tag_sharing, sharing) {
1429                (SharingState::Exclusive, SharingState::Exclusive | SharingState::ReuseAddress) => {
1430                    return Err(InsertError::ShadowerExists);
1431                }
1432                (SharingState::ReuseAddress, SharingState::Exclusive) => {
1433                    return Err(InsertError::ShadowerExists);
1434                }
1435                (SharingState::ReuseAddress, SharingState::ReuseAddress) => (),
1436            }
1437        }
1438        Ok(())
1439    }
1440}
1441
1442impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
1443    SocketMapConflictPolicy<
1444        ConnAddr<ConnIpAddr<I::Addr, NonZeroU16, NonZeroU16>, D>,
1445        SharingState,
1446        I,
1447        D,
1448        TcpPortSpec,
1449    > for TcpSocketSpec<I, D, BT>
1450{
1451    fn check_insert_conflicts(
1452        _sharing: &SharingState,
1453        addr: &ConnAddr<ConnIpAddr<I::Addr, NonZeroU16, NonZeroU16>, D>,
1454        socketmap: &SocketMap<AddrVec<I, D, TcpPortSpec>, Bound<Self>>,
1455    ) -> Result<(), InsertError> {
1456        // We need to make sure there are no present sockets that have the same
1457        // 5-tuple with the to-be-added socket.
1458        let addr_vec = AddrVec::Conn(addr.clone());
1459        if socketmap.get(&addr_vec).is_some() {
1460            return Err(InsertError::Exists);
1461        }
1462
1463        match &addr.device {
1464            // If the new connection does not have a device bound, check if
1465            // there is already another connection with the same 4-tuple but
1466            // a device bound. Otherwise the other connection will get all
1467            // traffic from us.
1468            None => {
1469                if socketmap.descendant_counts(&addr_vec).len() > 0 {
1470                    return Err(InsertError::ShadowerExists);
1471                }
1472            }
1473            // If the new connection has a device bound, check if there is
1474            // a different connection with the same 4-tuple but without a
1475            // device bound. Otherwise we will get all traffic from them.
1476            Some(_device) => {
1477                if socketmap.get(&AddrVec::Conn(ConnAddr { device: None, ip: addr.ip })).is_some() {
1478                    return Err(InsertError::ShadowAddrExists);
1479                }
1480            }
1481        }
1482        // Otherwise, connections don't conflict with existing listeners.
1483        Ok(())
1484    }
1485}
1486
1487#[derive(Debug)]
1488struct ConnAddrState<S> {
1489    sharing: SharingState,
1490    id: S,
1491}
1492
1493impl<S: SpecSocketId> ConnAddrState<S> {
1494    #[cfg_attr(feature = "instrumented", track_caller)]
1495    pub(crate) fn id(&self) -> S {
1496        self.id.clone()
1497    }
1498}
1499
1500impl<S: SpecSocketId> SocketMapAddrStateSpec for ConnAddrState<S> {
1501    type Id = S;
1502    type Inserter<'a> = Never;
1503    type SharingState = SharingState;
1504
1505    fn new(new_sharing_state: &Self::SharingState, id: Self::Id) -> Self {
1506        Self { sharing: *new_sharing_state, id }
1507    }
1508
1509    fn contains_id(&self, id: &Self::Id) -> bool {
1510        &self.id == id
1511    }
1512
1513    fn could_insert(
1514        &self,
1515        _new_sharing_state: &Self::SharingState,
1516    ) -> Result<(), IncompatibleError> {
1517        Err(IncompatibleError)
1518    }
1519
1520    fn remove_by_id(&mut self, id: Self::Id) -> RemoveResult {
1521        let Self { sharing: _, id: existing_id } = self;
1522        assert_eq!(*existing_id, id);
1523        return RemoveResult::IsLast;
1524    }
1525
1526    fn try_get_inserter<'a, 'b>(
1527        &'b mut self,
1528        _new_sharing_state: &'a Self::SharingState,
1529    ) -> Result<Self::Inserter<'b>, IncompatibleError> {
1530        Err(IncompatibleError)
1531    }
1532}
1533
1534#[derive(Debug, Clone)]
1535#[cfg_attr(test, derive(PartialEq))]
1536pub struct Unbound<D, Extra> {
1537    bound_device: Option<D>,
1538    buffer_sizes: BufferSizes,
1539    socket_extra: Takeable<Extra>,
1540}
1541
1542type PrimaryRc<I, D, BT> = netstack3_base::sync::PrimaryRc<ReferenceState<I, D, BT>>;
1543type StrongRc<I, D, BT> = netstack3_base::sync::StrongRc<ReferenceState<I, D, BT>>;
1544type WeakRc<I, D, BT> = netstack3_base::sync::WeakRc<ReferenceState<I, D, BT>>;
1545
1546#[derive(Derivative)]
1547#[derivative(Debug(bound = "D: Debug"))]
1548pub enum TcpSocketSetEntry<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
1549    /// The socket set is holding a primary reference.
1550    Primary(PrimaryRc<I, D, BT>),
1551    /// The socket set is holding a "dead on arrival" (DOA) entry for a strong
1552    /// reference.
1553    ///
1554    /// This mechanism guards against a subtle race between a connected socket
1555    /// created from a listener being added to the socket set and the same
1556    /// socket attempting to close itself before the listener has had a chance
1557    /// to add it to the set.
1558    ///
1559    /// See [`destroy_socket`] for the details handling this.
1560    DeadOnArrival,
1561}
1562
1563/// A thin wrapper around a hash map that keeps a set of all the known TCP
1564/// sockets in the system.
1565#[derive(Debug, Derivative)]
1566#[derivative(Default(bound = ""))]
1567pub struct TcpSocketSet<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
1568    HashMap<TcpSocketId<I, D, BT>, TcpSocketSetEntry<I, D, BT>>,
1569);
1570
1571impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> Deref
1572    for TcpSocketSet<I, D, BT>
1573{
1574    type Target = HashMap<TcpSocketId<I, D, BT>, TcpSocketSetEntry<I, D, BT>>;
1575    fn deref(&self) -> &Self::Target {
1576        &self.0
1577    }
1578}
1579
1580impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> DerefMut
1581    for TcpSocketSet<I, D, BT>
1582{
1583    fn deref_mut(&mut self) -> &mut Self::Target {
1584        &mut self.0
1585    }
1586}
1587
1588/// A custom drop impl for the entire set to make tests easier to handle.
1589///
1590/// Because [`TcpSocketId`] is not really RAII in respect to closing the socket,
1591/// tests might finish without closing them and it's easier to deal with that in
1592/// a single place.
1593impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> Drop
1594    for TcpSocketSet<I, D, BT>
1595{
1596    fn drop(&mut self) {
1597        // Listening sockets may hold references to other sockets so we walk
1598        // through all of the sockets looking for unclosed listeners and close
1599        // their accept queue so that dropping everything doesn't spring the
1600        // primary reference checks.
1601        //
1602        // Note that we don't pay attention to lock ordering here. Assuming that
1603        // when the set is dropped everything is going down and no locks are
1604        // held.
1605        let Self(map) = self;
1606        for TcpSocketId(rc) in map.keys() {
1607            let guard = rc.locked_state.read();
1608            let accept_queue = match &(*guard).socket_state {
1609                TcpSocketStateInner::Listener(Listener { accept_queue, .. }) => accept_queue,
1610                _ => continue,
1611            };
1612            if !accept_queue.is_closed() {
1613                let (_pending_sockets_iterator, _): (_, BT::ListenerNotifierOrProvidedBuffers) =
1614                    accept_queue.close();
1615            }
1616        }
1617    }
1618}
1619
1620type BoundSocketMap<I, D, BT> = socket::BoundSocketMap<I, D, TcpPortSpec, TcpSocketSpec<I, D, BT>>;
1621
1622/// TCP demux state.
1623#[derive(GenericOverIp)]
1624#[generic_over_ip(I, Ip)]
1625pub struct DemuxState<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
1626    socketmap: BoundSocketMap<I, D, BT>,
1627}
1628
1629/// Holds all the TCP socket states.
1630pub struct Sockets<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
1631    demux: RwLock<DemuxState<I, D, BT>>,
1632    // Destroy all_sockets last so the strong references in the demux are
1633    // dropped before the primary references in the set.
1634    all_sockets: RwLock<TcpSocketSet<I, D, BT>>,
1635}
1636
1637impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
1638    OrderedLockAccess<DemuxState<I, D, BT>> for Sockets<I, D, BT>
1639{
1640    type Lock = RwLock<DemuxState<I, D, BT>>;
1641    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
1642        OrderedLockRef::new(&self.demux)
1643    }
1644}
1645
1646impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
1647    OrderedLockAccess<TcpSocketSet<I, D, BT>> for Sockets<I, D, BT>
1648{
1649    type Lock = RwLock<TcpSocketSet<I, D, BT>>;
1650    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
1651        OrderedLockRef::new(&self.all_sockets)
1652    }
1653}
1654
1655/// The state held by a [`TcpSocketId`].
1656#[derive(Derivative)]
1657#[derivative(Debug(bound = "D: Debug"))]
1658pub struct ReferenceState<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
1659    locked_state: RwLock<TcpSocketState<I, D, BT>>,
1660    counters: TcpCountersWithSocket<I>,
1661}
1662
1663/// The locked state held by a TCP socket.
1664#[derive(Derivative)]
1665#[derivative(Debug(bound = "D: Debug"))]
1666pub struct TcpSocketState<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
1667    socket_state: TcpSocketStateInner<I, D, BT>,
1668    sharing: SharingState,
1669    // Options specific to the IP version.
1670    ip_options: I::DualStackIpOptions,
1671    // All other options.
1672    socket_options: SocketOptions,
1673}
1674
1675#[derive(Derivative)]
1676#[derivative(Debug(bound = "D: Debug"))]
1677pub enum TcpSocketStateInner<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
1678    Unbound(Unbound<D, BT::ListenerNotifierOrProvidedBuffers>),
1679    Bound(BoundState<I, D, BT>),
1680    Listener(Listener<I, D, BT>),
1681    Connected { conn: I::ConnectionAndAddr<D, BT>, timer: BT::Timer },
1682}
1683
1684struct TcpPortAlloc<'a, I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
1685    &'a BoundSocketMap<I, D, BT>,
1686);
1687
1688impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> PortAllocImpl
1689    for TcpPortAlloc<'_, I, D, BT>
1690{
1691    const EPHEMERAL_RANGE: RangeInclusive<u16> = 49152..=65535;
1692    type Id = Option<SocketIpAddr<I::Addr>>;
1693    /// The TCP port allocator takes an extra optional argument with a port to
1694    /// avoid.
1695    ///
1696    /// This is used to sidestep possible self-connections when allocating a
1697    /// local port on a connect call with an unset local port.
1698    type PortAvailableArg = Option<NonZeroU16>;
1699
1700    fn is_port_available(&self, addr: &Self::Id, port: u16, arg: &Option<NonZeroU16>) -> bool {
1701        let Self(socketmap) = self;
1702        // We can safely unwrap here, because the ports received in
1703        // `is_port_available` are guaranteed to be in `EPHEMERAL_RANGE`.
1704        let port = NonZeroU16::new(port).unwrap();
1705
1706        // Reject ports matching the argument.
1707        if arg.is_some_and(|a| a == port) {
1708            return false;
1709        }
1710
1711        let root_addr = AddrVec::from(ListenerAddr {
1712            ip: ListenerIpAddr { addr: *addr, identifier: port },
1713            device: None,
1714        });
1715
1716        // A port is free if there are no sockets currently using it, and if
1717        // there are no sockets that are shadowing it.
1718
1719        root_addr.iter_shadows().chain(core::iter::once(root_addr.clone())).all(|a| match &a {
1720            AddrVec::Listen(l) => socketmap.listeners().get_by_addr(&l).is_none(),
1721            AddrVec::Conn(_c) => {
1722                unreachable!("no connection shall be included in an iteration from a listener")
1723            }
1724        }) && socketmap.get_shadower_counts(&root_addr) == 0
1725    }
1726}
1727
1728struct TcpDualStackPortAlloc<'a, I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
1729    &'a BoundSocketMap<I, D, BT>,
1730    &'a BoundSocketMap<I::OtherVersion, D, BT>,
1731);
1732
1733/// When binding to IPv6 ANY address (::), we need to allocate a port that is
1734/// available in both stacks.
1735impl<'a, I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> PortAllocImpl
1736    for TcpDualStackPortAlloc<'a, I, D, BT>
1737{
1738    const EPHEMERAL_RANGE: RangeInclusive<u16> =
1739        <TcpPortAlloc<'a, I, D, BT> as PortAllocImpl>::EPHEMERAL_RANGE;
1740    type Id = ();
1741    type PortAvailableArg = ();
1742
1743    fn is_port_available(&self, (): &Self::Id, port: u16, (): &Self::PortAvailableArg) -> bool {
1744        let Self(this, other) = self;
1745        TcpPortAlloc(this).is_port_available(&None, port, &None)
1746            && TcpPortAlloc(other).is_port_available(&None, port, &None)
1747    }
1748}
1749
1750impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> Sockets<I, D, BT> {
1751    pub(crate) fn new() -> Self {
1752        Self {
1753            demux: RwLock::new(DemuxState { socketmap: Default::default() }),
1754            all_sockets: Default::default(),
1755        }
1756    }
1757}
1758
1759/// The Connection state.
1760///
1761/// Note: the `state` is not guaranteed to be [`State::Established`]. The
1762/// connection can be in any state as long as both the local and remote socket
1763/// addresses are specified.
1764#[derive(Derivative)]
1765#[derivative(Debug(bound = "D: Debug"))]
1766pub struct Connection<
1767    SockI: DualStackIpExt,
1768    WireI: DualStackIpExt,
1769    D: WeakDeviceIdentifier,
1770    BT: TcpBindingsTypes,
1771> {
1772    accept_queue: Option<
1773        AcceptQueue<
1774            TcpSocketId<SockI, D, BT>,
1775            BT::ReturnedBuffers,
1776            BT::ListenerNotifierOrProvidedBuffers,
1777        >,
1778    >,
1779    state: State<
1780        BT::Instant,
1781        BT::ReceiveBuffer,
1782        BT::SendBuffer,
1783        BT::ListenerNotifierOrProvidedBuffers,
1784    >,
1785    ip_sock: IpSock<WireI, D>,
1786    /// The user has indicated that this connection will never be used again, we
1787    /// keep the connection in the socketmap to perform the shutdown but it will
1788    /// be auto removed once the state reaches Closed.
1789    defunct: bool,
1790    /// In contrast to a hard error, which will cause a connection to be closed,
1791    /// a soft error will not abort the connection, but it can be read by either
1792    /// calling `get_socket_error`, or after the connection times out.
1793    soft_error: Option<ConnectionError>,
1794    /// Whether the handshake has finished or aborted.
1795    handshake_status: HandshakeStatus,
1796}
1797
1798impl<SockI: DualStackIpExt, WireI: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
1799    Connection<SockI, WireI, D, BT>
1800{
1801    /// Updates this connection's state to reflect the error.
1802    ///
1803    /// The connection's soft error, if previously unoccupied, holds the error.
1804    fn on_icmp_error<CC: TcpCounterContext<SockI, D, BT>>(
1805        &mut self,
1806        core_ctx: &mut CC,
1807        id: &TcpSocketId<SockI, D, BT>,
1808        seq: SeqNum,
1809        error: IcmpErrorCode,
1810    ) -> (NewlyClosed, ShouldRetransmit) {
1811        let Connection { soft_error, state, .. } = self;
1812        let (new_soft_error, newly_closed, should_send) =
1813            state.on_icmp_error(&TcpCountersRefs::from_ctx(core_ctx, id), error, seq);
1814        *soft_error = soft_error.or(new_soft_error);
1815        (newly_closed, should_send)
1816    }
1817}
1818
1819/// The Listener state.
1820///
1821/// State for sockets that participate in the passive open. Contrary to
1822/// [`Connection`], only the local address is specified.
1823#[derive(Derivative)]
1824#[derivative(Debug(bound = "D: Debug"))]
1825#[cfg_attr(
1826    test,
1827    derivative(
1828        PartialEq(
1829            bound = "BT::ReturnedBuffers: PartialEq, BT::ListenerNotifierOrProvidedBuffers: PartialEq, I::ListenerIpAddr: PartialEq"
1830        ),
1831        Eq(
1832            bound = "BT::ReturnedBuffers: Eq, BT::ListenerNotifierOrProvidedBuffers: Eq, I::ListenerIpAddr: Eq"
1833        ),
1834    )
1835)]
1836pub struct Listener<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
1837    addr: ListenerAddr<I::ListenerIpAddr, D>,
1838    backlog: NonZeroUsize,
1839    accept_queue: AcceptQueue<
1840        TcpSocketId<I, D, BT>,
1841        BT::ReturnedBuffers,
1842        BT::ListenerNotifierOrProvidedBuffers,
1843    >,
1844    buffer_sizes: BufferSizes,
1845    // If ip sockets can be half-specified so that only the local address
1846    // is needed, we can construct an ip socket here to be reused.
1847}
1848
1849impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> Listener<I, D, BT> {
1850    fn new(
1851        addr: ListenerAddr<I::ListenerIpAddr, D>,
1852        backlog: NonZeroUsize,
1853        buffer_sizes: BufferSizes,
1854        notifier: BT::ListenerNotifierOrProvidedBuffers,
1855    ) -> Self {
1856        Self { addr, backlog, accept_queue: AcceptQueue::new(notifier), buffer_sizes }
1857    }
1858}
1859
1860#[derive(Clone, Derivative)]
1861#[derivative(Debug(bound = "D: Debug"))]
1862#[cfg_attr(test, derive(Eq, PartialEq))]
1863pub struct BoundState<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
1864    addr: ListenerAddr<I::ListenerIpAddr, D>,
1865    buffer_sizes: BufferSizes,
1866    socket_extra: Takeable<BT::ListenerNotifierOrProvidedBuffers>,
1867}
1868
1869/// A TCP Socket ID.
1870#[derive(Derivative, GenericOverIp)]
1871#[generic_over_ip(I, Ip)]
1872#[derivative(Eq(bound = ""), PartialEq(bound = ""), Hash(bound = ""))]
1873pub struct TcpSocketId<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
1874    StrongRc<I, D, BT>,
1875);
1876
1877impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> Clone
1878    for TcpSocketId<I, D, BT>
1879{
1880    #[cfg_attr(feature = "instrumented", track_caller)]
1881    fn clone(&self) -> Self {
1882        let Self(rc) = self;
1883        Self(StrongRc::clone(rc))
1884    }
1885}
1886
1887impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> TcpSocketId<I, D, BT> {
1888    pub(crate) fn new(
1889        socket_state: TcpSocketStateInner<I, D, BT>,
1890        socket_options: SocketOptions,
1891    ) -> (Self, PrimaryRc<I, D, BT>) {
1892        let primary = PrimaryRc::new(ReferenceState {
1893            locked_state: RwLock::new(TcpSocketState {
1894                socket_state,
1895                sharing: Default::default(),
1896                ip_options: Default::default(),
1897                socket_options,
1898            }),
1899            counters: Default::default(),
1900        });
1901        let socket = Self(PrimaryRc::clone_strong(&primary));
1902        (socket, primary)
1903    }
1904
1905    pub(crate) fn new_cyclic<
1906        F: FnOnce(WeakTcpSocketId<I, D, BT>) -> TcpSocketStateInner<I, D, BT>,
1907    >(
1908        init: F,
1909        sharing: SharingState,
1910        socket_options: SocketOptions,
1911    ) -> (Self, PrimaryRc<I, D, BT>) {
1912        let primary = PrimaryRc::new_cyclic(move |weak| {
1913            let socket_state = init(WeakTcpSocketId(weak));
1914            ReferenceState {
1915                locked_state: RwLock::new(TcpSocketState {
1916                    socket_state,
1917                    sharing,
1918                    ip_options: Default::default(),
1919                    socket_options,
1920                }),
1921                counters: Default::default(),
1922            }
1923        });
1924        let socket = Self(PrimaryRc::clone_strong(&primary));
1925        (socket, primary)
1926    }
1927
1928    /// Obtains the counters tracked for this TCP socket.
1929    pub fn counters(&self) -> &TcpCountersWithSocket<I> {
1930        let Self(rc) = self;
1931        &rc.counters
1932    }
1933
1934    pub(crate) fn trace_id(&self) -> TraceResourceId<'_> {
1935        let Self(inner) = self;
1936        TraceResourceId::new(inner.resource_token())
1937    }
1938
1939    /// Returns `SocketCookie` for the socket.
1940    pub fn socket_cookie(&self) -> SocketCookie {
1941        let Self(inner) = self;
1942        SocketCookie::new(inner.resource_token())
1943    }
1944
1945    pub(crate) fn either(&self) -> EitherTcpSocketId<'_, D, BT> {
1946        I::map_ip_in(self, EitherTcpSocketId::V4, EitherTcpSocketId::V6)
1947    }
1948
1949    pub(crate) fn get_bound_device<CC>(&self, core_ctx: &mut CC) -> Option<D>
1950    where
1951        CC: TcpContext<I, BT, WeakDeviceId = D>,
1952    {
1953        core_ctx.with_socket(self, |state| match &state.socket_state {
1954            TcpSocketStateInner::Unbound(state) => state.bound_device.clone(),
1955            TcpSocketStateInner::Listener(Listener { addr, .. })
1956            | TcpSocketStateInner::Bound(BoundState { addr, .. }) => addr.device.clone(),
1957            TcpSocketStateInner::Connected { conn, .. } => I::get_conn_info(&conn).device,
1958        })
1959    }
1960}
1961
1962impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> Debug
1963    for TcpSocketId<I, D, BT>
1964{
1965    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1966        let Self(rc) = self;
1967        f.debug_tuple("TcpSocketId").field(&StrongRc::debug_id(rc)).finish()
1968    }
1969}
1970
1971impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> TcpSocketId<I, D, BT> {
1972    pub(crate) fn downgrade(&self) -> WeakTcpSocketId<I, D, BT> {
1973        let Self(this) = self;
1974        WeakTcpSocketId(StrongRc::downgrade(this))
1975    }
1976}
1977
1978impl<CC, I, BT> SocketMetadata<CC> for TcpSocketId<I, CC::WeakDeviceId, BT>
1979where
1980    CC: ?Sized + TcpContext<I, BT>,
1981    I: DualStackIpExt,
1982    BT: TcpBindingsTypes,
1983{
1984    fn socket_cookie(&self, _core_ctx: &mut CC) -> SocketCookie {
1985        self.socket_cookie()
1986    }
1987
1988    fn marks(&self, core_ctx: &mut CC) -> Marks {
1989        core_ctx.with_socket(self, |state| state.socket_options.ip_options.marks.clone())
1990    }
1991}
1992
1993/// A Weak TCP Socket ID.
1994#[derive(Derivative, GenericOverIp)]
1995#[generic_over_ip(I, Ip)]
1996#[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Hash(bound = ""))]
1997pub struct WeakTcpSocketId<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
1998    WeakRc<I, D, BT>,
1999);
2000
2001impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> Debug
2002    for WeakTcpSocketId<I, D, BT>
2003{
2004    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2005        let Self(rc) = self;
2006        f.debug_tuple("WeakTcpSocketId").field(&rc.debug_id()).finish()
2007    }
2008}
2009
2010impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
2011    PartialEq<TcpSocketId<I, D, BT>> for WeakTcpSocketId<I, D, BT>
2012{
2013    fn eq(&self, other: &TcpSocketId<I, D, BT>) -> bool {
2014        let Self(this) = self;
2015        let TcpSocketId(other) = other;
2016        StrongRc::weak_ptr_eq(other, this)
2017    }
2018}
2019
2020impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> WeakTcpSocketId<I, D, BT> {
2021    /// Tries to upgrade to a strong reference.
2022    #[cfg_attr(feature = "instrumented", track_caller)]
2023    pub fn upgrade(&self) -> Option<TcpSocketId<I, D, BT>> {
2024        let Self(this) = self;
2025        this.upgrade().map(TcpSocketId)
2026    }
2027}
2028
2029impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>
2030    OrderedLockAccess<TcpSocketState<I, D, BT>> for TcpSocketId<I, D, BT>
2031{
2032    type Lock = RwLock<TcpSocketState<I, D, BT>>;
2033    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
2034        let Self(rc) = self;
2035        OrderedLockRef::new(&rc.locked_state)
2036    }
2037}
2038
2039/// A borrow of either an IPv4 or IPv6 TCP socket.
2040///
2041/// This type is used to implement [`StateMachineDebugId`] in a way that doesn't
2042/// taint the state machine with IP-specific types, avoiding code generation
2043/// duplication.
2044#[derive(Derivative)]
2045#[derivative(Debug(bound = ""))]
2046pub(crate) enum EitherTcpSocketId<'a, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> {
2047    #[derivative(Debug = "transparent")]
2048    V4(&'a TcpSocketId<Ipv4, D, BT>),
2049    #[derivative(Debug = "transparent")]
2050    V6(&'a TcpSocketId<Ipv6, D, BT>),
2051}
2052
2053impl<D: WeakDeviceIdentifier, BT: TcpBindingsTypes> StateMachineDebugId
2054    for EitherTcpSocketId<'_, D, BT>
2055{
2056    fn trace_id(&self) -> TraceResourceId<'_> {
2057        match self {
2058            Self::V4(v4) => v4.trace_id(),
2059            Self::V6(v6) => v6.trace_id(),
2060        }
2061    }
2062}
2063
2064/// The status of a handshake.
2065#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2066pub enum HandshakeStatus {
2067    /// The handshake is still pending.
2068    Pending,
2069    /// The handshake is aborted.
2070    Aborted,
2071    /// The handshake is completed.
2072    Completed {
2073        /// Whether it has been reported to the user yet.
2074        reported: bool,
2075    },
2076}
2077
2078impl HandshakeStatus {
2079    fn update_if_pending(&mut self, new_status: Self) -> bool {
2080        if *self == HandshakeStatus::Pending {
2081            *self = new_status;
2082            true
2083        } else {
2084            false
2085        }
2086    }
2087}
2088
2089/// Resolves the demux local address and bound device for the `bind` operation.
2090fn bind_get_local_addr_and_device<I, BT, CC>(
2091    core_ctx: &mut CC,
2092    addr: Option<ZonedAddr<SocketIpAddr<I::Addr>, CC::DeviceId>>,
2093    bound_device: &Option<CC::WeakDeviceId>,
2094) -> Result<(Option<SocketIpAddr<I::Addr>>, Option<CC::WeakDeviceId>), LocalAddressError>
2095where
2096    I: DualStackIpExt,
2097    BT: TcpBindingsTypes,
2098    CC: TransportIpContext<I, BT>,
2099{
2100    let (local_ip, device) = match addr {
2101        Some(addr) => {
2102            // Extract the specified address and the device. The
2103            // device is either the one from the address or the one
2104            // to which the socket was previously bound.
2105            let (addr, required_device) = addr
2106                .resolve_addr_with_device(bound_device.clone())
2107                .map_err(LocalAddressError::Zone)?;
2108
2109            // TCP sockets cannot bind to multicast addresses.
2110            // TODO(https://fxbug.dev/424874749): Put this check in a witness type.
2111            if addr.addr().is_multicast()
2112                || I::map_ip_in(addr.addr(), |ip| ip.is_limited_broadcast(), |_| false)
2113            {
2114                return Err(LocalAddressError::CannotBindToAddress);
2115            }
2116
2117            core_ctx.with_devices_with_assigned_addr(addr.clone().into(), |mut assigned_to| {
2118                if !assigned_to.any(|d| {
2119                    required_device
2120                        .as_ref()
2121                        .map_or(true, |device| device == &EitherDeviceId::Strong(d))
2122                }) {
2123                    Err(LocalAddressError::AddressMismatch)
2124                } else {
2125                    Ok(())
2126                }
2127            })?;
2128            (Some(addr), required_device)
2129        }
2130        None => (None, bound_device.clone().map(EitherDeviceId::Weak)),
2131    };
2132    let weak_device = device.map(|d| d.as_weak().into_owned());
2133    Ok((local_ip, weak_device))
2134}
2135
2136fn bind_install_in_demux<I, D, BC>(
2137    bindings_ctx: &mut BC,
2138    demux_socket_id: I::DemuxSocketId<D, BC>,
2139    local_ip: Option<SocketIpAddr<I::Addr>>,
2140    weak_device: Option<D>,
2141    port: Option<NonZeroU16>,
2142    sharing: SharingState,
2143    DemuxState { socketmap }: &mut DemuxState<I, D, BC>,
2144) -> Result<ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, D>, LocalAddressError>
2145where
2146    I: DualStackIpExt,
2147    BC: TcpBindingsTypes + RngContext,
2148    D: WeakDeviceIdentifier,
2149{
2150    let port = match port {
2151        None => {
2152            match netstack3_base::simple_randomized_port_alloc(
2153                &mut bindings_ctx.rng(),
2154                &local_ip,
2155                &TcpPortAlloc(socketmap),
2156                &None,
2157            ) {
2158                Some(port) => NonZeroU16::new(port).expect("ephemeral ports must be non-zero"),
2159                None => {
2160                    return Err(LocalAddressError::FailedToAllocateLocalPort);
2161                }
2162            }
2163        }
2164        Some(port) => port,
2165    };
2166
2167    let addr = ListenerAddr {
2168        ip: ListenerIpAddr { addr: local_ip, identifier: port },
2169        device: weak_device,
2170    };
2171    let sharing = ListenerSharingState { sharing, listening: false };
2172
2173    let _inserted = socketmap
2174        .listeners_mut()
2175        .try_insert(addr.clone(), sharing, demux_socket_id)
2176        .map_err(Into::<LocalAddressError>::into)?;
2177
2178    Ok(addr)
2179}
2180
2181fn try_update_listener_sharing<I, CC, BT>(
2182    core_ctx: MaybeDualStack<
2183        (&mut CC::DualStackIpTransportAndDemuxCtx<'_>, CC::DualStackConverter),
2184        (&mut CC::SingleStackIpTransportAndDemuxCtx<'_>, CC::SingleStackConverter),
2185    >,
2186    id: &TcpSocketId<I, CC::WeakDeviceId, BT>,
2187    addr: ListenerAddr<I::ListenerIpAddr, CC::WeakDeviceId>,
2188    sharing: &ListenerSharingState,
2189    new_sharing: ListenerSharingState,
2190) -> Result<(), UpdateSharingError>
2191where
2192    I: DualStackIpExt,
2193    CC: TcpContext<I, BT>,
2194    BT: TcpBindingsTypes,
2195{
2196    match core_ctx {
2197        MaybeDualStack::NotDualStack((core_ctx, converter)) => {
2198            core_ctx.with_demux_mut(|DemuxState { socketmap }| {
2199                let mut entry = socketmap
2200                    .listeners_mut()
2201                    .entry(&I::into_demux_socket_id(id.clone()), &converter.convert(addr))
2202                    .expect("invalid listener id");
2203                entry.try_update_sharing(sharing, new_sharing)
2204            })
2205        }
2206        MaybeDualStack::DualStack((core_ctx, converter)) => match converter.convert(addr) {
2207            ListenerAddr { ip: DualStackListenerIpAddr::ThisStack(ip), device } => {
2208                TcpDemuxContext::<I, _, _>::with_demux_mut(core_ctx, |DemuxState { socketmap }| {
2209                    let mut entry = socketmap
2210                        .listeners_mut()
2211                        .entry(&I::into_demux_socket_id(id.clone()), &ListenerAddr { ip, device })
2212                        .expect("invalid listener id");
2213                    entry.try_update_sharing(sharing, new_sharing)
2214                })
2215            }
2216            ListenerAddr { ip: DualStackListenerIpAddr::OtherStack(ip), device } => {
2217                let demux_id = core_ctx.into_other_demux_socket_id(id.clone());
2218                TcpDemuxContext::<I::OtherVersion, _, _>::with_demux_mut(
2219                    core_ctx,
2220                    |DemuxState { socketmap }| {
2221                        let mut entry = socketmap
2222                            .listeners_mut()
2223                            .entry(&demux_id, &ListenerAddr { ip, device })
2224                            .expect("invalid listener id");
2225                        entry.try_update_sharing(sharing, new_sharing)
2226                    },
2227                )
2228            }
2229            ListenerAddr { ip: DualStackListenerIpAddr::BothStacks(port), device } => {
2230                let other_demux_id = core_ctx.into_other_demux_socket_id(id.clone());
2231                let demux_id = I::into_demux_socket_id(id.clone());
2232                core_ctx.with_both_demux_mut(
2233                    |DemuxState { socketmap: this_socketmap, .. },
2234                     DemuxState { socketmap: other_socketmap, .. }| {
2235                        let this_stack_listener_addr = ListenerAddr {
2236                            ip: ListenerIpAddr { addr: None, identifier: port },
2237                            device: device.clone(),
2238                        };
2239                        let mut this_stack_entry = this_socketmap
2240                            .listeners_mut()
2241                            .entry(&demux_id, &this_stack_listener_addr)
2242                            .expect("invalid listener id");
2243                        this_stack_entry.try_update_sharing(sharing, new_sharing)?;
2244                        let mut other_stack_entry = other_socketmap
2245                            .listeners_mut()
2246                            .entry(
2247                                &other_demux_id,
2248                                &ListenerAddr {
2249                                    ip: ListenerIpAddr { addr: None, identifier: port },
2250                                    device,
2251                                },
2252                            )
2253                            .expect("invalid listener id");
2254                        match other_stack_entry.try_update_sharing(sharing, new_sharing) {
2255                            Ok(()) => Ok(()),
2256                            Err(err) => {
2257                                this_stack_entry
2258                                    .try_update_sharing(&new_sharing, *sharing)
2259                                    .expect("failed to revert the sharing setting");
2260                                Err(err)
2261                            }
2262                        }
2263                    },
2264                )
2265            }
2266        },
2267    }
2268}
2269
2270struct ErrorReporter<'a, I, R, S, ActiveOpen> {
2271    state: &'a mut State<I, R, S, ActiveOpen>,
2272    soft_error: &'a mut Option<ConnectionError>,
2273}
2274
2275impl<'a, I, R, S, ActiveOpen> ErrorReporter<'a, I, R, S, ActiveOpen> {
2276    fn report_error(self) -> Option<ConnectionError> {
2277        let Self { state, soft_error } = self;
2278        if let State::Closed(Closed { reason }) = state {
2279            if let Some(hard_error) = reason.take() {
2280                return Some(hard_error);
2281            }
2282        }
2283        soft_error.take()
2284    }
2285
2286    fn new(
2287        state: &'a mut State<I, R, S, ActiveOpen>,
2288        soft_error: &'a mut Option<ConnectionError>,
2289    ) -> Self {
2290        Self { state, soft_error }
2291    }
2292}
2293
2294/// The TCP socket API.
2295pub struct TcpApi<I: Ip, C>(C, IpVersionMarker<I>);
2296
2297impl<I: Ip, C> TcpApi<I, C> {
2298    /// Creates a new `TcpApi` from `ctx`.
2299    pub fn new(ctx: C) -> Self {
2300        Self(ctx, IpVersionMarker::new())
2301    }
2302}
2303
2304/// A local alias for [`TcpSocketId`] for use in [`TcpApi`].
2305///
2306/// TODO(https://github.com/rust-lang/rust/issues/8995): Make this an inherent
2307/// associated type.
2308type TcpApiSocketId<I, C> = TcpSocketId<
2309    I,
2310    <<C as ContextPair>::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId,
2311    <C as ContextPair>::BindingsContext,
2312>;
2313
2314impl<I, C> TcpApi<I, C>
2315where
2316    I: DualStackIpExt,
2317    C: ContextPair,
2318    C::CoreContext: TcpContext<I, C::BindingsContext>,
2319    C::BindingsContext: TcpBindingsContext<
2320        <<C as ContextPair>::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId,
2321    >,
2322{
2323    pub(crate) fn core_ctx(&mut self) -> &mut C::CoreContext {
2324        let Self(pair, IpVersionMarker { .. }) = self;
2325        pair.core_ctx()
2326    }
2327
2328    pub(crate) fn contexts(&mut self) -> (&mut C::CoreContext, &mut C::BindingsContext) {
2329        let Self(pair, IpVersionMarker { .. }) = self;
2330        pair.contexts()
2331    }
2332
2333    /// Creates a new socket in unbound state.
2334    pub fn create(
2335        &mut self,
2336        socket_extra: <C::BindingsContext as TcpBindingsTypes>::ListenerNotifierOrProvidedBuffers,
2337    ) -> TcpApiSocketId<I, C> {
2338        let (core_ctx, bindings_ctx) = self.contexts();
2339        let settings = bindings_ctx.settings();
2340        let buffer_sizes = BufferSizes {
2341            send: settings.send_buffer.default().get(),
2342            receive: settings.receive_buffer.default().get(),
2343        };
2344        core_ctx.with_all_sockets_mut(|all_sockets| {
2345            let (sock, primary) = TcpSocketId::new(
2346                TcpSocketStateInner::Unbound(Unbound {
2347                    bound_device: Default::default(),
2348                    buffer_sizes,
2349                    socket_extra: Takeable::new(socket_extra),
2350                }),
2351                SocketOptions::default(),
2352            );
2353            assert_matches::assert_matches!(
2354                all_sockets.insert(sock.clone(), TcpSocketSetEntry::Primary(primary)),
2355                None
2356            );
2357            sock
2358        })
2359    }
2360
2361    /// Binds an unbound socket to a local socket address.
2362    ///
2363    /// Requests that the given socket be bound to the local address, if one is
2364    /// provided; otherwise to all addresses. If `port` is specified (is
2365    /// `Some`), the socket will be bound to that port. Otherwise a port will be
2366    /// selected to not conflict with existing bound or connected sockets.
2367    pub fn bind(
2368        &mut self,
2369        id: &TcpApiSocketId<I, C>,
2370        addr: Option<
2371            ZonedAddr<
2372                SpecifiedAddr<I::Addr>,
2373                <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId,
2374            >,
2375        >,
2376        port: Option<NonZeroU16>,
2377    ) -> Result<(), BindError> {
2378        #[derive(GenericOverIp)]
2379        #[generic_over_ip(I, Ip)]
2380        enum BindAddr<I: DualStackIpExt, D> {
2381            BindInBothStacks,
2382            BindInOneStack(
2383                EitherStack<
2384                    Option<ZonedAddr<SocketIpAddr<I::Addr>, D>>,
2385                    Option<ZonedAddr<SocketIpAddr<<I::OtherVersion as Ip>::Addr>, D>>,
2386                >,
2387            ),
2388        }
2389        debug!("bind {id:?} to {addr:?}:{port:?}");
2390        let bind_addr = match addr {
2391            None => I::map_ip(
2392                (),
2393                |()| BindAddr::BindInOneStack(EitherStack::ThisStack(None)),
2394                |()| BindAddr::BindInBothStacks,
2395            ),
2396            Some(addr) => match DualStackLocalIp::<I, _>::new(addr) {
2397                DualStackLocalIp::ThisStack(addr) => {
2398                    BindAddr::BindInOneStack(EitherStack::ThisStack(Some(addr)))
2399                }
2400                DualStackLocalIp::OtherStack(addr) => {
2401                    BindAddr::BindInOneStack(EitherStack::OtherStack(addr))
2402                }
2403            },
2404        };
2405
2406        let (core_ctx, bindings_ctx) = self.contexts();
2407        let result = core_ctx.with_socket_mut_transport_demux(id, |core_ctx, socket_state| {
2408            let TcpSocketState { socket_state, sharing, ip_options, socket_options: _ } = socket_state;
2409            let Unbound { bound_device, buffer_sizes, socket_extra } =
2410                match socket_state {
2411                    TcpSocketStateInner::Unbound(u) => u,
2412                    TcpSocketStateInner::Bound(_)
2413                    |TcpSocketStateInner::Listener(_)
2414                    | TcpSocketStateInner::Connected{..}
2415                     => return Err(BindError::AlreadyBound),
2416                };
2417
2418            let listener_addr = match core_ctx {
2419                MaybeDualStack::NotDualStack((core_ctx, converter)) => match bind_addr {
2420                    BindAddr::BindInOneStack(EitherStack::ThisStack(local_addr)) => {
2421                        let (local_addr, device) = bind_get_local_addr_and_device(core_ctx, local_addr, bound_device)?;
2422                        let addr =
2423                            core_ctx.with_demux_mut(|demux| {
2424                                bind_install_in_demux(
2425                                    bindings_ctx,
2426                                    I::into_demux_socket_id(id.clone()),
2427                                    local_addr,
2428                                    device,
2429                                    port,
2430                                    *sharing,
2431                                    demux,
2432                                )
2433                            })?;
2434                        converter.convert_back(addr)
2435                    }
2436                    BindAddr::BindInOneStack(EitherStack::OtherStack(_)) | BindAddr::BindInBothStacks => {
2437                        return Err(LocalAddressError::CannotBindToAddress.into());
2438                    }
2439                },
2440                MaybeDualStack::DualStack((core_ctx, converter)) => {
2441                    let bind_addr = match (
2442                            core_ctx.dual_stack_enabled(&ip_options),
2443                            bind_addr
2444                        ) {
2445                        // Allow binding in both stacks when dual stack is
2446                        // enabled.
2447                        (true, BindAddr::BindInBothStacks)
2448                            => BindAddr::<I, _>::BindInBothStacks,
2449                        // Only bind in this stack if dual stack is not enabled.
2450                        (false, BindAddr::BindInBothStacks)
2451                            => BindAddr::BindInOneStack(EitherStack::ThisStack(None)),
2452                        // Binding to this stack is always allowed.
2453                        (true | false, BindAddr::BindInOneStack(EitherStack::ThisStack(ip)))
2454                            => BindAddr::BindInOneStack(EitherStack::ThisStack(ip)),
2455                        // Can bind to the other stack only when dual stack is
2456                        // enabled, otherwise an error is returned.
2457                        (true, BindAddr::BindInOneStack(EitherStack::OtherStack(ip)))
2458                            => BindAddr::BindInOneStack(EitherStack::OtherStack(ip)),
2459                        (false, BindAddr::BindInOneStack(EitherStack::OtherStack(_)))
2460                            => return Err(LocalAddressError::CannotBindToAddress.into()),
2461                    };
2462                    match bind_addr {
2463                        BindAddr::BindInOneStack(EitherStack::ThisStack(addr)) => {
2464                            let (addr, device) = bind_get_local_addr_and_device::<I, _, _>(core_ctx, addr, bound_device)?;
2465                            let ListenerAddr { ip, device } =
2466                                core_ctx.with_demux_mut(|demux: &mut DemuxState<I, _, _>| {
2467                                    bind_install_in_demux(
2468                                        bindings_ctx,
2469                                        I::into_demux_socket_id(id.clone()),
2470                                        addr,
2471                                        device,
2472                                        port,
2473                                        *sharing,
2474                                        demux,
2475                                    )
2476                                })?;
2477                            converter.convert_back(ListenerAddr {
2478                                ip: DualStackListenerIpAddr::ThisStack(ip),
2479                                device,
2480                            })
2481                        }
2482                        BindAddr::BindInOneStack(EitherStack::OtherStack(addr)) => {
2483                            let other_demux_id = core_ctx.into_other_demux_socket_id(id.clone());
2484                            let (addr, device) = bind_get_local_addr_and_device::<I::OtherVersion, _, _>(core_ctx, addr, bound_device)?;
2485                            let ListenerAddr { ip, device } =
2486                                core_ctx.with_demux_mut(|demux: &mut DemuxState<I::OtherVersion, _, _>| {
2487                                    bind_install_in_demux(
2488                                        bindings_ctx,
2489                                        other_demux_id,
2490                                        addr,
2491                                        device,
2492                                        port,
2493                                        *sharing,
2494                                        demux,
2495                                    )
2496                                })?;
2497                            converter.convert_back(ListenerAddr {
2498                                ip: DualStackListenerIpAddr::OtherStack(ip),
2499                                device,
2500                            })
2501                        }
2502                        BindAddr::BindInBothStacks => {
2503                            let other_demux_id = core_ctx.into_other_demux_socket_id(id.clone());
2504                            let (port, device) =
2505                                core_ctx.with_both_demux_mut(|demux, other_demux| {
2506                                    // We need to allocate the port for both
2507                                    // stacks before `bind_inner` tries to make
2508                                    // a decision, because it might give two
2509                                    // unrelated ports which is undesired.
2510                                    let port_alloc = TcpDualStackPortAlloc(
2511                                        &demux.socketmap,
2512                                        &other_demux.socketmap
2513                                    );
2514                                    let port = match port {
2515                                        Some(port) => port,
2516                                        None => match netstack3_base::simple_randomized_port_alloc(
2517                                            &mut bindings_ctx.rng(),
2518                                            &(),
2519                                            &port_alloc,
2520                                            &(),
2521                                        ){
2522                                            Some(port) => NonZeroU16::new(port)
2523                                                .expect("ephemeral ports must be non-zero"),
2524                                            None => {
2525                                                return Err(LocalAddressError::FailedToAllocateLocalPort);
2526                                            }
2527                                        }
2528                                    };
2529                                    let this_stack_addr = bind_install_in_demux(
2530                                        bindings_ctx,
2531                                        I::into_demux_socket_id(id.clone()),
2532                                        None,
2533                                        bound_device.clone(),
2534                                        Some(port),
2535                                        *sharing,
2536                                        demux,
2537                                    )?;
2538                                    match bind_install_in_demux(
2539                                        bindings_ctx,
2540                                        other_demux_id,
2541                                        None,
2542                                        bound_device.clone(),
2543                                        Some(port),
2544                                        *sharing,
2545                                        other_demux,
2546                                    ) {
2547                                        Ok(ListenerAddr { ip, device }) => {
2548                                            assert_eq!(this_stack_addr.ip.identifier, ip.identifier);
2549                                            Ok((port, device))
2550                                        }
2551                                        Err(err) => {
2552                                            demux.socketmap.listeners_mut().remove(&I::into_demux_socket_id(id.clone()), &this_stack_addr).expect("failed to unbind");
2553                                            Err(err)
2554                                        }
2555                                    }
2556                                })?;
2557                            converter.convert_back(ListenerAddr {
2558                                ip: DualStackListenerIpAddr::BothStacks(port),
2559                                device,
2560                            })
2561                        }
2562                    }
2563                },
2564            };
2565
2566            *socket_state = TcpSocketStateInner::Bound(BoundState {
2567                addr: listener_addr,
2568                buffer_sizes: buffer_sizes.clone(),
2569                socket_extra: Takeable::from_ref(socket_extra.to_ref()),
2570            });
2571
2572            Ok(())
2573        });
2574        match &result {
2575            Err(BindError::LocalAddressError(LocalAddressError::FailedToAllocateLocalPort)) => {
2576                core_ctx.increment_both(id, |c| &c.failed_port_reservations);
2577            }
2578            Err(_) | Ok(_) => {}
2579        }
2580        result
2581    }
2582
2583    /// Listens on an already bound socket.
2584    pub fn listen(
2585        &mut self,
2586        id: &TcpApiSocketId<I, C>,
2587        backlog: NonZeroUsize,
2588    ) -> Result<(), ListenError> {
2589        debug!("listen on {id:?} with backlog {backlog}");
2590        self.core_ctx().with_socket_mut_transport_demux(id, |core_ctx, socket_state| {
2591            let TcpSocketState { socket_state, sharing, ip_options: _, socket_options: _ } =
2592                socket_state;
2593            let BoundState { addr, buffer_sizes, socket_extra } = match socket_state {
2594                TcpSocketStateInner::Bound(bound_state) => bound_state,
2595                TcpSocketStateInner::Connected { .. }
2596                | TcpSocketStateInner::Unbound(_)
2597                | TcpSocketStateInner::Listener(_) => {
2598                    return Err(ListenError::NotSupported);
2599                }
2600            };
2601            try_update_listener_sharing::<_, C::CoreContext, _>(
2602                core_ctx,
2603                id,
2604                addr.clone(),
2605                &ListenerSharingState { sharing: *sharing, listening: false },
2606                ListenerSharingState { sharing: *sharing, listening: true },
2607            )
2608            .map_err(|UpdateSharingError| ListenError::ListenerExists)?;
2609
2610            *socket_state = TcpSocketStateInner::Listener(Listener::new(
2611                addr.clone(),
2612                backlog,
2613                buffer_sizes.clone(),
2614                socket_extra.to_ref().take(),
2615            ));
2616            Ok(())
2617        })
2618    }
2619
2620    /// Accepts an established socket from the queue of a listener socket.
2621    ///
2622    /// Note: The accepted socket will have the marks of the incoming SYN
2623    /// instead of the listener itself.
2624    pub fn accept(
2625        &mut self,
2626        id: &TcpApiSocketId<I, C>,
2627    ) -> Result<
2628        (
2629            TcpApiSocketId<I, C>,
2630            SocketAddr<I::Addr, <C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
2631            <C::BindingsContext as TcpBindingsTypes>::ReturnedBuffers,
2632        ),
2633        AcceptError,
2634    > {
2635        let (conn_id, client_buffers) = self.core_ctx().with_socket_mut(id, |socket_state| {
2636            debug!("accept on {id:?}");
2637            let accept_queue = match &mut socket_state.socket_state {
2638                TcpSocketStateInner::Listener(Listener { accept_queue, .. }) => accept_queue,
2639                TcpSocketStateInner::Unbound(_)
2640                | TcpSocketStateInner::Bound(_)
2641                | TcpSocketStateInner::Connected { .. } => {
2642                    return Err(AcceptError::NotSupported);
2643                }
2644            };
2645            let (conn_id, client_buffers) =
2646                accept_queue.pop_ready().ok_or(AcceptError::WouldBlock)?;
2647
2648            Ok::<_, AcceptError>((conn_id, client_buffers))
2649        })?;
2650
2651        let remote_addr =
2652            self.core_ctx().with_socket_mut_and_converter(&conn_id, |socket_state, _converter| {
2653                let conn_and_addr = assert_matches!(
2654                    &mut socket_state.socket_state,
2655                    TcpSocketStateInner::Connected{ conn, .. } => conn,
2656                    "invalid socket ID"
2657                );
2658                *I::get_accept_queue_mut(conn_and_addr) = None;
2659                let ConnectionInfo { local_addr: _, remote_addr, device: _ } =
2660                    I::get_conn_info(conn_and_addr);
2661                remote_addr
2662            });
2663
2664        debug!("accepted connection {conn_id:?} from {remote_addr:?} on {id:?}");
2665        Ok((conn_id, remote_addr, client_buffers))
2666    }
2667
2668    /// Connects a socket to a remote address.
2669    ///
2670    /// When the method returns, the connection is not guaranteed to be
2671    /// established. It is up to the caller (Bindings) to determine when the
2672    /// connection has been established. Bindings are free to use anything
2673    /// available on the platform to check, for instance, signals.
2674    pub fn connect(
2675        &mut self,
2676        id: &TcpApiSocketId<I, C>,
2677        remote_ip: Option<
2678            ZonedAddr<
2679                SpecifiedAddr<I::Addr>,
2680                <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId,
2681            >,
2682        >,
2683        remote_port: NonZeroU16,
2684    ) -> Result<(), ConnectError> {
2685        let (core_ctx, bindings_ctx) = self.contexts();
2686        let result = core_ctx.with_socket_mut_generators_transport_demux(
2687            id,
2688            |core_ctx, socket_state, isn, timestamp_offset| {
2689                let TcpSocketState { socket_state, sharing, ip_options, socket_options } =
2690                    socket_state;
2691                debug!("connect on {id:?} to {remote_ip:?}:{remote_port}");
2692                let remote_ip = DualStackRemoteIp::<I, _>::new(remote_ip);
2693                let (local_addr, buffer_sizes, socket_extra) = match socket_state {
2694                    TcpSocketStateInner::Connected { conn, timer: _ } => {
2695                        let (handshake_status, error_reporter) = match core_ctx {
2696                            MaybeDualStack::NotDualStack((_core_ctx, converter)) => {
2697                                let (conn, _addr) = converter.convert(conn);
2698                                (
2699                                    &mut conn.handshake_status,
2700                                    ErrorReporter::new(&mut conn.state, &mut conn.soft_error),
2701                                )
2702                            }
2703                            MaybeDualStack::DualStack((_core_ctx, converter)) => {
2704                                match converter.convert(conn) {
2705                                    EitherStack::ThisStack((conn, _addr)) => (
2706                                        &mut conn.handshake_status,
2707                                        ErrorReporter::new(&mut conn.state, &mut conn.soft_error),
2708                                    ),
2709                                    EitherStack::OtherStack((conn, _addr)) => (
2710                                        &mut conn.handshake_status,
2711                                        ErrorReporter::new(&mut conn.state, &mut conn.soft_error),
2712                                    ),
2713                                }
2714                            }
2715                        };
2716                        match handshake_status {
2717                            HandshakeStatus::Pending => return Err(ConnectError::Pending),
2718                            HandshakeStatus::Aborted => {
2719                                return Err(error_reporter
2720                                    .report_error()
2721                                    .map(ConnectError::ConnectionError)
2722                                    .unwrap_or(ConnectError::Aborted));
2723                            }
2724                            HandshakeStatus::Completed { reported } => {
2725                                if *reported {
2726                                    return Err(ConnectError::Completed);
2727                                } else {
2728                                    *reported = true;
2729                                    return Ok(());
2730                                }
2731                            }
2732                        }
2733                    }
2734                    TcpSocketStateInner::Unbound(Unbound {
2735                        bound_device: _,
2736                        socket_extra,
2737                        buffer_sizes,
2738                    }) => (
2739                        DualStackTuple::<I, _>::new(None, None),
2740                        *buffer_sizes,
2741                        socket_extra.to_ref(),
2742                    ),
2743                    TcpSocketStateInner::Listener(_) => {
2744                        return Err(ConnectError::Listener);
2745                    }
2746                    TcpSocketStateInner::Bound(BoundState { addr, buffer_sizes, socket_extra }) => {
2747                        let local_addr = match &core_ctx {
2748                            MaybeDualStack::DualStack((_core_ctx, converter)) => {
2749                                match converter.convert(addr.clone()) {
2750                                    ListenerAddr {
2751                                        ip: DualStackListenerIpAddr::ThisStack(ip),
2752                                        device,
2753                                    } => {
2754                                        DualStackTuple::new(Some(ListenerAddr { ip, device }), None)
2755                                    }
2756                                    ListenerAddr {
2757                                        ip: DualStackListenerIpAddr::OtherStack(ip),
2758                                        device,
2759                                    } => {
2760                                        DualStackTuple::new(None, Some(ListenerAddr { ip, device }))
2761                                    }
2762                                    ListenerAddr {
2763                                        ip: DualStackListenerIpAddr::BothStacks(port),
2764                                        device,
2765                                    } => DualStackTuple::new(
2766                                        Some(ListenerAddr {
2767                                            ip: ListenerIpAddr { addr: None, identifier: port },
2768                                            device: device.clone(),
2769                                        }),
2770                                        Some(ListenerAddr {
2771                                            ip: ListenerIpAddr { addr: None, identifier: port },
2772                                            device,
2773                                        }),
2774                                    ),
2775                                }
2776                            }
2777                            MaybeDualStack::NotDualStack((_core_ctx, converter)) => {
2778                                DualStackTuple::new(Some(converter.convert(addr.clone())), None)
2779                            }
2780                        };
2781                        (local_addr, *buffer_sizes, socket_extra.to_ref())
2782                    }
2783                };
2784                // Local addr is a tuple of (this_stack, other_stack) bound
2785                // local address.
2786                let local_addr = local_addr.into_inner();
2787                match (core_ctx, local_addr, remote_ip) {
2788                    // If not dual stack, we allow the connect operation if socket
2789                    // was not bound or bound to a this-stack local address before,
2790                    // and the remote address also belongs to this stack.
2791                    (
2792                        MaybeDualStack::NotDualStack((core_ctx, converter)),
2793                        (local_addr_this_stack, None),
2794                        DualStackRemoteIp::ThisStack(remote_ip),
2795                    ) => {
2796                        *socket_state = connect_inner(
2797                            core_ctx,
2798                            bindings_ctx,
2799                            id,
2800                            isn,
2801                            timestamp_offset,
2802                            local_addr_this_stack.clone(),
2803                            remote_ip,
2804                            remote_port,
2805                            socket_extra,
2806                            buffer_sizes,
2807                            socket_options,
2808                            *sharing,
2809                            SingleStackDemuxStateAccessor(
2810                                &I::into_demux_socket_id(id.clone()),
2811                                local_addr_this_stack,
2812                            ),
2813                            |conn, addr| converter.convert_back((conn, addr)),
2814                            <C::CoreContext as CoreTimerContext<_, _>>::convert_timer,
2815                        )?;
2816                        Ok(())
2817                    }
2818                    // If dual stack, we can perform a this-stack only
2819                    // connection as long as we're not *only* bound in the other
2820                    // stack.
2821                    (
2822                        MaybeDualStack::DualStack((core_ctx, converter)),
2823                        (local_addr_this_stack, local_addr_other_stack @ None)
2824                        | (local_addr_this_stack @ Some(_), local_addr_other_stack @ Some(_)),
2825                        DualStackRemoteIp::ThisStack(remote_ip),
2826                    ) => {
2827                        *socket_state = connect_inner(
2828                            core_ctx,
2829                            bindings_ctx,
2830                            id,
2831                            isn,
2832                            timestamp_offset,
2833                            local_addr_this_stack.clone(),
2834                            remote_ip,
2835                            remote_port,
2836                            socket_extra,
2837                            buffer_sizes,
2838                            socket_options,
2839                            *sharing,
2840                            DualStackDemuxStateAccessor(
2841                                id,
2842                                DualStackTuple::new(local_addr_this_stack, local_addr_other_stack),
2843                            ),
2844                            |conn, addr| {
2845                                converter.convert_back(EitherStack::ThisStack((conn, addr)))
2846                            },
2847                            <C::CoreContext as CoreTimerContext<_, _>>::convert_timer,
2848                        )?;
2849                        Ok(())
2850                    }
2851                    // If dual stack, we can perform an other-stack only
2852                    // connection as long as we're not *only* bound in this
2853                    // stack.
2854                    (
2855                        MaybeDualStack::DualStack((core_ctx, converter)),
2856                        (local_addr_this_stack @ None, local_addr_other_stack)
2857                        | (local_addr_this_stack @ Some(_), local_addr_other_stack @ Some(_)),
2858                        DualStackRemoteIp::OtherStack(remote_ip),
2859                    ) => {
2860                        if !core_ctx.dual_stack_enabled(ip_options) {
2861                            return Err(ConnectError::NoRoute);
2862                        }
2863                        *socket_state = connect_inner(
2864                            core_ctx,
2865                            bindings_ctx,
2866                            id,
2867                            isn,
2868                            timestamp_offset,
2869                            local_addr_other_stack.clone(),
2870                            remote_ip,
2871                            remote_port,
2872                            socket_extra,
2873                            buffer_sizes,
2874                            socket_options,
2875                            *sharing,
2876                            DualStackDemuxStateAccessor(
2877                                id,
2878                                DualStackTuple::new(local_addr_this_stack, local_addr_other_stack),
2879                            ),
2880                            |conn, addr| {
2881                                converter.convert_back(EitherStack::OtherStack((conn, addr)))
2882                            },
2883                            <C::CoreContext as CoreTimerContext<_, _>>::convert_timer,
2884                        )?;
2885                        Ok(())
2886                    }
2887                    // Not possible for a non-dual-stack socket to bind in the other
2888                    // stack.
2889                    (
2890                        MaybeDualStack::NotDualStack(_),
2891                        (_, Some(_other_stack_local_addr)),
2892                        DualStackRemoteIp::ThisStack(_) | DualStackRemoteIp::OtherStack(_),
2893                    ) => unreachable!("The socket cannot be bound in the other stack"),
2894                    // Can't connect from one stack to the other.
2895                    (
2896                        MaybeDualStack::DualStack(_),
2897                        (_, Some(_other_stack_local_addr)),
2898                        DualStackRemoteIp::ThisStack(_),
2899                    ) => Err(ConnectError::NoRoute),
2900                    // Can't connect from one stack to the other.
2901                    (
2902                        MaybeDualStack::DualStack(_) | MaybeDualStack::NotDualStack(_),
2903                        (Some(_this_stack_local_addr), _),
2904                        DualStackRemoteIp::OtherStack(_),
2905                    ) => Err(ConnectError::NoRoute),
2906                    // Can't connect to the other stack for non-dual-stack sockets.
2907                    (
2908                        MaybeDualStack::NotDualStack(_),
2909                        (None, None),
2910                        DualStackRemoteIp::OtherStack(_),
2911                    ) => Err(ConnectError::NoRoute),
2912                }
2913            },
2914        );
2915        match &result {
2916            Ok(()) => {}
2917            Err(err) => {
2918                core_ctx.increment_both(id, |counters| &counters.failed_connection_attempts);
2919                match err {
2920                    ConnectError::NoRoute => {
2921                        core_ctx
2922                            .increment_both(id, |counters| &counters.active_open_no_route_errors);
2923                    }
2924                    ConnectError::NoPort => {
2925                        core_ctx.increment_both(id, |counters| &counters.failed_port_reservations);
2926                    }
2927                    _ => {}
2928                }
2929            }
2930        }
2931        result
2932    }
2933
2934    /// Closes a socket.
2935    pub fn close(&mut self, id: TcpApiSocketId<I, C>) {
2936        debug!("close on {id:?}");
2937        let (core_ctx, bindings_ctx) = self.contexts();
2938        let (destroy, pending) =
2939            core_ctx.with_socket_mut_transport_demux(&id, |core_ctx, socket_state| {
2940                let TcpSocketState { socket_state, sharing: _, ip_options: _, socket_options } =
2941                    socket_state;
2942                match socket_state {
2943                    TcpSocketStateInner::Unbound(_) => (true, None),
2944                    TcpSocketStateInner::Bound(BoundState { addr, .. })
2945                    | TcpSocketStateInner::Listener(Listener { addr, .. }) => {
2946                        match core_ctx {
2947                            MaybeDualStack::NotDualStack((core_ctx, converter)) => {
2948                                TcpDemuxContext::<I, _, _>::with_demux_mut(
2949                                    core_ctx,
2950                                    |DemuxState { socketmap }| {
2951                                        socketmap
2952                                            .listeners_mut()
2953                                            .remove(
2954                                                &I::into_demux_socket_id(id.clone()),
2955                                                &converter.convert(addr),
2956                                            )
2957                                            .expect("failed to remove from socketmap");
2958                                    },
2959                                );
2960                            }
2961                            MaybeDualStack::DualStack((core_ctx, converter)) => {
2962                                match converter.convert(addr.clone()) {
2963                                    ListenerAddr {
2964                                        ip: DualStackListenerIpAddr::ThisStack(ip),
2965                                        device,
2966                                    } => TcpDemuxContext::<I, _, _>::with_demux_mut(
2967                                        core_ctx,
2968                                        |DemuxState { socketmap }| {
2969                                            socketmap
2970                                                .listeners_mut()
2971                                                .remove(
2972                                                    &I::into_demux_socket_id(id.clone()),
2973                                                    &ListenerAddr { ip, device },
2974                                                )
2975                                                .expect("failed to remove from socketmap");
2976                                        },
2977                                    ),
2978                                    ListenerAddr {
2979                                        ip: DualStackListenerIpAddr::OtherStack(ip),
2980                                        device,
2981                                    } => {
2982                                        let other_demux_id =
2983                                            core_ctx.into_other_demux_socket_id(id.clone());
2984                                        TcpDemuxContext::<I::OtherVersion, _, _>::with_demux_mut(
2985                                            core_ctx,
2986                                            |DemuxState { socketmap }| {
2987                                                socketmap
2988                                                    .listeners_mut()
2989                                                    .remove(
2990                                                        &other_demux_id,
2991                                                        &ListenerAddr { ip, device },
2992                                                    )
2993                                                    .expect("failed to remove from socketmap");
2994                                            },
2995                                        );
2996                                    }
2997                                    ListenerAddr {
2998                                        ip: DualStackListenerIpAddr::BothStacks(port),
2999                                        device,
3000                                    } => {
3001                                        let other_demux_id =
3002                                            core_ctx.into_other_demux_socket_id(id.clone());
3003                                        core_ctx.with_both_demux_mut(|demux, other_demux| {
3004                                            demux
3005                                                .socketmap
3006                                                .listeners_mut()
3007                                                .remove(
3008                                                    &I::into_demux_socket_id(id.clone()),
3009                                                    &ListenerAddr {
3010                                                        ip: ListenerIpAddr {
3011                                                            addr: None,
3012                                                            identifier: port,
3013                                                        },
3014                                                        device: device.clone(),
3015                                                    },
3016                                                )
3017                                                .expect("failed to remove from socketmap");
3018                                            other_demux
3019                                                .socketmap
3020                                                .listeners_mut()
3021                                                .remove(
3022                                                    &other_demux_id,
3023                                                    &ListenerAddr {
3024                                                        ip: ListenerIpAddr {
3025                                                            addr: None,
3026                                                            identifier: port,
3027                                                        },
3028                                                        device,
3029                                                    },
3030                                                )
3031                                                .expect("failed to remove from socketmap");
3032                                        });
3033                                    }
3034                                }
3035                            }
3036                        };
3037                        // Move the listener down to a `Bound` state so it won't
3038                        // accept any more connections and close the accept
3039                        // queue.
3040                        if let TcpSocketStateInner::Listener(Listener {
3041                            addr,
3042                            backlog: _,
3043                            accept_queue,
3044                            buffer_sizes,
3045                        }) = socket_state
3046                        {
3047                            let (pending, socket_extra) = accept_queue.close();
3048                            let addr = addr.clone();
3049                            let buffer_sizes = buffer_sizes.clone();
3050                            *socket_state = TcpSocketStateInner::Bound(BoundState {
3051                                addr,
3052                                buffer_sizes,
3053                                socket_extra: Takeable::new(socket_extra),
3054                            });
3055                            (true, Some(pending))
3056                        } else {
3057                            (true, None)
3058                        }
3059                    }
3060                    TcpSocketStateInner::Connected { conn, timer } => {
3061                        fn do_close<SockI, WireI, CC, BC>(
3062                            core_ctx: &mut CC,
3063                            bindings_ctx: &mut BC,
3064                            id: &TcpSocketId<SockI, CC::WeakDeviceId, BC>,
3065                            demux_id: &WireI::DemuxSocketId<CC::WeakDeviceId, BC>,
3066                            socket_options: &SocketOptions,
3067                            conn: &mut Connection<SockI, WireI, CC::WeakDeviceId, BC>,
3068                            addr: &ConnAddr<
3069                                ConnIpAddr<<WireI as Ip>::Addr, NonZeroU16, NonZeroU16>,
3070                                CC::WeakDeviceId,
3071                            >,
3072                            timer: &mut BC::Timer,
3073                        ) -> bool
3074                        where
3075                            SockI: DualStackIpExt,
3076                            WireI: DualStackIpExt,
3077                            BC: TcpBindingsContext<CC::DeviceId>,
3078                            CC: TransportIpContext<WireI, BC>
3079                                + TcpDemuxContext<WireI, CC::WeakDeviceId, BC>
3080                                + TcpSocketContext<SockI, CC::WeakDeviceId, BC>,
3081                        {
3082                            // Ignore the result - errors are handled below after calling `close`.
3083                            let _: Result<(), CloseError> = conn.state.shutdown_recv();
3084
3085                            conn.defunct = true;
3086                            let newly_closed = match conn.state.close(
3087                                &TcpCountersRefs::from_ctx(core_ctx, id),
3088                                CloseReason::Close { now: bindings_ctx.now() },
3089                                socket_options,
3090                            ) {
3091                                Err(CloseError::NoConnection) => NewlyClosed::No,
3092                                Err(CloseError::Closing) | Ok(NewlyClosed::No) => do_send_inner(
3093                                    &id,
3094                                    socket_options,
3095                                    conn,
3096                                    DoSendLimit::MultipleSegments,
3097                                    &addr,
3098                                    timer,
3099                                    core_ctx,
3100                                    bindings_ctx,
3101                                ),
3102                                Ok(NewlyClosed::Yes) => NewlyClosed::Yes,
3103                            };
3104                            // The connection transitions to closed because of
3105                            // this call, we need to unregister it from the
3106                            // socketmap.
3107                            handle_newly_closed(
3108                                core_ctx,
3109                                bindings_ctx,
3110                                newly_closed,
3111                                demux_id,
3112                                addr,
3113                                timer,
3114                            );
3115                            let now_closed = matches!(conn.state, State::Closed(_));
3116                            if now_closed {
3117                                debug_assert!(
3118                                    core_ctx.with_demux_mut(|DemuxState { socketmap }| {
3119                                        socketmap.conns_mut().entry(demux_id, addr).is_none()
3120                                    }),
3121                                    "lingering state in socketmap: demux_id: {:?}, addr: {:?}",
3122                                    demux_id,
3123                                    addr,
3124                                );
3125                                debug_assert_eq!(
3126                                    bindings_ctx.scheduled_instant(timer),
3127                                    None,
3128                                    "lingering timer for {:?}",
3129                                    id,
3130                                )
3131                            };
3132                            now_closed
3133                        }
3134                        let closed = match core_ctx {
3135                            MaybeDualStack::NotDualStack((core_ctx, converter)) => {
3136                                let (conn, addr) = converter.convert(conn);
3137                                do_close(
3138                                    core_ctx,
3139                                    bindings_ctx,
3140                                    &id,
3141                                    &I::into_demux_socket_id(id.clone()),
3142                                    socket_options,
3143                                    conn,
3144                                    addr,
3145                                    timer,
3146                                )
3147                            }
3148                            MaybeDualStack::DualStack((core_ctx, converter)) => {
3149                                match converter.convert(conn) {
3150                                    EitherStack::ThisStack((conn, addr)) => do_close(
3151                                        core_ctx,
3152                                        bindings_ctx,
3153                                        &id,
3154                                        &I::into_demux_socket_id(id.clone()),
3155                                        socket_options,
3156                                        conn,
3157                                        addr,
3158                                        timer,
3159                                    ),
3160                                    EitherStack::OtherStack((conn, addr)) => do_close(
3161                                        core_ctx,
3162                                        bindings_ctx,
3163                                        &id,
3164                                        &core_ctx.into_other_demux_socket_id(id.clone()),
3165                                        socket_options,
3166                                        conn,
3167                                        addr,
3168                                        timer,
3169                                    ),
3170                                }
3171                            }
3172                        };
3173                        (closed, None)
3174                    }
3175                }
3176            });
3177
3178        close_pending_sockets(core_ctx, bindings_ctx, pending.into_iter().flatten());
3179
3180        if destroy {
3181            destroy_socket(core_ctx, bindings_ctx, id);
3182        }
3183    }
3184
3185    /// Shuts down a socket.
3186    ///
3187    /// For a connection, calling this function signals the other side of the
3188    /// connection that we will not be sending anything over the connection; The
3189    /// connection will be removed from the socketmap if the state moves to the
3190    /// `Closed` state.
3191    ///
3192    /// For a Listener, calling this function brings it back to bound state and
3193    /// shutdowns all the connection that is currently ready to be accepted.
3194    ///
3195    /// Returns Err(NoConnection) if the shutdown option does not apply.
3196    /// Otherwise, Whether a connection has been shutdown is returned, i.e., if
3197    /// the socket was a listener, the operation will succeed but false will be
3198    /// returned.
3199    pub fn shutdown(
3200        &mut self,
3201        id: &TcpApiSocketId<I, C>,
3202        shutdown_type: ShutdownType,
3203    ) -> Result<bool, NoConnection> {
3204        debug!("shutdown [{shutdown_type:?}] for {id:?}");
3205        let (core_ctx, bindings_ctx) = self.contexts();
3206        let (result, pending) =
3207            core_ctx.with_socket_mut_transport_demux(id, |core_ctx, socket_state| {
3208                let TcpSocketState { socket_state, sharing, ip_options: _, socket_options } =
3209                    socket_state;
3210                match socket_state {
3211                    TcpSocketStateInner::Unbound(_) => Err(NoConnection),
3212                    TcpSocketStateInner::Connected { conn, timer } => {
3213                        fn do_shutdown<SockI, WireI, CC, BC>(
3214                            core_ctx: &mut CC,
3215                            bindings_ctx: &mut BC,
3216                            id: &TcpSocketId<SockI, CC::WeakDeviceId, BC>,
3217                            demux_id: &WireI::DemuxSocketId<CC::WeakDeviceId, BC>,
3218                            socket_options: &SocketOptions,
3219                            conn: &mut Connection<SockI, WireI, CC::WeakDeviceId, BC>,
3220                            addr: &ConnAddr<
3221                                ConnIpAddr<<WireI as Ip>::Addr, NonZeroU16, NonZeroU16>,
3222                                CC::WeakDeviceId,
3223                            >,
3224                            timer: &mut BC::Timer,
3225                            shutdown_type: ShutdownType,
3226                        ) -> Result<(), NoConnection>
3227                        where
3228                            SockI: DualStackIpExt,
3229                            WireI: DualStackIpExt,
3230                            BC: TcpBindingsContext<CC::DeviceId>,
3231                            CC: TransportIpContext<WireI, BC>
3232                                + TcpDemuxContext<WireI, CC::WeakDeviceId, BC>
3233                                + TcpSocketContext<SockI, CC::WeakDeviceId, BC>,
3234                        {
3235                            let (shutdown_send, shutdown_receive) = shutdown_type.to_send_receive();
3236                            if shutdown_receive {
3237                                match conn.state.shutdown_recv() {
3238                                    Ok(()) => (),
3239                                    Err(CloseError::NoConnection) => return Err(NoConnection),
3240                                    Err(CloseError::Closing) => (),
3241                                }
3242                            }
3243
3244                            if !shutdown_send {
3245                                return Ok(());
3246                            }
3247
3248                            match conn.state.close(
3249                                &TcpCountersRefs::from_ctx(core_ctx, id),
3250                                CloseReason::Shutdown,
3251                                socket_options,
3252                            ) {
3253                                Ok(newly_closed) => {
3254                                    let newly_closed = match newly_closed {
3255                                        NewlyClosed::Yes => NewlyClosed::Yes,
3256                                        NewlyClosed::No => do_send_inner(
3257                                            id,
3258                                            socket_options,
3259                                            conn,
3260                                            DoSendLimit::MultipleSegments,
3261                                            addr,
3262                                            timer,
3263                                            core_ctx,
3264                                            bindings_ctx,
3265                                        ),
3266                                    };
3267                                    handle_newly_closed(
3268                                        core_ctx,
3269                                        bindings_ctx,
3270                                        newly_closed,
3271                                        demux_id,
3272                                        addr,
3273                                        timer,
3274                                    );
3275                                    Ok(())
3276                                }
3277                                Err(CloseError::NoConnection) => Err(NoConnection),
3278                                Err(CloseError::Closing) => Ok(()),
3279                            }
3280                        }
3281                        match core_ctx {
3282                            MaybeDualStack::NotDualStack((core_ctx, converter)) => {
3283                                let (conn, addr) = converter.convert(conn);
3284                                do_shutdown(
3285                                    core_ctx,
3286                                    bindings_ctx,
3287                                    id,
3288                                    &I::into_demux_socket_id(id.clone()),
3289                                    socket_options,
3290                                    conn,
3291                                    addr,
3292                                    timer,
3293                                    shutdown_type,
3294                                )?
3295                            }
3296                            MaybeDualStack::DualStack((core_ctx, converter)) => {
3297                                match converter.convert(conn) {
3298                                    EitherStack::ThisStack((conn, addr)) => do_shutdown(
3299                                        core_ctx,
3300                                        bindings_ctx,
3301                                        id,
3302                                        &I::into_demux_socket_id(id.clone()),
3303                                        socket_options,
3304                                        conn,
3305                                        addr,
3306                                        timer,
3307                                        shutdown_type,
3308                                    )?,
3309                                    EitherStack::OtherStack((conn, addr)) => do_shutdown(
3310                                        core_ctx,
3311                                        bindings_ctx,
3312                                        id,
3313                                        &core_ctx.into_other_demux_socket_id(id.clone()),
3314                                        socket_options,
3315                                        conn,
3316                                        addr,
3317                                        timer,
3318                                        shutdown_type,
3319                                    )?,
3320                                }
3321                            }
3322                        };
3323                        Ok((true, None))
3324                    }
3325                    TcpSocketStateInner::Bound(_) => Err(NoConnection),
3326                    TcpSocketStateInner::Listener(listener) => {
3327                        let (_shutdown_send, shutdown_receive) = shutdown_type.to_send_receive();
3328
3329                        if !shutdown_receive {
3330                            return Ok((false, None));
3331                        }
3332
3333                        let (pending, new_state) =
3334                            shut_down_listener_socket::<I, C::CoreContext, C::BindingsContext>(
3335                                core_ctx, id, listener, *sharing,
3336                            );
3337                        *socket_state = TcpSocketStateInner::Bound(new_state);
3338                        Ok((false, Some(pending)))
3339                    }
3340                }
3341            })?;
3342
3343        close_pending_sockets(core_ctx, bindings_ctx, pending.into_iter().flatten());
3344
3345        Ok(result)
3346    }
3347
3348    /// Polls the state machine after data is dequeued from the receive buffer.
3349    ///
3350    /// Possibly sends a window update to the peer if enough data has been read
3351    /// from the buffer and we suspect that the peer is in SWS avoidance.
3352    ///
3353    /// This does nothing for a disconnected socket.
3354    pub fn on_receive_buffer_read(&mut self, id: &TcpApiSocketId<I, C>) {
3355        let (core_ctx, bindings_ctx) = self.contexts();
3356        core_ctx.with_socket_mut_transport_demux(
3357            id,
3358            |core_ctx, TcpSocketState { socket_state, sharing: _, ip_options: _, socket_options }| {
3359                let conn = match socket_state {
3360                    TcpSocketStateInner::Unbound(_)| TcpSocketStateInner::Bound(_)|
3361                    TcpSocketStateInner::Listener(_) => return,
3362                    TcpSocketStateInner::Connected { conn, .. } => conn,
3363                };
3364
3365                let now = bindings_ctx.now();
3366                match core_ctx {
3367                    MaybeDualStack::NotDualStack((core_ctx, converter)) => {
3368                        let (conn, addr) = converter.convert(conn);
3369                        if let Some(ack) = conn.state.poll_receive_data_dequeued(now) {
3370                            send_tcp_segment(
3371                                core_ctx,
3372                                bindings_ctx,
3373                                Some(id),
3374                                Some(&conn.ip_sock),
3375                                addr.ip,
3376                                ack.into_empty(),
3377                                &socket_options.ip_options,
3378                            )
3379                        }
3380                    }
3381                    MaybeDualStack::DualStack((core_ctx, converter)) => {
3382                        match converter.convert(conn) {
3383                            EitherStack::ThisStack((conn, addr)) => {
3384                                if let Some(ack) = conn.state.poll_receive_data_dequeued(now) {
3385                                    send_tcp_segment(
3386                                        core_ctx,
3387                                        bindings_ctx,
3388                                        Some(id),
3389                                        Some(&conn.ip_sock),
3390                                        addr.ip,
3391                                        ack.into_empty(),
3392                                        &socket_options.ip_options,
3393                                    )
3394                                }
3395                            }
3396                            EitherStack::OtherStack((conn, addr)) => {
3397                                if let Some(ack) = conn.state.poll_receive_data_dequeued(now) {
3398                                    send_tcp_segment(
3399                                        core_ctx,
3400                                        bindings_ctx,
3401                                        Some(id),
3402                                        Some(&conn.ip_sock),
3403                                        addr.ip,
3404                                        ack.into_empty(),
3405                                        &socket_options.ip_options,
3406                                    )
3407                                }
3408                            }
3409                        }
3410                    }
3411                }
3412            },
3413        )
3414    }
3415
3416    fn set_device_conn<SockI, WireI, CC>(
3417        core_ctx: &mut CC,
3418        bindings_ctx: &mut C::BindingsContext,
3419        addr: &mut ConnAddr<ConnIpAddr<WireI::Addr, NonZeroU16, NonZeroU16>, CC::WeakDeviceId>,
3420        demux_id: &WireI::DemuxSocketId<CC::WeakDeviceId, C::BindingsContext>,
3421        ip_options: &TcpIpSockOptions,
3422        conn: &mut Connection<SockI, WireI, CC::WeakDeviceId, C::BindingsContext>,
3423        new_device: Option<CC::DeviceId>,
3424    ) -> Result<(), SetDeviceError>
3425    where
3426        SockI: DualStackIpExt,
3427        WireI: DualStackIpExt,
3428        CC: TransportIpContext<WireI, C::BindingsContext>
3429            + TcpDemuxContext<WireI, CC::WeakDeviceId, C::BindingsContext>,
3430    {
3431        let ConnAddr {
3432            device: old_device,
3433            ip: ConnIpAddr { local: (local_ip, _), remote: (remote_ip, _) },
3434        } = addr;
3435
3436        let update = SocketDeviceUpdate {
3437            local_ip: Some(local_ip.as_ref()),
3438            remote_ip: Some(remote_ip.as_ref()),
3439            old_device: old_device.as_ref(),
3440        };
3441        match update.check_update(new_device.as_ref()) {
3442            Ok(()) => (),
3443            Err(SocketDeviceUpdateNotAllowedError) => return Err(SetDeviceError::ZoneChange),
3444        }
3445        let new_socket = core_ctx
3446            .new_ip_socket(
3447                bindings_ctx,
3448                IpSocketArgs {
3449                    device: new_device.as_ref().map(EitherDeviceId::Strong),
3450                    local_ip: IpDeviceAddr::new_from_socket_ip_addr(*local_ip),
3451                    remote_ip: *remote_ip,
3452                    proto: IpProto::Tcp.into(),
3453                    options: ip_options,
3454                },
3455            )
3456            .map_err(|_: IpSockCreationError| SetDeviceError::Unroutable)?;
3457        let new_address = ConnAddr { device: new_socket.device().cloned(), ..addr.clone() };
3458        core_ctx.with_demux_mut(|DemuxState { socketmap }| {
3459            let entry = match socketmap.conns_mut().entry(demux_id, addr) {
3460                Some(entry) => entry,
3461                None => {
3462                    debug!("no demux entry for {addr:?} with {demux_id:?}");
3463                    // State must be closed or timewait if we have a bound
3464                    // and connected socket that is no longer present in the
3465                    // demux.
3466                    assert_matches!(&conn.state, State::Closed(_) | State::TimeWait(_));
3467                    // If the socket has already been removed from the
3468                    // demux, then we can update our address information
3469                    // locally.
3470                    *addr = new_address;
3471                    return Ok(());
3472                }
3473            };
3474
3475            match entry.try_update_addr(new_address) {
3476                Ok(entry) => {
3477                    *addr = entry.get_addr().clone();
3478                    conn.ip_sock = new_socket;
3479                    Ok(())
3480                }
3481                Err((ExistsError, _entry)) => Err(SetDeviceError::Conflict),
3482            }
3483        })
3484    }
3485
3486    /// Updates the `old_device` to the new device if it is allowed. Note that
3487    /// this `old_device` will be updated in-place, so it should come from the
3488    /// outside socketmap address.
3489    fn set_device_listener<WireI, D>(
3490        demux_id: &WireI::DemuxSocketId<D, C::BindingsContext>,
3491        ip_addr: ListenerIpAddr<WireI::Addr, NonZeroU16>,
3492        old_device: &mut Option<D>,
3493        new_device: Option<&D>,
3494        DemuxState { socketmap }: &mut DemuxState<WireI, D, C::BindingsContext>,
3495    ) -> Result<(), SetDeviceError>
3496    where
3497        WireI: DualStackIpExt,
3498        D: WeakDeviceIdentifier,
3499    {
3500        let entry = socketmap
3501            .listeners_mut()
3502            .entry(demux_id, &ListenerAddr { ip: ip_addr, device: old_device.clone() })
3503            .expect("invalid ID");
3504
3505        let update = SocketDeviceUpdate {
3506            local_ip: ip_addr.addr.as_ref().map(|a| a.as_ref()),
3507            remote_ip: None,
3508            old_device: old_device.as_ref(),
3509        };
3510        match update.check_update(new_device) {
3511            Ok(()) => (),
3512            Err(SocketDeviceUpdateNotAllowedError) => return Err(SetDeviceError::ZoneChange),
3513        }
3514        match entry.try_update_addr(ListenerAddr { device: new_device.cloned(), ip: ip_addr }) {
3515            Ok(entry) => {
3516                *old_device = entry.get_addr().device.clone();
3517                Ok(())
3518            }
3519            Err((ExistsError, _entry)) => Err(SetDeviceError::Conflict),
3520        }
3521    }
3522
3523    /// Sets the device on a socket.
3524    ///
3525    /// Passing `None` clears the bound device.
3526    pub fn set_device(
3527        &mut self,
3528        id: &TcpApiSocketId<I, C>,
3529        new_device: Option<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
3530    ) -> Result<(), SetDeviceError> {
3531        let (core_ctx, bindings_ctx) = self.contexts();
3532        let weak_device = new_device.as_ref().map(|d| d.downgrade());
3533        core_ctx.with_socket_mut_transport_demux(id, move |core_ctx, socket_state| {
3534            debug!("set device on {id:?} to {new_device:?}");
3535            let TcpSocketState { socket_state, sharing: _, ip_options: _, socket_options } =
3536                socket_state;
3537            match socket_state {
3538                TcpSocketStateInner::Unbound(unbound) => {
3539                    unbound.bound_device = weak_device;
3540                    Ok(())
3541                }
3542                TcpSocketStateInner::Connected { conn, timer: _ } => {
3543                    let this_or_other_stack = match core_ctx {
3544                        MaybeDualStack::NotDualStack((core_ctx, converter)) => {
3545                            let (conn, addr) = converter.convert(conn);
3546                            EitherStack::ThisStack((
3547                                core_ctx.as_this_stack(),
3548                                conn,
3549                                addr,
3550                                I::into_demux_socket_id(id.clone()),
3551                            ))
3552                        }
3553                        MaybeDualStack::DualStack((core_ctx, converter)) => {
3554                            match converter.convert(conn) {
3555                                EitherStack::ThisStack((conn, addr)) => EitherStack::ThisStack((
3556                                    core_ctx.as_this_stack(),
3557                                    conn,
3558                                    addr,
3559                                    I::into_demux_socket_id(id.clone()),
3560                                )),
3561                                EitherStack::OtherStack((conn, addr)) => {
3562                                    let demux_id = core_ctx.into_other_demux_socket_id(id.clone());
3563                                    EitherStack::OtherStack((core_ctx, conn, addr, demux_id))
3564                                }
3565                            }
3566                        }
3567                    };
3568                    match this_or_other_stack {
3569                        EitherStack::ThisStack((core_ctx, conn, addr, demux_id)) => {
3570                            Self::set_device_conn::<_, I, _>(
3571                                core_ctx,
3572                                bindings_ctx,
3573                                addr,
3574                                &demux_id,
3575                                &socket_options.ip_options,
3576                                conn,
3577                                new_device,
3578                            )
3579                        }
3580                        EitherStack::OtherStack((core_ctx, conn, addr, demux_id)) => {
3581                            Self::set_device_conn::<_, I::OtherVersion, _>(
3582                                core_ctx,
3583                                bindings_ctx,
3584                                addr,
3585                                &demux_id,
3586                                &socket_options.ip_options,
3587                                conn,
3588                                new_device,
3589                            )
3590                        }
3591                    }
3592                }
3593                TcpSocketStateInner::Bound(BoundState { addr, .. })
3594                | TcpSocketStateInner::Listener(Listener { addr, .. }) => match core_ctx {
3595                    MaybeDualStack::NotDualStack((core_ctx, converter)) => {
3596                        let ListenerAddr { ip, device } = converter.convert(addr);
3597                        core_ctx.with_demux_mut(|demux| {
3598                            Self::set_device_listener(
3599                                &I::into_demux_socket_id(id.clone()),
3600                                ip.clone(),
3601                                device,
3602                                weak_device.as_ref(),
3603                                demux,
3604                            )
3605                        })
3606                    }
3607                    MaybeDualStack::DualStack((core_ctx, converter)) => {
3608                        match converter.convert(addr) {
3609                            ListenerAddr { ip: DualStackListenerIpAddr::ThisStack(ip), device } => {
3610                                TcpDemuxContext::<I, _, _>::with_demux_mut(core_ctx, |demux| {
3611                                    Self::set_device_listener(
3612                                        &I::into_demux_socket_id(id.clone()),
3613                                        ip.clone(),
3614                                        device,
3615                                        weak_device.as_ref(),
3616                                        demux,
3617                                    )
3618                                })
3619                            }
3620                            ListenerAddr {
3621                                ip: DualStackListenerIpAddr::OtherStack(ip),
3622                                device,
3623                            } => {
3624                                let other_demux_id =
3625                                    core_ctx.into_other_demux_socket_id(id.clone());
3626                                TcpDemuxContext::<I::OtherVersion, _, _>::with_demux_mut(
3627                                    core_ctx,
3628                                    |demux| {
3629                                        Self::set_device_listener(
3630                                            &other_demux_id,
3631                                            ip.clone(),
3632                                            device,
3633                                            weak_device.as_ref(),
3634                                            demux,
3635                                        )
3636                                    },
3637                                )
3638                            }
3639                            ListenerAddr {
3640                                ip: DualStackListenerIpAddr::BothStacks(port),
3641                                device,
3642                            } => {
3643                                let other_demux_id =
3644                                    core_ctx.into_other_demux_socket_id(id.clone());
3645                                core_ctx.with_both_demux_mut(|demux, other_demux| {
3646                                    Self::set_device_listener(
3647                                        &I::into_demux_socket_id(id.clone()),
3648                                        ListenerIpAddr { addr: None, identifier: *port },
3649                                        device,
3650                                        weak_device.as_ref(),
3651                                        demux,
3652                                    )?;
3653                                    match Self::set_device_listener(
3654                                        &other_demux_id,
3655                                        ListenerIpAddr { addr: None, identifier: *port },
3656                                        device,
3657                                        weak_device.as_ref(),
3658                                        other_demux,
3659                                    ) {
3660                                        Ok(()) => Ok(()),
3661                                        Err(e) => {
3662                                            Self::set_device_listener(
3663                                                &I::into_demux_socket_id(id.clone()),
3664                                                ListenerIpAddr { addr: None, identifier: *port },
3665                                                device,
3666                                                device.clone().as_ref(),
3667                                                demux,
3668                                            )
3669                                            .expect("failed to revert back the device setting");
3670                                            Err(e)
3671                                        }
3672                                    }
3673                                })
3674                            }
3675                        }
3676                    }
3677                },
3678            }
3679        })
3680    }
3681
3682    /// Get information for a TCP socket.
3683    pub fn get_info(
3684        &mut self,
3685        id: &TcpApiSocketId<I, C>,
3686    ) -> SocketInfo<I::Addr, <C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId> {
3687        self.core_ctx().with_socket_and_converter(
3688            id,
3689            |TcpSocketState { socket_state, sharing: _, ip_options: _, socket_options: _ },
3690             _converter| {
3691                match socket_state {
3692                    TcpSocketStateInner::Unbound(unbound) => SocketInfo::Unbound(unbound.into()),
3693                    TcpSocketStateInner::Connected { conn, timer: _ } => {
3694                        SocketInfo::Connection(I::get_conn_info(conn))
3695                    }
3696                    TcpSocketStateInner::Bound(BoundState { addr, .. })
3697                    | TcpSocketStateInner::Listener(Listener { addr, .. }) => {
3698                        SocketInfo::Bound(I::get_bound_info(addr))
3699                    }
3700                }
3701            },
3702        )
3703    }
3704
3705    /// Call this function whenever a socket can push out more data. That means
3706    /// either:
3707    ///
3708    /// - A retransmission timer fires.
3709    /// - An ack received from peer so that our send window is enlarged.
3710    /// - The user puts data into the buffer and we are notified.
3711    pub fn do_send(&mut self, conn_id: &TcpApiSocketId<I, C>) {
3712        let (core_ctx, bindings_ctx) = self.contexts();
3713        core_ctx.with_socket_mut_transport_demux(conn_id, |core_ctx, socket_state| {
3714            let TcpSocketState { socket_state, sharing: _, ip_options: _, socket_options } =
3715                socket_state;
3716            let (conn, timer) = assert_matches!(
3717                socket_state,
3718                TcpSocketStateInner::Connected { conn, timer } => (conn, timer)
3719            );
3720            match core_ctx {
3721                MaybeDualStack::NotDualStack((core_ctx, converter)) => {
3722                    let (conn, addr) = converter.convert(conn);
3723                    do_send_inner_and_then_handle_newly_closed(
3724                        conn_id,
3725                        &I::into_demux_socket_id(conn_id.clone()),
3726                        socket_options,
3727                        conn,
3728                        DoSendLimit::MultipleSegments,
3729                        addr,
3730                        timer,
3731                        core_ctx,
3732                        bindings_ctx,
3733                    );
3734                }
3735                MaybeDualStack::DualStack((core_ctx, converter)) => match converter.convert(conn) {
3736                    EitherStack::ThisStack((conn, addr)) => {
3737                        do_send_inner_and_then_handle_newly_closed(
3738                            conn_id,
3739                            &I::into_demux_socket_id(conn_id.clone()),
3740                            socket_options,
3741                            conn,
3742                            DoSendLimit::MultipleSegments,
3743                            addr,
3744                            timer,
3745                            core_ctx,
3746                            bindings_ctx,
3747                        )
3748                    }
3749                    EitherStack::OtherStack((conn, addr)) => {
3750                        let other_demux_id = core_ctx.into_other_demux_socket_id(conn_id.clone());
3751                        do_send_inner_and_then_handle_newly_closed(
3752                            conn_id,
3753                            &other_demux_id,
3754                            socket_options,
3755                            conn,
3756                            DoSendLimit::MultipleSegments,
3757                            addr,
3758                            timer,
3759                            core_ctx,
3760                            bindings_ctx,
3761                        );
3762                    }
3763                },
3764            };
3765        })
3766    }
3767
3768    fn handle_timer(
3769        &mut self,
3770        weak_id: WeakTcpSocketId<
3771            I,
3772            <C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId,
3773            C::BindingsContext,
3774        >,
3775    ) {
3776        let id = match weak_id.upgrade() {
3777            Some(c) => c,
3778            None => return,
3779        };
3780        let (core_ctx, bindings_ctx) = self.contexts();
3781        debug!("handle_timer on {id:?}");
3782        // Alias refs so we can move weak_id to the closure.
3783        let id_alias = &id;
3784        let bindings_ctx_alias = &mut *bindings_ctx;
3785        let closed_and_defunct =
3786            core_ctx.with_socket_mut_transport_demux(&id, move |core_ctx, socket_state| {
3787                let TcpSocketState { socket_state, sharing: _, ip_options: _, socket_options } =
3788                    socket_state;
3789                let id = id_alias;
3790                trace_duration!("tcp::handle_timer", "id" => id.trace_id());
3791                let bindings_ctx = bindings_ctx_alias;
3792                let (conn, timer) = assert_matches!(
3793                    socket_state,
3794                    TcpSocketStateInner::Connected{ conn, timer} => (conn, timer)
3795                );
3796                fn do_handle_timer<SockI, WireI, CC, BC>(
3797                    core_ctx: &mut CC,
3798                    bindings_ctx: &mut BC,
3799                    id: &TcpSocketId<SockI, CC::WeakDeviceId, BC>,
3800                    demux_id: &WireI::DemuxSocketId<CC::WeakDeviceId, BC>,
3801                    socket_options: &SocketOptions,
3802                    conn: &mut Connection<SockI, WireI, CC::WeakDeviceId, BC>,
3803                    addr: &ConnAddr<
3804                        ConnIpAddr<<WireI as Ip>::Addr, NonZeroU16, NonZeroU16>,
3805                        CC::WeakDeviceId,
3806                    >,
3807                    timer: &mut BC::Timer,
3808                ) -> bool
3809                where
3810                    SockI: DualStackIpExt,
3811                    WireI: DualStackIpExt,
3812                    BC: TcpBindingsContext<CC::DeviceId>,
3813                    CC: TransportIpContext<WireI, BC>
3814                        + TcpDemuxContext<WireI, CC::WeakDeviceId, BC>
3815                        + TcpSocketContext<SockI, CC::WeakDeviceId, BC>,
3816                {
3817                    let time_wait = matches!(conn.state, State::TimeWait(_));
3818                    let newly_closed = do_send_inner(
3819                        id,
3820                        socket_options,
3821                        conn,
3822                        DoSendLimit::MultipleSegments,
3823                        addr,
3824                        timer,
3825                        core_ctx,
3826                        bindings_ctx,
3827                    );
3828                    match (newly_closed, time_wait) {
3829                        // Moved to closed state, remove from demux and cancel
3830                        // timers.
3831                        (NewlyClosed::Yes, time_wait) => {
3832                            let result = core_ctx.with_demux_mut(|DemuxState { socketmap }| {
3833                                socketmap.conns_mut().remove(demux_id, addr)
3834                            });
3835                            // Carve out an exception for time wait demux
3836                            // removal, since it could've been removed from the
3837                            // demux already as part of reuse.
3838                            //
3839                            // We can log rather silently because the demux will
3840                            // not allow us to remove the wrong connection, the
3841                            // panic is here to catch paths that are doing
3842                            // cleanup in the wrong way.
3843                            result.unwrap_or_else(|e| {
3844                                if time_wait {
3845                                    debug!(
3846                                        "raced with timewait removal for {id:?} {addr:?}: {e:?}"
3847                                    );
3848                                } else {
3849                                    panic!("failed to remove from socketmap: {e:?}");
3850                                }
3851                            });
3852                            let _: Option<_> = bindings_ctx.cancel_timer(timer);
3853
3854                            let Closed { reason } = assert_matches!(
3855                                &conn.state, State::Closed(c) => c
3856                            );
3857                            let _: bool = conn.handshake_status.update_if_pending(match reason {
3858                                None => HandshakeStatus::Completed {
3859                                    reported: conn.accept_queue.is_some(),
3860                                },
3861                                Some(_err) => HandshakeStatus::Aborted,
3862                            });
3863                        }
3864                        (NewlyClosed::No, _) => {}
3865                    }
3866                    conn.defunct && matches!(conn.state, State::Closed(_))
3867                }
3868                match core_ctx {
3869                    MaybeDualStack::NotDualStack((core_ctx, converter)) => {
3870                        let (conn, addr) = converter.convert(conn);
3871                        do_handle_timer(
3872                            core_ctx,
3873                            bindings_ctx,
3874                            id,
3875                            &I::into_demux_socket_id(id.clone()),
3876                            socket_options,
3877                            conn,
3878                            addr,
3879                            timer,
3880                        )
3881                    }
3882                    MaybeDualStack::DualStack((core_ctx, converter)) => {
3883                        match converter.convert(conn) {
3884                            EitherStack::ThisStack((conn, addr)) => do_handle_timer(
3885                                core_ctx,
3886                                bindings_ctx,
3887                                id,
3888                                &I::into_demux_socket_id(id.clone()),
3889                                socket_options,
3890                                conn,
3891                                addr,
3892                                timer,
3893                            ),
3894                            EitherStack::OtherStack((conn, addr)) => do_handle_timer(
3895                                core_ctx,
3896                                bindings_ctx,
3897                                id,
3898                                &core_ctx.into_other_demux_socket_id(id.clone()),
3899                                socket_options,
3900                                conn,
3901                                addr,
3902                                timer,
3903                            ),
3904                        }
3905                    }
3906                }
3907            });
3908        if closed_and_defunct {
3909            // Remove the entry from the primary map and drop primary.
3910            destroy_socket(core_ctx, bindings_ctx, id);
3911        }
3912    }
3913
3914    /// Access options mutably for a TCP socket.
3915    pub fn with_socket_options_mut<R, F: FnOnce(&mut SocketOptions) -> R>(
3916        &mut self,
3917        id: &TcpApiSocketId<I, C>,
3918        f: F,
3919    ) -> R {
3920        let (core_ctx, _) = self.contexts();
3921        core_ctx.with_socket_mut(id, |socket| f(&mut socket.socket_options))
3922    }
3923
3924    /// Access socket options immutably for a TCP socket
3925    pub fn with_socket_options<R, F: FnOnce(&SocketOptions) -> R>(
3926        &mut self,
3927        id: &TcpApiSocketId<I, C>,
3928        f: F,
3929    ) -> R {
3930        self.core_ctx().with_socket(id, |socket| f(&socket.socket_options))
3931    }
3932
3933    /// Set the size of the send buffer for this socket and future derived
3934    /// sockets.
3935    pub fn set_send_buffer_size(&mut self, id: &TcpApiSocketId<I, C>, size: usize) {
3936        let (core_ctx, bindings_ctx) = self.contexts();
3937        set_buffer_size::<SendBufferSize, I, _, _>(core_ctx, bindings_ctx, id, size)
3938    }
3939
3940    /// Get the size of the send buffer for this socket and future derived
3941    /// sockets.
3942    pub fn send_buffer_size(&mut self, id: &TcpApiSocketId<I, C>) -> Option<usize> {
3943        get_buffer_size::<SendBufferSize, I, _, _>(self.core_ctx(), id)
3944    }
3945
3946    /// Set the size of the send buffer for this socket and future derived
3947    /// sockets.
3948    pub fn set_receive_buffer_size(&mut self, id: &TcpApiSocketId<I, C>, size: usize) {
3949        let (core_ctx, bindings_ctx) = self.contexts();
3950        set_buffer_size::<ReceiveBufferSize, I, _, _>(core_ctx, bindings_ctx, id, size)
3951    }
3952
3953    /// Get the size of the receive buffer for this socket and future derived
3954    /// sockets.
3955    pub fn receive_buffer_size(&mut self, id: &TcpApiSocketId<I, C>) -> Option<usize> {
3956        get_buffer_size::<ReceiveBufferSize, I, _, _>(self.core_ctx(), id)
3957    }
3958
3959    /// Sets the POSIX SO_REUSEADDR socket option on a socket.
3960    pub fn set_reuseaddr(
3961        &mut self,
3962        id: &TcpApiSocketId<I, C>,
3963        reuse: bool,
3964    ) -> Result<(), SetReuseAddrError> {
3965        let new_sharing = match reuse {
3966            true => SharingState::ReuseAddress,
3967            false => SharingState::Exclusive,
3968        };
3969        self.core_ctx().with_socket_mut_transport_demux(id, |core_ctx, socket_state| {
3970            let old_sharing = socket_state.sharing;
3971            if old_sharing == new_sharing {
3972                return Ok(());
3973            }
3974
3975            match &socket_state.socket_state {
3976                TcpSocketStateInner::Unbound(_) => (),
3977                TcpSocketStateInner::Bound(BoundState { addr, .. })
3978                | TcpSocketStateInner::Listener(Listener { addr, .. }) => {
3979                    let listening =
3980                        matches!(&socket_state.socket_state, TcpSocketStateInner::Listener(_));
3981                    try_update_listener_sharing::<_, C::CoreContext, _>(
3982                        core_ctx,
3983                        id,
3984                        addr.clone(),
3985                        &ListenerSharingState { sharing: old_sharing, listening },
3986                        ListenerSharingState { sharing: new_sharing, listening },
3987                    )
3988                    .map_err(|UpdateSharingError| SetReuseAddrError::AddrInUse)?;
3989                }
3990                TcpSocketStateInner::Connected { .. } => {
3991                    // TODO(https://fxbug.dev/42180094): Support setting the option
3992                    // for connection sockets.
3993                    return Err(SetReuseAddrError::NotSupported);
3994                }
3995            };
3996
3997            socket_state.sharing = new_sharing;
3998            Ok(())
3999        })
4000    }
4001
4002    /// Gets the POSIX SO_REUSEADDR socket option on a socket.
4003    pub fn reuseaddr(&mut self, id: &TcpApiSocketId<I, C>) -> bool {
4004        self.core_ctx().with_socket(id, |state| state.sharing == SharingState::ReuseAddress)
4005    }
4006
4007    /// Gets the `dual_stack_enabled` option value.
4008    pub fn dual_stack_enabled(
4009        &mut self,
4010        id: &TcpSocketId<
4011            I,
4012            <C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId,
4013            C::BindingsContext,
4014        >,
4015    ) -> Result<bool, NotDualStackCapableError> {
4016        self.core_ctx().with_socket_mut_transport_demux(id, |core_ctx, socket_state| match core_ctx
4017        {
4018            MaybeDualStack::NotDualStack(_) => Err(NotDualStackCapableError),
4019            MaybeDualStack::DualStack((core_ctx, _converter)) => {
4020                Ok(core_ctx.dual_stack_enabled(&socket_state.ip_options))
4021            }
4022        })
4023    }
4024
4025    /// Sets the socket mark for the socket domain.
4026    pub fn set_mark(&mut self, id: &TcpApiSocketId<I, C>, domain: MarkDomain, mark: Mark) {
4027        self.with_socket_options_mut(id, |options| *options.ip_options.marks.get_mut(domain) = mark)
4028    }
4029
4030    /// Gets the socket mark for the socket domain.
4031    pub fn get_mark(&mut self, id: &TcpApiSocketId<I, C>, domain: MarkDomain) -> Mark {
4032        self.with_socket_options(id, |options| *options.ip_options.marks.get(domain))
4033    }
4034
4035    /// Sets the `dual_stack_enabled` option value.
4036    pub fn set_dual_stack_enabled(
4037        &mut self,
4038        id: &TcpSocketId<
4039            I,
4040            <C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId,
4041            C::BindingsContext,
4042        >,
4043        value: bool,
4044    ) -> Result<(), SetDualStackEnabledError> {
4045        self.core_ctx().with_socket_mut_transport_demux(id, |core_ctx, socket_state| match core_ctx
4046        {
4047            MaybeDualStack::NotDualStack(_) => Err(NotDualStackCapableError.into()),
4048            MaybeDualStack::DualStack((core_ctx, _converter)) => match socket_state.socket_state {
4049                TcpSocketStateInner::Unbound(_) => {
4050                    Ok(core_ctx.set_dual_stack_enabled(&mut socket_state.ip_options, value))
4051                }
4052                TcpSocketStateInner::Connected { .. }
4053                | TcpSocketStateInner::Bound(_)
4054                | TcpSocketStateInner::Listener(_) => Err(SetDualStackEnabledError::SocketIsBound),
4055            },
4056        })
4057    }
4058
4059    fn on_icmp_error_conn(
4060        core_ctx: &mut C::CoreContext,
4061        bindings_ctx: &mut C::BindingsContext,
4062        id: TcpSocketId<
4063            I,
4064            <C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId,
4065            C::BindingsContext,
4066        >,
4067        seq: SeqNum,
4068        error: IcmpErrorCode,
4069    ) {
4070        let destroy = core_ctx.with_socket_mut_transport_demux(&id, |core_ctx, socket_state| {
4071            let (conn_and_addr, timer) = assert_matches!(
4072                &mut socket_state.socket_state,
4073                TcpSocketStateInner::Connected { conn, timer } => (conn, timer),
4074                "invalid socket ID");
4075            let (
4076                newly_closed,
4077                accept_queue,
4078                state,
4079                soft_error,
4080                handshake_status,
4081                this_or_other_stack,
4082            ) = match core_ctx {
4083                MaybeDualStack::NotDualStack((core_ctx, converter)) => {
4084                    let (conn, addr) = converter.convert(conn_and_addr);
4085                    let (newly_closed, should_send) = conn.on_icmp_error(core_ctx, &id, seq, error);
4086                    let core_ctx = core_ctx.as_this_stack();
4087                    let demux_id = I::into_demux_socket_id(id.clone());
4088
4089                    match should_send {
4090                        ShouldRetransmit::No => {}
4091                        ShouldRetransmit::Yes => do_send_inner_and_then_handle_newly_closed(
4092                            &id,
4093                            &demux_id,
4094                            &socket_state.socket_options,
4095                            conn,
4096                            DoSendLimit::OneSegment,
4097                            addr,
4098                            timer,
4099                            core_ctx,
4100                            bindings_ctx,
4101                        ),
4102                    }
4103
4104                    (
4105                        newly_closed,
4106                        &mut conn.accept_queue,
4107                        &mut conn.state,
4108                        &mut conn.soft_error,
4109                        &mut conn.handshake_status,
4110                        EitherStack::ThisStack((core_ctx, demux_id, addr)),
4111                    )
4112                }
4113                MaybeDualStack::DualStack((core_ctx, converter)) => {
4114                    match converter.convert(conn_and_addr) {
4115                        EitherStack::ThisStack((conn, addr)) => {
4116                            let (newly_closed, should_send) =
4117                                conn.on_icmp_error(core_ctx, &id, seq, error);
4118                            let core_ctx = core_ctx.as_this_stack();
4119                            let demux_id = I::into_demux_socket_id(id.clone());
4120
4121                            match should_send {
4122                                ShouldRetransmit::No => {}
4123                                ShouldRetransmit::Yes => {
4124                                    do_send_inner_and_then_handle_newly_closed(
4125                                        &id,
4126                                        &demux_id,
4127                                        &socket_state.socket_options,
4128                                        conn,
4129                                        DoSendLimit::OneSegment,
4130                                        addr,
4131                                        timer,
4132                                        core_ctx,
4133                                        bindings_ctx,
4134                                    )
4135                                }
4136                            }
4137
4138                            (
4139                                newly_closed,
4140                                &mut conn.accept_queue,
4141                                &mut conn.state,
4142                                &mut conn.soft_error,
4143                                &mut conn.handshake_status,
4144                                EitherStack::ThisStack((core_ctx, demux_id, addr)),
4145                            )
4146                        }
4147                        EitherStack::OtherStack((conn, addr)) => {
4148                            let (newly_closed, should_send) =
4149                                conn.on_icmp_error(core_ctx, &id, seq, error);
4150                            let demux_id = core_ctx.into_other_demux_socket_id(id.clone());
4151
4152                            match should_send {
4153                                ShouldRetransmit::No => {}
4154                                ShouldRetransmit::Yes => {
4155                                    do_send_inner_and_then_handle_newly_closed(
4156                                        &id,
4157                                        &demux_id,
4158                                        &socket_state.socket_options,
4159                                        conn,
4160                                        DoSendLimit::OneSegment,
4161                                        addr,
4162                                        timer,
4163                                        core_ctx,
4164                                        bindings_ctx,
4165                                    )
4166                                }
4167                            }
4168
4169                            (
4170                                newly_closed,
4171                                &mut conn.accept_queue,
4172                                &mut conn.state,
4173                                &mut conn.soft_error,
4174                                &mut conn.handshake_status,
4175                                EitherStack::OtherStack((core_ctx, demux_id, addr)),
4176                            )
4177                        }
4178                    }
4179                }
4180            };
4181
4182            if let State::Closed(Closed { reason }) = state {
4183                debug!("handshake_status: {handshake_status:?}");
4184                let _: bool = handshake_status.update_if_pending(HandshakeStatus::Aborted);
4185                // Unregister the socket from the socketmap if newly closed.
4186                match this_or_other_stack {
4187                    EitherStack::ThisStack((core_ctx, demux_id, addr)) => {
4188                        handle_newly_closed::<I, _, _, _>(
4189                            core_ctx,
4190                            bindings_ctx,
4191                            newly_closed,
4192                            &demux_id,
4193                            addr,
4194                            timer,
4195                        );
4196                    }
4197                    EitherStack::OtherStack((core_ctx, demux_id, addr)) => {
4198                        handle_newly_closed::<I::OtherVersion, _, _, _>(
4199                            core_ctx,
4200                            bindings_ctx,
4201                            newly_closed,
4202                            &demux_id,
4203                            addr,
4204                            timer,
4205                        );
4206                    }
4207                };
4208                match accept_queue {
4209                    Some(accept_queue) => {
4210                        accept_queue.remove(&id);
4211                        // destroy the socket if not held by the user.
4212                        return true;
4213                    }
4214                    None => {
4215                        if let Some(err) = reason {
4216                            if *err == ConnectionError::TimedOut {
4217                                *err = soft_error.unwrap_or(ConnectionError::TimedOut);
4218                            }
4219                        }
4220                    }
4221                }
4222            }
4223            false
4224        });
4225        if destroy {
4226            destroy_socket(core_ctx, bindings_ctx, id);
4227        }
4228    }
4229
4230    fn on_icmp_error(
4231        &mut self,
4232        orig_src_ip: SpecifiedAddr<I::Addr>,
4233        orig_dst_ip: SpecifiedAddr<I::Addr>,
4234        orig_src_port: NonZeroU16,
4235        orig_dst_port: NonZeroU16,
4236        seq: SeqNum,
4237        error: IcmpErrorCode,
4238    ) where
4239        C::CoreContext: TcpContext<I::OtherVersion, C::BindingsContext>,
4240        C::BindingsContext: TcpBindingsContext<
4241            <<C as ContextPair>::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId,
4242        >,
4243    {
4244        let (core_ctx, bindings_ctx) = self.contexts();
4245
4246        let orig_src_ip = match SocketIpAddr::try_from(orig_src_ip) {
4247            Ok(ip) => ip,
4248            Err(AddrIsMappedError {}) => {
4249                trace!("ignoring ICMP error from IPv4-mapped-IPv6 source: {}", orig_src_ip);
4250                return;
4251            }
4252        };
4253        let orig_dst_ip = match SocketIpAddr::try_from(orig_dst_ip) {
4254            Ok(ip) => ip,
4255            Err(AddrIsMappedError {}) => {
4256                trace!("ignoring ICMP error to IPv4-mapped-IPv6 destination: {}", orig_dst_ip);
4257                return;
4258            }
4259        };
4260
4261        let id = TcpDemuxContext::<I, _, _>::with_demux(core_ctx, |DemuxState { socketmap }| {
4262            socketmap
4263                .conns()
4264                .get_by_addr(&ConnAddr {
4265                    ip: ConnIpAddr {
4266                        local: (orig_src_ip, orig_src_port),
4267                        remote: (orig_dst_ip, orig_dst_port),
4268                    },
4269                    device: None,
4270                })
4271                .map(|ConnAddrState { sharing: _, id }| id.clone())
4272        });
4273
4274        let id = match id {
4275            Some(id) => id,
4276            None => return,
4277        };
4278
4279        match I::into_dual_stack_ip_socket(id) {
4280            EitherStack::ThisStack(id) => {
4281                Self::on_icmp_error_conn(core_ctx, bindings_ctx, id, seq, error)
4282            }
4283            EitherStack::OtherStack(id) => TcpApi::<I::OtherVersion, C>::on_icmp_error_conn(
4284                core_ctx,
4285                bindings_ctx,
4286                id,
4287                seq,
4288                error,
4289            ),
4290        };
4291    }
4292
4293    /// Gets the last error on the connection.
4294    pub fn get_socket_error(&mut self, id: &TcpApiSocketId<I, C>) -> Option<ConnectionError> {
4295        self.core_ctx().with_socket_mut_and_converter(id, |socket_state, converter| {
4296            match &mut socket_state.socket_state {
4297                TcpSocketStateInner::Unbound(_)
4298                | TcpSocketStateInner::Bound(_)
4299                | TcpSocketStateInner::Listener(_) => None,
4300                TcpSocketStateInner::Connected { conn, timer: _ } => {
4301                    let reporter = match converter {
4302                        MaybeDualStack::NotDualStack(converter) => {
4303                            let (conn, _addr) = converter.convert(conn);
4304                            ErrorReporter::new(&mut conn.state, &mut conn.soft_error)
4305                        }
4306                        MaybeDualStack::DualStack(converter) => match converter.convert(conn) {
4307                            EitherStack::ThisStack((conn, _addr)) => {
4308                                ErrorReporter::new(&mut conn.state, &mut conn.soft_error)
4309                            }
4310                            EitherStack::OtherStack((conn, _addr)) => {
4311                                ErrorReporter::new(&mut conn.state, &mut conn.soft_error)
4312                            }
4313                        },
4314                    };
4315                    reporter.report_error()
4316                }
4317            }
4318        })
4319    }
4320
4321    /// Gets the original destination address for the socket, if it is connected
4322    /// and has a destination in the specified stack.
4323    ///
4324    /// Note that this always returns the original destination in the IP stack
4325    /// in which the socket is; for example, for a dual-stack IPv6 socket that
4326    /// is connected to an IPv4 address, this will return the IPv4-mapped IPv6
4327    /// version of that address.
4328    pub fn get_original_destination(
4329        &mut self,
4330        id: &TcpApiSocketId<I, C>,
4331    ) -> Result<(SpecifiedAddr<I::Addr>, NonZeroU16), OriginalDestinationError> {
4332        self.core_ctx().with_socket_mut_transport_demux(id, |core_ctx, state| {
4333            let TcpSocketState { socket_state, .. } = state;
4334            let conn = match socket_state {
4335                TcpSocketStateInner::Connected { conn, .. } => conn,
4336                TcpSocketStateInner::Bound(_)
4337                | TcpSocketStateInner::Listener(_)
4338                | TcpSocketStateInner::Unbound(_) => {
4339                    return Err(OriginalDestinationError::NotConnected);
4340                }
4341            };
4342
4343            fn tuple<I: IpExt>(
4344                ConnIpAddr { local, remote }: ConnIpAddr<I::Addr, NonZeroU16, NonZeroU16>,
4345            ) -> Tuple<I> {
4346                let (local_addr, local_port) = local;
4347                let (remote_addr, remote_port) = remote;
4348                Tuple {
4349                    protocol: IpProto::Tcp.into(),
4350                    src_addr: local_addr.addr(),
4351                    dst_addr: remote_addr.addr(),
4352                    src_port_or_id: local_port.get(),
4353                    dst_port_or_id: remote_port.get(),
4354                }
4355            }
4356
4357            let (addr, port) = match core_ctx {
4358                MaybeDualStack::NotDualStack((core_ctx, converter)) => {
4359                    let (_conn, addr) = converter.convert(conn);
4360                    let tuple: Tuple<I> = tuple(addr.ip);
4361                    core_ctx
4362                        .get_original_destination(&tuple)
4363                        .ok_or(OriginalDestinationError::NotFound)
4364                }
4365                MaybeDualStack::DualStack((core_ctx, converter)) => match converter.convert(conn) {
4366                    EitherStack::ThisStack((_conn, addr)) => {
4367                        let tuple: Tuple<I> = tuple(addr.ip);
4368                        let (addr, port) = core_ctx
4369                            .get_original_destination(&tuple)
4370                            .ok_or(OriginalDestinationError::NotFound)?;
4371                        let addr = I::get_original_dst(
4372                            converter.convert_back(EitherStack::ThisStack(addr)),
4373                        );
4374                        Ok((addr, port))
4375                    }
4376                    EitherStack::OtherStack((_conn, addr)) => {
4377                        let tuple: Tuple<I::OtherVersion> = tuple(addr.ip);
4378                        let (addr, port) = core_ctx
4379                            .get_original_destination(&tuple)
4380                            .ok_or(OriginalDestinationError::NotFound)?;
4381                        let addr = I::get_original_dst(
4382                            converter.convert_back(EitherStack::OtherStack(addr)),
4383                        );
4384                        Ok((addr, port))
4385                    }
4386                },
4387            }?;
4388
4389            // TCP connections always have a specified destination address and
4390            // port, but this invariant is not upheld in the type system here
4391            // because we are retrieving the destination from the connection
4392            // tracking table.
4393            let addr = SpecifiedAddr::new(addr).ok_or_else(|| {
4394                error!("original destination for socket {id:?} had unspecified addr (port {port})");
4395                OriginalDestinationError::UnspecifiedDestinationAddr
4396            })?;
4397            let port = NonZeroU16::new(port).ok_or_else(|| {
4398                error!("original destination for socket {id:?} had unspecified port (addr {addr})");
4399                OriginalDestinationError::UnspecifiedDestinationPort
4400            })?;
4401            Ok((addr, port))
4402        })
4403    }
4404
4405    /// Get diagnostic information for sockets matching the provided matcher.
4406    pub fn bound_sockets_diagnostics<M, E>(
4407        &mut self,
4408        matcher: &M,
4409        results: &mut E,
4410        extended_info: bool,
4411    ) where
4412        M: IpSocketPropertiesMatcher<<C::BindingsContext as MatcherBindingsTypes>::DeviceClass>
4413            + ?Sized,
4414        E: Extend<TcpSocketDiagnostics<I, <C::BindingsContext as InstantBindingsTypes>::Instant>>,
4415        <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId:
4416            netstack3_base::InterfaceProperties<
4417                    <C::BindingsContext as MatcherBindingsTypes>::DeviceClass,
4418                >,
4419    {
4420        self.core_ctx().for_each_socket(|id, state| {
4421            if !matcher.matches_ip_socket(&TcpSocketStateForMatching { state, id }) {
4422                return;
4423            }
4424
4425            // get_diagnostics returns None if the socket is unbound, which
4426            // we're not returning in order to match Linux's behavior.
4427            let counters = id.counters();
4428            results.extend(state.get_diagnostics(counters, extended_info).map(
4429                |(tuple, state_machine, marks, tcp_info)| TcpSocketDiagnostics {
4430                    tuple,
4431                    state_machine,
4432                    cookie: id.socket_cookie(),
4433                    marks,
4434                    tcp_info,
4435                },
4436            ));
4437        });
4438    }
4439
4440    /// Disconnects all bound sockets matching the provided matcher.
4441    ///
4442    /// They are moved to state CLOSE, and an RST is sent if required. For
4443    /// LISTEN sockets, an RST is sent to any sockets that are in the accept
4444    /// queue. The tuple is *not* cleared.
4445    ///
4446    /// Returns the number of sockets that were disconnected.
4447    pub fn disconnect_bound<M>(&mut self, matcher: &M) -> usize
4448    where
4449        M: IpSocketPropertiesMatcher<<C::BindingsContext as MatcherBindingsTypes>::DeviceClass>
4450            + ?Sized,
4451        <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId:
4452            netstack3_base::InterfaceProperties<
4453                    <C::BindingsContext as MatcherBindingsTypes>::DeviceClass,
4454                >,
4455    {
4456        let (core_ctx, bindings_ctx) = self.contexts();
4457
4458        // We filter and disconnect separately here because disconnection is not a
4459        // performance-sensitive operation and it's significantly easier to do
4460        // than to manage the lifetimes and locking. Also, the only expected
4461        // user at the time of writing is Starnix's SOCK_DESTROY implementation,
4462        // which will only call this with a single socket at a time.
4463        let mut ids = Vec::new();
4464        core_ctx.for_each_socket(|id, state| {
4465            if matcher.matches_ip_socket(&TcpSocketStateForMatching { state, id }) {
4466                ids.push(id.clone());
4467            }
4468        });
4469
4470        // It's possible a socket no longer matches. However, this is a
4471        // small race in comparison to the ones between API calls for different
4472        // sockets (bind, connect, etc).
4473        ids.into_iter()
4474            .filter(|id| match disconnect_socket(core_ctx, bindings_ctx, &id) {
4475                Ok(()) => true,
4476                // We're okay with this because it's possible we raced with the
4477                // socket being closed.
4478                Err(NoConnection) => false,
4479            })
4480            .count()
4481    }
4482
4483    /// Provides access to shared and per-socket TCP stats via a visitor.
4484    pub fn inspect<N>(&mut self, inspector: &mut N)
4485    where
4486        N: Inspector
4487            + InspectorDeviceExt<<C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
4488    {
4489        self.core_ctx().for_each_socket(|socket_id, socket_state| {
4490            inspector.record_debug_child(socket_id, |node| {
4491                node.record_str("TransportProtocol", "TCP");
4492                node.record_str(
4493                    "NetworkProtocol",
4494                    match I::VERSION {
4495                        IpVersion::V4 => "IPv4",
4496                        IpVersion::V6 => "IPv6",
4497                    },
4498                );
4499                let TcpSocketState { socket_state, sharing: _, ip_options: _, socket_options } =
4500                    socket_state;
4501                node.delegate_inspectable(&socket_options.ip_options.marks);
4502                match socket_state {
4503                    TcpSocketStateInner::Unbound(_) => {
4504                        node.record_local_socket_addr::<N, I::Addr, _, NonZeroU16>(None);
4505                        node.record_remote_socket_addr::<N, I::Addr, _, NonZeroU16>(None);
4506                    }
4507                    TcpSocketStateInner::Bound(BoundState { addr, .. }) => {
4508                        let BoundInfo { addr, port, device } = I::get_bound_info(addr);
4509                        let local = addr.map_or_else(
4510                            || ZonedAddr::Unzoned(I::UNSPECIFIED_ADDRESS),
4511                            |addr| maybe_zoned(addr.addr(), &device).into(),
4512                        );
4513                        node.record_local_socket_addr::<N, _, _, _>(Some((local, port)));
4514                        node.record_remote_socket_addr::<N, I::Addr, _, NonZeroU16>(None);
4515                    }
4516                    TcpSocketStateInner::Listener(Listener {
4517                        addr, accept_queue, backlog, ..
4518                    }) => {
4519                        let BoundInfo { addr, port, device } = I::get_bound_info(addr);
4520                        let local = addr.map_or_else(
4521                            || ZonedAddr::Unzoned(I::UNSPECIFIED_ADDRESS),
4522                            |addr| maybe_zoned(addr.addr(), &device).into(),
4523                        );
4524                        node.record_local_socket_addr::<N, _, _, _>(Some((local, port)));
4525                        node.record_remote_socket_addr::<N, I::Addr, _, NonZeroU16>(None);
4526                        node.record_child("AcceptQueue", |node| {
4527                            node.record_usize("BacklogSize", *backlog);
4528                            accept_queue.inspect(node);
4529                        });
4530                    }
4531                    TcpSocketStateInner::Connected { conn, .. } => {
4532                        if I::get_defunct(conn) {
4533                            return;
4534                        }
4535                        let state = I::get_state(conn);
4536                        let ConnectionInfo {
4537                            local_addr: SocketAddr { ip: local_ip, port: local_port },
4538                            remote_addr: SocketAddr { ip: remote_ip, port: remote_port },
4539                            device: _,
4540                        } = I::get_conn_info(conn);
4541                        node.record_local_socket_addr::<N, I::Addr, _, _>(Some((
4542                            local_ip.into(),
4543                            local_port,
4544                        )));
4545                        node.record_remote_socket_addr::<N, I::Addr, _, _>(Some((
4546                            remote_ip.into(),
4547                            remote_port,
4548                        )));
4549                        node.record_display("State", state);
4550                    }
4551                }
4552                node.record_child("Counters", |node| {
4553                    node.delegate_inspectable(&CombinedTcpCounters {
4554                        with_socket: socket_id.counters(),
4555                        without_socket: None,
4556                    })
4557                })
4558            });
4559        })
4560    }
4561
4562    /// Calls the callback with mutable access to the send buffer, if one is
4563    /// instantiated.
4564    ///
4565    /// If no buffer is instantiated returns `None`.
4566    pub fn with_send_buffer<
4567        R,
4568        F: FnOnce(&mut <C::BindingsContext as TcpBindingsTypes>::SendBuffer) -> R,
4569    >(
4570        &mut self,
4571        id: &TcpApiSocketId<I, C>,
4572        f: F,
4573    ) -> Option<R> {
4574        self.core_ctx().with_socket_mut_and_converter(id, |state, converter| {
4575            get_buffers_mut::<_, C::CoreContext, _>(state, converter).into_send_buffer().map(f)
4576        })
4577    }
4578
4579    /// Calls the callback with mutable access to the receive buffer, if one is
4580    /// instantiated.
4581    ///
4582    /// If no buffer is instantiated returns `None`.
4583    pub fn with_receive_buffer<
4584        R,
4585        F: FnOnce(&mut <C::BindingsContext as TcpBindingsTypes>::ReceiveBuffer) -> R,
4586    >(
4587        &mut self,
4588        id: &TcpApiSocketId<I, C>,
4589        f: F,
4590    ) -> Option<R> {
4591        self.core_ctx().with_socket_mut_and_converter(id, |state, converter| {
4592            get_buffers_mut::<_, C::CoreContext, _>(state, converter).into_receive_buffer().map(f)
4593        })
4594    }
4595}
4596
4597/// Destroys the socket with `id`.
4598fn destroy_socket<I, CC, BC>(
4599    core_ctx: &mut CC,
4600    bindings_ctx: &mut BC,
4601    id: TcpSocketId<I, CC::WeakDeviceId, BC>,
4602) where
4603    I: DualStackIpExt,
4604    CC: TcpContext<I, BC>,
4605    BC: TcpBindingsContext<CC::DeviceId>,
4606{
4607    let weak = id.downgrade();
4608
4609    core_ctx.with_all_sockets_mut(move |all_sockets| {
4610        let TcpSocketId(rc) = &id;
4611        let debug_refs = StrongRc::debug_references(rc);
4612        let entry = all_sockets.entry(id);
4613        let primary = match entry {
4614            hash_map::Entry::Occupied(o) => match o.get() {
4615                TcpSocketSetEntry::DeadOnArrival => {
4616                    let id = o.key();
4617                    debug!("{id:?} destruction skipped, socket is DOA. References={debug_refs:?}",);
4618                    None
4619                }
4620                TcpSocketSetEntry::Primary(_) => {
4621                    assert_matches!(o.remove_entry(), (_, TcpSocketSetEntry::Primary(p)) => Some(p))
4622                }
4623            },
4624            hash_map::Entry::Vacant(v) => {
4625                let id = v.key();
4626                let TcpSocketId(rc) = id;
4627                if !StrongRc::marked_for_destruction(rc) {
4628                    // Socket is not yet marked for destruction, we've raced
4629                    // this removal with the addition to the socket set. Mark
4630                    // the entry as DOA.
4631                    debug!(
4632                        "{id:?} raced with insertion, marking socket as DOA. \
4633                        References={debug_refs:?}",
4634                    );
4635                    let _: &mut _ = v.insert(TcpSocketSetEntry::DeadOnArrival);
4636                } else {
4637                    debug!("{id:?} destruction is already deferred. References={debug_refs:?}");
4638                }
4639                None
4640            }
4641        };
4642
4643        // There are a number of races that can happen with attempted socket
4644        // destruction, but these should not be possible in tests because
4645        // they're singlethreaded.
4646        #[cfg(test)]
4647        let primary = primary.unwrap_or_else(|| {
4648            panic!("deferred destruction not allowed in tests. References={debug_refs:?}")
4649        });
4650        #[cfg(not(test))]
4651        let Some(primary) = primary else {
4652            return;
4653        };
4654
4655        let remove_result =
4656            BC::unwrap_or_notify_with_new_reference_notifier(primary, |state| state);
4657        match remove_result {
4658            RemoveResourceResult::Removed(state) => debug!("destroyed {weak:?} {state:?}"),
4659            RemoveResourceResult::Deferred(receiver) => {
4660                debug!("deferred removal {weak:?}");
4661                bindings_ctx.defer_removal(receiver)
4662            }
4663        }
4664    })
4665}
4666
4667// Shuts down the listener socket and returns the pending connections and the
4668// new bound state for the socket. Pending connections should be closed by
4669// passed `close_pending_sockets`.
4670fn shut_down_listener_socket<I, CC, BC>(
4671    core_ctx: MaybeDualStack<
4672        (&mut CC::DualStackIpTransportAndDemuxCtx<'_>, CC::DualStackConverter),
4673        (&mut CC::SingleStackIpTransportAndDemuxCtx<'_>, CC::SingleStackConverter),
4674    >,
4675    id: &TcpSocketId<I, CC::WeakDeviceId, BC>,
4676    listener: &Listener<I, CC::WeakDeviceId, BC>,
4677    sharing: SharingState,
4678) -> (
4679    impl Iterator<Item = TcpSocketId<I, CC::WeakDeviceId, BC>> + use<I, CC, BC>,
4680    BoundState<I, CC::WeakDeviceId, BC>,
4681)
4682where
4683    I: DualStackIpExt,
4684    BC: TcpBindingsContext<CC::DeviceId>,
4685    CC: TcpContext<I, BC>,
4686{
4687    let Listener { addr, backlog: _, accept_queue, buffer_sizes } = listener;
4688    let (pending, socket_extra) = accept_queue.close();
4689
4690    try_update_listener_sharing::<_, CC, _>(
4691        core_ctx,
4692        id,
4693        addr.clone(),
4694        &ListenerSharingState { listening: true, sharing },
4695        ListenerSharingState { listening: false, sharing },
4696    )
4697    .unwrap_or_else(|e| {
4698        unreachable!("downgrading a TCP listener to bound should not fail, got {e:?}")
4699    });
4700
4701    let bound = BoundState {
4702        addr: addr.clone(),
4703        buffer_sizes: buffer_sizes.clone(),
4704        socket_extra: Takeable::new(socket_extra),
4705    };
4706
4707    (pending, bound)
4708}
4709
4710fn disconnect_socket<I, CC, BC>(
4711    core_ctx: &mut CC,
4712    bindings_ctx: &mut BC,
4713    id: &TcpSocketId<I, CC::WeakDeviceId, BC>,
4714) -> Result<(), NoConnection>
4715where
4716    I: DualStackIpExt,
4717    BC: TcpBindingsContext<CC::DeviceId>,
4718    CC: TcpContext<I, BC>,
4719{
4720    debug!("disconnect for {id:?}");
4721    let pending = core_ctx.with_socket_mut_transport_demux(id, |core_ctx, socket_state| {
4722        let TcpSocketState { socket_state, sharing, ip_options: _, socket_options } = socket_state;
4723        match socket_state {
4724            TcpSocketStateInner::Unbound(_) => Err(NoConnection),
4725            TcpSocketStateInner::Connected { conn, timer } => {
4726                match core_ctx {
4727                    MaybeDualStack::NotDualStack((core_ctx, converter)) => {
4728                        let (conn, addr) = converter.convert(conn);
4729                        abort_socket(
4730                            core_ctx,
4731                            bindings_ctx,
4732                            id,
4733                            &I::into_demux_socket_id(id.clone()),
4734                            socket_options,
4735                            timer,
4736                            conn,
4737                            addr,
4738                            ConnectionError::Aborted,
4739                        )
4740                    }
4741                    MaybeDualStack::DualStack((core_ctx, converter)) => {
4742                        match converter.convert(conn) {
4743                            EitherStack::ThisStack((conn, addr)) => abort_socket(
4744                                core_ctx,
4745                                bindings_ctx,
4746                                id,
4747                                &I::into_demux_socket_id(id.clone()),
4748                                socket_options,
4749                                timer,
4750                                conn,
4751                                addr,
4752                                ConnectionError::Aborted,
4753                            ),
4754                            EitherStack::OtherStack((conn, addr)) => abort_socket(
4755                                core_ctx,
4756                                bindings_ctx,
4757                                id,
4758                                &core_ctx.into_other_demux_socket_id(id.clone()),
4759                                socket_options,
4760                                timer,
4761                                conn,
4762                                addr,
4763                                ConnectionError::Aborted,
4764                            ),
4765                        }
4766                    }
4767                };
4768                Ok(None)
4769            }
4770            TcpSocketStateInner::Bound(_) => Ok(None),
4771            TcpSocketStateInner::Listener(listener) => {
4772                let (pending, bound) =
4773                    shut_down_listener_socket::<I, CC, BC>(core_ctx, id, listener, *sharing);
4774                *socket_state = TcpSocketStateInner::Bound(bound);
4775                Ok(Some(pending))
4776            }
4777        }
4778    })?;
4779
4780    close_pending_sockets(core_ctx, bindings_ctx, pending.into_iter().flatten());
4781
4782    Ok(())
4783}
4784
4785/// Closes all sockets in `pending`.
4786///
4787/// Used to cleanup all pending sockets in the accept queue when a listener
4788/// socket is shutdown or closed.
4789fn close_pending_sockets<I, CC, BC>(
4790    core_ctx: &mut CC,
4791    bindings_ctx: &mut BC,
4792    pending: impl Iterator<Item = TcpSocketId<I, CC::WeakDeviceId, BC>>,
4793) where
4794    I: DualStackIpExt,
4795    BC: TcpBindingsContext<CC::DeviceId>,
4796    CC: TcpContext<I, BC>,
4797{
4798    for conn_id in pending {
4799        core_ctx.with_socket_mut_transport_demux(&conn_id, |core_ctx, socket_state| {
4800            let TcpSocketState { socket_state, sharing: _, ip_options: _, socket_options } =
4801                socket_state;
4802            let (conn_and_addr, timer) = assert_matches!(
4803                socket_state,
4804                TcpSocketStateInner::Connected{ conn, timer } => (conn, timer),
4805                "invalid socket ID"
4806            );
4807            let _: Option<BC::Instant> = bindings_ctx.cancel_timer(timer);
4808            let this_or_other_stack = match core_ctx {
4809                MaybeDualStack::NotDualStack((core_ctx, converter)) => {
4810                    let (conn, addr) = converter.convert(conn_and_addr);
4811                    EitherStack::ThisStack((
4812                        core_ctx.as_this_stack(),
4813                        I::into_demux_socket_id(conn_id.clone()),
4814                        conn,
4815                        addr.clone(),
4816                    ))
4817                }
4818                MaybeDualStack::DualStack((core_ctx, converter)) => match converter
4819                    .convert(conn_and_addr)
4820                {
4821                    EitherStack::ThisStack((conn, addr)) => EitherStack::ThisStack((
4822                        core_ctx.as_this_stack(),
4823                        I::into_demux_socket_id(conn_id.clone()),
4824                        conn,
4825                        addr.clone(),
4826                    )),
4827                    EitherStack::OtherStack((conn, addr)) => {
4828                        let other_demux_id = core_ctx.into_other_demux_socket_id(conn_id.clone());
4829                        EitherStack::OtherStack((core_ctx, other_demux_id, conn, addr.clone()))
4830                    }
4831                },
4832            };
4833
4834            match this_or_other_stack {
4835                EitherStack::ThisStack((core_ctx, demux_id, conn, conn_addr)) => abort_socket(
4836                    core_ctx,
4837                    bindings_ctx,
4838                    &conn_id,
4839                    &demux_id,
4840                    socket_options,
4841                    timer,
4842                    conn,
4843                    &conn_addr,
4844                    ConnectionError::ConnectionReset,
4845                ),
4846                EitherStack::OtherStack((core_ctx, demux_id, conn, conn_addr)) => abort_socket(
4847                    core_ctx,
4848                    bindings_ctx,
4849                    &conn_id,
4850                    &demux_id,
4851                    socket_options,
4852                    timer,
4853                    conn,
4854                    &conn_addr,
4855                    ConnectionError::ConnectionReset,
4856                ),
4857            }
4858        });
4859        destroy_socket(core_ctx, bindings_ctx, conn_id);
4860    }
4861}
4862
4863fn abort_socket<WireI, SockI, DC, BC>(
4864    core_ctx: &mut DC,
4865    bindings_ctx: &mut BC,
4866    sock_id: &TcpSocketId<SockI, DC::WeakDeviceId, BC>,
4867    demux_id: &WireI::DemuxSocketId<DC::WeakDeviceId, BC>,
4868    socket_options: &SocketOptions,
4869    timer: &mut BC::Timer,
4870    conn: &mut Connection<SockI, WireI, DC::WeakDeviceId, BC>,
4871    conn_addr: &ConnAddr<ConnIpAddr<WireI::Addr, NonZeroU16, NonZeroU16>, DC::WeakDeviceId>,
4872    reason: ConnectionError,
4873) where
4874    WireI: DualStackIpExt,
4875    SockI: DualStackIpExt,
4876    DC: TransportIpContext<WireI, BC>
4877        + DeviceIpSocketHandler<WireI, BC>
4878        + TcpDemuxContext<WireI, DC::WeakDeviceId, BC>
4879        + TcpSocketContext<SockI, DC::WeakDeviceId, BC>,
4880    BC: TcpBindingsContext<DC::DeviceId>,
4881{
4882    debug!("aborting socket {sock_id:?} with reason {reason}");
4883    let (maybe_reset, newly_closed) =
4884        conn.state.abort(&TcpCountersRefs::from_ctx(core_ctx, sock_id), bindings_ctx.now(), reason);
4885    handle_newly_closed(core_ctx, bindings_ctx, newly_closed, demux_id, conn_addr, timer);
4886    if let Some(reset) = maybe_reset {
4887        let ConnAddr { ip, device: _ } = conn_addr;
4888        send_tcp_segment(
4889            core_ctx,
4890            bindings_ctx,
4891            Some(sock_id),
4892            Some(&conn.ip_sock),
4893            *ip,
4894            reset.into_empty(),
4895            &socket_options.ip_options,
4896        );
4897    }
4898}
4899
4900// How many segments to send as part of the "do_send" routine.
4901pub(crate) enum DoSendLimit {
4902    OneSegment,
4903    MultipleSegments,
4904}
4905
4906// Calls `do_send_inner` and handle the result.
4907fn do_send_inner_and_then_handle_newly_closed<SockI, WireI, CC, BC>(
4908    conn_id: &TcpSocketId<SockI, CC::WeakDeviceId, BC>,
4909    demux_id: &WireI::DemuxSocketId<CC::WeakDeviceId, BC>,
4910    socket_options: &SocketOptions,
4911    conn: &mut Connection<SockI, WireI, CC::WeakDeviceId, BC>,
4912    limit: DoSendLimit,
4913    addr: &ConnAddr<ConnIpAddr<WireI::Addr, NonZeroU16, NonZeroU16>, CC::WeakDeviceId>,
4914    timer: &mut BC::Timer,
4915    core_ctx: &mut CC,
4916    bindings_ctx: &mut BC,
4917) where
4918    SockI: DualStackIpExt,
4919    WireI: DualStackIpExt,
4920    BC: TcpBindingsContext<CC::DeviceId>,
4921    CC: TransportIpContext<WireI, BC>
4922        + TcpSocketContext<SockI, CC::WeakDeviceId, BC>
4923        + TcpDemuxContext<WireI, CC::WeakDeviceId, BC>,
4924{
4925    let newly_closed =
4926        do_send_inner(conn_id, socket_options, conn, limit, addr, timer, core_ctx, bindings_ctx);
4927    handle_newly_closed(core_ctx, bindings_ctx, newly_closed, demux_id, addr, timer);
4928}
4929
4930#[inline]
4931fn handle_newly_closed<I, D, CC, BC>(
4932    core_ctx: &mut CC,
4933    bindings_ctx: &mut BC,
4934    newly_closed: NewlyClosed,
4935    demux_id: &I::DemuxSocketId<D, BC>,
4936    addr: &ConnAddr<ConnIpAddr<I::Addr, NonZeroU16, NonZeroU16>, D>,
4937    timer: &mut BC::Timer,
4938) where
4939    I: DualStackIpExt,
4940    D: WeakDeviceIdentifier,
4941    CC: TcpDemuxContext<I, D, BC>,
4942    BC: TcpBindingsContext<D::Strong>,
4943{
4944    if newly_closed == NewlyClosed::Yes {
4945        core_ctx.with_demux_mut(|DemuxState { socketmap }| {
4946            socketmap.conns_mut().remove(demux_id, addr).expect("failed to remove from demux");
4947            let _: Option<_> = bindings_ctx.cancel_timer(timer);
4948        });
4949    }
4950}
4951
4952fn do_send_inner<SockI, WireI, CC, BC>(
4953    conn_id: &TcpSocketId<SockI, CC::WeakDeviceId, BC>,
4954    socket_options: &SocketOptions,
4955    conn: &mut Connection<SockI, WireI, CC::WeakDeviceId, BC>,
4956    limit: DoSendLimit,
4957    addr: &ConnAddr<ConnIpAddr<WireI::Addr, NonZeroU16, NonZeroU16>, CC::WeakDeviceId>,
4958    timer: &mut BC::Timer,
4959    core_ctx: &mut CC,
4960    bindings_ctx: &mut BC,
4961) -> NewlyClosed
4962where
4963    SockI: DualStackIpExt,
4964    WireI: DualStackIpExt,
4965    BC: TcpBindingsContext<CC::DeviceId>,
4966    CC: TransportIpContext<WireI, BC> + TcpSocketContext<SockI, CC::WeakDeviceId, BC>,
4967{
4968    let newly_closed = loop {
4969        match conn.state.poll_send(
4970            &conn_id.either(),
4971            &TcpCountersRefs::from_ctx(core_ctx, conn_id),
4972            bindings_ctx.now(),
4973            socket_options,
4974        ) {
4975            Ok(seg) => {
4976                send_tcp_segment(
4977                    core_ctx,
4978                    bindings_ctx,
4979                    Some(conn_id),
4980                    Some(&conn.ip_sock),
4981                    addr.ip.clone(),
4982                    seg,
4983                    &socket_options.ip_options,
4984                );
4985                match limit {
4986                    DoSendLimit::OneSegment => break NewlyClosed::No,
4987                    DoSendLimit::MultipleSegments => {}
4988                }
4989            }
4990            Err(newly_closed) => break newly_closed,
4991        }
4992    };
4993
4994    if let Some(instant) = conn.state.poll_send_at() {
4995        let _: Option<_> = bindings_ctx.schedule_timer_instant(instant, timer);
4996    }
4997
4998    newly_closed
4999}
5000
5001enum SendBufferSize {}
5002enum ReceiveBufferSize {}
5003
5004trait AccessBufferSize<R, S> {
5005    fn set_buffer_size(buffers: BuffersRefMut<'_, R, S>, new_size: usize);
5006    fn get_buffer_size(buffers: BuffersRefMut<'_, R, S>) -> Option<usize>;
5007    fn allowed_range(settings: &TcpSettings) -> (usize, usize);
5008}
5009
5010impl<R: Buffer, S: Buffer> AccessBufferSize<R, S> for SendBufferSize {
5011    fn set_buffer_size(buffers: BuffersRefMut<'_, R, S>, new_size: usize) {
5012        match buffers {
5013            BuffersRefMut::NoBuffers | BuffersRefMut::RecvOnly { .. } => {}
5014            BuffersRefMut::Both { send, recv: _ } | BuffersRefMut::SendOnly(send) => {
5015                send.request_capacity(new_size)
5016            }
5017            BuffersRefMut::Sizes(BufferSizes { send, receive: _ }) => *send = new_size,
5018        }
5019    }
5020
5021    fn allowed_range(settings: &TcpSettings) -> (usize, usize) {
5022        (settings.send_buffer.min().get(), settings.send_buffer.max().get())
5023    }
5024
5025    fn get_buffer_size(buffers: BuffersRefMut<'_, R, S>) -> Option<usize> {
5026        match buffers {
5027            BuffersRefMut::NoBuffers | BuffersRefMut::RecvOnly { .. } => None,
5028            BuffersRefMut::Both { send, recv: _ } | BuffersRefMut::SendOnly(send) => {
5029                Some(send.target_capacity())
5030            }
5031            BuffersRefMut::Sizes(BufferSizes { send, receive: _ }) => Some(*send),
5032        }
5033    }
5034}
5035
5036impl<R: Buffer, S: Buffer> AccessBufferSize<R, S> for ReceiveBufferSize {
5037    fn set_buffer_size(buffers: BuffersRefMut<'_, R, S>, new_size: usize) {
5038        match buffers {
5039            BuffersRefMut::NoBuffers | BuffersRefMut::SendOnly(_) => {}
5040            BuffersRefMut::Both { recv, send: _ } | BuffersRefMut::RecvOnly(recv) => {
5041                recv.request_capacity(new_size)
5042            }
5043            BuffersRefMut::Sizes(BufferSizes { receive, send: _ }) => *receive = new_size,
5044        }
5045    }
5046
5047    fn allowed_range(settings: &TcpSettings) -> (usize, usize) {
5048        (settings.receive_buffer.min().get(), settings.receive_buffer.max().get())
5049    }
5050
5051    fn get_buffer_size(buffers: BuffersRefMut<'_, R, S>) -> Option<usize> {
5052        match buffers {
5053            BuffersRefMut::NoBuffers | BuffersRefMut::SendOnly(_) => None,
5054            BuffersRefMut::Both { recv, send: _ } | BuffersRefMut::RecvOnly(recv) => {
5055                Some(recv.target_capacity())
5056            }
5057            BuffersRefMut::Sizes(BufferSizes { receive, send: _ }) => Some(*receive),
5058        }
5059    }
5060}
5061
5062fn get_buffers_mut<I, CC, BC>(
5063    state: &mut TcpSocketState<I, CC::WeakDeviceId, BC>,
5064    converter: MaybeDualStack<CC::DualStackConverter, CC::SingleStackConverter>,
5065) -> BuffersRefMut<'_, BC::ReceiveBuffer, BC::SendBuffer>
5066where
5067    I: DualStackIpExt,
5068    CC: TcpContext<I, BC>,
5069    BC: TcpBindingsContext<CC::DeviceId>,
5070{
5071    match &mut state.socket_state {
5072        TcpSocketStateInner::Unbound(Unbound { buffer_sizes, .. })
5073        | TcpSocketStateInner::Bound(BoundState { buffer_sizes, .. })
5074        | TcpSocketStateInner::Listener(Listener { buffer_sizes, .. }) => {
5075            BuffersRefMut::Sizes(buffer_sizes)
5076        }
5077        TcpSocketStateInner::Connected { conn, .. } => {
5078            let state = match converter {
5079                MaybeDualStack::NotDualStack(converter) => {
5080                    let (conn, _addr) = converter.convert(conn);
5081                    &mut conn.state
5082                }
5083                MaybeDualStack::DualStack(converter) => match converter.convert(conn) {
5084                    EitherStack::ThisStack((conn, _addr)) => &mut conn.state,
5085                    EitherStack::OtherStack((conn, _addr)) => &mut conn.state,
5086                },
5087            };
5088            state.buffers_mut()
5089        }
5090    }
5091}
5092
5093fn set_buffer_size<
5094    Which: AccessBufferSize<BC::ReceiveBuffer, BC::SendBuffer>,
5095    I: DualStackIpExt,
5096    BC: TcpBindingsContext<CC::DeviceId>,
5097    CC: TcpContext<I, BC>,
5098>(
5099    core_ctx: &mut CC,
5100    bindings_ctx: &mut BC,
5101    id: &TcpSocketId<I, CC::WeakDeviceId, BC>,
5102    size: usize,
5103) {
5104    let (min, max) = Which::allowed_range(&*bindings_ctx.settings());
5105    let size = size.clamp(min, max);
5106    core_ctx.with_socket_mut_and_converter(id, |state, converter| {
5107        Which::set_buffer_size(get_buffers_mut::<I, CC, BC>(state, converter), size)
5108    })
5109}
5110
5111fn get_buffer_size<
5112    Which: AccessBufferSize<BC::ReceiveBuffer, BC::SendBuffer>,
5113    I: DualStackIpExt,
5114    BC: TcpBindingsContext<CC::DeviceId>,
5115    CC: TcpContext<I, BC>,
5116>(
5117    core_ctx: &mut CC,
5118    id: &TcpSocketId<I, CC::WeakDeviceId, BC>,
5119) -> Option<usize> {
5120    core_ctx.with_socket_mut_and_converter(id, |state, converter| {
5121        Which::get_buffer_size(get_buffers_mut::<I, CC, BC>(state, converter))
5122    })
5123}
5124
5125/// Error returned when failing to set the bound device for a socket.
5126#[derive(Debug, GenericOverIp, Error)]
5127#[generic_over_ip()]
5128pub enum SetDeviceError {
5129    /// The socket would conflict with another socket.
5130    #[error("cannot set bound device due to conflict with another socket")]
5131    Conflict,
5132    /// The socket would become unroutable.
5133    #[error("cannot set bound device as socket would become unroutable")]
5134    Unroutable,
5135    /// The socket has an address with a different zone.
5136    #[error("cannot set bound device as socket's address has a different zone")]
5137    ZoneChange,
5138}
5139
5140/// Possible errors for accept operation.
5141#[derive(Debug, GenericOverIp, Error)]
5142#[generic_over_ip()]
5143pub enum AcceptError {
5144    /// There is no established socket currently.
5145    #[error("would block: no currently-established socket")]
5146    WouldBlock,
5147    /// Cannot accept on this socket.
5148    #[error("this socket does not support accept")]
5149    NotSupported,
5150}
5151
5152/// Errors for the listen operation.
5153#[derive(Debug, GenericOverIp, PartialEq, Error)]
5154#[generic_over_ip()]
5155pub enum ListenError {
5156    /// There would be a conflict with another listening socket.
5157    #[error("conflict with another listening socket")]
5158    ListenerExists,
5159    /// Cannot listen on such socket.
5160    #[error("listening not supported")]
5161    NotSupported,
5162}
5163
5164/// Possible error for calling `shutdown` on a not-yet connected socket.
5165#[derive(Debug, GenericOverIp, Eq, PartialEq, Error)]
5166#[generic_over_ip()]
5167#[error("no connection")]
5168pub struct NoConnection;
5169
5170/// Error returned when attempting to set the ReuseAddress option.
5171#[derive(Debug, GenericOverIp, Error)]
5172#[generic_over_ip()]
5173pub enum SetReuseAddrError {
5174    /// Cannot share the address because it is already used.
5175    #[error("cannot share in-use address")]
5176    AddrInUse,
5177    /// Cannot set ReuseAddr on a connected socket.
5178    #[error("cannot set ReuseAddr on a connected socket")]
5179    NotSupported,
5180}
5181
5182/// Possible errors when connecting a socket.
5183#[derive(Debug, Error, GenericOverIp)]
5184#[generic_over_ip()]
5185#[cfg_attr(test, derive(PartialEq, Eq))]
5186pub enum ConnectError {
5187    /// Cannot allocate a local port for the connection.
5188    #[error("unable to allocate a port")]
5189    NoPort,
5190    /// Cannot find a route to the remote host.
5191    #[error("no route to remote host")]
5192    NoRoute,
5193    /// There was a problem with the provided address relating to its zone.
5194    #[error(transparent)]
5195    Zone(#[from] ZonedAddressError),
5196    /// There is an existing connection with the same 4-tuple.
5197    #[error("there is already a connection at the address requested")]
5198    ConnectionExists,
5199    /// Doesn't support `connect` for a listener.
5200    #[error("called connect on a listener")]
5201    Listener,
5202    /// The handshake is still going on.
5203    #[error("the handshake has already started")]
5204    Pending,
5205    /// Cannot call connect on a connection that is already established.
5206    #[error("the handshake is completed")]
5207    Completed,
5208    /// The handshake is refused by the remote host.
5209    #[error("the handshake is aborted")]
5210    Aborted,
5211    /// A connection error (ICMP error or timeout) occurred.
5212    #[error("connection error: {0}")]
5213    ConnectionError(#[from] ConnectionError),
5214}
5215
5216/// Possible errors when connecting a socket.
5217#[derive(Debug, Error, GenericOverIp, PartialEq)]
5218#[generic_over_ip()]
5219pub enum BindError {
5220    /// The socket was already bound.
5221    #[error("the socket was already bound")]
5222    AlreadyBound,
5223    /// The socket cannot bind to the local address.
5224    #[error(transparent)]
5225    LocalAddressError(#[from] LocalAddressError),
5226}
5227
5228/// Possible errors when retrieving the original destination of a socket.
5229#[derive(GenericOverIp, Debug, Error)]
5230#[generic_over_ip()]
5231pub enum OriginalDestinationError {
5232    /// Cannot retrieve original destination for an unconnected socket.
5233    #[error("cannot retrieve original destination for unconnected socket")]
5234    NotConnected,
5235    /// The socket's original destination could not be found in the connection
5236    /// tracking table.
5237    #[error("socket's original destination could not be found in connection tracking table")]
5238    NotFound,
5239    /// The socket's original destination had an unspecified address, which is
5240    /// invalid for TCP.
5241    #[error("socket's original destination address should be specified for TCP")]
5242    UnspecifiedDestinationAddr,
5243    /// The socket's original destination had an unspecified port, which is
5244    /// invalid for TCP.
5245    #[error("socket's original destination port should be specified for TCP")]
5246    UnspecifiedDestinationPort,
5247}
5248
5249/// A `GenericOverIp` wrapper for `I::DemuxSocketId`.
5250#[derive(GenericOverIp)]
5251#[generic_over_ip(I, Ip)]
5252pub struct DemuxSocketId<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes>(
5253    I::DemuxSocketId<D, BT>,
5254);
5255
5256/// A helper trait to implement dual stack demux state access for connect.
5257///
5258/// `I` gives access to demux version `I`, which should be the wire IP version.
5259trait DemuxStateAccessor<I: DualStackIpExt, CC: DeviceIdContext<AnyDevice>, BT: TcpBindingsTypes> {
5260    /// Calls the callback with access to the demux state for IP version `I`.
5261    ///
5262    /// If `cb` returns `Ok`, implementations must remove previous bound-state
5263    /// demux entries.
5264    fn update_demux_state_for_connect<
5265        O,
5266        E,
5267        F: FnOnce(
5268            &I::DemuxSocketId<CC::WeakDeviceId, BT>,
5269            &mut DemuxState<I, CC::WeakDeviceId, BT>,
5270        ) -> Result<O, E>,
5271    >(
5272        self,
5273        core_ctx: &mut CC,
5274        cb: F,
5275    ) -> Result<O, E>;
5276}
5277
5278struct SingleStackDemuxStateAccessor<
5279    'a,
5280    I: DualStackIpExt,
5281    CC: DeviceIdContext<AnyDevice>,
5282    BT: TcpBindingsTypes,
5283>(
5284    &'a I::DemuxSocketId<CC::WeakDeviceId, BT>,
5285    Option<ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, CC::WeakDeviceId>>,
5286);
5287
5288impl<'a, I, CC, BT> DemuxStateAccessor<I, CC, BT> for SingleStackDemuxStateAccessor<'a, I, CC, BT>
5289where
5290    I: DualStackIpExt,
5291    BT: TcpBindingsTypes,
5292    CC: DeviceIdContext<AnyDevice> + TcpDemuxContext<I, CC::WeakDeviceId, BT>,
5293{
5294    fn update_demux_state_for_connect<
5295        O,
5296        E,
5297        F: FnOnce(
5298            &I::DemuxSocketId<CC::WeakDeviceId, BT>,
5299            &mut DemuxState<I, CC::WeakDeviceId, BT>,
5300        ) -> Result<O, E>,
5301    >(
5302        self,
5303        core_ctx: &mut CC,
5304        cb: F,
5305    ) -> Result<O, E> {
5306        core_ctx.with_demux_mut(|demux| {
5307            let Self(demux_id, listener_addr) = self;
5308            let output = cb(demux_id, demux)?;
5309
5310            // If update is successful we must remove the listener address
5311            // from the demux.
5312
5313            if let Some(listener_addr) = listener_addr {
5314                demux
5315                    .socketmap
5316                    .listeners_mut()
5317                    .remove(demux_id, &listener_addr)
5318                    .expect("failed to remove a bound socket");
5319            }
5320            Ok(output)
5321        })
5322    }
5323}
5324
5325struct DualStackDemuxStateAccessor<
5326    'a,
5327    I: DualStackIpExt,
5328    CC: DeviceIdContext<AnyDevice>,
5329    BT: TcpBindingsTypes,
5330>(
5331    &'a TcpSocketId<I, CC::WeakDeviceId, BT>,
5332    DualStackTuple<I, Option<ListenerAddr<ListenerIpAddr<I::Addr, NonZeroU16>, CC::WeakDeviceId>>>,
5333);
5334
5335impl<'a, SockI, WireI, CC, BT> DemuxStateAccessor<WireI, CC, BT>
5336    for DualStackDemuxStateAccessor<'a, SockI, CC, BT>
5337where
5338    SockI: DualStackIpExt,
5339    WireI: DualStackIpExt,
5340    BT: TcpBindingsTypes,
5341    CC: DeviceIdContext<AnyDevice>
5342        + TcpDualStackContext<SockI, CC::WeakDeviceId, BT>
5343        + TcpDemuxContext<WireI, CC::WeakDeviceId, BT>
5344        + TcpDemuxContext<WireI::OtherVersion, CC::WeakDeviceId, BT>,
5345{
5346    fn update_demux_state_for_connect<
5347        O,
5348        E,
5349        F: FnOnce(
5350            &WireI::DemuxSocketId<CC::WeakDeviceId, BT>,
5351            &mut DemuxState<WireI, CC::WeakDeviceId, BT>,
5352        ) -> Result<O, E>,
5353    >(
5354        self,
5355        core_ctx: &mut CC,
5356        cb: F,
5357    ) -> Result<O, E> {
5358        let Self(id, local_addr) = self;
5359        let (DemuxSocketId(wire_id), DemuxSocketId(other_id)) =
5360            core_ctx.dual_stack_demux_id(id.clone()).cast::<WireI>().into_inner();
5361        let (wire_local_addr, other_local_addr) = local_addr.cast::<WireI>().into_inner();
5362        let output = core_ctx.with_demux_mut(|wire_demux: &mut DemuxState<WireI, _, _>| {
5363            let output = cb(&wire_id, wire_demux)?;
5364
5365            // On success we must remove our local address.
5366            if let Some(wire_local_addr) = wire_local_addr {
5367                wire_demux
5368                    .socketmap
5369                    .listeners_mut()
5370                    .remove(&wire_id, &wire_local_addr)
5371                    .expect("failed to remove a bound socket");
5372            }
5373            Ok(output)
5374        })?;
5375
5376        // If the operation succeeded and we're bound on the other stack then we
5377        // must clean that up as well.
5378        if let Some(other_local_addr) = other_local_addr {
5379            core_ctx.with_demux_mut(|other_demux: &mut DemuxState<WireI::OtherVersion, _, _>| {
5380                other_demux
5381                    .socketmap
5382                    .listeners_mut()
5383                    .remove(&other_id, &other_local_addr)
5384                    .expect("failed to remove a bound socket");
5385            });
5386        }
5387
5388        Ok(output)
5389    }
5390}
5391
5392fn connect_inner<CC, BC, SockI, WireI, Demux>(
5393    core_ctx: &mut CC,
5394    bindings_ctx: &mut BC,
5395    sock_id: &TcpSocketId<SockI, CC::WeakDeviceId, BC>,
5396    isn: &IsnGenerator<BC::Instant>,
5397    timestamp_offset: &TimestampOffsetGenerator<BC::Instant>,
5398    listener_addr: Option<ListenerAddr<ListenerIpAddr<WireI::Addr, NonZeroU16>, CC::WeakDeviceId>>,
5399    remote_ip: ZonedAddr<SocketIpAddr<WireI::Addr>, CC::DeviceId>,
5400    remote_port: NonZeroU16,
5401    active_open: TakeableRef<'_, BC::ListenerNotifierOrProvidedBuffers>,
5402    buffer_sizes: BufferSizes,
5403    socket_options: &SocketOptions,
5404    sharing: SharingState,
5405    demux: Demux,
5406    convert_back_op: impl FnOnce(
5407        Connection<SockI, WireI, CC::WeakDeviceId, BC>,
5408        ConnAddr<ConnIpAddr<WireI::Addr, NonZeroU16, NonZeroU16>, CC::WeakDeviceId>,
5409    ) -> SockI::ConnectionAndAddr<CC::WeakDeviceId, BC>,
5410    convert_timer: impl FnOnce(WeakTcpSocketId<SockI, CC::WeakDeviceId, BC>) -> BC::DispatchId,
5411) -> Result<TcpSocketStateInner<SockI, CC::WeakDeviceId, BC>, ConnectError>
5412where
5413    SockI: DualStackIpExt,
5414    WireI: DualStackIpExt,
5415    BC: TcpBindingsContext<CC::DeviceId>,
5416    CC: TransportIpContext<WireI, BC>
5417        + DeviceIpSocketHandler<WireI, BC>
5418        + TcpSocketContext<SockI, CC::WeakDeviceId, BC>,
5419    Demux: DemuxStateAccessor<WireI, CC, BC>,
5420{
5421    let (local_ip, bound_device, local_port) = match listener_addr {
5422        Some(ListenerAddr { ip: ListenerIpAddr { addr, identifier }, device }) => {
5423            (addr.and_then(IpDeviceAddr::new_from_socket_ip_addr), device, Some(identifier))
5424        }
5425        None => (None, None, None),
5426    };
5427    let (remote_ip, device) = remote_ip.resolve_addr_with_device(bound_device)?;
5428
5429    // TCP sockets cannot connect to multicast addresses so error out early.
5430    // Per RFC 9293 (https://datatracker.ietf.org/doc/html/rfc9293#name-open):
5431    //   A TCP implementation MUST reject as an error a local OPEN call for an invalid remote
5432    //   IP address (e.g., a broadcast or multicast address) (MUST-46).
5433    if remote_ip.addr().is_multicast()
5434        || WireI::map_ip_in(remote_ip.addr(), |ip| ip.is_limited_broadcast(), |_| false)
5435    {
5436        return Err(ConnectError::NoRoute);
5437    }
5438
5439    let ip_sock = core_ctx
5440        .new_ip_socket(
5441            bindings_ctx,
5442            IpSocketArgs {
5443                device: device.as_ref().map(|d| d.as_ref()),
5444                local_ip,
5445                remote_ip,
5446                proto: IpProto::Tcp.into(),
5447                options: &socket_options.ip_options,
5448            },
5449        )
5450        .map_err(|err| match err {
5451            IpSockCreationError::Route(_) => ConnectError::NoRoute,
5452        })?;
5453
5454    let device_mms = core_ctx.get_mms(bindings_ctx, &ip_sock, &socket_options.ip_options).map_err(
5455        |_err: ip::socket::MmsError| {
5456            // We either cannot find the route, or the device for
5457            // the route cannot handle the smallest TCP/IP packet.
5458            ConnectError::NoRoute
5459        },
5460    )?;
5461
5462    let conn_addr =
5463        demux.update_demux_state_for_connect(core_ctx, |demux_id, DemuxState { socketmap }| {
5464            let local_port = local_port.map_or_else(
5465                // NB: Pass the remote port into the allocator to avoid
5466                // unexpected self-connections when allocating a local port.
5467                // This could be optimized by checking if the IP socket has
5468                // resolved to local delivery, but excluding a single port
5469                // should be enough here and avoids adding more dependencies.
5470                || match netstack3_base::simple_randomized_port_alloc(
5471                    &mut bindings_ctx.rng(),
5472                    &Some(SocketIpAddr::from(*ip_sock.local_ip())),
5473                    &TcpPortAlloc(socketmap),
5474                    &Some(remote_port),
5475                ) {
5476                    Some(port) => {
5477                        Ok(NonZeroU16::new(port).expect("ephemeral ports must be non-zero"))
5478                    }
5479                    None => Err(ConnectError::NoPort),
5480                },
5481                Ok,
5482            )?;
5483
5484            let conn_addr = ConnAddr {
5485                ip: ConnIpAddr {
5486                    local: (SocketIpAddr::from(*ip_sock.local_ip()), local_port),
5487                    remote: (*ip_sock.remote_ip(), remote_port),
5488                },
5489                device: ip_sock.device().cloned(),
5490            };
5491
5492            let _entry = socketmap
5493                .conns_mut()
5494                .try_insert(conn_addr.clone(), sharing, demux_id.clone())
5495                .map_err(|err| match err {
5496                    // The connection will conflict with an existing one.
5497                    InsertError::Exists | InsertError::ShadowerExists => {
5498                        ConnectError::ConnectionExists
5499                    }
5500                    // Connections don't conflict with listeners, and we should
5501                    // not observe the following errors.
5502                    InsertError::ShadowAddrExists | InsertError::IndirectConflict => {
5503                        panic!("failed to insert connection: {:?}", err)
5504                    }
5505                })?;
5506            Ok::<_, ConnectError>(conn_addr)
5507        })?;
5508
5509    let isn = isn.generate::<SocketIpAddr<WireI::Addr>, NonZeroU16>(
5510        bindings_ctx.now(),
5511        conn_addr.ip.local,
5512        conn_addr.ip.remote,
5513    );
5514    let timestamp_offset = timestamp_offset.generate::<SocketIpAddr<WireI::Addr>, NonZeroU16>(
5515        bindings_ctx.now(),
5516        conn_addr.ip.local,
5517        conn_addr.ip.remote,
5518    );
5519
5520    let now = bindings_ctx.now();
5521    let mss = Mss::from_mms(device_mms).ok_or(ConnectError::NoRoute)?;
5522
5523    // No more errors can occur after here, because we're taking active_open
5524    // buffers out. Use a closure to guard against bad evolution.
5525    let active_open = active_open.take();
5526    Ok((move || {
5527        let (syn_sent, syn) = Closed::<Initial>::connect(
5528            isn,
5529            timestamp_offset,
5530            now,
5531            active_open,
5532            buffer_sizes,
5533            mss,
5534            Mss::default::<WireI>(),
5535            socket_options,
5536        );
5537        let state = State::<_, BC::ReceiveBuffer, BC::SendBuffer, _>::SynSent(syn_sent);
5538        let poll_send_at = state.poll_send_at().expect("no retrans timer");
5539
5540        // Send first SYN packet.
5541        send_tcp_segment(
5542            core_ctx,
5543            bindings_ctx,
5544            Some(&sock_id),
5545            Some(&ip_sock),
5546            conn_addr.ip,
5547            syn.into_empty(),
5548            &socket_options.ip_options,
5549        );
5550
5551        let mut timer = bindings_ctx.new_timer(convert_timer(sock_id.downgrade()));
5552        assert_eq!(bindings_ctx.schedule_timer_instant(poll_send_at, &mut timer), None);
5553
5554        let conn = convert_back_op(
5555            Connection {
5556                accept_queue: None,
5557                state,
5558                ip_sock,
5559                defunct: false,
5560                soft_error: None,
5561                handshake_status: HandshakeStatus::Pending,
5562            },
5563            conn_addr,
5564        );
5565        core_ctx.increment_both(sock_id, |counters| &counters.active_connection_openings);
5566        TcpSocketStateInner::Connected { conn, timer }
5567    })())
5568}
5569
5570/// Information about a socket.
5571#[derive(Clone, Debug, Eq, PartialEq, GenericOverIp)]
5572#[generic_over_ip(A, IpAddress)]
5573pub enum SocketInfo<A: IpAddress, D> {
5574    /// Unbound socket info.
5575    Unbound(UnboundInfo<D>),
5576    /// Bound or listener socket info.
5577    Bound(BoundInfo<A, D>),
5578    /// Connection socket info.
5579    Connection(ConnectionInfo<A, D>),
5580}
5581
5582/// Information about an unbound socket.
5583#[derive(Clone, Debug, Eq, PartialEq, GenericOverIp)]
5584#[generic_over_ip()]
5585pub struct UnboundInfo<D> {
5586    /// The device the socket will be bound to.
5587    pub device: Option<D>,
5588}
5589
5590/// Information about a bound socket's address.
5591#[derive(Clone, Debug, Eq, PartialEq, GenericOverIp)]
5592#[generic_over_ip(A, IpAddress)]
5593pub struct BoundInfo<A: IpAddress, D> {
5594    /// The IP address the socket is bound to, or `None` for all local IPs.
5595    pub addr: Option<ZonedAddr<SpecifiedAddr<A>, D>>,
5596    /// The port number the socket is bound to.
5597    pub port: NonZeroU16,
5598    /// The device the socket is bound to.
5599    pub device: Option<D>,
5600}
5601
5602/// Information about a connected socket's address.
5603#[derive(Clone, Debug, Eq, PartialEq, GenericOverIp)]
5604#[generic_over_ip(A, IpAddress)]
5605pub struct ConnectionInfo<A: IpAddress, D> {
5606    /// The local address the socket is bound to.
5607    pub local_addr: SocketAddr<A, D>,
5608    /// The remote address the socket is connected to.
5609    pub remote_addr: SocketAddr<A, D>,
5610    /// The device the socket is bound to.
5611    pub device: Option<D>,
5612}
5613
5614impl<D: Clone, Extra> From<&'_ Unbound<D, Extra>> for UnboundInfo<D> {
5615    fn from(unbound: &Unbound<D, Extra>) -> Self {
5616        Self { device: unbound.bound_device.clone() }
5617    }
5618}
5619
5620fn maybe_zoned<A: IpAddress, D: Clone>(
5621    ip: SpecifiedAddr<A>,
5622    device: &Option<D>,
5623) -> ZonedAddr<SpecifiedAddr<A>, D> {
5624    device
5625        .as_ref()
5626        .and_then(|device| {
5627            AddrAndZone::new(ip, device).map(|az| ZonedAddr::Zoned(az.map_zone(Clone::clone)))
5628        })
5629        .unwrap_or(ZonedAddr::Unzoned(ip))
5630}
5631
5632impl<A: IpAddress, D: Clone> From<ListenerAddr<ListenerIpAddr<A, NonZeroU16>, D>>
5633    for BoundInfo<A, D>
5634{
5635    fn from(addr: ListenerAddr<ListenerIpAddr<A, NonZeroU16>, D>) -> Self {
5636        let ListenerAddr { ip: ListenerIpAddr { addr, identifier }, device } = addr;
5637        let addr = addr.map(|ip| maybe_zoned(ip.into(), &device));
5638        BoundInfo { addr, port: identifier, device }
5639    }
5640}
5641
5642impl<A: IpAddress, D: Clone> From<ConnAddr<ConnIpAddr<A, NonZeroU16, NonZeroU16>, D>>
5643    for ConnectionInfo<A, D>
5644{
5645    fn from(addr: ConnAddr<ConnIpAddr<A, NonZeroU16, NonZeroU16>, D>) -> Self {
5646        let ConnAddr { ip: ConnIpAddr { local, remote }, device } = addr;
5647        let convert = |(ip, port): (SocketIpAddr<A>, NonZeroU16)| SocketAddr {
5648            ip: maybe_zoned(ip.into(), &device),
5649            port,
5650        };
5651        Self { local_addr: convert(local), remote_addr: convert(remote), device }
5652    }
5653}
5654
5655impl<CC, BC> HandleableTimer<CC, BC> for TcpTimerId<CC::WeakDeviceId, BC>
5656where
5657    BC: TcpBindingsContext<CC::DeviceId>,
5658    CC: TcpContext<Ipv4, BC> + TcpContext<Ipv6, BC>,
5659{
5660    fn handle(self, core_ctx: &mut CC, bindings_ctx: &mut BC, _: BC::UniqueTimerId) {
5661        let ctx_pair = CtxPair { core_ctx, bindings_ctx };
5662        match self {
5663            TcpTimerId::V4(conn_id) => TcpApi::new(ctx_pair).handle_timer(conn_id),
5664            TcpTimerId::V6(conn_id) => TcpApi::new(ctx_pair).handle_timer(conn_id),
5665        }
5666    }
5667}
5668
5669/// Send the given TCP Segment.
5670///
5671/// A centralized send path for TCP segments that increments counters and logs
5672/// errors.
5673///
5674/// When `ip_sock` is some, it is used to send the segment, otherwise, one is
5675/// constructed on demand to send a oneshot segment.
5676fn send_tcp_segment<'a, WireI, SockI, CC, BC, D>(
5677    core_ctx: &mut CC,
5678    bindings_ctx: &mut BC,
5679    socket_id: Option<&TcpSocketId<SockI, D, BC>>,
5680    ip_sock: Option<&IpSock<WireI, D>>,
5681    conn_addr: ConnIpAddr<WireI::Addr, NonZeroU16, NonZeroU16>,
5682    segment: Segment<<BC::SendBuffer as SendBuffer>::Payload<'a>>,
5683    ip_sock_options: &TcpIpSockOptions,
5684) where
5685    WireI: IpExt + FilterIpExt,
5686    SockI: IpExt + DualStackIpExt,
5687    CC: TcpSocketContext<SockI, D, BC>
5688        + IpSocketHandler<WireI, BC, DeviceId = D::Strong, WeakDeviceId = D>,
5689    BC: TcpBindingsTypes,
5690    D: WeakDeviceIdentifier,
5691{
5692    // NB: TCP does not use tx metadata to enforce send buffer. The TCP
5693    // application buffers only open send buffer space once the data is
5694    // acknowledged by the peer. That lives entirely in the TCP module and we
5695    // don't need to track segments sitting in device queues.
5696    let tx_metadata: BC::TxMetadata = match socket_id {
5697        Some(socket_id) => {
5698            core_ctx.convert_tx_meta(TcpSocketTxMetadata::new(socket_id.downgrade()))
5699        }
5700        None => Default::default(),
5701    };
5702
5703    let (header, data) = segment.into_parts();
5704    let control = header.control;
5705    let result = match ip_sock {
5706        Some(ip_sock) => {
5707            let body = tcp_serialize_segment(&header, data, conn_addr);
5708            core_ctx
5709                .send_ip_packet(bindings_ctx, ip_sock, body, ip_sock_options, tx_metadata)
5710                .map_err(|err| IpSockCreateAndSendError::Send(err))
5711        }
5712        None => {
5713            let ConnIpAddr { local: (local_ip, _), remote: (remote_ip, _) } = conn_addr;
5714            core_ctx.send_oneshot_ip_packet(
5715                bindings_ctx,
5716                IpSocketArgs {
5717                    device: None,
5718                    local_ip: IpDeviceAddr::new_from_socket_ip_addr(local_ip),
5719                    remote_ip,
5720                    proto: IpProto::Tcp.into(),
5721                    options: ip_sock_options,
5722                },
5723                tx_metadata,
5724                |_addr| tcp_serialize_segment(&header, data, conn_addr),
5725            )
5726        }
5727    };
5728    match result {
5729        Ok(()) => {
5730            counters::increment_counter_with_optional_socket_id(core_ctx, socket_id, |counters| {
5731                &counters.segments_sent
5732            });
5733            if let Some(control) = control {
5734                counters::increment_counter_with_optional_socket_id(
5735                    core_ctx,
5736                    socket_id,
5737                    |counters| match control {
5738                        Control::RST => &counters.resets_sent,
5739                        Control::SYN => &counters.syns_sent,
5740                        Control::FIN => &counters.fins_sent,
5741                    },
5742                )
5743            }
5744        }
5745        Err(err) => {
5746            counters::increment_counter_with_optional_socket_id(core_ctx, socket_id, |counters| {
5747                &counters.segment_send_errors
5748            });
5749            match socket_id {
5750                Some(socket_id) => debug!("{:?}: failed to send segment: {:?}", socket_id, err),
5751                None => debug!("TCP: failed to send segment: {:?}", err),
5752            }
5753        }
5754    }
5755}
5756
5757impl<I, C> TcpApi<I, C>
5758where
5759    I: DualStackIpExt,
5760    C: ContextPair,
5761    C::CoreContext: TcpContext<I, C::BindingsContext>,
5762    C::BindingsContext: TcpBindingsContext<
5763        <<C as ContextPair>::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId,
5764    >,
5765{
5766    /// Gets detailed diagnostic information about the TCP socket.
5767    pub fn get_tcp_info(
5768        &mut self,
5769        id: &TcpApiSocketId<I, C>,
5770    ) -> TcpSocketInfo<<C::BindingsContext as InstantBindingsTypes>::Instant> {
5771        self.core_ctx().with_socket(id, |socket_state| socket_state.tcp_info(id.counters()))
5772    }
5773}
5774
5775#[cfg(test)]
5776mod tests {
5777    use alloc::rc::Rc;
5778    use alloc::string::String;
5779    use alloc::sync::Arc;
5780    use alloc::vec::Vec;
5781    use alloc::{format, vec};
5782    use core::cell::RefCell;
5783    use core::num::NonZeroU16;
5784    use core::time::Duration;
5785    use core::u16;
5786
5787    use ip_test_macro::ip_test;
5788    use net_declare::net_ip_v6;
5789    use net_types::ip::{Ip, IpAddr, IpVersion, Ipv4, Ipv4SourceAddr, Ipv6, Ipv6SourceAddr, Mtu};
5790    use net_types::{LinkLocalAddr, Witness};
5791    use netstack3_base::sync::{DynDebugReferences, Mutex};
5792    use netstack3_base::testutil::{
5793        AlwaysDefaultsSettingsContext, FakeAtomicInstant, FakeCoreCtx, FakeCryptoRng, FakeDeviceId,
5794        FakeInstant, FakeNetwork, FakeNetworkSpec, FakeStrongDeviceId, FakeTimerCtx, FakeTimerId,
5795        FakeTxMetadata, FakeWeakDeviceId, InstantAndData, MultipleDevicesId, PendingFrameData,
5796        StepResult, TestIpExt, WithFakeFrameContext, WithFakeTimerContext, new_rng,
5797        run_with_many_seeds, set_logger_for_test,
5798    };
5799    use netstack3_base::{
5800        ContextProvider, CounterCollection, CounterContext, IcmpIpExt, Icmpv4ErrorCode,
5801        Icmpv6ErrorCode, Instant as _, InstantContext, LinkDevice, Mark, MarkDomain,
5802        MatcherBindingsTypes, Mms, ReferenceNotifiers, ResourceCounterContext,
5803        StrongDeviceIdentifier, Uninstantiable, UninstantiableWrapper,
5804    };
5805    use netstack3_filter::testutil::NoOpSocketOpsFilter;
5806    use netstack3_filter::{SocketOpsFilter, TransportPacketSerializer, Tuple};
5807    use netstack3_ip::device::IpDeviceStateIpExt;
5808    use netstack3_ip::nud::LinkResolutionContext;
5809    use netstack3_ip::nud::testutil::FakeLinkResolutionNotifier;
5810    use netstack3_ip::socket::testutil::{FakeDeviceConfig, FakeDualStackIpSocketCtx};
5811    use netstack3_ip::socket::{IpSockSendError, MmsError, RouteResolutionOptions, SendOptions};
5812    use netstack3_ip::testutil::DualStackSendIpPacketMeta;
5813    use netstack3_ip::{
5814        BaseTransportIpContext, HopLimits, IpTransportContext, LocalDeliveryPacketInfo,
5815    };
5816    use packet::{Buf, BufferMut, PacketBuilder as _, ParseBuffer as _, Serializer as _};
5817    use packet_formats::icmp::{
5818        IcmpDestUnreachable, Icmpv4DestUnreachableCode, Icmpv4ParameterProblemCode,
5819        Icmpv4TimeExceededCode, Icmpv6DestUnreachableCode, Icmpv6ParameterProblemCode,
5820        Icmpv6TimeExceededCode,
5821    };
5822    use packet_formats::tcp::{TcpParseArgs, TcpSegment, TcpSegmentBuilder};
5823    use rand::Rng as _;
5824    use test_case::test_case;
5825    use test_util::assert_gt;
5826
5827    use super::*;
5828    use crate::internal::base::{ConnectionError, DEFAULT_FIN_WAIT2_TIMEOUT};
5829    use crate::internal::buffer::BufferLimits;
5830    use crate::internal::buffer::testutil::{
5831        ClientBuffers, ProvidedBuffers, RingBuffer, TestSendBuffer, WriteBackClientBuffers,
5832    };
5833    use crate::internal::congestion::CongestionWindow;
5834    use crate::internal::counters::TcpCountersWithoutSocket;
5835    use crate::internal::counters::testutil::{
5836        CounterExpectations, CounterExpectationsWithoutSocket,
5837    };
5838    use crate::internal::state::{Established, MSL, TimeWait};
5839
5840    pub(crate) trait TcpTestIpExt:
5841        DualStackIpExt + TestIpExt + IpDeviceStateIpExt + DualStackIpExt
5842    {
5843        type SingleStackConverter: SingleStackConverter<Self, FakeWeakDeviceId<FakeDeviceId>, TcpBindingsCtx<FakeDeviceId>>;
5844        type DualStackConverter: DualStackConverter<Self, FakeWeakDeviceId<FakeDeviceId>, TcpBindingsCtx<FakeDeviceId>>;
5845        fn recv_src_addr(addr: Self::Addr) -> Self::RecvSrcAddr;
5846
5847        fn converter() -> MaybeDualStack<Self::DualStackConverter, Self::SingleStackConverter>;
5848    }
5849
5850    /// This trait anchors the timer DispatchId for our context implementations
5851    /// that require a core converter.
5852    ///
5853    /// This is required because we implement the traits on [`TcpCoreCtx`]
5854    /// abstracting away the bindings types, even though they're always
5855    /// [`TcpBindingsCtx`].
5856    trait TcpTestBindingsTypes<D: StrongDeviceIdentifier>:
5857        TcpBindingsTypes<DispatchId = TcpTimerId<D::Weak, Self>> + Sized
5858    {
5859    }
5860
5861    impl<D, BT> TcpTestBindingsTypes<D> for BT
5862    where
5863        BT: TcpBindingsTypes<DispatchId = TcpTimerId<D::Weak, Self>> + Sized,
5864        D: StrongDeviceIdentifier,
5865    {
5866    }
5867
5868    struct FakeTcpState<I: TcpTestIpExt, D: FakeStrongDeviceId, BT: TcpBindingsTypes> {
5869        isn_generator: Rc<IsnGenerator<BT::Instant>>,
5870        timestamp_offset_generator: Rc<TimestampOffsetGenerator<BT::Instant>>,
5871        demux: Rc<RefCell<DemuxState<I, D::Weak, BT>>>,
5872        // Always destroy all sockets last so the strong references in the demux
5873        // are gone.
5874        all_sockets: TcpSocketSet<I, D::Weak, BT>,
5875        counters_with_socket: TcpCountersWithSocket<I>,
5876        counters_without_socket: TcpCountersWithoutSocket<I>,
5877    }
5878
5879    impl<I, D, BT> Default for FakeTcpState<I, D, BT>
5880    where
5881        I: TcpTestIpExt,
5882        D: FakeStrongDeviceId,
5883        BT: TcpBindingsTypes,
5884        BT::Instant: Default,
5885    {
5886        fn default() -> Self {
5887            Self {
5888                isn_generator: Default::default(),
5889                timestamp_offset_generator: Default::default(),
5890                all_sockets: Default::default(),
5891                demux: Rc::new(RefCell::new(DemuxState { socketmap: Default::default() })),
5892                counters_with_socket: Default::default(),
5893                counters_without_socket: Default::default(),
5894            }
5895        }
5896    }
5897
5898    struct FakeDualStackTcpState<D: FakeStrongDeviceId, BT: TcpBindingsTypes> {
5899        v4: FakeTcpState<Ipv4, D, BT>,
5900        v6: FakeTcpState<Ipv6, D, BT>,
5901    }
5902
5903    impl<D, BT> Default for FakeDualStackTcpState<D, BT>
5904    where
5905        D: FakeStrongDeviceId,
5906        BT: TcpBindingsTypes,
5907        BT::Instant: Default,
5908    {
5909        fn default() -> Self {
5910            Self { v4: Default::default(), v6: Default::default() }
5911        }
5912    }
5913
5914    type InnerCoreCtx<D> =
5915        FakeCoreCtx<FakeDualStackIpSocketCtx<D>, DualStackSendIpPacketMeta<D>, D>;
5916
5917    pub(crate) struct TcpCoreCtx<D: FakeStrongDeviceId, BT: TcpBindingsTypes> {
5918        tcp: FakeDualStackTcpState<D, BT>,
5919        ip_socket_ctx: InnerCoreCtx<D>,
5920        // Marks to attach for incoming packets.
5921        recv_packet_marks: netstack3_base::Marks,
5922    }
5923
5924    impl<D: FakeStrongDeviceId, BT: TcpBindingsTypes> ContextProvider for TcpCoreCtx<D, BT> {
5925        type Context = Self;
5926
5927        fn context(&mut self) -> &mut Self::Context {
5928            self
5929        }
5930    }
5931
5932    impl<D, BT> DeviceIdContext<AnyDevice> for TcpCoreCtx<D, BT>
5933    where
5934        D: FakeStrongDeviceId,
5935        BT: TcpBindingsTypes,
5936    {
5937        type DeviceId = D;
5938        type WeakDeviceId = FakeWeakDeviceId<D>;
5939    }
5940
5941    pub(crate) type TcpCtx<D> = CtxPair<TcpCoreCtx<D, TcpBindingsCtx<D>>, TcpBindingsCtx<D>>;
5942
5943    pub(crate) struct FakeTcpNetworkSpec<D: FakeStrongDeviceId>(PhantomData<D>, Never);
5944    impl<D: FakeStrongDeviceId> FakeNetworkSpec for FakeTcpNetworkSpec<D> {
5945        type Context = TcpCtx<D>;
5946        type TimerId = TcpTimerId<D::Weak, TcpBindingsCtx<D>>;
5947        type SendMeta = DualStackSendIpPacketMeta<D>;
5948        type RecvMeta = DualStackSendIpPacketMeta<D>;
5949        fn handle_frame(ctx: &mut Self::Context, meta: Self::RecvMeta, buffer: Buf<Vec<u8>>) {
5950            let TcpCtx { core_ctx, bindings_ctx } = ctx;
5951            match meta {
5952                DualStackSendIpPacketMeta::V4(meta) => {
5953                    let early_demux_socket =
5954                        <TcpIpTransportContext as IpTransportContext<Ipv4, _, _>>::early_demux(
5955                            core_ctx,
5956                            &meta.device,
5957                            *meta.src_ip,
5958                            *meta.dst_ip,
5959                            buffer.as_ref(),
5960                        );
5961                    <TcpIpTransportContext as IpTransportContext<Ipv4, _, _>>::receive_ip_packet(
5962                        core_ctx,
5963                        bindings_ctx,
5964                        &meta.device,
5965                        Ipv4::recv_src_addr(*meta.src_ip),
5966                        meta.dst_ip,
5967                        buffer,
5968                        &LocalDeliveryPacketInfo {
5969                            marks: core_ctx.recv_packet_marks,
5970                            ..Default::default()
5971                        },
5972                        early_demux_socket,
5973                    )
5974                    .expect("failed to deliver bytes");
5975                }
5976                DualStackSendIpPacketMeta::V6(meta) => {
5977                    let early_demux_socket =
5978                        <TcpIpTransportContext as IpTransportContext<Ipv6, _, _>>::early_demux(
5979                            core_ctx,
5980                            &meta.device,
5981                            *meta.src_ip,
5982                            *meta.dst_ip,
5983                            buffer.as_ref(),
5984                        );
5985                    <TcpIpTransportContext as IpTransportContext<Ipv6, _, _>>::receive_ip_packet(
5986                        core_ctx,
5987                        bindings_ctx,
5988                        &meta.device,
5989                        Ipv6::recv_src_addr(*meta.src_ip),
5990                        meta.dst_ip,
5991                        buffer,
5992                        &LocalDeliveryPacketInfo {
5993                            marks: core_ctx.recv_packet_marks,
5994                            ..Default::default()
5995                        },
5996                        early_demux_socket,
5997                    )
5998                    .expect("failed to deliver bytes");
5999                }
6000            }
6001        }
6002        fn handle_timer(ctx: &mut Self::Context, dispatch: Self::TimerId, _: FakeTimerId) {
6003            match dispatch {
6004                TcpTimerId::V4(id) => ctx.tcp_api().handle_timer(id),
6005                TcpTimerId::V6(id) => ctx.tcp_api().handle_timer(id),
6006            }
6007        }
6008        fn process_queues(_ctx: &mut Self::Context) -> bool {
6009            false
6010        }
6011        fn fake_frames(ctx: &mut Self::Context) -> &mut impl WithFakeFrameContext<Self::SendMeta> {
6012            &mut ctx.core_ctx.ip_socket_ctx.frames
6013        }
6014    }
6015
6016    impl<D: FakeStrongDeviceId> WithFakeTimerContext<TcpTimerId<D::Weak, TcpBindingsCtx<D>>>
6017        for TcpCtx<D>
6018    {
6019        fn with_fake_timer_ctx<
6020            O,
6021            F: FnOnce(&FakeTimerCtx<TcpTimerId<D::Weak, TcpBindingsCtx<D>>>) -> O,
6022        >(
6023            &self,
6024            f: F,
6025        ) -> O {
6026            let Self { core_ctx: _, bindings_ctx } = self;
6027            f(&bindings_ctx.timers)
6028        }
6029
6030        fn with_fake_timer_ctx_mut<
6031            O,
6032            F: FnOnce(&mut FakeTimerCtx<TcpTimerId<D::Weak, TcpBindingsCtx<D>>>) -> O,
6033        >(
6034            &mut self,
6035            f: F,
6036        ) -> O {
6037            let Self { core_ctx: _, bindings_ctx } = self;
6038            f(&mut bindings_ctx.timers)
6039        }
6040    }
6041
6042    #[derive(Derivative)]
6043    #[derivative(Default(bound = ""))]
6044    pub(crate) struct TcpBindingsCtx<D: FakeStrongDeviceId> {
6045        rng: FakeCryptoRng,
6046        timers: FakeTimerCtx<TcpTimerId<D::Weak, Self>>,
6047    }
6048
6049    impl<D: FakeStrongDeviceId> ContextProvider for TcpBindingsCtx<D> {
6050        type Context = Self;
6051        fn context(&mut self) -> &mut Self::Context {
6052            self
6053        }
6054    }
6055
6056    impl<D: LinkDevice + FakeStrongDeviceId> LinkResolutionContext<D> for TcpBindingsCtx<D> {
6057        type Notifier = FakeLinkResolutionNotifier<D>;
6058    }
6059
6060    /// Delegate implementation to internal thing.
6061    impl<D: FakeStrongDeviceId> TimerBindingsTypes for TcpBindingsCtx<D> {
6062        type Timer = <FakeTimerCtx<TcpTimerId<D::Weak, Self>> as TimerBindingsTypes>::Timer;
6063        type DispatchId =
6064            <FakeTimerCtx<TcpTimerId<D::Weak, Self>> as TimerBindingsTypes>::DispatchId;
6065        type UniqueTimerId =
6066            <FakeTimerCtx<TcpTimerId<D::Weak, Self>> as TimerBindingsTypes>::UniqueTimerId;
6067    }
6068
6069    /// Delegate implementation to internal thing.
6070    impl<D: FakeStrongDeviceId> InstantBindingsTypes for TcpBindingsCtx<D> {
6071        type Instant = FakeInstant;
6072        type AtomicInstant = FakeAtomicInstant;
6073    }
6074
6075    impl<D: FakeStrongDeviceId> SocketOpsFilterBindingContext<D> for TcpBindingsCtx<D> {
6076        fn socket_ops_filter(&self) -> impl SocketOpsFilter<D> {
6077            NoOpSocketOpsFilter
6078        }
6079    }
6080
6081    /// Delegate implementation to internal thing.
6082    impl<D: FakeStrongDeviceId> InstantContext for TcpBindingsCtx<D> {
6083        fn now(&self) -> FakeInstant {
6084            self.timers.now()
6085        }
6086    }
6087
6088    /// Delegate implementation to internal thing.
6089    impl<D: FakeStrongDeviceId> TimerContext for TcpBindingsCtx<D> {
6090        fn new_timer(&mut self, id: Self::DispatchId) -> Self::Timer {
6091            self.timers.new_timer(id)
6092        }
6093
6094        fn schedule_timer_instant(
6095            &mut self,
6096            time: Self::Instant,
6097            timer: &mut Self::Timer,
6098        ) -> Option<Self::Instant> {
6099            self.timers.schedule_timer_instant(time, timer)
6100        }
6101
6102        fn cancel_timer(&mut self, timer: &mut Self::Timer) -> Option<Self::Instant> {
6103            self.timers.cancel_timer(timer)
6104        }
6105
6106        fn scheduled_instant(&self, timer: &mut Self::Timer) -> Option<Self::Instant> {
6107            self.timers.scheduled_instant(timer)
6108        }
6109
6110        fn unique_timer_id(&self, timer: &Self::Timer) -> Self::UniqueTimerId {
6111            self.timers.unique_timer_id(timer)
6112        }
6113    }
6114
6115    impl<D: FakeStrongDeviceId> ReferenceNotifiers for TcpBindingsCtx<D> {
6116        type ReferenceReceiver<T: 'static> = Never;
6117
6118        type ReferenceNotifier<T: Send + 'static> = Never;
6119
6120        fn new_reference_notifier<T: Send + 'static>(
6121            debug_references: DynDebugReferences,
6122        ) -> (Self::ReferenceNotifier<T>, Self::ReferenceReceiver<T>) {
6123            // We don't support deferred destruction, tests are single threaded.
6124            panic!(
6125                "can't create deferred reference notifiers for type {}: \
6126                debug_references={debug_references:?}",
6127                core::any::type_name::<T>()
6128            );
6129        }
6130    }
6131
6132    impl<D: FakeStrongDeviceId> DeferredResourceRemovalContext for TcpBindingsCtx<D> {
6133        fn defer_removal<T: Send + 'static>(&mut self, receiver: Self::ReferenceReceiver<T>) {
6134            match receiver {}
6135        }
6136    }
6137
6138    impl<D: FakeStrongDeviceId> RngContext for TcpBindingsCtx<D> {
6139        type Rng<'a> = &'a mut FakeCryptoRng;
6140        fn rng(&mut self) -> Self::Rng<'_> {
6141            &mut self.rng
6142        }
6143    }
6144
6145    impl<D: FakeStrongDeviceId> TxMetadataBindingsTypes for TcpBindingsCtx<D> {
6146        type TxMetadata = FakeTxMetadata;
6147    }
6148
6149    impl<D: FakeStrongDeviceId> MatcherBindingsTypes for TcpBindingsCtx<D> {
6150        type DeviceClass = ();
6151        type BindingsPacketMatcher = Never;
6152    }
6153
6154    impl<D: FakeStrongDeviceId> TcpBindingsTypes for TcpBindingsCtx<D> {
6155        type ReceiveBuffer = Arc<Mutex<RingBuffer>>;
6156        type SendBuffer = TestSendBuffer;
6157        type ReturnedBuffers = ClientBuffers;
6158        type ListenerNotifierOrProvidedBuffers = ProvidedBuffers;
6159
6160        fn new_passive_open_buffers(
6161            buffer_sizes: BufferSizes,
6162        ) -> (Self::ReceiveBuffer, Self::SendBuffer, Self::ReturnedBuffers) {
6163            let client = ClientBuffers::new(buffer_sizes);
6164            (
6165                Arc::clone(&client.receive),
6166                TestSendBuffer::new(Arc::clone(&client.send), RingBuffer::default()),
6167                client,
6168            )
6169        }
6170    }
6171
6172    impl<D: FakeStrongDeviceId> AlwaysDefaultsSettingsContext for TcpBindingsCtx<D> {}
6173
6174    const LINK_MTU: Mtu = Mtu::new(1500);
6175
6176    impl<I, D, BC> DeviceIpSocketHandler<I, BC> for TcpCoreCtx<D, BC>
6177    where
6178        I: TcpTestIpExt,
6179        D: FakeStrongDeviceId,
6180        BC: TcpTestBindingsTypes<D>,
6181    {
6182        fn get_mms<O>(
6183            &mut self,
6184            _bindings_ctx: &mut BC,
6185            _ip_sock: &IpSock<I, Self::WeakDeviceId>,
6186            _options: &O,
6187        ) -> Result<Mms, MmsError>
6188        where
6189            O: RouteResolutionOptions<I>,
6190        {
6191            Ok(Mms::from_mtu::<I>(LINK_MTU, 0).unwrap())
6192        }
6193    }
6194
6195    /// Delegate implementation to inner context.
6196    impl<I, D, BC> BaseTransportIpContext<I, BC> for TcpCoreCtx<D, BC>
6197    where
6198        I: TcpTestIpExt,
6199        D: FakeStrongDeviceId,
6200        BC: TcpTestBindingsTypes<D>,
6201    {
6202        type DevicesWithAddrIter<'a>
6203            = <InnerCoreCtx<D> as BaseTransportIpContext<I, BC>>::DevicesWithAddrIter<'a>
6204        where
6205            Self: 'a;
6206
6207        fn with_devices_with_assigned_addr<O, F: FnOnce(Self::DevicesWithAddrIter<'_>) -> O>(
6208            &mut self,
6209            addr: SpecifiedAddr<I::Addr>,
6210            cb: F,
6211        ) -> O {
6212            BaseTransportIpContext::<I, BC>::with_devices_with_assigned_addr(
6213                &mut self.ip_socket_ctx,
6214                addr,
6215                cb,
6216            )
6217        }
6218
6219        fn get_default_hop_limits(&mut self, device: Option<&Self::DeviceId>) -> HopLimits {
6220            BaseTransportIpContext::<I, BC>::get_default_hop_limits(&mut self.ip_socket_ctx, device)
6221        }
6222
6223        fn get_original_destination(&mut self, tuple: &Tuple<I>) -> Option<(I::Addr, u16)> {
6224            BaseTransportIpContext::<I, BC>::get_original_destination(
6225                &mut self.ip_socket_ctx,
6226                tuple,
6227            )
6228        }
6229    }
6230
6231    /// Delegate implementation to inner context.
6232    impl<I: TcpTestIpExt, D: FakeStrongDeviceId, BC: TcpTestBindingsTypes<D>> IpSocketHandler<I, BC>
6233        for TcpCoreCtx<D, BC>
6234    {
6235        fn new_ip_socket<O>(
6236            &mut self,
6237            bindings_ctx: &mut BC,
6238            args: IpSocketArgs<'_, Self::DeviceId, I, O>,
6239        ) -> Result<IpSock<I, Self::WeakDeviceId>, IpSockCreationError>
6240        where
6241            O: RouteResolutionOptions<I>,
6242        {
6243            IpSocketHandler::<I, BC>::new_ip_socket(&mut self.ip_socket_ctx, bindings_ctx, args)
6244        }
6245
6246        fn send_ip_packet<S, O>(
6247            &mut self,
6248            bindings_ctx: &mut BC,
6249            socket: &IpSock<I, Self::WeakDeviceId>,
6250            body: S,
6251            options: &O,
6252            tx_meta: BC::TxMetadata,
6253        ) -> Result<(), IpSockSendError>
6254        where
6255            S: TransportPacketSerializer<I>,
6256            S::Buffer: BufferMut,
6257            O: SendOptions<I> + RouteResolutionOptions<I>,
6258        {
6259            self.ip_socket_ctx.send_ip_packet(bindings_ctx, socket, body, options, tx_meta)
6260        }
6261
6262        fn confirm_reachable<O>(
6263            &mut self,
6264            bindings_ctx: &mut BC,
6265            socket: &IpSock<I, Self::WeakDeviceId>,
6266            options: &O,
6267        ) where
6268            O: RouteResolutionOptions<I>,
6269        {
6270            self.ip_socket_ctx.confirm_reachable(bindings_ctx, socket, options)
6271        }
6272    }
6273
6274    impl<D, BC> TcpDemuxContext<Ipv4, D::Weak, BC> for TcpCoreCtx<D, BC>
6275    where
6276        D: FakeStrongDeviceId,
6277        BC: TcpTestBindingsTypes<D>,
6278    {
6279        type IpTransportCtx<'a> = Self;
6280        fn with_demux<O, F: FnOnce(&DemuxState<Ipv4, D::Weak, BC>) -> O>(&mut self, cb: F) -> O {
6281            cb(&self.tcp.v4.demux.borrow())
6282        }
6283
6284        fn with_demux_mut<O, F: FnOnce(&mut DemuxState<Ipv4, D::Weak, BC>) -> O>(
6285            &mut self,
6286            cb: F,
6287        ) -> O {
6288            cb(&mut self.tcp.v4.demux.borrow_mut())
6289        }
6290    }
6291
6292    impl<D, BC> TcpDemuxContext<Ipv6, D::Weak, BC> for TcpCoreCtx<D, BC>
6293    where
6294        D: FakeStrongDeviceId,
6295        BC: TcpTestBindingsTypes<D>,
6296    {
6297        type IpTransportCtx<'a> = Self;
6298        fn with_demux<O, F: FnOnce(&DemuxState<Ipv6, D::Weak, BC>) -> O>(&mut self, cb: F) -> O {
6299            cb(&self.tcp.v6.demux.borrow())
6300        }
6301
6302        fn with_demux_mut<O, F: FnOnce(&mut DemuxState<Ipv6, D::Weak, BC>) -> O>(
6303            &mut self,
6304            cb: F,
6305        ) -> O {
6306            cb(&mut self.tcp.v6.demux.borrow_mut())
6307        }
6308    }
6309
6310    impl<I, D, BT> CoreTimerContext<WeakTcpSocketId<I, D::Weak, BT>, BT> for TcpCoreCtx<D, BT>
6311    where
6312        I: DualStackIpExt,
6313        D: FakeStrongDeviceId,
6314        BT: TcpTestBindingsTypes<D>,
6315    {
6316        fn convert_timer(dispatch_id: WeakTcpSocketId<I, D::Weak, BT>) -> BT::DispatchId {
6317            dispatch_id.into()
6318        }
6319    }
6320
6321    impl<I, D, BC> CoreTxMetadataContext<TcpSocketTxMetadata<I, D::Weak, BC>, BC> for TcpCoreCtx<D, BC>
6322    where
6323        I: TcpTestIpExt,
6324        D: FakeStrongDeviceId,
6325        BC: TcpTestBindingsTypes<D>,
6326    {
6327        fn convert_tx_meta(&self, _tx_meta: TcpSocketTxMetadata<I, D::Weak, BC>) -> BC::TxMetadata {
6328            Default::default()
6329        }
6330    }
6331
6332    impl<D: FakeStrongDeviceId, BC: TcpTestBindingsTypes<D>> TcpContext<Ipv6, BC>
6333        for TcpCoreCtx<D, BC>
6334    {
6335        type ThisStackIpTransportAndDemuxCtx<'a> = Self;
6336        type SingleStackIpTransportAndDemuxCtx<'a> = UninstantiableWrapper<Self>;
6337        type SingleStackConverter = Uninstantiable;
6338        type DualStackIpTransportAndDemuxCtx<'a> = Self;
6339        type DualStackConverter = ();
6340        fn with_all_sockets_mut<
6341            O,
6342            F: FnOnce(&mut TcpSocketSet<Ipv6, Self::WeakDeviceId, BC>) -> O,
6343        >(
6344            &mut self,
6345            cb: F,
6346        ) -> O {
6347            cb(&mut self.tcp.v6.all_sockets)
6348        }
6349
6350        fn for_each_socket<
6351            F: FnMut(
6352                &TcpSocketId<Ipv6, Self::WeakDeviceId, BC>,
6353                &TcpSocketState<Ipv6, Self::WeakDeviceId, BC>,
6354            ),
6355        >(
6356            &mut self,
6357            mut cb: F,
6358        ) {
6359            for id in self.tcp.v6.all_sockets.keys() {
6360                cb(id, &id.get());
6361            }
6362        }
6363
6364        fn with_socket_mut_generators_transport_demux<
6365            O,
6366            F: for<'a> FnOnce(
6367                MaybeDualStack<
6368                    (&'a mut Self::DualStackIpTransportAndDemuxCtx<'a>, Self::DualStackConverter),
6369                    (
6370                        &'a mut Self::SingleStackIpTransportAndDemuxCtx<'a>,
6371                        Self::SingleStackConverter,
6372                    ),
6373                >,
6374                &mut TcpSocketState<Ipv6, Self::WeakDeviceId, BC>,
6375                &IsnGenerator<BC::Instant>,
6376                &TimestampOffsetGenerator<BC::Instant>,
6377            ) -> O,
6378        >(
6379            &mut self,
6380            id: &TcpSocketId<Ipv6, Self::WeakDeviceId, BC>,
6381            cb: F,
6382        ) -> O {
6383            let isn = Rc::clone(&self.tcp.v6.isn_generator);
6384            let timestamp_offset = Rc::clone(&self.tcp.v6.timestamp_offset_generator);
6385            cb(
6386                MaybeDualStack::DualStack((self, ())),
6387                id.get_mut().deref_mut(),
6388                isn.deref(),
6389                timestamp_offset.deref(),
6390            )
6391        }
6392
6393        fn with_socket_and_converter<
6394            O,
6395            F: FnOnce(
6396                &TcpSocketState<Ipv6, Self::WeakDeviceId, BC>,
6397                MaybeDualStack<Self::DualStackConverter, Self::SingleStackConverter>,
6398            ) -> O,
6399        >(
6400            &mut self,
6401            id: &TcpSocketId<Ipv6, Self::WeakDeviceId, BC>,
6402            cb: F,
6403        ) -> O {
6404            cb(id.get_mut().deref_mut(), MaybeDualStack::DualStack(()))
6405        }
6406    }
6407
6408    impl<D: FakeStrongDeviceId, BC: TcpTestBindingsTypes<D>> TcpContext<Ipv4, BC>
6409        for TcpCoreCtx<D, BC>
6410    {
6411        type ThisStackIpTransportAndDemuxCtx<'a> = Self;
6412        type SingleStackIpTransportAndDemuxCtx<'a> = Self;
6413        type SingleStackConverter = ();
6414        type DualStackIpTransportAndDemuxCtx<'a> = UninstantiableWrapper<Self>;
6415        type DualStackConverter = Uninstantiable;
6416        fn with_all_sockets_mut<
6417            O,
6418            F: FnOnce(&mut TcpSocketSet<Ipv4, Self::WeakDeviceId, BC>) -> O,
6419        >(
6420            &mut self,
6421            cb: F,
6422        ) -> O {
6423            cb(&mut self.tcp.v4.all_sockets)
6424        }
6425
6426        fn for_each_socket<
6427            F: FnMut(
6428                &TcpSocketId<Ipv4, Self::WeakDeviceId, BC>,
6429                &TcpSocketState<Ipv4, Self::WeakDeviceId, BC>,
6430            ),
6431        >(
6432            &mut self,
6433            mut cb: F,
6434        ) {
6435            for id in self.tcp.v4.all_sockets.keys() {
6436                cb(id, &id.get());
6437            }
6438        }
6439
6440        fn with_socket_mut_generators_transport_demux<
6441            O,
6442            F: for<'a> FnOnce(
6443                MaybeDualStack<
6444                    (&'a mut Self::DualStackIpTransportAndDemuxCtx<'a>, Self::DualStackConverter),
6445                    (
6446                        &'a mut Self::SingleStackIpTransportAndDemuxCtx<'a>,
6447                        Self::SingleStackConverter,
6448                    ),
6449                >,
6450                &mut TcpSocketState<Ipv4, Self::WeakDeviceId, BC>,
6451                &IsnGenerator<BC::Instant>,
6452                &TimestampOffsetGenerator<BC::Instant>,
6453            ) -> O,
6454        >(
6455            &mut self,
6456            id: &TcpSocketId<Ipv4, Self::WeakDeviceId, BC>,
6457            cb: F,
6458        ) -> O {
6459            let isn: Rc<IsnGenerator<<BC as InstantBindingsTypes>::Instant>> =
6460                Rc::clone(&self.tcp.v4.isn_generator);
6461            let timestamp_offset: Rc<
6462                TimestampOffsetGenerator<<BC as InstantBindingsTypes>::Instant>,
6463            > = Rc::clone(&self.tcp.v4.timestamp_offset_generator);
6464            cb(
6465                MaybeDualStack::NotDualStack((self, ())),
6466                id.get_mut().deref_mut(),
6467                isn.deref(),
6468                timestamp_offset.deref(),
6469            )
6470        }
6471
6472        fn with_socket_and_converter<
6473            O,
6474            F: FnOnce(
6475                &TcpSocketState<Ipv4, Self::WeakDeviceId, BC>,
6476                MaybeDualStack<Self::DualStackConverter, Self::SingleStackConverter>,
6477            ) -> O,
6478        >(
6479            &mut self,
6480            id: &TcpSocketId<Ipv4, Self::WeakDeviceId, BC>,
6481            cb: F,
6482        ) -> O {
6483            cb(id.get_mut().deref_mut(), MaybeDualStack::NotDualStack(()))
6484        }
6485    }
6486
6487    impl<D: FakeStrongDeviceId, BT: TcpTestBindingsTypes<D>>
6488        TcpDualStackContext<Ipv6, FakeWeakDeviceId<D>, BT> for TcpCoreCtx<D, BT>
6489    {
6490        type DualStackIpTransportCtx<'a> = Self;
6491        fn other_demux_id_converter(&self) -> impl DualStackDemuxIdConverter<Ipv6> {
6492            Ipv6SocketIdToIpv4DemuxIdConverter
6493        }
6494        fn dual_stack_enabled(&self, ip_options: &Ipv6Options) -> bool {
6495            ip_options.dual_stack_enabled
6496        }
6497        fn set_dual_stack_enabled(&self, ip_options: &mut Ipv6Options, value: bool) {
6498            ip_options.dual_stack_enabled = value;
6499        }
6500        fn with_both_demux_mut<
6501            O,
6502            F: FnOnce(
6503                &mut DemuxState<Ipv6, FakeWeakDeviceId<D>, BT>,
6504                &mut DemuxState<Ipv4, FakeWeakDeviceId<D>, BT>,
6505            ) -> O,
6506        >(
6507            &mut self,
6508            cb: F,
6509        ) -> O {
6510            cb(&mut self.tcp.v6.demux.borrow_mut(), &mut self.tcp.v4.demux.borrow_mut())
6511        }
6512    }
6513
6514    impl<I: Ip, D: FakeStrongDeviceId, BT: TcpTestBindingsTypes<D>>
6515        CounterContext<TcpCountersWithSocket<I>> for TcpCoreCtx<D, BT>
6516    {
6517        fn counters(&self) -> &TcpCountersWithSocket<I> {
6518            I::map_ip(
6519                (),
6520                |()| &self.tcp.v4.counters_with_socket,
6521                |()| &self.tcp.v6.counters_with_socket,
6522            )
6523        }
6524    }
6525
6526    impl<I: Ip, D: FakeStrongDeviceId, BT: TcpTestBindingsTypes<D>>
6527        CounterContext<TcpCountersWithoutSocket<I>> for TcpCoreCtx<D, BT>
6528    {
6529        fn counters(&self) -> &TcpCountersWithoutSocket<I> {
6530            I::map_ip(
6531                (),
6532                |()| &self.tcp.v4.counters_without_socket,
6533                |()| &self.tcp.v6.counters_without_socket,
6534            )
6535        }
6536    }
6537
6538    impl<I: DualStackIpExt, D: FakeStrongDeviceId, BT: TcpTestBindingsTypes<D>>
6539        ResourceCounterContext<TcpSocketId<I, FakeWeakDeviceId<D>, BT>, TcpCountersWithSocket<I>>
6540        for TcpCoreCtx<D, BT>
6541    {
6542        fn per_resource_counters<'a>(
6543            &'a self,
6544            resource: &'a TcpSocketId<I, FakeWeakDeviceId<D>, BT>,
6545        ) -> &'a TcpCountersWithSocket<I> {
6546            resource.counters()
6547        }
6548    }
6549
6550    impl<D, BT> TcpCoreCtx<D, BT>
6551    where
6552        D: FakeStrongDeviceId,
6553        BT: TcpBindingsTypes,
6554        BT::Instant: Default,
6555    {
6556        fn with_ip_socket_ctx_state(state: FakeDualStackIpSocketCtx<D>) -> Self {
6557            Self {
6558                tcp: Default::default(),
6559                ip_socket_ctx: FakeCoreCtx::with_state(state),
6560                recv_packet_marks: Default::default(),
6561            }
6562        }
6563    }
6564
6565    impl TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>> {
6566        pub(crate) fn new<I: TcpTestIpExt>(
6567            addr: SpecifiedAddr<I::Addr>,
6568            peer: SpecifiedAddr<I::Addr>,
6569        ) -> Self {
6570            Self::with_ip_socket_ctx_state(FakeDualStackIpSocketCtx::new(core::iter::once(
6571                FakeDeviceConfig {
6572                    device: FakeDeviceId,
6573                    local_ips: vec![addr],
6574                    remote_ips: vec![peer],
6575                },
6576            )))
6577        }
6578    }
6579
6580    impl TcpCoreCtx<MultipleDevicesId, TcpBindingsCtx<MultipleDevicesId>> {
6581        fn new_multiple_devices() -> Self {
6582            Self::with_ip_socket_ctx_state(FakeDualStackIpSocketCtx::new(core::iter::empty::<
6583                FakeDeviceConfig<MultipleDevicesId, SpecifiedAddr<IpAddr>>,
6584            >()))
6585        }
6586    }
6587
6588    impl<D: WeakDeviceIdentifier, BT: TcpBindingsTypes> TcpTimerId<D, BT> {
6589        fn assert_ip_version<I: DualStackIpExt>(self) -> WeakTcpSocketId<I, D, BT> {
6590            I::map_ip_out(
6591                self,
6592                |v4| assert_matches!(v4, TcpTimerId::V4(v4) => v4),
6593                |v6| assert_matches!(v6, TcpTimerId::V6(v6) => v6),
6594            )
6595        }
6596    }
6597
6598    const LOCAL: &'static str = "local";
6599    const REMOTE: &'static str = "remote";
6600    pub(crate) const PORT_1: NonZeroU16 = NonZeroU16::new(42).unwrap();
6601    const PORT_2: NonZeroU16 = NonZeroU16::new(43).unwrap();
6602
6603    impl TcpTestIpExt for Ipv4 {
6604        type SingleStackConverter = ();
6605        type DualStackConverter = Uninstantiable;
6606        fn converter() -> MaybeDualStack<Self::DualStackConverter, Self::SingleStackConverter> {
6607            MaybeDualStack::NotDualStack(())
6608        }
6609        fn recv_src_addr(addr: Self::Addr) -> Self::RecvSrcAddr {
6610            Ipv4SourceAddr::new(addr).unwrap()
6611        }
6612    }
6613
6614    impl TcpTestIpExt for Ipv6 {
6615        type SingleStackConverter = Uninstantiable;
6616        type DualStackConverter = ();
6617        fn converter() -> MaybeDualStack<Self::DualStackConverter, Self::SingleStackConverter> {
6618            MaybeDualStack::DualStack(())
6619        }
6620        fn recv_src_addr(addr: Self::Addr) -> Self::RecvSrcAddr {
6621            Ipv6SourceAddr::new(addr).unwrap()
6622        }
6623    }
6624
6625    type TcpTestNetwork = FakeNetwork<
6626        FakeTcpNetworkSpec<FakeDeviceId>,
6627        &'static str,
6628        fn(
6629            &'static str,
6630            DualStackSendIpPacketMeta<FakeDeviceId>,
6631        ) -> Vec<(
6632            &'static str,
6633            DualStackSendIpPacketMeta<FakeDeviceId>,
6634            Option<core::time::Duration>,
6635        )>,
6636    >;
6637
6638    fn new_test_net<I: TcpTestIpExt>() -> TcpTestNetwork {
6639        FakeTcpNetworkSpec::new_network(
6640            [
6641                (
6642                    LOCAL,
6643                    TcpCtx {
6644                        core_ctx: TcpCoreCtx::new::<I>(
6645                            I::TEST_ADDRS.local_ip,
6646                            I::TEST_ADDRS.remote_ip,
6647                        ),
6648                        bindings_ctx: TcpBindingsCtx::default(),
6649                    },
6650                ),
6651                (
6652                    REMOTE,
6653                    TcpCtx {
6654                        core_ctx: TcpCoreCtx::new::<I>(
6655                            I::TEST_ADDRS.remote_ip,
6656                            I::TEST_ADDRS.local_ip,
6657                        ),
6658                        bindings_ctx: TcpBindingsCtx::default(),
6659                    },
6660                ),
6661            ],
6662            move |net, meta: DualStackSendIpPacketMeta<_>| {
6663                if net == LOCAL {
6664                    alloc::vec![(REMOTE, meta, None)]
6665                } else {
6666                    alloc::vec![(LOCAL, meta, None)]
6667                }
6668            },
6669        )
6670    }
6671
6672    /// Utilities for accessing locked internal state in tests.
6673    impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> TcpSocketId<I, D, BT> {
6674        fn get(&self) -> impl Deref<Target = TcpSocketState<I, D, BT>> + '_ {
6675            let Self(rc) = self;
6676            rc.locked_state.read()
6677        }
6678
6679        fn get_mut(&self) -> impl DerefMut<Target = TcpSocketState<I, D, BT>> + '_ {
6680            let Self(rc) = self;
6681            rc.locked_state.write()
6682        }
6683    }
6684
6685    fn assert_this_stack_conn<
6686        'a,
6687        I: DualStackIpExt,
6688        BC: TcpBindingsContext<CC::DeviceId>,
6689        CC: TcpContext<I, BC>,
6690    >(
6691        conn: &'a I::ConnectionAndAddr<CC::WeakDeviceId, BC>,
6692        converter: &MaybeDualStack<CC::DualStackConverter, CC::SingleStackConverter>,
6693    ) -> &'a (
6694        Connection<I, I, CC::WeakDeviceId, BC>,
6695        ConnAddr<ConnIpAddr<I::Addr, NonZeroU16, NonZeroU16>, CC::WeakDeviceId>,
6696    ) {
6697        match converter {
6698            MaybeDualStack::NotDualStack(nds) => nds.convert(conn),
6699            MaybeDualStack::DualStack(ds) => {
6700                assert_matches!(ds.convert(conn), EitherStack::ThisStack(conn) => conn)
6701            }
6702        }
6703    }
6704
6705    /// A trait providing a shortcut to instantiate a [`TcpApi`] from a context.
6706    pub(crate) trait TcpApiExt: ContextPair + Sized {
6707        fn tcp_api<I: Ip>(&mut self) -> TcpApi<I, &mut Self> {
6708            TcpApi::new(self)
6709        }
6710    }
6711
6712    impl<O> TcpApiExt for O where O: ContextPair + Sized {}
6713
6714    /// How to bind the client socket in `bind_listen_connect_accept_inner`.
6715    struct BindConfig {
6716        /// Which port to bind the client to.
6717        client_port: Option<NonZeroU16>,
6718        /// Which port to bind the server to.
6719        server_port: NonZeroU16,
6720        /// Whether to set REUSE_ADDR for the client.
6721        client_reuse_addr: bool,
6722        /// Whether to send bidirectional test data after establishing the
6723        /// connection.
6724        send_test_data: bool,
6725    }
6726
6727    /// The following test sets up two connected testing context - one as the
6728    /// server and the other as the client. Tests if a connection can be
6729    /// established using `bind`, `listen`, `connect` and `accept`.
6730    ///
6731    /// # Arguments
6732    ///
6733    /// * `listen_addr` - The address to listen on.
6734    /// * `bind_config` - Specifics about how to bind the client socket.
6735    ///
6736    /// # Returns
6737    ///
6738    /// Returns a tuple of
6739    ///   - the created test network.
6740    ///   - the client socket from local.
6741    ///   - the send end of the client socket.
6742    ///   - the accepted socket from remote.
6743    fn bind_listen_connect_accept_inner<I: TcpTestIpExt>(
6744        listen_addr: I::Addr,
6745        BindConfig { client_port, server_port, client_reuse_addr, send_test_data }: BindConfig,
6746        seed: u128,
6747        drop_rate: f64,
6748    ) -> (
6749        TcpTestNetwork,
6750        TcpSocketId<I, FakeWeakDeviceId<FakeDeviceId>, TcpBindingsCtx<FakeDeviceId>>,
6751        Arc<Mutex<Vec<u8>>>,
6752        TcpSocketId<I, FakeWeakDeviceId<FakeDeviceId>, TcpBindingsCtx<FakeDeviceId>>,
6753    )
6754    where
6755        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
6756                I,
6757                TcpBindingsCtx<FakeDeviceId>,
6758                SingleStackConverter = I::SingleStackConverter,
6759                DualStackConverter = I::DualStackConverter,
6760            >,
6761    {
6762        let mut net = new_test_net::<I>();
6763        let mut rng = new_rng(seed);
6764
6765        let mut maybe_drop_frame =
6766            |_: &mut TcpCtx<_>, meta: DualStackSendIpPacketMeta<_>, buffer: Buf<Vec<u8>>| {
6767                let x: f64 = rng.random();
6768                (x > drop_rate).then_some((meta, buffer))
6769            };
6770
6771        let backlog = NonZeroUsize::new(1).unwrap();
6772        let server = net.with_context(REMOTE, |ctx| {
6773            let mut api = ctx.tcp_api::<I>();
6774            let server = api.create(Default::default());
6775            api.bind(
6776                &server,
6777                SpecifiedAddr::new(listen_addr).map(|a| ZonedAddr::Unzoned(a)),
6778                Some(server_port),
6779            )
6780            .expect("failed to bind the server socket");
6781            api.listen(&server, backlog).expect("can listen");
6782            server
6783        });
6784
6785        let client_ends = WriteBackClientBuffers::default();
6786        let client = net.with_context(LOCAL, |ctx| {
6787            let mut api = ctx.tcp_api::<I>();
6788            let socket = api.create(ProvidedBuffers::Buffers(client_ends.clone()));
6789            if client_reuse_addr {
6790                api.set_reuseaddr(&socket, true).expect("can set");
6791            }
6792            if let Some(port) = client_port {
6793                api.bind(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(port))
6794                    .expect("failed to bind the client socket")
6795            }
6796            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), server_port)
6797                .expect("failed to connect");
6798            socket
6799        });
6800        // If drop rate is 0, the SYN is guaranteed to be delivered, so we can
6801        // look at the SYN queue deterministically.
6802        if drop_rate == 0.0 {
6803            // Step once for the SYN packet to be sent.
6804            let _: StepResult = net.step();
6805            // The listener should create a pending socket.
6806            assert_matches!(
6807                &server.get().deref().socket_state,
6808                TcpSocketStateInner::Listener(Listener { accept_queue, .. }) => {
6809                    assert_eq!(accept_queue.ready_len(), 0);
6810                    assert_eq!(accept_queue.pending_len(), 1);
6811                }
6812            );
6813            // The handshake is not done, calling accept here should not succeed.
6814            net.with_context(REMOTE, |ctx| {
6815                let mut api = ctx.tcp_api::<I>();
6816                assert_matches!(api.accept(&server), Err(AcceptError::WouldBlock));
6817            });
6818        }
6819
6820        // Step the test network until the handshake is done.
6821        net.run_until_idle_with(&mut maybe_drop_frame);
6822        let (accepted, addr, accepted_ends) = net.with_context(REMOTE, |ctx| {
6823            ctx.tcp_api::<I>().accept(&server).expect("failed to accept")
6824        });
6825        if let Some(port) = client_port {
6826            assert_eq!(
6827                addr,
6828                SocketAddr { ip: ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip), port: port }
6829            );
6830        } else {
6831            assert_eq!(addr.ip, ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip));
6832        }
6833
6834        net.with_context(LOCAL, |ctx| {
6835            let mut api = ctx.tcp_api::<I>();
6836            assert_eq!(
6837                api.connect(
6838                    &client,
6839                    Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)),
6840                    server_port,
6841                ),
6842                Ok(())
6843            );
6844        });
6845
6846        let assert_connected = |conn_id: &TcpSocketId<I, _, _>| {
6847            assert_matches!(
6848                &conn_id.get().deref().socket_state,
6849                TcpSocketStateInner::Connected { conn, .. } => {
6850                        let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
6851                        assert_matches!(
6852                            conn,
6853                            Connection {
6854                                accept_queue: None,
6855                                state: State::Established(_),
6856                                ip_sock: _,
6857                                defunct: false,
6858                                soft_error: None,
6859                                handshake_status: HandshakeStatus::Completed { reported: true },
6860                            }
6861                        );
6862                    }
6863            )
6864        };
6865
6866        assert_connected(&client);
6867        assert_connected(&accepted);
6868
6869        let ClientBuffers { send: client_snd_end, receive: client_rcv_end } =
6870            client_ends.0.as_ref().lock().take().unwrap();
6871        let ClientBuffers { send: accepted_snd_end, receive: accepted_rcv_end } = accepted_ends;
6872
6873        if send_test_data {
6874            for snd_end in [client_snd_end.clone(), accepted_snd_end] {
6875                snd_end.lock().extend_from_slice(b"Hello");
6876            }
6877
6878            for (c, id) in [(LOCAL, &client), (REMOTE, &accepted)] {
6879                net.with_context(c, |ctx| ctx.tcp_api::<I>().do_send(id))
6880            }
6881            net.run_until_idle_with(&mut maybe_drop_frame);
6882
6883            for rcv_end in [client_rcv_end, accepted_rcv_end] {
6884                assert_eq!(
6885                    rcv_end.lock().read_with(|avail| {
6886                        let avail = avail.concat();
6887                        assert_eq!(avail, b"Hello");
6888                        avail.len()
6889                    }),
6890                    5
6891                );
6892            }
6893        }
6894
6895        // Check the listener is in correct state.
6896        assert_matches!(
6897            &server.get().deref().socket_state,
6898            TcpSocketStateInner::Listener(Listener {
6899                addr: _,
6900                backlog: actual_backlog,
6901                accept_queue: _,
6902                buffer_sizes
6903            }) => {
6904                assert_eq!(*actual_backlog, backlog);
6905                assert_eq!(*buffer_sizes, BufferSizes::default());
6906            }
6907        );
6908
6909        net.with_context(REMOTE, |ctx| {
6910            let mut api = ctx.tcp_api::<I>();
6911            assert_eq!(api.shutdown(&server, ShutdownType::Receive), Ok(false));
6912            api.close(server);
6913        });
6914
6915        (net, client, client_snd_end, accepted)
6916    }
6917
6918    #[test]
6919    fn test_socket_addr_display() {
6920        assert_eq!(
6921            format!(
6922                "{}",
6923                SocketAddr {
6924                    ip: maybe_zoned(
6925                        SpecifiedAddr::new(Ipv4Addr::new([192, 168, 0, 1]))
6926                            .expect("failed to create specified addr"),
6927                        &None::<usize>,
6928                    ),
6929                    port: NonZeroU16::new(1024).expect("failed to create NonZeroU16"),
6930                }
6931            ),
6932            String::from("192.168.0.1:1024"),
6933        );
6934        assert_eq!(
6935            format!(
6936                "{}",
6937                SocketAddr {
6938                    ip: maybe_zoned(
6939                        SpecifiedAddr::new(Ipv6Addr::new([0x2001, 0xDB8, 0, 0, 0, 0, 0, 1]))
6940                            .expect("failed to create specified addr"),
6941                        &None::<usize>,
6942                    ),
6943                    port: NonZeroU16::new(1024).expect("failed to create NonZeroU16"),
6944                }
6945            ),
6946            String::from("[2001:db8::1]:1024")
6947        );
6948        assert_eq!(
6949            format!(
6950                "{}",
6951                SocketAddr {
6952                    ip: maybe_zoned(
6953                        SpecifiedAddr::new(Ipv6Addr::new([0xFE80, 0, 0, 0, 0, 0, 0, 1]))
6954                            .expect("failed to create specified addr"),
6955                        &Some(42),
6956                    ),
6957                    port: NonZeroU16::new(1024).expect("failed to create NonZeroU16"),
6958                }
6959            ),
6960            String::from("[fe80::1%42]:1024")
6961        );
6962    }
6963
6964    #[ip_test(I)]
6965    #[test_case(BindConfig { client_port: None, server_port: PORT_1, client_reuse_addr: false, send_test_data: true }, I::UNSPECIFIED_ADDRESS)]
6966    #[test_case(BindConfig { client_port: Some(PORT_1), server_port: PORT_1, client_reuse_addr: false, send_test_data: true }, I::UNSPECIFIED_ADDRESS)]
6967    #[test_case(BindConfig { client_port: None, server_port: PORT_1, client_reuse_addr: true, send_test_data: true }, I::UNSPECIFIED_ADDRESS)]
6968    #[test_case(BindConfig { client_port: Some(PORT_1), server_port: PORT_1, client_reuse_addr: true, send_test_data: true }, I::UNSPECIFIED_ADDRESS)]
6969    #[test_case(BindConfig { client_port: None, server_port: PORT_1, client_reuse_addr: false, send_test_data: true }, *<I as TestIpExt>::TEST_ADDRS.remote_ip)]
6970    #[test_case(BindConfig { client_port: Some(PORT_1), server_port: PORT_1, client_reuse_addr: false, send_test_data: true }, *<I as TestIpExt>::TEST_ADDRS.remote_ip)]
6971    #[test_case(BindConfig { client_port: None, server_port: PORT_1, client_reuse_addr: true, send_test_data: true }, *<I as TestIpExt>::TEST_ADDRS.remote_ip)]
6972    #[test_case(BindConfig { client_port: Some(PORT_1), server_port: PORT_1, client_reuse_addr: true, send_test_data: true }, *<I as TestIpExt>::TEST_ADDRS.remote_ip)]
6973    fn bind_listen_connect_accept<I: TcpTestIpExt>(bind_config: BindConfig, listen_addr: I::Addr)
6974    where
6975        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
6976                I,
6977                TcpBindingsCtx<FakeDeviceId>,
6978                SingleStackConverter = I::SingleStackConverter,
6979                DualStackConverter = I::DualStackConverter,
6980            >,
6981    {
6982        set_logger_for_test();
6983        let (mut net, client, _client_snd_end, accepted) =
6984            bind_listen_connect_accept_inner::<I>(listen_addr, bind_config, 0, 0.0);
6985
6986        let mut assert_counters =
6987            |context_name: &'static str,
6988             socket: &TcpSocketId<I, _, _>,
6989             expected: CounterExpectations,
6990             expected_without_socket: CounterExpectationsWithoutSocket,
6991             expected_per_socket: CounterExpectations| {
6992                net.with_context(context_name, |ctx| {
6993                    let counters =
6994                        CounterContext::<TcpCountersWithSocket<I>>::counters(&ctx.core_ctx);
6995                    let counters_without_socket =
6996                        CounterContext::<TcpCountersWithoutSocket<I>>::counters(&ctx.core_ctx);
6997                    let counters_per_socket = ctx.core_ctx.per_resource_counters(socket);
6998                    assert_eq!(expected, counters.as_ref().cast(), "{context_name}");
6999                    assert_eq!(
7000                        expected_without_socket,
7001                        counters_without_socket.as_ref().cast(),
7002                        "{context_name}"
7003                    );
7004                    assert_eq!(
7005                        expected_per_socket,
7006                        counters_per_socket.as_ref().cast(),
7007                        "{context_name}"
7008                    )
7009                })
7010            };
7011
7012        // Communication done by `bind_listen_connect_accept_inner`:
7013        //   LOCAL -> REMOTE: SYN to initiate the connection.
7014        //   LOCAL <- REMOTE: ACK the connection.
7015        //   LOCAL -> REMOTE: ACK the ACK.
7016        //   LOCAL -> REMOTE: Send "hello".
7017        //   LOCAL <- REMOTE: ACK "hello".
7018        //   LOCAL <- REMOTE: Send "hello".
7019        //   LOCAL -> REMOTE: ACK "hello".
7020        let local_with_socket_expects = || CounterExpectations {
7021            segments_sent: 4,
7022            received_segments_dispatched: 3,
7023            active_connection_openings: 1,
7024            syns_sent: 1,
7025            syns_received: 1,
7026            ..Default::default()
7027        };
7028        assert_counters(
7029            LOCAL,
7030            &client,
7031            local_with_socket_expects(),
7032            CounterExpectationsWithoutSocket { valid_segments_received: 3, ..Default::default() },
7033            // Note: The local side only has 1 socket, so the stack-wide and
7034            // per-socket expectations are identical.
7035            local_with_socket_expects(),
7036        );
7037
7038        assert_counters(
7039            REMOTE,
7040            &accepted,
7041            CounterExpectations {
7042                segments_sent: 3,
7043                received_segments_dispatched: 4,
7044                passive_connection_openings: 1,
7045                syns_sent: 1,
7046                syns_received: 1,
7047                ..Default::default()
7048            },
7049            CounterExpectationsWithoutSocket { valid_segments_received: 4, ..Default::default() },
7050            // Note: The remote side has a listener socket and the accepted
7051            // socket. The stack-wide counters are higher than the accepted
7052            // socket's counters, because some events are attributed to the
7053            // listener.
7054            CounterExpectations {
7055                segments_sent: 2,
7056                received_segments_dispatched: 3,
7057                ..Default::default()
7058            },
7059        );
7060    }
7061
7062    #[ip_test(I)]
7063    #[test_case(*<I as TestIpExt>::TEST_ADDRS.local_ip; "same addr")]
7064    #[test_case(I::UNSPECIFIED_ADDRESS; "any addr")]
7065    fn bind_conflict<I: TcpTestIpExt>(conflict_addr: I::Addr)
7066    where
7067        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7068            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7069    {
7070        set_logger_for_test();
7071        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
7072            I::TEST_ADDRS.local_ip,
7073            I::TEST_ADDRS.local_ip,
7074        ));
7075        let mut api = ctx.tcp_api::<I>();
7076        let s1 = api.create(Default::default());
7077        let s2 = api.create(Default::default());
7078
7079        api.bind(&s1, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(PORT_1))
7080            .expect("first bind should succeed");
7081        assert_matches!(
7082            api.bind(&s2, SpecifiedAddr::new(conflict_addr).map(ZonedAddr::Unzoned), Some(PORT_1)),
7083            Err(BindError::LocalAddressError(LocalAddressError::AddressInUse))
7084        );
7085        api.bind(&s2, SpecifiedAddr::new(conflict_addr).map(ZonedAddr::Unzoned), Some(PORT_2))
7086            .expect("able to rebind to a free address");
7087    }
7088
7089    #[ip_test(I)]
7090    #[test_case(NonZeroU16::new(u16::MAX).unwrap(), Ok(NonZeroU16::new(u16::MAX).unwrap()); "ephemeral available")]
7091    #[test_case(NonZeroU16::new(100).unwrap(), Err(LocalAddressError::FailedToAllocateLocalPort);
7092                "no ephemeral available")]
7093    fn bind_picked_port_all_others_taken<I: TcpTestIpExt>(
7094        available_port: NonZeroU16,
7095        expected_result: Result<NonZeroU16, LocalAddressError>,
7096    ) where
7097        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7098            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7099    {
7100        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
7101            I::TEST_ADDRS.local_ip,
7102            I::TEST_ADDRS.local_ip,
7103        ));
7104        let mut api = ctx.tcp_api::<I>();
7105        for port in 1..=u16::MAX {
7106            let port = NonZeroU16::new(port).unwrap();
7107            if port == available_port {
7108                continue;
7109            }
7110            let socket = api.create(Default::default());
7111
7112            api.bind(&socket, None, Some(port)).expect("uncontested bind");
7113            api.listen(&socket, NonZeroUsize::new(1).unwrap()).expect("can listen");
7114        }
7115
7116        // Now that all but the LOCAL_PORT are occupied, ask the stack to
7117        // select a port.
7118        let socket = api.create(Default::default());
7119        let result = api.bind(&socket, None, None).map(|()| {
7120            assert_matches!(
7121                api.get_info(&socket),
7122                SocketInfo::Bound(bound) => bound.port
7123            )
7124        });
7125        assert_eq!(result, expected_result.map_err(From::from));
7126
7127        // Now close the socket and try a connect call to ourselves on the
7128        // available port. Self-connection protection should always prevent us
7129        // from doing that even when the port is in the ephemeral range.
7130        api.close(socket);
7131        let socket = api.create(Default::default());
7132        let result =
7133            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), available_port);
7134        assert_eq!(result, Err(ConnectError::NoPort));
7135    }
7136
7137    #[ip_test(I)]
7138    fn bind_to_non_existent_address<I: TcpTestIpExt>()
7139    where
7140        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7141            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7142    {
7143        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
7144            I::TEST_ADDRS.local_ip,
7145            I::TEST_ADDRS.remote_ip,
7146        ));
7147        let mut api = ctx.tcp_api::<I>();
7148        let unbound = api.create(Default::default());
7149        assert_matches!(
7150            api.bind(&unbound, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), None),
7151            Err(BindError::LocalAddressError(LocalAddressError::AddressMismatch))
7152        );
7153
7154        assert_matches!(unbound.get().deref().socket_state, TcpSocketStateInner::Unbound(_));
7155    }
7156
7157    #[test]
7158    fn bind_addr_requires_zone() {
7159        let local_ip = LinkLocalAddr::new(net_ip_v6!("fe80::1")).unwrap().into_specified();
7160
7161        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(
7162            Ipv6::TEST_ADDRS.local_ip,
7163            Ipv6::TEST_ADDRS.remote_ip,
7164        ));
7165        let mut api = ctx.tcp_api::<Ipv6>();
7166        let unbound = api.create(Default::default());
7167        assert_matches!(
7168            api.bind(&unbound, Some(ZonedAddr::Unzoned(local_ip)), None),
7169            Err(BindError::LocalAddressError(LocalAddressError::Zone(
7170                ZonedAddressError::RequiredZoneNotProvided
7171            )))
7172        );
7173
7174        assert_matches!(unbound.get().deref().socket_state, TcpSocketStateInner::Unbound(_));
7175    }
7176
7177    #[test]
7178    fn connect_bound_requires_zone() {
7179        let ll_ip = LinkLocalAddr::new(net_ip_v6!("fe80::1")).unwrap().into_specified();
7180
7181        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(
7182            Ipv6::TEST_ADDRS.local_ip,
7183            Ipv6::TEST_ADDRS.remote_ip,
7184        ));
7185        let mut api = ctx.tcp_api::<Ipv6>();
7186        let socket = api.create(Default::default());
7187        api.bind(&socket, None, None).expect("bind succeeds");
7188        assert_matches!(
7189            api.connect(&socket, Some(ZonedAddr::Unzoned(ll_ip)), PORT_1,),
7190            Err(ConnectError::Zone(ZonedAddressError::RequiredZoneNotProvided))
7191        );
7192
7193        assert_matches!(
7194            socket.get().deref().socket_state,
7195            TcpSocketStateInner::Bound { .. } | TcpSocketStateInner::Connected { .. }
7196        );
7197    }
7198
7199    // This is a regression test for https://fxbug.dev/361402347.
7200    #[ip_test(I)]
7201    fn bind_listen_on_same_port_different_addrs<I: TcpTestIpExt>()
7202    where
7203        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7204            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7205    {
7206        set_logger_for_test();
7207
7208        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::with_ip_socket_ctx_state(
7209            FakeDualStackIpSocketCtx::new(core::iter::once(FakeDeviceConfig {
7210                device: FakeDeviceId,
7211                local_ips: vec![I::TEST_ADDRS.local_ip, I::TEST_ADDRS.remote_ip],
7212                remote_ips: vec![],
7213            })),
7214        ));
7215        let mut api = ctx.tcp_api::<I>();
7216
7217        let s1 = api.create(Default::default());
7218        api.bind(&s1, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(PORT_1)).unwrap();
7219        api.listen(&s1, NonZeroUsize::MIN).unwrap();
7220
7221        let s2 = api.create(Default::default());
7222        api.bind(&s2, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), Some(PORT_1)).unwrap();
7223        api.listen(&s2, NonZeroUsize::MIN).unwrap();
7224    }
7225
7226    #[ip_test(I)]
7227    #[test_case(None, None; "both any addr")]
7228    #[test_case(None, Some(<I as TestIpExt>::TEST_ADDRS.local_ip); "any then specified")]
7229    #[test_case(Some(<I as TestIpExt>::TEST_ADDRS.local_ip), None; "specified then any")]
7230    #[test_case(
7231        Some(<I as TestIpExt>::TEST_ADDRS.local_ip),
7232        Some(<I as TestIpExt>::TEST_ADDRS.local_ip);
7233        "both specified"
7234    )]
7235    fn cannot_listen_on_same_port_with_shadowed_address<I: TcpTestIpExt>(
7236        first: Option<SpecifiedAddr<I::Addr>>,
7237        second: Option<SpecifiedAddr<I::Addr>>,
7238    ) where
7239        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7240            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7241    {
7242        set_logger_for_test();
7243
7244        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::with_ip_socket_ctx_state(
7245            FakeDualStackIpSocketCtx::new(core::iter::once(FakeDeviceConfig {
7246                device: FakeDeviceId,
7247                local_ips: vec![I::TEST_ADDRS.local_ip],
7248                remote_ips: vec![],
7249            })),
7250        ));
7251        let mut api = ctx.tcp_api::<I>();
7252
7253        let s1 = api.create(Default::default());
7254        api.set_reuseaddr(&s1, true).unwrap();
7255        api.bind(&s1, first.map(ZonedAddr::Unzoned), Some(PORT_1)).unwrap();
7256
7257        let s2 = api.create(Default::default());
7258        api.set_reuseaddr(&s2, true).unwrap();
7259        api.bind(&s2, second.map(ZonedAddr::Unzoned), Some(PORT_1)).unwrap();
7260
7261        api.listen(&s1, NonZeroUsize::MIN).unwrap();
7262        assert_eq!(api.listen(&s2, NonZeroUsize::MIN), Err(ListenError::ListenerExists));
7263    }
7264
7265    #[test]
7266    fn connect_unbound_picks_link_local_source_addr() {
7267        set_logger_for_test();
7268        let client_ip = SpecifiedAddr::new(net_ip_v6!("fe80::1")).unwrap();
7269        let server_ip = SpecifiedAddr::new(net_ip_v6!("1:2:3:4::")).unwrap();
7270        let mut net = FakeTcpNetworkSpec::new_network(
7271            [
7272                (LOCAL, TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(client_ip, server_ip))),
7273                (REMOTE, TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(server_ip, client_ip))),
7274            ],
7275            |net, meta| {
7276                if net == LOCAL {
7277                    alloc::vec![(REMOTE, meta, None)]
7278                } else {
7279                    alloc::vec![(LOCAL, meta, None)]
7280                }
7281            },
7282        );
7283        const PORT: NonZeroU16 = NonZeroU16::new(100).unwrap();
7284        let client_connection = net.with_context(LOCAL, |ctx| {
7285            let mut api = ctx.tcp_api();
7286            let socket: TcpSocketId<Ipv6, _, _> = api.create(Default::default());
7287            api.connect(&socket, Some(ZonedAddr::Unzoned(server_ip)), PORT).expect("can connect");
7288            socket
7289        });
7290        net.with_context(REMOTE, |ctx| {
7291            let mut api = ctx.tcp_api::<Ipv6>();
7292            let socket = api.create(Default::default());
7293            api.bind(&socket, None, Some(PORT)).expect("failed to bind the client socket");
7294            let _listener = api.listen(&socket, NonZeroUsize::MIN).expect("can listen");
7295        });
7296
7297        // Advance until the connection is established.
7298        net.run_until_idle();
7299
7300        net.with_context(LOCAL, |ctx| {
7301            let mut api = ctx.tcp_api();
7302            assert_eq!(
7303                api.connect(&client_connection, Some(ZonedAddr::Unzoned(server_ip)), PORT),
7304                Ok(())
7305            );
7306
7307            let info = assert_matches!(
7308                api.get_info(&client_connection),
7309                SocketInfo::Connection(info) => info
7310            );
7311            // The local address picked for the connection is link-local, which
7312            // means the device for the connection must also be set (since the
7313            // address requires a zone).
7314            let (local_ip, remote_ip) = assert_matches!(
7315                info,
7316                ConnectionInfo {
7317                    local_addr: SocketAddr { ip: local_ip, port: _ },
7318                    remote_addr: SocketAddr { ip: remote_ip, port: PORT },
7319                    device: Some(FakeWeakDeviceId(FakeDeviceId))
7320                } => (local_ip, remote_ip)
7321            );
7322            assert_eq!(
7323                local_ip,
7324                ZonedAddr::Zoned(
7325                    AddrAndZone::new(client_ip, FakeWeakDeviceId(FakeDeviceId)).unwrap()
7326                )
7327            );
7328            assert_eq!(remote_ip, ZonedAddr::Unzoned(server_ip));
7329
7330            // Double-check that the bound device can't be changed after being set
7331            // implicitly.
7332            assert_matches!(
7333                api.set_device(&client_connection, None),
7334                Err(SetDeviceError::ZoneChange)
7335            );
7336        });
7337    }
7338
7339    #[test]
7340    fn accept_connect_picks_link_local_addr() {
7341        set_logger_for_test();
7342        let server_ip = SpecifiedAddr::new(net_ip_v6!("fe80::1")).unwrap();
7343        let client_ip = SpecifiedAddr::new(net_ip_v6!("1:2:3:4::")).unwrap();
7344        let mut net = FakeTcpNetworkSpec::new_network(
7345            [
7346                (LOCAL, TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(server_ip, client_ip))),
7347                (REMOTE, TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(client_ip, server_ip))),
7348            ],
7349            |net, meta| {
7350                if net == LOCAL {
7351                    alloc::vec![(REMOTE, meta, None)]
7352                } else {
7353                    alloc::vec![(LOCAL, meta, None)]
7354                }
7355            },
7356        );
7357        const PORT: NonZeroU16 = NonZeroU16::new(100).unwrap();
7358        let server_listener = net.with_context(LOCAL, |ctx| {
7359            let mut api = ctx.tcp_api::<Ipv6>();
7360            let socket: TcpSocketId<Ipv6, _, _> = api.create(Default::default());
7361            api.bind(&socket, None, Some(PORT)).expect("failed to bind the client socket");
7362            api.listen(&socket, NonZeroUsize::MIN).expect("can listen");
7363            socket
7364        });
7365        let client_connection = net.with_context(REMOTE, |ctx| {
7366            let mut api = ctx.tcp_api::<Ipv6>();
7367            let socket = api.create(Default::default());
7368            api.connect(
7369                &socket,
7370                Some(ZonedAddr::Zoned(AddrAndZone::new(server_ip, FakeDeviceId).unwrap())),
7371                PORT,
7372            )
7373            .expect("failed to open a connection");
7374            socket
7375        });
7376
7377        // Advance until the connection is established.
7378        net.run_until_idle();
7379
7380        net.with_context(LOCAL, |ctx| {
7381            let mut api = ctx.tcp_api();
7382            let (server_connection, _addr, _buffers) =
7383                api.accept(&server_listener).expect("connection is waiting");
7384
7385            let info = assert_matches!(
7386                api.get_info(&server_connection),
7387                SocketInfo::Connection(info) => info
7388            );
7389            // The local address picked for the connection is link-local, which
7390            // means the device for the connection must also be set (since the
7391            // address requires a zone).
7392            let (local_ip, remote_ip) = assert_matches!(
7393                info,
7394                ConnectionInfo {
7395                    local_addr: SocketAddr { ip: local_ip, port: PORT },
7396                    remote_addr: SocketAddr { ip: remote_ip, port: _ },
7397                    device: Some(FakeWeakDeviceId(FakeDeviceId))
7398                } => (local_ip, remote_ip)
7399            );
7400            assert_eq!(
7401                local_ip,
7402                ZonedAddr::Zoned(
7403                    AddrAndZone::new(server_ip, FakeWeakDeviceId(FakeDeviceId)).unwrap()
7404                )
7405            );
7406            assert_eq!(remote_ip, ZonedAddr::Unzoned(client_ip));
7407
7408            // Double-check that the bound device can't be changed after being set
7409            // implicitly.
7410            assert_matches!(
7411                api.set_device(&server_connection, None),
7412                Err(SetDeviceError::ZoneChange)
7413            );
7414        });
7415        net.with_context(REMOTE, |ctx| {
7416            assert_eq!(
7417                ctx.tcp_api().connect(
7418                    &client_connection,
7419                    Some(ZonedAddr::Zoned(AddrAndZone::new(server_ip, FakeDeviceId).unwrap())),
7420                    PORT,
7421                ),
7422                Ok(())
7423            );
7424        });
7425    }
7426
7427    // The test verifies that if client tries to connect to a closed port on
7428    // server, the connection is aborted and RST is received.
7429    #[ip_test(I)]
7430    fn connect_reset<I: TcpTestIpExt>()
7431    where
7432        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
7433                I,
7434                TcpBindingsCtx<FakeDeviceId>,
7435                SingleStackConverter = I::SingleStackConverter,
7436                DualStackConverter = I::DualStackConverter,
7437            >,
7438    {
7439        set_logger_for_test();
7440        let mut net = new_test_net::<I>();
7441
7442        let client = net.with_context(LOCAL, |ctx| {
7443            let mut api = ctx.tcp_api::<I>();
7444            let conn = api.create(Default::default());
7445            api.bind(&conn, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(PORT_1))
7446                .expect("failed to bind the client socket");
7447            api.connect(&conn, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), PORT_1)
7448                .expect("failed to connect");
7449            conn
7450        });
7451
7452        // Step one time for SYN packet to be delivered.
7453        let _: StepResult = net.step();
7454        // Assert that we got a RST back.
7455        net.collect_frames();
7456        assert_matches!(
7457            &net.iter_pending_frames().collect::<Vec<_>>()[..],
7458            [InstantAndData(_instant, PendingFrameData {
7459                dst_context: _,
7460                meta,
7461                frame,
7462            })] => {
7463            let mut buffer = Buf::new(frame, ..);
7464            match I::VERSION {
7465                IpVersion::V4 => {
7466                    let meta = assert_matches!(meta, DualStackSendIpPacketMeta::V4(v4) => v4);
7467                    let parsed = buffer.parse_with::<_, TcpSegment<_>>(
7468                        TcpParseArgs::new(*meta.src_ip, *meta.dst_ip)
7469                    ).expect("failed to parse");
7470                    assert!(parsed.rst())
7471                }
7472                IpVersion::V6 => {
7473                    let meta = assert_matches!(meta, DualStackSendIpPacketMeta::V6(v6) => v6);
7474                    let parsed = buffer.parse_with::<_, TcpSegment<_>>(
7475                        TcpParseArgs::new(*meta.src_ip, *meta.dst_ip)
7476                    ).expect("failed to parse");
7477                    assert!(parsed.rst())
7478                }
7479            }
7480        });
7481
7482        net.run_until_idle();
7483        // Finally, the connection should be reset and bindings should have been
7484        // signaled.
7485        assert_matches!(
7486            &client.get().deref().socket_state,
7487            TcpSocketStateInner::Connected { conn, .. } => {
7488                let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
7489                assert_matches!(
7490                    conn,
7491                    Connection {
7492                    accept_queue: None,
7493                    state: State::Closed(Closed {
7494                        reason: Some(ConnectionError::ConnectionRefused)
7495                    }),
7496                    ip_sock: _,
7497                    defunct: false,
7498                    soft_error: None,
7499                    handshake_status: HandshakeStatus::Aborted,
7500                    }
7501                );
7502            }
7503        );
7504        net.with_context(LOCAL, |ctx| {
7505            assert_matches!(
7506                ctx.tcp_api().connect(
7507                    &client,
7508                    Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)),
7509                    PORT_1
7510                ),
7511                Err(ConnectError::ConnectionError(ConnectionError::ConnectionRefused))
7512            );
7513            // Connect already yielded the error.
7514            assert_eq!(ctx.tcp_api().get_socket_error(&client), None);
7515        });
7516    }
7517
7518    #[ip_test(I)]
7519    fn retransmission<I: TcpTestIpExt>()
7520    where
7521        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
7522                I,
7523                TcpBindingsCtx<FakeDeviceId>,
7524                SingleStackConverter = I::SingleStackConverter,
7525                DualStackConverter = I::DualStackConverter,
7526            >,
7527    {
7528        set_logger_for_test();
7529        run_with_many_seeds(|seed| {
7530            let (_net, _client, _client_snd_end, _accepted) = bind_listen_connect_accept_inner::<I>(
7531                I::UNSPECIFIED_ADDRESS,
7532                BindConfig {
7533                    client_port: None,
7534                    server_port: PORT_1,
7535                    client_reuse_addr: false,
7536                    send_test_data: true,
7537                },
7538                seed,
7539                0.2,
7540            );
7541        });
7542    }
7543
7544    const LOCAL_PORT: NonZeroU16 = NonZeroU16::new(1845).unwrap();
7545
7546    #[ip_test(I)]
7547    fn listener_with_bound_device_conflict<I: TcpTestIpExt>()
7548    where
7549        TcpCoreCtx<MultipleDevicesId, TcpBindingsCtx<MultipleDevicesId>>:
7550            TcpContext<I, TcpBindingsCtx<MultipleDevicesId>>,
7551    {
7552        set_logger_for_test();
7553        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new_multiple_devices());
7554        let mut api = ctx.tcp_api::<I>();
7555        let sock_a = api.create(Default::default());
7556        assert_matches!(api.set_device(&sock_a, Some(MultipleDevicesId::A),), Ok(()));
7557        api.bind(&sock_a, None, Some(LOCAL_PORT)).expect("bind should succeed");
7558        api.listen(&sock_a, NonZeroUsize::new(10).unwrap()).expect("can listen");
7559
7560        let socket = api.create(Default::default());
7561        // Binding `socket` to the unspecified address should fail since the address
7562        // is shadowed by `sock_a`.
7563        assert_matches!(
7564            api.bind(&socket, None, Some(LOCAL_PORT)),
7565            Err(BindError::LocalAddressError(LocalAddressError::AddressInUse))
7566        );
7567
7568        // Once `socket` is bound to a different device, though, it no longer
7569        // conflicts.
7570        assert_matches!(api.set_device(&socket, Some(MultipleDevicesId::B),), Ok(()));
7571        api.bind(&socket, None, Some(LOCAL_PORT)).expect("no conflict");
7572    }
7573
7574    #[test_case(None)]
7575    #[test_case(Some(MultipleDevicesId::B); "other")]
7576    fn set_bound_device_listener_on_zoned_addr(set_device: Option<MultipleDevicesId>) {
7577        set_logger_for_test();
7578        let ll_addr = LinkLocalAddr::new(Ipv6::LINK_LOCAL_UNICAST_SUBNET.network()).unwrap();
7579
7580        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::with_ip_socket_ctx_state(
7581            FakeDualStackIpSocketCtx::new(MultipleDevicesId::all().into_iter().map(|device| {
7582                FakeDeviceConfig {
7583                    device,
7584                    local_ips: vec![ll_addr.into_specified()],
7585                    remote_ips: vec![ll_addr.into_specified()],
7586                }
7587            })),
7588        ));
7589        let mut api = ctx.tcp_api::<Ipv6>();
7590        let socket = api.create(Default::default());
7591        api.bind(
7592            &socket,
7593            Some(ZonedAddr::Zoned(
7594                AddrAndZone::new(ll_addr.into_specified(), MultipleDevicesId::A).unwrap(),
7595            )),
7596            Some(LOCAL_PORT),
7597        )
7598        .expect("bind should succeed");
7599
7600        assert_matches!(api.set_device(&socket, set_device), Err(SetDeviceError::ZoneChange));
7601    }
7602
7603    #[test_case(None)]
7604    #[test_case(Some(MultipleDevicesId::B); "other")]
7605    fn set_bound_device_connected_to_zoned_addr(set_device: Option<MultipleDevicesId>) {
7606        set_logger_for_test();
7607        let ll_addr = LinkLocalAddr::new(Ipv6::LINK_LOCAL_UNICAST_SUBNET.network()).unwrap();
7608
7609        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::with_ip_socket_ctx_state(
7610            FakeDualStackIpSocketCtx::new(MultipleDevicesId::all().into_iter().map(|device| {
7611                FakeDeviceConfig {
7612                    device,
7613                    local_ips: vec![ll_addr.into_specified()],
7614                    remote_ips: vec![ll_addr.into_specified()],
7615                }
7616            })),
7617        ));
7618        let mut api = ctx.tcp_api::<Ipv6>();
7619        let socket = api.create(Default::default());
7620        api.connect(
7621            &socket,
7622            Some(ZonedAddr::Zoned(
7623                AddrAndZone::new(ll_addr.into_specified(), MultipleDevicesId::A).unwrap(),
7624            )),
7625            LOCAL_PORT,
7626        )
7627        .expect("connect should succeed");
7628
7629        assert_matches!(api.set_device(&socket, set_device), Err(SetDeviceError::ZoneChange));
7630    }
7631
7632    // Regression test for https://fxbug.dev/388656903.
7633    #[ip_test(I)]
7634    fn set_bound_to_device_after_connect_fails<I: TcpTestIpExt>()
7635    where
7636        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7637            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7638    {
7639        set_logger_for_test();
7640        let mut net = new_test_net::<I>();
7641        let socket = net.with_context(LOCAL, |ctx| {
7642            let mut api = ctx.tcp_api::<I>();
7643            let socket = api.create(Default::default());
7644            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), PORT_1)
7645                .expect("bind should succeed");
7646            socket
7647        });
7648
7649        net.run_until_idle();
7650
7651        net.with_context(LOCAL, |ctx| {
7652            let mut api = ctx.tcp_api::<I>();
7653            assert_matches!(api.set_device(&socket, Some(FakeDeviceId)), Ok(()));
7654            let ConnectionInfo { local_addr: _, remote_addr, device } =
7655                assert_matches!(api.get_info(&socket), SocketInfo::Connection(c) => c);
7656            assert_eq!(
7657                remote_addr,
7658                SocketAddr { ip: ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip), port: PORT_1 }
7659            );
7660            assert_eq!(device, Some(FakeWeakDeviceId(FakeDeviceId)));
7661            api.close(socket);
7662        });
7663    }
7664
7665    #[ip_test(I)]
7666    #[test_case(*<I as TestIpExt>::TEST_ADDRS.local_ip, true; "specified bound")]
7667    #[test_case(I::UNSPECIFIED_ADDRESS, true; "unspecified bound")]
7668    #[test_case(*<I as TestIpExt>::TEST_ADDRS.local_ip, false; "specified listener")]
7669    #[test_case(I::UNSPECIFIED_ADDRESS, false; "unspecified listener")]
7670    fn bound_socket_info<I: TcpTestIpExt>(ip_addr: I::Addr, listen: bool)
7671    where
7672        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7673            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7674    {
7675        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
7676            I::TEST_ADDRS.local_ip,
7677            I::TEST_ADDRS.remote_ip,
7678        ));
7679        let mut api = ctx.tcp_api::<I>();
7680        let socket = api.create(Default::default());
7681
7682        let (addr, port) = (SpecifiedAddr::new(ip_addr).map(ZonedAddr::Unzoned), PORT_1);
7683
7684        api.bind(&socket, addr, Some(port)).expect("bind should succeed");
7685        if listen {
7686            api.listen(&socket, NonZeroUsize::new(25).unwrap()).expect("can listen");
7687        }
7688        let info = api.get_info(&socket);
7689        assert_eq!(
7690            info,
7691            SocketInfo::Bound(BoundInfo {
7692                addr: addr.map(|a| a.map_zone(FakeWeakDeviceId)),
7693                port,
7694                device: None
7695            })
7696        );
7697    }
7698
7699    #[ip_test(I)]
7700    fn connection_info<I: TcpTestIpExt>()
7701    where
7702        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7703            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7704    {
7705        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
7706            I::TEST_ADDRS.local_ip,
7707            I::TEST_ADDRS.remote_ip,
7708        ));
7709        let mut api = ctx.tcp_api::<I>();
7710        let local = SocketAddr { ip: ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip), port: PORT_1 };
7711        let remote = SocketAddr { ip: ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip), port: PORT_2 };
7712
7713        let socket = api.create(Default::default());
7714        api.bind(&socket, Some(local.ip), Some(local.port)).expect("bind should succeed");
7715
7716        api.connect(&socket, Some(remote.ip), remote.port).expect("connect should succeed");
7717
7718        assert_eq!(
7719            api.get_info(&socket),
7720            SocketInfo::Connection(ConnectionInfo {
7721                local_addr: local.map_zone(FakeWeakDeviceId),
7722                remote_addr: remote.map_zone(FakeWeakDeviceId),
7723                device: None,
7724            }),
7725        );
7726    }
7727
7728    #[test_case(Ipv6::get_multicast_addr(1).into(), PhantomData::<Ipv6>)]
7729    #[test_case(Ipv4::get_multicast_addr(1).into(), PhantomData::<Ipv4>)]
7730    #[test_case(Ipv4::LIMITED_BROADCAST_ADDRESS, PhantomData::<Ipv4>)]
7731    fn non_unicast_ip_bind<I>(local_ip: SpecifiedAddr<I::Addr>, _ip: PhantomData<I>)
7732    where
7733        I: TcpTestIpExt + Ip,
7734        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7735            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7736    {
7737        let mut ctx =
7738            TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(local_ip, I::TEST_ADDRS.remote_ip));
7739        let mut api = ctx.tcp_api::<I>();
7740        let local = SocketAddr { ip: ZonedAddr::Unzoned(local_ip), port: PORT_1 };
7741        let socket = api.create(Default::default());
7742
7743        assert_eq!(
7744            api.bind(&socket, Some(local.ip), Some(local.port))
7745                .expect_err("bind should fail for non-unicast address"),
7746            BindError::LocalAddressError(LocalAddressError::CannotBindToAddress)
7747        );
7748    }
7749
7750    #[test_case(Ipv6::get_multicast_addr(1).into(), PhantomData::<Ipv6>)]
7751    #[test_case(Ipv4::get_multicast_addr(1).into(), PhantomData::<Ipv4>)]
7752    #[test_case(Ipv4::LIMITED_BROADCAST_ADDRESS, PhantomData::<Ipv4>)]
7753    fn non_unicast_ip_peer<I>(remote_ip: SpecifiedAddr<I::Addr>, _ip: PhantomData<I>)
7754    where
7755        I: TcpTestIpExt + Ip,
7756        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
7757            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
7758    {
7759        let mut ctx =
7760            TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(I::TEST_ADDRS.local_ip, remote_ip));
7761        let mut api = ctx.tcp_api::<I>();
7762        let remote = SocketAddr { ip: ZonedAddr::Unzoned(remote_ip), port: PORT_2 };
7763        let socket = api.create(Default::default());
7764
7765        assert_eq!(
7766            api.connect(&socket, Some(remote.ip), remote.port)
7767                .expect_err("connect should fail for non-unicast peer"),
7768            ConnectError::NoRoute
7769        );
7770    }
7771
7772    #[test_case(true; "any")]
7773    #[test_case(false; "link local")]
7774    fn accepted_connection_info_zone(listen_any: bool) {
7775        set_logger_for_test();
7776        let client_ip = SpecifiedAddr::new(net_ip_v6!("fe80::1")).unwrap();
7777        let server_ip = SpecifiedAddr::new(net_ip_v6!("fe80::2")).unwrap();
7778        let mut net = FakeTcpNetworkSpec::new_network(
7779            [
7780                (LOCAL, TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(server_ip, client_ip))),
7781                (REMOTE, TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(client_ip, server_ip))),
7782            ],
7783            move |net, meta: DualStackSendIpPacketMeta<_>| {
7784                if net == LOCAL {
7785                    alloc::vec![(REMOTE, meta, None)]
7786                } else {
7787                    alloc::vec![(LOCAL, meta, None)]
7788                }
7789            },
7790        );
7791
7792        let local_server = net.with_context(LOCAL, |ctx| {
7793            let mut api = ctx.tcp_api::<Ipv6>();
7794            let socket = api.create(Default::default());
7795            let device = FakeDeviceId;
7796            let bind_addr = match listen_any {
7797                true => None,
7798                false => Some(ZonedAddr::Zoned(AddrAndZone::new(server_ip, device).unwrap())),
7799            };
7800
7801            api.bind(&socket, bind_addr, Some(PORT_1)).expect("failed to bind the client socket");
7802            api.listen(&socket, NonZeroUsize::new(1).unwrap()).expect("can listen");
7803            socket
7804        });
7805
7806        let _remote_client = net.with_context(REMOTE, |ctx| {
7807            let mut api = ctx.tcp_api::<Ipv6>();
7808            let socket = api.create(Default::default());
7809            let device = FakeDeviceId;
7810            api.connect(
7811                &socket,
7812                Some(ZonedAddr::Zoned(AddrAndZone::new(server_ip, device).unwrap())),
7813                PORT_1,
7814            )
7815            .expect("failed to connect");
7816            socket
7817        });
7818
7819        net.run_until_idle();
7820
7821        let ConnectionInfo { remote_addr, local_addr, device } = net.with_context(LOCAL, |ctx| {
7822            let mut api = ctx.tcp_api();
7823            let (server_conn, _addr, _buffers) =
7824                api.accept(&local_server).expect("connection is available");
7825            assert_matches!(
7826                api.get_info(&server_conn),
7827                SocketInfo::Connection(info) => info
7828            )
7829        });
7830
7831        let device = assert_matches!(device, Some(device) => device);
7832        assert_eq!(
7833            local_addr,
7834            SocketAddr {
7835                ip: ZonedAddr::Zoned(AddrAndZone::new(server_ip, device).unwrap()),
7836                port: PORT_1
7837            }
7838        );
7839        let SocketAddr { ip: remote_ip, port: _ } = remote_addr;
7840        assert_eq!(remote_ip, ZonedAddr::Zoned(AddrAndZone::new(client_ip, device).unwrap()));
7841    }
7842
7843    #[test]
7844    fn bound_connection_info_zoned_addrs() {
7845        let local_ip = LinkLocalAddr::new(net_ip_v6!("fe80::1")).unwrap().into_specified();
7846        let remote_ip = LinkLocalAddr::new(net_ip_v6!("fe80::2")).unwrap().into_specified();
7847        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<Ipv6>(local_ip, remote_ip));
7848
7849        let local_addr = SocketAddr {
7850            ip: ZonedAddr::Zoned(AddrAndZone::new(local_ip, FakeDeviceId).unwrap()),
7851            port: PORT_1,
7852        };
7853        let remote_addr = SocketAddr {
7854            ip: ZonedAddr::Zoned(AddrAndZone::new(remote_ip, FakeDeviceId).unwrap()),
7855            port: PORT_2,
7856        };
7857        let mut api = ctx.tcp_api::<Ipv6>();
7858
7859        let socket = api.create(Default::default());
7860        api.bind(&socket, Some(local_addr.ip), Some(local_addr.port)).expect("bind should succeed");
7861
7862        assert_eq!(
7863            api.get_info(&socket),
7864            SocketInfo::Bound(BoundInfo {
7865                addr: Some(local_addr.ip.map_zone(FakeWeakDeviceId)),
7866                port: local_addr.port,
7867                device: Some(FakeWeakDeviceId(FakeDeviceId))
7868            })
7869        );
7870
7871        api.connect(&socket, Some(remote_addr.ip), remote_addr.port)
7872            .expect("connect should succeed");
7873
7874        assert_eq!(
7875            api.get_info(&socket),
7876            SocketInfo::Connection(ConnectionInfo {
7877                local_addr: local_addr.map_zone(FakeWeakDeviceId),
7878                remote_addr: remote_addr.map_zone(FakeWeakDeviceId),
7879                device: Some(FakeWeakDeviceId(FakeDeviceId))
7880            })
7881        );
7882    }
7883
7884    #[ip_test(I)]
7885    // Assuming instant delivery of segments:
7886    // - If peer calls close, then the timeout we need to wait is in
7887    // TIME_WAIT, which is 2MSL.
7888    #[test_case(true, 2 * MSL; "peer calls close")]
7889    // - If not, we will be in the FIN_WAIT2 state and waiting for its
7890    // timeout.
7891    #[test_case(false, DEFAULT_FIN_WAIT2_TIMEOUT; "peer doesn't call close")]
7892    fn connection_close_peer_calls_close<I: TcpTestIpExt>(
7893        peer_calls_close: bool,
7894        expected_time_to_close: Duration,
7895    ) where
7896        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
7897                I,
7898                TcpBindingsCtx<FakeDeviceId>,
7899                SingleStackConverter = I::SingleStackConverter,
7900                DualStackConverter = I::DualStackConverter,
7901            >,
7902    {
7903        set_logger_for_test();
7904        let (mut net, local, _local_snd_end, remote) = bind_listen_connect_accept_inner::<I>(
7905            I::UNSPECIFIED_ADDRESS,
7906            BindConfig {
7907                client_port: None,
7908                server_port: PORT_1,
7909                client_reuse_addr: false,
7910                send_test_data: false,
7911            },
7912            0,
7913            0.0,
7914        );
7915
7916        let weak_local = local.downgrade();
7917        let close_called = net.with_context(LOCAL, |ctx| {
7918            ctx.tcp_api().close(local);
7919            ctx.bindings_ctx.now()
7920        });
7921
7922        while {
7923            assert!(!net.step().is_idle());
7924            let is_fin_wait_2 = {
7925                let local = weak_local.upgrade().unwrap();
7926                let state = local.get();
7927                let state = assert_matches!(
7928                    &state.deref().socket_state,
7929                    TcpSocketStateInner::Connected { conn, .. } => {
7930                    let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
7931                    assert_matches!(
7932                        conn,
7933                        Connection {
7934                            state,
7935                            ..
7936                        } => state
7937                    )
7938                }
7939                );
7940                matches!(state, State::FinWait2(_))
7941            };
7942            !is_fin_wait_2
7943        } {}
7944
7945        let weak_remote = remote.downgrade();
7946        if peer_calls_close {
7947            net.with_context(REMOTE, |ctx| {
7948                ctx.tcp_api().close(remote);
7949            });
7950        }
7951
7952        net.run_until_idle();
7953
7954        net.with_context(LOCAL, |TcpCtx { core_ctx: _, bindings_ctx }| {
7955            assert_eq!(
7956                bindings_ctx.now().checked_duration_since(close_called).unwrap(),
7957                expected_time_to_close
7958            );
7959            assert_eq!(weak_local.upgrade(), None);
7960        });
7961        if peer_calls_close {
7962            assert_eq!(weak_remote.upgrade(), None);
7963        }
7964    }
7965
7966    #[ip_test(I)]
7967    fn connection_shutdown_then_close_peer_doesnt_call_close<I: TcpTestIpExt>()
7968    where
7969        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
7970                I,
7971                TcpBindingsCtx<FakeDeviceId>,
7972                SingleStackConverter = I::SingleStackConverter,
7973                DualStackConverter = I::DualStackConverter,
7974            >,
7975    {
7976        set_logger_for_test();
7977        let (mut net, local, _local_snd_end, _remote) = bind_listen_connect_accept_inner::<I>(
7978            I::UNSPECIFIED_ADDRESS,
7979            BindConfig {
7980                client_port: None,
7981                server_port: PORT_1,
7982                client_reuse_addr: false,
7983                send_test_data: false,
7984            },
7985            0,
7986            0.0,
7987        );
7988        net.with_context(LOCAL, |ctx| {
7989            assert_eq!(ctx.tcp_api().shutdown(&local, ShutdownType::Send), Ok(true));
7990        });
7991        loop {
7992            assert!(!net.step().is_idle());
7993            let is_fin_wait_2 = {
7994                let state = local.get();
7995                let state = assert_matches!(
7996                &state.deref().socket_state,
7997                TcpSocketStateInner::Connected { conn, .. } => {
7998                let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
7999                assert_matches!(
8000                    conn,
8001                    Connection {
8002                        state, ..
8003                    } => state
8004                )});
8005                matches!(state, State::FinWait2(_))
8006            };
8007            if is_fin_wait_2 {
8008                break;
8009            }
8010        }
8011
8012        let weak_local = local.downgrade();
8013        net.with_context(LOCAL, |ctx| {
8014            ctx.tcp_api().close(local);
8015        });
8016        net.run_until_idle();
8017        assert_eq!(weak_local.upgrade(), None);
8018    }
8019
8020    #[ip_test(I)]
8021    fn connection_shutdown_then_close<I: TcpTestIpExt>()
8022    where
8023        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
8024                I,
8025                TcpBindingsCtx<FakeDeviceId>,
8026                SingleStackConverter = I::SingleStackConverter,
8027                DualStackConverter = I::DualStackConverter,
8028            >,
8029    {
8030        set_logger_for_test();
8031        let (mut net, local, _local_snd_end, remote) = bind_listen_connect_accept_inner::<I>(
8032            I::UNSPECIFIED_ADDRESS,
8033            BindConfig {
8034                client_port: None,
8035                server_port: PORT_1,
8036                client_reuse_addr: false,
8037                send_test_data: false,
8038            },
8039            0,
8040            0.0,
8041        );
8042
8043        for (name, id) in [(LOCAL, &local), (REMOTE, &remote)] {
8044            net.with_context(name, |ctx| {
8045                let mut api = ctx.tcp_api();
8046                assert_eq!(
8047                    api.shutdown(id,ShutdownType::Send),
8048                    Ok(true)
8049                );
8050                assert_matches!(
8051                    &id.get().deref().socket_state,
8052                    TcpSocketStateInner::Connected { conn, .. } => {
8053                    let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
8054                    assert_matches!(
8055                        conn,
8056                        Connection {
8057                            state: State::FinWait1(_),
8058                            ..
8059                        }
8060                    );
8061                });
8062                assert_eq!(
8063                    api.shutdown(id,ShutdownType::Send),
8064                    Ok(true)
8065                );
8066            });
8067        }
8068        net.run_until_idle();
8069        for (name, id) in [(LOCAL, local), (REMOTE, remote)] {
8070            net.with_context(name, |ctx| {
8071                assert_matches!(
8072                    &id.get().deref().socket_state,
8073                    TcpSocketStateInner::Connected { conn, .. } => {
8074                    let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
8075                    assert_matches!(
8076                        conn,
8077                        Connection {
8078                            state: State::Closed(_),
8079                            ..
8080                        }
8081                    );
8082                });
8083                let weak_id = id.downgrade();
8084                ctx.tcp_api().close(id);
8085                assert_eq!(weak_id.upgrade(), None)
8086            });
8087        }
8088    }
8089
8090    #[ip_test(I)]
8091    fn remove_unbound<I: TcpTestIpExt>()
8092    where
8093        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8094            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8095    {
8096        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8097            I::TEST_ADDRS.local_ip,
8098            I::TEST_ADDRS.remote_ip,
8099        ));
8100        let mut api = ctx.tcp_api::<I>();
8101        let unbound = api.create(Default::default());
8102        let weak_unbound = unbound.downgrade();
8103        api.close(unbound);
8104        assert_eq!(weak_unbound.upgrade(), None);
8105    }
8106
8107    #[ip_test(I)]
8108    fn remove_bound<I: TcpTestIpExt>()
8109    where
8110        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8111            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8112    {
8113        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8114            I::TEST_ADDRS.local_ip,
8115            I::TEST_ADDRS.remote_ip,
8116        ));
8117        let mut api = ctx.tcp_api::<I>();
8118        let socket = api.create(Default::default());
8119        api.bind(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), None)
8120            .expect("bind should succeed");
8121        let weak_socket = socket.downgrade();
8122        api.close(socket);
8123        assert_eq!(weak_socket.upgrade(), None);
8124    }
8125
8126    #[ip_test(I)]
8127    fn shutdown_listener<I: TcpTestIpExt>()
8128    where
8129        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
8130                I,
8131                TcpBindingsCtx<FakeDeviceId>,
8132                SingleStackConverter = I::SingleStackConverter,
8133                DualStackConverter = I::DualStackConverter,
8134            >,
8135    {
8136        set_logger_for_test();
8137        let mut net = new_test_net::<I>();
8138        let local_listener = net.with_context(LOCAL, |ctx| {
8139            let mut api = ctx.tcp_api::<I>();
8140            let socket = api.create(Default::default());
8141            api.bind(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(PORT_1))
8142                .expect("bind should succeed");
8143            api.listen(&socket, NonZeroUsize::new(5).unwrap()).expect("can listen");
8144            socket
8145        });
8146
8147        let remote_connection = net.with_context(REMOTE, |ctx| {
8148            let mut api = ctx.tcp_api::<I>();
8149            let socket = api.create(Default::default());
8150            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), PORT_1)
8151                .expect("connect should succeed");
8152            socket
8153        });
8154
8155        // After the following step, we should have one established connection
8156        // in the listener's accept queue, which ought to be aborted during
8157        // shutdown.
8158        net.run_until_idle();
8159
8160        // The incoming connection was signaled, and the remote end was notified
8161        // of connection establishment.
8162        net.with_context(REMOTE, |ctx| {
8163            assert_eq!(
8164                ctx.tcp_api().connect(
8165                    &remote_connection,
8166                    Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)),
8167                    PORT_1
8168                ),
8169                Ok(())
8170            );
8171        });
8172
8173        // Create a second half-open connection so that we have one entry in the
8174        // pending queue.
8175        let second_connection = net.with_context(REMOTE, |ctx| {
8176            let mut api = ctx.tcp_api::<I>();
8177            let socket = api.create(Default::default());
8178            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), PORT_1)
8179                .expect("connect should succeed");
8180            socket
8181        });
8182
8183        let _: StepResult = net.step();
8184
8185        // We have a timer scheduled for the pending connection.
8186        net.with_context(LOCAL, |TcpCtx { core_ctx: _, bindings_ctx }| {
8187            assert_matches!(bindings_ctx.timers.timers().len(), 1);
8188        });
8189
8190        net.with_context(LOCAL, |ctx| {
8191            assert_eq!(ctx.tcp_api().shutdown(&local_listener, ShutdownType::Receive,), Ok(false));
8192        });
8193
8194        // The timer for the pending connection should be cancelled.
8195        net.with_context(LOCAL, |TcpCtx { core_ctx: _, bindings_ctx }| {
8196            assert_eq!(bindings_ctx.timers.timers().len(), 0);
8197        });
8198
8199        net.run_until_idle();
8200
8201        // Both remote sockets should now be reset to Closed state.
8202        net.with_context(REMOTE, |ctx| {
8203            for conn in [&remote_connection, &second_connection] {
8204                assert_eq!(
8205                    ctx.tcp_api().get_socket_error(conn),
8206                    Some(ConnectionError::ConnectionReset),
8207                )
8208            }
8209
8210            assert_matches!(
8211                &remote_connection.get().deref().socket_state,
8212                TcpSocketStateInner::Connected { conn, .. } => {
8213                        let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
8214                        assert_matches!(
8215                            conn,
8216                            Connection {
8217                                state: State::Closed(Closed {
8218                                    // Error was cleared by get_socket_error.
8219                                    reason: None
8220                                }),
8221                                ..
8222                            }
8223                        );
8224                    }
8225            );
8226        });
8227
8228        net.with_context(LOCAL, |ctx| {
8229            let mut api = ctx.tcp_api::<I>();
8230            let new_unbound = api.create(Default::default());
8231            assert_matches!(
8232                api.bind(
8233                    &new_unbound,
8234                    Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip,)),
8235                    Some(PORT_1),
8236                ),
8237                Err(BindError::LocalAddressError(LocalAddressError::AddressInUse))
8238            );
8239            // Bring the already-shutdown listener back to listener again.
8240            api.listen(&local_listener, NonZeroUsize::new(5).unwrap()).expect("can listen again");
8241        });
8242
8243        let new_remote_connection = net.with_context(REMOTE, |ctx| {
8244            let mut api = ctx.tcp_api::<I>();
8245            let socket = api.create(Default::default());
8246            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), PORT_1)
8247                .expect("connect should succeed");
8248            socket
8249        });
8250
8251        net.run_until_idle();
8252
8253        net.with_context(REMOTE, |ctx| {
8254            assert_matches!(
8255                &new_remote_connection.get().deref().socket_state,
8256                TcpSocketStateInner::Connected { conn, .. } => {
8257                    let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
8258                    assert_matches!(
8259                        conn,
8260                        Connection {
8261                            state: State::Established(_),
8262                            ..
8263                        }
8264                    );
8265                    });
8266            assert_eq!(
8267                ctx.tcp_api().connect(
8268                    &new_remote_connection,
8269                    Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)),
8270                    PORT_1,
8271                ),
8272                Ok(())
8273            );
8274        });
8275    }
8276
8277    #[ip_test(I)]
8278    fn clamp_buffer_size<I: TcpTestIpExt>()
8279    where
8280        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8281            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8282    {
8283        set_logger_for_test();
8284        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8285            I::TEST_ADDRS.local_ip,
8286            I::TEST_ADDRS.remote_ip,
8287        ));
8288        let mut api = ctx.tcp_api::<I>();
8289        let socket = api.create(Default::default());
8290
8291        let (min, max) =
8292            SettingsContext::<TcpSettings>::settings(&ctx.bindings_ctx).send_buffer.min_max();
8293        let mut api = ctx.tcp_api::<I>();
8294        api.set_send_buffer_size(&socket, min.get() - 1);
8295        assert_eq!(api.send_buffer_size(&socket), Some(min.get()));
8296        api.set_send_buffer_size(&socket, max.get() + 1);
8297        assert_eq!(api.send_buffer_size(&socket), Some(max.get()));
8298
8299        let (min, max) =
8300            SettingsContext::<TcpSettings>::settings(&ctx.bindings_ctx).receive_buffer.min_max();
8301        let mut api = ctx.tcp_api::<I>();
8302        api.set_receive_buffer_size(&socket, min.get() - 1);
8303        assert_eq!(api.receive_buffer_size(&socket), Some(min.get()));
8304        api.set_receive_buffer_size(&socket, max.get() + 1);
8305        assert_eq!(api.receive_buffer_size(&socket), Some(max.get()));
8306    }
8307
8308    #[ip_test(I)]
8309    fn set_reuseaddr_unbound<I: TcpTestIpExt>()
8310    where
8311        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8312            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8313    {
8314        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8315            I::TEST_ADDRS.local_ip,
8316            I::TEST_ADDRS.remote_ip,
8317        ));
8318        let mut api = ctx.tcp_api::<I>();
8319
8320        let first_bound = {
8321            let socket = api.create(Default::default());
8322            api.set_reuseaddr(&socket, true).expect("can set");
8323            api.bind(&socket, None, None).expect("bind succeeds");
8324            socket
8325        };
8326        let _second_bound = {
8327            let socket = api.create(Default::default());
8328            api.set_reuseaddr(&socket, true).expect("can set");
8329            api.bind(&socket, None, None).expect("bind succeeds");
8330            socket
8331        };
8332
8333        api.listen(&first_bound, NonZeroUsize::new(10).unwrap()).expect("can listen");
8334    }
8335
8336    #[ip_test(I)]
8337    #[test_case([true, true], Ok(()); "allowed with set")]
8338    #[test_case([false, true], Err(LocalAddressError::AddressInUse); "first unset")]
8339    #[test_case([true, false], Err(LocalAddressError::AddressInUse); "second unset")]
8340    #[test_case([false, false], Err(LocalAddressError::AddressInUse); "both unset")]
8341    fn reuseaddr_multiple_bound<I: TcpTestIpExt>(
8342        set_reuseaddr: [bool; 2],
8343        expected: Result<(), LocalAddressError>,
8344    ) where
8345        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8346            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8347    {
8348        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8349            I::TEST_ADDRS.local_ip,
8350            I::TEST_ADDRS.remote_ip,
8351        ));
8352        let mut api = ctx.tcp_api::<I>();
8353
8354        let first = api.create(Default::default());
8355        api.set_reuseaddr(&first, set_reuseaddr[0]).expect("can set");
8356        api.bind(&first, None, Some(PORT_1)).expect("bind succeeds");
8357
8358        let second = api.create(Default::default());
8359        api.set_reuseaddr(&second, set_reuseaddr[1]).expect("can set");
8360        let second_bind_result = api.bind(&second, None, Some(PORT_1));
8361
8362        assert_eq!(second_bind_result, expected.map_err(From::from));
8363    }
8364
8365    #[ip_test(I)]
8366    fn toggle_reuseaddr_bound_different_addrs<I: TcpTestIpExt>()
8367    where
8368        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8369            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8370    {
8371        let addrs = [1, 2].map(|i| I::get_other_ip_address(i));
8372        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::with_ip_socket_ctx_state(
8373            FakeDualStackIpSocketCtx::new(core::iter::once(FakeDeviceConfig {
8374                device: FakeDeviceId,
8375                local_ips: addrs.iter().cloned().map(SpecifiedAddr::<IpAddr>::from).collect(),
8376                remote_ips: Default::default(),
8377            })),
8378        ));
8379        let mut api = ctx.tcp_api::<I>();
8380
8381        let first = api.create(Default::default());
8382        api.bind(&first, Some(ZonedAddr::Unzoned(addrs[0])), Some(PORT_1)).unwrap();
8383
8384        let second = api.create(Default::default());
8385        api.bind(&second, Some(ZonedAddr::Unzoned(addrs[1])), Some(PORT_1)).unwrap();
8386        // Setting and un-setting ReuseAddr should be fine since these sockets
8387        // don't conflict.
8388        api.set_reuseaddr(&first, true).expect("can set");
8389        api.set_reuseaddr(&first, false).expect("can un-set");
8390    }
8391
8392    #[ip_test(I)]
8393    fn unset_reuseaddr_bound_unspecified_specified<I: TcpTestIpExt>()
8394    where
8395        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8396            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8397    {
8398        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8399            I::TEST_ADDRS.local_ip,
8400            I::TEST_ADDRS.remote_ip,
8401        ));
8402        let mut api = ctx.tcp_api::<I>();
8403        let first = api.create(Default::default());
8404        api.set_reuseaddr(&first, true).expect("can set");
8405        api.bind(&first, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(PORT_1)).unwrap();
8406
8407        let second = api.create(Default::default());
8408        api.set_reuseaddr(&second, true).expect("can set");
8409        api.bind(&second, None, Some(PORT_1)).unwrap();
8410
8411        // Both sockets can be bound because they have ReuseAddr set. Since
8412        // removing it would introduce inconsistent state, that's not allowed.
8413        assert_matches!(api.set_reuseaddr(&first, false), Err(SetReuseAddrError::AddrInUse));
8414        assert_matches!(api.set_reuseaddr(&second, false), Err(SetReuseAddrError::AddrInUse));
8415    }
8416
8417    #[ip_test(I)]
8418    fn reuseaddr_allows_binding_under_connection<I: TcpTestIpExt>()
8419    where
8420        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8421            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8422    {
8423        set_logger_for_test();
8424        let mut net = new_test_net::<I>();
8425
8426        let server = net.with_context(LOCAL, |ctx| {
8427            let mut api = ctx.tcp_api::<I>();
8428            let server = api.create(Default::default());
8429            api.set_reuseaddr(&server, true).expect("can set");
8430            api.bind(&server, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(PORT_1))
8431                .expect("failed to bind the client socket");
8432            api.listen(&server, NonZeroUsize::new(10).unwrap()).expect("can listen");
8433            server
8434        });
8435
8436        let client = net.with_context(REMOTE, |ctx| {
8437            let mut api = ctx.tcp_api::<I>();
8438            let client = api.create(Default::default());
8439            api.connect(&client, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), PORT_1)
8440                .expect("connect should succeed");
8441            client
8442        });
8443        // Finish the connection establishment.
8444        net.run_until_idle();
8445        net.with_context(REMOTE, |ctx| {
8446            assert_eq!(
8447                ctx.tcp_api().connect(
8448                    &client,
8449                    Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)),
8450                    PORT_1
8451                ),
8452                Ok(())
8453            );
8454        });
8455
8456        // Now accept the connection and close the listening socket. Then
8457        // binding a new socket on the same local address should fail unless the
8458        // socket has SO_REUSEADDR set.
8459        net.with_context(LOCAL, |ctx| {
8460            let mut api = ctx.tcp_api();
8461            let (_server_conn, _, _): (_, SocketAddr<_, _>, ClientBuffers) =
8462                api.accept(&server).expect("pending connection");
8463
8464            assert_eq!(api.shutdown(&server, ShutdownType::Receive), Ok(false));
8465            api.close(server);
8466
8467            let unbound = api.create(Default::default());
8468            assert_eq!(
8469                api.bind(&unbound, None, Some(PORT_1)),
8470                Err(BindError::LocalAddressError(LocalAddressError::AddressInUse))
8471            );
8472
8473            // Binding should succeed after setting ReuseAddr.
8474            api.set_reuseaddr(&unbound, true).expect("can set");
8475            api.bind(&unbound, None, Some(PORT_1)).expect("bind succeeds");
8476        });
8477    }
8478
8479    #[ip_test(I)]
8480    #[test_case([true, true]; "specified specified")]
8481    #[test_case([false, true]; "any specified")]
8482    #[test_case([true, false]; "specified any")]
8483    #[test_case([false, false]; "any any")]
8484    fn set_reuseaddr_bound_allows_other_bound<I: TcpTestIpExt>(bind_specified: [bool; 2])
8485    where
8486        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8487            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8488    {
8489        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8490            I::TEST_ADDRS.local_ip,
8491            I::TEST_ADDRS.remote_ip,
8492        ));
8493        let mut api = ctx.tcp_api::<I>();
8494
8495        let [first_addr, second_addr] =
8496            bind_specified.map(|b| b.then_some(I::TEST_ADDRS.local_ip).map(ZonedAddr::Unzoned));
8497        let first_bound = {
8498            let socket = api.create(Default::default());
8499            api.bind(&socket, first_addr, Some(PORT_1)).expect("bind succeeds");
8500            socket
8501        };
8502
8503        let second = api.create(Default::default());
8504
8505        // Binding the second socket will fail because the first doesn't have
8506        // SO_REUSEADDR set.
8507        assert_matches!(
8508            api.bind(&second, second_addr, Some(PORT_1)),
8509            Err(BindError::LocalAddressError(LocalAddressError::AddressInUse))
8510        );
8511
8512        // Setting SO_REUSEADDR for the second socket isn't enough.
8513        api.set_reuseaddr(&second, true).expect("can set");
8514        assert_matches!(
8515            api.bind(&second, second_addr, Some(PORT_1)),
8516            Err(BindError::LocalAddressError(LocalAddressError::AddressInUse))
8517        );
8518
8519        // Setting SO_REUSEADDR for the first socket lets the second bind.
8520        api.set_reuseaddr(&first_bound, true).expect("only socket");
8521        api.bind(&second, second_addr, Some(PORT_1)).expect("can bind");
8522    }
8523
8524    #[ip_test(I)]
8525    fn clear_reuseaddr_listener<I: TcpTestIpExt>()
8526    where
8527        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
8528            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
8529    {
8530        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8531            I::TEST_ADDRS.local_ip,
8532            I::TEST_ADDRS.remote_ip,
8533        ));
8534        let mut api = ctx.tcp_api::<I>();
8535
8536        let bound = {
8537            let socket = api.create(Default::default());
8538            api.set_reuseaddr(&socket, true).expect("can set");
8539            api.bind(&socket, None, Some(PORT_1)).expect("bind succeeds");
8540            socket
8541        };
8542
8543        let listener = {
8544            let socket = api.create(Default::default());
8545            api.set_reuseaddr(&socket, true).expect("can set");
8546
8547            api.bind(&socket, None, Some(PORT_1)).expect("bind succeeds");
8548            api.listen(&socket, NonZeroUsize::new(5).unwrap()).expect("can listen");
8549            socket
8550        };
8551
8552        // We can't clear SO_REUSEADDR on the listener because it's sharing with
8553        // the bound socket.
8554        assert_matches!(api.set_reuseaddr(&listener, false), Err(SetReuseAddrError::AddrInUse));
8555
8556        // We can, however, connect to the listener with the bound socket. Then
8557        // the unencumbered listener can clear SO_REUSEADDR.
8558        api.connect(&bound, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), PORT_1)
8559            .expect("can connect");
8560        api.set_reuseaddr(&listener, false).expect("can unset")
8561    }
8562
8563    fn deliver_icmp_error<
8564        I: TcpTestIpExt + IcmpIpExt,
8565        CC: TcpContext<I, BC, DeviceId = FakeDeviceId>
8566            + TcpContext<I::OtherVersion, BC, DeviceId = FakeDeviceId>,
8567        BC: TcpBindingsContext<CC::DeviceId>,
8568    >(
8569        core_ctx: &mut CC,
8570        bindings_ctx: &mut BC,
8571        original_src_ip: SpecifiedAddr<I::Addr>,
8572        original_dst_ip: SpecifiedAddr<I::Addr>,
8573        original_body: &[u8],
8574        err: I::ErrorCode,
8575    ) {
8576        <TcpIpTransportContext as IpTransportContext<I, _, _>>::receive_icmp_error(
8577            core_ctx,
8578            bindings_ctx,
8579            &FakeDeviceId,
8580            Some(original_src_ip),
8581            original_dst_ip,
8582            original_body,
8583            err,
8584        );
8585    }
8586
8587    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestNetworkUnreachable, IcmpDestUnreachable::default()) => ConnectionError::NetworkUnreachable)]
8588    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestHostUnreachable, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8589    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestProtocolUnreachable, IcmpDestUnreachable::default()) => ConnectionError::ProtocolUnreachable)]
8590    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestPortUnreachable, IcmpDestUnreachable::default()) => ConnectionError::PortUnreachable)]
8591    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::SourceRouteFailed, IcmpDestUnreachable::default()) => ConnectionError::SourceRouteFailed)]
8592    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestNetworkUnknown, IcmpDestUnreachable::default()) => ConnectionError::NetworkUnreachable)]
8593    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestHostUnknown, IcmpDestUnreachable::default()) => ConnectionError::DestinationHostDown)]
8594    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::SourceHostIsolated, IcmpDestUnreachable::default()) => ConnectionError::SourceHostIsolated)]
8595    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::NetworkAdministrativelyProhibited, IcmpDestUnreachable::default()) => ConnectionError::NetworkUnreachable)]
8596    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::HostAdministrativelyProhibited, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8597    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::NetworkUnreachableForToS, IcmpDestUnreachable::default()) => ConnectionError::NetworkUnreachable)]
8598    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::HostUnreachableForToS, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8599    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::CommAdministrativelyProhibited, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8600    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::HostPrecedenceViolation, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8601    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::PrecedenceCutoffInEffect, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8602    #[test_case(Icmpv4ErrorCode::ParameterProblem(Icmpv4ParameterProblemCode::PointerIndicatesError) => ConnectionError::ProtocolError)]
8603    #[test_case(Icmpv4ErrorCode::ParameterProblem(Icmpv4ParameterProblemCode::MissingRequiredOption) => ConnectionError::ProtocolError)]
8604    #[test_case(Icmpv4ErrorCode::ParameterProblem(Icmpv4ParameterProblemCode::BadLength) => ConnectionError::ProtocolError)]
8605    #[test_case(Icmpv4ErrorCode::TimeExceeded(Icmpv4TimeExceededCode::TtlExpired) => ConnectionError::HostUnreachable)]
8606    #[test_case(Icmpv4ErrorCode::TimeExceeded(Icmpv4TimeExceededCode::FragmentReassemblyTimeExceeded) => ConnectionError::TimedOut)]
8607    fn icmp_destination_unreachable_connect_v4(error: Icmpv4ErrorCode) -> ConnectionError {
8608        icmp_destination_unreachable_connect_inner::<Ipv4>(error)
8609    }
8610
8611    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::NoRoute) => ConnectionError::NetworkUnreachable)]
8612    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::CommAdministrativelyProhibited) => ConnectionError::PermissionDenied)]
8613    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::BeyondScope) => ConnectionError::HostUnreachable)]
8614    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::AddrUnreachable) => ConnectionError::HostUnreachable)]
8615    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::PortUnreachable) => ConnectionError::PortUnreachable)]
8616    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::SrcAddrFailedPolicy) => ConnectionError::PermissionDenied)]
8617    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::RejectRoute) => ConnectionError::PermissionDenied)]
8618    #[test_case(Icmpv6ErrorCode::ParameterProblem(Icmpv6ParameterProblemCode::ErroneousHeaderField) => ConnectionError::ProtocolError)]
8619    #[test_case(Icmpv6ErrorCode::ParameterProblem(Icmpv6ParameterProblemCode::UnrecognizedNextHeaderType) => ConnectionError::ProtocolError)]
8620    #[test_case(Icmpv6ErrorCode::ParameterProblem(Icmpv6ParameterProblemCode::UnrecognizedIpv6Option) => ConnectionError::ProtocolError)]
8621    #[test_case(Icmpv6ErrorCode::TimeExceeded(Icmpv6TimeExceededCode::HopLimitExceeded) => ConnectionError::HostUnreachable)]
8622    #[test_case(Icmpv6ErrorCode::TimeExceeded(Icmpv6TimeExceededCode::FragmentReassemblyTimeExceeded) => ConnectionError::HostUnreachable)]
8623    fn icmp_destination_unreachable_connect_v6(error: Icmpv6ErrorCode) -> ConnectionError {
8624        icmp_destination_unreachable_connect_inner::<Ipv6>(error)
8625    }
8626
8627    fn icmp_destination_unreachable_connect_inner<I: TcpTestIpExt + IcmpIpExt>(
8628        icmp_error: I::ErrorCode,
8629    ) -> ConnectionError
8630    where
8631        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<I, TcpBindingsCtx<FakeDeviceId>>
8632            + TcpContext<I::OtherVersion, TcpBindingsCtx<FakeDeviceId>>,
8633    {
8634        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
8635            I::TEST_ADDRS.local_ip,
8636            I::TEST_ADDRS.remote_ip,
8637        ));
8638        let mut api = ctx.tcp_api::<I>();
8639
8640        let connection = api.create(Default::default());
8641        api.connect(&connection, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), PORT_1)
8642            .expect("failed to create a connection socket");
8643
8644        let (core_ctx, bindings_ctx) = api.contexts();
8645        let frames = core_ctx.ip_socket_ctx.take_frames();
8646        let frame = assert_matches!(&frames[..], [(_meta, frame)] => frame);
8647
8648        deliver_icmp_error::<I, _, _>(
8649            core_ctx,
8650            bindings_ctx,
8651            I::TEST_ADDRS.local_ip,
8652            I::TEST_ADDRS.remote_ip,
8653            &frame[0..8],
8654            icmp_error,
8655        );
8656        // The TCP handshake should fail.
8657        let err = api
8658            .connect(&connection, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), PORT_1)
8659            .expect_err("should fail");
8660        // The connect call should've taken the error.
8661        assert_eq!(api.get_socket_error(&connection), None);
8662        // Failure due to ICMP error.
8663        assert_matches!(err, ConnectError::ConnectionError(e) => e)
8664    }
8665
8666    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestNetworkUnreachable, IcmpDestUnreachable::default()) => ConnectionError::NetworkUnreachable)]
8667    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestHostUnreachable, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8668    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestProtocolUnreachable, IcmpDestUnreachable::default()) => ConnectionError::ProtocolUnreachable)]
8669    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestPortUnreachable, IcmpDestUnreachable::default()) => ConnectionError::PortUnreachable)]
8670    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::SourceRouteFailed, IcmpDestUnreachable::default()) => ConnectionError::SourceRouteFailed)]
8671    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestNetworkUnknown, IcmpDestUnreachable::default()) => ConnectionError::NetworkUnreachable)]
8672    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::DestHostUnknown, IcmpDestUnreachable::default()) => ConnectionError::DestinationHostDown)]
8673    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::SourceHostIsolated, IcmpDestUnreachable::default()) => ConnectionError::SourceHostIsolated)]
8674    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::NetworkAdministrativelyProhibited, IcmpDestUnreachable::default()) => ConnectionError::NetworkUnreachable)]
8675    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::HostAdministrativelyProhibited, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8676    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::NetworkUnreachableForToS, IcmpDestUnreachable::default()) => ConnectionError::NetworkUnreachable)]
8677    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::HostUnreachableForToS, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8678    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::CommAdministrativelyProhibited, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8679    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::HostPrecedenceViolation, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8680    #[test_case(Icmpv4ErrorCode::DestUnreachable(Icmpv4DestUnreachableCode::PrecedenceCutoffInEffect, IcmpDestUnreachable::default()) => ConnectionError::HostUnreachable)]
8681    #[test_case(Icmpv4ErrorCode::ParameterProblem(Icmpv4ParameterProblemCode::PointerIndicatesError) => ConnectionError::ProtocolError)]
8682    #[test_case(Icmpv4ErrorCode::ParameterProblem(Icmpv4ParameterProblemCode::MissingRequiredOption) => ConnectionError::ProtocolError)]
8683    #[test_case(Icmpv4ErrorCode::ParameterProblem(Icmpv4ParameterProblemCode::BadLength) => ConnectionError::ProtocolError)]
8684    #[test_case(Icmpv4ErrorCode::TimeExceeded(Icmpv4TimeExceededCode::TtlExpired) => ConnectionError::HostUnreachable)]
8685    #[test_case(Icmpv4ErrorCode::TimeExceeded(Icmpv4TimeExceededCode::FragmentReassemblyTimeExceeded) => ConnectionError::TimedOut)]
8686    fn icmp_destination_unreachable_established_v4(error: Icmpv4ErrorCode) -> ConnectionError {
8687        icmp_destination_unreachable_established_inner::<Ipv4>(error)
8688    }
8689
8690    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::NoRoute) => ConnectionError::NetworkUnreachable)]
8691    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::CommAdministrativelyProhibited) => ConnectionError::PermissionDenied)]
8692    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::BeyondScope) => ConnectionError::HostUnreachable)]
8693    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::AddrUnreachable) => ConnectionError::HostUnreachable)]
8694    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::PortUnreachable) => ConnectionError::PortUnreachable)]
8695    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::SrcAddrFailedPolicy) => ConnectionError::PermissionDenied)]
8696    #[test_case(Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::RejectRoute) => ConnectionError::PermissionDenied)]
8697    #[test_case(Icmpv6ErrorCode::ParameterProblem(Icmpv6ParameterProblemCode::ErroneousHeaderField) => ConnectionError::ProtocolError)]
8698    #[test_case(Icmpv6ErrorCode::ParameterProblem(Icmpv6ParameterProblemCode::UnrecognizedNextHeaderType) => ConnectionError::ProtocolError)]
8699    #[test_case(Icmpv6ErrorCode::ParameterProblem(Icmpv6ParameterProblemCode::UnrecognizedIpv6Option) => ConnectionError::ProtocolError)]
8700    #[test_case(Icmpv6ErrorCode::TimeExceeded(Icmpv6TimeExceededCode::HopLimitExceeded) => ConnectionError::HostUnreachable)]
8701    #[test_case(Icmpv6ErrorCode::TimeExceeded(Icmpv6TimeExceededCode::FragmentReassemblyTimeExceeded) => ConnectionError::HostUnreachable)]
8702    fn icmp_destination_unreachable_established_v6(error: Icmpv6ErrorCode) -> ConnectionError {
8703        icmp_destination_unreachable_established_inner::<Ipv6>(error)
8704    }
8705
8706    fn icmp_destination_unreachable_established_inner<I: TcpTestIpExt + IcmpIpExt>(
8707        icmp_error: I::ErrorCode,
8708    ) -> ConnectionError
8709    where
8710        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
8711                I,
8712                TcpBindingsCtx<FakeDeviceId>,
8713                SingleStackConverter = I::SingleStackConverter,
8714                DualStackConverter = I::DualStackConverter,
8715            > + TcpContext<I::OtherVersion, TcpBindingsCtx<FakeDeviceId>>,
8716    {
8717        let (mut net, local, local_snd_end, _remote) = bind_listen_connect_accept_inner::<I>(
8718            I::UNSPECIFIED_ADDRESS,
8719            BindConfig {
8720                client_port: None,
8721                server_port: PORT_1,
8722                client_reuse_addr: false,
8723                send_test_data: false,
8724            },
8725            0,
8726            0.0,
8727        );
8728        local_snd_end.lock().extend_from_slice(b"Hello");
8729        net.with_context(LOCAL, |ctx| {
8730            ctx.tcp_api().do_send(&local);
8731        });
8732        net.collect_frames();
8733        let original_body = assert_matches!(
8734            &net.iter_pending_frames().collect::<Vec<_>>()[..],
8735            [InstantAndData(_instant, PendingFrameData {
8736                dst_context: _,
8737                meta: _,
8738                frame,
8739            })] => {
8740            frame.clone()
8741        });
8742        net.with_context(LOCAL, |ctx| {
8743            let TcpCtx { core_ctx, bindings_ctx } = ctx;
8744            deliver_icmp_error::<I, _, _>(
8745                core_ctx,
8746                bindings_ctx,
8747                I::TEST_ADDRS.local_ip,
8748                I::TEST_ADDRS.remote_ip,
8749                &original_body[..],
8750                icmp_error,
8751            );
8752            // An error should be posted on the connection.
8753            let error = assert_matches!(
8754                ctx.tcp_api().get_socket_error(&local),
8755                Some(error) => error
8756            );
8757            // But it should stay established.
8758            assert_matches!(
8759                &local.get().deref().socket_state,
8760                TcpSocketStateInner::Connected { conn, .. } => {
8761                    let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
8762                    assert_matches!(
8763                        conn,
8764                        Connection {
8765                            state: State::Established(_),
8766                            ..
8767                        }
8768                    );
8769                }
8770            );
8771            error
8772        })
8773    }
8774
8775    #[ip_test(I)]
8776    fn icmp_destination_unreachable_listener<I: TcpTestIpExt + IcmpIpExt>()
8777    where
8778        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<I, TcpBindingsCtx<FakeDeviceId>>
8779            + TcpContext<I::OtherVersion, TcpBindingsCtx<FakeDeviceId>>
8780            + CounterContext<TcpCountersWithSocket<I>>,
8781    {
8782        let mut net = new_test_net::<I>();
8783
8784        let backlog = NonZeroUsize::new(1).unwrap();
8785        let server = net.with_context(REMOTE, |ctx| {
8786            let mut api = ctx.tcp_api::<I>();
8787            let server = api.create(Default::default());
8788            api.bind(&server, None, Some(PORT_1)).expect("failed to bind the server socket");
8789            api.listen(&server, backlog).expect("can listen");
8790            server
8791        });
8792
8793        net.with_context(LOCAL, |ctx| {
8794            let mut api = ctx.tcp_api::<I>();
8795            let conn = api.create(Default::default());
8796            api.connect(&conn, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), PORT_1)
8797                .expect("failed to connect");
8798        });
8799
8800        assert!(!net.step().is_idle());
8801
8802        net.collect_frames();
8803        let original_body = assert_matches!(
8804            &net.iter_pending_frames().collect::<Vec<_>>()[..],
8805            [InstantAndData(_instant, PendingFrameData {
8806                dst_context: _,
8807                meta: _,
8808                frame,
8809            })] => {
8810            frame.clone()
8811        });
8812        let icmp_error = I::map_ip(
8813            (),
8814            |()| {
8815                Icmpv4ErrorCode::DestUnreachable(
8816                    Icmpv4DestUnreachableCode::DestPortUnreachable,
8817                    IcmpDestUnreachable::default(),
8818                )
8819            },
8820            |()| Icmpv6ErrorCode::DestUnreachable(Icmpv6DestUnreachableCode::PortUnreachable),
8821        );
8822        net.with_context(REMOTE, |TcpCtx { core_ctx, bindings_ctx }| {
8823            let in_queue = {
8824                let state = server.get();
8825                let accept_queue = assert_matches!(
8826                    &state.deref().socket_state,
8827                    TcpSocketStateInner::Listener(Listener { accept_queue, .. }) => accept_queue
8828                );
8829                assert_eq!(accept_queue.len(), 1);
8830                accept_queue.collect_pending().first().unwrap().downgrade()
8831            };
8832            deliver_icmp_error::<I, _, _>(
8833                core_ctx,
8834                bindings_ctx,
8835                I::TEST_ADDRS.remote_ip,
8836                I::TEST_ADDRS.local_ip,
8837                &original_body[..],
8838                icmp_error,
8839            );
8840            {
8841                let state = server.get();
8842                let queue_len = assert_matches!(
8843                    &state.deref().socket_state,
8844                    TcpSocketStateInner::Listener(Listener { accept_queue, .. }) => accept_queue.len()
8845                );
8846                assert_eq!(queue_len, 0);
8847            }
8848            // Socket must've been destroyed.
8849            assert_eq!(in_queue.upgrade(), None);
8850        });
8851    }
8852
8853    #[ip_test(I)]
8854    fn time_wait_reuse<I: TcpTestIpExt>()
8855    where
8856        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
8857                I,
8858                TcpBindingsCtx<FakeDeviceId>,
8859                SingleStackConverter = I::SingleStackConverter,
8860                DualStackConverter = I::DualStackConverter,
8861            >,
8862    {
8863        set_logger_for_test();
8864        const CLIENT_PORT: NonZeroU16 = NonZeroU16::new(2).unwrap();
8865        const SERVER_PORT: NonZeroU16 = NonZeroU16::new(1).unwrap();
8866        let (mut net, local, _local_snd_end, remote) = bind_listen_connect_accept_inner::<I>(
8867            I::UNSPECIFIED_ADDRESS,
8868            BindConfig {
8869                client_port: Some(CLIENT_PORT),
8870                server_port: SERVER_PORT,
8871                client_reuse_addr: true,
8872                send_test_data: false,
8873            },
8874            0,
8875            0.0,
8876        );
8877        // Locally, we create a connection with a full accept queue.
8878        let listener = net.with_context(LOCAL, |ctx| {
8879            let mut api = ctx.tcp_api::<I>();
8880            let listener = api.create(Default::default());
8881            api.set_reuseaddr(&listener, true).expect("can set");
8882            api.bind(
8883                &listener,
8884                Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)),
8885                Some(CLIENT_PORT),
8886            )
8887            .expect("failed to bind");
8888            api.listen(&listener, NonZeroUsize::new(1).unwrap()).expect("failed to listen");
8889            listener
8890        });
8891        // This connection is never used, just to keep accept queue full.
8892        let extra_conn = net.with_context(REMOTE, |ctx| {
8893            let mut api = ctx.tcp_api::<I>();
8894            let extra_conn = api.create(Default::default());
8895            api.connect(&extra_conn, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), CLIENT_PORT)
8896                .expect("failed to connect");
8897            extra_conn
8898        });
8899        net.run_until_idle();
8900
8901        net.with_context(REMOTE, |ctx| {
8902            assert_eq!(
8903                ctx.tcp_api().connect(
8904                    &extra_conn,
8905                    Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)),
8906                    CLIENT_PORT,
8907                ),
8908                Ok(())
8909            );
8910        });
8911
8912        // Now we shutdown the sockets and try to bring the local socket to
8913        // TIME-WAIT.
8914        let weak_local = local.downgrade();
8915        net.with_context(LOCAL, |ctx| {
8916            ctx.tcp_api().close(local);
8917        });
8918        assert!(!net.step().is_idle());
8919        assert!(!net.step().is_idle());
8920        net.with_context(REMOTE, |ctx| {
8921            ctx.tcp_api().close(remote);
8922        });
8923        assert!(!net.step().is_idle());
8924        assert!(!net.step().is_idle());
8925        // The connection should go to TIME-WAIT.
8926        let (tw_last_seq, tw_last_ack, tw_expiry) = {
8927            assert_matches!(
8928                &weak_local.upgrade().unwrap().get().deref().socket_state,
8929                TcpSocketStateInner::Connected { conn, .. } => {
8930                    let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
8931                    assert_matches!(
8932                        conn,
8933                        Connection {
8934                        state: State::TimeWait(TimeWait {
8935                            last_seq,
8936                            closed_rcv,
8937                            expiry,
8938                            ..
8939                        }), ..
8940                        } => (*last_seq, closed_rcv.ack, *expiry)
8941                    )
8942                }
8943            )
8944        };
8945
8946        // Try to initiate a connection from the remote since we have an active
8947        // listener locally.
8948        let conn = net.with_context(REMOTE, |ctx| {
8949            let mut api = ctx.tcp_api::<I>();
8950            let conn = api.create(Default::default());
8951            api.connect(&conn, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), CLIENT_PORT)
8952                .expect("failed to connect");
8953            conn
8954        });
8955        while net.next_step() != Some(tw_expiry) {
8956            assert!(!net.step().is_idle());
8957        }
8958        // This attempt should fail due the full accept queue at the listener.
8959        assert_matches!(
8960        &conn.get().deref().socket_state,
8961        TcpSocketStateInner::Connected { conn, .. } => {
8962                let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(conn, &I::converter());
8963                assert_matches!(
8964                    conn,
8965                Connection {
8966                    state: State::Closed(Closed { reason: Some(ConnectionError::TimedOut) }),
8967                    ..
8968                }
8969                );
8970            });
8971
8972        // Now free up the accept queue by accepting the connection.
8973        net.with_context(LOCAL, |ctx| {
8974            let _accepted =
8975                ctx.tcp_api().accept(&listener).expect("failed to accept a new connection");
8976        });
8977        let conn = net.with_context(REMOTE, |ctx| {
8978            let mut api = ctx.tcp_api::<I>();
8979            let socket = api.create(Default::default());
8980            api.bind(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), Some(SERVER_PORT))
8981                .expect("failed to bind");
8982            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), CLIENT_PORT)
8983                .expect("failed to connect");
8984            socket
8985        });
8986        net.collect_frames();
8987        assert_matches!(
8988            &net.iter_pending_frames().collect::<Vec<_>>()[..],
8989            [InstantAndData(_instant, PendingFrameData {
8990                dst_context: _,
8991                meta,
8992                frame,
8993            })] => {
8994            let mut buffer = Buf::new(frame, ..);
8995            let iss = match I::VERSION {
8996                IpVersion::V4 => {
8997                    let meta = assert_matches!(meta, DualStackSendIpPacketMeta::V4(meta) => meta);
8998                    let parsed = buffer.parse_with::<_, TcpSegment<_>>(
8999                        TcpParseArgs::new(*meta.src_ip, *meta.dst_ip)
9000                    ).expect("failed to parse");
9001                    assert!(parsed.syn());
9002                    SeqNum::new(parsed.seq_num())
9003                }
9004                IpVersion::V6 => {
9005                    let meta = assert_matches!(meta, DualStackSendIpPacketMeta::V6(meta) => meta);
9006                    let parsed = buffer.parse_with::<_, TcpSegment<_>>(
9007                        TcpParseArgs::new(*meta.src_ip, *meta.dst_ip)
9008                    ).expect("failed to parse");
9009                    assert!(parsed.syn());
9010                    SeqNum::new(parsed.seq_num())
9011                }
9012            };
9013            assert!(iss.after(tw_last_ack) && iss.before(tw_last_seq));
9014        });
9015        // The TIME-WAIT socket should be reused to establish the connection.
9016        net.run_until_idle();
9017        net.with_context(REMOTE, |ctx| {
9018            assert_eq!(
9019                ctx.tcp_api().connect(
9020                    &conn,
9021                    Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)),
9022                    CLIENT_PORT
9023                ),
9024                Ok(())
9025            );
9026        });
9027    }
9028
9029    #[ip_test(I)]
9030    fn conn_addr_not_available<I: TcpTestIpExt + IcmpIpExt>()
9031    where
9032        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
9033                I,
9034                TcpBindingsCtx<FakeDeviceId>,
9035                SingleStackConverter = I::SingleStackConverter,
9036                DualStackConverter = I::DualStackConverter,
9037            >,
9038    {
9039        set_logger_for_test();
9040        let (mut net, _local, _local_snd_end, _remote) = bind_listen_connect_accept_inner::<I>(
9041            I::UNSPECIFIED_ADDRESS,
9042            BindConfig {
9043                client_port: Some(PORT_1),
9044                server_port: PORT_1,
9045                client_reuse_addr: true,
9046                send_test_data: false,
9047            },
9048            0,
9049            0.0,
9050        );
9051        // Now we are using the same 4-tuple again to try to create a new
9052        // connection, this should fail.
9053        net.with_context(LOCAL, |ctx| {
9054            let mut api = ctx.tcp_api::<I>();
9055            let socket = api.create(Default::default());
9056            api.set_reuseaddr(&socket, true).expect("can set");
9057            api.bind(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(PORT_1))
9058                .expect("failed to bind");
9059            assert_eq!(
9060                api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), PORT_1),
9061                Err(ConnectError::ConnectionExists),
9062            )
9063        });
9064    }
9065
9066    #[test_case::test_matrix(
9067        [None, Some(ZonedAddr::Unzoned((*Ipv4::TEST_ADDRS.remote_ip).to_ipv6_mapped()))],
9068        [None, Some(PORT_1)],
9069        [true, false]
9070    )]
9071    fn dual_stack_connect(
9072        server_bind_ip: Option<ZonedAddr<SpecifiedAddr<Ipv6Addr>, FakeDeviceId>>,
9073        server_bind_port: Option<NonZeroU16>,
9074        bind_client: bool,
9075    ) {
9076        set_logger_for_test();
9077        let mut net = new_test_net::<Ipv4>();
9078        let backlog = NonZeroUsize::new(1).unwrap();
9079        let (server, listen_port) = net.with_context(REMOTE, |ctx| {
9080            let mut api = ctx.tcp_api::<Ipv6>();
9081            let server = api.create(Default::default());
9082            api.bind(&server, server_bind_ip, server_bind_port)
9083                .expect("failed to bind the server socket");
9084            api.listen(&server, backlog).expect("can listen");
9085            let port = assert_matches!(
9086                api.get_info(&server),
9087                SocketInfo::Bound(info) => info.port
9088            );
9089            (server, port)
9090        });
9091
9092        let client_ends = WriteBackClientBuffers::default();
9093        let client = net.with_context(LOCAL, |ctx| {
9094            let mut api = ctx.tcp_api::<Ipv6>();
9095            let socket = api.create(ProvidedBuffers::Buffers(client_ends.clone()));
9096            if bind_client {
9097                api.bind(&socket, None, None).expect("failed to bind");
9098            }
9099            api.connect(
9100                &socket,
9101                Some(ZonedAddr::Unzoned((*Ipv4::TEST_ADDRS.remote_ip).to_ipv6_mapped())),
9102                listen_port,
9103            )
9104            .expect("failed to connect");
9105            socket
9106        });
9107
9108        // Step the test network until the handshake is done.
9109        net.run_until_idle();
9110        let (accepted, addr, accepted_ends) = net
9111            .with_context(REMOTE, |ctx| ctx.tcp_api().accept(&server).expect("failed to accept"));
9112        assert_eq!(addr.ip, ZonedAddr::Unzoned((*Ipv4::TEST_ADDRS.local_ip).to_ipv6_mapped()));
9113
9114        let ClientBuffers { send: client_snd_end, receive: client_rcv_end } =
9115            client_ends.0.as_ref().lock().take().unwrap();
9116        let ClientBuffers { send: accepted_snd_end, receive: accepted_rcv_end } = accepted_ends;
9117        for snd_end in [client_snd_end, accepted_snd_end] {
9118            snd_end.lock().extend_from_slice(b"Hello");
9119        }
9120        net.with_context(LOCAL, |ctx| ctx.tcp_api().do_send(&client));
9121        net.with_context(REMOTE, |ctx| ctx.tcp_api().do_send(&accepted));
9122        net.run_until_idle();
9123
9124        for rcv_end in [client_rcv_end, accepted_rcv_end] {
9125            assert_eq!(
9126                rcv_end.lock().read_with(|avail| {
9127                    let avail = avail.concat();
9128                    assert_eq!(avail, b"Hello");
9129                    avail.len()
9130                }),
9131                5
9132            );
9133        }
9134
9135        // Verify that the client is connected to the IPv4 remote and has been
9136        // assigned an IPv4 local IP.
9137        let info = assert_matches!(
9138            net.with_context(LOCAL, |ctx| ctx.tcp_api().get_info(&client)),
9139            SocketInfo::Connection(info) => info
9140        );
9141        let (local_ip, remote_ip, port) = assert_matches!(
9142            info,
9143            ConnectionInfo {
9144                local_addr: SocketAddr { ip: local_ip, port: _ },
9145                remote_addr: SocketAddr { ip: remote_ip, port },
9146                device: _
9147            } => (local_ip.addr(), remote_ip.addr(), port)
9148        );
9149        assert_eq!(remote_ip, Ipv4::TEST_ADDRS.remote_ip.to_ipv6_mapped());
9150        assert_matches!(local_ip.to_ipv4_mapped(), Some(_));
9151        assert_eq!(port, listen_port);
9152    }
9153
9154    #[test]
9155    fn ipv6_dual_stack_enabled() {
9156        set_logger_for_test();
9157        let mut net = new_test_net::<Ipv4>();
9158        net.with_context(LOCAL, |ctx| {
9159            let mut api = ctx.tcp_api::<Ipv6>();
9160            let socket = api.create(Default::default());
9161            assert_eq!(api.dual_stack_enabled(&socket), Ok(true));
9162            api.set_dual_stack_enabled(&socket, false).expect("failed to disable dual stack");
9163            assert_eq!(api.dual_stack_enabled(&socket), Ok(false));
9164            assert_eq!(
9165                api.bind(
9166                    &socket,
9167                    Some(ZonedAddr::Unzoned((*Ipv4::TEST_ADDRS.local_ip).to_ipv6_mapped())),
9168                    Some(PORT_1),
9169                ),
9170                Err(BindError::LocalAddressError(LocalAddressError::CannotBindToAddress))
9171            );
9172            assert_eq!(
9173                api.connect(
9174                    &socket,
9175                    Some(ZonedAddr::Unzoned((*Ipv4::TEST_ADDRS.remote_ip).to_ipv6_mapped())),
9176                    PORT_1,
9177                ),
9178                Err(ConnectError::NoRoute)
9179            );
9180        });
9181    }
9182
9183    #[test]
9184    fn ipv4_dual_stack_enabled() {
9185        set_logger_for_test();
9186        let mut net = new_test_net::<Ipv4>();
9187        net.with_context(LOCAL, |ctx| {
9188            let mut api = ctx.tcp_api::<Ipv4>();
9189            let socket = api.create(Default::default());
9190            assert_eq!(api.dual_stack_enabled(&socket), Err(NotDualStackCapableError));
9191            assert_eq!(
9192                api.set_dual_stack_enabled(&socket, true),
9193                Err(NotDualStackCapableError.into())
9194            );
9195        });
9196    }
9197
9198    #[ip_test(I)]
9199    fn closed_not_in_demux<I: TcpTestIpExt>()
9200    where
9201        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
9202                I,
9203                TcpBindingsCtx<FakeDeviceId>,
9204                SingleStackConverter = I::SingleStackConverter,
9205                DualStackConverter = I::DualStackConverter,
9206            >,
9207    {
9208        let (mut net, local, _local_snd_end, remote) = bind_listen_connect_accept_inner::<I>(
9209            I::UNSPECIFIED_ADDRESS,
9210            BindConfig {
9211                client_port: None,
9212                server_port: PORT_1,
9213                client_reuse_addr: false,
9214                send_test_data: false,
9215            },
9216            0,
9217            0.0,
9218        );
9219        // Assert that the sockets are bound in the socketmap.
9220        for ctx_name in [LOCAL, REMOTE] {
9221            net.with_context(ctx_name, |CtxPair { core_ctx, bindings_ctx: _ }| {
9222                TcpDemuxContext::<I, _, _>::with_demux(core_ctx, |DemuxState { socketmap }| {
9223                    assert_eq!(socketmap.len(), 1);
9224                })
9225            });
9226        }
9227        for (ctx_name, socket) in [(LOCAL, &local), (REMOTE, &remote)] {
9228            net.with_context(ctx_name, |ctx| {
9229                assert_eq!(ctx.tcp_api().shutdown(socket, ShutdownType::SendAndReceive), Ok(true));
9230            });
9231        }
9232        net.run_until_idle();
9233        // Both sockets are closed by now, but they are not defunct because we
9234        // never called `close` on them, but they should not be in the demuxer
9235        // regardless.
9236        for ctx_name in [LOCAL, REMOTE] {
9237            net.with_context(ctx_name, |CtxPair { core_ctx, bindings_ctx: _ }| {
9238                TcpDemuxContext::<I, _, _>::with_demux(core_ctx, |DemuxState { socketmap }| {
9239                    assert_eq!(socketmap.len(), 0);
9240                })
9241            });
9242        }
9243    }
9244
9245    #[ip_test(I)]
9246    fn tcp_accept_queue_clean_up_closed<I: TcpTestIpExt>()
9247    where
9248        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
9249            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
9250    {
9251        let mut net = new_test_net::<I>();
9252        let backlog = NonZeroUsize::new(1).unwrap();
9253        let server_port = NonZeroU16::new(1024).unwrap();
9254        let server = net.with_context(REMOTE, |ctx| {
9255            let mut api = ctx.tcp_api::<I>();
9256            let server = api.create(Default::default());
9257            api.bind(&server, None, Some(server_port)).expect("failed to bind the server socket");
9258            api.listen(&server, backlog).expect("can listen");
9259            server
9260        });
9261
9262        let client = net.with_context(LOCAL, |ctx| {
9263            let mut api = ctx.tcp_api::<I>();
9264            let socket = api.create(ProvidedBuffers::Buffers(WriteBackClientBuffers::default()));
9265            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), server_port)
9266                .expect("failed to connect");
9267            socket
9268        });
9269        // Step so that SYN is received by the server.
9270        assert!(!net.step().is_idle());
9271        // Make sure the server now has a pending socket in the accept queue.
9272        assert_matches!(
9273            &server.get().deref().socket_state,
9274            TcpSocketStateInner::Listener(Listener { accept_queue, .. }) => {
9275                assert_eq!(accept_queue.ready_len(), 0);
9276                assert_eq!(accept_queue.pending_len(), 1);
9277            }
9278        );
9279        // Now close the client socket.
9280        net.with_context(LOCAL, |ctx| {
9281            let mut api = ctx.tcp_api::<I>();
9282            api.close(client);
9283        });
9284        // Server's SYN-ACK will get a RST response because the connection is
9285        // no longer there.
9286        net.run_until_idle();
9287        // We verify that no lingering socket in the accept_queue.
9288        assert_matches!(
9289            &server.get().deref().socket_state,
9290            TcpSocketStateInner::Listener(Listener { accept_queue, .. }) => {
9291                assert_eq!(accept_queue.ready_len(), 0);
9292                assert_eq!(accept_queue.pending_len(), 0);
9293            }
9294        );
9295        // Server should be the only socket in `all_sockets`.
9296        net.with_context(REMOTE, |ctx| {
9297            ctx.core_ctx.with_all_sockets_mut(|all_sockets| {
9298                assert_eq!(all_sockets.keys().collect::<Vec<_>>(), [&server]);
9299            })
9300        })
9301    }
9302
9303    #[ip_test(I)]
9304    #[test_case::test_matrix(
9305        [MarkDomain::Mark1, MarkDomain::Mark2],
9306        [None, Some(0), Some(1)]
9307    )]
9308    fn tcp_socket_marks<I: TcpTestIpExt>(domain: MarkDomain, mark: Option<u32>)
9309    where
9310        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>:
9311            TcpContext<I, TcpBindingsCtx<FakeDeviceId>>,
9312    {
9313        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
9314            I::TEST_ADDRS.local_ip,
9315            I::TEST_ADDRS.remote_ip,
9316        ));
9317        let mut api = ctx.tcp_api::<I>();
9318        let socket = api.create(Default::default());
9319
9320        // Doesn't have a mark by default.
9321        assert_eq!(api.get_mark(&socket, domain), Mark(None));
9322
9323        let mark = Mark(mark);
9324        // We can set and get back the mark.
9325        api.set_mark(&socket, domain, mark);
9326        assert_eq!(api.get_mark(&socket, domain), mark);
9327    }
9328
9329    #[ip_test(I)]
9330    fn tcp_marks_for_accepted_sockets<I: TcpTestIpExt>()
9331    where
9332        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
9333                I,
9334                TcpBindingsCtx<FakeDeviceId>,
9335                SingleStackConverter = I::SingleStackConverter,
9336                DualStackConverter = I::DualStackConverter,
9337            >,
9338    {
9339        // We want the accepted socket to be marked 101 for MARK_1 and 102 for MARK_2.
9340        let expected_marks = [(MarkDomain::Mark1, 101), (MarkDomain::Mark2, 102)];
9341        let marks = netstack3_base::Marks::new(expected_marks);
9342        let mut net = new_test_net::<I>();
9343
9344        for c in [LOCAL, REMOTE] {
9345            net.with_context(c, |ctx| {
9346                ctx.core_ctx.recv_packet_marks = marks;
9347            })
9348        }
9349
9350        let backlog = NonZeroUsize::new(1).unwrap();
9351        let server_port = NonZeroU16::new(1234).unwrap();
9352
9353        let server = net.with_context(REMOTE, |ctx| {
9354            let mut api = ctx.tcp_api::<I>();
9355            let server = api.create(Default::default());
9356            api.set_mark(&server, MarkDomain::Mark1, Mark(Some(1)));
9357            api.bind(&server, None, Some(server_port)).expect("failed to bind the server socket");
9358            api.listen(&server, backlog).expect("can listen");
9359            server
9360        });
9361
9362        let client_ends = WriteBackClientBuffers::default();
9363        let _client = net.with_context(LOCAL, |ctx| {
9364            let mut api = ctx.tcp_api::<I>();
9365            let socket = api.create(ProvidedBuffers::Buffers(client_ends.clone()));
9366            api.connect(&socket, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), server_port)
9367                .expect("failed to connect");
9368            socket
9369        });
9370        net.run_until_idle();
9371        net.with_context(REMOTE, |ctx| {
9372            let (accepted, _addr, _accepted_ends) =
9373                ctx.tcp_api::<I>().accept(&server).expect("failed to accept");
9374            for (domain, expected) in expected_marks {
9375                assert_eq!(ctx.tcp_api::<I>().get_mark(&accepted, domain), Mark(Some(expected)));
9376            }
9377        });
9378    }
9379
9380    #[ip_test(I)]
9381    fn do_send_can_remove_sockets_from_demux_state<I: TcpTestIpExt>()
9382    where
9383        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
9384                I,
9385                TcpBindingsCtx<FakeDeviceId>,
9386                SingleStackConverter = I::SingleStackConverter,
9387                DualStackConverter = I::DualStackConverter,
9388            >,
9389    {
9390        let (mut net, client, _client_snd_end, accepted) = bind_listen_connect_accept_inner(
9391            I::UNSPECIFIED_ADDRESS,
9392            BindConfig {
9393                client_port: None,
9394                server_port: PORT_1,
9395                client_reuse_addr: false,
9396                send_test_data: false,
9397            },
9398            0,
9399            0.0,
9400        );
9401        net.with_context(LOCAL, |ctx| {
9402            let mut api = ctx.tcp_api::<I>();
9403            assert_eq!(api.shutdown(&client, ShutdownType::Send), Ok(true));
9404        });
9405        // client -> accepted FIN.
9406        assert!(!net.step().is_idle());
9407        // accepted -> client ACK.
9408        assert!(!net.step().is_idle());
9409        net.with_context(REMOTE, |ctx| {
9410            let mut api = ctx.tcp_api::<I>();
9411            assert_eq!(api.shutdown(&accepted, ShutdownType::Send), Ok(true));
9412        });
9413        // accepted -> client FIN.
9414        assert!(!net.step().is_idle());
9415        // client -> accepted ACK.
9416        assert!(!net.step().is_idle());
9417
9418        // client is now in TIME_WAIT
9419        net.with_context(LOCAL, |CtxPair { core_ctx, bindings_ctx: _ }| {
9420            TcpDemuxContext::<I, _, _>::with_demux(core_ctx, |DemuxState { socketmap }| {
9421                assert_eq!(socketmap.len(), 1);
9422            })
9423        });
9424        assert_matches!(
9425            &client.get().deref().socket_state,
9426            TcpSocketStateInner::Connected { conn, .. } => {
9427                let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(
9428                    conn,
9429                    &I::converter()
9430                );
9431                assert_matches!(
9432                    conn,
9433                    Connection {
9434                        state: State::TimeWait(_),
9435                        ..
9436                    }
9437                );
9438            }
9439        );
9440        net.with_context(LOCAL, |ctx| {
9441            // Advance the current time but don't fire the timer.
9442            ctx.with_fake_timer_ctx_mut(|ctx| {
9443                ctx.instant.time =
9444                    ctx.instant.time.checked_add(Duration::from_secs(120 * 60)).unwrap()
9445            });
9446            // Race with `do_send`.
9447            let mut api = ctx.tcp_api::<I>();
9448            api.do_send(&client);
9449        });
9450        assert_matches!(
9451            &client.get().deref().socket_state,
9452            TcpSocketStateInner::Connected { conn, .. } => {
9453                let (conn, _addr) = assert_this_stack_conn::<I, _, TcpCoreCtx<_, _>>(
9454                    conn,
9455                    &I::converter()
9456                );
9457                assert_matches!(
9458                    conn,
9459                    Connection {
9460                        state: State::Closed(_),
9461                        ..
9462                    }
9463                );
9464            }
9465        );
9466        net.with_context(LOCAL, |CtxPair { core_ctx, bindings_ctx: _ }| {
9467            TcpDemuxContext::<I, _, _>::with_demux(core_ctx, |DemuxState { socketmap }| {
9468                assert_eq!(socketmap.len(), 0);
9469            })
9470        });
9471    }
9472
9473    #[ip_test(I)]
9474    #[test_case(true; "server read over mss")]
9475    #[test_case(false; "server read under mss")]
9476    fn tcp_data_dequeue_sends_window_update<I: TcpTestIpExt>(server_read_over_mss: bool)
9477    where
9478        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
9479                I,
9480                TcpBindingsCtx<FakeDeviceId>,
9481                SingleStackConverter = I::SingleStackConverter,
9482                DualStackConverter = I::DualStackConverter,
9483            >,
9484    {
9485        const EXTRA_DATA_AMOUNT: usize = 128;
9486        set_logger_for_test();
9487
9488        let (mut net, client, client_snd_end, accepted) = bind_listen_connect_accept_inner(
9489            I::UNSPECIFIED_ADDRESS,
9490            BindConfig {
9491                client_port: None,
9492                server_port: PORT_1,
9493                client_reuse_addr: false,
9494                send_test_data: false,
9495            },
9496            0,
9497            0.0,
9498        );
9499
9500        let accepted_rcv_bufsize = net
9501            .with_context(REMOTE, |ctx| ctx.tcp_api::<I>().receive_buffer_size(&accepted).unwrap());
9502
9503        // Send enough data to the server to fill up its receive buffer.
9504        client_snd_end.lock().extend(core::iter::repeat(0xAB).take(accepted_rcv_bufsize));
9505        net.with_context(LOCAL, |ctx| {
9506            ctx.tcp_api().do_send(&client);
9507        });
9508        net.run_until_idle();
9509
9510        // From now on, we don't want to trigger timers
9511        // because that would result in either:
9512        // 1. The client to time out, since the server isn't going to read any
9513        //    data from its buffer.
9514        // 2. ZWP from the client, which would make this test pointless.
9515
9516        // Push extra data into the send buffer that won't be sent because the
9517        // receive window is zero.
9518        client_snd_end.lock().extend(core::iter::repeat(0xAB).take(EXTRA_DATA_AMOUNT));
9519        net.with_context(LOCAL, |ctx| {
9520            ctx.tcp_api().do_send(&client);
9521        });
9522        let _ = net.step_deliver_frames();
9523
9524        let send_buf_len = net
9525            .with_context(LOCAL, |ctx| {
9526                ctx.tcp_api::<I>().with_send_buffer(&client, |buf| {
9527                    let BufferLimits { len, capacity: _ } = buf.limits();
9528                    len
9529                })
9530            })
9531            .unwrap();
9532        assert_eq!(send_buf_len, EXTRA_DATA_AMOUNT);
9533
9534        if server_read_over_mss {
9535            // Clear out the receive buffer
9536            let nread = net
9537                .with_context(REMOTE, |ctx| {
9538                    ctx.tcp_api::<I>().with_receive_buffer(&accepted, |buf| {
9539                        buf.lock()
9540                            .read_with(|readable| readable.into_iter().map(|buf| buf.len()).sum())
9541                    })
9542                })
9543                .unwrap();
9544            assert_eq!(nread, accepted_rcv_bufsize);
9545
9546            // The server sends a window update because the window went from 0 to
9547            // larger than MSS.
9548            net.with_context(REMOTE, |ctx| ctx.tcp_api::<I>().on_receive_buffer_read(&accepted));
9549
9550            let (server_snd_max, server_acknum) = {
9551                let socket = accepted.get();
9552                let state = assert_matches!(
9553                    &socket.deref().socket_state,
9554                    TcpSocketStateInner::Connected { conn, .. } => {
9555                        assert_matches!(I::get_state(conn), State::Established(e) => e)
9556                    }
9557                );
9558
9559                (state.snd.max, state.rcv.nxt())
9560            };
9561
9562            // Deliver the window update to the client.
9563            assert_eq!(
9564                net.step_deliver_frames_with(|_, meta, frame| {
9565                    let mut buffer = Buf::new(frame.clone(), ..);
9566
9567                    let (packet_seq, packet_ack, window_size, body_len) = match I::VERSION {
9568                        IpVersion::V4 => {
9569                            let meta =
9570                                assert_matches!(&meta, DualStackSendIpPacketMeta::V4(v4) => v4);
9571
9572                            // Server -> Client.
9573                            assert_eq!(*meta.src_ip, Ipv4::TEST_ADDRS.remote_ip.into_addr());
9574                            assert_eq!(*meta.dst_ip, Ipv4::TEST_ADDRS.local_ip.into_addr());
9575
9576                            let parsed = buffer
9577                                .parse_with::<_, TcpSegment<_>>(TcpParseArgs::new(
9578                                    *meta.src_ip,
9579                                    *meta.dst_ip,
9580                                ))
9581                                .expect("failed to parse");
9582
9583                            (
9584                                parsed.seq_num(),
9585                                parsed.ack_num().unwrap(),
9586                                parsed.window_size(),
9587                                parsed.body().len(),
9588                            )
9589                        }
9590                        IpVersion::V6 => {
9591                            let meta =
9592                                assert_matches!(&meta, DualStackSendIpPacketMeta::V6(v6) => v6);
9593
9594                            // Server -> Client.
9595                            assert_eq!(*meta.src_ip, Ipv6::TEST_ADDRS.remote_ip.into_addr());
9596                            assert_eq!(*meta.dst_ip, Ipv6::TEST_ADDRS.local_ip.into_addr());
9597
9598                            let parsed = buffer
9599                                .parse_with::<_, TcpSegment<_>>(TcpParseArgs::new(
9600                                    *meta.src_ip,
9601                                    *meta.dst_ip,
9602                                ))
9603                                .expect("failed to parse");
9604
9605                            (
9606                                parsed.seq_num(),
9607                                parsed.ack_num().unwrap(),
9608                                parsed.window_size(),
9609                                parsed.body().len(),
9610                            )
9611                        }
9612                    };
9613
9614                    // Ensure that this is actually a window update, and no data
9615                    // is being sent or ACKed.
9616                    assert_eq!(packet_seq, u32::from(server_snd_max));
9617                    assert_eq!(packet_ack, u32::from(server_acknum));
9618                    assert_eq!(window_size, 65535);
9619                    assert_eq!(body_len, 0);
9620
9621                    Some((meta, frame))
9622                })
9623                .frames_sent,
9624                1
9625            );
9626
9627            // Deliver the data send to the server.
9628            assert_eq!(
9629                net.step_deliver_frames_with(|_, meta, frame| {
9630                    let mut buffer = Buf::new(frame.clone(), ..);
9631
9632                    let body_len = match I::VERSION {
9633                        IpVersion::V4 => {
9634                            let meta =
9635                                assert_matches!(&meta, DualStackSendIpPacketMeta::V4(v4) => v4);
9636
9637                            // Client -> Server.
9638                            assert_eq!(*meta.src_ip, Ipv4::TEST_ADDRS.local_ip.into_addr());
9639                            assert_eq!(*meta.dst_ip, Ipv4::TEST_ADDRS.remote_ip.into_addr());
9640
9641                            let parsed = buffer
9642                                .parse_with::<_, TcpSegment<_>>(TcpParseArgs::new(
9643                                    *meta.src_ip,
9644                                    *meta.dst_ip,
9645                                ))
9646                                .expect("failed to parse");
9647
9648                            parsed.body().len()
9649                        }
9650                        IpVersion::V6 => {
9651                            let meta =
9652                                assert_matches!(&meta, DualStackSendIpPacketMeta::V6(v6) => v6);
9653
9654                            // Client -> Server.
9655                            assert_eq!(*meta.src_ip, Ipv6::TEST_ADDRS.local_ip.into_addr());
9656                            assert_eq!(*meta.dst_ip, Ipv6::TEST_ADDRS.remote_ip.into_addr());
9657
9658                            let parsed = buffer
9659                                .parse_with::<_, TcpSegment<_>>(TcpParseArgs::new(
9660                                    *meta.src_ip,
9661                                    *meta.dst_ip,
9662                                ))
9663                                .expect("failed to parse");
9664
9665                            parsed.body().len()
9666                        }
9667                    };
9668
9669                    assert_eq!(body_len, EXTRA_DATA_AMOUNT);
9670
9671                    Some((meta, frame))
9672                })
9673                .frames_sent,
9674                1
9675            );
9676
9677            // Deliver the ACK of the data send to the client so it will flush the
9678            // data from its buffers.
9679            assert_eq!(
9680                net.step_deliver_frames_with(|_, meta, frame| {
9681                    let mut buffer = Buf::new(frame.clone(), ..);
9682
9683                    let (packet_seq, packet_ack, body_len) = match I::VERSION {
9684                        IpVersion::V4 => {
9685                            let meta =
9686                                assert_matches!(&meta, DualStackSendIpPacketMeta::V4(v4) => v4);
9687
9688                            // Server -> Client.
9689                            assert_eq!(*meta.src_ip, Ipv4::TEST_ADDRS.remote_ip.into_addr());
9690                            assert_eq!(*meta.dst_ip, Ipv4::TEST_ADDRS.local_ip.into_addr());
9691
9692                            let parsed = buffer
9693                                .parse_with::<_, TcpSegment<_>>(TcpParseArgs::new(
9694                                    *meta.src_ip,
9695                                    *meta.dst_ip,
9696                                ))
9697                                .expect("failed to parse");
9698
9699                            (parsed.seq_num(), parsed.ack_num().unwrap(), parsed.body().len())
9700                        }
9701                        IpVersion::V6 => {
9702                            let meta =
9703                                assert_matches!(&meta, DualStackSendIpPacketMeta::V6(v6) => v6);
9704
9705                            // Server -> Client.
9706                            assert_eq!(*meta.src_ip, Ipv6::TEST_ADDRS.remote_ip.into_addr());
9707                            assert_eq!(*meta.dst_ip, Ipv6::TEST_ADDRS.local_ip.into_addr());
9708
9709                            let parsed = buffer
9710                                .parse_with::<_, TcpSegment<_>>(TcpParseArgs::new(
9711                                    *meta.src_ip,
9712                                    *meta.dst_ip,
9713                                ))
9714                                .expect("failed to parse");
9715
9716                            (parsed.seq_num(), parsed.ack_num().unwrap(), parsed.body().len())
9717                        }
9718                    };
9719
9720                    assert_eq!(packet_seq, u32::from(server_snd_max));
9721                    assert_eq!(
9722                        packet_ack,
9723                        u32::from(server_acknum) + u32::try_from(EXTRA_DATA_AMOUNT).unwrap()
9724                    );
9725                    assert_eq!(body_len, 0);
9726
9727                    Some((meta, frame))
9728                })
9729                .frames_sent,
9730                1
9731            );
9732
9733            let send_buf_len = net
9734                .with_context(LOCAL, |ctx| {
9735                    ctx.tcp_api::<I>().with_send_buffer(&client, |buf| {
9736                        let BufferLimits { len, capacity: _ } = buf.limits();
9737                        len
9738                    })
9739                })
9740                .unwrap();
9741            assert_eq!(send_buf_len, 0);
9742        } else {
9743            // Read a single byte out of the receive buffer, which is guaranteed
9744            // to be less than MSS.
9745            let nread = net
9746                .with_context(REMOTE, |ctx| {
9747                    ctx.tcp_api::<I>()
9748                        .with_receive_buffer(&accepted, |buf| buf.lock().read_with(|_readable| 1))
9749                })
9750                .unwrap();
9751            assert_eq!(nread, 1);
9752
9753            // The server won't send a window update because it wouldn't be
9754            // advertising a window that's larger than the MSS.
9755            net.with_context(REMOTE, |ctx| ctx.tcp_api::<I>().on_receive_buffer_read(&accepted));
9756            assert_eq!(net.step_deliver_frames().frames_sent, 0);
9757
9758            let send_buf_len = net
9759                .with_context(LOCAL, |ctx| {
9760                    ctx.tcp_api::<I>().with_send_buffer(&client, |buf| {
9761                        let BufferLimits { len, capacity: _ } = buf.limits();
9762                        len
9763                    })
9764                })
9765                .unwrap();
9766            // The client didn't hear about the data being read, since no window
9767            // update was sent.
9768            assert_eq!(send_buf_len, EXTRA_DATA_AMOUNT);
9769        }
9770    }
9771
9772    impl<I: DualStackIpExt, D: WeakDeviceIdentifier, BT: TcpBindingsTypes> TcpSocketId<I, D, BT> {
9773        fn established_state(
9774            state: &impl Deref<Target = TcpSocketState<I, D, BT>>,
9775        ) -> &Established<BT::Instant, BT::ReceiveBuffer, BT::SendBuffer> {
9776            assert_matches!(
9777                &state.deref().socket_state,
9778                TcpSocketStateInner::Connected { conn, .. } => {
9779                    assert_matches!(I::get_state(conn), State::Established(e) => e)
9780                }
9781            )
9782        }
9783
9784        fn mss(&self) -> Mss {
9785            *Self::established_state(&self.get()).snd.congestion_control().mss().mss()
9786        }
9787
9788        fn cwnd(&self) -> CongestionWindow {
9789            Self::established_state(&self.get()).snd.congestion_control().inspect_cwnd()
9790        }
9791    }
9792
9793    #[derive(PartialEq)]
9794    enum MssUpdate {
9795        Decrease,
9796        DecreaseBelowMin,
9797        Same,
9798        Increase,
9799    }
9800
9801    #[ip_test(I)]
9802    #[test_case(MssUpdate::Decrease; "update if decrease")]
9803    #[test_case(MssUpdate::DecreaseBelowMin; "update to min if decreased below min")]
9804    #[test_case(MssUpdate::Same; "ignore if same")]
9805    #[test_case(MssUpdate::Increase; "ignore if increase")]
9806    fn pmtu_update_mss<I: TcpTestIpExt + IcmpIpExt>(mss_update: MssUpdate)
9807    where
9808        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<I, TcpBindingsCtx<FakeDeviceId>>
9809            + TcpContext<I::OtherVersion, TcpBindingsCtx<FakeDeviceId>>,
9810    {
9811        let mut net = new_test_net::<I>();
9812
9813        let server = net.with_context(REMOTE, |ctx| {
9814            let mut api = ctx.tcp_api::<I>();
9815            let server = api.create(Default::default());
9816            api.bind(&server, None, Some(PORT_1)).expect("bind to port");
9817            api.listen(&server, NonZeroUsize::MIN).expect("can listen");
9818            server
9819        });
9820
9821        let client_buffers = WriteBackClientBuffers::default();
9822        let client = net.with_context(LOCAL, |ctx| {
9823            let mut api = ctx.tcp_api::<I>();
9824            let client = api.create(ProvidedBuffers::Buffers(client_buffers.clone()));
9825            api.connect(&client, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), PORT_1)
9826                .expect("connect to server");
9827            client
9828        });
9829
9830        // Allow the connection to be established.
9831        net.run_until_idle();
9832        let (_accepted, accepted_buffers) = net.with_context(REMOTE, |ctx| {
9833            let (accepted, _addr, accepted_ends) =
9834                ctx.tcp_api::<I>().accept(&server).expect("accept incoming connection");
9835            (accepted, accepted_ends)
9836        });
9837
9838        let initial_mss = client.mss();
9839
9840        // The minimum link MTU needed to support TCP connections.
9841        let min_mtu = u32::from(Mss::MIN)
9842            + I::IP_HEADER_LENGTH.get()
9843            + packet_formats::tcp::HDR_PREFIX_LEN as u32;
9844
9845        let pmtu_update = match mss_update {
9846            MssUpdate::DecreaseBelowMin => Mtu::new(min_mtu - 1),
9847            MssUpdate::Decrease => Mtu::new(min_mtu),
9848            MssUpdate::Same => LINK_MTU,
9849            MssUpdate::Increase => Mtu::max(),
9850        };
9851        let icmp_error = I::map_ip(
9852            (),
9853            |()| {
9854                let mtu = u16::try_from(pmtu_update.get()).unwrap_or(u16::MAX);
9855                let mtu = NonZeroU16::new(mtu).unwrap();
9856                Icmpv4ErrorCode::DestUnreachable(
9857                    Icmpv4DestUnreachableCode::FragmentationRequired,
9858                    IcmpDestUnreachable::new_for_frag_req(mtu),
9859                )
9860            },
9861            |()| Icmpv6ErrorCode::PacketTooBig(pmtu_update),
9862        );
9863
9864        // Send a payload that is large enough that it will need to be re-segmented if
9865        // the PMTU decreases, and deliver a PMTU update.
9866        let ClientBuffers { send: client_snd_end, receive: _ } =
9867            client_buffers.0.as_ref().lock().take().unwrap();
9868        let payload = vec![0xFF; min_mtu.try_into().unwrap()];
9869        client_snd_end.lock().extend_from_slice(&payload);
9870        net.with_context(LOCAL, |ctx| {
9871            ctx.tcp_api().do_send(&client);
9872            let (core_ctx, bindings_ctx) = ctx.contexts();
9873            let frames = core_ctx.ip_socket_ctx.take_frames();
9874            let frame = assert_matches!(&frames[..], [(_meta, frame)] => frame);
9875
9876            deliver_icmp_error::<I, _, _>(
9877                core_ctx,
9878                bindings_ctx,
9879                I::TEST_ADDRS.local_ip,
9880                I::TEST_ADDRS.remote_ip,
9881                &frame[0..8],
9882                icmp_error,
9883            );
9884        });
9885
9886        let requested_mms = Mms::from_mtu::<I>(pmtu_update, 0 /* no IP options */).unwrap();
9887        let requested_mss = Mss::from_mms(requested_mms);
9888        match mss_update {
9889            MssUpdate::DecreaseBelowMin => {
9890                // NB: The requested MSS is invalid.
9891                assert_eq!(requested_mss, None);
9892            }
9893            MssUpdate::Decrease => {
9894                assert_matches!(requested_mss, Some(mss) if mss < initial_mss);
9895            }
9896            MssUpdate::Same => {
9897                assert_eq!(requested_mss, Some(initial_mss));
9898            }
9899            MssUpdate::Increase => {
9900                assert_matches!(requested_mss, Some(mss) if mss > initial_mss);
9901            }
9902        };
9903
9904        // The socket should only update its MSS if the new MSS is a decrease.
9905        match mss_update {
9906            MssUpdate::Decrease | MssUpdate::DecreaseBelowMin => {}
9907            MssUpdate::Same | MssUpdate::Increase => {
9908                assert_eq!(client.mss(), initial_mss);
9909                return;
9910            }
9911        }
9912
9913        // Note the MSS & MMS used by the stack will be clamped to minimum valid
9914        // value.
9915        let expected_mss = requested_mss.unwrap_or(Mss::MIN);
9916        let expected_mms = usize::from(expected_mss) + packet_formats::tcp::HDR_PREFIX_LEN;
9917
9918        assert_eq!(client.mss(), expected_mss);
9919        // The PMTU update should not represent a congestion event.
9920        assert_gt!(client.cwnd().cwnd(), u32::from(expected_mss));
9921
9922        // The segment that was too large should be eagerly retransmitted.
9923        net.with_context(LOCAL, |ctx| {
9924            let frames = ctx.core_ctx().ip_socket_ctx.frames();
9925            let frame = assert_matches!(&frames[..], [(_meta, frame)] => frame);
9926            assert_eq!(frame.len(), expected_mms);
9927        });
9928
9929        // The remaining in-flight segment(s) are retransmitted via the retransmission
9930        // timer (rather than immediately).
9931        net.run_until_idle();
9932        let ClientBuffers { send: _, receive: accepted_rcv_end } = accepted_buffers;
9933        let read = accepted_rcv_end.lock().read_with(|avail| {
9934            let avail = avail.concat();
9935            assert_eq!(avail, payload);
9936            avail.len()
9937        });
9938        assert_eq!(read, payload.len());
9939    }
9940
9941    #[ip_test(I)]
9942    fn connect_timeout<I: TcpTestIpExt>()
9943    where
9944        TcpCoreCtx<FakeDeviceId, TcpBindingsCtx<FakeDeviceId>>: TcpContext<
9945                I,
9946                TcpBindingsCtx<FakeDeviceId>,
9947                SingleStackConverter = I::SingleStackConverter,
9948                DualStackConverter = I::DualStackConverter,
9949            >,
9950    {
9951        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::new::<I>(
9952            I::TEST_ADDRS.local_ip,
9953            I::TEST_ADDRS.remote_ip,
9954        ));
9955        let mut api = ctx.tcp_api::<I>();
9956        let socket = api.create(Default::default());
9957        let connect_addr = Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip));
9958        api.connect(&socket, connect_addr, PORT_1).expect("first connect should succeed");
9959        assert_eq!(api.connect(&socket, connect_addr, PORT_1), Err(ConnectError::Pending));
9960        while let Some(id) = ctx.bindings_ctx.timers.pop_next_timer_and_advance_time() {
9961            let mut api = ctx.tcp_api::<I>();
9962            assert_eq!(api.connect(&socket, connect_addr, PORT_1), Err(ConnectError::Pending));
9963            api.handle_timer(id.assert_ip_version());
9964        }
9965        // Once we timeout, we're done and an error should be reported.
9966        let mut api = ctx.tcp_api::<I>();
9967        assert_eq!(
9968            api.connect(&socket, connect_addr, PORT_1),
9969            Err(ConnectError::ConnectionError(ConnectionError::TimedOut))
9970        );
9971
9972        // NB: This matches the linux behavior. Whenever errors are reported
9973        // from the connect call, they're not observable from SO_ERROR later.
9974        assert_eq!(api.get_socket_error(&socket), None);
9975    }
9976
9977    // Regression test for https://issues.fuchsia.dev/475191687.
9978    #[test]
9979    fn conflict_with_same_link_local_addr_on_different_interfaces() {
9980        set_logger_for_test();
9981        const LOCAL_IP: Ipv6Addr = net_ip_v6!("fe80::1");
9982        const REMOTE_IP: Ipv6Addr = net_ip_v6!("fe80::2");
9983        const LOCAL_PORT: NonZeroU16 = NonZeroU16::new(12345).unwrap();
9984        const REMOTE_PORT: NonZeroU16 = NonZeroU16::new(54321).unwrap();
9985
9986        let mut ctx = TcpCtx::with_core_ctx(TcpCoreCtx::with_ip_socket_ctx_state(
9987            FakeDualStackIpSocketCtx::new(MultipleDevicesId::all().into_iter().map(|device| {
9988                FakeDeviceConfig {
9989                    device,
9990                    local_ips: vec![SpecifiedAddr::new(LOCAL_IP).unwrap()],
9991                    remote_ips: vec![SpecifiedAddr::new(REMOTE_IP).unwrap()],
9992                }
9993            })),
9994        ));
9995        let mut api = ctx.tcp_api::<Ipv6>();
9996        let socket = api.create(Default::default());
9997        api.bind(&socket, None, Some(LOCAL_PORT)).expect("bind should succeed");
9998
9999        api.listen(&socket, NonZeroUsize::new(5).unwrap()).unwrap();
10000
10001        let mut builder =
10002            TcpSegmentBuilder::new(REMOTE_IP, LOCAL_IP, REMOTE_PORT, LOCAL_PORT, 1, None, u16::MAX);
10003        builder.syn(true);
10004        let syn =
10005            builder.wrap_body(Buf::new(vec![], ..)).serialize_vec_outer().unwrap().into_inner();
10006
10007        <TcpIpTransportContext as IpTransportContext<Ipv6, _, _>>::receive_ip_packet(
10008            &mut ctx.core_ctx,
10009            &mut ctx.bindings_ctx,
10010            &MultipleDevicesId::A,
10011            Ipv6::recv_src_addr(REMOTE_IP),
10012            SpecifiedAddr::new(LOCAL_IP).unwrap(),
10013            syn.clone(),
10014            &Default::default(),
10015            None,
10016        )
10017        .expect("failed to deliver bytes");
10018
10019        <TcpIpTransportContext as IpTransportContext<Ipv6, _, _>>::receive_ip_packet(
10020            &mut ctx.core_ctx,
10021            &mut ctx.bindings_ctx,
10022            &MultipleDevicesId::B,
10023            Ipv6::recv_src_addr(REMOTE_IP),
10024            SpecifiedAddr::new(LOCAL_IP).unwrap(),
10025            syn,
10026            &Default::default(),
10027            None,
10028        )
10029        .expect("failed to deliver bytes");
10030    }
10031}