Debian Codegraph @

third_party/rust/mtu/src/windows.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, Result},
10 net::IpAddr,
11 ptr, slice,
12 };
13
14 use windows::Win32::{
15 Foundation::NO_ERROR,
16 NetworkManagement::{
17 IpHelper::{
18 if_indextoname, FreeMibTable, GetBestInterfaceEx, GetIpInterfaceTable,
19 MIB_IPINTERFACE_ROW, MIB_IPINTERFACE_TABLE,
20 },
21 Ndis::IF_MAX_STRING_SIZE,
22 },
23 Networking::WinSock::{
24 AF_INET, AF_INET6, IN6_ADDR, IN6_ADDR_0, IN_ADDR, IN_ADDR_0, SOCKADDR, SOCKADDR_IN,
25 SOCKADDR_IN6, SOCKADDR_INET,
26 },
27 };
28
29 use crate::default_err;
30
31 struct MibTablePtr(*mut MIB_IPINTERFACE_TABLE);
32
33 impl MibTablePtr {
34 fn mut_ptr_ptr(&mut self) -> *mut *mut MIB_IPINTERFACE_TABLE {
35 ptr::from_mut(&mut self.0)
36 }
37 }
38
39 impl Default for MibTablePtr {
40 fn default() -> Self {
41 Self(ptr::null_mut())
42 }
43 }
44
45 impl Drop for MibTablePtr {
46 fn drop(&mut self) {
47 if !self.0.is_null() {
48 // Free the memory allocated by GetIpInterfaceTable.
49 unsafe {
50 FreeMibTable(self.0.cast());
51 }
52 }
53 }
54 }
55
56 pub fn interface_and_mtu_impl(remote: IpAddr) -> Result<(String, usize)> {
57 // Convert remote to Windows SOCKADDR_INET format. The SOCKADDR_INET union contains an IPv4 or
58 // an IPv6 address.
59 //
60 // See https://learn.microsoft.com/en-us/windows/win32/api/ws2ipdef/ns-ws2ipdef-sockaddr_inet
61 let dst = match remote {
62 IpAddr::V4(ip) => {
63 // Initialize the `SOCKADDR_IN` variant of `SOCKADDR_INET` based on `ip`.
64 SOCKADDR_INET {
65 Ipv4: SOCKADDR_IN {
66 sin_family: AF_INET,
67 sin_addr: IN_ADDR {
68 S_un: IN_ADDR_0 {
69 S_addr: u32::to_be(ip.into()),
70 },
71 },
72 ..Default::default()
73 },
74 }
75 }
76 IpAddr::V6(ip) => {
77 // Initialize the `SOCKADDR_IN6` variant of `SOCKADDR_INET` based on `ip`.
78 SOCKADDR_INET {
79 Ipv6: SOCKADDR_IN6 {
80 sin6_family: AF_INET6,
81 sin6_addr: IN6_ADDR {
82 u: IN6_ADDR_0 { Byte: ip.octets() },
83 },
84 ..Default::default()
85 },
86 }
87 }
88 };
89
90 // Get the interface index of the best outbound interface towards `dst`.
91 let mut idx = 0;
92 let res = unsafe {
93 // We're now casting `&dst` to a `SOCKADDR` pointer. This is OK based on
94 // https://learn.microsoft.com/en-us/windows/win32/winsock/sockaddr-2.
95 // With that, we call `GetBestInterfaceEx` to get the interface index into `idx`.
96 // See https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getbestinterfaceex
97 GetBestInterfaceEx(
98 ptr::from_ref(&dst).cast::<SOCKADDR>(),
99 ptr::from_mut(&mut idx),
100 )
101 };
102 if res != 0 {
103 return Err(Error::last_os_error());
104 }
105
106 // Get a list of all interfaces with associated metadata.
107 let mut if_table = MibTablePtr::default();
108 // GetIpInterfaceTable allocates memory, which MibTablePtr::drop will free.
109 let family = if remote.is_ipv4() { AF_INET } else { AF_INET6 };
110 if unsafe { GetIpInterfaceTable(family, if_table.mut_ptr_ptr()) } != NO_ERROR {
111 return Err(Error::last_os_error());
112 }
113 // Make a slice
114 let ifaces = unsafe {
115 slice::from_raw_parts::<MIB_IPINTERFACE_ROW>(
116 &(*if_table.0).Table[0],
117 (*if_table.0).NumEntries as usize,
118 )
119 };
120
121 // Find the local interface matching `idx`.
122 for iface in ifaces {
123 if iface.InterfaceIndex == idx {
124 // Get the MTU.
125 let mtu: usize = iface.NlMtu.try_into().map_err(|_| default_err())?;
126 // Get the interface name.
127 let mut interfacename = [0u8; IF_MAX_STRING_SIZE as usize];
128 // if_indextoname writes into the provided buffer.
129 if unsafe { if_indextoname(iface.InterfaceIndex, &mut interfacename).is_null() } {
130 return Err(default_err());
131 }
132 // Convert the interface name to a Rust string.
133 let name = CStr::from_bytes_until_nul(interfacename.as_ref())
134 .map_err(|_| default_err())?
135 .to_str()
136 .map_err(|err| Error::new(ErrorKind::Other, err))?
137 .to_string();
138 // We found our interface information.
139 return Ok((name, mtu));
140 }
141 }
142 Err(default_err())
143 }