| 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 |
marker::PhantomData, |
| 11 |
net::IpAddr, |
| 12 |
num::TryFromIntError, |
| 13 |
ops::Deref, |
| 14 |
ptr, slice, |
| 15 |
}; |
| 16 |
|
| 17 |
use libc::{ |
| 18 |
freeifaddrs, getifaddrs, getpid, if_indextoname, ifaddrs, in6_addr, in_addr, sockaddr, |
| 19 |
sockaddr_dl, sockaddr_in, sockaddr_in6, sockaddr_storage, AF_UNSPEC, PF_ROUTE, |
| 20 |
}; |
| 21 |
use static_assertions::{const_assert, const_assert_eq}; |
| 22 |
|
| 23 |
#[allow( |
| 24 |
non_camel_case_types, |
| 25 |
clippy::struct_field_names, |
| 26 |
clippy::too_many_lines, |
| 27 |
clippy::cognitive_complexity, |
| 28 |
dead_code // RTA_IFP is only used on NetBSD and Solaris |
| 29 |
)] |
| 30 |
mod bindings { |
| 31 |
include!(env!("BINDINGS")); |
| 32 |
} |
| 33 |
|
| 34 |
#[cfg(any(target_os = "netbsd", target_os = "solaris"))] |
| 35 |
use crate::bsd::bindings::RTA_IFP; |
| 36 |
use crate::{ |
| 37 |
aligned_by, |
| 38 |
bsd::bindings::{if_data, rt_msghdr, RTAX_MAX, RTA_DST}, |
| 39 |
default_err, |
| 40 |
routesocket::RouteSocket, |
| 41 |
unlikely_err, |
| 42 |
}; |
| 43 |
|
| 44 |
#[cfg(target_os = "macos")] |
| 45 |
const ALIGN: usize = std::mem::size_of::<libc::c_int>(); |
| 46 |
|
| 47 |
#[cfg(bsd)] |
| 48 |
// See https://github.com/freebsd/freebsd-src/blob/524a425d30fce3d5e47614db796046830b1f6a83/sys/net/route.h#L362-L371 |
| 49 |
// See https://github.com/NetBSD/src/blob/4b50954e98313db58d189dd87b4541929efccb09/sys/net/route.h#L329-L331 |
| 50 |
// See https://github.com/Arquivotheca/Solaris-8/blob/2ad1d32f9eeed787c5adb07eb32544276e2e2444/osnet_volume/usr/src/cmd/cmd-inet/usr.sbin/route.c#L238-L239 |
| 51 |
const ALIGN: usize = std::mem::size_of::<libc::c_long>(); |
| 52 |
|
| 53 |
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))] |
| 54 |
asserted_const_with_type!(RTM_ADDRS, i32, RTA_DST, u32); |
| 55 |
|
| 56 |
#[cfg(any(target_os = "netbsd", target_os = "solaris"))] |
| 57 |
asserted_const_with_type!(RTM_ADDRS, i32, RTA_DST | RTA_IFP, u32); |
| 58 |
|
| 59 |
#[cfg(not(target_os = "solaris"))] |
| 60 |
type AddressFamily = u8; |
| 61 |
|
| 62 |
#[cfg(target_os = "solaris")] |
| 63 |
type AddressFamily = u16; |
| 64 |
|
| 65 |
asserted_const_with_type!(AF_INET, AddressFamily, libc::AF_INET, i32); |
| 66 |
asserted_const_with_type!(AF_INET6, AddressFamily, libc::AF_INET6, i32); |
| 67 |
asserted_const_with_type!(AF_LINK, AddressFamily, libc::AF_LINK, i32); |
| 68 |
asserted_const_with_type!(RTM_VERSION, u8, bindings::RTM_VERSION, u32); |
| 69 |
asserted_const_with_type!(RTM_GET, u8, bindings::RTM_GET, u32); |
| 70 |
|
| 71 |
const_assert!(std::mem::size_of::<sockaddr_in>() + ALIGN <= u8::MAX as usize); |
| 72 |
const_assert!(std::mem::size_of::<sockaddr_in6>() + ALIGN <= u8::MAX as usize); |
| 73 |
const_assert!(std::mem::size_of::<rt_msghdr>() <= u8::MAX as usize); |
| 74 |
|
| 75 |
struct IfAddrs(*mut ifaddrs); |
| 76 |
|
| 77 |
impl Default for IfAddrs { |
| 78 |
fn default() -> Self { |
| 79 |
Self(ptr::null_mut()) |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
impl IfAddrs { |
| 84 |
fn new() -> Result<Self> { |
| 85 |
let mut ifap = Self::default(); |
| 86 |
// getifaddrs allocates memory for the linked list of interfaces that is freed by |
| 87 |
// `IfAddrs::drop`. |
| 88 |
if unsafe { getifaddrs(ptr::from_mut(&mut ifap.0)) } != 0 { |
| 89 |
return Err(Error::last_os_error()); |
| 90 |
} |
| 91 |
Ok(ifap) |
| 92 |
} |
| 93 |
|
| 94 |
const fn iter(&self) -> IfAddrPtr { |
| 95 |
IfAddrPtr { |
| 96 |
ptr: self.0, |
| 97 |
_ref: PhantomData, |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
impl Drop for IfAddrs { |
| 103 |
fn drop(&mut self) { |
| 104 |
if !self.0.is_null() { |
| 105 |
// Free the memory allocated by `getifaddrs`. |
| 106 |
unsafe { |
| 107 |
freeifaddrs(self.0); |
| 108 |
} |
| 109 |
} |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
struct IfAddrPtr<'a> { |
| 114 |
ptr: *mut ifaddrs, |
| 115 |
_ref: PhantomData<&'a ifaddrs>, |
| 116 |
} |
| 117 |
|
| 118 |
impl IfAddrPtr<'_> { |
| 119 |
fn addr(&self) -> sockaddr { |
| 120 |
unsafe { *self.ifa_addr } |
| 121 |
} |
| 122 |
|
| 123 |
fn name(&self) -> String { |
| 124 |
unsafe { CStr::from_ptr(self.ifa_name).to_string_lossy().to_string() } |
| 125 |
} |
| 126 |
|
| 127 |
fn data(&self) -> Option<if_data> { |
| 128 |
if self.ifa_data.is_null() { |
| 129 |
None |
| 130 |
} else { |
| 131 |
Some(unsafe { self.ifa_data.cast::<if_data>().read() }) |
| 132 |
} |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
impl Deref for IfAddrPtr<'_> { |
| 137 |
type Target = ifaddrs; |
| 138 |
|
| 139 |
fn deref(&self) -> &Self::Target { |
| 140 |
unsafe { self.ptr.as_ref().expect("can deref") } |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
impl Iterator for IfAddrPtr<'_> { |
| 145 |
type Item = Self; |
| 146 |
|
| 147 |
fn next(&mut self) -> Option<Self::Item> { |
| 148 |
ptr::NonNull::new(self.ptr).map(|p| { |
| 149 |
self.ptr = unsafe { p.as_ref().ifa_next }; |
| 150 |
IfAddrPtr { |
| 151 |
ptr: p.as_ptr(), |
| 152 |
_ref: PhantomData, |
| 153 |
} |
| 154 |
}) |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
fn if_name_mtu(idx: u32) -> Result<(String, Option<usize>)> { |
| 159 |
let mut name = [0; libc::IF_NAMESIZE]; |
| 160 |
// if_indextoname writes into the provided buffer. |
| 161 |
if unsafe { if_indextoname(idx, name.as_mut_ptr()).is_null() } { |
| 162 |
return Err(Error::last_os_error()); |
| 163 |
} |
| 164 |
// Convert to Rust string. |
| 165 |
let name = unsafe { |
| 166 |
CStr::from_ptr(name.as_ptr()) |
| 167 |
.to_str() |
| 168 |
.map_err(|err| Error::new(ErrorKind::Other, err))? |
| 169 |
}; |
| 170 |
let mtu = IfAddrs::new()? |
| 171 |
.iter() |
| 172 |
.find(|ifa| ifa.addr().sa_family == AF_LINK && ifa.name() == name) |
| 173 |
.and_then(|ifa| ifa.data()) |
| 174 |
.and_then(|ifa_data| usize::try_from(ifa_data.ifi_mtu).ok()); |
| 175 |
Ok((name.to_string(), mtu)) |
| 176 |
} |
| 177 |
|
| 178 |
#[repr(C)] |
| 179 |
union SockaddrStorage { |
| 180 |
sin: sockaddr_in, |
| 181 |
sin6: sockaddr_in6, |
| 182 |
} |
| 183 |
|
| 184 |
fn sockaddr_len(af: AddressFamily) -> Result<usize> { |
| 185 |
let sa_len = match af { |
| 186 |
AF_INET => std::mem::size_of::<sockaddr_in>(), |
| 187 |
AF_INET6 => std::mem::size_of::<sockaddr_in6>(), |
| 188 |
_ => { |
| 189 |
return Err(Error::new( |
| 190 |
ErrorKind::InvalidInput, |
| 191 |
format!("Unsupported address family {af:?}"), |
| 192 |
)) |
| 193 |
} |
| 194 |
}; |
| 195 |
Ok(aligned_by(sa_len, ALIGN)) |
| 196 |
} |
| 197 |
|
| 198 |
impl From<IpAddr> for SockaddrStorage { |
| 199 |
fn from(ip: IpAddr) -> Self { |
| 200 |
match ip { |
| 201 |
IpAddr::V4(ip) => SockaddrStorage { |
| 202 |
sin: sockaddr_in { |
| 203 |
#[cfg(not(target_os = "solaris"))] |
| 204 |
#[allow(clippy::cast_possible_truncation)] |
| 205 |
// `sockaddr_in` len is <= u8::MAX per `const_assert!` above. |
| 206 |
sin_len: std::mem::size_of::<sockaddr_in>() as u8, |
| 207 |
sin_family: AF_INET, |
| 208 |
sin_addr: in_addr { |
| 209 |
s_addr: u32::from_ne_bytes(ip.octets()), |
| 210 |
}, |
| 211 |
sin_port: 0, |
| 212 |
sin_zero: [0; 8], |
| 213 |
}, |
| 214 |
}, |
| 215 |
IpAddr::V6(ip) => SockaddrStorage { |
| 216 |
sin6: sockaddr_in6 { |
| 217 |
#[cfg(not(target_os = "solaris"))] |
| 218 |
#[allow(clippy::cast_possible_truncation)] |
| 219 |
// `sockaddr_in6` len is <= u8::MAX per `const_assert!` above. |
| 220 |
sin6_len: std::mem::size_of::<sockaddr_in6>() as u8, |
| 221 |
sin6_family: AF_INET6, |
| 222 |
sin6_addr: in6_addr { |
| 223 |
s6_addr: ip.octets(), |
| 224 |
}, |
| 225 |
sin6_port: 0, |
| 226 |
sin6_flowinfo: 0, |
| 227 |
sin6_scope_id: 0, |
| 228 |
#[cfg(target_os = "solaris")] |
| 229 |
__sin6_src_id: 0, |
| 230 |
}, |
| 231 |
}, |
| 232 |
} |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
#[repr(C)] |
| 237 |
struct RouteMessage { |
| 238 |
rtm: rt_msghdr, |
| 239 |
sa: SockaddrStorage, |
| 240 |
} |
| 241 |
|
| 242 |
impl RouteMessage { |
| 243 |
fn new(remote: IpAddr, seq: i32) -> Result<Self> { |
| 244 |
let sa = SockaddrStorage::from(remote); |
| 245 |
let sa_len = sockaddr_len(match remote { |
| 246 |
IpAddr::V4(_) => AF_INET, |
| 247 |
IpAddr::V6(_) => AF_INET6, |
| 248 |
})?; |
| 249 |
Ok(Self { |
| 250 |
rtm: rt_msghdr { |
| 251 |
#[allow(clippy::cast_possible_truncation)] |
| 252 |
// `rt_msghdr` len + `ALIGN` is <= u8::MAX per `const_assert!` above. |
| 253 |
rtm_msglen: (std::mem::size_of::<rt_msghdr>() + sa_len) as u16, |
| 254 |
rtm_version: RTM_VERSION, |
| 255 |
rtm_type: RTM_GET, |
| 256 |
rtm_seq: seq, |
| 257 |
rtm_addrs: RTM_ADDRS, |
| 258 |
..Default::default() |
| 259 |
}, |
| 260 |
sa, |
| 261 |
}) |
| 262 |
} |
| 263 |
|
| 264 |
const fn version(&self) -> u8 { |
| 265 |
self.rtm.rtm_version |
| 266 |
} |
| 267 |
|
| 268 |
const fn kind(&self) -> u8 { |
| 269 |
self.rtm.rtm_type |
| 270 |
} |
| 271 |
|
| 272 |
const fn len(&self) -> usize { |
| 273 |
self.rtm.rtm_msglen as usize |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
impl From<&RouteMessage> for &[u8] { |
| 278 |
fn from(value: &RouteMessage) -> Self { |
| 279 |
debug_assert!(value.len() >= std::mem::size_of::<Self>()); |
| 280 |
unsafe { slice::from_raw_parts(ptr::from_ref(value).cast(), value.len()) } |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
impl From<&[u8]> for rt_msghdr { |
| 285 |
fn from(value: &[u8]) -> Self { |
| 286 |
debug_assert!(value.len() >= std::mem::size_of::<Self>()); |
| 287 |
unsafe { ptr::read_unaligned(value.as_ptr().cast()) } |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
fn if_index_mtu(remote: IpAddr) -> Result<(u16, Option<usize>)> { |
| 292 |
// Open route socket. |
| 293 |
let mut fd = RouteSocket::new(PF_ROUTE, AF_UNSPEC)?; |
| 294 |
|
| 295 |
// Send route message. |
| 296 |
let query_seq = RouteSocket::new_seq(); |
| 297 |
let query = RouteMessage::new(remote, query_seq)?; |
| 298 |
let query_version = query.version(); |
| 299 |
let query_type = query.kind(); |
| 300 |
fd.write_all((&query).into())?; |
| 301 |
|
| 302 |
// Read route messages. |
| 303 |
let pid = unsafe { getpid() }; |
| 304 |
loop { |
| 305 |
let mut buf = vec![ |
| 306 |
0u8; |
| 307 |
std::mem::size_of::<rt_msghdr>() + |
| 308 |
// There will never be `RTAX_MAX` sockaddrs attached, but it's a safe upper bound. |
| 309 |
(RTAX_MAX as usize * std::mem::size_of::<sockaddr_storage>()) |
| 310 |
]; |
| 311 |
let len = fd.read(&mut buf[..])?; |
| 312 |
if len < std::mem::size_of::<rt_msghdr>() { |
| 313 |
return Err(default_err()); |
| 314 |
} |
| 315 |
let (reply, mut sa) = buf.split_at(std::mem::size_of::<rt_msghdr>()); |
| 316 |
let reply: rt_msghdr = reply.into(); |
| 317 |
if !(reply.rtm_version == query_version |
| 318 |
&& reply.rtm_pid == pid |
| 319 |
&& reply.rtm_seq == query_seq) |
| 320 |
{ |
| 321 |
continue; |
| 322 |
} |
| 323 |
if reply.rtm_type != query_type { |
| 324 |
return Err(default_err()); |
| 325 |
} |
| 326 |
|
| 327 |
// This is a reply to our query. |
| 328 |
// This is the reply we are looking for. |
| 329 |
// Some BSDs let us get the interface index and MTU directly from the reply. |
| 330 |
let mtu = (reply.rtm_rmx.rmx_mtu != 0) |
| 331 |
.then(|| usize::try_from(reply.rtm_rmx.rmx_mtu)) |
| 332 |
.transpose() |
| 333 |
.map_err(|e: TryFromIntError| unlikely_err(e.to_string()))?; |
| 334 |
if reply.rtm_index != 0 { |
| 335 |
// Some BSDs return the interface index directly. |
| 336 |
return Ok((reply.rtm_index, mtu)); |
| 337 |
} |
| 338 |
// For others, we need to extract it from the sockaddrs. |
| 339 |
for i in 0..RTAX_MAX { |
| 340 |
if (reply.rtm_addrs & (1 << i)) == 0 { |
| 341 |
continue; |
| 342 |
} |
| 343 |
let saddr = unsafe { ptr::read_unaligned(sa.as_ptr().cast::<sockaddr>()) }; |
| 344 |
if saddr.sa_family != AF_LINK { |
| 345 |
(_, sa) = sa.split_at(sockaddr_len(saddr.sa_family)?); |
| 346 |
continue; |
| 347 |
} |
| 348 |
let sdl = unsafe { ptr::read_unaligned(sa.as_ptr().cast::<sockaddr_dl>()) }; |
| 349 |
return Ok((sdl.sdl_index, mtu)); |
| 350 |
} |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
pub fn interface_and_mtu_impl(remote: IpAddr) -> Result<(String, usize)> { |
| 355 |
let (if_index, mtu1) = if_index_mtu(remote)?; |
| 356 |
let (if_name, mtu2) = if_name_mtu(if_index.into())?; |
| 357 |
Ok((if_name, mtu1.or(mtu2).ok_or_else(default_err)?)) |
| 358 |
} |