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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// SPDX-License-Identifier: MIT

use anyhow::Context;
use netlink_packet_utils::{
    nla::{NlaBuffer, NlasIterator},
    traits::{Emitable, ParseableParametrized},
    DecodeError,
};

use super::{
    super::AddressFamily, RouteAttribute, RouteLwEnCapType, RouteType,
};

pub(crate) const RTNH_F_DEAD: u8 = 1;
pub(crate) const RTNH_F_PERVASIVE: u8 = 2;
pub(crate) const RTNH_F_ONLINK: u8 = 4;
pub(crate) const RTNH_F_OFFLOAD: u8 = 8;
pub(crate) const RTNH_F_LINKDOWN: u8 = 16;
pub(crate) const RTNH_F_UNRESOLVED: u8 = 32;
pub(crate) const RTNH_F_TRAP: u8 = 64;

#[derive(Clone, Eq, PartialEq, Debug, Copy)]
#[non_exhaustive]
pub enum RouteNextHopFlag {
    Dead,
    Pervasive,
    Onlink,
    Offload,
    Linkdown,
    Unresolved,
    Trap,
    Other(u8),
}

impl From<RouteNextHopFlag> for u8 {
    fn from(v: RouteNextHopFlag) -> u8 {
        match v {
            RouteNextHopFlag::Dead => RTNH_F_DEAD,
            RouteNextHopFlag::Pervasive => RTNH_F_PERVASIVE,
            RouteNextHopFlag::Onlink => RTNH_F_ONLINK,
            RouteNextHopFlag::Offload => RTNH_F_OFFLOAD,
            RouteNextHopFlag::Linkdown => RTNH_F_LINKDOWN,
            RouteNextHopFlag::Unresolved => RTNH_F_UNRESOLVED,
            RouteNextHopFlag::Trap => RTNH_F_TRAP,
            RouteNextHopFlag::Other(i) => i,
        }
    }
}

const ALL_NH_FLAGS: [RouteNextHopFlag; 7] = [
    RouteNextHopFlag::Dead,
    RouteNextHopFlag::Pervasive,
    RouteNextHopFlag::Onlink,
    RouteNextHopFlag::Offload,
    RouteNextHopFlag::Linkdown,
    RouteNextHopFlag::Unresolved,
    RouteNextHopFlag::Trap,
];

#[derive(Clone, Eq, PartialEq, Debug)]
struct VecRouteNextHopFlag(Vec<RouteNextHopFlag>);

impl From<u8> for VecRouteNextHopFlag {
    fn from(d: u8) -> Self {
        let mut got: u8 = 0;
        let mut ret = Vec::new();
        for flag in ALL_NH_FLAGS {
            if (d & (u8::from(flag))) > 0 {
                ret.push(flag);
                got += u8::from(flag);
            }
        }
        if got != d {
            ret.push(RouteNextHopFlag::Other(d - got));
        }
        Self(ret)
    }
}

impl From<&VecRouteNextHopFlag> for u8 {
    fn from(v: &VecRouteNextHopFlag) -> u8 {
        let mut d: u8 = 0;
        for flag in &v.0 {
            d += u8::from(*flag);
        }
        d
    }
}

const PAYLOAD_OFFSET: usize = 8;

buffer!(RouteNextHopBuffer {
    length: (u16, 0..2),
    flags: (u8, 2),
    hops: (u8, 3),
    interface_index: (u32, 4..8),
    payload: (slice, PAYLOAD_OFFSET..),
});

impl<T: AsRef<[u8]>> RouteNextHopBuffer<T> {
    pub fn new_checked(buffer: T) -> Result<Self, DecodeError> {
        let packet = Self::new(buffer);
        packet.check_buffer_length()?;
        Ok(packet)
    }

    fn check_buffer_length(&self) -> Result<(), DecodeError> {
        let len = self.buffer.as_ref().len();
        if len < PAYLOAD_OFFSET {
            return Err(format!(
                "invalid RouteNextHopBuffer: length {len} < {PAYLOAD_OFFSET}"
            )
            .into());
        }
        if len < self.length() as usize {
            return Err(format!(
                "invalid RouteNextHopBuffer: length {} < {}",
                len,
                8 + self.length()
            )
            .into());
        }
        Ok(())
    }
}

impl<'a, T: AsRef<[u8]> + ?Sized> RouteNextHopBuffer<&'a T> {
    pub fn attributes(
        &self,
    ) -> impl Iterator<Item = Result<NlaBuffer<&'a [u8]>, DecodeError>> {
        NlasIterator::new(
            &self.payload()[..(self.length() as usize - PAYLOAD_OFFSET)],
        )
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Default)]
#[non_exhaustive]
pub struct RouteNextHop {
    /// Next-hop flags
    pub flags: Vec<RouteNextHopFlag>,
    /// Next-hop priority
    pub hops: u8,
    /// Interface index for the next-hop
    pub interface_index: u32,
    /// Attributes
    pub attributes: Vec<RouteAttribute>,
}

impl<'a, T: AsRef<[u8]>>
    ParseableParametrized<
        RouteNextHopBuffer<&'a T>,
        (AddressFamily, RouteType, RouteLwEnCapType),
    > for RouteNextHop
{
    fn parse_with_param(
        buf: &RouteNextHopBuffer<&T>,
        (address_family, route_type, encap_type): (
            AddressFamily,
            RouteType,
            RouteLwEnCapType,
        ),
    ) -> Result<RouteNextHop, DecodeError> {
        let attributes = Vec::<RouteAttribute>::parse_with_param(
            &RouteNextHopBuffer::new_checked(buf.buffer)
                .context("cannot parse route attributes in next-hop")?,
            (address_family, route_type, encap_type),
        )
        .context("cannot parse route attributes in next-hop")?;
        Ok(RouteNextHop {
            flags: VecRouteNextHopFlag::from(buf.flags()).0,
            hops: buf.hops(),
            interface_index: buf.interface_index(),
            attributes,
        })
    }
}

impl<'a, T: AsRef<[u8]> + 'a>
    ParseableParametrized<
        RouteNextHopBuffer<&'a T>,
        (AddressFamily, RouteType, RouteLwEnCapType),
    > for Vec<RouteAttribute>
{
    fn parse_with_param(
        buf: &RouteNextHopBuffer<&'a T>,
        (address_family, route_type, encap_type): (
            AddressFamily,
            RouteType,
            RouteLwEnCapType,
        ),
    ) -> Result<Self, DecodeError> {
        let mut nlas = vec![];
        for nla_buf in buf.attributes() {
            nlas.push(RouteAttribute::parse_with_param(
                &nla_buf?,
                (address_family, route_type, encap_type),
            )?);
        }
        Ok(nlas)
    }
}

impl Emitable for RouteNextHop {
    fn buffer_len(&self) -> usize {
        // len, flags, hops and interface id fields
        PAYLOAD_OFFSET + self.attributes.as_slice().buffer_len()
    }

    fn emit(&self, buffer: &mut [u8]) {
        let mut nh_buffer = RouteNextHopBuffer::new(buffer);
        nh_buffer.set_length(self.buffer_len() as u16);
        nh_buffer
            .set_flags(u8::from(&VecRouteNextHopFlag(self.flags.to_vec())));
        nh_buffer.set_hops(self.hops);
        nh_buffer.set_interface_index(self.interface_index);
        self.attributes.as_slice().emit(nh_buffer.payload_mut())
    }
}