Skip to main content

zond_engine/model/
mac.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # Hardware addresses
10//!
11//! [`MacAddr`] is the 48-bit address a device answers under on its segment, and
12//! [`vendor`] is who made the hardware, looked up from the address's
13//! Organizationally Unique Identifier.
14//!
15//! The type is this crate's own, so the packet library stays out of public signatures.
16//! A MAC crosses the whole engine (an ARP reply produces one, a host record keeps them,
17//! a report prints them), and the frame builders and readers in
18//! [`protocols`](crate::protocols) and [`transport`](crate::transport) use it too.
19
20use mac_oui::Oui;
21use std::fmt;
22use std::str::FromStr;
23use std::sync::OnceLock;
24
25/// A 48-bit hardware address.
26///
27/// Ordered and hashable, so a host's addresses can be kept in a sorted map and
28/// rendered in the same order twice.
29#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
30pub struct MacAddr([u8; 6]);
31
32impl MacAddr {
33    /// The address every station on a segment receives, `ff:ff:ff:ff:ff:ff`.
34    pub const BROADCAST: Self = Self([0xff; 6]);
35
36    /// The all-zero address, which names no station: what an ARP request carries as
37    /// the target hardware address it asks for, and what a reader takes as "not
38    /// stated".
39    pub const ZERO: Self = Self([0; 6]);
40
41    /// Creates a `MacAddr` from six octets, most significant first.
42    pub const fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> Self {
43        Self([a, b, c, d, e, f])
44    }
45
46    /// The six octets, most significant first.
47    pub const fn octets(self) -> [u8; 6] {
48        self.0
49    }
50
51    /// Whether this address was assigned locally, not allocated to a manufacturer,
52    /// as the second-least-significant bit of the first octet marks.
53    ///
54    /// There is no OUI to look up for one, so [`vendor`] returns `None`. A device
55    /// randomizing its address produces them, so one host may answer under a series
56    /// of unrelated addresses.
57    pub const fn is_locally_administered(self) -> bool {
58        self.0[0] & 0b0000_0010 != 0
59    }
60
61    /// Whether this is a group address, as the least significant bit of the first
62    /// octet marks.
63    pub const fn is_multicast(self) -> bool {
64        self.0[0] & 0b0000_0001 != 0
65    }
66
67    /// Whether this is [`BROADCAST`](Self::BROADCAST).
68    pub const fn is_broadcast(self) -> bool {
69        matches!(self.0, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff])
70    }
71
72    /// Whether this is [`ZERO`](Self::ZERO).
73    pub const fn is_zero(self) -> bool {
74        matches!(self.0, [0, 0, 0, 0, 0, 0])
75    }
76}
77
78impl From<[u8; 6]> for MacAddr {
79    fn from(octets: [u8; 6]) -> Self {
80        Self(octets)
81    }
82}
83
84impl From<MacAddr> for [u8; 6] {
85    fn from(mac: MacAddr) -> Self {
86        mac.0
87    }
88}
89
90/// Why a string could not be read as a hardware address.
91#[non_exhaustive]
92#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
93#[error("'{input}' is not a MAC address: expected six hex octets separated by ':' or '-'")]
94pub struct MacAddrParseError {
95    /// What the caller wrote.
96    pub input: String,
97}
98
99impl FromStr for MacAddr {
100    type Err = MacAddrParseError;
101
102    /// Reads `00:1a:2b:3c:4d:5e`, in either case, and the same address written
103    /// with `-` between the octets.
104    ///
105    /// The colon form is what Unix tooling prints and [`fmt::Display`] writes; the
106    /// hyphen form is what Windows and most printed labels use.
107    fn from_str(s: &str) -> Result<Self, Self::Err> {
108        let fail = || MacAddrParseError {
109            input: s.to_string(),
110        };
111
112        let mut octets = [0u8; 6];
113        let mut parts = s.trim().split([':', '-']);
114
115        for octet in &mut octets {
116            let part = parts.next().ok_or_else(fail)?;
117            if part.len() != 2 {
118                return Err(fail());
119            }
120            *octet = u8::from_str_radix(part, 16).map_err(|_| fail())?;
121        }
122
123        if parts.next().is_some() {
124            return Err(fail());
125        }
126
127        Ok(Self(octets))
128    }
129}
130
131impl fmt::Debug for MacAddr {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        write!(
134            f,
135            "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
136            self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
137        )
138    }
139}
140
141impl fmt::Display for MacAddr {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        write!(
144            f,
145            "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
146            self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
147        )
148    }
149}
150
151/// The manufacturer database, loaded once. `None` records a load that failed; see
152/// [`oui_db`].
153static OUI_DB: OnceLock<Option<Oui>> = OnceLock::new();
154
155/// The OUI database, loaded once, or `None` if it could not be loaded at all.
156///
157/// A failure is remembered and not raised: the database is compiled in, so a load that
158/// fails once fails every time, and a scan without manufacturer names is still a scan.
159fn oui_db() -> Option<&'static Oui> {
160    OUI_DB.get_or_init(|| Oui::default().ok()).as_ref()
161}
162
163/// The manufacturer `mac`'s OUI is allocated to, if the database recognises it.
164///
165/// `None` for a [locally administered](MacAddr::is_locally_administered)
166/// address, which is allocated to nobody, and for an address whose OUI is not
167/// in the database.
168///
169/// The first case is read from the address bit, independent of the database, which
170/// also skips a lookup for every rotation of a randomized address.
171pub fn vendor(mac: &MacAddr) -> Option<String> {
172    if mac.is_locally_administered() {
173        return None;
174    }
175    let entry = oui_db()?.lookup_by_mac(&mac.to_string()).ok()??;
176    Some(entry.company_name.clone())
177}
178
179/// Loads the manufacturer database, where nothing has yet, on the blocking
180/// pool, for a pass that reads link-layer addresses to call before its first
181/// frame is read.
182///
183/// Otherwise the database loads the first time a host's address is recorded, inside
184/// the task that read the frame. Parsing tens of thousands of entries takes some
185/// hundreds of milliseconds in a debug build, and a runtime worker busy with it delays
186/// every probe answer it would have read, skewing their timings.
187pub(crate) async fn load_vendors() {
188    // A failed load is remembered by `oui_db`, so the result can be ignored.
189    let _ = tokio::task::spawn_blocking(|| {
190        oui_db();
191    })
192    .await;
193}
194
195// ╔════════════════════════════════════════════╗
196// ║ ████████╗███████╗███████╗████████╗███████╗ ║
197// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
198// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
199// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
200// ║    ██║   ███████╗███████║   ██║   ███████║ ║
201// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
202// ╚════════════════════════════════════════════╝
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    /// Lowercase hex, colon-separated, and the same from both formatters.
209    ///
210    /// [`vendor`] queries the OUI database with this exact string, and readers paste
211    /// it into their own tooling. `Debug` matches `Display` so a logged address matches
212    /// the report.
213    #[test]
214    fn an_address_renders_as_lowercase_colon_separated_hex() {
215        let mac = MacAddr::new(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E);
216        assert_eq!(mac.to_string(), "00:1a:2b:3c:4d:5e");
217        assert_eq!(format!("{mac:?}"), "00:1a:2b:3c:4d:5e");
218    }
219
220    /// The conversions to and from raw octets keep their order; frame parsing relies
221    /// on them.
222    #[test]
223    fn octets_survive_the_conversions_frame_parsing_uses() {
224        let octets = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
225        let mac = MacAddr::from(octets);
226
227        assert_eq!(mac.octets(), octets);
228        assert_eq!(<[u8; 6]>::from(mac), octets);
229    }
230
231    /// The form `Display` writes is the form `FromStr` reads.
232    #[test]
233    fn an_address_round_trips_through_its_own_rendering() {
234        let mac = MacAddr::new(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E);
235        assert_eq!(mac.to_string().parse(), Ok(mac));
236    }
237
238    /// Both separators and either case parse.
239    #[test]
240    fn both_separators_and_either_case_are_accepted() {
241        let mac = MacAddr::new(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E);
242        assert_eq!("00-1A-2B-3C-4D-5E".parse(), Ok(mac));
243        assert_eq!("00:1a:2b:3c:4d:5e".parse(), Ok(mac));
244    }
245
246    /// Each of these is refused outright: an address that silently loses an octet
247    /// identifies the wrong device.
248    #[test]
249    fn malformed_addresses_are_refused() {
250        for input in [
251            "",
252            "00:1a:2b:3c:4d",
253            "00:1a:2b:3c:4d:5e:6f",
254            "zz:1a:2b:3c:4d:5e",
255            "001a2b3c4d5e",
256        ] {
257            assert!(
258                input.parse::<MacAddr>().is_err(),
259                "'{input}' parsed as an address"
260            );
261        }
262    }
263
264    /// The locally administered and multicast bits are read from the first octet.
265    #[test]
266    fn the_locally_administered_and_multicast_bits_are_read() {
267        assert!(MacAddr::new(0x02, 0, 0, 0, 0, 0).is_locally_administered());
268        assert!(!MacAddr::new(0x00, 0x0C, 0x29, 0, 0, 0).is_locally_administered());
269        assert!(MacAddr::new(0x01, 0, 0x5e, 0, 0, 0).is_multicast());
270        assert!(!MacAddr::new(0x00, 0x0C, 0x29, 0, 0, 0).is_multicast());
271    }
272
273    /// The database is queried with the address's [`fmt::Display`] form, so a change
274    /// to how a MAC renders would stop every vendor resolving.
275    ///
276    /// Asserts only that some vendor resolves, so a data update to the third-party
277    /// database cannot break it.
278    #[test]
279    fn a_registered_oui_resolves_to_a_vendor() {
280        let vmware = MacAddr::new(0x00, 0x0C, 0x29, 0xAB, 0xCD, 0xEF);
281        assert!(vendor(&vmware).is_some());
282    }
283
284    /// A locally administered address has no OUI to resolve. The second address is a
285    /// registered OUI with the local bit set, so this tests the bit check, not the
286    /// database contents.
287    #[test]
288    fn a_locally_administered_address_has_no_vendor() {
289        let local = MacAddr::new(0x02, 0x00, 0x00, 0x00, 0x00, 0x00);
290        assert_eq!(vendor(&local), None);
291
292        let registered_but_local = MacAddr::new(0x02, 0x0C, 0x29, 0xAB, 0xCD, 0xEF);
293        assert!(registered_but_local.is_locally_administered());
294        assert_eq!(vendor(&registered_but_local), None);
295    }
296}