Skip to main content

network/fundamentals/
route.rs

1use core::time::Duration;
2
3use file_system::IoErrorKind;
4
5use crate::{IpAddress, IpAddressAbi, IpCidr, IpCidrAbi};
6
7#[repr(C)]
8#[derive(Default, Clone, PartialEq, Eq)]
9pub struct Route {
10    pub cidr: IpCidr,
11    pub via_router: IpAddress,
12    /// Absolute monotonic time in the time manager source's epoch, not UTC.
13    pub preferred_until: Option<Duration>,
14    /// Absolute monotonic time in the time manager source's epoch, not UTC.
15    pub expires_at: Option<Duration>,
16}
17
18file_system::plain_data! {
19    #[repr(C)]
20    /// Plain-data payload mirror of an optional [`Duration`]: same size (16
21    /// bytes) and alignment (8) as `Option<Duration>`, but every byte pattern
22    /// is a valid value. Layout: `seconds` at offset 0, `nanoseconds` at
23    /// offset 8, `present` at offset 12, `reserved` at offset 13 (3 bytes,
24    /// must be zero). `present` is `0` or `1`; any other value is rejected with
25    /// `InvalidArgument`.
26    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27    pub struct OptionalDurationAbi {
28        pub seconds: u64,
29        pub nanoseconds: u32,
30        pub present: u8,
31        pub reserved: [u8; 3],
32    }
33}
34
35impl From<Option<Duration>> for OptionalDurationAbi {
36    fn from(value: Option<Duration>) -> Self {
37        match value {
38            Some(duration) => Self {
39                seconds: duration.as_secs(),
40                nanoseconds: duration.subsec_nanos(),
41                present: 1,
42                reserved: [0; 3],
43            },
44            None => Self::default(),
45        }
46    }
47}
48
49impl TryFrom<OptionalDurationAbi> for Option<Duration> {
50    type Error = IoErrorKind;
51
52    fn try_from(value: OptionalDurationAbi) -> file_system::Result<Self> {
53        match value.present {
54            0 if value.seconds == 0 && value.nanoseconds == 0 && value.reserved == [0; 3] => {
55                Ok(None)
56            }
57            1 => {
58                if value.nanoseconds >= 1_000_000_000 || value.reserved != [0; 3] {
59                    return Err(IoErrorKind::InvalidArgument);
60                }
61                Ok(Some(Duration::new(value.seconds, value.nanoseconds)))
62            }
63            _ => Err(IoErrorKind::InvalidArgument),
64        }
65    }
66}
67
68file_system::plain_data! {
69    #[repr(C)]
70    /// Plain-data payload mirror of [`Route`]: same size (80 bytes) and
71    /// alignment (8), but every byte pattern is a valid value. Layout:
72    /// `cidr` at offset 0, `via_router` at offset 24, `reserved` at offset 44
73    /// (4 bytes, must be zero), `preferred_until` at offset 48, `expires_at` at
74    /// offset 64. Unknown families and invalid optional durations are rejected
75    /// with `InvalidArgument` when converting back.
76    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77    pub struct RouteAbi {
78        pub cidr: IpCidrAbi,
79        pub via_router: IpAddressAbi,
80        pub reserved: [u8; 4],
81        pub preferred_until: OptionalDurationAbi,
82        pub expires_at: OptionalDurationAbi,
83    }
84}
85
86impl From<Route> for RouteAbi {
87    fn from(value: Route) -> Self {
88        Self {
89            cidr: value.cidr.into(),
90            via_router: value.via_router.into(),
91            reserved: [0; 4],
92            preferred_until: value.preferred_until.into(),
93            expires_at: value.expires_at.into(),
94        }
95    }
96}
97
98impl TryFrom<RouteAbi> for Route {
99    type Error = IoErrorKind;
100
101    fn try_from(value: RouteAbi) -> file_system::Result<Self> {
102        if value.reserved != [0; 4] {
103            return Err(IoErrorKind::InvalidArgument);
104        }
105        Ok(Self {
106            cidr: value.cidr.try_into()?,
107            via_router: value.via_router.try_into()?,
108            preferred_until: value.preferred_until.try_into()?,
109            expires_at: value.expires_at.try_into()?,
110        })
111    }
112}
113
114impl Route {
115    pub const fn new_default_ipv4(via_router: [u8; 4]) -> Self {
116        Self {
117            cidr: IpCidr::new_ipv4([0, 0, 0, 0], 0),
118            via_router: IpAddress::new_ipv4(via_router),
119            preferred_until: None,
120            expires_at: None,
121        }
122    }
123
124    pub const fn new_default_ipv6(via_router: [u16; 8]) -> Self {
125        Self {
126            cidr: IpCidr::new_ipv6([0, 0, 0, 0, 0, 0, 0, 0], 0),
127            via_router: IpAddress::new_ipv6(via_router),
128            preferred_until: None,
129            expires_at: None,
130        }
131    }
132
133    pub const fn from_smoltcp(route: smoltcp::iface::Route) -> Self {
134        let preferred_until = if let Some(dur) = route.preferred_until {
135            Some(Duration::from_micros(dur.total_micros() as u64))
136        } else {
137            None
138        };
139
140        let expires_at = if let Some(dur) = route.expires_at {
141            Some(Duration::from_micros(dur.total_micros() as u64))
142        } else {
143            None
144        };
145
146        Self {
147            cidr: IpCidr::from_smoltcp(&route.cidr),
148            via_router: IpAddress::from_smoltcp(&route.via_router),
149            preferred_until,
150            expires_at,
151        }
152    }
153
154    pub fn into_smoltcp(&self) -> smoltcp::iface::Route {
155        let preferred_until = self
156            .preferred_until
157            .map(|dur| smoltcp::time::Instant::from_micros(dur.as_micros() as i64));
158
159        let expires_at = self
160            .expires_at
161            .map(|dur| smoltcp::time::Instant::from_micros(dur.as_micros() as i64));
162
163        smoltcp::iface::Route {
164            cidr: self.cidr.into_smoltcp(),
165            via_router: self.via_router.into_smoltcp(),
166            preferred_until,
167            expires_at,
168        }
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::Route;
175    use core::time::Duration;
176
177    #[test]
178    fn smoltcp_conversion_keeps_whole_seconds() {
179        let mut route = Route::new_default_ipv4([192, 0, 2, 1]);
180        route.preferred_until = Some(Duration::from_millis(30_500));
181        route.expires_at = Some(Duration::from_secs(60));
182
183        assert!(Route::from_smoltcp(route.into_smoltcp()) == route);
184    }
185}
186
187#[cfg(test)]
188mod abi_tests {
189    use super::*;
190
191    #[test]
192    fn route_abi_round_trips_and_keeps_the_size_and_alignment() {
193        assert_eq!(
194            core::mem::size_of::<RouteAbi>(),
195            core::mem::size_of::<Route>()
196        );
197        assert_eq!(
198            core::mem::align_of::<RouteAbi>(),
199            core::mem::align_of::<Route>()
200        );
201        assert_eq!(
202            core::mem::size_of::<RouteAbi>(),
203            core::mem::size_of::<IpCidrAbi>()
204                + core::mem::size_of::<IpAddressAbi>()
205                + core::mem::size_of::<[u8; 4]>()
206                + 2 * core::mem::size_of::<OptionalDurationAbi>(),
207            "RouteAbi must be padding-free"
208        );
209        let route = Route {
210            cidr: IpCidr::new_ipv4([192, 168, 0, 0], 24),
211            via_router: IpAddress::new_ipv4([192, 168, 0, 1]),
212            preferred_until: Some(Duration::from_millis(1500)),
213            expires_at: None,
214        };
215        assert!(Route::try_from(RouteAbi::from(route.clone())).unwrap() == route);
216    }
217
218    #[test]
219    fn optional_duration_abi_rejects_unknown_values() {
220        assert_eq!(
221            Option::<Duration>::try_from(OptionalDurationAbi {
222                seconds: 1,
223                nanoseconds: 0,
224                present: 2,
225                reserved: [0; 3],
226            }),
227            Err(IoErrorKind::InvalidArgument)
228        );
229        assert_eq!(
230            Option::<Duration>::try_from(OptionalDurationAbi {
231                seconds: 1,
232                nanoseconds: 1_000_000_000,
233                present: 1,
234                reserved: [0; 3],
235            }),
236            Err(IoErrorKind::InvalidArgument)
237        );
238        assert_eq!(
239            Option::<Duration>::try_from(OptionalDurationAbi {
240                seconds: 3,
241                nanoseconds: 4,
242                present: 0,
243                reserved: [0; 3],
244            }),
245            Err(IoErrorKind::InvalidArgument)
246        );
247        assert_eq!(
248            Option::<Duration>::try_from(OptionalDurationAbi {
249                seconds: 3,
250                nanoseconds: 4,
251                present: 1,
252                reserved: [0; 3],
253            })
254            .unwrap(),
255            Some(Duration::new(3, 4))
256        );
257    }
258
259    #[test]
260    fn route_abi_rejects_an_invalid_nested_value() {
261        let mut route = RouteAbi::default();
262        route.cidr.family = 8;
263        assert_eq!(
264            Route::try_from(route).err(),
265            Some(IoErrorKind::InvalidArgument)
266        );
267        let route = RouteAbi {
268            reserved: [1, 0, 0, 0],
269            ..RouteAbi::default()
270        };
271        assert_eq!(
272            Route::try_from(route).err(),
273            Some(IoErrorKind::InvalidArgument)
274        );
275    }
276}