Skip to main content

ieee80211/
mac_addr.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// LINT.IfChange
6
7use crate::Bssid;
8use anyhow::{Error, format_err};
9use fidl_fuchsia_wlan_ieee80211 as fidl_ieee80211;
10use std::fmt;
11use std::str::FromStr;
12use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
13
14// Strictly speaking, the MAC address is not defined in 802.11, but it's defined
15// here for convenience.
16pub(crate) type MacAddrByteArray = [u8; fidl_ieee80211::MAC_ADDR_LEN as usize];
17
18pub const BROADCAST_ADDR: MacAddr = MacAddr([0xFF; 6]);
19pub const NULL_ADDR: MacAddr = MacAddr([0x00; fidl_ieee80211::MAC_ADDR_LEN as usize]);
20
21#[repr(transparent)]
22#[derive(
23    KnownLayout,
24    FromBytes,
25    IntoBytes,
26    Immutable,
27    Unaligned,
28    Clone,
29    Copy,
30    PartialEq,
31    Eq,
32    PartialOrd,
33    Ord,
34    Hash,
35)]
36pub struct MacAddr(pub(crate) MacAddrByteArray);
37
38impl MacAddr {
39    pub const fn len(&self) -> usize {
40        self.0.len()
41    }
42
43    /// A MAC address is a unicast address if the least significant bit of the first octet is 0.
44    /// See "individual/group bit" in
45    /// https://standards.ieee.org/content/dam/ieee-standards/standards/web/documents/tutorials/macgrp.pdf
46    pub fn is_unicast(&self) -> bool {
47        self.0[0] & 1 == 0
48    }
49
50    /// IEEE Std 802.3-2015, 3.2.3: The least significant bit of the first octet of a MAC address
51    /// denotes multicast.
52    pub fn is_multicast(&self) -> bool {
53        self.0[0] & 0x01 != 0
54    }
55
56    pub fn as_slice(&self) -> &[u8] {
57        &self.0
58    }
59}
60
61/// This trait aims to add some friction to convert a type into MacAddrBytes. The purpose being that
62/// function using the types implementing this trait, e.g. MacAddr, should prefer not accessing
63/// the MacAddrBytes directly when possible.
64pub trait MacAddrBytes {
65    fn to_array(&self) -> MacAddrByteArray;
66    fn as_array(&self) -> &MacAddrByteArray;
67}
68
69impl MacAddrBytes for MacAddr {
70    fn to_array(&self) -> MacAddrByteArray {
71        self.0
72    }
73
74    fn as_array(&self) -> &MacAddrByteArray {
75        &self.0
76    }
77}
78
79pub(crate) trait MacFmt {
80    fn to_mac_string(&self) -> String
81    where
82        Self: MacAddrBytes,
83    {
84        let mac = self.to_array();
85        format!(
86            "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
87            mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
88        )
89    }
90}
91
92pub trait OuiFmt {
93    fn to_oui_uppercase(&self, sep: &str) -> String
94    where
95        Self: MacAddrBytes,
96    {
97        let mac = self.to_array();
98        format!("{:02X}{}{:02X}{}{:02X}", mac[0], sep, mac[1], sep, mac[2])
99    }
100}
101
102impl MacFmt for MacAddr {}
103impl OuiFmt for MacAddr {}
104
105impl From<Bssid> for MacAddr {
106    fn from(bssid: Bssid) -> MacAddr {
107        MacAddr(bssid.0)
108    }
109}
110
111impl From<MacAddrByteArray> for MacAddr {
112    fn from(bytes: MacAddrByteArray) -> MacAddr {
113        MacAddr(bytes)
114    }
115}
116
117impl fmt::Display for MacAddr {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        write!(f, "{}", self.to_mac_string())
120    }
121}
122
123fn detect_delimiter(s: &str) -> Result<char, Error> {
124    let contains_semicolon = s.contains(':');
125    let contains_hyphen = s.contains('-');
126    match (contains_semicolon, contains_hyphen) {
127        (true, true) => return Err(format_err!("Either exclusively ':' or '-' must be used.")),
128        (false, false) => {
129            return Err(format_err!("No valid delimiter found. Only ':' and '-' are supported."));
130        }
131        (true, false) => Ok(':'),
132        (false, true) => Ok('-'),
133    }
134}
135
136impl FromStr for MacAddr {
137    type Err = Error;
138
139    fn from_str(s: &str) -> Result<Self, Self::Err> {
140        let mut bytes: MacAddrByteArray = [0; 6];
141        let mut index = 0;
142
143        let delimiter = detect_delimiter(s)?;
144        for octet in s.split(delimiter) {
145            if index == 6 {
146                return Err(format_err!("Too many octets"));
147            }
148            bytes[index] = u8::from_str_radix(octet, 16)?;
149            index += 1;
150        }
151
152        if index != 6 {
153            return Err(format_err!("Too few octets. Mixed delimiters are not supported."));
154        }
155        Ok(MacAddr(bytes))
156    }
157}
158
159impl fmt::Debug for MacAddr {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        write!(f, "MacAddr({})", self)
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn format_mac_addr_as_mac_string() {
171        let mac_addr: MacAddr = MacAddr::from([0x00, 0x12, 0x48, 0x9a, 0xbc, 0xdf]);
172        assert_eq!("00:12:48:9a:bc:df", &format!("{}", mac_addr));
173    }
174
175    #[test]
176    fn format_mac_addr_as_mac_debug_string() {
177        let mac_addr: MacAddr = MacAddr::from([0x00, 0x12, 0x48, 0x9a, 0xbc, 0xdf]);
178        assert_eq!("MacAddr(00:12:48:9a:bc:df)", &format!("{:?}", mac_addr));
179    }
180
181    #[test]
182    fn format_oui_uppercase() {
183        let mac: MacAddr = MacAddr::from([0x0a, 0xb1, 0xcd, 0x9a, 0xbc, 0xdf]);
184        assert_eq!(mac.to_oui_uppercase(""), "0AB1CD");
185        assert_eq!(mac.to_oui_uppercase(":"), "0A:B1:CD");
186        assert_eq!(mac.to_oui_uppercase("-"), "0A-B1-CD");
187    }
188
189    #[test]
190    fn unicast_addresses() {
191        assert!(MacAddr::from([0; 6]).is_unicast());
192        assert!(MacAddr::from([0xfe; 6]).is_unicast());
193    }
194
195    #[test]
196    fn non_unicast_addresses() {
197        assert!(!MacAddr::from([0xff; 6]).is_unicast()); // broadcast
198        assert!(!MacAddr::from([0x33, 0x33, 0, 0, 0, 0]).is_unicast()); // IPv6 multicast
199        assert!(!MacAddr::from([0x01, 0x00, 0x53, 0, 0, 0]).is_unicast()); // IPv4 multicast
200    }
201
202    #[test]
203    fn is_multicast_valid_addr() {
204        assert!(MacAddr::from([33, 33, 33, 33, 33, 33]).is_multicast());
205    }
206
207    #[test]
208    fn is_multicast_not_valid_addr() {
209        assert!(!MacAddr::from([34, 33, 33, 33, 33, 33]).is_multicast());
210    }
211
212    #[test]
213    fn successfully_parse_mac_str() {
214        assert_eq!(
215            "01:23:cd:11:11:11".parse::<MacAddr>().unwrap(),
216            MacAddr::from([0x01, 0x23, 0xcd, 0x11, 0x11, 0x11])
217        );
218        assert_eq!(
219            "01-23-cd-11-11-11".parse::<MacAddr>().unwrap(),
220            MacAddr::from([0x01, 0x23, 0xcd, 0x11, 0x11, 0x11])
221        );
222        assert_eq!(
223            "1-23-cd-11-11-11".parse::<MacAddr>().unwrap(),
224            MacAddr::from([0x01, 0x23, 0xcd, 0x11, 0x11, 0x11])
225        );
226    }
227
228    #[test]
229    fn mac_addr_from_str() {
230        assert_eq!(
231            MacAddr::from_str("01:02:03:ab:cd:ef").unwrap(),
232            MacAddr([0x01, 0x02, 0x03, 0xab, 0xcd, 0xef])
233        );
234        assert_eq!(
235            MacAddr::from_str("01-02-03-ab-cd-ef").unwrap(),
236            MacAddr([0x01, 0x02, 0x03, 0xab, 0xcd, 0xef])
237        );
238    }
239
240    #[test]
241    fn fail_to_parse_mac_str() {
242        assert!("11:11:23::11:11:11".parse::<MacAddr>().is_err());
243        assert!("11:11:23:11:11:11:11".parse::<MacAddr>().is_err());
244        assert!(":11:23:11:11:11:11".parse::<MacAddr>().is_err());
245        assert!("11:23:11:11:11:11:11".parse::<MacAddr>().is_err());
246        assert!("11:23:11:11:11:11:".parse::<MacAddr>().is_err());
247        assert!("111:23:11:11:11:11".parse::<MacAddr>().is_err());
248        assert!("11:23-11:11-11:11".parse::<MacAddr>().is_err());
249        assert!("11-23:11-11:11-11".parse::<MacAddr>().is_err());
250        assert!("-11-23-11-11-11-11".parse::<MacAddr>().is_err());
251        assert!("11-23-11-11-11-11-".parse::<MacAddr>().is_err());
252    }
253}
254
255// LINT.ThenChange(//src/connectivity/wlan/drivers/lib/macaddr/include/wlan/drivers/macaddr.h)