Skip to main content

network/device/wifi/
types.rs

1//! Fixed-layout Wi-Fi control payloads. Byte-backed state values deliberately
2//! accept every bit pattern: validate at the driver boundary before use.
3use core::fmt;
4use file_system::{IoErrorKind, Result};
5
6macro_rules! byte_value {
7    ($name:ident { $($constant:ident = $value:expr),* $(,)? }) => {
8        // A transparent wrapper over a `u8` accepts every bit pattern, so it
9        // is plain data and can be a control payload as-is.
10        file_system::plain_data! {
11            #[repr(transparent)]
12            #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
13            pub struct $name(pub u8);
14        }
15        impl $name { $(pub const $constant: Self = Self($value);)* }
16    };
17}
18byte_value!(WifiAuthentication { OPEN = 0, WPA2_PERSONAL = 1, WPA3_PERSONAL = 2, WPA2_WPA3_PERSONAL = 3, UNSUPPORTED = 255 });
19byte_value!(WifiRadioState { OFF = 0, ON = 1 });
20byte_value!(WifiScanPhase { IDLE = 0, SCANNING = 1, COMPLETED = 2, FAILED = 3 });
21byte_value!(WifiConnectionState { DISCONNECTED = 0, CONNECTING = 1, CONNECTED = 2, DISCONNECTING = 3 });
22byte_value!(WifiConnectionErrorKind { NONE = 0, AUTHENTICATION = 1, ACCESS_POINT_NOT_FOUND = 2, ASSOCIATION = 3, TIMEOUT = 4, UNSUPPORTED_CONFIGURATION = 5, RADIO = 6, DRIVER = 7 });
23
24file_system::plain_data! {
25    #[repr(C)]
26    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
27    pub struct WifiSsid {
28        pub bytes: [u8; 32],
29        pub length: u8,
30    }
31}
32impl WifiSsid {
33    pub fn new(bytes: &[u8]) -> Result<Self> {
34        if bytes.is_empty() || bytes.len() > 32 {
35            return Err(IoErrorKind::InvalidArgument);
36        }
37        let mut ssid = Self::default();
38        ssid.bytes[..bytes.len()].copy_from_slice(bytes);
39        ssid.length = bytes.len() as u8;
40        Ok(ssid)
41    }
42    pub fn as_bytes(&self) -> Result<&[u8]> {
43        if !(1..=32).contains(&self.length) {
44            return Err(IoErrorKind::InvalidArgument);
45        }
46        Ok(&self.bytes[..self.length as usize])
47    }
48}
49
50file_system::plain_data! {
51    #[repr(C)]
52    /// Never printed or returned by status commands. Clear caller-owned copies too.
53    #[derive(Clone, Eq, PartialEq)]
54    pub struct WifiPassword {
55        pub bytes: [u8; 64],
56        pub length: u8,
57    }
58}
59impl Default for WifiPassword {
60    fn default() -> Self {
61        Self {
62            bytes: [0; 64],
63            length: 0,
64        }
65    }
66}
67impl fmt::Debug for WifiPassword {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.write_str("<redacted>")
70    }
71}
72impl WifiPassword {
73    pub fn new(bytes: &[u8]) -> Result<Self> {
74        if bytes.len() > 64 {
75            return Err(IoErrorKind::InvalidArgument);
76        }
77        let mut result = Self::default();
78        result.bytes[..bytes.len()].copy_from_slice(bytes);
79        result.length = bytes.len() as u8;
80        Ok(result)
81    }
82    pub fn as_bytes(&self) -> Result<&[u8]> {
83        self.bytes
84            .get(..self.length as usize)
85            .ok_or(IoErrorKind::InvalidArgument)
86    }
87    pub fn clear(&mut self) {
88        // Volatile stores prevent dead-store elimination of this owned buffer.
89        for byte in &mut self.bytes {
90            unsafe {
91                core::ptr::write_volatile(byte, 0);
92            }
93        }
94        self.length = 0;
95    }
96}
97impl Drop for WifiPassword {
98    fn drop(&mut self) {
99        self.clear();
100    }
101}
102
103file_system::plain_data! {
104    #[repr(C)]
105    #[derive(Clone, Debug, Default, Eq, PartialEq)]
106    pub struct WifiClientConfiguration {
107        pub ssid: WifiSsid,
108        pub credential: WifiPassword,
109        pub authentication: WifiAuthentication,
110        pub bssid: [u8; 6],
111        /// Zero means unspecified.
112        pub channel: u8,
113        /// 0 or 1. Kept as a byte for raw control payload validity.
114        pub use_bssid: u8,
115    }
116}
117impl WifiClientConfiguration {
118    pub fn new(ssid: &[u8], authentication: WifiAuthentication, secret: &[u8]) -> Result<Self> {
119        let result = Self {
120            ssid: WifiSsid::new(ssid)?,
121            credential: WifiPassword::new(secret)?,
122            authentication,
123            ..Self::default()
124        };
125        result.validate()?;
126        Ok(result)
127    }
128    pub fn validate(&self) -> Result<()> {
129        self.ssid.as_bytes()?;
130        if self.use_bssid > 1 || self.channel > 196 {
131            return Err(IoErrorKind::InvalidArgument);
132        }
133        let secret = self.credential.as_bytes()?;
134        let valid = match self.authentication {
135            WifiAuthentication::OPEN => secret.is_empty(),
136            WifiAuthentication::WPA2_PERSONAL | WifiAuthentication::WPA2_WPA3_PERSONAL => {
137                ((8..=63).contains(&secret.len()) && secret.iter().all(|b| (32..=126).contains(b)))
138                    || (secret.len() == 64 && secret.iter().all(u8::is_ascii_hexdigit))
139            }
140            WifiAuthentication::WPA3_PERSONAL => {
141                (1..=63).contains(&secret.len())
142                    && core::str::from_utf8(secret).is_ok()
143                    && !secret.contains(&0)
144            }
145            _ => return Err(IoErrorKind::Unsupported),
146        };
147        if valid {
148            Ok(())
149        } else {
150            Err(IoErrorKind::InvalidArgument)
151        }
152    }
153}
154
155file_system::plain_data! {
156    #[repr(C)]
157    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
158    pub struct WifiAccessPoint {
159        pub ssid: WifiSsid,
160        /// All zero when unavailable.
161        pub bssid: [u8; 6],
162        /// Zero when unavailable.
163        pub channel: u8,
164        /// dBm; i8::MIN means unavailable.
165        pub rssi: i8,
166        pub authentication: WifiAuthentication,
167    }
168}
169/// Connection metadata never contains credentials.
170pub type WifiConnectionInfo = WifiAccessPoint;
171
172file_system::plain_data! {
173    #[repr(C)]
174    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
175    pub struct WifiCapabilities {
176        pub station: u8,
177        pub access_point: u8,
178        /// Bit n advertises WifiAuthentication(n); extended methods are not advertised.
179        pub authentication_mask: u8,
180        pub maximum_scan_results: u8,
181    }
182}
183impl WifiCapabilities {
184    pub fn supports(&self, authentication: WifiAuthentication) -> bool {
185        authentication.0 < 8 && self.authentication_mask & (1 << authentication.0) != 0
186    }
187}
188file_system::plain_data! {
189    #[repr(C)]
190    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
191    pub struct WifiScanConfiguration {
192        /// Zero means all channels.
193        pub channel: u8,
194        pub passive: u8,
195        pub result_limit: u16,
196    }
197}
198impl Default for WifiScanConfiguration {
199    fn default() -> Self {
200        Self {
201            channel: 0,
202            passive: 0,
203            result_limit: 16,
204        }
205    }
206}
207impl WifiScanConfiguration {
208    pub fn validate(&self) -> Result<()> {
209        if self.channel > 196 || self.passive > 1 || self.result_limit == 0 {
210            Err(IoErrorKind::InvalidArgument)
211        } else {
212            Ok(())
213        }
214    }
215}
216file_system::plain_data! {
217    #[repr(C)]
218    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
219    pub struct WifiScanState {
220        /// Generation of the latest completed scan; unchanged while scanning.
221        pub generation: u32,
222        pub phase: WifiScanPhase,
223        pub reserved: [u8; 3],
224    }
225}
226file_system::plain_data! {
227    #[repr(C)]
228    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
229    pub struct WifiScanResultCount {
230        pub generation: u32,
231        pub count: u16,
232        pub reserved: [u8; 2],
233    }
234}
235file_system::plain_data! {
236    #[repr(C)]
237    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
238    pub struct WifiScanResultRequest {
239        pub generation: u32,
240        pub index: u16,
241        pub reserved: [u8; 2],
242    }
243}