Skip to main content

netstack3_ip/multicast_forwarding/
api.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//! Declares the API for configuring multicast forwarding within the netstack.
6
7use alloc::collections::btree_map;
8use core::sync::atomic::Ordering;
9
10use log::warn;
11use net_types::SpecifiedAddr;
12use net_types::ip::{Ip, IpVersionMarker};
13use netstack3_base::{
14    AnyDevice, AtomicInstant, ContextPair, CoreTimerContext, CounterContext, DeviceIdContext,
15    Inspector, InspectorDeviceExt, InstantBindingsTypes, InstantContext, StrongDeviceIdentifier,
16    WeakDeviceIdentifier,
17};
18
19use crate::internal::base::IpLayerForwardingContext;
20use crate::internal::multicast_forwarding::counters::MulticastForwardingCounters;
21use crate::internal::multicast_forwarding::packet_queue::{PacketQueue, QueuedPacket};
22use crate::internal::multicast_forwarding::route::{
23    Action, MulticastRoute, MulticastRouteEntry, MulticastRouteKey, MulticastRouteStats,
24    MulticastRouteTarget,
25};
26use crate::internal::multicast_forwarding::state::{
27    MulticastForwardingEnabledState, MulticastForwardingPendingPacketsContext as _,
28    MulticastForwardingState, MulticastForwardingStateContext, MulticastRouteTableContext as _,
29};
30use crate::internal::multicast_forwarding::{
31    MulticastForwardingBindingsTypes, MulticastForwardingDeviceContext, MulticastForwardingEvent,
32    MulticastForwardingTimerId,
33};
34use crate::{IpLayerBindingsContext, IpLayerIpExt, IpPacketDestination};
35
36/// The API action can not be performed while multicast forwarding is disabled.
37#[derive(Debug, Eq, PartialEq)]
38pub struct MulticastForwardingDisabledError {}
39
40trait MulticastForwardingStateExt<
41    I: IpLayerIpExt,
42    D: StrongDeviceIdentifier,
43    BT: MulticastForwardingBindingsTypes,
44>
45{
46    fn try_enabled(
47        &self,
48    ) -> Result<&MulticastForwardingEnabledState<I, D, BT>, MulticastForwardingDisabledError>;
49}
50
51impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: MulticastForwardingBindingsTypes>
52    MulticastForwardingStateExt<I, D, BT> for MulticastForwardingState<I, D, BT>
53{
54    fn try_enabled(
55        &self,
56    ) -> Result<&MulticastForwardingEnabledState<I, D, BT>, MulticastForwardingDisabledError> {
57        self.enabled().ok_or(MulticastForwardingDisabledError {})
58    }
59}
60
61/// The multicast forwarding API.
62pub struct MulticastForwardingApi<I: Ip, C> {
63    ctx: C,
64    _ip_mark: IpVersionMarker<I>,
65}
66
67impl<I: Ip, C> MulticastForwardingApi<I, C> {
68    /// Constructs a new multicast forwarding API.
69    pub fn new(ctx: C) -> Self {
70        Self { ctx, _ip_mark: IpVersionMarker::new() }
71    }
72}
73
74impl<I: IpLayerIpExt, C> MulticastForwardingApi<I, C>
75where
76    C: ContextPair,
77    C::CoreContext: MulticastForwardingStateContext<I, C::BindingsContext>
78        + MulticastForwardingDeviceContext<I>
79        + IpLayerForwardingContext<I, C::BindingsContext>
80        + CounterContext<MulticastForwardingCounters<I>>
81        + CoreTimerContext<MulticastForwardingTimerId<I>, C::BindingsContext>,
82    C::BindingsContext:
83        IpLayerBindingsContext<I, <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
84{
85    pub(crate) fn core_ctx(&mut self) -> &mut C::CoreContext {
86        let Self { ctx, _ip_mark } = self;
87        ctx.core_ctx()
88    }
89
90    pub(crate) fn contexts(&mut self) -> (&mut C::CoreContext, &mut C::BindingsContext) {
91        let Self { ctx, _ip_mark } = self;
92        ctx.contexts()
93    }
94
95    /// Enables multicast forwarding.
96    ///
97    /// Returns whether multicast forwarding was newly enabled.
98    pub fn enable(&mut self) -> bool {
99        let (core_ctx, bindings_ctx) = self.contexts();
100        core_ctx.with_state_mut(|state, _ctx| match state {
101            MulticastForwardingState::Enabled(_) => false,
102            MulticastForwardingState::Disabled => {
103                *state = MulticastForwardingState::Enabled(MulticastForwardingEnabledState::new::<
104                    C::CoreContext,
105                >(bindings_ctx));
106                true
107            }
108        })
109    }
110
111    /// Disables multicast forwarding.
112    ///
113    /// Returns whether multicast forwarding was newly disabled.
114    ///
115    /// Upon being disabled, the multicast route table will be cleared,
116    /// and all pending packets will be dropped.
117    pub fn disable(&mut self) -> bool {
118        self.core_ctx().with_state_mut(|state, _ctx| match state {
119            MulticastForwardingState::Disabled => false,
120            MulticastForwardingState::Enabled(_) => {
121                *state = MulticastForwardingState::Disabled;
122                true
123            }
124        })
125    }
126
127    /// Add the route to the multicast route table.
128    ///
129    /// If a route already exists with the same key, it will be replaced, and
130    /// the original route will be returned.
131    pub fn add_multicast_route(
132        &mut self,
133        key: MulticastRouteKey<I>,
134        route: MulticastRoute<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
135    ) -> Result<
136        Option<MulticastRoute<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>>,
137        MulticastForwardingDisabledError,
138    > {
139        let (core_ctx, bindings_ctx) = self.contexts();
140        let (orig_route, packet_queue_and_new_route) = core_ctx.with_state_mut(|state, ctx| {
141            let state = state.try_enabled()?;
142            ctx.with_route_table_mut(state, |route_table, ctx| {
143                let stats = MulticastRouteStats { last_used: bindings_ctx.now_atomic() };
144                match route_table.entry(key.clone()) {
145                    btree_map::Entry::Occupied(mut entry) => {
146                        // NB: We consider the stats to be associated with the
147                        // `route` rather than the route's key. As such we
148                        // replace the stats instead of preserving them.
149                        let MulticastRouteEntry { route: orig_route, stats: _ } =
150                            entry.insert(MulticastRouteEntry { route, stats });
151                        // NB: Check the invariant that any key present in the
152                        // route table is not also present in the pending table.
153                        #[cfg(debug_assertions)]
154                        ctx.with_pending_table_mut(state, |pending_table| {
155                            debug_assert!(!pending_table.contains(&key));
156                        });
157                        Ok((Some(orig_route), None))
158                    }
159                    btree_map::Entry::Vacant(entry) => {
160                        let MulticastRouteEntry { route: new_route_ref, stats: _ } =
161                            entry.insert(MulticastRouteEntry { route, stats });
162                        let packet_queue_and_new_route = ctx
163                            .with_pending_table_mut(state, |pending_table| {
164                                pending_table.remove(&key, bindings_ctx)
165                            })
166                            .map(|packet_queue| (packet_queue, new_route_ref.clone()));
167                        Ok((None, packet_queue_and_new_route))
168                    }
169                }
170            })
171        })?;
172
173        if let Some((packet_queue, new_route)) = packet_queue_and_new_route {
174            // NB: we cloned the route out to a context that's no longer holding
175            // the routing table lock. This means the route could have been
176            // removed. In general, that's okay. We'll operate on the
177            // potentially stale route as if it still exists. This mirrors the
178            // lookup pattern used by the unicast/multicast route tables in
179            // other parts of the stack.
180            handle_pending_packets(core_ctx, bindings_ctx, packet_queue, key, new_route)
181        }
182
183        Ok(orig_route)
184    }
185
186    /// Remove the route from the multicast route table.
187    ///
188    /// Returns `None` if the route did not exist.
189    pub fn remove_multicast_route(
190        &mut self,
191        key: &MulticastRouteKey<I>,
192    ) -> Result<
193        Option<MulticastRoute<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>>,
194        MulticastForwardingDisabledError,
195    > {
196        self.core_ctx().with_state_mut(|state, ctx| {
197            let state = state.try_enabled()?;
198            ctx.with_route_table_mut(state, |route_table, _ctx| {
199                Ok(route_table.remove(key).map(|MulticastRouteEntry { route, stats: _ }| route))
200            })
201        })
202    }
203
204    /// Remove all references to the device from the multicast forwarding state.
205    ///
206    /// Typically, this is called as part of device removal to purge all strong
207    /// device references.
208    ///
209    /// Any routes that reference the device as an `input_interface` will be
210    /// removed. Any routes that reference the device as a
211    /// [`MulticastRouteTarget`] will have that target removed (and will
212    /// themselves be removed if it's the only target).
213    pub fn remove_references_to_device(
214        &mut self,
215        dev: &<C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId,
216    ) {
217        self.core_ctx().with_state_mut(|state, ctx| {
218            let Some(state) = state.enabled() else {
219                // There's no state to update if forwarding is disabled.
220                return;
221            };
222            ctx.with_route_table_mut(state, |route_table, _ctx| {
223                route_table.retain(
224                    |_route_key,
225                     MulticastRouteEntry {
226                         route: MulticastRoute { action, input_interface },
227                         stats: _,
228                     }| {
229                        if dev == &*input_interface {
230                            return false;
231                        }
232                        match action {
233                            Action::Forward(targets) => {
234                                // If all targets reference the device, we should
235                                // discard the route entirely.
236                                if targets.iter().all(|target| dev == &target.output_interface) {
237                                    return false;
238                                }
239                                // Otherwise, if any target references the device,
240                                // we should remove it from the set of targets.
241                                if targets.iter().any(|target| dev == &target.output_interface) {
242                                    *targets = targets
243                                        .iter()
244                                        .filter(|target| dev != &target.output_interface)
245                                        .cloned()
246                                        .collect();
247                                }
248                            }
249                        }
250                        true
251                    },
252                )
253            })
254        })
255    }
256
257    /// Returns the [`MulticastRouteStats`], if any, for the given key.
258    pub fn get_route_stats(
259        &mut self,
260        key: &MulticastRouteKey<I>,
261    ) -> Result<
262        Option<MulticastRouteStats<<C::BindingsContext as InstantBindingsTypes>::Instant>>,
263        MulticastForwardingDisabledError,
264    > {
265        self.core_ctx().with_state(|state, ctx| {
266            let state = state.try_enabled()?;
267            ctx.with_route_table(state, |route_table, _ctx| {
268                Ok(route_table.get(key).map(
269                    |MulticastRouteEntry { route: _, stats: MulticastRouteStats { last_used } }| {
270                        MulticastRouteStats { last_used: last_used.load(Ordering::Relaxed) }
271                    },
272                ))
273            })
274        })
275    }
276
277    /// Writes multicast routing table information to the provided `inspector`.
278    pub fn inspect<
279        N: Inspector + InspectorDeviceExt<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
280    >(
281        &mut self,
282        inspector: &mut N,
283    ) {
284        self.core_ctx().with_state(|state, ctx| match state {
285            MulticastForwardingState::Disabled => {
286                inspector.record_bool("ForwardingEnabled", false);
287            }
288            MulticastForwardingState::Enabled(state) => {
289                inspector.record_bool("ForwardingEnabled", true);
290                inspector.record_child("Routes", |inspector| {
291                    ctx.with_route_table(state, |route_table, _ctx| {
292                        for (route_key, route_entry) in route_table.iter() {
293                            inspector.record_unnamed_child(|inspector| {
294                                inspector.delegate_inspectable(route_key);
295                                route_entry.inspect::<_, N>(inspector);
296                            })
297                        }
298                    })
299                });
300                // NB: All other operations on the pending table require mutable
301                // access; don't bother introducing an immutable accessor just
302                // for inspect.
303                ctx.with_pending_table_mut(state, |pending_table| {
304                    inspector.record_inspectable("PendingRoutes", pending_table);
305                });
306            }
307        })
308    }
309}
310
311/// Attempt to forward the packets from a pending [`PacketQueue`] according to a
312/// newly installed [`MulticastRoute`].
313fn handle_pending_packets<I: IpLayerIpExt, CC, BC>(
314    core_ctx: &mut CC,
315    bindings_ctx: &mut BC,
316    packet_queue: PacketQueue<I, CC::WeakDeviceId, BC>,
317    key: MulticastRouteKey<I>,
318    route: MulticastRoute<CC::DeviceId>,
319) where
320    CC: IpLayerForwardingContext<I, BC>
321        + MulticastForwardingDeviceContext<I>
322        + CounterContext<MulticastForwardingCounters<I>>,
323    BC: IpLayerBindingsContext<I, CC::DeviceId>,
324{
325    let MulticastRoute { input_interface, action } = route;
326
327    // NB: We checked that forwarding was enabled on the device before the
328    // packet was enqueued in the pending table. However, the packet may sit in
329    // the queue for an extended period of time, during which forwarding may
330    // have been disabled on the device. Check again here just in case.
331    if !core_ctx.is_device_multicast_forwarding_enabled(&input_interface) {
332        // The user just installed a multicast route, but also disabled
333        // forwarding on the device. Log a warning because that likely indicates
334        // incorrect API usage.
335        warn!(
336            "Dropping pending packets for newly installed multicast route: {key:?}. \
337            Multicast forwarding is disabled on input interface: {input_interface:?}"
338        );
339        CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
340            .pending_packet_drops_disabled_dev
341            .increment();
342        return;
343    }
344
345    let MulticastRouteKey { src_addr, dst_addr } = key.clone();
346    let dst_ip: SpecifiedAddr<I::Addr> = dst_addr.into();
347    let src_ip: I::RecvSrcAddr = src_addr.into();
348
349    for QueuedPacket { device, packet, frame_dst } in packet_queue.into_iter() {
350        let device = match device.upgrade() {
351            // Short circuit if the device was removed while the packet was
352            // pending.
353            None => continue,
354            Some(d) => d,
355        };
356        // Short circuit if the queued packet arrived on the wrong device.
357        if device != input_interface {
358            CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
359                .pending_packet_drops_wrong_dev
360                .increment();
361            bindings_ctx.on_event(
362                MulticastForwardingEvent::WrongInputInterface {
363                    key: key.clone(),
364                    actual_input_interface: device.clone(),
365                    expected_input_interface: input_interface.clone(),
366                }
367                .into(),
368            );
369            continue;
370        }
371
372        // NB: We could choose to update the `last_used` value on the route's
373        // statistics here, but that's probably overkill. We only end up in this
374        // function as part of route installation, which will have appropriately
375        // initialized `last_used`. It's not worth re-acquiring the route table
376        // lock to update it again here, as the change in time will be
377        // negligible.
378
379        match &action {
380            Action::Forward(targets) => {
381                CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
382                    .pending_packet_tx
383                    .increment();
384                let packet_iter = core::iter::repeat_n(packet, targets.len());
385                for (mut packet, MulticastRouteTarget { output_interface, min_ttl }) in
386                    packet_iter.zip(targets.iter())
387                {
388                    let packet_metadata = Default::default();
389                    crate::internal::base::determine_ip_packet_forwarding_action::<I, _, _>(
390                        core_ctx,
391                        packet.parse_ip_packet_mut(),
392                        packet_metadata,
393                        Some(*min_ttl),
394                        &input_interface,
395                        &output_interface,
396                        IpPacketDestination::from_addr(dst_ip),
397                        frame_dst,
398                        src_ip,
399                        dst_ip,
400                    )
401                    .perform_action_with_buffer(
402                        core_ctx,
403                        bindings_ctx,
404                        packet.into_inner(),
405                    );
406                }
407            }
408        }
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    use alloc::vec;
417    use core::num::NonZeroU8;
418    use core::ops::Deref;
419    use core::time::Duration;
420
421    use assert_matches::assert_matches;
422    use ip_test_macro::ip_test;
423    use net_types::MulticastAddr;
424    use netstack3_base::testutil::MultipleDevicesId;
425    use netstack3_base::{LocalFrameDestination, StrongDeviceIdentifier};
426    use packet::ParseBuffer;
427    use test_case::test_case;
428
429    use crate::IpLayerEvent;
430    use crate::internal::multicast_forwarding;
431    use crate::internal::multicast_forwarding::packet_queue::QueuePacketOutcome;
432    use crate::internal::multicast_forwarding::testutil::{SentPacket, TestIpExt};
433    use crate::multicast_forwarding::{MulticastRoute, MulticastRouteKey, MulticastRouteTarget};
434
435    const MIN_TTL: NonZeroU8 = NonZeroU8::new(1).unwrap();
436
437    #[ip_test(I)]
438    fn enable_disable<I: IpLayerIpExt>() {
439        let mut api = multicast_forwarding::testutil::new_api::<I>();
440
441        assert_matches!(
442            api.core_ctx().state.multicast_forwarding.borrow().deref(),
443            &MulticastForwardingState::Disabled
444        );
445        assert!(api.enable());
446        assert!(!api.enable());
447        assert_matches!(
448            api.core_ctx().state.multicast_forwarding.borrow().deref(),
449            &MulticastForwardingState::Enabled(_)
450        );
451        assert!(api.disable());
452        assert!(!api.disable());
453        assert_matches!(
454            api.core_ctx().state.multicast_forwarding.borrow().deref(),
455            &MulticastForwardingState::Disabled
456        );
457    }
458
459    #[ip_test(I)]
460    fn add_remove_route<I: TestIpExt>() {
461        let key1 = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
462        let key2 = MulticastRouteKey::new(I::SRC2, I::DST2).unwrap();
463        let forward_to_b = MulticastRoute::new_forward(
464            MultipleDevicesId::A,
465            [MulticastRouteTarget { output_interface: MultipleDevicesId::B, min_ttl: MIN_TTL }]
466                .into(),
467        )
468        .unwrap();
469        let forward_to_c = MulticastRoute::new_forward(
470            MultipleDevicesId::A,
471            [MulticastRouteTarget { output_interface: MultipleDevicesId::C, min_ttl: MIN_TTL }]
472                .into(),
473        )
474        .unwrap();
475
476        let mut api = multicast_forwarding::testutil::new_api::<I>();
477
478        // Adding/removing routes before multicast forwarding is enabled should
479        // fail.
480        assert_eq!(
481            api.add_multicast_route(key1.clone(), forward_to_b.clone()),
482            Err(MulticastForwardingDisabledError {})
483        );
484        assert_eq!(api.remove_multicast_route(&key1), Err(MulticastForwardingDisabledError {}));
485
486        // Enable the API and observe success.
487        assert!(api.enable());
488        assert_eq!(api.add_multicast_route(key1.clone(), forward_to_b.clone()), Ok(None));
489        assert_eq!(api.remove_multicast_route(&key1), Ok(Some(forward_to_b.clone())));
490
491        // Removing a route that doesn't exist should return `None`.
492        assert_eq!(api.remove_multicast_route(&key1), Ok(None));
493
494        // Adding a route with the same key as an existing route should
495        // overwrite the original.
496        assert_eq!(api.add_multicast_route(key1.clone(), forward_to_b.clone()), Ok(None));
497        assert_eq!(
498            api.add_multicast_route(key1.clone(), forward_to_c.clone()),
499            Ok(Some(forward_to_b.clone()))
500        );
501        assert_eq!(api.remove_multicast_route(&key1), Ok(Some(forward_to_c.clone())));
502
503        // Routes with different keys can co-exist.
504        assert_eq!(api.add_multicast_route(key1.clone(), forward_to_b.clone()), Ok(None));
505        assert_eq!(api.add_multicast_route(key2.clone(), forward_to_c.clone()), Ok(None));
506        assert_eq!(api.remove_multicast_route(&key1), Ok(Some(forward_to_b)));
507        assert_eq!(api.remove_multicast_route(&key2), Ok(Some(forward_to_c)));
508    }
509
510    #[ip_test(I)]
511    #[test_case(false, true; "forwarding_disabled")]
512    #[test_case(true, false; "forwarding_enabled_and_wrong_dev")]
513    #[test_case(true, true; "forwarding_enabled_and_right_dev")]
514    fn add_route_with_pending_packets<I: TestIpExt>(
515        forwarding_enabled_for_dev: bool,
516        right_dev: bool,
517    ) {
518        const FRAME_DST: Option<LocalFrameDestination> = None;
519        const OUTPUT_DEV: MultipleDevicesId = MultipleDevicesId::C;
520        let right_key = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
521        let wrong_key = MulticastRouteKey::new(I::SRC2, I::DST2).unwrap();
522        let expected_dev = MultipleDevicesId::A;
523        let actual_dev = if right_dev { expected_dev } else { MultipleDevicesId::B };
524
525        let route = MulticastRoute::new_forward(
526            expected_dev,
527            [MulticastRouteTarget { output_interface: OUTPUT_DEV, min_ttl: MIN_TTL }].into(),
528        )
529        .unwrap();
530
531        let mut api = multicast_forwarding::testutil::new_api::<I>();
532        assert!(api.enable());
533        api.core_ctx()
534            .state
535            .set_multicast_forwarding_enabled_for_dev(expected_dev, forwarding_enabled_for_dev);
536
537        // Setup a queued packet for `right_key`.
538        let (core_ctx, bindings_ctx) = api.contexts();
539        multicast_forwarding::testutil::with_pending_table(core_ctx, |pending_table| {
540            let buf = multicast_forwarding::testutil::new_ip_packet_buf::<I>(I::SRC1, I::DST1);
541            let mut buf_ref = buf.as_ref();
542            let packet = buf_ref.parse::<I::Packet<_>>().expect("parse should succeed");
543            assert_eq!(
544                pending_table.try_queue_packet(
545                    bindings_ctx,
546                    right_key.clone(),
547                    &packet,
548                    &actual_dev,
549                    FRAME_DST
550                ),
551                QueuePacketOutcome::QueuedInNewQueue,
552            );
553        });
554
555        // Add a route with the wrong key and expect that the packet queue is
556        // unaffected.
557        assert_eq!(api.add_multicast_route(wrong_key, route.clone()), Ok(None));
558        assert!(multicast_forwarding::testutil::with_pending_table(
559            api.core_ctx(),
560            |pending_table| pending_table.contains(&right_key)
561        ));
562
563        // Add a route with the right key and expect that the packet queue is
564        // removed.
565        assert_eq!(api.add_multicast_route(right_key.clone(), route), Ok(None));
566        assert!(multicast_forwarding::testutil::with_pending_table(
567            api.core_ctx(),
568            |pending_table| !pending_table.contains(&right_key)
569        ));
570
571        let expect_sent_packet = forwarding_enabled_for_dev && right_dev;
572        let mut expected_sent_packets = vec![];
573        if expect_sent_packet {
574            expected_sent_packets.push(SentPacket {
575                dst: MulticastAddr::new(right_key.dst_addr()).unwrap(),
576                device: OUTPUT_DEV,
577            });
578        }
579        assert_eq!(api.core_ctx().state.take_sent_packets(), expected_sent_packets);
580
581        // Verify that multicast routing events are generated.
582        let mut expected_events = vec![];
583        if !right_dev {
584            expected_events.push(IpLayerEvent::MulticastForwarding(
585                MulticastForwardingEvent::WrongInputInterface {
586                    key: right_key,
587                    actual_input_interface: actual_dev,
588                    expected_input_interface: expected_dev,
589                },
590            ));
591        }
592
593        let (_core_ctx, bindings_ctx) = api.contexts();
594        assert_eq!(bindings_ctx.take_events(), expected_events);
595
596        // Verify that counters are updated.
597        let counters: &MulticastForwardingCounters<I> = api.core_ctx().counters();
598        assert_eq!(counters.pending_packet_tx.get(), if expect_sent_packet { 1 } else { 0 });
599        assert_eq!(
600            counters.pending_packet_drops_disabled_dev.get(),
601            if forwarding_enabled_for_dev { 0 } else { 1 }
602        );
603        assert_eq!(counters.pending_packet_drops_wrong_dev.get(), if right_dev { 0 } else { 1 });
604    }
605
606    #[ip_test(I)]
607    fn remove_references_to_device<I: TestIpExt>() {
608        // NB: 4 arbitrary keys, that are unique from each other.
609        let key1 = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
610        let key2 = MulticastRouteKey::new(I::SRC2, I::DST1).unwrap();
611        let key3 = MulticastRouteKey::new(I::SRC1, I::DST2).unwrap();
612        let key4 = MulticastRouteKey::new(I::SRC2, I::DST2).unwrap();
613
614        // Create 4 routes, each exercising a different edge case.
615        const GOOD_DEV1: MultipleDevicesId = MultipleDevicesId::A;
616        const GOOD_DEV2: MultipleDevicesId = MultipleDevicesId::B;
617        const BAD_DEV: MultipleDevicesId = MultipleDevicesId::C;
618        const GOOD_TARGET1: MulticastRouteTarget<MultipleDevicesId> =
619            MulticastRouteTarget { output_interface: GOOD_DEV1, min_ttl: MIN_TTL };
620        const GOOD_TARGET2: MulticastRouteTarget<MultipleDevicesId> =
621            MulticastRouteTarget { output_interface: GOOD_DEV2, min_ttl: MIN_TTL };
622        const BAD_TARGET: MulticastRouteTarget<MultipleDevicesId> =
623            MulticastRouteTarget { output_interface: BAD_DEV, min_ttl: MIN_TTL };
624        let dev_is_input = MulticastRoute::new_forward(BAD_DEV, [GOOD_TARGET1].into()).unwrap();
625        let dev_is_only_output =
626            MulticastRoute::new_forward(GOOD_DEV1, [BAD_TARGET].into()).unwrap();
627        let dev_is_one_output =
628            MulticastRoute::new_forward(GOOD_DEV1, [GOOD_TARGET2, BAD_TARGET].into()).unwrap();
629        let no_ref_to_dev = MulticastRoute::new_forward(GOOD_DEV1, [GOOD_TARGET2].into()).unwrap();
630
631        // Verify that removing device references is a no-op when multicast
632        // forwarding is disabled.
633        let mut api = multicast_forwarding::testutil::new_api::<I>();
634        api.remove_references_to_device(&BAD_DEV.downgrade());
635        assert!(api.enable());
636
637        // Add the four routes, remove references to `Dev`, and verify that:
638        // * `dev_is_input` & `dev_is_only_output`, were both removed.
639        // * `dev_is_one_output` was updated to not list the dev in its
640        //    targets.
641        // * `no_ref_to_dev` was not updated.
642        assert_eq!(api.add_multicast_route(key1.clone(), dev_is_input), Ok(None));
643        assert_eq!(api.add_multicast_route(key2.clone(), dev_is_only_output), Ok(None));
644        assert_eq!(api.add_multicast_route(key3.clone(), dev_is_one_output), Ok(None));
645        assert_eq!(api.add_multicast_route(key4.clone(), no_ref_to_dev.clone()), Ok(None));
646        api.remove_references_to_device(&BAD_DEV.downgrade());
647        assert_eq!(api.remove_multicast_route(&key1), Ok(None));
648        assert_eq!(api.remove_multicast_route(&key2), Ok(None));
649        // NB: Equal to `dev_is_one_output`, but with `BAD_TARGET` removed.
650        assert_eq!(
651            api.remove_multicast_route(&key3),
652            Ok(Some(MulticastRoute::new_forward(GOOD_DEV1, [GOOD_TARGET2].into()).unwrap()))
653        );
654        assert_eq!(api.remove_multicast_route(&key4), Ok(Some(no_ref_to_dev)));
655    }
656
657    #[ip_test(I)]
658    fn get_route_stats<I: TestIpExt>() {
659        let key = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
660
661        let mut api = multicast_forwarding::testutil::new_api::<I>();
662
663        // Verify that get_route_stats fails when forwarding is disabled.
664        assert_eq!(api.get_route_stats(&key), Err(MulticastForwardingDisabledError {}));
665
666        // Verify that get_route_stats returns `None` if the route doesn't exist.
667        assert!(api.enable());
668        assert_eq!(api.get_route_stats(&key), Ok(None));
669
670        // Install a route and verify that get_route_stats succeeds.
671        let route = MulticastRoute::new_forward(
672            MultipleDevicesId::A,
673            [MulticastRouteTarget { output_interface: MultipleDevicesId::B, min_ttl: MIN_TTL }]
674                .into(),
675        )
676        .unwrap();
677        assert_eq!(api.add_multicast_route(key.clone(), route.clone()), Ok(None));
678        let original_time = api.ctx.bindings_ctx().now();
679        let expected_stats = MulticastRouteStats { last_used: original_time };
680        assert_eq!(api.get_route_stats(&key), Ok(Some(expected_stats)));
681
682        // Advance the timer and overwrite the route to prove we initialize
683        // stats with an up-to-date instant.
684        api.ctx.bindings_ctx().timers.instant.sleep(Duration::from_secs(5));
685        let new_time = api.ctx.bindings_ctx().now();
686        assert!(new_time > original_time);
687        let expected_stats = MulticastRouteStats { last_used: new_time };
688        assert_eq!(api.add_multicast_route(key.clone(), route.clone()), Ok(Some(route)));
689        assert_eq!(api.get_route_stats(&key), Ok(Some(expected_stats)));
690    }
691}