Debian Codegraph @

third_party/rust/mtu/src/lib.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 //! A crate to return the name and maximum transmission unit (MTU) of the local network interface
8 //! towards a given destination `SocketAddr`, optionally from a given local `SocketAddr`.
9 //!
10 //! # Usage
11 //!
12 //! This crate exports a single function `interface_and_mtu` that returns the name and
13 //! [maximum transmission unit (MTU)](https://en.wikipedia.org/wiki/Maximum_transmission_unit)
14 //! of the outgoing network interface towards a remote destination identified by an `IpAddr`.
15 //!
16 //! # Example
17 //! ```
18 //! # use std::net::{IpAddr, Ipv4Addr};
19 //! let destination = IpAddr::V4(Ipv4Addr::LOCALHOST);
20 //! let (name, mtu): (String, usize) = mtu::interface_and_mtu(destination).unwrap();
21 //! println!("MTU towards {destination} is {mtu} on {name}");
22 //! ```
23 //!
24 //! # Supported Platforms
25 //!
26 //! * Linux
27 //! * macOS
28 //! * Windows
29 //! * FreeBSD
30 //! * NetBSD
31 //! * OpenBSD
32 //! * Solaris
33 //!
34 //! # Notes
35 //!
36 //! The returned MTU may exceed the maximum IP packet size of 65,535 bytes on some platforms for
37 //! some remote destinations. (For example, loopback destinations on Windows.)
38 //!
39 //! The returned interface name is obtained from the operating system.
40 //!
41 //! # Contributing
42 //!
43 //! We're happy to receive PRs that improve this crate. Please take a look at our [community
44 //! guidelines](CODE_OF_CONDUCT.md) beforehand.
45
46 use std::{
47 io::{Error, ErrorKind, Result},
48 net::IpAddr,
49 };
50
51 #[cfg(not(target_os = "windows"))]
52 macro_rules! asserted_const_with_type {
53 ($name:ident, $t1:ty, $e:expr, $t2:ty) => {
54 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] // Guarded by the following `const_assert_eq!`.
55 const $name: $t1 = $e as $t1;
56 const_assert_eq!($name as $t2, $e);
57 };
58 }
59
60 #[cfg(any(target_os = "macos", bsd))]
61 mod bsd;
62
63 #[cfg(any(target_os = "linux", target_os = "android"))]
64 mod linux;
65
66 #[cfg(target_os = "windows")]
67 mod windows;
68
69 #[cfg(not(target_os = "windows"))]
70 mod routesocket;
71
72 #[cfg(any(target_os = "macos", bsd))]
73 use bsd::interface_and_mtu_impl;
74 #[cfg(any(target_os = "linux", target_os = "android"))]
75 use linux::interface_and_mtu_impl;
76 #[cfg(target_os = "windows")]
77 use windows::interface_and_mtu_impl;
78
79 /// Prepare a default error.
80 fn default_err() -> Error {
81 Error::new(ErrorKind::NotFound, "Local interface MTU not found")
82 }
83
84 /// Prepare an error for cases that "should never happen".
85 #[cfg(not(target_os = "windows"))]
86 fn unlikely_err(msg: String) -> Error {
87 debug_assert!(false, "{msg}");
88 Error::new(ErrorKind::Other, msg)
89 }
90
91 /// Align `size` to the next multiple of `align` (which needs to be a power of two).
92 #[cfg(not(target_os = "windows"))]
93 const fn aligned_by(size: usize, align: usize) -> usize {
94 if size == 0 {
95 align
96 } else {
97 1 + ((size - 1) | (align - 1))
98 }
99 }
100
101 // Platforms currently not supported.
102 //
103 // See <https://github.com/mozilla/mtu/issues/82>.
104 #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "visionos"))]
105 pub fn interface_and_mtu_impl(remote: IpAddr) -> Result<(String, usize)> {
106 return Err(default_err());
107 }
108
109 /// Return the name and maximum transmission unit (MTU) of the outgoing network interface towards a
110 /// remote destination identified by an [`IpAddr`],
111 ///
112 /// The returned MTU may exceed the maximum IP packet size of 65,535 bytes on some platforms for
113 /// some remote destinations. (For example, loopback destinations on Windows.)
114 ///
115 /// The returned interface name is obtained from the operating system.
116 ///
117 /// # Errors
118 ///
119 /// This function returns an error if the local interface MTU cannot be determined.
120 pub fn interface_and_mtu(remote: IpAddr) -> Result<(String, usize)> {
121 interface_and_mtu_impl(remote)
122 }
123
124 #[cfg(test)]
125 mod test {
126 use std::{
127 env,
128 net::{IpAddr, Ipv4Addr, Ipv6Addr},
129 };
130
131 use crate::interface_and_mtu;
132
133 #[derive(Debug)]
134 struct NameMtu<'a>(Option<&'a str>, usize);
135
136 impl PartialEq<NameMtu<'_>> for (String, usize) {
137 fn eq(&self, other: &NameMtu<'_>) -> bool {
138 other.0.map_or(true, |name| name == self.0) && other.1 == self.1
139 }
140 }
141
142 #[cfg(any(target_os = "macos", target_os = "freebsd",))]
143 const LOOPBACK: &[NameMtu] = &[NameMtu(Some("lo0"), 16_384), NameMtu(Some("lo0"), 16_384)];
144 #[cfg(any(target_os = "linux", target_os = "android"))]
145 const LOOPBACK: &[NameMtu] = &[NameMtu(Some("lo"), 65_536), NameMtu(Some("lo"), 65_536)];
146 #[cfg(target_os = "windows")]
147 const LOOPBACK: &[NameMtu] = &[
148 NameMtu(Some("loopback_0"), 4_294_967_295),
149 NameMtu(Some("loopback_0"), 4_294_967_295),
150 ];
151 #[cfg(target_os = "openbsd")]
152 const LOOPBACK: &[NameMtu] = &[NameMtu(Some("lo0"), 32_768), NameMtu(Some("lo0"), 32_768)];
153 #[cfg(target_os = "netbsd")]
154 const LOOPBACK: &[NameMtu] = &[NameMtu(Some("lo0"), 33_624), NameMtu(Some("lo0"), 33_624)];
155 #[cfg(target_os = "solaris")]
156 // Note: Different loopback MTUs for IPv4 and IPv6?!
157 const LOOPBACK: &[NameMtu] = &[NameMtu(Some("lo0"), 8_232), NameMtu(Some("lo0"), 8_252)];
158
159 // Non-loopback interface names are unpredictable, so we only check the MTU.
160 const INET: NameMtu = NameMtu(None, 1_500);
161
162 #[test]
163 fn loopback_v4() {
164 assert_eq!(
165 interface_and_mtu(IpAddr::V4(Ipv4Addr::LOCALHOST)).unwrap(),
166 LOOPBACK[0]
167 );
168 }
169
170 #[test]
171 fn loopback_v6() {
172 assert_eq!(
173 interface_and_mtu(IpAddr::V6(Ipv6Addr::LOCALHOST)).unwrap(),
174 LOOPBACK[1]
175 );
176 }
177
178 #[test]
179 fn inet_v4() {
180 assert_eq!(
181 interface_and_mtu(IpAddr::V4(Ipv4Addr::new(
182 104, 16, 132, 229 // cloudflare.com
183 )))
184 .unwrap(),
185 INET
186 );
187 }
188
189 #[test]
190 fn inet_v6() {
191 match interface_and_mtu(IpAddr::V6(Ipv6Addr::new(
192 0x2606, 0x4700, 0, 0, 0, 0, 0x6810, 0x84e5, // cloudflare.com
193 ))) {
194 Ok(res) => assert_eq!(res, INET),
195 // The GitHub CI environment does not have IPv6 connectivity.
196 Err(_) => assert!(env::var("GITHUB_ACTIONS").is_ok()),
197 }
198 }
199 }