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, FrameDestination,
27    HandleableTimer, InstantBindingsTypes, InstantContext, 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<FrameDestination>,
198) -> Option<MulticastRouteTargets<CC::DeviceId>>
199where
200    I: IpLayerIpExt,
201    B: SplitByteSlice,
202    CC: MulticastForwardingStateContext<I, BC>
203        + MulticastForwardingDeviceContext<I>
204        + CounterContext<MulticastForwardingCounters<I>>,
205    BC: MulticastForwardingBindingsContext<I, CC::DeviceId>,
206{
207    CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx).rx.increment();
208    // Short circuit if the packet's addresses don't constitute a valid
209    // multicast route key (e.g. src is not unicast, or dst is not multicast).
210    let key = MulticastRouteKey::new(packet.src_ip(), packet.dst_ip())?;
211    CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
212        .no_tx_invalid_key
213        .increment();
214
215    // Short circuit if the device has forwarding disabled.
216    if !core_ctx.is_device_multicast_forwarding_enabled(dev) {
217        CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
218            .no_tx_disabled_dev
219            .increment();
220        return None;
221    }
222
223    core_ctx.with_state(|state, ctx| {
224        // Short circuit if forwarding is disabled stack-wide.
225        let Some(state) = state.enabled() else {
226            CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
227                .no_tx_disabled_stack_wide
228                .increment();
229            return None;
230        };
231        ctx.with_route_table(state, |route_table, ctx| {
232            if let Some(MulticastRouteEntry {
233                route: MulticastRoute { input_interface, action },
234                stats,
235            }) = route_table.get(&key)
236            {
237                if dev != input_interface {
238                    CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
239                        .no_tx_wrong_dev
240                        .increment();
241                    bindings_ctx.on_event(
242                        MulticastForwardingEvent::WrongInputInterface {
243                            key,
244                            actual_input_interface: dev.clone(),
245                            expected_input_interface: input_interface.clone(),
246                        }
247                        .into(),
248                    );
249                    return None;
250                }
251
252                stats.last_used.store_max(bindings_ctx.now(), Ordering::Relaxed);
253
254                match action {
255                    Action::Forward(targets) => {
256                        CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
257                            .tx
258                            .increment();
259                        return Some(targets.clone());
260                    }
261                }
262            }
263            CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
264                .pending_packets
265                .increment();
266            match ctx.with_pending_table_mut(state, |pending_table| {
267                pending_table.try_queue_packet(bindings_ctx, key.clone(), packet, dev, frame_dst)
268            }) {
269                QueuePacketOutcome::QueuedInNewQueue => {
270                    bindings_ctx.on_event(
271                        MulticastForwardingEvent::MissingRoute {
272                            key,
273                            input_interface: dev.clone(),
274                        }
275                        .into(),
276                    );
277                }
278                QueuePacketOutcome::QueuedInExistingQueue => {}
279                QueuePacketOutcome::ExistingQueueFull => {
280                    CounterContext::<MulticastForwardingCounters<I>>::counters(ctx)
281                        .pending_packet_drops_queue_full
282                        .increment();
283                }
284            }
285            return None;
286        })
287    })
288}
289
290#[cfg(test)]
291mod testutil {
292    use super::*;
293
294    use alloc::collections::HashSet;
295    use alloc::rc::Rc;
296    use alloc::vec::Vec;
297    use core::cell::RefCell;
298    use derivative::Derivative;
299    use net_declare::{net_ip_v4, net_ip_v6};
300    use net_types::ip::{Ipv4, Ipv4Addr, Ipv6, Ipv6Addr, Mtu};
301    use net_types::{MulticastAddr, SpecifiedAddr};
302    use netstack3_base::testutil::{FakeStrongDeviceId, MultipleDevicesId};
303    use netstack3_base::{CoreTimerContext, CounterContext, CtxPair, FrameDestination, Marks};
304    use netstack3_filter::ProofOfEgressCheck;
305    use packet::{BufferMut, InnerPacketBuilder, Serializer};
306    use packet_formats::ip::{IpPacketBuilder, IpProto};
307
308    use crate::device::IpDeviceSendContext;
309    use crate::internal::base::DeviceIpLayerMetadata;
310    use crate::internal::icmp::{IcmpErrorHandler, IcmpHandlerIpExt};
311    use crate::multicast_forwarding::{
312        MulticastForwardingApi, MulticastForwardingEnabledState, MulticastForwardingPendingPackets,
313        MulticastForwardingPendingPacketsContext, MulticastForwardingState, MulticastRouteTable,
314        MulticastRouteTableContext,
315    };
316    use crate::{IpCounters, IpDeviceMtuContext, IpLayerEvent, IpPacketDestination};
317
318    /// An IP extension trait providing constants for various IP addresses.
319    pub(crate) trait TestIpExt: IpLayerIpExt {
320        const SRC1: Self::Addr;
321        const SRC2: Self::Addr;
322        const DST1: Self::Addr;
323        const DST2: Self::Addr;
324    }
325
326    impl TestIpExt for Ipv4 {
327        const SRC1: Ipv4Addr = net_ip_v4!("192.0.2.1");
328        const SRC2: Ipv4Addr = net_ip_v4!("192.0.2.2");
329        const DST1: Ipv4Addr = net_ip_v4!("224.0.1.1");
330        const DST2: Ipv4Addr = net_ip_v4!("224.0.1.2");
331    }
332
333    impl TestIpExt for Ipv6 {
334        const SRC1: Ipv6Addr = net_ip_v6!("2001:0DB8::1");
335        const SRC2: Ipv6Addr = net_ip_v6!("2001:0DB8::2");
336        const DST1: Ipv6Addr = net_ip_v6!("ff0e::1");
337        const DST2: Ipv6Addr = net_ip_v6!("ff0e::2");
338    }
339
340    /// Constructs a buffer containing an IP packet with sensible defaults.
341    pub(crate) fn new_ip_packet_buf<I: IpLayerIpExt>(
342        src_addr: I::Addr,
343        dst_addr: I::Addr,
344    ) -> impl AsRef<[u8]> {
345        const TTL: u8 = 255;
346        /// Arbitrary data to put inside of an IP packet.
347        const IP_BODY: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
348        IP_BODY
349            .into_serializer()
350            .encapsulate(I::PacketBuilder::new(src_addr, dst_addr, TTL, IpProto::Udp.into()))
351            .serialize_vec_outer()
352            .unwrap()
353    }
354
355    #[derive(Debug, PartialEq)]
356    pub(crate) struct SentPacket<I: IpLayerIpExt, D> {
357        pub(crate) dst: MulticastAddr<I::Addr>,
358        pub(crate) device: D,
359    }
360
361    #[derive(Derivative)]
362    #[derivative(Default(bound = ""))]
363    pub(crate) struct FakeCoreCtxState<I: IpLayerIpExt, D: FakeStrongDeviceId> {
364        // NB: Hold in an `Rc<RefCell<...>>` to switch to runtime borrow
365        // checking. This allows us to borrow the multicast forwarding state at
366        // the same time as the outer `FakeCoreCtx` is mutably borrowed.
367        pub(crate) multicast_forwarding:
368            Rc<RefCell<MulticastForwardingState<I, D, FakeBindingsCtx<I, D>>>>,
369        // The list of devices that have multicast forwarding enabled.
370        pub(crate) forwarding_enabled_devices: HashSet<D>,
371        // The list of packets sent by the netstack.
372        pub(crate) sent_packets: Vec<SentPacket<I, D>>,
373        counters: IpCounters<I>,
374        multicast_forwarding_counters: MulticastForwardingCounters<I>,
375    }
376
377    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> FakeCoreCtxState<I, D> {
378        pub(crate) fn set_multicast_forwarding_enabled_for_dev(&mut self, dev: D, enabled: bool) {
379            if enabled {
380                let _: bool = self.forwarding_enabled_devices.insert(dev);
381            } else {
382                let _: bool = self.forwarding_enabled_devices.remove(&dev);
383            }
384        }
385
386        pub(crate) fn take_sent_packets(&mut self) -> Vec<SentPacket<I, D>> {
387            core::mem::take(&mut self.sent_packets)
388        }
389    }
390
391    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> CounterContext<IpCounters<I>>
392        for FakeCoreCtxState<I, D>
393    {
394        fn counters(&self) -> &IpCounters<I> {
395            &self.counters
396        }
397    }
398
399    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> CounterContext<MulticastForwardingCounters<I>>
400        for FakeCoreCtxState<I, D>
401    {
402        fn counters(&self) -> &MulticastForwardingCounters<I> {
403            &self.multicast_forwarding_counters
404        }
405    }
406
407    pub(crate) type FakeBindingsCtx<I, D> = netstack3_base::testutil::FakeBindingsCtx<
408        MulticastForwardingTimerId<I>,
409        IpLayerEvent<D, I>,
410        (),
411        (),
412    >;
413    pub(crate) type FakeCoreCtx<I, D> =
414        netstack3_base::testutil::FakeCoreCtx<FakeCoreCtxState<I, D>, (), D>;
415
416    impl<I: IpLayerIpExt, D: FakeStrongDeviceId>
417        MulticastForwardingStateContext<I, FakeBindingsCtx<I, D>> for FakeCoreCtx<I, D>
418    {
419        type Ctx<'a> = FakeCoreCtx<I, D>;
420        fn with_state<
421            O,
422            F: FnOnce(
423                &MulticastForwardingState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
424                &mut Self::Ctx<'_>,
425            ) -> O,
426        >(
427            &mut self,
428            cb: F,
429        ) -> O {
430            let state = self.state.multicast_forwarding.clone();
431            let borrow = state.borrow();
432            cb(&borrow, self)
433        }
434        fn with_state_mut<
435            O,
436            F: FnOnce(
437                &mut MulticastForwardingState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
438                &mut Self::Ctx<'_>,
439            ) -> O,
440        >(
441            &mut self,
442            cb: F,
443        ) -> O {
444            let state = self.state.multicast_forwarding.clone();
445            let mut borrow = state.borrow_mut();
446            cb(&mut borrow, self)
447        }
448    }
449
450    impl<I: IpLayerIpExt, D: FakeStrongDeviceId>
451        MulticastRouteTableContext<I, FakeBindingsCtx<I, D>> for FakeCoreCtx<I, D>
452    {
453        type Ctx<'a> = FakeCoreCtx<I, D>;
454        fn with_route_table<
455            O,
456            F: FnOnce(
457                &MulticastRouteTable<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
458                &mut Self::Ctx<'_>,
459            ) -> O,
460        >(
461            &mut self,
462            state: &MulticastForwardingEnabledState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
463            cb: F,
464        ) -> O {
465            let route_table = state.route_table().read();
466            cb(&route_table, self)
467        }
468        fn with_route_table_mut<
469            O,
470            F: FnOnce(
471                &mut MulticastRouteTable<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
472                &mut Self::Ctx<'_>,
473            ) -> O,
474        >(
475            &mut self,
476            state: &MulticastForwardingEnabledState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
477            cb: F,
478        ) -> O {
479            let mut route_table = state.route_table().write();
480            cb(&mut route_table, self)
481        }
482    }
483
484    impl<I: IpLayerIpExt, D: FakeStrongDeviceId>
485        MulticastForwardingPendingPacketsContext<I, FakeBindingsCtx<I, D>> for FakeCoreCtx<I, D>
486    {
487        fn with_pending_table_mut<
488            O,
489            F: FnOnce(
490                &mut MulticastForwardingPendingPackets<I, Self::WeakDeviceId, FakeBindingsCtx<I, D>>,
491            ) -> O,
492        >(
493            &mut self,
494            state: &MulticastForwardingEnabledState<I, Self::DeviceId, FakeBindingsCtx<I, D>>,
495            cb: F,
496        ) -> O {
497            let mut pending_table = state.pending_table().lock();
498            cb(&mut pending_table)
499        }
500    }
501
502    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> MulticastForwardingDeviceContext<I>
503        for FakeCoreCtx<I, D>
504    {
505        fn is_device_multicast_forwarding_enabled(&mut self, device_id: &Self::DeviceId) -> bool {
506            self.state.forwarding_enabled_devices.contains(device_id)
507        }
508    }
509
510    impl<I: IpLayerIpExt, D: FakeStrongDeviceId>
511        CoreTimerContext<MulticastForwardingTimerId<I>, FakeBindingsCtx<I, D>>
512        for FakeCoreCtx<I, D>
513    {
514        fn convert_timer(
515            dispatch_id: MulticastForwardingTimerId<I>,
516        ) -> MulticastForwardingTimerId<I> {
517            dispatch_id
518        }
519    }
520
521    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> IpDeviceSendContext<I, FakeBindingsCtx<I, D>>
522        for FakeCoreCtx<I, D>
523    {
524        fn send_ip_frame<S>(
525            &mut self,
526            _bindings_ctx: &mut FakeBindingsCtx<I, D>,
527            device_id: &D,
528            destination: IpPacketDestination<I, &D>,
529            _ip_layer_metadata: DeviceIpLayerMetadata<FakeBindingsCtx<I, D>>,
530            _body: S,
531            _egress_proof: ProofOfEgressCheck,
532        ) -> Result<(), netstack3_base::SendFrameError<S>>
533        where
534            S: Serializer,
535            S::Buffer: BufferMut,
536        {
537            let dst = match destination {
538                IpPacketDestination::Multicast(dst) => dst,
539                dst => panic!("unexpected sent packet: destination={dst:?}"),
540            };
541            self.state.sent_packets.push(SentPacket { dst, device: device_id.clone() });
542            Ok(())
543        }
544    }
545
546    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> IpDeviceMtuContext<I> for FakeCoreCtx<I, D> {
547        fn get_mtu(&mut self, _device_id: &Self::DeviceId) -> Mtu {
548            Mtu::max()
549        }
550    }
551
552    impl<I: IpLayerIpExt, D: FakeStrongDeviceId> IcmpErrorHandler<I, FakeBindingsCtx<I, D>>
553        for FakeCoreCtx<I, D>
554    {
555        fn send_icmp_error_message<B: BufferMut>(
556            &mut self,
557            _bindings_ctx: &mut FakeBindingsCtx<I, D>,
558            _device: &D,
559            _frame_dst: Option<FrameDestination>,
560            _src_ip: <I as IcmpHandlerIpExt>::SourceAddress,
561            _dst_ip: SpecifiedAddr<I::Addr>,
562            _original_packet: B,
563            _error: I::IcmpError,
564            _marks: &Marks,
565        ) {
566            unimplemented!()
567        }
568    }
569
570    pub(crate) fn new_api<I: IpLayerIpExt>() -> MulticastForwardingApi<
571        I,
572        CtxPair<FakeCoreCtx<I, MultipleDevicesId>, FakeBindingsCtx<I, MultipleDevicesId>>,
573    > {
574        MulticastForwardingApi::new(CtxPair::with_core_ctx(FakeCoreCtx::with_state(
575            Default::default(),
576        )))
577    }
578
579    /// A test helper to access the [`MulticastForwardingPendingPackets`] table.
580    ///
581    /// # Panics
582    ///
583    /// Panics if multicast forwarding is disabled.
584    pub(crate) fn with_pending_table<I, O, F, CC, BT>(core_ctx: &mut CC, cb: F) -> O
585    where
586        I: IpLayerIpExt,
587        CC: MulticastForwardingStateContext<I, BT>,
588        BT: MulticastForwardingBindingsTypes,
589        F: FnOnce(&mut MulticastForwardingPendingPackets<I, CC::WeakDeviceId, BT>) -> O,
590    {
591        core_ctx.with_state(|state, ctx| {
592            let state = state.enabled().unwrap();
593            ctx.with_route_table(state, |_routing_table, ctx| {
594                ctx.with_pending_table_mut(state, |pending_table| cb(pending_table))
595            })
596        })
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603
604    use alloc::vec;
605    use core::time::Duration;
606
607    use ip_test_macro::ip_test;
608    use netstack3_base::testutil::MultipleDevicesId;
609    use packet::ParseBuffer;
610    use test_case::test_case;
611    use testutil::TestIpExt;
612
613    use crate::internal::multicast_forwarding::route::MulticastRouteStats;
614    use crate::multicast_forwarding::MulticastRouteTarget;
615
616    struct LookupTestCase {
617        // Whether multicast forwarding is enabled for the netstack.
618        enabled: bool,
619        // Whether multicast forwarding is enabled for the device.
620        dev_enabled: bool,
621        // Whether the packet has the correct src/dst addrs.
622        right_key: bool,
623        // Whether the packet arrived on the correct device.
624        right_dev: bool,
625    }
626    const LOOKUP_SUCCESS_CASE: LookupTestCase =
627        LookupTestCase { enabled: true, dev_enabled: true, right_key: true, right_dev: true };
628
629    #[ip_test(I)]
630    #[test_case(LOOKUP_SUCCESS_CASE => true; "success")]
631    #[test_case(LookupTestCase{enabled: false, ..LOOKUP_SUCCESS_CASE} => false; "disabled")]
632    #[test_case(LookupTestCase{dev_enabled: false, ..LOOKUP_SUCCESS_CASE} => false; "dev_disabled")]
633    #[test_case(LookupTestCase{right_key: false, ..LOOKUP_SUCCESS_CASE} => false; "wrong_key")]
634    #[test_case(LookupTestCase{right_dev: false, ..LOOKUP_SUCCESS_CASE} => false; "wrong_dev")]
635    fn lookup_route<I: TestIpExt>(test_case: LookupTestCase) -> bool {
636        let LookupTestCase { enabled, dev_enabled, right_key, right_dev } = test_case;
637        const FRAME_DST: Option<FrameDestination> = None;
638        let mut api = testutil::new_api::<I>();
639
640        let expected_key = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
641        let actual_key = if right_key {
642            expected_key.clone()
643        } else {
644            MulticastRouteKey::new(I::SRC2, I::DST2).unwrap()
645        };
646
647        let expected_dev = MultipleDevicesId::A;
648        let actual_dev = if right_dev { expected_dev } else { MultipleDevicesId::B };
649
650        if enabled {
651            assert!(api.enable());
652            // NB: Only attempt to install the route when enabled; Otherwise
653            // installation fails.
654            assert_eq!(
655                api.add_multicast_route(
656                    expected_key.clone(),
657                    MulticastRoute::new_forward(
658                        expected_dev,
659                        [MulticastRouteTarget {
660                            output_interface: MultipleDevicesId::C,
661                            min_ttl: 0
662                        }]
663                        .into()
664                    )
665                    .unwrap()
666                ),
667                Ok(None)
668            );
669        }
670
671        api.core_ctx().state.set_multicast_forwarding_enabled_for_dev(actual_dev, dev_enabled);
672
673        let (core_ctx, bindings_ctx) = api.contexts();
674        let creation_time = bindings_ctx.now();
675        bindings_ctx.timers.instant.sleep(Duration::from_secs(5));
676        let lookup_time = bindings_ctx.now();
677        assert!(lookup_time > creation_time);
678
679        let buf = testutil::new_ip_packet_buf::<I>(actual_key.src_addr(), actual_key.dst_addr());
680        let mut buf_ref = buf.as_ref();
681        let packet = buf_ref.parse::<I::Packet<_>>().expect("parse should succeed");
682
683        let route = lookup_multicast_route_or_stash_packet(
684            core_ctx,
685            bindings_ctx,
686            &packet,
687            &actual_dev,
688            FRAME_DST,
689        );
690
691        // Verify that multicast routing events are generated.
692        let mut expected_events = vec![];
693        if !right_key {
694            expected_events.push(IpLayerEvent::MulticastForwarding(
695                MulticastForwardingEvent::MissingRoute {
696                    key: actual_key.clone(),
697                    input_interface: actual_dev,
698                },
699            ));
700        }
701        if !right_dev {
702            expected_events.push(IpLayerEvent::MulticastForwarding(
703                MulticastForwardingEvent::WrongInputInterface {
704                    key: actual_key,
705                    actual_input_interface: actual_dev,
706                    expected_input_interface: expected_dev,
707                },
708            ));
709        }
710        assert_eq!(bindings_ctx.take_events(), expected_events);
711
712        let lookup_succeeded = route.is_some();
713
714        if enabled {
715            // Verify that on success, the last_used field in stats is updated.
716            let expected_stats = if lookup_succeeded {
717                MulticastRouteStats { last_used: lookup_time }
718            } else {
719                MulticastRouteStats { last_used: creation_time }
720            };
721            assert_eq!(api.get_route_stats(&expected_key), Ok(Some(expected_stats)));
722        }
723
724        // Verify that counters are updated.
725        let counters: &MulticastForwardingCounters<I> = api.core_ctx().counters();
726        assert_eq!(counters.rx.get(), 1);
727        assert_eq!(counters.tx.get(), if lookup_succeeded { 1 } else { 0 });
728        assert_eq!(counters.no_tx_disabled_dev.get(), if dev_enabled { 0 } else { 1 });
729        assert_eq!(counters.no_tx_disabled_stack_wide.get(), if enabled { 0 } else { 1 });
730        assert_eq!(counters.no_tx_wrong_dev.get(), if right_dev { 0 } else { 1 });
731        assert_eq!(counters.pending_packets.get(), if right_key { 0 } else { 1 });
732
733        lookup_succeeded
734    }
735}