Skip to main content

netstack3_ip/
multicast_forwarding.rs

1// Copyright 2024 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//! An implementation of multicast forwarding.
6//!
7//! Multicast forwarding is the ability for netstack to forward multicast
8//! packets that arrive on an interface out multiple interfaces (while also
9//! optionally delivering the packet to the host itself if the arrival host has
10//! an interest in the packet).
11//!
12//! Note that multicast forwarding decisions are made by consulting the
13//! multicast routing table, a routing table entirely separate from the unicast
14//! routing table(s).
15
16pub(crate) mod api;
17pub(crate) mod counters;
18pub(crate) mod packet_queue;
19pub(crate) mod route;
20pub(crate) mod state;
21
22use core::sync::atomic::Ordering;
23
24use net_types::ip::{GenericOverIp, Ip, IpVersionMarker};
25use netstack3_base::{
26    AnyDevice, AtomicInstant, CounterContext, DeviceIdContext, EventContext, HandleableTimer,
27    InstantBindingsTypes, InstantContext, LocalFrameDestination, TimerBindingsTypes, TimerContext,
28    WeakDeviceIdentifier,
29};
30use packet_formats::ip::IpPacket;
31use zerocopy::SplitByteSlice;
32
33use crate::internal::multicast_forwarding::counters::MulticastForwardingCounters;
34use crate::internal::multicast_forwarding::packet_queue::QueuePacketOutcome;
35use crate::internal::multicast_forwarding::route::{
36    Action, MulticastRouteEntry, MulticastRouteTargets,
37};
38use crate::multicast_forwarding::{
39    MulticastForwardingPendingPacketsContext, MulticastForwardingState,
40    MulticastForwardingStateContext, MulticastRoute, MulticastRouteKey,
41    MulticastRouteTableContext as _,
42};
43use crate::{IpLayerEvent, IpLayerIpExt};
44
45/// Required types for multicast forwarding provided by Bindings.
46pub trait MulticastForwardingBindingsTypes: InstantBindingsTypes + TimerBindingsTypes {}
47impl<BT: InstantBindingsTypes + TimerBindingsTypes> MulticastForwardingBindingsTypes for BT {}
48
49/// Required functionality for multicast forwarding provided by Bindings.
50pub trait MulticastForwardingBindingsContext<I: IpLayerIpExt, D>:
51    MulticastForwardingBindingsTypes + InstantContext + TimerContext + EventContext<IpLayerEvent<D, I>>
52{
53}
54impl<
55    I: IpLayerIpExt,
56    D,
57    BC: MulticastForwardingBindingsTypes
58        + InstantContext
59        + TimerContext
60        + EventContext<IpLayerEvent<D, I>>,
61> MulticastForwardingBindingsContext<I, D> for BC
62{
63}
64
65/// Device related functionality required by multicast forwarding.
66pub trait MulticastForwardingDeviceContext<I: IpLayerIpExt>: DeviceIdContext<AnyDevice> {
67    /// True if the given device has multicast forwarding enabled.
68    fn is_device_multicast_forwarding_enabled(&mut self, dev: &Self::DeviceId) -> bool;
69}
70
71/// A timer event for multicast forwarding.
72#[derive(Clone, Debug, Eq, GenericOverIp, Hash, PartialEq)]
73#[generic_over_ip(I, Ip)]
74pub enum MulticastForwardingTimerId<I: Ip> {
75    /// A trigger to perform garbage collection on the pending packets table.
76    PendingPacketsGc(IpVersionMarker<I>),
77}
78
79impl<
80    I: IpLayerIpExt,
81    BC: MulticastForwardingBindingsContext<I, CC::DeviceId>,
82    CC: MulticastForwardingStateContext<I, BC> + CounterContext<MulticastForwardingCounters<I>>,
83> HandleableTimer<CC, BC> for MulticastForwardingTimerId<I>
84{
85    fn handle(self, core_ctx: &mut CC, bindings_ctx: &mut BC, _: BC::UniqueTimerId) {
86        match self {
87            MulticastForwardingTimerId::PendingPacketsGc(_) => {
88                core_ctx.with_state(|state, ctx| match state {
89                    // Multicast forwarding was disabled after GC was scheduled;
90                    // there are no resources to GC now.
91                    MulticastForwardingState::Disabled => {}
92                    MulticastForwardingState::Enabled(state) => {
93                        CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
94                            .pending_table_gc
95                            .increment();
96                        let removed_count = ctx.with_pending_table_mut(state, |pending_table| {
97                            pending_table.run_garbage_collection(bindings_ctx)
98                        });
99                        CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
100                            .pending_packet_drops_gc
101                            .add(removed_count);
102                    }
103                })
104            }
105        }
106    }
107}
108
109/// Events that may be published by the multicast forwarding engine.
110#[derive(Debug, Eq, Hash, PartialEq, GenericOverIp)]
111#[generic_over_ip(I, Ip)]
112pub enum MulticastForwardingEvent<I: IpLayerIpExt, D> {
113    /// A multicast packet was received for which there was no applicable route.
114    MissingRoute {
115        /// The key of the route that's missing.
116        key: MulticastRouteKey<I>,
117        /// The interface on which the packet was received.
118        input_interface: D,
119    },
120    /// A multicast packet was received on an unexpected input interface.
121    WrongInputInterface {
122        /// The key of the route with the unexpected input interface.
123        key: MulticastRouteKey<I>,
124        /// The interface on which the packet was received.
125        actual_input_interface: D,
126        /// The interface on which the packet was expected (as specified in the
127        /// multicast route).
128        expected_input_interface: D,
129    },
130}
131
132impl<I: IpLayerIpExt, D> MulticastForwardingEvent<I, D> {
133    pub(crate) fn map_device<O, F: Fn(D) -> O>(self, map: F) -> MulticastForwardingEvent<I, O> {
134        match self {
135            MulticastForwardingEvent::MissingRoute { key, input_interface } => {
136                MulticastForwardingEvent::MissingRoute {
137                    key,
138                    input_interface: map(input_interface),
139                }
140            }
141            MulticastForwardingEvent::WrongInputInterface {
142                key,
143                actual_input_interface,
144                expected_input_interface,
145            } => MulticastForwardingEvent::WrongInputInterface {
146                key,
147                actual_input_interface: map(actual_input_interface),
148                expected_input_interface: map(expected_input_interface),
149            },
150        }
151    }
152}
153
154impl<I: IpLayerIpExt, D: WeakDeviceIdentifier> MulticastForwardingEvent<I, D> {
155    /// Upgrades the device IDs held by this event.
156    pub fn upgrade_device_id(self) -> Option<MulticastForwardingEvent<I, D::Strong>> {
157        match self {
158            MulticastForwardingEvent::MissingRoute { key, input_interface } => {
159                Some(MulticastForwardingEvent::MissingRoute {
160                    key,
161                    input_interface: input_interface.upgrade()?,
162                })
163            }
164            MulticastForwardingEvent::WrongInputInterface {
165                key,
166                actual_input_interface,
167                expected_input_interface,
168            } => Some(MulticastForwardingEvent::WrongInputInterface {
169                key,
170                actual_input_interface: actual_input_interface.upgrade()?,
171                expected_input_interface: expected_input_interface.upgrade()?,
172            }),
173        }
174    }
175}
176
177/// Query the multicast route table and return the forwarding targets.
178///
179/// `None` may be returned in several situations:
180///   * if multicast forwarding is disabled (either stack-wide or for the
181///     provided `dev`),
182///   * if the packets src/dst addrs are not viable for multicast forwarding
183///     (see the requirements on [`MulticastRouteKey`]), or
184///   * if the route table does not have an entry suitable for this packet.
185///
186/// In the latter case, the packet is stashed in the
187/// [`MulticastForwardingPendingPackets`] table, and a relevant event is
188/// dispatched to bindings.
189///
190/// Note that the returned targets are not synchronized with the multicast route
191/// table and may grow stale if the table is updated.
192pub(crate) fn lookup_multicast_route_or_stash_packet<I, B, CC, BC>(
193    core_ctx: &mut CC,
194    bindings_ctx: &mut BC,
195    packet: &I::Packet<B>,
196    dev: &CC::DeviceId,
197    frame_dst: Option<LocalFrameDestination>,
198    max_fragment_len: Option<usize>,
199) -> Option<MulticastRouteTargets<CC::DeviceId>>
200where
201    I: IpLayerIpExt,
202    B: SplitByteSlice,
203    CC: MulticastForwardingStateContext<I, BC>
204        + MulticastForwardingDeviceContext<I>
205        + CounterContext<MulticastForwardingCounters<I>>,
206    BC: MulticastForwardingBindingsContext<I, CC::DeviceId>,
207{
208    CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx).rx.increment();
209    // Short circuit if the packet's addresses don't constitute a valid
210    // multicast route key (e.g. src is not unicast, or dst is not multicast).
211    let Some(key) = MulticastRouteKey::new(packet.src_ip(), packet.dst_ip()) else {
212        CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
213            .no_tx_invalid_key
214            .increment();
215        return None;
216    };
217
218    // Short circuit if the device has forwarding disabled.
219    if !core_ctx.is_device_multicast_forwarding_enabled(dev) {
220        CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
221            .no_tx_disabled_dev
222            .increment();
223        return None;
224    }
225
226    core_ctx.with_state(|state, ctx| {
227        // Short circuit if forwarding is disabled stack-wide.
228        let Some(state) = state.enabled() else {
229            CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
230                .no_tx_disabled_stack_wide
231                .increment();
232            return None;
233        };
234        ctx.with_route_table(state, |route_table, ctx| {
235            if let Some(MulticastRouteEntry {
236                route: MulticastRoute { input_interface, action },
237                stats,
238            }) = route_table.get(&key)
239            {
240                if dev != input_interface {
241                    CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
242                        .no_tx_wrong_dev
243                        .increment();
244                    bindings_ctx.on_event(
245                        MulticastForwardingEvent::WrongInputInterface {
246                            key,
247                            actual_input_interface: dev.clone(),
248                            expected_input_interface: input_interface.clone(),
249                        }
250                        .into(),
251                    );
252                    return None;
253                }
254
255                stats.last_used.store_max(bindings_ctx.now(), Ordering::Relaxed);
256
257                match action {
258                    Action::Forward(targets) => {
259                        CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
260                            .tx
261                            .increment();
262                        return Some(targets.clone());
263                    }
264                }
265            }
266            CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
267                .pending_packets
268                .increment();
269            match ctx.with_pending_table_mut(state, |pending_table| {
270                pending_table.try_queue_packet(
271                    bindings_ctx,
272                    key.clone(),
273                    packet,
274                    dev,
275                    frame_dst,
276                    max_fragment_len,
277                )
278            }) {
279                QueuePacketOutcome::QueuedInNewQueue => {
280                    bindings_ctx.on_event(
281                        MulticastForwardingEvent::MissingRoute {
282                            key,
283                            input_interface: dev.clone(),
284                        }
285                        .into(),
286                    );
287                }
288                QueuePacketOutcome::QueuedInExistingQueue => {}
289                QueuePacketOutcome::ExistingQueueFull => {
290                    CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
291                        .pending_packet_drops_queue_full
292                        .increment();
293                }
294            }
295            return None;
296        })
297    })
298}
299
300#[cfg(test)]
301mod testutil {
302    use super::*;
303
304    use alloc::rc::Rc;
305    use alloc::vec::Vec;
306    use core::cell::RefCell;
307    use derivative::Derivative;
308    use net_declare::{net_ip_v4, net_ip_v6};
309    use net_types::MulticastAddr;
310    use net_types::ip::{Ipv4, Ipv4Addr, Ipv6, Ipv6Addr, Mtu};
311    use netstack3_base::socket::SocketIpAddr;
312    use netstack3_base::testutil::{FakeStrongDeviceId, MultipleDevicesId};
313    use netstack3_base::{
314        CoreTimerContext, CounterContext, CtxPair, Marks, NetworkSerializationContext,
315        NetworkSerializer, ResourceCounterContext,
316    };
317    use netstack3_filter::ProofOfEgressCheck;
318    use netstack3_hashmap::HashSet;
319    use packet::{BufferMut, InnerPacketBuilder, NestablePacketBuilder as _, Serializer};
320    use packet_formats::ip::{IpPacketBuilder, IpProto};
321
322    use crate::device::IpDeviceSendContext;
323    use crate::internal::base::DeviceIpLayerMetadata;
324    use crate::internal::icmp::IcmpErrorHandler;
325    use crate::multicast_forwarding::{
326        MulticastForwardingApi, MulticastForwardingEnabledState, MulticastForwardingPendingPackets,
327        MulticastForwardingPendingPacketsContext, MulticastForwardingState, MulticastRouteTable,
328        MulticastRouteTableContext,
329    };
330    use crate::{IpCounters, IpDeviceMtuContext, IpLayerEvent, IpPacketDestination};
331
332    /// An IP extension trait providing constants for various IP addresses.
333    pub(crate) trait TestIpExt: IpLayerIpExt {
334        const SRC1: Self::Addr;
335        const SRC2: Self::Addr;
336        const DST1: Self::Addr;
337        const DST2: Self::Addr;
338    }
339
340    impl TestIpExt for Ipv4 {
341        const SRC1: Ipv4Addr = net_ip_v4!("192.0.2.1");
342        const SRC2: Ipv4Addr = net_ip_v4!("192.0.2.2");
343        const DST1: Ipv4Addr = net_ip_v4!("224.0.1.1");
344        const DST2: Ipv4Addr = net_ip_v4!("224.0.1.2");
345    }
346
347    impl TestIpExt for Ipv6 {
348        const SRC1: Ipv6Addr = net_ip_v6!("2001:0DB8::1");
349        const SRC2: Ipv6Addr = net_ip_v6!("2001:0DB8::2");
350        const DST1: Ipv6Addr = net_ip_v6!("ff0e::1");
351        const DST2: Ipv6Addr = net_ip_v6!("ff0e::2");
352    }
353
354    /// Constructs a buffer containing an IP packet with sensible defaults.
355    pub(crate) fn new_ip_packet_buf<I: IpLayerIpExt>(
356        src_addr: I::Addr,
357        dst_addr: I::Addr,
358    ) -> impl AsRef<[u8]> {
359        const TTL: u8 = 255;
360        /// Arbitrary data to put inside of an IP packet.
361        const IP_BODY: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
362        I::PacketBuilder::new(src_addr, dst_addr, TTL, IpProto::Udp.into())
363            .wrap_body(IP_BODY.into_serializer())
364            .serialize_vec_outer(&mut NetworkSerializationContext::default())
365            .unwrap()
366    }
367
368    #[derive(Debug, PartialEq)]
369    pub(crate) struct SentPacket<I: IpLayerIpExt, D> {
370        pub(crate) dst: MulticastAddr<I::Addr>,
371        pub(crate) device: D,
372    }
373
374    #[derive(Derivative)]
375    #[derivative(Default(bound = ""))]
376    pub(crate) struct FakeCoreCtxState<I: IpLayerIpExt, D: FakeStrongDeviceId> {
377        // NB: Hold in an `Rc<RefCell<...>>` to switch to runtime borrow
378        // checking. This allows us to borrow the multicast forwarding state at
379        // the same time as the outer `FakeCoreCtx` is mutably borrowed.
380        pub(crate) multicast_forwarding:
381            Rc<RefCell<MulticastForwardingState<I, D, FakeBindingsCtx<I, D>>>>,
382        // The list of devices that have multicast forwarding enabled.
383        pub(crate) forwarding_enabled_devices: HashSet<D>,
384        // The list of packets sent by the netstack.
385        pub(crate) sent_packets: Vec<SentPacket<I, D>>,
386        stack_wide_counters: IpCounters<I>,
387        per_device_counters: IpCounters<I>,
388        multicast_forwarding_counters: MulticastForwardingCounters<I>,
389    }
390
391    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> FakeCoreCtxState<I, D> {
392        pub(crate) fn set_multicast_forwarding_enabled_for_dev(&mut self, dev: D, enabled: bool) {
393            if enabled {
394                let _: bool = self.forwarding_enabled_devices.insert(dev);
395            } else {
396                let _: bool = self.forwarding_enabled_devices.remove(&dev);
397            }
398        }
399
400        pub(crate) fn take_sent_packets(&mut self) -> Vec<SentPacket<I, D>> {
401            core::mem::take(&mut self.sent_packets)
402        }
403    }
404
405    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> CounterContext<IpCounters<I>>
406        for FakeCoreCtxState<I, D>
407    {
408        fn counters(&self) -> &IpCounters<I> {
409            &self.stack_wide_counters
410        }
411    }
412
413    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> ResourceCounterContext<D, IpCounters<I>>
414        for FakeCoreCtxState<I, D>
415    {
416        fn per_resource_counters(&self, _resource: &D) -> &IpCounters<I> {
417            &self.per_device_counters
418        }
419    }
420
421    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> CounterContext<MulticastForwardingCounters<I>>
422        for FakeCoreCtxState<I, D>
423    {
424        fn counters(&self) -> &MulticastForwardingCounters<I> {
425            &self.multicast_forwarding_counters
426        }
427    }
428
429    pub(crate) type FakeBindingsCtx<I, D> = netstack3_base::testutil::FakeBindingsCtx<
430        MulticastForwardingTimerId<I>,
431        IpLayerEvent<D, I>,
432        (),
433        (),
434    >;
435    pub(crate) type FakeCoreCtx<I, D> =
436        netstack3_base::testutil::FakeCoreCtx<FakeCoreCtxState<I, D>, (), D>;
437
438    impl<I: IpLayerIpExt, D: FakeStrongDeviceId>
439        MulticastForwardingStateContext<I, FakeBindingsCtx<I, D>> for FakeCoreCtx<I, D>
440    {
441        type Ctx<'a> = FakeCoreCtx<I, D>;
442        fn with_state<
443            O,
444            F: FnOnce(
445                &MulticastForwardingState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
446                &mut Self::Ctx<'_>,
447            ) -> O,
448        >(
449            &mut self,
450            cb: F,
451        ) -> O {
452            let state = self.state.multicast_forwarding.clone();
453            let borrow = state.borrow();
454            cb(&borrow, self)
455        }
456        fn with_state_mut<
457            O,
458            F: FnOnce(
459                &mut MulticastForwardingState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
460                &mut Self::Ctx<'_>,
461            ) -> O,
462        >(
463            &mut self,
464            cb: F,
465        ) -> O {
466            let state = self.state.multicast_forwarding.clone();
467            let mut borrow = state.borrow_mut();
468            cb(&mut borrow, self)
469        }
470    }
471
472    impl<I: IpLayerIpExt, D: FakeStrongDeviceId>
473        MulticastRouteTableContext<I, FakeBindingsCtx<I, D>> for FakeCoreCtx<I, D>
474    {
475        type Ctx<'a> = FakeCoreCtx<I, D>;
476        fn with_route_table<
477            O,
478            F: FnOnce(
479                &MulticastRouteTable<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
480                &mut Self::Ctx<'_>,
481            ) -> O,
482        >(
483            &mut self,
484            state: &MulticastForwardingEnabledState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
485            cb: F,
486        ) -> O {
487            let route_table = state.route_table().read();
488            cb(&route_table, self)
489        }
490        fn with_route_table_mut<
491            O,
492            F: FnOnce(
493                &mut MulticastRouteTable<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
494                &mut Self::Ctx<'_>,
495            ) -> O,
496        >(
497            &mut self,
498            state: &MulticastForwardingEnabledState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
499            cb: F,
500        ) -> O {
501            let mut route_table = state.route_table().write();
502            cb(&mut route_table, self)
503        }
504    }
505
506    impl<I: IpLayerIpExt, D: FakeStrongDeviceId>
507        MulticastForwardingPendingPacketsContext<I, FakeBindingsCtx<I, D>> for FakeCoreCtx<I, D>
508    {
509        fn with_pending_table_mut<
510            O,
511            F: FnOnce(
512                &mut MulticastForwardingPendingPackets<I, Self::WeakDeviceId, FakeBindingsCtx<I, D>>,
513            ) -> O,
514        >(
515            &mut self,
516            state: &MulticastForwardingEnabledState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
517            cb: F,
518        ) -> O {
519            let mut pending_table = state.pending_table().lock();
520            cb(&mut pending_table)
521        }
522    }
523
524    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> MulticastForwardingDeviceContext<I>
525        for FakeCoreCtx<I, D>
526    {
527        fn is_device_multicast_forwarding_enabled(&mut self, device_id: &Self::DeviceId) -> bool {
528            self.state.forwarding_enabled_devices.contains(device_id)
529        }
530    }
531
532    impl<I: IpLayerIpExt, D: FakeStrongDeviceId>
533        CoreTimerContext<MulticastForwardingTimerId<I>, FakeBindingsCtx<I, D>>
534        for FakeCoreCtx<I, D>
535    {
536        fn convert_timer(
537            dispatch_id: MulticastForwardingTimerId<I>,
538        ) -> MulticastForwardingTimerId<I> {
539            dispatch_id
540        }
541    }
542
543    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> IpDeviceSendContext<I, FakeBindingsCtx<I, D>>
544        for FakeCoreCtx<I, D>
545    {
546        fn send_ip_frame<S>(
547            &mut self,
548            _bindings_ctx: &mut FakeBindingsCtx<I, D>,
549            device_id: &D,
550            destination: IpPacketDestination<I, &D>,
551            _ip_layer_metadata: DeviceIpLayerMetadata<FakeBindingsCtx<I, D>>,
552            _body: S,
553            _egress_proof: ProofOfEgressCheck,
554        ) -> Result<(), netstack3_base::SendFrameError<S>>
555        where
556            S: NetworkSerializer,
557            S::Buffer: BufferMut,
558        {
559            let dst = match destination {
560                IpPacketDestination::Multicast(dst) => dst,
561                dst => panic!("unexpected sent packet: destination={dst:?}"),
562            };
563            self.state.sent_packets.push(SentPacket { dst, device: device_id.clone() });
564            Ok(())
565        }
566    }
567
568    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> IpDeviceMtuContext<I> for FakeCoreCtx<I, D> {
569        fn get_mtu(&mut self, _device_id: &Self::DeviceId) -> Mtu {
570            Mtu::max()
571        }
572    }
573
574    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> IcmpErrorHandler<I, FakeBindingsCtx<I, D>>
575        for FakeCoreCtx<I, D>
576    {
577        fn send_icmp_error_message<B: BufferMut>(
578            &mut self,
579            _bindings_ctx: &mut FakeBindingsCtx<I, D>,
580            _device: Option<&D>,
581            _frame_dst: Option<LocalFrameDestination>,
582            _src_ip: SocketIpAddr<I::Addr>,
583            _dst_ip: SocketIpAddr<I::Addr>,
584            _original_packet: B,
585            _error: I::IcmpError,
586            _header_len: usize,
587            _proto: I::Proto,
588            _marks: &Marks,
589        ) {
590            unimplemented!()
591        }
592    }
593
594    pub(crate) fn new_api<I: IpLayerIpExt>() -> MulticastForwardingApi<
595        I,
596        CtxPair<FakeCoreCtx<I, MultipleDevicesId>, FakeBindingsCtx<I, MultipleDevicesId>>,
597    > {
598        MulticastForwardingApi::new(CtxPair::with_core_ctx(FakeCoreCtx::with_state(
599            Default::default(),
600        )))
601    }
602
603    /// A test helper to access the [`MulticastForwardingPendingPackets`] table.
604    ///
605    /// # Panics
606    ///
607    /// Panics if multicast forwarding is disabled.
608    pub(crate) fn with_pending_table<I, O, F, CC, BT>(core_ctx: &mut CC, cb: F) -> O
609    where
610        I: IpLayerIpExt,
611        CC: MulticastForwardingStateContext<I, BT>,
612        BT: MulticastForwardingBindingsTypes,
613        F: FnOnce(&mut MulticastForwardingPendingPackets<I, CC::WeakDeviceId, BT>) -> O,
614    {
615        core_ctx.with_state(|state, ctx| {
616            let state = state.enabled().unwrap();
617            ctx.with_route_table(state, |_routing_table, ctx| {
618                ctx.with_pending_table_mut(state, |pending_table| cb(pending_table))
619            })
620        })
621    }
622}
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627
628    use alloc::vec;
629    use core::num::NonZeroU8;
630    use core::time::Duration;
631
632    use ip_test_macro::ip_test;
633    use netstack3_base::testutil::MultipleDevicesId;
634    use packet::ParseBuffer;
635    use test_case::test_case;
636    use testutil::TestIpExt;
637
638    use crate::internal::multicast_forwarding::route::MulticastRouteStats;
639    use crate::multicast_forwarding::MulticastRouteTarget;
640
641    struct LookupTestCase {
642        // Whether multicast forwarding is enabled for the netstack.
643        enabled: bool,
644        // Whether multicast forwarding is enabled for the device.
645        dev_enabled: bool,
646        // Whether the packet has the correct src/dst addrs.
647        right_key: bool,
648        // Whether the packet arrived on the correct device.
649        right_dev: bool,
650    }
651    const LOOKUP_SUCCESS_CASE: LookupTestCase =
652        LookupTestCase { enabled: true, dev_enabled: true, right_key: true, right_dev: true };
653
654    #[ip_test(I)]
655    #[test_case(LOOKUP_SUCCESS_CASE => true; "success")]
656    #[test_case(LookupTestCase{enabled: false, ..LOOKUP_SUCCESS_CASE} => false; "disabled")]
657    #[test_case(LookupTestCase{dev_enabled: false, ..LOOKUP_SUCCESS_CASE} => false; "dev_disabled")]
658    #[test_case(LookupTestCase{right_key: false, ..LOOKUP_SUCCESS_CASE} => false; "wrong_key")]
659    #[test_case(LookupTestCase{right_dev: false, ..LOOKUP_SUCCESS_CASE} => false; "wrong_dev")]
660    fn lookup_route<I: TestIpExt>(test_case: LookupTestCase) -> bool {
661        let LookupTestCase { enabled, dev_enabled, right_key, right_dev } = test_case;
662        const FRAME_DST: Option<LocalFrameDestination> = None;
663        const MAX_FRAGMENT_LEN: Option<usize> = None;
664        let mut api = testutil::new_api::<I>();
665
666        let expected_key = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
667        let actual_key = if right_key {
668            expected_key.clone()
669        } else {
670            MulticastRouteKey::new(I::SRC2, I::DST2).unwrap()
671        };
672
673        let expected_dev = MultipleDevicesId::A;
674        let actual_dev = if right_dev { expected_dev } else { MultipleDevicesId::B };
675
676        if enabled {
677            assert!(api.enable());
678            // NB: Only attempt to install the route when enabled; Otherwise
679            // installation fails.
680            assert_eq!(
681                api.add_multicast_route(
682                    expected_key.clone(),
683                    MulticastRoute::new_forward(
684                        expected_dev,
685                        [MulticastRouteTarget {
686                            output_interface: MultipleDevicesId::C,
687                            min_ttl: NonZeroU8::new(1).unwrap(),
688                        }]
689                        .into()
690                    )
691                    .unwrap()
692                ),
693                Ok(None)
694            );
695        }
696
697        api.core_ctx().state.set_multicast_forwarding_enabled_for_dev(actual_dev, dev_enabled);
698
699        let (core_ctx, bindings_ctx) = api.contexts();
700        let creation_time = bindings_ctx.now();
701        bindings_ctx.timers.instant.sleep(Duration::from_secs(5));
702        let lookup_time = bindings_ctx.now();
703        assert!(lookup_time > creation_time);
704
705        let buf = testutil::new_ip_packet_buf::<I>(actual_key.src_addr(), actual_key.dst_addr());
706        let mut buf_ref = buf.as_ref();
707        let packet = buf_ref.parse::<I::Packet<_>>().expect("parse should succeed");
708
709        let route = lookup_multicast_route_or_stash_packet(
710            core_ctx,
711            bindings_ctx,
712            &packet,
713            &actual_dev,
714            FRAME_DST,
715            MAX_FRAGMENT_LEN,
716        );
717
718        // Verify that multicast routing events are generated.
719        let mut expected_events = vec![];
720        if !right_key {
721            expected_events.push(IpLayerEvent::MulticastForwarding(
722                MulticastForwardingEvent::MissingRoute {
723                    key: actual_key.clone(),
724                    input_interface: actual_dev,
725                },
726            ));
727        }
728        if !right_dev {
729            expected_events.push(IpLayerEvent::MulticastForwarding(
730                MulticastForwardingEvent::WrongInputInterface {
731                    key: actual_key,
732                    actual_input_interface: actual_dev,
733                    expected_input_interface: expected_dev,
734                },
735            ));
736        }
737        assert_eq!(bindings_ctx.take_events(), expected_events);
738
739        let lookup_succeeded = route.is_some();
740
741        if enabled {
742            // Verify that on success, the last_used field in stats is updated.
743            let expected_stats = if lookup_succeeded {
744                MulticastRouteStats { last_used: lookup_time }
745            } else {
746                MulticastRouteStats { last_used: creation_time }
747            };
748            assert_eq!(api.get_route_stats(&expected_key), Ok(Some(expected_stats)));
749        }
750
751        // Verify that counters are updated.
752        let counters: &MulticastForwardingCounters<I> = api.core_ctx().counters();
753        assert_eq!(counters.rx.get(), 1);
754        assert_eq!(counters.tx.get(), if lookup_succeeded { 1 } else { 0 });
755        assert_eq!(counters.no_tx_disabled_dev.get(), if dev_enabled { 0 } else { 1 });
756        assert_eq!(counters.no_tx_disabled_stack_wide.get(), if enabled { 0 } else { 1 });
757        assert_eq!(counters.no_tx_wrong_dev.get(), if right_dev { 0 } else { 1 });
758        assert_eq!(counters.pending_packets.get(), if right_key { 0 } else { 1 });
759
760        lookup_succeeded
761    }
762}