1use core::hash::Hash;
10
11use fakealloc::collections::HashSet;
12use net_types::ip::{Ipv6Addr, Subnet};
13use net_types::LinkLocalUnicastAddr;
14use netstack3_base::{
15 AnyDevice, CoreTimerContext, DeviceIdContext, HandleableTimer, InstantBindingsTypes,
16 LocalTimerHeap, TimerBindingsTypes, TimerContext, WeakDeviceIdentifier,
17};
18use packet_formats::icmp::ndp::NonZeroNdpLifetime;
19
20#[derive(Debug)]
22pub struct Ipv6RouteDiscoveryState<BT: Ipv6RouteDiscoveryBindingsTypes> {
23 routes: HashSet<Ipv6DiscoveredRoute>,
28 timers: LocalTimerHeap<Ipv6DiscoveredRoute, (), BT>,
29}
30
31impl<BT: Ipv6RouteDiscoveryBindingsTypes> Ipv6RouteDiscoveryState<BT> {
32 #[cfg(any(test, feature = "testutils"))]
34 pub fn timers(&self) -> &LocalTimerHeap<Ipv6DiscoveredRoute, (), BT> {
35 &self.timers
36 }
37}
38
39impl<BC: Ipv6RouteDiscoveryBindingsContext> Ipv6RouteDiscoveryState<BC> {
40 pub fn new<D: WeakDeviceIdentifier, CC: CoreTimerContext<Ipv6DiscoveredRouteTimerId<D>, BC>>(
42 bindings_ctx: &mut BC,
43 device_id: D,
44 ) -> Self {
45 Self {
46 routes: Default::default(),
47 timers: LocalTimerHeap::new_with_context::<_, CC>(
48 bindings_ctx,
49 Ipv6DiscoveredRouteTimerId { device_id },
50 ),
51 }
52 }
53}
54
55#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
57pub struct Ipv6DiscoveredRoute {
58 pub subnet: Subnet<Ipv6Addr>,
60
61 pub gateway: Option<LinkLocalUnicastAddr<Ipv6Addr>>,
65}
66
67#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
69pub struct Ipv6DiscoveredRouteTimerId<D: WeakDeviceIdentifier> {
70 device_id: D,
71}
72
73impl<D: WeakDeviceIdentifier> Ipv6DiscoveredRouteTimerId<D> {
74 pub(super) fn device_id(&self) -> &D {
75 &self.device_id
76 }
77}
78
79pub trait Ipv6DiscoveredRoutesContext<BC>: DeviceIdContext<AnyDevice> {
84 fn add_discovered_ipv6_route(
86 &mut self,
87 bindings_ctx: &mut BC,
88 device_id: &Self::DeviceId,
89 route: Ipv6DiscoveredRoute,
90 );
91
92 fn del_discovered_ipv6_route(
95 &mut self,
96 bindings_ctx: &mut BC,
97 device_id: &Self::DeviceId,
98 route: Ipv6DiscoveredRoute,
99 );
100}
101
102pub trait Ipv6RouteDiscoveryContext<BT: Ipv6RouteDiscoveryBindingsTypes>:
104 DeviceIdContext<AnyDevice>
105{
106 type WithDiscoveredRoutesMutCtx<'a>: Ipv6DiscoveredRoutesContext<BT, DeviceId = Self::DeviceId>;
108
109 fn with_discovered_routes_mut<
111 O,
112 F: FnOnce(&mut Ipv6RouteDiscoveryState<BT>, &mut Self::WithDiscoveredRoutesMutCtx<'_>) -> O,
113 >(
114 &mut self,
115 device_id: &Self::DeviceId,
116 cb: F,
117 ) -> O;
118}
119
120pub trait Ipv6RouteDiscoveryBindingsTypes: TimerBindingsTypes + InstantBindingsTypes {}
122impl<BT> Ipv6RouteDiscoveryBindingsTypes for BT where BT: TimerBindingsTypes + InstantBindingsTypes {}
123
124pub trait Ipv6RouteDiscoveryBindingsContext:
126 Ipv6RouteDiscoveryBindingsTypes + TimerContext
127{
128}
129impl<BC> Ipv6RouteDiscoveryBindingsContext for BC where
130 BC: Ipv6RouteDiscoveryBindingsTypes + TimerContext
131{
132}
133
134pub trait RouteDiscoveryHandler<BC>: DeviceIdContext<AnyDevice> {
136 fn update_route(
143 &mut self,
144 bindings_ctx: &mut BC,
145 device_id: &Self::DeviceId,
146 route: Ipv6DiscoveredRoute,
147 lifetime: Option<NonZeroNdpLifetime>,
148 );
149
150 fn invalidate_routes(&mut self, bindings_ctx: &mut BC, device_id: &Self::DeviceId);
152}
153
154impl<BC: Ipv6RouteDiscoveryBindingsContext, CC: Ipv6RouteDiscoveryContext<BC>>
155 RouteDiscoveryHandler<BC> for CC
156{
157 fn update_route(
158 &mut self,
159 bindings_ctx: &mut BC,
160 device_id: &CC::DeviceId,
161 route: Ipv6DiscoveredRoute,
162 lifetime: Option<NonZeroNdpLifetime>,
163 ) {
164 self.with_discovered_routes_mut(device_id, |state, core_ctx| {
165 let Ipv6RouteDiscoveryState { routes, timers } = state;
166 match lifetime {
167 Some(lifetime) => {
168 let newly_added = routes.insert(route.clone());
169 if newly_added {
170 core_ctx.add_discovered_ipv6_route(bindings_ctx, device_id, route);
171 }
172
173 let prev_timer_fires_at = match lifetime {
174 NonZeroNdpLifetime::Finite(lifetime) => {
175 timers.schedule_after(bindings_ctx, route, (), lifetime.get())
176 }
177 NonZeroNdpLifetime::Infinite => timers.cancel(bindings_ctx, &route),
179 };
180
181 if newly_added {
182 if let Some((prev_timer_fires_at, ())) = prev_timer_fires_at {
183 panic!(
184 "newly added route {:?} should not have already been \
185 scheduled to fire at {:?}",
186 route, prev_timer_fires_at,
187 )
188 }
189 }
190 }
191 None => {
192 if routes.remove(&route) {
193 invalidate_route(core_ctx, bindings_ctx, device_id, state, route);
194 }
195 }
196 }
197 })
198 }
199
200 fn invalidate_routes(&mut self, bindings_ctx: &mut BC, device_id: &CC::DeviceId) {
201 self.with_discovered_routes_mut(device_id, |state, core_ctx| {
202 for route in core::mem::take(&mut state.routes).into_iter() {
203 invalidate_route(core_ctx, bindings_ctx, device_id, state, route);
204 }
205 })
206 }
207}
208
209impl<BC: Ipv6RouteDiscoveryBindingsContext, CC: Ipv6RouteDiscoveryContext<BC>>
210 HandleableTimer<CC, BC> for Ipv6DiscoveredRouteTimerId<CC::WeakDeviceId>
211{
212 fn handle(self, core_ctx: &mut CC, bindings_ctx: &mut BC, _: BC::UniqueTimerId) {
213 let Self { device_id } = self;
214 let Some(device_id) = device_id.upgrade() else {
215 return;
216 };
217 core_ctx.with_discovered_routes_mut(
218 &device_id,
219 |Ipv6RouteDiscoveryState { routes, timers }, core_ctx| {
220 let Some((route, ())) = timers.pop(bindings_ctx) else {
221 return;
222 };
223 assert!(routes.remove(&route), "invalidated route should be discovered");
224 core_ctx.del_discovered_ipv6_route(bindings_ctx, &device_id, route);
225 },
226 )
227 }
228}
229
230fn invalidate_route<BC: Ipv6RouteDiscoveryBindingsContext, CC: Ipv6DiscoveredRoutesContext<BC>>(
231 core_ctx: &mut CC,
232 bindings_ctx: &mut BC,
233 device_id: &CC::DeviceId,
234 state: &mut Ipv6RouteDiscoveryState<BC>,
235 route: Ipv6DiscoveredRoute,
236) {
237 let _: Option<(BC::Instant, ())> = state.timers.cancel(bindings_ctx, &route);
239 core_ctx.del_discovered_ipv6_route(bindings_ctx, device_id, route)
240}
241
242#[cfg(test)]
243mod tests {
244 use netstack3_base::testutil::{
245 FakeBindingsCtx, FakeCoreCtx, FakeDeviceId, FakeInstant, FakeTimerCtxExt as _,
246 FakeWeakDeviceId,
247 };
248 use netstack3_base::{CtxPair, IntoCoreTimerCtx};
249 use packet_formats::utils::NonZeroDuration;
250
251 use super::*;
252 use crate::internal::base::IPV6_DEFAULT_SUBNET;
253
254 #[derive(Default)]
255 struct FakeWithDiscoveredRoutesMutCtx {
256 route_table: HashSet<Ipv6DiscoveredRoute>,
257 }
258
259 impl DeviceIdContext<AnyDevice> for FakeWithDiscoveredRoutesMutCtx {
260 type DeviceId = FakeDeviceId;
261 type WeakDeviceId = FakeWeakDeviceId<FakeDeviceId>;
262 }
263
264 impl<C> Ipv6DiscoveredRoutesContext<C> for FakeWithDiscoveredRoutesMutCtx {
265 fn add_discovered_ipv6_route(
266 &mut self,
267 _bindings_ctx: &mut C,
268 FakeDeviceId: &Self::DeviceId,
269 route: Ipv6DiscoveredRoute,
270 ) {
271 let Self { route_table } = self;
272 let _newly_inserted = route_table.insert(route);
273 }
274
275 fn del_discovered_ipv6_route(
276 &mut self,
277 _bindings_ctx: &mut C,
278 FakeDeviceId: &Self::DeviceId,
279 route: Ipv6DiscoveredRoute,
280 ) {
281 let Self { route_table } = self;
282 let _: bool = route_table.remove(&route);
283 }
284 }
285
286 struct FakeIpv6RouteDiscoveryContext {
287 state: Ipv6RouteDiscoveryState<FakeBindingsCtxImpl>,
288 route_table: FakeWithDiscoveredRoutesMutCtx,
289 }
290
291 type FakeCoreCtxImpl = FakeCoreCtx<FakeIpv6RouteDiscoveryContext, (), FakeDeviceId>;
292
293 type FakeBindingsCtxImpl =
294 FakeBindingsCtx<Ipv6DiscoveredRouteTimerId<FakeWeakDeviceId<FakeDeviceId>>, (), (), ()>;
295
296 impl Ipv6RouteDiscoveryContext<FakeBindingsCtxImpl> for FakeCoreCtxImpl {
297 type WithDiscoveredRoutesMutCtx<'a> = FakeWithDiscoveredRoutesMutCtx;
298
299 fn with_discovered_routes_mut<
300 O,
301 F: FnOnce(
302 &mut Ipv6RouteDiscoveryState<FakeBindingsCtxImpl>,
303 &mut Self::WithDiscoveredRoutesMutCtx<'_>,
304 ) -> O,
305 >(
306 &mut self,
307 &FakeDeviceId: &Self::DeviceId,
308 cb: F,
309 ) -> O {
310 let FakeIpv6RouteDiscoveryContext { state, route_table, .. } = &mut self.state;
311 cb(state, route_table)
312 }
313 }
314
315 const ROUTE1: Ipv6DiscoveredRoute =
316 Ipv6DiscoveredRoute { subnet: IPV6_DEFAULT_SUBNET, gateway: None };
317 const ROUTE2: Ipv6DiscoveredRoute = Ipv6DiscoveredRoute {
318 subnet: unsafe {
319 Subnet::new_unchecked(Ipv6Addr::new([0x2620, 0x1012, 0x1000, 0x5000, 0, 0, 0, 0]), 64)
320 },
321 gateway: None,
322 };
323
324 const ONE_SECOND: NonZeroDuration = NonZeroDuration::from_secs(1).unwrap();
325 const TWO_SECONDS: NonZeroDuration = NonZeroDuration::from_secs(2).unwrap();
326
327 fn new_context() -> CtxPair<FakeCoreCtxImpl, FakeBindingsCtxImpl> {
328 CtxPair::with_default_bindings_ctx(|bindings_ctx| {
329 FakeCoreCtxImpl::with_state(FakeIpv6RouteDiscoveryContext {
330 state: Ipv6RouteDiscoveryState::new::<_, IntoCoreTimerCtx>(
331 bindings_ctx,
332 FakeWeakDeviceId(FakeDeviceId),
333 ),
334 route_table: Default::default(),
335 })
336 })
337 }
338
339 #[test]
340 fn new_route_no_lifetime() {
341 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
342
343 RouteDiscoveryHandler::update_route(
344 &mut core_ctx,
345 &mut bindings_ctx,
346 &FakeDeviceId,
347 ROUTE1,
348 None,
349 );
350 bindings_ctx.timers.assert_no_timers_installed();
351 }
352
353 fn discover_new_route(
354 core_ctx: &mut FakeCoreCtxImpl,
355 bindings_ctx: &mut FakeBindingsCtxImpl,
356 route: Ipv6DiscoveredRoute,
357 duration: NonZeroNdpLifetime,
358 ) {
359 RouteDiscoveryHandler::update_route(
360 core_ctx,
361 bindings_ctx,
362 &FakeDeviceId,
363 route,
364 Some(duration),
365 );
366
367 let route_table = &core_ctx.state.route_table.route_table;
368 assert!(route_table.contains(&route), "route_table={route_table:?}");
369
370 let expect = match duration {
371 NonZeroNdpLifetime::Finite(duration) => Some((FakeInstant::from(duration.get()), &())),
372 NonZeroNdpLifetime::Infinite => None,
373 };
374 assert_eq!(core_ctx.state.state.timers.get(&route), expect);
375 }
376
377 fn trigger_next_timer(
378 core_ctx: &mut FakeCoreCtxImpl,
379 bindings_ctx: &mut FakeBindingsCtxImpl,
380 route: Ipv6DiscoveredRoute,
381 ) {
382 core_ctx.state.state.timers.assert_top(&route, &());
383 assert_eq!(
384 bindings_ctx.trigger_next_timer(core_ctx),
385 Some(Ipv6DiscoveredRouteTimerId { device_id: FakeWeakDeviceId(FakeDeviceId) })
386 );
387 }
388
389 fn assert_route_invalidated(
390 core_ctx: &mut FakeCoreCtxImpl,
391 bindings_ctx: &mut FakeBindingsCtxImpl,
392 route: Ipv6DiscoveredRoute,
393 ) {
394 let route_table = &core_ctx.state.route_table.route_table;
395 assert!(!route_table.contains(&route), "route_table={route_table:?}");
396 bindings_ctx.timers.assert_no_timers_installed();
397 }
398
399 fn assert_single_invalidation_timer(
400 core_ctx: &mut FakeCoreCtxImpl,
401 bindings_ctx: &mut FakeBindingsCtxImpl,
402 route: Ipv6DiscoveredRoute,
403 ) {
404 trigger_next_timer(core_ctx, bindings_ctx, route);
405 assert_route_invalidated(core_ctx, bindings_ctx, route);
406 }
407
408 #[test]
409 fn invalidated_route_not_found() {
410 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
411
412 discover_new_route(&mut core_ctx, &mut bindings_ctx, ROUTE1, NonZeroNdpLifetime::Infinite);
413
414 assert!(core_ctx.state.route_table.route_table.remove(&ROUTE1));
417 update_to_invalidate_check_invalidation(&mut core_ctx, &mut bindings_ctx, ROUTE1);
420 }
421
422 #[test]
423 fn new_route_with_infinite_lifetime() {
424 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
425
426 discover_new_route(&mut core_ctx, &mut bindings_ctx, ROUTE1, NonZeroNdpLifetime::Infinite);
427 bindings_ctx.timers.assert_no_timers_installed();
428 }
429
430 #[test]
431 fn update_route_from_infinite_to_finite_lifetime() {
432 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
433
434 discover_new_route(&mut core_ctx, &mut bindings_ctx, ROUTE1, NonZeroNdpLifetime::Infinite);
435 bindings_ctx.timers.assert_no_timers_installed();
436
437 RouteDiscoveryHandler::update_route(
438 &mut core_ctx,
439 &mut bindings_ctx,
440 &FakeDeviceId,
441 ROUTE1,
442 Some(NonZeroNdpLifetime::Finite(ONE_SECOND)),
443 );
444 assert_eq!(
445 core_ctx.state.state.timers.get(&ROUTE1),
446 Some((FakeInstant::from(ONE_SECOND.get()), &()))
447 );
448 assert_single_invalidation_timer(&mut core_ctx, &mut bindings_ctx, ROUTE1);
449 }
450
451 fn update_to_invalidate_check_invalidation(
452 core_ctx: &mut FakeCoreCtxImpl,
453 bindings_ctx: &mut FakeBindingsCtxImpl,
454 route: Ipv6DiscoveredRoute,
455 ) {
456 RouteDiscoveryHandler::update_route(core_ctx, bindings_ctx, &FakeDeviceId, ROUTE1, None);
457 assert_route_invalidated(core_ctx, bindings_ctx, route);
458 }
459
460 #[test]
461 fn invalidate_route_with_infinite_lifetime() {
462 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
463
464 discover_new_route(&mut core_ctx, &mut bindings_ctx, ROUTE1, NonZeroNdpLifetime::Infinite);
465 bindings_ctx.timers.assert_no_timers_installed();
466
467 update_to_invalidate_check_invalidation(&mut core_ctx, &mut bindings_ctx, ROUTE1);
468 }
469 #[test]
470 fn new_route_with_finite_lifetime() {
471 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
472
473 discover_new_route(
474 &mut core_ctx,
475 &mut bindings_ctx,
476 ROUTE1,
477 NonZeroNdpLifetime::Finite(ONE_SECOND),
478 );
479 assert_single_invalidation_timer(&mut core_ctx, &mut bindings_ctx, ROUTE1);
480 }
481
482 #[test]
483 fn update_route_from_finite_to_infinite_lifetime() {
484 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
485
486 discover_new_route(
487 &mut core_ctx,
488 &mut bindings_ctx,
489 ROUTE1,
490 NonZeroNdpLifetime::Finite(ONE_SECOND),
491 );
492
493 RouteDiscoveryHandler::update_route(
494 &mut core_ctx,
495 &mut bindings_ctx,
496 &FakeDeviceId,
497 ROUTE1,
498 Some(NonZeroNdpLifetime::Infinite),
499 );
500 bindings_ctx.timers.assert_no_timers_installed();
501 }
502
503 #[test]
504 fn update_route_from_finite_to_finite_lifetime() {
505 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
506
507 discover_new_route(
508 &mut core_ctx,
509 &mut bindings_ctx,
510 ROUTE1,
511 NonZeroNdpLifetime::Finite(ONE_SECOND),
512 );
513
514 RouteDiscoveryHandler::update_route(
515 &mut core_ctx,
516 &mut bindings_ctx,
517 &FakeDeviceId,
518 ROUTE1,
519 Some(NonZeroNdpLifetime::Finite(TWO_SECONDS)),
520 );
521 assert_eq!(
522 core_ctx.state.state.timers.get(&ROUTE1),
523 Some((FakeInstant::from(TWO_SECONDS.get()), &()))
524 );
525 assert_single_invalidation_timer(&mut core_ctx, &mut bindings_ctx, ROUTE1);
526 }
527
528 #[test]
529 fn invalidate_route_with_finite_lifetime() {
530 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
531
532 discover_new_route(
533 &mut core_ctx,
534 &mut bindings_ctx,
535 ROUTE1,
536 NonZeroNdpLifetime::Finite(ONE_SECOND),
537 );
538
539 update_to_invalidate_check_invalidation(&mut core_ctx, &mut bindings_ctx, ROUTE1);
540 }
541
542 #[test]
543 fn invalidate_all_routes() {
544 let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
545 discover_new_route(
546 &mut core_ctx,
547 &mut bindings_ctx,
548 ROUTE1,
549 NonZeroNdpLifetime::Finite(ONE_SECOND),
550 );
551 discover_new_route(
552 &mut core_ctx,
553 &mut bindings_ctx,
554 ROUTE2,
555 NonZeroNdpLifetime::Finite(TWO_SECONDS),
556 );
557
558 RouteDiscoveryHandler::invalidate_routes(&mut core_ctx, &mut bindings_ctx, &FakeDeviceId);
559 bindings_ctx.timers.assert_no_timers_installed();
560 let route_table = &core_ctx.state.route_table.route_table;
561 assert!(route_table.is_empty(), "route_table={route_table:?}");
562 }
563}