Debian Codegraph @

third_party/rust/mtu/src/linux.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{
8 ffi::CStr,
9 io::{Error, ErrorKind, Read as _, Result, Write as _},
10 net::IpAddr,
11 num::TryFromIntError,
12 ptr, slice,
13 };
14
15 use libc::{
16 c_int, AF_NETLINK, ARPHRD_NONE, IFLA_IFNAME, IFLA_MTU, NETLINK_ROUTE, RTA_DST, RTA_OIF,
17 RTM_GETLINK, RTM_GETROUTE, RTM_NEWLINK, RTM_NEWROUTE, RTN_UNICAST, RT_SCOPE_UNIVERSE,
18 RT_TABLE_MAIN,
19 };
20 use static_assertions::{const_assert, const_assert_eq};
21
22 use crate::{aligned_by, default_err, routesocket::RouteSocket, unlikely_err};
23
24 #[allow(
25 clippy::struct_field_names,
26 non_camel_case_types,
27 clippy::too_many_lines
28 )]
29 mod bindings {
30 include!(env!("BINDINGS"));
31 }
32
33 use bindings::{ifinfomsg, nlmsghdr, rtattr, rtmsg};
34
35 asserted_const_with_type!(AF_INET, u8, libc::AF_INET, i32);
36 asserted_const_with_type!(AF_INET6, u8, libc::AF_INET6, i32);
37 asserted_const_with_type!(AF_UNSPEC, u8, libc::AF_UNSPEC, i32);
38 asserted_const_with_type!(NLM_F_REQUEST, u16, libc::NLM_F_REQUEST, c_int);
39 asserted_const_with_type!(NLM_F_ACK, u16, libc::NLM_F_ACK, c_int);
40 asserted_const_with_type!(NLMSG_ERROR, u16, libc::NLMSG_ERROR, c_int);
41
42 const_assert!(std::mem::size_of::<nlmsghdr>() <= u8::MAX as usize);
43 const_assert!(std::mem::size_of::<rtmsg>() <= u8::MAX as usize);
44 const_assert!(std::mem::size_of::<rtattr>() <= u8::MAX as usize);
45 const_assert!(std::mem::size_of::<ifinfomsg>() <= u8::MAX as usize);
46
47 const NETLINK_BUFFER_SIZE: usize = 8192; // See netlink(7) man page.
48
49 #[repr(C)]
50 enum AddrBytes {
51 V4([u8; 4]),
52 V6([u8; 16]),
53 }
54
55 impl AddrBytes {
56 const fn new(ip: IpAddr) -> Self {
57 match ip {
58 IpAddr::V4(ip) => Self::V4(ip.octets()),
59 IpAddr::V6(ip) => Self::V6(ip.octets()),
60 }
61 }
62
63 const fn len(&self) -> usize {
64 match self {
65 Self::V4(_) => 4,
66 Self::V6(_) => 16,
67 }
68 }
69 }
70
71 impl From<AddrBytes> for [u8; 16] {
72 fn from(addr: AddrBytes) -> Self {
73 match addr {
74 AddrBytes::V4(bytes) => {
75 let mut v6 = [0; 16];
76 v6[..4].copy_from_slice(&bytes);
77 v6
78 }
79 AddrBytes::V6(bytes) => bytes,
80 }
81 }
82 }
83
84 #[repr(C)]
85 #[derive(Default)]
86 struct IfIndexMsg {
87 nlmsg: nlmsghdr,
88 rtm: rtmsg,
89 rt: rtattr,
90 addr: [u8; 16],
91 }
92
93 impl IfIndexMsg {
94 fn new(remote: IpAddr, nlmsg_seq: u32) -> Self {
95 let addr = AddrBytes::new(remote);
96 #[allow(clippy::cast_possible_truncation)]
97 // Structs lens are <= u8::MAX per `const_assert!`s above; `addr_bytes` is max. 16 for IPv6.
98 let nlmsg_len = (std::mem::size_of::<nlmsghdr>()
99 + std::mem::size_of::<rtmsg>()
100 + std::mem::size_of::<rtattr>()
101 + addr.len()) as u32;
102 Self {
103 nlmsg: nlmsghdr {
104 nlmsg_len,
105 nlmsg_type: RTM_GETROUTE,
106 nlmsg_flags: NLM_F_REQUEST | NLM_F_ACK,
107 nlmsg_seq,
108 ..Default::default()
109 },
110 rtm: rtmsg {
111 rtm_family: match remote {
112 IpAddr::V4(_) => AF_INET,
113 IpAddr::V6(_) => AF_INET6,
114 },
115 rtm_dst_len: match remote {
116 IpAddr::V4(_) => 32,
117 IpAddr::V6(_) => 128,
118 },
119 rtm_table: RT_TABLE_MAIN,
120 rtm_scope: RT_SCOPE_UNIVERSE,
121 rtm_type: RTN_UNICAST,
122 ..Default::default()
123 },
124 rt: rtattr {
125 #[allow(clippy::cast_possible_truncation)]
126 // Structs len is <= u8::MAX per `const_assert!` above; `addr_bytes` is max. 16 for IPv6.
127 rta_len: (std::mem::size_of::<rtattr>() + addr.len()) as u16,
128 rta_type: RTA_DST,
129 },
130 addr: addr.into(),
131 }
132 }
133
134 const fn len(&self) -> usize {
135 let len = self.nlmsg.nlmsg_len as usize;
136 debug_assert!(len <= std::mem::size_of::<Self>());
137 len
138 }
139 }
140
141 impl From<&IfIndexMsg> for &[u8] {
142 fn from(value: &IfIndexMsg) -> Self {
143 unsafe { slice::from_raw_parts(ptr::from_ref(value).cast(), value.len()) }
144 }
145 }
146
147 impl TryFrom<&[u8]> for nlmsghdr {
148 type Error = Error;
149
150 fn try_from(value: &[u8]) -> Result<Self> {
151 if value.len() < std::mem::size_of::<Self>() {
152 return Err(default_err());
153 }
154 Ok(unsafe { ptr::read_unaligned(value.as_ptr().cast()) })
155 }
156 }
157
158 fn parse_c_int(buf: &[u8]) -> Result<c_int> {
159 let bytes = <&[u8] as TryInto<[u8; std::mem::size_of::<c_int>()]>>::try_into(
160 &buf[..std::mem::size_of::<c_int>()],
161 )
162 .map_err(|_| default_err())?;
163 Ok(c_int::from_ne_bytes(bytes))
164 }
165
166 fn read_msg_with_seq(fd: &mut RouteSocket, seq: u32, kind: u16) -> Result<(nlmsghdr, Vec<u8>)> {
167 loop {
168 let buf = &mut [0u8; NETLINK_BUFFER_SIZE];
169 let len = fd.read(buf.as_mut_slice())?;
170 let mut next = &buf[..len];
171 while std::mem::size_of::<nlmsghdr>() <= next.len() {
172 let (hdr, mut msg) = next.split_at(std::mem::size_of::<nlmsghdr>());
173 let hdr: nlmsghdr = hdr.try_into()?;
174 // `msg` has the remainder of this message plus any following messages.
175 // Strip those it off and assign them to `next`.
176 debug_assert!(std::mem::size_of::<nlmsghdr>() <= hdr.nlmsg_len as usize);
177 (msg, next) = msg.split_at(hdr.nlmsg_len as usize - std::mem::size_of::<nlmsghdr>());
178
179 if hdr.nlmsg_seq != seq {
180 continue;
181 }
182
183 if hdr.nlmsg_type == NLMSG_ERROR {
184 // Extract the error code and return it.
185 let err = parse_c_int(msg)?;
186 if err != 0 {
187 return Err(Error::from_raw_os_error(-err));
188 }
189 } else if hdr.nlmsg_type == kind {
190 // Return the header and the message.
191 return Ok((hdr, msg.to_vec()));
192 }
193 }
194 }
195 }
196
197 impl TryFrom<&[u8]> for rtattr {
198 type Error = Error;
199
200 fn try_from(value: &[u8]) -> Result<Self> {
201 if value.len() < std::mem::size_of::<Self>() {
202 return Err(default_err());
203 }
204 Ok(unsafe { ptr::read_unaligned(value.as_ptr().cast()) })
205 }
206 }
207
208 struct RtAttr<'a> {
209 hdr: rtattr,
210 msg: &'a [u8],
211 }
212
213 impl<'a> RtAttr<'a> {
214 fn new(bytes: &'a [u8]) -> Result<Self> {
215 debug_assert!(bytes.len() >= std::mem::size_of::<rtattr>());
216 let (hdr, mut msg) = bytes.split_at(std::mem::size_of::<rtattr>());
217 let hdr: rtattr = hdr.try_into()?;
218 let aligned_len = aligned_by(hdr.rta_len.into(), 4);
219 debug_assert!(std::mem::size_of::<rtattr>() <= aligned_len);
220 (msg, _) = msg.split_at(aligned_len - std::mem::size_of::<rtattr>());
221 Ok(Self { hdr, msg })
222 }
223 }
224
225 struct RtAttrs<'a>(&'a [u8]);
226
227 impl<'a> Iterator for RtAttrs<'a> {
228 type Item = RtAttr<'a>;
229
230 fn next(&mut self) -> Option<Self::Item> {
231 if std::mem::size_of::<rtattr>() <= self.0.len() {
232 let attr = RtAttr::new(self.0).ok()?;
233 let aligned_len = aligned_by(attr.hdr.rta_len.into(), 4);
234 debug_assert!(self.0.len() >= aligned_len);
235 self.0 = self.0.split_at(aligned_len).1;
236 Some(attr)
237 } else {
238 None
239 }
240 }
241 }
242
243 fn if_index(remote: IpAddr, fd: &mut RouteSocket) -> Result<i32> {
244 // Send RTM_GETROUTE message to get the interface index associated with the destination.
245 let msg_seq = RouteSocket::new_seq();
246 let msg = IfIndexMsg::new(remote, msg_seq);
247 fd.write_all((&msg).into())?;
248
249 // Receive RTM_GETROUTE response.
250 let (_hdr, mut buf) = read_msg_with_seq(fd, msg_seq, RTM_NEWROUTE)?;
251 debug_assert!(std::mem::size_of::<rtmsg>() <= buf.len());
252 let buf = buf.split_off(std::mem::size_of::<rtmsg>());
253
254 // Parse through the attributes to find the interface index.
255 for attr in RtAttrs(buf.as_slice()).by_ref() {
256 if attr.hdr.rta_type == RTA_OIF {
257 // We have our interface index.
258 return parse_c_int(attr.msg);
259 }
260 }
261 Err(default_err())
262 }
263
264 #[repr(C)]
265 struct IfInfoMsg {
266 nlmsg: nlmsghdr,
267 ifim: ifinfomsg,
268 }
269
270 impl IfInfoMsg {
271 fn new(if_index: i32, nlmsg_seq: u32) -> Self {
272 #[allow(clippy::cast_possible_truncation)]
273 // Structs lens are <= u8::MAX per `const_assert!`s above.
274 let nlmsg_len = (std::mem::size_of::<nlmsghdr>() + std::mem::size_of::<ifinfomsg>()) as u32;
275 Self {
276 nlmsg: nlmsghdr {
277 nlmsg_len,
278 nlmsg_type: RTM_GETLINK,
279 nlmsg_flags: NLM_F_REQUEST | NLM_F_ACK,
280 nlmsg_seq,
281 ..Default::default()
282 },
283 ifim: ifinfomsg {
284 ifi_family: AF_UNSPEC,
285 ifi_type: ARPHRD_NONE,
286 ifi_index: if_index,
287 ..Default::default()
288 },
289 }
290 }
291
292 const fn len(&self) -> usize {
293 self.nlmsg.nlmsg_len as usize
294 }
295 }
296
297 impl From<&IfInfoMsg> for &[u8] {
298 fn from(value: &IfInfoMsg) -> Self {
299 debug_assert!(value.len() >= std::mem::size_of::<Self>());
300 unsafe { slice::from_raw_parts(ptr::from_ref(value).cast(), value.len()) }
301 }
302 }
303
304 fn if_name_mtu(if_index: i32, fd: &mut RouteSocket) -> Result<(String, usize)> {
305 // Send RTM_GETLINK message to get interface information for the given interface index.
306 let msg_seq = RouteSocket::new_seq();
307 let msg = IfInfoMsg::new(if_index, msg_seq);
308 fd.write_all((&msg).into())?;
309
310 // Receive RTM_GETLINK response.
311 let (_hdr, mut buf) = read_msg_with_seq(fd, msg_seq, RTM_NEWLINK)?;
312 debug_assert!(std::mem::size_of::<ifinfomsg>() <= buf.len());
313 let buf = buf.split_off(std::mem::size_of::<ifinfomsg>());
314
315 // Parse through the attributes to find the interface name and MTU.
316 let mut ifname = None;
317 let mut mtu = None;
318 for attr in RtAttrs(buf.as_slice()).by_ref() {
319 match attr.hdr.rta_type {
320 IFLA_IFNAME => {
321 let name = CStr::from_bytes_until_nul(attr.msg)
322 .map_err(|err| Error::new(ErrorKind::Other, err))?;
323 ifname = Some(
324 name.to_str()
325 .map_err(|err| Error::new(ErrorKind::Other, err))?
326 .to_string(),
327 );
328 }
329 IFLA_MTU => {
330 mtu = Some(
331 parse_c_int(attr.msg)?
332 .try_into()
333 .map_err(|e: TryFromIntError| unlikely_err(e.to_string()))?,
334 );
335 }
336 _ => (),
337 }
338 if let (Some(ifname), Some(mtu)) = (ifname.as_ref(), mtu.as_ref()) {
339 return Ok((ifname.clone(), *mtu));
340 }
341 }
342
343 Err(default_err())
344 }
345
346 pub fn interface_and_mtu_impl(remote: IpAddr) -> Result<(String, usize)> {
347 // Create a netlink socket.
348 let mut fd = RouteSocket::new(AF_NETLINK, NETLINK_ROUTE)?;
349 let if_index = if_index(remote, &mut fd)?;
350 if_name_mtu(if_index, &mut fd)
351 }