Skip to main content

netstack3_core/
testutil.rs

1// Copyright 2018 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//! Testing-related utilities.
6
7#![cfg(any(test, feature = "testutils"))]
8
9pub use netstack3_base::testutil::{FakeDeviceId, TestIpExt};
10pub use netstack3_filter::testutil::new_filter_egress_ip_packet;
11
12use alloc::borrow::ToOwned;
13use alloc::sync::Arc;
14use alloc::vec;
15use alloc::vec::Vec;
16
17use core::borrow::Borrow;
18use core::fmt::Debug;
19use core::hash::Hash;
20use core::ops::{Deref, DerefMut};
21use core::time::Duration;
22
23use derivative::Derivative;
24use net_types::ethernet::Mac;
25use net_types::ip::{
26    AddrSubnet, AddrSubnetEither, GenericOverIp, Ip, IpAddr, IpAddress, IpInvariant, IpVersion,
27    Ipv4, Ipv4Addr, Ipv6, Ipv6Addr, Mtu, Subnet, SubnetEither,
28};
29use net_types::{MulticastAddr, SpecifiedAddr, UnicastAddr, Witness as _};
30use netstack3_base::sync::{DynDebugReferences, Mutex};
31use netstack3_base::testutil::{
32    AlwaysDefaultsSettingsContext, FakeAtomicInstant, FakeCryptoRng, FakeFrameCtx, FakeInstant,
33    FakeNetwork, FakeNetworkLinks, FakeNetworkSpec, FakeSendToken, FakeTimerCtx, FakeTimerCtxExt,
34    FakeTimerId, MonotonicIdentifier, TestAddrs, WithFakeFrameContext, WithFakeTimerContext,
35};
36use netstack3_base::{
37    AddressResolutionFailed, CtxPair, DeferredResourceRemovalContext, EventContext,
38    InstantBindingsTypes, InstantContext, IpDeviceAddr, LinkDevice, LocalFrameDestination,
39    MarkDomain, Marks, MatcherBindingsTypes, NetworkParsingContext, NotFoundError, PacketType,
40    ReferenceNotifiers, RemoveResourceResult, RemoveResourceResultWithContext, RngContext,
41    SocketDiagnosticsSeed, TimerBindingsTypes, TimerContext, TimerHandler, TxMetadataBindingsTypes,
42    WorkQueueReport,
43};
44use netstack3_datagram::PendingDatagramSocketError;
45use netstack3_device::ethernet::{
46    EthernetCreationProperties, EthernetDeviceEvent, EthernetDeviceId, EthernetLinkDevice,
47    EthernetWeakDeviceId, RecvEthernetFrameMeta,
48};
49use netstack3_device::loopback::{LoopbackCreationProperties, LoopbackDevice, LoopbackDeviceId};
50use netstack3_device::pure_ip::{PureIpDeviceId, PureIpWeakDeviceId};
51use netstack3_device::queue::{ReceiveQueueBindingsContext, TransmitQueueBindingsContext};
52use netstack3_device::socket::{
53    DeviceSocketBindingsContext, DeviceSocketTypes, ReceiveFrameError, SocketId,
54};
55use netstack3_device::testutil::IPV6_MIN_IMPLIED_MAX_FRAME_SIZE;
56use netstack3_device::{
57    self as device, DeviceBufferBindingsTypes, DeviceId, DeviceLayerEventDispatcher,
58    DeviceLayerStateTypes, DeviceLayerTypes, DeviceProvider, DeviceSendFrameError, WeakDeviceId,
59    for_any_device_id,
60};
61use netstack3_filter::{FilterTimerId, SocketOpsFilter, SocketOpsFilterBindingContext};
62use netstack3_hashmap::HashMap;
63use netstack3_icmp_echo::{
64    IcmpEchoBindingsContext, IcmpEchoBindingsTypes, IcmpSocketId, ReceiveIcmpEchoError,
65};
66use netstack3_ip::device::{
67    IpDeviceConfiguration, IpDeviceConfigurationUpdate, IpDeviceEvent,
68    Ipv4DeviceConfigurationUpdate, Ipv6DeviceConfigurationUpdate,
69};
70use netstack3_ip::nud::{self, LinkResolutionContext, LinkResolutionNotifier};
71use netstack3_ip::raw::{
72    RawIpSocketId, RawIpSocketsBindingsContext, RawIpSocketsBindingsTypes, ReceivePacketError,
73};
74use netstack3_ip::{
75    self as ip, AddRouteError, AddableEntryEither, AddableMetric, DeviceIpLayerMetadata,
76    IpLayerEvent, IpLayerTimerId, IpRoutingBindingsTypes, MarksBindingsContext, RawMetric,
77    ResolveRouteError, ResolvedRoute, RoutableIpAddr, RouterAdvertisementEvent,
78};
79use netstack3_tcp::testutil::{ClientBuffers, ProvidedBuffers, RingBuffer, TestSendBuffer};
80use netstack3_tcp::{
81    BufferSizes, TcpBindingsTypes, TcpSocketDestructionContext, TcpSocketDiagnostics,
82};
83use netstack3_udp::{
84    ReceiveUdpError, UdpBindingsTypes, UdpPacketMeta, UdpReceiveBindingsContext, UdpSocketId,
85};
86use packet::{Buf, BufferMut};
87use zerocopy::SplitByteSlice;
88
89use crate::api::CoreApi;
90use crate::context::UnlockedCoreCtx;
91use crate::context::prelude::*;
92use crate::state::{StackState, StackStateBuilder};
93use crate::time::{TimerId, TimerIdInner};
94use crate::{BindingsContext, BindingsTypes, CoreTxMetadata, IpExt};
95
96/// The default interface routing metric for test interfaces.
97pub const DEFAULT_INTERFACE_METRIC: RawMetric = RawMetric(100);
98
99/// Context available during the execution of the netstack.
100pub type Ctx<BT> = CtxPair<StackState<BT>, BT>;
101
102/// Extensions to [`CtxPair`] when it holds a full stack state.
103pub trait CtxPairExt<BC: BindingsContext> {
104    /// Retrieves the core and bindings context, respectively.
105    ///
106    /// This function can be used to call into non-api core functions that want
107    /// a core context.
108    fn contexts(&mut self) -> (UnlockedCoreCtx<'_, BC>, &mut BC);
109
110    /// Retrieves a [`CoreApi`] from this context pair.
111    fn core_api(&mut self) -> CoreApi<'_, &mut BC> {
112        let (core_ctx, bindings_ctx) = self.contexts();
113        CoreApi::new(CtxPair { core_ctx, bindings_ctx })
114    }
115
116    /// Like [`CtxPairExt::contexts`], but retrieves only the core context.
117    fn core_ctx(&self) -> UnlockedCoreCtx<'_, BC>;
118
119    /// Retrieves a [`TestApi`] from this context pair.
120    fn test_api(&mut self) -> TestApi<'_, BC> {
121        let (core_ctx, bindings_ctx) = self.contexts();
122        TestApi(core_ctx, bindings_ctx)
123    }
124
125    /// Shortcut for [`FakeTimerCtxExt::trigger_next_timer`].
126    fn trigger_next_timer<Id>(&mut self) -> Option<Id>
127    where
128        BC: FakeTimerCtxExt<Id>,
129        for<'a> UnlockedCoreCtx<'a, BC>: TimerHandler<BC, Id>,
130    {
131        let (mut core_ctx, bindings_ctx) = self.contexts();
132        bindings_ctx.trigger_next_timer(&mut core_ctx)
133    }
134
135    /// Shortcut for [`FakeTimerCtxExt::trigger_timers_for`].
136    fn trigger_timers_for<Id>(&mut self, duration: Duration) -> Vec<Id>
137    where
138        BC: FakeTimerCtxExt<Id>,
139        for<'a> UnlockedCoreCtx<'a, BC>: TimerHandler<BC, Id>,
140    {
141        let (mut core_ctx, bindings_ctx) = self.contexts();
142        bindings_ctx.trigger_timers_for(duration, &mut core_ctx)
143    }
144
145    /// Shortcut for [`FaketimerCtx::trigger_timers_until_instant`].
146    fn trigger_timers_until_instant<Id>(&mut self, instant: FakeInstant) -> Vec<Id>
147    where
148        BC: FakeTimerCtxExt<Id>,
149        for<'a> UnlockedCoreCtx<'a, BC>: TimerHandler<BC, Id>,
150    {
151        let (mut core_ctx, bindings_ctx) = self.contexts();
152        bindings_ctx.trigger_timers_until_instant(instant, &mut core_ctx)
153    }
154
155    /// Shortcut for [`FakeTimerCtxExt::trigger_timers_until_and_expect_unordered`].
156    fn trigger_timers_until_and_expect_unordered<Id, I: IntoIterator<Item = Id>>(
157        &mut self,
158        instant: FakeInstant,
159        timers: I,
160    ) where
161        Id: Debug + Hash + Eq,
162        BC: FakeTimerCtxExt<Id>,
163        for<'a> UnlockedCoreCtx<'a, BC>: TimerHandler<BC, Id>,
164    {
165        let (mut core_ctx, bindings_ctx) = self.contexts();
166        bindings_ctx.trigger_timers_until_and_expect_unordered(instant, timers, &mut core_ctx)
167    }
168}
169
170impl<CC, BC> CtxPairExt<BC> for CtxPair<CC, BC>
171where
172    CC: Borrow<StackState<BC>>,
173    BC: BindingsContext,
174{
175    fn contexts(&mut self) -> (UnlockedCoreCtx<'_, BC>, &mut BC) {
176        let Self { core_ctx, bindings_ctx } = self;
177        (UnlockedCoreCtx::new(CC::borrow(core_ctx)), bindings_ctx)
178    }
179
180    fn core_ctx(&self) -> UnlockedCoreCtx<'_, BC> {
181        UnlockedCoreCtx::new(CC::borrow(&self.core_ctx))
182    }
183}
184
185/// An API struct for test utilities.
186pub struct TestApi<'a, BT: BindingsTypes>(UnlockedCoreCtx<'a, BT>, &'a mut BT);
187
188impl<'l, BC> TestApi<'l, BC>
189where
190    BC: BindingsContext,
191{
192    fn contexts(&mut self) -> (&mut UnlockedCoreCtx<'l, BC>, &mut BC) {
193        let Self(core_ctx, bindings_ctx) = self;
194        (core_ctx, bindings_ctx)
195    }
196
197    fn core_api(&mut self) -> CoreApi<'_, &mut BC> {
198        let (core_ctx, bindings_ctx) = self.contexts();
199        let core_ctx = core_ctx.as_owned();
200        CoreApi::new(CtxPair { core_ctx, bindings_ctx })
201    }
202
203    /// Joins the multicast group `multicast_addr` for `device`.
204    #[netstack3_macros::context_ip_bounds(A::Version, BC, crate)]
205    pub fn join_ip_multicast<A: IpAddress>(
206        &mut self,
207        device: &DeviceId<BC>,
208        multicast_addr: MulticastAddr<A>,
209    ) where
210        A::Version: IpExt,
211    {
212        let (core_ctx, bindings_ctx) = self.contexts();
213        ip::device::join_ip_multicast::<A::Version, _, _>(
214            core_ctx,
215            bindings_ctx,
216            device,
217            multicast_addr,
218        );
219    }
220
221    /// Leaves the multicast group `multicast_addr` for `device`.
222    #[netstack3_macros::context_ip_bounds(A::Version, BC, crate)]
223    pub fn leave_ip_multicast<A: IpAddress>(
224        &mut self,
225        device: &DeviceId<BC>,
226        multicast_addr: MulticastAddr<A>,
227    ) where
228        A::Version: IpExt,
229    {
230        let (core_ctx, bindings_ctx) = self.contexts();
231        ip::device::leave_ip_multicast::<A::Version, _, _>(
232            core_ctx,
233            bindings_ctx,
234            device,
235            multicast_addr,
236        );
237    }
238
239    /// Returns whether `device` is in the multicast group `addr`.
240    #[netstack3_macros::context_ip_bounds(A::Version, BC, crate)]
241    pub fn is_in_ip_multicast<A: IpAddress>(
242        &mut self,
243        device: &DeviceId<BC>,
244        addr: MulticastAddr<A>,
245    ) -> bool
246    where
247        A::Version: IpExt,
248    {
249        use ip::{
250            AddressStatus, IpDeviceIngressStateContext, IpLayerIpExt, Ipv4PresentAddressStatus,
251            Ipv6PresentAddressStatus,
252        };
253
254        let (core_ctx, _) = self.contexts();
255        let addr_status = IpDeviceIngressStateContext::<A::Version>::address_status_for_device(
256            core_ctx,
257            addr.into_specified(),
258            device,
259        );
260        let status = match addr_status {
261            AddressStatus::Present(p) => p,
262            AddressStatus::Unassigned => return false,
263        };
264        #[derive(GenericOverIp)]
265        #[generic_over_ip(I, Ip)]
266        struct Wrap<I: IpLayerIpExt>(I::AddressStatus);
267        A::Version::map_ip(
268            Wrap(status),
269            |Wrap(v4)| match v4 {
270                Ipv4PresentAddressStatus::Multicast => true,
271                Ipv4PresentAddressStatus::LimitedBroadcast
272                | Ipv4PresentAddressStatus::SubnetBroadcast
273                | Ipv4PresentAddressStatus::LoopbackSubnet
274                | Ipv4PresentAddressStatus::UnicastAssigned
275                | Ipv4PresentAddressStatus::UnicastTentative => false,
276            },
277            |Wrap(v6)| match v6 {
278                Ipv6PresentAddressStatus::Multicast => true,
279                Ipv6PresentAddressStatus::UnicastAssigned
280                | Ipv6PresentAddressStatus::UnicastTentative => false,
281            },
282        )
283    }
284
285    /// Receive an IP packet from a device.
286    ///
287    /// `receive_ip_packet` injects a packet directly at the IP layer for this
288    /// context.
289    pub fn receive_ip_packet<I: Ip, B: BufferMut>(
290        &mut self,
291        device: &DeviceId<BC>,
292        frame_dst: Option<LocalFrameDestination>,
293        buffer: B,
294    ) {
295        self.receive_ip_packet_with_marks::<I, B>(device, frame_dst, buffer, Default::default())
296    }
297
298    /// Receive an IP packet from a device with given marks.
299    ///
300    /// `receive_ip_packet_with_marks` injects a packet directly at the IP layer
301    /// for this context with the given marks.
302    pub fn receive_ip_packet_with_marks<I: Ip, B: BufferMut>(
303        &mut self,
304        device: &DeviceId<BC>,
305        frame_dst: Option<LocalFrameDestination>,
306        buffer: B,
307        marks: Marks,
308    ) {
309        self.receive_ip_packet_with_marks_and_context::<I, B>(
310            device,
311            frame_dst,
312            buffer,
313            marks,
314            NetworkParsingContext::default(),
315        )
316    }
317
318    /// Receive an IP packet from a device with given marks and parsing context.
319    ///
320    /// `receive_ip_packet_with_marks_and_context` injects a packet directly at
321    /// the IP layer for this context with the given marks and parsing context.
322    pub fn receive_ip_packet_with_marks_and_context<I: Ip, B: BufferMut>(
323        &mut self,
324        device: &DeviceId<BC>,
325        frame_dst: Option<LocalFrameDestination>,
326        buffer: B,
327        marks: Marks,
328        parsing_context: NetworkParsingContext,
329    ) {
330        let (core_ctx, bindings_ctx) = self.contexts();
331        let packet_type = frame_dst.map(PacketType::from).unwrap_or(PacketType::Host);
332        let metadata = DeviceIpLayerMetadata::with_marks_and_packet_type(marks, packet_type);
333        match I::VERSION {
334            IpVersion::V4 => ip::receive_ipv4_packet(
335                core_ctx,
336                bindings_ctx,
337                device,
338                frame_dst,
339                metadata,
340                parsing_context,
341                None,
342                buffer,
343            ),
344            IpVersion::V6 => ip::receive_ipv6_packet(
345                core_ctx,
346                bindings_ctx,
347                device,
348                frame_dst,
349                metadata,
350                parsing_context,
351                None,
352                buffer,
353            ),
354        }
355    }
356
357    /// Receive an Ethernet frame from a device.
358    pub fn receive_ethernet_frame<B: BufferMut + Debug>(
359        &mut self,
360        device: &EthernetDeviceId<BC>,
361        buffer: B,
362    ) {
363        self.core_api().device::<EthernetLinkDevice>().receive_frame(
364            RecvEthernetFrameMeta {
365                device_id: device.clone(),
366                parsing_context: NetworkParsingContext::default(),
367                gso_info: None,
368            },
369            buffer,
370        );
371    }
372
373    /// Add a route directly to the forwarding table.
374    pub fn add_route(
375        &mut self,
376        entry: AddableEntryEither<DeviceId<BC>>,
377    ) -> Result<(), AddRouteError> {
378        let (core_ctx, _bindings_ctx) = self.contexts();
379        match entry {
380            AddableEntryEither::V4(entry) => ip::testutil::add_route::<Ipv4, _, _>(core_ctx, entry),
381            AddableEntryEither::V6(entry) => ip::testutil::add_route::<Ipv6, _, _>(core_ctx, entry),
382        }
383    }
384
385    /// Install rules, these rules will replace the rules currently installed.
386    #[netstack3_macros::context_ip_bounds(I, BC, crate)]
387    pub fn set_rules<I: IpExt>(&mut self, rules: Vec<netstack3_ip::Rule<I, DeviceId<BC>, BC>>) {
388        let (core_ctx, _bindings_ctx) = self.contexts();
389        ip::testutil::set_rules(core_ctx, rules)
390    }
391
392    /// Resolves a route with a given source address.
393    #[netstack3_macros::context_ip_bounds(I, BC, crate)]
394    pub fn resolve_route_with_src_addr<I: IpExt>(
395        &mut self,
396        src_ip: IpDeviceAddr<I::Addr>,
397        dst_ip: Option<RoutableIpAddr<I::Addr>>,
398    ) -> Result<ResolvedRoute<I, DeviceId<BC>>, ResolveRouteError> {
399        let (core_ctx, _bindings_ctx) = self.contexts();
400        ip::resolve_output_route_to_destination(
401            core_ctx,
402            None,
403            Some((src_ip, ip::NonLocalSrcAddrPolicy::Deny)),
404            dst_ip,
405            &Default::default(),
406        )
407    }
408
409    /// Resolves a route with a given mark.
410    #[netstack3_macros::context_ip_bounds(I, BC, crate)]
411    pub fn resolve_route_with_marks<I: IpExt>(
412        &mut self,
413        dst_ip: Option<RoutableIpAddr<I::Addr>>,
414        marks: &Marks,
415    ) -> Result<ResolvedRoute<I, DeviceId<BC>>, ResolveRouteError> {
416        let (core_ctx, _bindings_ctx) = self.contexts();
417        ip::resolve_output_route_to_destination(core_ctx, None, None, dst_ip, marks)
418    }
419
420    /// Delete a route from the forwarding table, returning `Err` if no route
421    /// was found to be deleted.
422    pub fn del_routes_to_subnet(
423        &mut self,
424        subnet: net_types::ip::SubnetEither,
425    ) -> Result<(), NotFoundError> {
426        let (core_ctx, _bindings_ctx) = self.contexts();
427        match subnet {
428            SubnetEither::V4(subnet) => {
429                ip::testutil::del_routes_to_subnet::<Ipv4, _, _>(core_ctx, subnet)
430            }
431            SubnetEither::V6(subnet) => {
432                ip::testutil::del_routes_to_subnet::<Ipv6, _, _>(core_ctx, subnet)
433            }
434        }
435    }
436
437    /// Deletes all routes targeting `device`.
438    pub fn del_device_routes(&mut self, device: &DeviceId<BC>) {
439        let (core_ctx, _bindings_ctx) = self.contexts();
440        ip::testutil::del_device_routes::<Ipv4, _, _>(core_ctx, device);
441        ip::testutil::del_device_routes::<Ipv6, _, _>(core_ctx, device);
442    }
443
444    /// Removes all of the routes through the device, then removes the device.
445    pub fn clear_routes_and_remove_device<D: Into<DeviceId<BC>>>(&mut self, device: D) {
446        let device = device.into();
447        self.del_device_routes(&device);
448
449        for_any_device_id!(DeviceId, DeviceProvider, D, device,
450            device => match self.core_api().device::<D>().remove_device(device) {
451                RemoveResourceResult::Removed(_external_state) => {}
452                RemoveResourceResult::Deferred(_reference_receiver) => {
453                panic!("failed to remove device")
454            }
455        });
456    }
457
458    /// Enables or disables the device for IP version `I` and returns whether it
459    /// was enabled before.
460    #[netstack3_macros::context_ip_bounds(I, BC, crate)]
461    pub fn set_ip_device_enabled<I: IpExt>(
462        &mut self,
463        device: &DeviceId<BC>,
464        enabled: bool,
465    ) -> bool {
466        let update =
467            IpDeviceConfigurationUpdate { ip_enabled: Some(enabled), ..Default::default() };
468        let prev =
469            self.core_api().device_ip::<I>().update_configuration(device, update.into()).unwrap();
470        prev.as_ref().ip_enabled.unwrap()
471    }
472
473    /// Enables `device`.
474    pub fn enable_device(&mut self, device: &DeviceId<BC>) {
475        let _was_enabled: bool = self.set_ip_device_enabled::<Ipv4>(device, true);
476        let _was_enabled: bool = self.set_ip_device_enabled::<Ipv6>(device, true);
477    }
478
479    /// Enables or disables IP packet unicast forwarding on `device`.
480    #[netstack3_macros::context_ip_bounds(I, BC, crate)]
481    pub fn set_unicast_forwarding_enabled<I: IpExt>(
482        &mut self,
483        device: &DeviceId<BC>,
484        enabled: bool,
485    ) {
486        let _config = self
487            .core_api()
488            .device_ip::<I>()
489            .update_configuration(
490                device,
491                IpDeviceConfigurationUpdate {
492                    unicast_forwarding_enabled: Some(enabled),
493                    ..Default::default()
494                }
495                .into(),
496            )
497            .unwrap();
498    }
499
500    /// Enables or disables IP packet multicast forwarding on `device`.
501    #[netstack3_macros::context_ip_bounds(I, BC, crate)]
502    pub fn set_multicast_forwarding_enabled<I: IpExt>(
503        &mut self,
504        device: &DeviceId<BC>,
505        enabled: bool,
506    ) {
507        let _config = self
508            .core_api()
509            .device_ip::<I>()
510            .update_configuration(
511                device,
512                IpDeviceConfigurationUpdate {
513                    multicast_forwarding_enabled: Some(enabled),
514                    ..Default::default()
515                }
516                .into(),
517            )
518            .unwrap();
519    }
520
521    /// Returns whether IP packet unicast forwarding is enabled on `device`.
522    #[netstack3_macros::context_ip_bounds(I, BC, crate)]
523    pub fn is_unicast_forwarding_enabled<I: IpExt>(&mut self, device: &DeviceId<BC>) -> bool {
524        let configuration = self.core_api().device_ip::<I>().get_configuration(device);
525        let IpDeviceConfiguration { unicast_forwarding_enabled, .. } = configuration.as_ref();
526        *unicast_forwarding_enabled
527    }
528
529    /// Adds a loopback device with the IPv4/IPv6 loopback addresses assigned.
530    pub fn add_loopback(&mut self) -> LoopbackDeviceId<BC>
531    where
532        <BC as DeviceLayerStateTypes>::DeviceIdentifier: Default,
533        <BC as DeviceLayerStateTypes>::LoopbackDeviceState: Default,
534    {
535        let loopback_id = self.core_api().device::<LoopbackDevice>().add_device_with_default_state(
536            LoopbackCreationProperties { mtu: Mtu::new(u32::MAX) },
537            DEFAULT_INTERFACE_METRIC,
538        );
539        let device_id: DeviceId<_> = loopback_id.clone().into();
540        self.enable_device(&device_id);
541
542        self.core_api()
543            .device_ip::<Ipv4>()
544            .add_ip_addr_subnet(
545                &device_id,
546                AddrSubnet::from_witness(Ipv4::LOOPBACK_ADDRESS, Ipv4::LOOPBACK_SUBNET.prefix())
547                    .unwrap(),
548            )
549            .unwrap();
550
551        self.core_api()
552            .device_ip::<Ipv6>()
553            .add_ip_addr_subnet(
554                &device_id,
555                AddrSubnet::from_witness(Ipv6::LOOPBACK_ADDRESS, Ipv6::LOOPBACK_SUBNET.prefix())
556                    .unwrap(),
557            )
558            .unwrap();
559        loopback_id
560    }
561}
562
563impl<'a> TestApi<'a, FakeBindingsCtx> {
564    /// Handles any pending frames and returns true if any frames that were in
565    /// the RX queue were processed.
566    pub fn handle_queued_rx_packets(&mut self) -> bool {
567        let mut handled = false;
568        loop {
569            let (_, bindings_ctx) = self.contexts();
570            let rx_available = core::mem::take(&mut bindings_ctx.state_mut().rx_available);
571            if rx_available.len() == 0 {
572                break handled;
573            }
574            handled = true;
575            for id in rx_available.into_iter() {
576                loop {
577                    match self.core_api().receive_queue().handle_queued_frames(&id) {
578                        WorkQueueReport::AllDone => break,
579                        WorkQueueReport::Pending => (),
580                    }
581                }
582            }
583        }
584    }
585}
586
587#[derive(Default)]
588/// Bindings context state held by [`FakeBindingsCtx`].
589pub struct FakeBindingsCtxState {
590    icmpv4_replies:
591        HashMap<IcmpSocketId<Ipv4, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>, Vec<Vec<u8>>>,
592    icmpv6_replies:
593        HashMap<IcmpSocketId<Ipv6, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>, Vec<Vec<u8>>>,
594    udpv4_received:
595        HashMap<UdpSocketId<Ipv4, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>, Vec<Vec<u8>>>,
596    udpv6_received:
597        HashMap<UdpSocketId<Ipv6, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>, Vec<Vec<u8>>>,
598    /// IDs with rx queue signaled available.
599    pub rx_available: Vec<LoopbackDeviceId<FakeBindingsCtx>>,
600    /// IDs with tx queue signaled available.
601    pub tx_available: Vec<DeviceId<FakeBindingsCtx>>,
602    /// Recorded `(SocketInfo, Marks, PacketType, Option<GsoInfo>)` passed to
603    /// `SocketOpsFilter::on_ingress`.
604    pub packet_metadata: Vec<(
605        netstack3_base::socket::SocketInfo,
606        Marks,
607        PacketType,
608        Option<netstack3_base::GsoInfo>,
609    )>,
610    /// Deferred resource removals.
611    #[cfg(loom)]
612    pub deferred_receivers: Vec<loom_notifiers::LoomReceiver>,
613}
614
615impl FakeBindingsCtxState {
616    pub(crate) fn udp_state_mut<I: IpExt>(
617        &mut self,
618    ) -> &mut HashMap<UdpSocketId<I, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>, Vec<Vec<u8>>>
619    {
620        #[derive(GenericOverIp)]
621        #[generic_over_ip(I, Ip)]
622        struct Wrapper<'a, I: IpExt>(
623            &'a mut HashMap<
624                UdpSocketId<I, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>,
625                Vec<Vec<u8>>,
626            >,
627        );
628        let Wrapper(map) = I::map_ip_out::<_, Wrapper<'_, I>>(
629            self,
630            |this| Wrapper(&mut this.udpv4_received),
631            |this| Wrapper(&mut this.udpv6_received),
632        );
633        map
634    }
635}
636
637/// Shorthand for [`Ctx`] with a [`FakeBindingsCtx`].
638pub type FakeCtx = Ctx<FakeBindingsCtx>;
639/// Shorthand for [`StackState`] that uses a [`FakeBindingsCtx`].
640pub type FakeCoreCtx = StackState<FakeBindingsCtx>;
641
642type InnerFakeBindingsCtx = netstack3_base::testutil::FakeBindingsCtx<
643    TimerId<FakeBindingsCtx>,
644    DispatchedEvent,
645    FakeBindingsCtxState,
646    DispatchedFrame,
647>;
648
649/// Test-only implementation of [`BindingsContext`].
650#[derive(Default, Clone)]
651pub struct FakeBindingsCtx(Arc<Mutex<InnerFakeBindingsCtx>>);
652
653/// A wrapper type that makes it easier to implement `Deref` (and optionally
654/// `DerefMut`) for a value that is protected by a lock.
655///
656/// The first field is the type that provides access to the inner value,
657/// probably a lock guard. The second and third fields are functions that, given
658/// the first field, provide shared and mutable access (respectively) to the
659/// inner value.
660// TODO(https://github.com/rust-lang/rust/issues/117108): Replace this with
661// mapped mutex guards once stable.
662struct Wrapper<S, Callback, CallbackMut>(S, Callback, CallbackMut);
663
664impl<T: ?Sized, S: Deref, Callback: for<'a> Fn(&'a <S as Deref>::Target) -> &'a T, CallbackMut>
665    Deref for Wrapper<S, Callback, CallbackMut>
666{
667    type Target = T;
668
669    fn deref(&self) -> &T {
670        let Self(guard, f, _) = self;
671        let target = guard.deref();
672        f(target)
673    }
674}
675
676impl<
677    T: ?Sized,
678    S: DerefMut,
679    Callback: for<'a> Fn(&'a <S as Deref>::Target) -> &'a T,
680    CallbackMut: for<'a> Fn(&'a mut <S as Deref>::Target) -> &'a mut T,
681> DerefMut for Wrapper<S, Callback, CallbackMut>
682{
683    fn deref_mut(&mut self) -> &mut T {
684        let Self(guard, _, f) = self;
685        let target = guard.deref_mut();
686        f(target)
687    }
688}
689
690impl FakeBindingsCtx {
691    fn with_inner<F: FnOnce(&InnerFakeBindingsCtx) -> O, O>(&self, f: F) -> O {
692        let Self(this) = self;
693        let locked = this.lock();
694        f(&*locked)
695    }
696
697    fn with_inner_mut<F: FnOnce(&mut InnerFakeBindingsCtx) -> O, O>(&self, f: F) -> O {
698        let Self(this) = self;
699        let mut locked = this.lock();
700        f(&mut *locked)
701    }
702
703    /// Gets the fake timer context.
704    pub fn timer_ctx(&self) -> impl Deref<Target = FakeTimerCtx<TimerId<Self>>> + '_ {
705        // NB: Helper function is required to satisfy lifetime requirements of
706        // borrow.
707        fn get_timers<'a>(
708            i: &'a InnerFakeBindingsCtx,
709        ) -> &'a FakeTimerCtx<TimerId<FakeBindingsCtx>> {
710            &i.timers
711        }
712        Wrapper(self.0.lock(), get_timers, ())
713    }
714
715    /// Returns a mutable reference guard to [`FakeBindingsCtxState`].
716    pub fn state_mut(&mut self) -> impl DerefMut<Target = FakeBindingsCtxState> + '_ {
717        // NB: Helper functions are required to satisfy lifetime requirements of
718        // borrow.
719        fn get_state<'a>(i: &'a InnerFakeBindingsCtx) -> &'a FakeBindingsCtxState {
720            &i.state
721        }
722        fn get_state_mut<'a>(i: &'a mut InnerFakeBindingsCtx) -> &'a mut FakeBindingsCtxState {
723            &mut i.state
724        }
725        Wrapper(self.0.lock(), get_state, get_state_mut)
726    }
727
728    /// Copy all ethernet frames sent so far.
729    ///
730    /// # Panics
731    ///
732    /// Panics if the there are non-Ethernet frames stored.
733    pub fn copy_ethernet_frames(
734        &mut self,
735    ) -> Vec<(EthernetWeakDeviceId<FakeBindingsCtx>, Vec<u8>)> {
736        self.with_inner_mut(|ctx| {
737            ctx.frames
738                .frames()
739                .iter()
740                .map(|(meta, frame)| match meta {
741                    DispatchedFrame::Ethernet(eth) => (eth.clone(), frame.clone()),
742                    DispatchedFrame::PureIp(ip) => panic!("unexpected IP packet {ip:?}: {frame:?}"),
743                })
744                .collect()
745        })
746    }
747
748    /// Take all ethernet frames sent so far.
749    ///
750    /// # Panics
751    ///
752    /// Panics if the there are non-Ethernet frames stored.
753    pub fn take_ethernet_frames(
754        &mut self,
755    ) -> Vec<(EthernetWeakDeviceId<FakeBindingsCtx>, Vec<u8>)> {
756        self.with_inner_mut(|ctx| {
757            ctx.frames
758                .take_frames()
759                .into_iter()
760                .map(|(meta, frame)| match meta {
761                    DispatchedFrame::Ethernet(eth) => (eth, frame),
762                    DispatchedFrame::PureIp(ip) => panic!("unexpected IP packet {ip:?}: {frame:?}"),
763                })
764                .collect()
765        })
766    }
767
768    /// Take all IP frames sent so far.
769    ///
770    /// # Panics
771    ///
772    /// Panics if the there are non-IP frames stored.
773    pub fn take_ip_frames(&mut self) -> Vec<(PureIpDeviceAndIpVersion<FakeBindingsCtx>, Vec<u8>)> {
774        self.with_inner_mut(|ctx| {
775            ctx.frames
776                .take_frames()
777                .into_iter()
778                .map(|(meta, frame)| match meta {
779                    DispatchedFrame::Ethernet(eth) => {
780                        panic!("unexpected Ethernet frame {eth:?}: {frame:?}")
781                    }
782                    DispatchedFrame::PureIp(ip) => (ip, frame),
783                })
784                .collect()
785        })
786    }
787
788    /// Takes all the events stored in the fake context.
789    pub fn take_events(&mut self) -> Vec<DispatchedEvent> {
790        self.with_inner_mut(|ctx| ctx.events.take())
791    }
792
793    /// Takes all the received ICMP replies for a given `conn`.
794    pub fn take_icmp_replies<I: IpExt>(
795        &mut self,
796        conn: &IcmpSocketId<I, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>,
797    ) -> Vec<Vec<u8>> {
798        I::map_ip_in(
799            (IpInvariant(self), conn),
800            |(IpInvariant(this), conn)| this.state_mut().icmpv4_replies.remove(conn),
801            |(IpInvariant(this), conn)| this.state_mut().icmpv6_replies.remove(conn),
802        )
803        .unwrap_or_else(Vec::default)
804    }
805
806    /// Takes all received UDP frames from the fake bindings context.
807    pub fn take_udp_received<I: IpExt>(
808        &mut self,
809        conn: &UdpSocketId<I, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>,
810    ) -> Vec<Vec<u8>> {
811        self.state_mut().udp_state_mut::<I>().remove(conn).unwrap_or_else(Vec::default)
812    }
813
814    /// Seed the RNG.
815    pub fn seed_rng(&self, seed: u128) {
816        self.with_inner_mut(|ctx| {
817            ctx.rng = FakeCryptoRng::new_xorshift(seed);
818        })
819    }
820
821    /// Moves the fake clock forward by `duration`. Doesn't trigger any timers.
822    pub fn sleep(&self, duration: Duration) {
823        self.with_inner_mut(|ctx| ctx.timers.instant.sleep(duration));
824    }
825}
826
827impl MatcherBindingsTypes for FakeBindingsCtx {
828    type DeviceClass = ();
829    type BindingsPacketMatcher = !;
830}
831
832impl DeviceBufferBindingsTypes for FakeBindingsCtx {
833    type TxBuffer = packet::Buf<Vec<u8>>;
834    type TxAllocator = netstack3_device::queue::BufVecU8Allocator;
835}
836
837struct FakeSocketOpsFilter<'a>(&'a FakeBindingsCtx);
838
839impl SocketOpsFilter<DeviceId<FakeBindingsCtx>> for FakeSocketOpsFilter<'_> {
840    fn on_egress<I: netstack3_filter::FilterIpExt, P: netstack3_filter::FilterIpPacket<I>>(
841        &self,
842        _packet: &P,
843        _device: &DeviceId<FakeBindingsCtx>,
844        _socket_info: netstack3_base::socket::SocketInfo,
845        _marks: &Marks,
846        _gso_info: Option<netstack3_base::GsoInfo>,
847    ) -> netstack3_filter::SocketEgressFilterResult {
848        netstack3_filter::SocketEgressFilterResult::Pass { congestion: false }
849    }
850
851    fn on_ingress(
852        &self,
853        _ip_version: net_types::ip::IpVersion,
854        _packet: packet::FragmentedByteSlice<'_, &[u8]>,
855        _header_len: usize,
856        _device: &DeviceId<FakeBindingsCtx>,
857        socket_info: netstack3_base::socket::SocketInfo,
858        marks: &Marks,
859        packet_type: PacketType,
860        gso_info: Option<netstack3_base::GsoInfo>,
861    ) -> netstack3_filter::SocketIngressFilterResult {
862        self.0.0.lock().state.packet_metadata.push((socket_info, *marks, packet_type, gso_info));
863        netstack3_filter::SocketIngressFilterResult::Accept
864    }
865}
866
867impl SocketOpsFilterBindingContext<DeviceId<FakeBindingsCtx>> for FakeBindingsCtx {
868    fn socket_ops_filter(&self) -> impl SocketOpsFilter<DeviceId<FakeBindingsCtx>> {
869        FakeSocketOpsFilter(self)
870    }
871}
872
873impl WithFakeTimerContext<TimerId<FakeBindingsCtx>> for FakeBindingsCtx {
874    fn with_fake_timer_ctx<O, F: FnOnce(&FakeTimerCtx<TimerId<FakeBindingsCtx>>) -> O>(
875        &self,
876        f: F,
877    ) -> O {
878        self.with_inner(|ctx| f(&ctx.timers))
879    }
880
881    fn with_fake_timer_ctx_mut<O, F: FnOnce(&mut FakeTimerCtx<TimerId<FakeBindingsCtx>>) -> O>(
882        &mut self,
883        f: F,
884    ) -> O {
885        self.with_inner_mut(|ctx| f(&mut ctx.timers))
886    }
887}
888
889impl WithFakeFrameContext<DispatchedFrame> for FakeBindingsCtx {
890    fn with_fake_frame_ctx_mut<O, F: FnOnce(&mut FakeFrameCtx<DispatchedFrame>) -> O>(
891        &mut self,
892        f: F,
893    ) -> O {
894        self.with_inner_mut(|ctx| f(&mut ctx.frames))
895    }
896}
897
898impl InstantBindingsTypes for FakeBindingsCtx {
899    type Instant = FakeInstant;
900    type AtomicInstant = FakeAtomicInstant;
901}
902
903impl InstantContext for FakeBindingsCtx {
904    fn now(&self) -> FakeInstant {
905        self.with_inner(|ctx| ctx.now())
906    }
907}
908
909impl TimerBindingsTypes for FakeBindingsCtx {
910    type Timer = <FakeTimerCtx<TimerId<Self>> as TimerBindingsTypes>::Timer;
911    type DispatchId = TimerId<Self>;
912    type UniqueTimerId = <FakeTimerCtx<TimerId<Self>> as TimerBindingsTypes>::UniqueTimerId;
913}
914
915impl TimerContext for FakeBindingsCtx {
916    fn new_timer(&mut self, id: Self::DispatchId) -> Self::Timer {
917        self.with_inner_mut(|ctx| ctx.new_timer(id))
918    }
919
920    fn schedule_timer_instant(
921        &mut self,
922        time: Self::Instant,
923        timer: &mut Self::Timer,
924    ) -> Option<Self::Instant> {
925        // Filter out conntrack GC timers. We don't need conntrack GC in most
926        // tests, and this causes issues with tests that are expecting the
927        // netstack to quiesce.
928        match timer.dispatch_id.0 {
929            TimerIdInner::IpLayer(IpLayerTimerId::FilterTimerv4(FilterTimerId::ConntrackGc(_)))
930            | TimerIdInner::IpLayer(IpLayerTimerId::FilterTimerv6(FilterTimerId::ConntrackGc(_))) =>
931            {
932                return None;
933            }
934            _ => {}
935        }
936        self.with_inner_mut(|ctx| ctx.schedule_timer_instant(time, timer))
937    }
938
939    fn cancel_timer(&mut self, timer: &mut Self::Timer) -> Option<Self::Instant> {
940        self.with_inner_mut(|ctx| ctx.cancel_timer(timer))
941    }
942
943    fn scheduled_instant(&self, timer: &mut Self::Timer) -> Option<Self::Instant> {
944        self.with_inner_mut(|ctx| ctx.scheduled_instant(timer))
945    }
946
947    fn unique_timer_id(&self, timer: &Self::Timer) -> Self::UniqueTimerId {
948        self.with_inner_mut(|ctx| ctx.unique_timer_id(timer))
949    }
950}
951
952impl TxMetadataBindingsTypes for FakeBindingsCtx {
953    type TxMetadata = CoreTxMetadata<Self>;
954}
955
956impl RngContext for FakeBindingsCtx {
957    type Rng<'a> = FakeCryptoRng;
958
959    fn rng(&mut self) -> Self::Rng<'_> {
960        let Self(this) = self;
961        this.lock().rng()
962    }
963}
964
965impl<T: Into<DispatchedEvent>> EventContext<T> for FakeBindingsCtx {
966    fn on_event(&mut self, event: T) {
967        self.with_inner_mut(|ctx| ctx.events.on_event(event.into()))
968    }
969}
970
971impl TcpBindingsTypes for FakeBindingsCtx {
972    type ReceiveBuffer = Arc<Mutex<RingBuffer>>;
973
974    type SendBuffer = TestSendBuffer;
975
976    type ReturnedBuffers = ClientBuffers;
977
978    type ListenerNotifierOrProvidedBuffers = ProvidedBuffers;
979
980    fn new_passive_open_buffers(
981        buffer_sizes: BufferSizes,
982    ) -> (Self::ReceiveBuffer, Self::SendBuffer, Self::ReturnedBuffers) {
983        let client = ClientBuffers::new(buffer_sizes);
984        (
985            Arc::clone(&client.receive),
986            TestSendBuffer::new(Arc::clone(&client.send), RingBuffer::default()),
987            client,
988        )
989    }
990}
991
992impl IpRoutingBindingsTypes for FakeBindingsCtx {
993    type RoutingTableId = ();
994}
995
996impl MarksBindingsContext for FakeBindingsCtx {
997    fn marks_to_keep_on_egress() -> &'static [MarkDomain] {
998        const MARKS: [MarkDomain; 1] = [MarkDomain::Mark1];
999        &MARKS
1000    }
1001
1002    fn marks_to_set_on_ingress() -> &'static [MarkDomain] {
1003        const MARKS: [MarkDomain; 1] = [MarkDomain::Mark2];
1004        &MARKS
1005    }
1006}
1007
1008#[cfg(not(loom))]
1009mod fake_notifiers {
1010
1011    use super::*;
1012
1013    impl ReferenceNotifiers for FakeBindingsCtx {
1014        type ReferenceReceiver<T: 'static> = !;
1015
1016        type ReferenceNotifier<T: Send + 'static> = !;
1017
1018        fn new_reference_notifier<T: Send + 'static>(
1019            debug_references: DynDebugReferences,
1020        ) -> (Self::ReferenceNotifier<T>, Self::ReferenceReceiver<T>) {
1021            // NB: We don't want deferred destruction in core tests. These are
1022            // always single-threaded and single-task, and we want to encourage
1023            // explicit cleanup.
1024            panic!(
1025                "FakeBindingsCtx can't create deferred reference notifiers for type {}: \
1026                debug_references={debug_references:?}",
1027                core::any::type_name::<T>()
1028            );
1029        }
1030    }
1031
1032    impl DeferredResourceRemovalContext for FakeBindingsCtx {
1033        fn defer_removal<T: Send + 'static>(&mut self, receiver: Self::ReferenceReceiver<T>) {
1034            match receiver {}
1035        }
1036    }
1037}
1038
1039/// Implements the notifier methods for loom tests, which use multiple threads
1040/// and hence need to handle notifiers.
1041#[cfg(loom)]
1042mod loom_notifiers {
1043    use super::*;
1044
1045    use core::sync::atomic::{self, AtomicBool};
1046    use netstack3_sync::rc::Notifier;
1047
1048    #[derive(Debug)]
1049    pub struct LoomNotifier(Arc<AtomicBool>);
1050
1051    #[derive(Debug)]
1052    pub struct LoomReceiver {
1053        pub debug_refs: DynDebugReferences,
1054        pub signal: Arc<AtomicBool>,
1055    }
1056
1057    impl LoomReceiver {
1058        #[track_caller]
1059        pub fn assert_signalled(&self) {
1060            let Self { debug_refs, signal } = self;
1061            assert!(signal.load(atomic::Ordering::SeqCst), "pending references: {debug_refs:?}")
1062        }
1063    }
1064
1065    impl<T> Notifier<T> for LoomNotifier {
1066        fn notify(&mut self, _data: T) {
1067            let Self(signal) = self;
1068            signal.store(true, atomic::Ordering::SeqCst);
1069        }
1070    }
1071
1072    impl ReferenceNotifiers for FakeBindingsCtx {
1073        type ReferenceReceiver<T: 'static> = LoomReceiver;
1074        type ReferenceNotifier<T: Send + 'static> = LoomNotifier;
1075
1076        fn new_reference_notifier<T: Send + 'static>(
1077            debug_refs: DynDebugReferences,
1078        ) -> (Self::ReferenceNotifier<T>, Self::ReferenceReceiver<T>) {
1079            let signal = Arc::new(AtomicBool::default());
1080            (LoomNotifier(Arc::clone(&signal)), LoomReceiver { debug_refs, signal })
1081        }
1082    }
1083
1084    impl DeferredResourceRemovalContext for FakeBindingsCtx {
1085        fn defer_removal<T: Send + 'static>(&mut self, receiver: Self::ReferenceReceiver<T>) {
1086            self.state_mut().deferred_receivers.push(receiver);
1087        }
1088    }
1089}
1090
1091/// A link resolution notifier that ignores all notifications.
1092#[derive(Debug)]
1093pub struct NoOpLinkResolutionNotifier;
1094
1095impl<D: LinkDevice> LinkResolutionContext<D> for FakeBindingsCtx {
1096    type Notifier = NoOpLinkResolutionNotifier;
1097}
1098
1099impl<D: LinkDevice> LinkResolutionNotifier<D> for NoOpLinkResolutionNotifier {
1100    type Observer = ();
1101
1102    fn new() -> (Self, Self::Observer) {
1103        (NoOpLinkResolutionNotifier, ())
1104    }
1105
1106    fn notify(self, _result: Result<UnicastAddr<D::Address>, AddressResolutionFailed>) {}
1107}
1108
1109#[derive(Clone)]
1110struct DeviceConfig {
1111    mac: UnicastAddr<Mac>,
1112    addr_subnet: Option<AddrSubnetEither>,
1113    ipv4_config: Option<Ipv4DeviceConfigurationUpdate>,
1114    ipv6_config: Option<Ipv6DeviceConfigurationUpdate>,
1115}
1116
1117/// A builder for `FakeCtx`s.
1118///
1119/// A `FakeCtxBuilder` is capable of storing the configuration of a network
1120/// stack including forwarding table entries, devices and their assigned
1121/// addresses and configurations, ARP table entries, etc. It can be built using
1122/// `build`, producing a `FakeCtx` with all of the appropriate state configured.
1123#[derive(Clone, Default)]
1124pub struct FakeCtxBuilder {
1125    devices: Vec<DeviceConfig>,
1126    // TODO(https://fxbug.dev/42083952): Use NeighborAddr when available.
1127    arp_table_entries: Vec<(usize, SpecifiedAddr<Ipv4Addr>, UnicastAddr<Mac>)>,
1128    ndp_table_entries: Vec<(usize, UnicastAddr<Ipv6Addr>, UnicastAddr<Mac>)>,
1129    // usize refers to index into devices Vec.
1130    device_routes: Vec<(SubnetEither, usize)>,
1131}
1132
1133impl FakeCtxBuilder {
1134    /// Construct a `FakeCtxBuilder` from a `TestAddrs`.
1135    pub fn with_addrs<A: IpAddress>(addrs: TestAddrs<A>) -> FakeCtxBuilder {
1136        assert!(addrs.subnet.contains(&addrs.local_ip));
1137        assert!(addrs.subnet.contains(&addrs.remote_ip));
1138
1139        let mut builder = FakeCtxBuilder::default();
1140        builder.devices.push(DeviceConfig {
1141            mac: addrs.local_mac,
1142            addr_subnet: Some(
1143                AddrSubnetEither::new(addrs.local_ip.get().into(), addrs.subnet.prefix()).unwrap(),
1144            ),
1145            ipv4_config: None,
1146            ipv6_config: None,
1147        });
1148
1149        match addrs.remote_ip.into() {
1150            IpAddr::V4(ip) => builder.arp_table_entries.push((0, ip, addrs.remote_mac)),
1151            IpAddr::V6(ip) => builder.ndp_table_entries.push((
1152                0,
1153                UnicastAddr::new(ip.get()).unwrap(),
1154                addrs.remote_mac,
1155            )),
1156        };
1157
1158        // Even with fixed ipv4 address we can have IPv6 link local addresses
1159        // pre-cached.
1160        builder.ndp_table_entries.push((
1161            0,
1162            addrs.remote_mac.to_ipv6_link_local().addr().get(),
1163            addrs.remote_mac,
1164        ));
1165
1166        builder.device_routes.push((addrs.subnet.into(), 0));
1167        builder
1168    }
1169
1170    /// Add a device.
1171    ///
1172    /// `add_device` returns a key which can be used to refer to the device in
1173    /// future calls to `add_arp_table_entry` and `add_device_route`.
1174    pub fn add_device(&mut self, mac: UnicastAddr<Mac>) -> usize {
1175        let idx = self.devices.len();
1176        self.devices.push(DeviceConfig {
1177            mac,
1178            addr_subnet: None,
1179            ipv4_config: None,
1180            ipv6_config: None,
1181        });
1182        idx
1183    }
1184
1185    /// Add a device with an IPv4 and IPv6 configuration.
1186    ///
1187    /// `add_device_with_config` is like `add_device`, except that it takes an
1188    /// IPv4 and IPv6 configuration to apply to the device when it is enabled.
1189    pub fn add_device_with_config(
1190        &mut self,
1191        mac: UnicastAddr<Mac>,
1192        ipv4_config: Ipv4DeviceConfigurationUpdate,
1193        ipv6_config: Ipv6DeviceConfigurationUpdate,
1194    ) -> usize {
1195        let idx = self.devices.len();
1196        self.devices.push(DeviceConfig {
1197            mac,
1198            addr_subnet: None,
1199            ipv4_config: Some(ipv4_config),
1200            ipv6_config: Some(ipv6_config),
1201        });
1202        idx
1203    }
1204
1205    /// Add a device with an associated IP address.
1206    ///
1207    /// `add_device_with_ip` is like `add_device`, except that it takes an
1208    /// associated IP address and subnet to assign to the device.
1209    pub fn add_device_with_ip<A: IpAddress>(
1210        &mut self,
1211        mac: UnicastAddr<Mac>,
1212        ip: A,
1213        subnet: Subnet<A>,
1214    ) -> usize {
1215        assert!(subnet.contains(&ip));
1216        let idx = self.devices.len();
1217        self.devices.push(DeviceConfig {
1218            mac,
1219            addr_subnet: Some(AddrSubnetEither::new(ip.into(), subnet.prefix()).unwrap()),
1220            ipv4_config: None,
1221            ipv6_config: None,
1222        });
1223        self.device_routes.push((subnet.into(), idx));
1224        idx
1225    }
1226
1227    /// Add a device with an associated IP address and a particular IPv4 and
1228    /// IPv6 configuration.
1229    ///
1230    /// `add_device_with_ip_and_config` is like `add_device`, except that it
1231    /// takes an associated IP address and subnet to assign to the device, as
1232    /// well as IPv4 and IPv6 configurations to apply to the device when it is
1233    /// enabled.
1234    pub fn add_device_with_ip_and_config<A: IpAddress>(
1235        &mut self,
1236        mac: UnicastAddr<Mac>,
1237        ip: A,
1238        subnet: Subnet<A>,
1239        ipv4_config: Ipv4DeviceConfigurationUpdate,
1240        ipv6_config: Ipv6DeviceConfigurationUpdate,
1241    ) -> usize {
1242        assert!(subnet.contains(&ip));
1243        let idx = self.devices.len();
1244        self.devices.push(DeviceConfig {
1245            mac,
1246            addr_subnet: Some(AddrSubnetEither::new(ip.into(), subnet.prefix()).unwrap()),
1247            ipv4_config: Some(ipv4_config),
1248            ipv6_config: Some(ipv6_config),
1249        });
1250        self.device_routes.push((subnet.into(), idx));
1251        idx
1252    }
1253
1254    /// Add an ARP table entry for a device's ARP table.
1255    pub fn add_arp_table_entry(
1256        &mut self,
1257        device: usize,
1258        // TODO(https://fxbug.dev/42083952): Use NeighborAddr when available.
1259        ip: SpecifiedAddr<Ipv4Addr>,
1260        mac: UnicastAddr<Mac>,
1261    ) {
1262        self.arp_table_entries.push((device, ip, mac));
1263    }
1264
1265    /// Add an NDP table entry for a device's NDP table.
1266    pub fn add_ndp_table_entry(
1267        &mut self,
1268        device: usize,
1269        // TODO(https://fxbug.dev/42083952): Use NeighborAddr when available.
1270        ip: UnicastAddr<Ipv6Addr>,
1271        mac: UnicastAddr<Mac>,
1272    ) {
1273        self.ndp_table_entries.push((device, ip, mac));
1274    }
1275
1276    /// Add either an NDP entry (if IPv6) or ARP entry (if IPv4) to a
1277    /// `FakeCtxBuilder`.
1278    pub fn add_arp_or_ndp_table_entry<A: IpAddress>(
1279        &mut self,
1280        device: usize,
1281        // TODO(https://fxbug.dev/42083952): Use NeighborAddr when available.
1282        ip: SpecifiedAddr<A>,
1283        mac: UnicastAddr<Mac>,
1284    ) {
1285        match ip.into() {
1286            IpAddr::V4(ip) => self.add_arp_table_entry(device, ip, mac),
1287            IpAddr::V6(ip) => {
1288                self.add_ndp_table_entry(device, UnicastAddr::new(ip.get()).unwrap(), mac)
1289            }
1290        }
1291    }
1292
1293    /// Builds a `Ctx` from the present configuration with a default dispatcher.
1294    pub fn build(self) -> (FakeCtx, Vec<EthernetDeviceId<FakeBindingsCtx>>) {
1295        self.build_with_modifications(|_| {})
1296    }
1297
1298    /// `build_with_modifications` is equivalent to `build`, except that after
1299    /// the `StackStateBuilder` is initialized, it is passed to `f` for further
1300    /// modification before the `Ctx` is constructed.
1301    pub fn build_with_modifications<F: FnOnce(&mut StackStateBuilder)>(
1302        self,
1303        f: F,
1304    ) -> (FakeCtx, Vec<EthernetDeviceId<FakeBindingsCtx>>) {
1305        let mut stack_builder = StackStateBuilder::default();
1306        f(&mut stack_builder);
1307        self.build_with(stack_builder)
1308    }
1309
1310    /// Build a `Ctx` from the present configuration with a caller-provided
1311    /// dispatcher and `StackStateBuilder`.
1312    pub fn build_with(
1313        self,
1314        state_builder: StackStateBuilder,
1315    ) -> (FakeCtx, Vec<EthernetDeviceId<FakeBindingsCtx>>) {
1316        let mut ctx = Ctx::new_with_builder(state_builder);
1317
1318        let FakeCtxBuilder { devices, arp_table_entries, ndp_table_entries, device_routes } = self;
1319        let idx_to_device_id: Vec<_> = devices
1320            .into_iter()
1321            .map(|DeviceConfig { mac, addr_subnet: ip_and_subnet, ipv4_config, ipv6_config }| {
1322                let eth_id =
1323                    ctx.core_api().device::<EthernetLinkDevice>().add_device_with_default_state(
1324                        EthernetCreationProperties {
1325                            mac: mac,
1326                            max_frame_size: IPV6_MIN_IMPLIED_MAX_FRAME_SIZE,
1327                            tx_offload_spec: Default::default(),
1328                        },
1329                        DEFAULT_INTERFACE_METRIC,
1330                    );
1331                let id = eth_id.clone().into();
1332                if let Some(ipv4_config) = ipv4_config {
1333                    let _previous = ctx
1334                        .core_api()
1335                        .device_ip::<Ipv4>()
1336                        .update_configuration(&id, ipv4_config)
1337                        .unwrap();
1338                }
1339                if let Some(ipv6_config) = ipv6_config {
1340                    let _previous = ctx
1341                        .core_api()
1342                        .device_ip::<Ipv6>()
1343                        .update_configuration(&id, ipv6_config)
1344                        .unwrap();
1345                }
1346                ctx.test_api().enable_device(&id);
1347                match ip_and_subnet {
1348                    Some(addr_sub) => {
1349                        ctx.core_api().device_ip_any().add_ip_addr_subnet(&id, addr_sub).unwrap();
1350                    }
1351                    None => {}
1352                }
1353                eth_id
1354            })
1355            .collect();
1356        for (idx, ip, mac) in arp_table_entries {
1357            let device = &idx_to_device_id[idx];
1358            ctx.core_api()
1359                .neighbor::<Ipv4, EthernetLinkDevice>()
1360                .insert_static_entry(&device, ip.get(), mac)
1361                .expect("error inserting static ARP entry");
1362        }
1363        for (idx, ip, mac) in ndp_table_entries {
1364            let device = &idx_to_device_id[idx];
1365            ctx.core_api()
1366                .neighbor::<Ipv6, EthernetLinkDevice>()
1367                .insert_static_entry(&device, ip.get(), mac)
1368                .expect("error inserting static NDP entry");
1369        }
1370
1371        for (subnet, idx) in device_routes {
1372            let device = &idx_to_device_id[idx];
1373            ctx.test_api()
1374                .add_route(AddableEntryEither::without_gateway(
1375                    subnet,
1376                    device.clone().into(),
1377                    AddableMetric::ExplicitMetric(RawMetric(0)),
1378                ))
1379                .expect("add device route");
1380        }
1381
1382        (ctx, idx_to_device_id)
1383    }
1384}
1385
1386/// The fake network spec to use in integration tests.
1387///
1388/// It creates an Ethernet network.
1389pub enum FakeCtxNetworkSpec {}
1390
1391impl FakeNetworkSpec for FakeCtxNetworkSpec {
1392    type Context = FakeCtx;
1393    type TimerId = TimerId<FakeBindingsCtx>;
1394    type SendMeta = DispatchedFrame;
1395    type RecvMeta = EthernetDeviceId<FakeBindingsCtx>;
1396    fn handle_frame(ctx: &mut FakeCtx, device_id: Self::RecvMeta, data: Buf<Vec<u8>>) {
1397        ctx.core_api().device::<EthernetLinkDevice>().receive_frame(
1398            RecvEthernetFrameMeta {
1399                device_id,
1400                parsing_context: NetworkParsingContext::default(),
1401                gso_info: None,
1402            },
1403            data,
1404        )
1405    }
1406    fn handle_timer(ctx: &mut FakeCtx, dispatch: Self::TimerId, timer: FakeTimerId) {
1407        ctx.core_api().handle_timer(dispatch, timer)
1408    }
1409    fn process_queues(ctx: &mut FakeCtx) -> bool {
1410        ctx.test_api().handle_queued_rx_packets()
1411    }
1412    fn fake_frames(ctx: &mut FakeCtx) -> &mut impl WithFakeFrameContext<Self::SendMeta> {
1413        &mut ctx.bindings_ctx
1414    }
1415}
1416
1417impl<I: IpExt> UdpReceiveBindingsContext<I, DeviceId<Self>> for FakeBindingsCtx {
1418    fn receive_udp(
1419        &mut self,
1420        id: &UdpSocketId<I, WeakDeviceId<Self>, FakeBindingsCtx>,
1421        _device_id: &DeviceId<Self>,
1422        _meta: UdpPacketMeta<I>,
1423        body: &[u8],
1424    ) -> Result<(), ReceiveUdpError> {
1425        let mut state = self.state_mut();
1426        let received =
1427            (&mut *state).udp_state_mut::<I>().entry(id.clone()).or_insert_with(Vec::default);
1428        received.push(body.to_owned());
1429        Ok(())
1430    }
1431
1432    fn on_socket_error(
1433        &mut self,
1434        _id: &UdpSocketId<I, WeakDeviceId<Self>, FakeBindingsCtx>,
1435        _err: PendingDatagramSocketError,
1436    ) {
1437    }
1438}
1439
1440impl UdpBindingsTypes for FakeBindingsCtx {
1441    type ExternalData<I: Ip> = ();
1442    type SendToken = FakeSendToken;
1443}
1444
1445impl<I: IpExt> IcmpEchoBindingsContext<I, DeviceId<Self>> for FakeBindingsCtx {
1446    fn receive_icmp_echo_reply<B: BufferMut>(
1447        &mut self,
1448        conn: &IcmpSocketId<I, WeakDeviceId<FakeBindingsCtx>, FakeBindingsCtx>,
1449        _device: &DeviceId<Self>,
1450        _src_ip: I::Addr,
1451        _dst_ip: I::Addr,
1452        _id: u16,
1453        data: B,
1454    ) -> Result<(), ReceiveIcmpEchoError> {
1455        I::map_ip_in(
1456            (IpInvariant(self.state_mut()), conn.clone()),
1457            |(IpInvariant(mut state), conn)| {
1458                let replies = state.icmpv4_replies.entry(conn).or_insert_with(Vec::default);
1459                replies.push(data.as_ref().to_owned());
1460            },
1461            |(IpInvariant(mut state), conn)| {
1462                let replies = state.icmpv6_replies.entry(conn).or_insert_with(Vec::default);
1463                replies.push(data.as_ref().to_owned());
1464            },
1465        );
1466        Ok(())
1467    }
1468}
1469
1470impl IcmpEchoBindingsTypes for FakeBindingsCtx {
1471    type ExternalData<I: Ip> = ();
1472    type SendToken = FakeSendToken;
1473}
1474
1475impl DeviceSocketTypes for FakeBindingsCtx {
1476    type SocketState<D: Send + Sync + Debug> = Mutex<Vec<(WeakDeviceId<FakeBindingsCtx>, Vec<u8>)>>;
1477}
1478
1479impl RawIpSocketsBindingsTypes for FakeBindingsCtx {
1480    type RawIpSocketState<I: Ip> = ();
1481}
1482
1483impl DeviceSocketBindingsContext<DeviceId<Self>> for FakeBindingsCtx {
1484    fn receive_frame(
1485        &self,
1486        socket_id: &SocketId<Self>,
1487        device: &DeviceId<Self>,
1488        _frame: device::socket::Frame<&[u8]>,
1489        raw_frame: &[u8],
1490    ) -> Result<(), ReceiveFrameError> {
1491        let state = socket_id.socket_state();
1492        state.lock().push((device.downgrade(), raw_frame.into()));
1493        Ok(())
1494    }
1495}
1496
1497impl<I: IpExt> RawIpSocketsBindingsContext<I, DeviceId<Self>> for FakeBindingsCtx {
1498    fn receive_packet<B: SplitByteSlice>(
1499        &self,
1500        _socket: &RawIpSocketId<I, WeakDeviceId<Self>, Self>,
1501        _packet: &I::Packet<B>,
1502        _device: &DeviceId<Self>,
1503    ) -> Result<(), ReceivePacketError> {
1504        unimplemented!()
1505    }
1506}
1507
1508impl DeviceLayerStateTypes for FakeBindingsCtx {
1509    type LoopbackDeviceState = ();
1510    type EthernetDeviceState = ();
1511    type BlackholeDeviceState = ();
1512    type PureIpDeviceState = ();
1513    type DeviceIdentifier = MonotonicIdentifier;
1514}
1515
1516impl ReceiveQueueBindingsContext<LoopbackDeviceId<Self>> for FakeBindingsCtx {
1517    fn wake_rx_task(&mut self, device: &LoopbackDeviceId<FakeBindingsCtx>) {
1518        self.state_mut().rx_available.push(device.clone());
1519    }
1520}
1521
1522impl<D: Clone + Into<DeviceId<Self>>> TransmitQueueBindingsContext<D> for FakeBindingsCtx {
1523    fn wake_tx_task(&mut self, device: &D) {
1524        self.state_mut().tx_available.push(device.clone().into());
1525    }
1526}
1527
1528impl DeviceLayerEventDispatcher for FakeBindingsCtx {
1529    type DequeueContext = ();
1530
1531    fn send_ethernet_frame(
1532        &mut self,
1533        device: &EthernetDeviceId<FakeBindingsCtx>,
1534        frame: Buf<Vec<u8>>,
1535        _dequeue_context: Option<&mut Self::DequeueContext>,
1536        _csum_offload: Option<netstack3_base::ChecksumOffloadResult>,
1537    ) -> Result<(), DeviceSendFrameError> {
1538        let frame_meta = DispatchedFrame::Ethernet(device.downgrade());
1539        self.with_inner_mut(|ctx| ctx.frames.push(frame_meta, frame.into_inner()));
1540        Ok(())
1541    }
1542
1543    fn send_ip_packet(
1544        &mut self,
1545        device: &PureIpDeviceId<FakeBindingsCtx>,
1546        packet: Buf<Vec<u8>>,
1547        ip_version: IpVersion,
1548        _dequeue_context: Option<&mut Self::DequeueContext>,
1549        _csum_offload: Option<netstack3_base::ChecksumOffloadResult>,
1550    ) -> Result<(), DeviceSendFrameError> {
1551        let frame_meta = DispatchedFrame::PureIp(PureIpDeviceAndIpVersion {
1552            device: device.downgrade(),
1553            version: ip_version,
1554        });
1555        self.with_inner_mut(|ctx| ctx.frames.push(frame_meta, packet.into_inner()));
1556        Ok(())
1557    }
1558}
1559
1560impl AlwaysDefaultsSettingsContext for FakeBindingsCtx {}
1561
1562/// Wraps all events emitted by Core into a single enum type.
1563#[derive(Debug, Eq, PartialEq, Hash, GenericOverIp)]
1564#[generic_over_ip()]
1565#[allow(missing_docs)]
1566pub enum DispatchedEvent {
1567    IpDeviceIpv4(IpDeviceEvent<WeakDeviceId<FakeBindingsCtx>, Ipv4, FakeInstant>),
1568    IpDeviceIpv6(IpDeviceEvent<WeakDeviceId<FakeBindingsCtx>, Ipv6, FakeInstant>),
1569    IpLayerIpv4(IpLayerEvent<WeakDeviceId<FakeBindingsCtx>, Ipv4>),
1570    IpLayerIpv6(IpLayerEvent<WeakDeviceId<FakeBindingsCtx>, Ipv6>),
1571    NeighborIpv4(nud::Event<Mac, EthernetWeakDeviceId<FakeBindingsCtx>, Ipv4, FakeInstant>),
1572    NeighborIpv6(nud::Event<Mac, EthernetWeakDeviceId<FakeBindingsCtx>, Ipv6, FakeInstant>),
1573    RouterAdvertisement(RouterAdvertisementEvent<WeakDeviceId<FakeBindingsCtx>>),
1574    EthernetDevice(EthernetDeviceEvent<EthernetWeakDeviceId<FakeBindingsCtx>>),
1575}
1576
1577/// A tuple of device ID and IP version.
1578#[derive(Derivative)]
1579#[derivative(Debug(bound = ""))]
1580#[allow(missing_docs)]
1581pub struct PureIpDeviceAndIpVersion<BT: DeviceLayerTypes> {
1582    pub device: PureIpWeakDeviceId<BT>,
1583    pub version: IpVersion,
1584}
1585
1586/// A frame that's been dispatched to Bindings to be sent out the device driver.
1587#[derive(Debug)]
1588pub enum DispatchedFrame {
1589    /// A frame that's been dispatched to an Ethernet device.
1590    Ethernet(EthernetWeakDeviceId<FakeBindingsCtx>),
1591    /// A frame that's been dispatched to a PureIp device.
1592    PureIp(PureIpDeviceAndIpVersion<FakeBindingsCtx>),
1593}
1594
1595impl<I: Ip> From<IpDeviceEvent<DeviceId<FakeBindingsCtx>, I, FakeInstant>> for DispatchedEvent {
1596    fn from(e: IpDeviceEvent<DeviceId<FakeBindingsCtx>, I, FakeInstant>) -> DispatchedEvent {
1597        let e = e.map_device(|d| d.downgrade());
1598        I::map_ip(e, |e| DispatchedEvent::IpDeviceIpv4(e), |e| DispatchedEvent::IpDeviceIpv6(e))
1599    }
1600}
1601
1602impl<I: IpExt> From<IpLayerEvent<DeviceId<FakeBindingsCtx>, I>> for DispatchedEvent {
1603    fn from(e: IpLayerEvent<DeviceId<FakeBindingsCtx>, I>) -> DispatchedEvent {
1604        let e = e.map_device(|d| d.downgrade());
1605        I::map_ip(e, |e| DispatchedEvent::IpLayerIpv4(e), |e| DispatchedEvent::IpLayerIpv6(e))
1606    }
1607}
1608
1609impl<I: Ip> From<nud::Event<Mac, EthernetDeviceId<FakeBindingsCtx>, I, FakeInstant>>
1610    for DispatchedEvent
1611{
1612    fn from(
1613        e: nud::Event<Mac, EthernetDeviceId<FakeBindingsCtx>, I, FakeInstant>,
1614    ) -> DispatchedEvent {
1615        let e = e.map_device(|d| d.downgrade());
1616        I::map_ip(e, |e| DispatchedEvent::NeighborIpv4(e), |e| DispatchedEvent::NeighborIpv6(e))
1617    }
1618}
1619
1620impl From<EthernetDeviceEvent<EthernetDeviceId<FakeBindingsCtx>>> for DispatchedEvent {
1621    fn from(e: EthernetDeviceEvent<EthernetDeviceId<FakeBindingsCtx>>) -> DispatchedEvent {
1622        let e = e.map_device(|d| d.downgrade());
1623        DispatchedEvent::EthernetDevice(e)
1624    }
1625}
1626
1627impl From<RouterAdvertisementEvent<DeviceId<FakeBindingsCtx>>> for DispatchedEvent {
1628    fn from(e: RouterAdvertisementEvent<DeviceId<FakeBindingsCtx>>) -> DispatchedEvent {
1629        let e = e.map_device(|d| d.downgrade());
1630        DispatchedEvent::RouterAdvertisement(e)
1631    }
1632}
1633
1634impl TcpSocketDestructionContext for FakeBindingsCtx {
1635    fn defer_tcp_socket_destruction<I, S>(&self, _result: RemoveResourceResultWithContext<S, Self>)
1636    where
1637        I: Ip,
1638        S: SocketDiagnosticsSeed<Output = TcpSocketDiagnostics<I, Self::Instant>> + Send + 'static,
1639    {
1640        // Do nothing since we don't care about these notifications in unit tests.
1641    }
1642}
1643
1644/// Creates a new [`FakeNetwork`] of [`Ctx`]s in a simple two-host
1645/// configuration.
1646///
1647/// Two hosts are created with the given names. Packets emitted by one
1648/// arrive at the other and vice-versa.
1649pub fn new_simple_fake_network<CtxId: Copy + Debug + Hash + Eq>(
1650    a_id: CtxId,
1651    a: FakeCtx,
1652    a_device_id: EthernetWeakDeviceId<FakeBindingsCtx>,
1653    b_id: CtxId,
1654    b: FakeCtx,
1655    b_device_id: EthernetWeakDeviceId<FakeBindingsCtx>,
1656) -> FakeNetwork<
1657    FakeCtxNetworkSpec,
1658    CtxId,
1659    impl FakeNetworkLinks<DispatchedFrame, EthernetDeviceId<FakeBindingsCtx>, CtxId>,
1660> {
1661    let contexts = vec![(a_id, a), (b_id, b)].into_iter();
1662    FakeNetwork::new(contexts, move |net, _frame: DispatchedFrame| {
1663        if net == a_id {
1664            b_device_id
1665                .upgrade()
1666                .map(|device_id| (b_id, device_id, None))
1667                .into_iter()
1668                .collect::<Vec<_>>()
1669        } else {
1670            a_device_id
1671                .upgrade()
1672                .map(|device_id| (a_id, device_id, None))
1673                .into_iter()
1674                .collect::<Vec<_>>()
1675        }
1676    })
1677}