ipv6_router_advertisement/lib.rs
1#![doc = include_str!("../README.md")]
2
3//! Policy-free IPv6 Router Advertisement processing.
4//!
5//! This crate listens for ICMPv6 Router Advertisements, performs parsing,
6//! lifecycle handling and aggregation, and emits aggregated router events
7//! as a stream.
8//!
9//! Dropping the returned stream immediately aborts all background processing.
10
11mod aggregator;
12mod detector;
13pub mod icmpv6_socket;
14mod lifecycle;
15pub mod router_advertisement;
16
17use aggregator::Aggregator;
18use core::net::Ipv6Addr;
19use core::time::Duration;
20use detector::detect;
21use futures::StreamExt;
22use futures::{
23 future::{AbortHandle, Abortable},
24 Stream,
25};
26use icmpv6_socket::{Icmpv6Socket, RealIcmpv6Socket};
27use lifecycle::Lifecycle;
28use router_advertisement::RouterAdvertisement;
29use router_advertisement::{decode_router_advertisement, send_router_solicitation_burst};
30use std::collections::HashMap;
31use std::sync::Arc;
32use tokio::sync::mpsc;
33use tokio::time::{sleep_until, Instant};
34use tokio_stream::wrappers::ReceiverStream;
35use tracing::debug;
36
37/// IPv6 address identifying a router.
38pub type RouterIp = Ipv6Addr;
39
40/// Interface index on which router information applies.
41pub type InterfaceIndex = u32;
42
43/// Trait for types that carry a protocol-defined lifetime.
44///
45/// Implementors represent data whose validity is explicitly bounded
46/// by a duration as advertised on the wire (e.g. via Router Advertisements).
47///
48/// The returned lifetime:
49/// - is interpreted relative to the time of reception,
50/// - is converted into an absolute expiration timestamp by the lifecycle layer,
51/// - may be zero to indicate an explicit withdrawal of previously advertised data.
52///
53/// This trait intentionally carries **no time semantics** beyond exposing
54/// the raw lifetime value; expiration handling is performed by higher layers.
55pub trait Lifetime {
56 /// Returns the advertised lifetime of this item.
57 fn lifetime(&self) -> Duration;
58}
59
60/// IPv6 Prefix Information as advertised via the Prefix Information Option (PIO)
61/// in an ICMPv6 Router Advertisement (RFC 4861).
62#[derive(Debug, Clone, PartialEq, Eq, Hash)]
63pub struct PrefixInfo {
64 /// IPv6 network prefix advertised by the router.
65 ///
66 /// This is the base address of the prefix. Bits beyond `prefix_len`
67 /// MUST be ignored.
68 pub prefix: Ipv6Addr,
69
70 /// Length of the IPv6 prefix in bits.
71 ///
72 /// Typical values are:
73 /// - 64 for SLAAC prefixes
74 /// - 48 / 56 / 60 for delegated prefixes
75 pub prefix_len: u8,
76}
77
78/// Aggregated, policy-free router events emitted by this crate.
79///
80/// These events represent changes in the *effective* Router Advertisement
81/// (RA) state as observed on a given interface.
82///
83/// ## Event semantics
84///
85/// - Events are emitted **only when the aggregated state changes**.
86/// - Multiple Router Advertisements may be coalesced into a single event.
87/// - Events are always scoped to a single interface (`ifindex`).
88/// - Each event carries the **complete current state** of the affected section.
89///
90/// This crate performs **no policy decisions**:
91/// it does not start DHCPv6, configure addresses, or modify the system.
92/// Consumers are expected to interpret these events according to their
93/// own policy (e.g. via a network manager or FSM).
94#[derive(Debug, Clone)]
95pub enum Event {
96 /// At least one active router is available on this interface.
97 ///
98 /// This event is emitted when:
99 /// - the first router becomes active on the interface, or
100 /// - router flags (M/O) change as a result of aggregation.
101 RouterUpdate {
102 /// Network interface index.
103 ifindex: InterfaceIndex,
104 /// Managed (M) flag is set by at least one active router.
105 managed: bool,
106 /// Other Configuration (O) flag is set by at least one active router.
107 other_config: bool,
108 },
109
110 /// All previously known routers on this interface have expired.
111 ///
112 /// This event is emitted when the last active router on the interface
113 /// expires according to its advertised lifetime.
114 RouterDown {
115 /// Network interface index.
116 ifindex: InterfaceIndex,
117 },
118
119 /// DNS information learned via Router Advertisements (RDNSS/DNSSL).
120 ///
121 /// This event represents the **complete current DNS state** for the
122 /// interface, aggregated across all active routers.
123 ///
124 /// - `servers` contains the deduplicated DNS server list.
125 /// - `domains` contains the deduplicated DNS search domain list.
126 ///
127 /// An empty list explicitly indicates that no DNS information
128 /// remains valid for the interface.
129 RaDns {
130 /// Network interface index.
131 ifindex: InterfaceIndex,
132 /// Aggregated DNS servers.
133 servers: Vec<Ipv6Addr>,
134 /// Aggregated DNS search domains.
135 domains: Vec<String>,
136 },
137
138 /// Prefix information learned via Router Advertisements (PIO).
139 ///
140 /// This event represents the **complete set of currently valid prefixes**
141 /// for the interface, aggregated across all active routers.
142 ///
143 /// Prefixes are lease-based and may expire independently.
144 RaPrefix {
145 /// Network interface index.
146 ifindex: InterfaceIndex,
147 /// Aggregated valid prefixes.
148 prefixes: Vec<PrefixInfo>,
149 },
150
151 /// Advisory event indicating that a prefix has reached its preferred lifetime.
152 ///
153 /// This event does **not** remove the prefix. It signals that the prefix
154 /// should no longer be preferred for new address assignments, while
155 /// remaining valid until its hard lifetime expires.
156 RaPrefixSoftExpiry {
157 /// Network interface index.
158 ifindex: InterfaceIndex,
159 /// The prefix whose preferred lifetime has expired.
160 prefix: PrefixInfo,
161 },
162}
163
164/// Stream of aggregated, policy-free router events.
165///
166/// This stream is backed by an internal background task which:
167/// - receives Router Advertisements via a raw ICMPv6 socket,
168/// - performs lifecycle tracking and aggregation,
169/// - emits semantic router events.
170///
171/// ## Cancellation
172///
173/// Dropping this stream **immediately aborts** all background processing,
174/// including:
175/// - the ICMPv6 receive loop,
176/// - lifecycle timers,
177/// - any outstanding Router Solicitation bursts.
178///
179/// No explicit shutdown or cancellation handle is required.
180pub struct RouterEventStream {
181 /// Internal receiver yielding aggregated router events.
182 inner: ReceiverStream<Event>,
183 /// Abort handle used to immediately cancel all background tasks on drop.
184 abort: AbortHandle,
185}
186
187/// Delegates polling to the underlying receiver stream.
188///
189/// `RouterEventStream` implements `Stream<Item = Event>` and yields
190/// aggregated router events as they occur.
191///
192/// The stream ends only when the underlying task is terminated.
193impl Stream for RouterEventStream {
194 type Item = Event;
195
196 fn poll_next(
197 mut self: std::pin::Pin<&mut Self>,
198 cx: &mut std::task::Context<'_>,
199 ) -> std::task::Poll<Option<Self::Item>> {
200 std::pin::Pin::new(&mut self.inner).poll_next(cx)
201 }
202}
203
204/// Aborts all background processing immediately when the stream is dropped.
205///
206/// This ensures that no background tasks remain alive once the consumer
207/// stops polling the str
208impl Drop for RouterEventStream {
209 fn drop(&mut self) {
210 // Immediate cancellation of all background processing.
211 self.abort.abort();
212 }
213}
214
215impl RouterEventStream {
216 pub fn empty() -> Self {
217 let (_tx, rx) = mpsc::channel::<Event>(1);
218 let (abort, _) = AbortHandle::new_pair();
219
220 RouterEventStream {
221 inner: ReceiverStream::new(rx),
222 abort,
223 }
224 }
225}
226
227/// Start processing IPv6 Router Advertisements and return a stream of
228/// aggregated router events.
229///
230/// # Cancellation
231///
232/// Dropping the returned stream **immediately aborts** all background
233/// processing, closes the ICMPv6 socket and stops any outstanding Router
234/// Solicitation activity.
235///
236/// # Parameters
237///
238/// - `link_up_rx`: Broadcast receiver emitting interface indices whose
239/// links have transitioned to `UP`.
240///
241/// # Returns
242///
243/// A `Stream<Item = Event>` producing aggregated, policy-free router events.
244///
245/// # Notes
246///
247/// - The stream owns all background tasks.
248/// - No external shutdown or cancellation handle is required.
249/// - This function requires Tokio and Linux.
250///
251/// # Example
252///
253/// ```no_run
254/// use futures::StreamExt;
255/// use tokio_stream::wrappers::BroadcastStream;
256///
257/// # async fn example() -> anyhow::Result<()> {
258/// let (link_tx, link_rx) = tokio::sync::broadcast::channel(16);
259///
260/// // Convert broadcast receiver into a Stream of interface indices
261/// let link_up_stream = BroadcastStream::new(link_rx)
262/// .filter_map(|res| async move { res.ok() });
263///
264/// let mut events = ipv6_router_advertisement::router_events(link_up_stream);
265///
266/// // Signal that interface 2 is up
267/// let _ = link_tx.send(2);
268///
269/// while let Some(event) = events.next().await {
270/// println!("router event: {:?}", event);
271/// }
272/// # Ok(())
273/// # }
274/// ```
275pub fn router_events<S>(link_up: S) -> RouterEventStream
276where
277 S: Stream<Item = InterfaceIndex> + Send + 'static,
278{
279 let socket = match RealIcmpv6Socket::new() {
280 Ok(s) => Arc::new(s),
281 Err(e) => {
282 debug!("failed to create RA socket: {:?}", e);
283 return RouterEventStream::empty();
284 }
285 };
286
287 router_events_with_socket(link_up, socket)
288}
289
290/// Creates a stream of aggregated router events using a custom ICMPv6 socket.
291///
292/// This function wires together the complete processing pipeline:
293///
294/// - interface-up notifications,
295/// - Router Advertisement reception via the provided socket,
296/// - detector, lifecycle, and aggregation layers.
297///
298/// The returned stream yields high-level, policy-free `Event`s describing
299/// changes in the effective RA state per interface.
300///
301/// ## Parameters
302///
303/// - `link_up`: A stream producing interface indices when interfaces become active.
304/// - `socket`: An ICMPv6 socket used to receive Router Advertisements.
305///
306/// ## Returns
307///
308/// A `RouterEventStream` yielding aggregated router events.
309pub fn router_events_with_socket<S, I>(link_up: S, socket: Arc<I>) -> RouterEventStream
310where
311 S: Stream<Item = InterfaceIndex> + Send + 'static,
312 I: Icmpv6Socket + Send + Sync + 'static,
313{
314 let (event_tx, event_rx) = mpsc::channel::<Event>(16);
315 let (abort_handle, abort_reg) = AbortHandle::new_pair();
316
317 tokio::spawn(async move {
318 let mut link_up = Box::pin(link_up);
319
320 let mut aggregator = Aggregator::default();
321 let mut lifecycle = Lifecycle::default();
322 let mut pending_rs = HashMap::new();
323
324 let task = async {
325 loop {
326 let now = Instant::now();
327 tokio::select! {
328 Some(ifindex) = link_up.next() => {
329 start_rs_burst(
330 Arc::clone(&socket),
331 &mut pending_rs,
332 ifindex,
333 );
334 }
335
336 Ok((ifindex, router_ip, payload)) = socket.receive() => {
337 let Ok(ra) =
338 decode_router_advertisement(ifindex, router_ip, &payload)
339 else {
340 continue;
341 };
342
343 let lifecycle_events =
344 handle_router_advertisement(
345 ra,
346 &mut lifecycle,
347 &mut pending_rs,
348 now
349 );
350
351 if !emit_aggregated(
352 &mut aggregator,
353 lifecycle_events,
354 &event_tx,
355 ).await {
356 return;
357 }
358 }
359
360 _ = lifecycle_sleep(&lifecycle) => {
361 let (expired, soft_expiry) = lifecycle.expire(Instant::now());
362 emit_soft_expiry(&aggregator, soft_expiry, &event_tx).await;
363 if !emit_aggregated(
364 &mut aggregator,
365 expired,
366 &event_tx,
367 ).await {
368 return;
369 }
370 }
371 }
372 }
373 };
374
375 let _ = Abortable::new(task, abort_reg).await;
376 });
377
378 RouterEventStream {
379 inner: ReceiverStream::new(event_rx),
380 abort: abort_handle,
381 }
382}
383
384/// Await until the next lifecycle expiration, if any.
385///
386/// This function converts the next expiration timestamp provided by
387/// `Lifecycle` into an awaitable future.
388///
389/// If no expiration is scheduled, this function awaits indefinitely.
390///
391/// ## Notes
392///
393/// - This function performs no lifecycle logic itself.
394/// - It exists solely to bridge timestamp-based lifecycle data
395/// with Tokio's async scheduling.
396async fn lifecycle_sleep(lifecycle: &Lifecycle) {
397 if let Some(deadline) = lifecycle.next_expiry() {
398 sleep_until(deadline).await;
399 } else {
400 futures::future::pending::<()>().await;
401 }
402}
403
404/// Emit soft-expiry events for prefixes whose preferred lifetime expired.
405///
406/// Soft expiry is a *status change*, not a structural change:
407/// the prefix remains valid until its hard (valid) lifetime expires.
408/// Therefore, these events intentionally bypass the aggregator diff logic.
409///
410/// Returns `false` if the output stream has been dropped and no further
411/// events should be produced.
412async fn emit_soft_expiry(
413 aggregator: &Aggregator,
414 lifecycle_events: Vec<lifecycle::Event>,
415 tx: &mpsc::Sender<Event>,
416) -> bool {
417 for ev in lifecycle_events {
418 let lifecycle::Event::PrefixSoftExpiry { key, prefix_info } = ev else {
419 continue;
420 };
421
422 // Soft expiry is only meaningful if the prefix still exists
423 let Some(prefixes) = aggregator.get_prefixes(&key) else {
424 // Prefix already gone (hard expiry won), nothing to emit
425 continue;
426 };
427
428 if !prefixes.contains(&prefix_info) {
429 continue;
430 }
431
432 let out = Event::RaPrefixSoftExpiry {
433 ifindex: key.ifindex,
434 prefix: prefix_info,
435 };
436
437 if tx.send(out).await.is_err() {
438 return false; // consumer dropped the stream
439 }
440 }
441
442 true
443}
444
445/// Aggregate lifecycle events and emit resulting router events.
446///
447/// Returns `false` if the output stream has been dropped and no further
448/// events should be produced.
449///
450/// ## Returns
451///
452/// - `true` if all events were successfully emitted
453/// - `false` if the consumer has dropped the stream
454async fn emit_aggregated(
455 aggregator: &mut Aggregator,
456 events: Vec<lifecycle::Event>,
457 tx: &mpsc::Sender<Event>,
458) -> bool {
459 let aggregated = aggregator.process(events);
460
461 for ev in aggregated {
462 if tx.send(ev).await.is_err() {
463 return false; // stream dropped
464 }
465 }
466 true
467}
468
469/// Process a received Router Advertisement.
470///
471/// This function:
472/// - cancels any pending Router Solicitation for the interface,
473/// - converts the RA into policy-free detector events,
474/// - updates lifecycle state using the current timestamp,
475/// - returns resulting lifecycle events for aggregation.
476fn handle_router_advertisement(
477 ra: RouterAdvertisement,
478 lifecycle: &mut Lifecycle,
479 pending_rs: &mut HashMap<InterfaceIndex, AbortHandle>,
480 now: Instant,
481) -> Vec<lifecycle::Event> {
482 if let Some(handle) = pending_rs.remove(&ra.ifindex) {
483 handle.abort();
484 }
485
486 let detector_events = detect(ra);
487 lifecycle.update(detector_events, now)
488}
489
490/// Start a Router Solicitation burst for the given interface.
491///
492/// Any previously running solicitation burst for the same interface
493/// is immediately aborted.
494///
495/// The solicitation burst runs in a background task and is expected
496/// to be cancelled either:
497/// - when a Router Advertisement is received, or
498/// - when the parent event stream is dropped.
499fn start_rs_burst<I: Icmpv6Socket + 'static>(
500 socket: Arc<I>,
501 pending_rs: &mut HashMap<InterfaceIndex, AbortHandle>,
502 ifindex: InterfaceIndex,
503) {
504 if let Some(handle) = pending_rs.remove(&ifindex) {
505 handle.abort();
506 }
507
508 let (rs_abort, rs_reg) = AbortHandle::new_pair();
509 pending_rs.insert(ifindex, rs_abort);
510
511 tokio::spawn(async move {
512 let rs_task = async {
513 send_router_solicitation_burst(&*socket, ifindex, 3, Duration::from_secs(1)).await;
514 };
515 let _ = Abortable::new(rs_task, rs_reg).await;
516 });
517}
518
519#[cfg(test)]
520mod tests {
521 use super::*;
522 use detector::{DnsServers, Key};
523
524 #[tokio::test]
525 async fn stream_drop_aborts_background_task() -> anyhow::Result<()> {
526 use tokio_stream::wrappers::ReceiverStream;
527
528 let (_tx, rx) = tokio::sync::mpsc::channel::<u32>(1);
529 let stream = router_events(ReceiverStream::new(rx));
530
531 // Drop immediately
532 drop(stream);
533
534 // If this test hangs, abort handling is broken.
535 Ok(())
536 }
537
538 #[test]
539 fn lifecycle_expiry_triggers_router_down() -> anyhow::Result<()> {
540 let mut lifecycle = Lifecycle::default();
541 let mut aggregator = Aggregator::default();
542
543 let now = Instant::now();
544
545 // Pretend we detected a router
546 let events = lifecycle.update(
547 vec![detector::Event::Router {
548 key: Key::new(1, Ipv6Addr::LOCALHOST),
549 managed: false,
550 other_config: false,
551 lifetime: Duration::from_secs(1),
552 }],
553 now,
554 );
555 let _aggregated = aggregator.process(events);
556
557 // Advance time past expiry
558 let (expired, _soft_expired) = lifecycle.expire(now + Duration::from_secs(2));
559 println!("expired: {expired:?}");
560 let aggregated = aggregator.process(expired);
561 println!("aggregated: {aggregated:?}");
562
563 anyhow::ensure!(aggregated
564 .iter()
565 .any(|e| matches!(e, Event::RouterDown { ifindex: 1 })));
566 Ok(())
567 }
568
569 #[test]
570 fn ra_dns_event_is_emitted() -> anyhow::Result<()> {
571 let mut aggregator = Aggregator::default();
572
573 let events = vec![lifecycle::Event::DnsServers {
574 key: detector::Key::new(1, Ipv6Addr::LOCALHOST),
575 servers: vec![DnsServers {
576 servers: vec!["2001:db8::1".parse().unwrap()],
577 lifetime: Duration::from_secs(1),
578 }],
579 }];
580
581 let aggregated = aggregator.process(events);
582
583 anyhow::ensure!(aggregated
584 .iter()
585 .any(|e| matches!(e, Event::RaDns { ifindex: 1, .. })));
586 Ok(())
587 }
588}