netlink_packet_route/route/
message.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// SPDX-License-Identifier: MIT

use super::super::AddressFamily;
use super::attribute::RTA_ENCAP_TYPE;
use super::error::RouteError;
use super::{RouteAttribute, RouteHeader, RouteLwEnCapType, RouteMessageBuffer, RouteType};
use netlink_packet_utils::traits::{Emitable, Parseable, ParseableParametrized};

#[derive(Debug, PartialEq, Eq, Clone, Default)]
#[non_exhaustive]
pub struct RouteMessage {
    pub header: RouteHeader,
    pub attributes: Vec<RouteAttribute>,
}

impl Emitable for RouteMessage {
    fn buffer_len(&self) -> usize {
        self.header.buffer_len() + self.attributes.as_slice().buffer_len()
    }

    fn emit(&self, buffer: &mut [u8]) {
        self.header.emit(buffer);
        self.attributes.as_slice().emit(&mut buffer[self.header.buffer_len()..]);
    }
}

impl<'a, T: AsRef<[u8]> + 'a> Parseable<RouteMessageBuffer<&'a T>> for RouteMessage {
    type Error = RouteError;
    fn parse(buf: &RouteMessageBuffer<&'a T>) -> Result<Self, RouteError> {
        // unwrap: RouteHeader can't fail.
        let header = RouteHeader::parse(buf).unwrap();
        let address_family = header.address_family;
        let route_type = header.kind;
        Ok(RouteMessage {
            header,
            attributes: Vec::<RouteAttribute>::parse_with_param(buf, (address_family, route_type))?,
        })
    }
}

impl<'a, T: AsRef<[u8]> + 'a>
    ParseableParametrized<RouteMessageBuffer<&'a T>, (AddressFamily, RouteType)>
    for Vec<RouteAttribute>
{
    type Error = RouteError;
    fn parse_with_param(
        buf: &RouteMessageBuffer<&'a T>,
        (address_family, route_type): (AddressFamily, RouteType),
    ) -> Result<Self, RouteError> {
        let mut attributes = vec![];
        let mut encap_type = RouteLwEnCapType::None;
        // The RTA_ENCAP_TYPE is provided __after__ RTA_ENCAP, we should find
        // RTA_ENCAP_TYPE first.
        for nla_buf in buf.attributes() {
            let nla = match nla_buf {
                Ok(n) => n,
                Err(_) => continue,
            };
            if nla.kind() == RTA_ENCAP_TYPE {
                if let Ok(RouteAttribute::EncapType(v)) =
                    RouteAttribute::parse_with_param(&nla, (address_family, route_type, encap_type))
                {
                    encap_type = v;
                    break;
                }
            }
        }
        for nla_buf in buf.attributes() {
            attributes.push(RouteAttribute::parse_with_param(
                &nla_buf?,
                (address_family, route_type, encap_type),
            )?);
        }
        Ok(attributes)
    }
}