Skip to main content

vpp_plugin/vnet/
types.rs

1//! VPP networking types
2
3use std::fmt;
4
5use crate::{
6    bindings::{
7        ip4_header_t, ip6_address_t, ip6_header_t, vlib_helper_format_ip4_header,
8        vlib_helper_format_ip6_header, vlib_helper_format_vnet_sw_if_index_name,
9        vlib_helper_unformat_vnet_sw_interface, vnet_get_main,
10    },
11    vlib, vppinfra,
12};
13
14impl ip6_address_t {
15    /// Creates a new IPv6 address with all bytes set to zero
16    pub const fn new() -> Self {
17        Self { as_u8: [0; 16] }
18    }
19}
20
21impl ip6_header_t {
22    /// Creates a new IPv6 header with all fields set to zero
23    pub const fn new() -> Self {
24        Self {
25            ip_version_traffic_class_and_flow_label: 0,
26            payload_length: 0,
27            protocol: 0,
28            hop_limit: 0,
29            src_address: ip6_address_t::new(),
30            dst_address: ip6_address_t::new(),
31        }
32    }
33}
34
35impl fmt::Debug for ip6_header_t {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        <Self as fmt::Display>::fmt(self, f)
38    }
39}
40
41impl fmt::Display for ip6_header_t {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        // SAFETY: vlib_helper_format_ip6_header returns a valid Vec of (not NUL-terminated)
44        // string bytes (on allocation failure it aborts)
45        let s = unsafe {
46            vppinfra::vec::Vec::from_raw(vlib_helper_format_ip6_header(
47                std::ptr::null_mut(),
48                self,
49                std::mem::size_of::<Self>(),
50            ))
51        };
52        write!(f, "{}", String::from_utf8_lossy(&s))
53    }
54}
55
56impl Clone for ip6_header_t {
57    fn clone(&self) -> Self {
58        Self { ..*self }
59    }
60}
61
62/// Error for [`SwIfIndex::parse`]
63#[derive(Debug, Copy, Clone, PartialEq, Eq)]
64pub struct SwIfIndexParseError;
65
66impl fmt::Display for SwIfIndexParseError {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        write!(f, "Software interface index parse error")
69    }
70}
71
72impl std::error::Error for SwIfIndexParseError {}
73
74/// Helper struct for displaying [`SwIfIndex`]
75pub struct SwIfIndexDisplay<'a> {
76    sw_if_index: SwIfIndex,
77    _vm: &'a vlib::MainRef,
78}
79
80impl<'a> fmt::Display for SwIfIndexDisplay<'a> {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        // SAFETY: the variable argument list matches what the format_vnet_sw_if_index_name
83        // implementation in VPP expects, and it's allowed for the s parameter to be null as
84        // this is a VPP vector which automatically allocates on null. The function cannot fail
85        // so the return value is always a valid vector pointer (of string bytes that aren't
86        // NUL-terminated). We are on a VPP main/worker thread so the shared state is initialised
87        // and there cannot be any data races in accessing it (since the state must only be
88        // mutated with the barrier taken).
89        let s = unsafe {
90            vppinfra::vec::Vec::from_raw(vlib_helper_format_vnet_sw_if_index_name(
91                std::ptr::null_mut(),
92                vnet_get_main(),
93                self.sw_if_index.0,
94            ))
95        };
96        write!(f, "{}", String::from_utf8_lossy(&s))
97    }
98}
99
100/// Software interface index
101#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
102pub struct SwIfIndex(u32);
103
104impl SwIfIndex {
105    /// The local0 interface
106    pub const LOCAL0: Self = SwIfIndex::new(0);
107
108    /// Creates a software interface index from a `u32` value
109    pub const fn new(sw_if_index: u32) -> Self {
110        Self(sw_if_index)
111    }
112
113    /// Parse the given interface name to a value of this type
114    pub fn parse(_vm: &vlib::MainRef, s: &str) -> Result<Self, SwIfIndexParseError> {
115        let mut i = vppinfra::unformat::UnformatInput::from(s);
116        let mut sw_if_index = 0;
117        // SAFETY: the variable argument list matches what the unformat_vnet_sw_interface
118        // implementation in VPP expects, and we are on a VPP main/worker thread so the shared
119        // state is initialised and there cannot be any data races in accessing it (since the
120        // state must only be mutated with the barrier taken).
121        let ret = unsafe {
122            vlib_helper_unformat_vnet_sw_interface(i.as_ptr(), vnet_get_main(), &mut sw_if_index)
123        };
124        if ret > 0 && i.eof() {
125            Ok(Self(sw_if_index))
126        } else {
127            Err(SwIfIndexParseError)
128        }
129    }
130
131    /// Return an object which implements [`fmt::Display`]
132    #[must_use]
133    pub fn display<'a>(&self, vm: &'a vlib::MainRef) -> SwIfIndexDisplay<'a> {
134        SwIfIndexDisplay {
135            sw_if_index: *self,
136            _vm: vm,
137        }
138    }
139}
140
141impl From<u32> for SwIfIndex {
142    fn from(value: u32) -> Self {
143        Self(value)
144    }
145}
146
147impl From<SwIfIndex> for u32 {
148    fn from(value: SwIfIndex) -> Self {
149        value.0
150    }
151}
152
153impl fmt::Debug for ip4_header_t {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        <Self as fmt::Display>::fmt(self, f)
156    }
157}
158
159impl fmt::Display for ip4_header_t {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        // SAFETY: vlib_helper_format_ip4_header returns a valid Vec of (not NUL-terminated)
162        // string bytes (on allocation failure it aborts)
163        let s = unsafe {
164            vppinfra::vec::Vec::from_raw(vlib_helper_format_ip4_header(
165                std::ptr::null_mut(),
166                self,
167                std::mem::size_of::<Self>(),
168            ))
169        };
170        write!(f, "{}", String::from_utf8_lossy(&s))
171    }
172}