1use core::fmt;
12use super::super::iana::OptionCode;
13use super::super::message_builder::OptBuilder;
14use super::super::net::IpAddr;
15use super::super::wire::{Compose, Composer, FormError, ParseError};
16use super::{Opt, OptData, ComposeOptData, ParseOptData};
17use octseq::builder::OctetsBuilder;
18use octseq::octets::Octets;
19use octseq::parse::Parser;
20
21#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize))]
42pub struct ClientSubnet {
43 source_prefix_len: u8,
45
46 scope_prefix_len: u8,
48
49 addr: IpAddr,
51}
52
53impl ClientSubnet {
54 pub(super) const CODE: OptionCode = OptionCode::CLIENT_SUBNET;
56
57 #[must_use]
64 pub fn new(
65 source_prefix_len: u8,
66 scope_prefix_len: u8,
67 addr: IpAddr,
68 ) -> ClientSubnet {
69 let source_prefix_len = normalize_prefix_len(addr, source_prefix_len);
70 let scope_prefix_len = normalize_prefix_len(addr, scope_prefix_len);
71 let (addr, _) = addr_apply_mask(addr, source_prefix_len);
72
73 ClientSubnet {
74 source_prefix_len,
75 scope_prefix_len,
76 addr,
77 }
78 }
79
80 #[must_use]
85 pub fn source_prefix_len(&self) -> u8 {
86 self.source_prefix_len
87 }
88
89 #[must_use]
94 pub fn scope_prefix_len(&self) -> u8 {
95 self.scope_prefix_len
96 }
97
98 #[must_use]
100 pub fn addr(&self) -> IpAddr {
101 self.addr
102 }
103
104 pub fn parse<Octs: AsRef<[u8]>>(
106 parser: &mut Parser<Octs>
107 ) -> Result<Self, ParseError> {
108 const ERR_ADDR_LEN: &str = "invalid address length in client \
109 subnet option";
110
111 let family = parser.parse_u16_be()?;
112 let source_prefix_len = parser.parse_u8()?;
113 let scope_prefix_len = parser.parse_u8()?;
114
115 let prefix_bytes = prefix_bytes(source_prefix_len);
122
123 let addr = match family {
124 1 => {
125 let mut buf = [0; 4];
126 if prefix_bytes > buf.len() {
127 return Err(ParseError::form_error(ERR_ADDR_LEN));
128 }
129 parser
130 .parse_buf(&mut buf[..prefix_bytes])
131 .map_err(|_| ParseError::form_error(ERR_ADDR_LEN))?;
132
133 if parser.remaining() != 0 {
134 return Err(ParseError::form_error(ERR_ADDR_LEN));
135 }
136
137 IpAddr::from(buf)
138 }
139 2 => {
140 let mut buf = [0; 16];
141 if prefix_bytes > buf.len() {
142 return Err(ParseError::form_error(ERR_ADDR_LEN));
143 }
144 parser
145 .parse_buf(&mut buf[..prefix_bytes])
146 .map_err(|_| ParseError::form_error(ERR_ADDR_LEN))?;
147
148 if parser.remaining() != 0 {
149 return Err(ParseError::form_error(ERR_ADDR_LEN));
150 }
151
152 IpAddr::from(buf)
153 }
154 _ => {
155 return Err(FormError::new(
156 "invalid client subnet address family",
157 )
158 .into())
159 }
160 };
161
162 let (addr, modified) = addr_apply_mask(addr, source_prefix_len);
165 if modified {
166 return Err(ParseError::form_error(ERR_ADDR_LEN));
167 }
168
169 Ok(ClientSubnet {
171 source_prefix_len,
172 scope_prefix_len,
173 addr,
174 })
175 }
176
177 pub(super) fn try_octets_from<E>(src: Self) -> Result<Self, E> {
181 Ok(src)
182 }
183}
184
185impl OptData for ClientSubnet {
188 fn code(&self) -> OptionCode {
189 OptionCode::CLIENT_SUBNET
190 }
191}
192
193impl<'a, Octs: AsRef<[u8]>> ParseOptData<'a, Octs> for ClientSubnet {
194 fn parse_option(
195 code: OptionCode,
196 parser: &mut Parser<'a, Octs>,
197 ) -> Result<Option<Self>, ParseError> {
198 if code == OptionCode::CLIENT_SUBNET {
199 Self::parse(parser).map(Some)
200 }
201 else {
202 Ok(None)
203 }
204 }
205}
206
207impl ComposeOptData for ClientSubnet {
208 fn compose_len(&self) -> u16 {
209 u16::try_from(prefix_bytes(self.source_prefix_len)).unwrap() + 4
210 }
211
212 fn compose_option<Target: OctetsBuilder + ?Sized>(
213 &self, target: &mut Target
214 ) -> Result<(), Target::AppendError> {
215 let prefix_bytes = prefix_bytes(self.source_prefix_len);
216 match self.addr {
217 IpAddr::V4(addr) => {
218 1u16.compose(target)?;
219 self.source_prefix_len.compose(target)?;
220 self.scope_prefix_len.compose(target)?;
221 let array = addr.octets();
222 assert!(prefix_bytes <= array.len());
223 target.append_slice(&array[..prefix_bytes])
224 }
225 IpAddr::V6(addr) => {
226 2u16.compose(target)?;
227 self.source_prefix_len.compose(target)?;
228 self.scope_prefix_len.compose(target)?;
229 let array = addr.octets();
230 assert!(prefix_bytes <= array.len());
231 target.append_slice(&array[..prefix_bytes])
232 }
233 }
234 }
235}
236
237impl fmt::Display for ClientSubnet {
240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
241 match self.addr {
242 IpAddr::V4(a) => {
243 if self.scope_prefix_len != 0 {
244 write!(f, "{}/{}/{}", a, self.source_prefix_len,
245 self.scope_prefix_len)?;
246 } else {
247 write!(f, "{}/{}", a, self.source_prefix_len)?;
248 }
249 }
250 IpAddr::V6(a) => {
251 if self.scope_prefix_len != 0 {
252 write!(f, "{}/{}/{}", a, self.source_prefix_len,
253 self.scope_prefix_len)?;
254 } else {
255 write!(f, "{}/{}", a, self.source_prefix_len)?;
256 }
257 }
258 }
259
260 Ok(())
261 }
262}
263
264impl<Octs: Octets> Opt<Octs> {
267 pub fn client_subnet(&self) -> Option<ClientSubnet> {
274 self.first()
275 }
276}
277
278impl<Target: Composer> OptBuilder<'_, Target> {
279 pub fn client_subnet(
280 &mut self,
281 source_prefix_len: u8,
282 scope_prefix_len: u8,
283 addr: IpAddr,
284 ) -> Result<(), Target::AppendError> {
285 self.push(
286 &ClientSubnet::new(source_prefix_len, scope_prefix_len, addr)
287 )
288 }
289}
290
291fn prefix_bytes(bits: u8) -> usize {
295 usize::from(bits).div_ceil(8)
296}
297
298fn apply_bit_mask(buf: &mut [u8], mask: usize) -> bool {
302 let mut modified = false;
303
304 let mut p = mask / 8;
306 if p >= buf.len() {
307 return modified;
308 }
309
310 let bits = mask % 8;
312 if bits != 0 {
313 if buf[p].trailing_zeros() < (8 - bits) as u32 {
314 buf[p] &= 0xff << (8 - bits);
315 modified = true;
316 }
317 p += 1;
318 }
319
320 while p < buf.len() {
322 if buf[p] != 0 {
323 buf[p] = 0;
324 modified = true;
325 }
326 p += 1;
327 }
328
329 modified
330}
331
332fn addr_apply_mask(addr: IpAddr, len: u8) -> (IpAddr, bool) {
336 match addr {
337 IpAddr::V4(a) => {
338 let mut array = a.octets();
339 let m = apply_bit_mask(&mut array, len as usize);
340 (array.into(), m)
341 }
342 IpAddr::V6(a) => {
343 let mut array = a.octets();
344 let m = apply_bit_mask(&mut array, len as usize);
345 (array.into(), m)
346 }
347 }
348}
349
350fn normalize_prefix_len(addr: IpAddr, len: u8) -> u8 {
352 let max = match addr {
353 IpAddr::V4(_) => 32,
354 IpAddr::V6(_) => 128,
355 };
356
357 core::cmp::min(len, max)
358}
359
360#[cfg(all(test, feature="std", feature = "bytes"))]
363mod tests {
364 use super::*;
365 use super::super::test::test_option_compose_parse;
366 use octseq::builder::infallible;
367 use std::vec::Vec;
368 use core::str::FromStr;
369
370 macro_rules! check {
371 ($name:ident, $addr:expr, $prefix:expr, $exp:expr, $ok:expr) => {
372 #[test]
373 fn $name() {
374 let addr = $addr.parse().unwrap();
375 let opt = ClientSubnet::new($prefix, 0, addr);
376 assert_eq!(opt.addr(), $exp.parse::<IpAddr>().unwrap());
377
378 let mut opt_ = opt.clone();
381 opt_.addr = addr;
382 let mut buf = Vec::new();
383
384 infallible(opt_.compose_option(&mut buf));
385 match ClientSubnet::parse(&mut Parser::from_ref(&buf)) {
386 Ok(v) => assert_eq!(opt, v),
387 Err(_) => assert!(!$ok),
388 }
389 }
390 };
391 }
392
393 check!(prefix_at_boundary_v4, "192.0.2.0", 24, "192.0.2.0", true);
394 check!(prefix_at_boundary_v6, "2001:db8::", 32, "2001:db8::", true);
395 check!(prefix_no_truncation, "192.0.2.0", 23, "192.0.2.0", true);
396 check!(prefix_need_truncation, "192.0.2.0", 22, "192.0.0.0", false);
397 check!(prefix_min, "192.0.2.0", 0, "0.0.0.0", true);
398 check!(prefix_max, "192.0.2.0", 32, "192.0.2.0", true);
399 check!(prefix_too_long, "192.0.2.0", 100, "192.0.2.0", false);
400
401 #[test]
402 #[allow(clippy::redundant_closure)] fn client_subnet_compose_parse() {
404 test_option_compose_parse(
405 &ClientSubnet::new(4, 6, IpAddr::from_str("127.0.0.1").unwrap()),
406 |parser| ClientSubnet::parse(parser)
407 );
408 }
409}