wlan_common/ie/
parse.rs

1// Copyright 2021 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
5use super::*;
6use crate::buffer_reader::BufferReader;
7use crate::error::{FrameParseError, FrameParseResult};
8use crate::organization::Oui;
9use fidl_fuchsia_wlan_ieee80211 as fidl_ieee80211;
10use paste::paste;
11use zerocopy::{Ref, SplitByteSlice};
12
13macro_rules! validate {
14    ( $condition:expr, $message:expr ) => {
15        if !$condition {
16            return Err($crate::error::FrameParseError(format!($message)));
17        }
18    };
19}
20
21macro_rules! simple_parse_func {
22    ( $ie_snake_case:ident ) => {
23        paste! {
24            pub fn [<parse_ $ie_snake_case>]<B: SplitByteSlice>(
25                raw_body: B,
26            ) -> FrameParseResult<Ref<B, [<$ie_snake_case:camel>]>> {
27                Ref::from_bytes(raw_body)
28                    .map_err(|_| FrameParseError(
29                        format!(concat!(
30                            "Invalid length or alignment for ",
31                            stringify!([<$ie_snake_case:camel>])))))
32            }
33        }
34    };
35}
36
37// Each of the following creates a `parse_some_ie()` function associated with a `SomeIe` type.
38simple_parse_func!(dsss_param_set);
39simple_parse_func!(ht_capabilities);
40simple_parse_func!(ht_operation);
41simple_parse_func!(rm_enabled_capabilities);
42simple_parse_func!(vht_capabilities);
43simple_parse_func!(vht_operation);
44simple_parse_func!(wmm_info);
45simple_parse_func!(wmm_param);
46simple_parse_func!(channel_switch_announcement);
47simple_parse_func!(extended_channel_switch_announcement);
48simple_parse_func!(sec_chan_offset);
49simple_parse_func!(wide_bandwidth_channel_switch);
50
51pub fn parse_ssid<B: SplitByteSlice>(raw_body: B) -> FrameParseResult<B> {
52    validate!(raw_body.len() <= (fidl_ieee80211::MAX_SSID_BYTE_LEN as usize), "SSID is too long");
53    Ok(raw_body)
54}
55
56pub fn parse_supported_rates<B: SplitByteSlice>(
57    raw_body: B,
58) -> FrameParseResult<Ref<B, [SupportedRate]>> {
59    // IEEE Std 802.11-2016, 9.2.4.3 specifies that the Supported Rates IE may contain at most
60    // eight rates. However, in practice some devices transmit more (rather than using Extended
61    // Supported Rates). As the rates are encoded in a standard IE, this function does not validate
62    // the number of rates to improve interoperability.
63    validate!(!raw_body.is_empty(), "Empty Supported Rates IE");
64    // unwrap() is OK because sizeof(SupportedRate) is 1, and any slice length is a multiple of 1
65    Ok(Ref::from_bytes(raw_body).unwrap())
66}
67
68pub fn parse_extended_supported_rates<B: SplitByteSlice>(
69    raw_body: B,
70) -> FrameParseResult<Ref<B, [SupportedRate]>> {
71    validate!(!raw_body.is_empty(), "Empty Extended Supported Rates IE");
72    // The maximum number of extended supported rates (each a single u8) is the same as the
73    // maximum number of bytes in an IE. Therefore, there is no need to check the max length
74    // of the extended supported rates IE body.
75    // unwrap() is OK because sizeof(SupportedRate) is 1, and any slice length is a multiple of 1
76    Ok(Ref::from_bytes(raw_body).unwrap())
77}
78
79pub fn parse_tim<B: SplitByteSlice>(raw_body: B) -> FrameParseResult<TimView<B>> {
80    let (header, bitmap) = Ref::<B, TimHeader>::from_prefix(raw_body).map_err(Into::into).map_err(
81        |_: zerocopy::SizeError<_, _>| {
82            FrameParseError(format!("Element body is too short to include a TIM header"))
83        },
84    )?;
85    validate!(!bitmap.is_empty(), "Bitmap in TIM is empty");
86    validate!(bitmap.len() <= TIM_MAX_BITMAP_LEN, "Bitmap in TIM is too long");
87    Ok(TimView { header: *header, bitmap })
88}
89
90pub fn parse_country<B: SplitByteSlice>(raw_body: B) -> FrameParseResult<CountryView<B>> {
91    let mut reader = BufferReader::new(raw_body);
92    let country_code = reader.read::<[u8; 2]>().ok_or_else(|| {
93        FrameParseError(format!("Element body is too short to include a country code"))
94    })?;
95    let environment = reader.read_byte().ok_or_else(|| {
96        FrameParseError(format!("Element body is too short to include the whole country string"))
97    })?;
98    Ok(CountryView {
99        country_code: *country_code,
100        environment: CountryEnvironment(environment),
101        subbands: reader.into_remaining(),
102    })
103}
104
105pub fn parse_ext_capabilities<B: SplitByteSlice>(raw_body: B) -> ExtCapabilitiesView<B> {
106    let mut reader = BufferReader::new(raw_body);
107    let ext_caps_octet_1 = reader.read();
108    let ext_caps_octet_2 = reader.read();
109    let ext_caps_octet_3 = reader.read();
110    ExtCapabilitiesView {
111        ext_caps_octet_1,
112        ext_caps_octet_2,
113        ext_caps_octet_3,
114        remaining: reader.into_remaining(),
115    }
116}
117
118pub fn parse_wpa_ie<B: SplitByteSlice>(raw_body: B) -> FrameParseResult<wpa::WpaIe> {
119    wpa::from_bytes(&raw_body[..])
120        .map(|(_, r)| r)
121        .map_err(|_| FrameParseError(format!("Failed to parse WPA IE")))
122}
123
124pub fn parse_transmit_power_envelope<B: SplitByteSlice>(
125    raw_body: B,
126) -> FrameParseResult<TransmitPowerEnvelopeView<B>> {
127    let mut reader = BufferReader::new(raw_body);
128    let transmit_power_info = reader
129        .read::<TransmitPowerInfo>()
130        .ok_or_else(|| FrameParseError(format!("Transmit Power Envelope element too short")))?;
131    if transmit_power_info.max_transmit_power_count() > 3 {
132        return FrameParseResult::Err(FrameParseError(format!(
133            "Invalid transmit power count for Transmit Power Envelope element"
134        )));
135    }
136    let expected_bytes_remaining = transmit_power_info.max_transmit_power_count() as usize + 1;
137    if reader.bytes_remaining() < expected_bytes_remaining {
138        return FrameParseResult::Err(FrameParseError(format!(
139            "Transmit Power Envelope element too short"
140        )));
141    } else if reader.bytes_remaining() > expected_bytes_remaining {
142        return FrameParseResult::Err(FrameParseError(format!(
143            "Transmit Power Envelope element too long"
144        )));
145    }
146    // Unwrap safe due to checks above.
147    let max_transmit_power_20 = reader.read().unwrap();
148    let max_transmit_power_40 = reader.read();
149    let max_transmit_power_80 = reader.read();
150    let max_transmit_power_160 = reader.read();
151    FrameParseResult::Ok(TransmitPowerEnvelopeView {
152        transmit_power_info,
153        max_transmit_power_20,
154        max_transmit_power_40,
155        max_transmit_power_80,
156        max_transmit_power_160,
157    })
158}
159
160pub fn parse_channel_switch_wrapper<B: SplitByteSlice>(
161    raw_body: B,
162) -> FrameParseResult<ChannelSwitchWrapperView<B>> {
163    let mut result = ChannelSwitchWrapperView {
164        new_country: None,
165        wide_bandwidth_channel_switch: None,
166        new_transmit_power_envelope: None,
167    };
168    let ie_reader = crate::ie::Reader::new(raw_body);
169    for (ie_id, ie_body) in ie_reader {
170        match ie_id {
171            Id::COUNTRY => {
172                result.new_country.replace(parse_country(ie_body)?);
173            }
174            Id::WIDE_BANDWIDTH_CHANNEL_SWITCH => {
175                result
176                    .wide_bandwidth_channel_switch
177                    .replace(parse_wide_bandwidth_channel_switch(ie_body)?);
178            }
179            Id::TRANSMIT_POWER_ENVELOPE => {
180                result.new_transmit_power_envelope.replace(parse_transmit_power_envelope(ie_body)?);
181            }
182            _ => {
183                return Err(FrameParseError(format!(
184                    "Unexpected sub-element Id in Channel Switch Wrapper"
185                )));
186            }
187        }
188    }
189    FrameParseResult::Ok(result)
190}
191
192pub fn parse_vendor_ie<B: SplitByteSlice>(raw_body: B) -> FrameParseResult<VendorIe<B>> {
193    let mut reader = BufferReader::new(raw_body);
194    let oui = *reader
195        .read::<Oui>()
196        .ok_or_else(|| FrameParseError(format!("Failed to read vendor OUI")))?;
197    let vendor_ie = match oui {
198        Oui::MSFT => {
199            let ie_type = reader.peek_byte();
200            match ie_type {
201                Some(wpa::VENDOR_SPECIFIC_TYPE) => {
202                    // We already know from our peek_byte that at least one byte remains, so this
203                    // split will not panic.
204                    let (_type, body) = reader.into_remaining().split_at(1).ok().unwrap();
205                    VendorIe::MsftLegacyWpa(body)
206                }
207                Some(wsc::VENDOR_SPECIFIC_TYPE) => {
208                    let (_type, body) = reader.into_remaining().split_at(1).ok().unwrap();
209                    VendorIe::Wsc(body)
210                }
211                // The first three bytes after OUI are OUI type, OUI subtype, and version.
212                Some(WMM_OUI_TYPE) if reader.bytes_remaining() >= 3 => {
213                    let body = reader.into_remaining();
214                    let subtype = body[1];
215                    // The version byte is 0x01 for both WMM Information and Parameter elements
216                    // as of WFA WMM v1.2.0.
217                    if body[2] != 0x01 {
218                        return Err(FrameParseError(format!("Unexpected WMM Version byte")));
219                    }
220                    match subtype {
221                        // Safe to split because we already checked that there are at least 3
222                        // bytes remaining.
223                        WMM_INFO_OUI_SUBTYPE => VendorIe::WmmInfo(body.split_at(3).ok().unwrap().1),
224                        WMM_PARAM_OUI_SUBTYPE => {
225                            VendorIe::WmmParam(body.split_at(3).ok().unwrap().1)
226                        }
227                        _ => VendorIe::Unknown { oui, body },
228                    }
229                }
230                _ => VendorIe::Unknown { oui, body: reader.into_remaining() },
231            }
232        }
233        _ => VendorIe::Unknown { oui, body: reader.into_remaining() },
234    };
235    Ok(vendor_ie)
236}
237
238pub fn parse_rsnxe<B: SplitByteSlice>(raw_body: B) -> RsnxeView<B> {
239    let mut reader = BufferReader::new(raw_body);
240    let rsnxe_octet_1 = reader.read();
241    RsnxeView { rsnxe_octet_1, remaining: reader.into_remaining() }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use assert_matches::assert_matches;
248    use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
249
250    #[repr(C)]
251    #[derive(IntoBytes, KnownLayout, FromBytes, Immutable)]
252    pub struct SomeIe {
253        some_field: u16,
254    }
255    simple_parse_func!(some_ie);
256
257    #[test]
258    pub fn simple_parse_func_ok() {
259        let some_ie = parse_some_ie(&[0xfa, 0xde][..]).unwrap();
260        assert_eq!(some_ie.some_field, 0xdefa);
261    }
262
263    #[test]
264    pub fn simple_parse_func_wrong_size() {
265        let err_too_short = parse_some_ie(&[0xfa][..]).err().unwrap();
266        assert_eq!(
267            "Error parsing frame: Invalid length or alignment for SomeIe",
268            &err_too_short.to_string()
269        );
270        let err_too_long = parse_some_ie(&[0xfa, 0xde, 0xed][..]).err().unwrap();
271        assert_eq!(
272            "Error parsing frame: Invalid length or alignment for SomeIe",
273            &err_too_long.to_string()
274        );
275    }
276
277    #[test]
278    pub fn simple_parse_func_wrong_alignment() {
279        // Construct valid length but incorrectly aligned SomeIe
280        struct Buf {
281            b: [u8; 3],
282            _t: u16, // Make Buf align to u16
283        }
284        let buf = Buf { b: [0x00, 0xfa, 0xde], _t: 0 };
285        let buf_slice = &buf.b[1..];
286        assert_eq!(buf_slice.len(), std::mem::size_of::<SomeIe>());
287
288        let err_not_aligned = parse_some_ie(buf_slice).err().unwrap();
289        assert_eq!(
290            "Error parsing frame: Invalid length or alignment for SomeIe",
291            &err_not_aligned.to_string()
292        );
293    }
294
295    #[test]
296    pub fn ssid_ok() {
297        assert_eq!(Ok(&[][..]), parse_ssid(&[][..]));
298        assert_eq!(Ok(&[1, 2, 3][..]), parse_ssid(&[1, 2, 3][..]));
299    }
300
301    #[test]
302    pub fn ssid_too_long() {
303        assert_eq!(Err(FrameParseError(format!("SSID is too long"))), parse_ssid(&[0u8; 33][..]));
304    }
305
306    #[test]
307    pub fn supported_rates_ok() {
308        let r = parse_supported_rates(&[1, 2, 3][..]).expect("expected Ok");
309        assert_eq!(&[SupportedRate(1), SupportedRate(2), SupportedRate(3)][..], &r[..]);
310    }
311
312    #[test]
313    pub fn supported_rates_empty() {
314        let err = parse_supported_rates(&[][..]).expect_err("expected Err");
315        assert_eq!("Error parsing frame: Empty Supported Rates IE", &err.to_string());
316    }
317
318    // This test expects to pass despite IEEE Std 802.11-2016, 9.2.4.3 specifying a limit of eight
319    // rates. This limit is intentionally ignored when parsing Supported Rates to improve
320    // interoperability with devices that write more than eight rates into the IE.
321    #[test]
322    pub fn supported_rates_ok_overloaded() {
323        let rates =
324            parse_supported_rates(&[0u8; 9][..]).expect("rejected overloaded Supported Rates IE");
325        assert_eq!(&rates[..], &[SupportedRate(0); 9][..],);
326    }
327
328    #[test]
329    pub fn tim_ok() {
330        let r = parse_tim(&[1, 2, 3, 4, 5][..]).expect("expected Ok");
331        assert_eq!(2, r.header.dtim_period);
332        assert_eq!(&[4, 5][..], r.bitmap);
333    }
334
335    #[test]
336    pub fn tim_too_short_for_header() {
337        let err = parse_tim(&[1, 2][..]).err().expect("expected Err");
338        assert_eq!(
339            "Error parsing frame: Element body is too short to include a TIM header",
340            &err.to_string()
341        );
342    }
343
344    #[test]
345    pub fn tim_empty_bitmap() {
346        let err = parse_tim(&[1, 2, 3][..]).err().expect("expected Err");
347        assert_eq!("Error parsing frame: Bitmap in TIM is empty", &err.to_string());
348    }
349
350    #[test]
351    pub fn tim_bitmap_too_long() {
352        let err = parse_tim(&[0u8; 255][..]).err().expect("expected Err");
353        assert_eq!("Error parsing frame: Bitmap in TIM is too long", &err.to_string());
354    }
355
356    #[test]
357    pub fn country_ok() {
358        // Country element without Element Id and length
359        #[rustfmt::skip]
360        let raw_body = [
361            0x55, 0x53, // Country: US
362            0x20, // Environment: Any
363            0x24, 0x04, 0x24, // Subband triplet 1
364            0x34, 0x04, 0x1e, // Subband triplet 2
365            0x64, 0x0c, 0x1e, // Subband triplet 3
366            0x95, 0x05, 0x24, // Subband triplet 4
367            0x00, // padding
368        ];
369        let country = parse_country(&raw_body[..]).expect("valid frame should result in OK");
370
371        assert_eq!(country.country_code, [0x55, 0x53]);
372        assert_eq!(country.environment, CountryEnvironment::ANY);
373        assert_eq!(country.subbands, &raw_body[3..]);
374    }
375
376    #[test]
377    pub fn country_too_short() {
378        let err = parse_country(&[0x55, 0x53][..]).err().expect("expected Err");
379        assert_eq!(
380            "Error parsing frame: Element body is too short to include the whole country string",
381            &err.to_string()
382        );
383    }
384
385    #[test]
386    pub fn channel_switch_announcement() {
387        let raw_csa = [1, 30, 40];
388        let csa =
389            parse_channel_switch_announcement(&raw_csa[..]).expect("valid CSA should result in OK");
390        assert_eq!(csa.mode, 1);
391        assert_eq!(csa.new_channel_number, 30);
392        assert_eq!(csa.channel_switch_count, 40);
393    }
394
395    #[test]
396    pub fn extended_channel_switch_announcement() {
397        let raw_ecsa = [1, 20, 30, 40];
398        let ecsa = parse_extended_channel_switch_announcement(&raw_ecsa[..])
399            .expect("valid CSA should result in OK");
400        assert_eq!(ecsa.mode, 1);
401        assert_eq!(ecsa.new_operating_class, 20);
402        assert_eq!(ecsa.new_channel_number, 30);
403        assert_eq!(ecsa.channel_switch_count, 40);
404    }
405
406    #[test]
407    pub fn wide_bandwidth_channel_switch() {
408        let raw_wbcs = [0, 10, 20];
409        let wbcs = parse_wide_bandwidth_channel_switch(&raw_wbcs[..])
410            .expect("valid WBCS should result in OK");
411        assert_eq!(wbcs.new_width, VhtChannelBandwidth::CBW_20_40);
412        assert_eq!(wbcs.new_center_freq_seg0, 10);
413        assert_eq!(wbcs.new_center_freq_seg1, 20);
414    }
415
416    #[test]
417    pub fn transmit_power_envelope_view() {
418        #[rustfmt::skip]
419        let raw_tpe = [
420            // transmit power information: All fields present, EIRP unit
421            0b00_000_011,
422            20, 40, 80, 160,
423        ];
424        let tpe =
425            parse_transmit_power_envelope(&raw_tpe[..]).expect("valid TPE should result in OK");
426        assert_eq!(tpe.transmit_power_info.max_transmit_power_count(), 3);
427        assert_eq!(
428            tpe.transmit_power_info.max_transmit_power_unit_interpretation(),
429            MaxTransmitPowerUnitInterpretation::EIRP
430        );
431        assert_eq!(*tpe.max_transmit_power_20, TransmitPower(20));
432        assert_eq!(tpe.max_transmit_power_40.map(|t| *t), Some(TransmitPower(40)));
433        assert_eq!(tpe.max_transmit_power_80.map(|t| *t), Some(TransmitPower(80)));
434        assert_eq!(tpe.max_transmit_power_160.map(|t| *t), Some(TransmitPower(160)));
435    }
436
437    #[test]
438    pub fn transmit_power_envelope_view_20_only() {
439        #[rustfmt::skip]
440        let raw_tpe = [
441            // transmit power information: Only 20 MHz, EIRP unit
442            0b00_000_000,
443            20,
444        ];
445        let tpe =
446            parse_transmit_power_envelope(&raw_tpe[..]).expect("valid TPE should result in OK");
447        assert_eq!(tpe.transmit_power_info.max_transmit_power_count(), 0);
448        assert_eq!(
449            tpe.transmit_power_info.max_transmit_power_unit_interpretation(),
450            MaxTransmitPowerUnitInterpretation::EIRP
451        );
452        assert_eq!(*tpe.max_transmit_power_20, TransmitPower(20));
453        assert_eq!(tpe.max_transmit_power_40, None);
454        assert_eq!(tpe.max_transmit_power_80, None);
455        assert_eq!(tpe.max_transmit_power_160, None);
456    }
457
458    #[test]
459    pub fn transmit_power_envelope_view_too_long() {
460        #[rustfmt::skip]
461        let raw_tpe = [
462            // transmit power information: Only 20 MHz, EIRP unit
463            0b00_000_000,
464            20, 40, 80, 160
465        ];
466        let err = parse_transmit_power_envelope(&raw_tpe[..]).err().expect("expected Err");
467        assert_eq!(
468            "Error parsing frame: Transmit Power Envelope element too long",
469            &err.to_string()
470        );
471    }
472
473    #[test]
474    pub fn transmit_power_envelope_view_too_short() {
475        #[rustfmt::skip]
476        let raw_tpe = [
477            // transmit power information: 20 + 40 MHz, EIRP unit
478            0b00_000_001,
479            20,
480        ];
481        let err = parse_transmit_power_envelope(&raw_tpe[..]).err().expect("expected Err");
482        assert_eq!(
483            "Error parsing frame: Transmit Power Envelope element too short",
484            &err.to_string()
485        );
486    }
487
488    #[test]
489    pub fn transmit_power_envelope_invalid_count() {
490        #[rustfmt::skip]
491        let raw_tpe = [
492            // transmit power information: Invalid count (4), EIRP unit
493            0b00_000_100,
494            20,
495        ];
496        let err = parse_transmit_power_envelope(&raw_tpe[..]).err().expect("expected Err");
497        assert_eq!(
498            "Error parsing frame: Invalid transmit power count for Transmit Power Envelope element",
499            &err.to_string()
500        );
501    }
502
503    #[test]
504    pub fn channel_switch_wrapper_view() {
505        #[rustfmt::skip]
506        let raw_csw = [
507            Id::COUNTRY.0, 3, b'U', b'S', b'O',
508            Id::WIDE_BANDWIDTH_CHANNEL_SWITCH.0, 3, 0, 10, 20,
509            Id::TRANSMIT_POWER_ENVELOPE.0, 2, 0b00_000_000, 20,
510        ];
511        let csw =
512            parse_channel_switch_wrapper(&raw_csw[..]).expect("valid CSW should result in OK");
513        let country = csw.new_country.expect("New country present in CSW.");
514        assert_eq!(country.country_code, [b'U', b'S']);
515        assert_eq!(country.environment, CountryEnvironment::OUTDOOR);
516        assert_matches!(csw.wide_bandwidth_channel_switch, Some(wbcs) => {
517            assert_eq!(wbcs.new_width, VhtChannelBandwidth::CBW_20_40);
518            assert_eq!(wbcs.new_center_freq_seg0, 10);
519            assert_eq!(wbcs.new_center_freq_seg1, 20);
520        });
521        let tpe = csw.new_transmit_power_envelope.expect("Transmit power present in CSW.");
522        assert_eq!(*tpe.max_transmit_power_20, TransmitPower(20));
523        assert_eq!(tpe.max_transmit_power_40, None);
524        assert_eq!(tpe.max_transmit_power_80, None);
525        assert_eq!(tpe.max_transmit_power_160, None);
526    }
527
528    #[test]
529    pub fn partial_channel_switch_wrapper_view() {
530        #[rustfmt::skip]
531        let raw_csw = [
532            Id::WIDE_BANDWIDTH_CHANNEL_SWITCH.0, 3, 0, 10, 20,
533        ];
534        let csw =
535            parse_channel_switch_wrapper(&raw_csw[..]).expect("valid CSW should result in OK");
536        assert!(csw.new_country.is_none());
537        assert_matches!(csw.wide_bandwidth_channel_switch, Some(wbcs) => {
538            assert_eq!(wbcs.new_width, VhtChannelBandwidth::CBW_20_40);
539            assert_eq!(wbcs.new_center_freq_seg0, 10);
540            assert_eq!(wbcs.new_center_freq_seg1, 20);
541        });
542        assert!(csw.new_transmit_power_envelope.is_none());
543    }
544
545    #[test]
546    pub fn channel_switch_wrapper_view_unexpected_subelement() {
547        #[rustfmt::skip]
548        let raw_csw = [
549            Id::WIDE_BANDWIDTH_CHANNEL_SWITCH.0, 3, 40, 10, 20,
550            Id::HT_OPERATION.0, 3, 1, 2, 3,
551        ];
552        let err = parse_channel_switch_wrapper(&raw_csw[..]).err().expect("expected Err");
553        assert_eq!(
554            "Error parsing frame: Unexpected sub-element Id in Channel Switch Wrapper",
555            &err.to_string()
556        );
557    }
558
559    #[test]
560    fn ht_capabilities_ok() {
561        // HtCapabilities element without Element Id and length
562        #[rustfmt::skip]
563        let raw_body = [
564            0x4e, 0x11, // HtCapabilitiInfo(u16)
565            0x1b, // AmpduParams(u8)
566            0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
567            0x00, 0x00, 0xab, 0xcd, 0x00, 0x00, 0x00, 0x00, // SupportedMcsSet(u128)
568            0x06, 0x03, // HtExtCapabilities(u16)
569            0xc0, 0xb0, 0xcb, 0x13, // TxBfCapability(u32)
570            0x00, // AselCapability(u8)
571        ];
572        let ht_cap = parse_ht_capabilities(&raw_body[..]).expect("valid frame should result in OK");
573
574        let ht_cap_info = ht_cap.ht_cap_info;
575        assert_eq!(ht_cap_info.0, 0x114e);
576        assert_eq!(ht_cap_info.chan_width_set(), ChanWidthSet::TWENTY_FORTY);
577        assert_eq!(ht_cap_info.sm_power_save(), SmPowerSave::DISABLED);
578        assert_eq!(ht_cap_info.max_amsdu_len(), MaxAmsduLen::OCTETS_3839);
579
580        let ampdu_params = ht_cap.ampdu_params;
581        assert_eq!(ampdu_params.0, 0x1b);
582        assert_eq!(ampdu_params.max_ampdu_exponent().to_len(), 65535);
583        assert_eq!(ampdu_params.min_start_spacing(), MinMpduStartSpacing::EIGHT_USEC);
584
585        let mcs_set = ht_cap.mcs_set;
586        assert_eq!(mcs_set.0, 0x00000000_cdab0000_00000000_000000ff);
587        assert_eq!(mcs_set.rx_mcs().0, 0xff);
588        assert_eq!(mcs_set.rx_mcs().support(7), true);
589        assert_eq!(mcs_set.rx_mcs().support(8), false);
590        assert_eq!(mcs_set.rx_highest_rate(), 0x01ab);
591
592        let ht_ext_cap = ht_cap.ht_ext_cap;
593        let raw_value = ht_ext_cap.0;
594        assert_eq!(raw_value, 0x0306);
595        assert_eq!(ht_ext_cap.pco_transition(), PcoTransitionTime::PCO_5000_USEC);
596        assert_eq!(ht_ext_cap.mcs_feedback(), McsFeedback::BOTH);
597
598        let txbf_cap = ht_cap.txbf_cap;
599        let raw_value = txbf_cap.0;
600        assert_eq!(raw_value, 0x13cbb0c0);
601        assert_eq!(txbf_cap.calibration(), Calibration::RESPOND_INITIATE);
602        assert_eq!(txbf_cap.csi_feedback(), Feedback::IMMEDIATE);
603        assert_eq!(txbf_cap.noncomp_feedback(), Feedback::DELAYED);
604        assert_eq!(txbf_cap.min_grouping(), MinGroup::TWO);
605
606        // human-readable representation
607        assert_eq!(txbf_cap.csi_antennas().to_human(), 2);
608        assert_eq!(txbf_cap.noncomp_steering_ants().to_human(), 3);
609        assert_eq!(txbf_cap.comp_steering_ants().to_human(), 4);
610        assert_eq!(txbf_cap.csi_rows().to_human(), 2);
611        assert_eq!(txbf_cap.chan_estimation().to_human(), 3);
612
613        let asel_cap = ht_cap.asel_cap;
614        assert_eq!(asel_cap.0, 0);
615    }
616
617    #[test]
618    pub fn extended_supported_rates_ok() {
619        let r = parse_extended_supported_rates(&[1, 2, 3][..]).expect("expected Ok");
620        assert_eq!(&[SupportedRate(1), SupportedRate(2), SupportedRate(3)][..], &r[..]);
621    }
622
623    #[test]
624    pub fn extended_supported_rates_empty() {
625        let err = parse_extended_supported_rates(&[][..]).expect_err("expected Err");
626        assert_eq!("Error parsing frame: Empty Extended Supported Rates IE", &err.to_string());
627    }
628
629    #[test]
630    fn ht_operation_ok() {
631        // HtOperation element without Element Id and length
632        #[rustfmt::skip]
633        let raw_body = [
634            99, // primary_channel
635            0xff, 0xfe, 0xff, 0xff, 0xff, // ht_op_info
636            // basic_ht_mcs_set
637            0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
638            0x00, 0x00, 0xab, 0xcd, 0x00, 0x00, 0x00, 0x00,
639        ];
640        let ht_op = parse_ht_operation(&raw_body[..]).expect("valid frame should result in OK");
641
642        assert_eq!(ht_op.primary_channel, 99);
643
644        let ht_op_info = ht_op.ht_op_info;
645        assert_eq!(ht_op_info.secondary_chan_offset(), SecChanOffset::SECONDARY_BELOW);
646        assert_eq!(ht_op_info.sta_chan_width(), StaChanWidth::ANY);
647        assert_eq!(ht_op_info.ht_protection(), HtProtection::TWENTY_MHZ);
648        assert_eq!(ht_op_info.pco_phase(), PcoPhase::FORTY_MHZ);
649
650        let basic_mcs_set = ht_op.basic_ht_mcs_set;
651        assert_eq!(basic_mcs_set.0, 0x00000000_cdab0000_00000000_000000ff);
652    }
653
654    #[test]
655    fn rm_enabled_capabilities_ok() {
656        #[rustfmt::skip]
657        let raw_body = [
658            0x03, 0x00, 0x00, 0x00, 0x02, // rm_enabled_capabilities
659        ];
660
661        let caps =
662            parse_rm_enabled_capabilities(&raw_body[..]).expect("valid frame should result in OK");
663        assert!(caps.link_measurement_enabled());
664        assert!(caps.neighbor_report_enabled());
665        assert!(!caps.lci_azimuth_enabled());
666        assert!(caps.antenna_enabled());
667        assert!(!caps.ftm_range_report_enabled());
668    }
669
670    #[test]
671    fn sec_chan_offset_ok() {
672        let sec_chan_offset =
673            parse_sec_chan_offset(&[3][..]).expect("valid sec chan offset should result in OK");
674        assert_eq!(sec_chan_offset.0, 3);
675    }
676
677    #[test]
678    fn ext_capabilities_ok() {
679        let data = [0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x40];
680        let ext_capabilities = parse_ext_capabilities(&data[..]);
681        assert_matches!(ext_capabilities.ext_caps_octet_1, Some(caps) => {
682            assert!(caps.extended_channel_switching());
683            assert!(!caps.psmp_capability());
684        });
685        assert_matches!(ext_capabilities.ext_caps_octet_2, Some(caps) => {
686            assert!(!caps.civic_location());
687        });
688        assert_matches!(ext_capabilities.ext_caps_octet_3, Some(caps) => {
689            assert!(caps.bss_transition());
690            assert!(!caps.ac_station_count());
691        });
692        assert_eq!(ext_capabilities.remaining, &[0x00, 0x00, 0x00, 0x00, 0x40]);
693    }
694
695    #[test]
696    fn vht_capabilities_ok() {
697        // VhtCapabilities element without Element Id and length
698        #[rustfmt::skip]
699        let raw_body = [
700            0xfe, 0xff, 0xff, 0xff, // VhtCapabilitiesInfo(u32)
701            0xff, 0xaa, 0x00, 0x00, 0x55, 0xff, 0x00, 0x00, // VhtMcsNssSet(u64)
702        ];
703        let vht_cap = parse_vht_capabilities(&raw_body[..]).expect("expected OK from valid frames");
704
705        let cap_info = vht_cap.vht_cap_info;
706        assert_eq!(cap_info.max_mpdu_len(), MaxMpduLen::OCTECTS_11454);
707        assert_eq!(cap_info.link_adapt(), VhtLinkAdaptation::BOTH);
708        let max_ampdu_component = cap_info.max_ampdu_exponent();
709        assert_eq!(max_ampdu_component.to_len(), 1048575);
710
711        let mcs_nss = vht_cap.vht_mcs_nss;
712        assert_eq!(mcs_nss.rx_max_mcs().ss1(), VhtMcsSet::NONE);
713        assert_eq!(mcs_nss.rx_max_mcs().ss7(), VhtMcsSet::UP_TO_9);
714        assert_eq!(mcs_nss.tx_max_mcs().ss1(), VhtMcsSet::UP_TO_8);
715        assert_eq!(mcs_nss.tx_max_mcs().ss7(), VhtMcsSet::NONE);
716
717        assert_eq!(mcs_nss.rx_max_mcs().ss(2), Ok(VhtMcsSet::NONE));
718        assert_eq!(mcs_nss.rx_max_mcs().ss(6), Ok(VhtMcsSet::UP_TO_9));
719        assert_eq!(mcs_nss.tx_max_mcs().ss(2), Ok(VhtMcsSet::UP_TO_8));
720        assert_eq!(mcs_nss.tx_max_mcs().ss(6), Ok(VhtMcsSet::NONE));
721    }
722
723    #[test]
724    fn vht_operation_ok() {
725        // VhtOperation element without Element Id and length
726        #[rustfmt::skip]
727        let raw_body = [
728            231, // vht_cbw(u8)
729            232, // center_freq_seg0(u8)
730            233, // center_freq_seg1(u8)
731            0xff, 0x66, // basic_mcs_nss(VhtMcsNssMap(u16))
732        ];
733        let vht_op = parse_vht_operation(&raw_body[..]).expect("expected OK from valid frames");
734        assert_eq!(231, vht_op.vht_cbw.0);
735        assert_eq!(232, vht_op.center_freq_seg0);
736        assert_eq!(233, vht_op.center_freq_seg1);
737    }
738
739    #[test]
740    fn rsnxe_ok() {
741        let data = [0b00100001, 0x00, 0x00, 0x40];
742        let rsnxe = parse_rsnxe(&data[..]);
743        assert_matches!(rsnxe.rsnxe_octet_1, Some(oct1) => {
744            assert_eq!(oct1.field_length(), 1);
745            assert!(!oct1.protected_twt_operations_support());
746            assert!(oct1.sae_hash_to_element());
747        });
748        assert_eq!(rsnxe.remaining, &[0x00, 0x00, 0x40]);
749    }
750
751    #[test]
752    fn parse_wpa_ie_ok() {
753        let raw_body: Vec<u8> = vec![
754            0x00, 0x50, 0xf2, // MSFT OUI
755            0x01, 0x01, 0x00, // WPA IE header
756            0x00, 0x50, 0xf2, 0x02, // multicast cipher: AKM
757            0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, // 1 unicast cipher: TKIP
758            0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, // 1 AKM: PSK
759        ];
760        let wpa_ie = parse_vendor_ie(&raw_body[..]).expect("failed to parse wpa vendor ie");
761        assert_matches!(wpa_ie, VendorIe::MsftLegacyWpa(wpa_body) => {
762            parse_wpa_ie(&wpa_body[..]).expect("failed to parse wpa vendor ie")
763        });
764    }
765
766    #[test]
767    fn parse_bad_wpa_ie() {
768        let raw_body: Vec<u8> = vec![
769            0x00, 0x50, 0xf2, // MSFT OUI
770            0x01, 0x01, 0x00, // WPA IE header
771            0x00, 0x50, 0xf2, 0x02, // multicast cipher: AKM
772                  // truncated
773        ];
774        // parse_vendor_ie does not validate the actual wpa ie body, so this
775        // succeeds.
776        let wpa_ie = parse_vendor_ie(&raw_body[..]).expect("failed to parse wpa vendor ie");
777        assert_matches!(wpa_ie, VendorIe::MsftLegacyWpa(wpa_body) => {
778            parse_wpa_ie(&wpa_body[..]).expect_err("parsed truncated wpa ie")
779        });
780    }
781
782    #[test]
783    fn parse_wmm_info_ie_ok() {
784        let raw_body = [
785            0x00, 0x50, 0xf2, // MSFT OUI
786            0x02, 0x00, 0x01, // WMM Info IE header
787            0x80, // QoS Info: U-APSD enabled
788        ];
789        let wmm_info_ie = parse_vendor_ie(&raw_body[..]).expect("expected Ok");
790        assert_matches!(wmm_info_ie, VendorIe::WmmInfo(body) => {
791            assert_matches!(parse_wmm_info(&body[..]), Ok(wmm_info) => {
792                assert_eq!(wmm_info.0, 0x80);
793            })
794        });
795    }
796
797    #[test]
798    fn parse_wmm_info_ie_too_short() {
799        let raw_body = [
800            0x00, 0x50, 0xf2, // MSFT OUI
801            0x02, 0x00, 0x01, // WMM Info IE header
802                  // truncated
803        ];
804        let wmm_info_ie = parse_vendor_ie(&raw_body[..]).expect("expected Ok");
805        assert_matches!(wmm_info_ie, VendorIe::WmmInfo(body) => {
806            parse_wmm_info(&body[..]).expect_err("parsed truncated WMM info ie")
807        });
808    }
809
810    #[test]
811    fn parse_wmm_param_ie_ok() {
812        let raw_body = [
813            0x00, 0x50, 0xf2, // MSFT OUI
814            0x02, 0x01, 0x01, // WMM Param IE header
815            0x80, // QoS Info: U-APSD enabled
816            0x00, // reserved
817            0x03, 0xa4, 0x00, 0x00, // AC_BE Params - ACM no, AIFSN 3, ECWmin/max 4/10, TXOP 0
818            0x27, 0xa4, 0x00, 0x00, // AC_BK Params - ACM no, AIFSN 7, ECWmin/max 4/10, TXOP 0
819            0x42, 0x43, 0x5e, 0x00, // AC_VI Params - ACM no, AIFSN 2, ECWmin/max 3/4, TXOP 94
820            0x62, 0x32, 0x2f, 0x00, // AC_VO Params - ACM no, AIFSN 2, ECWmin/max 2/3, TXOP 47
821        ];
822        let wmm_param_ie = parse_vendor_ie(&raw_body[..]).expect("expected Ok");
823        assert_matches!(wmm_param_ie, VendorIe::WmmParam(body) => {
824            assert_matches!(parse_wmm_param(&body[..]), Ok(wmm_param) => {
825                assert_eq!(wmm_param.wmm_info.0, 0x80);
826                let ac_be = wmm_param.ac_be_params;
827                assert_eq!(ac_be.aci_aifsn.aifsn(), 3);
828                assert_eq!(ac_be.aci_aifsn.acm(), false);
829                assert_eq!(ac_be.aci_aifsn.aci(), 0);
830                assert_eq!(ac_be.ecw_min_max.ecw_min(), 4);
831                assert_eq!(ac_be.ecw_min_max.ecw_max(), 10);
832                assert_eq!({ ac_be.txop_limit }, 0);
833
834                let ac_bk = wmm_param.ac_bk_params;
835                assert_eq!(ac_bk.aci_aifsn.aifsn(), 7);
836                assert_eq!(ac_bk.aci_aifsn.acm(), false);
837                assert_eq!(ac_bk.aci_aifsn.aci(), 1);
838                assert_eq!(ac_bk.ecw_min_max.ecw_min(), 4);
839                assert_eq!(ac_bk.ecw_min_max.ecw_max(), 10);
840                assert_eq!({ ac_bk.txop_limit }, 0);
841
842                let ac_vi = wmm_param.ac_vi_params;
843                assert_eq!(ac_vi.aci_aifsn.aifsn(), 2);
844                assert_eq!(ac_vi.aci_aifsn.acm(), false);
845                assert_eq!(ac_vi.aci_aifsn.aci(), 2);
846                assert_eq!(ac_vi.ecw_min_max.ecw_min(), 3);
847                assert_eq!(ac_vi.ecw_min_max.ecw_max(), 4);
848                assert_eq!({ ac_vi.txop_limit }, 94);
849
850                let ac_vo = wmm_param.ac_vo_params;
851                assert_eq!(ac_vo.aci_aifsn.aifsn(), 2);
852                assert_eq!(ac_vo.aci_aifsn.acm(), false);
853                assert_eq!(ac_vo.aci_aifsn.aci(), 3);
854                assert_eq!(ac_vo.ecw_min_max.ecw_min(), 2);
855                assert_eq!(ac_vo.ecw_min_max.ecw_max(), 3);
856                assert_eq!({ ac_vo.txop_limit }, 47);
857            });
858        });
859    }
860
861    #[test]
862    fn parse_wmm_param_ie_too_short() {
863        let raw_body = [
864            0x00, 0x50, 0xf2, // MSFT OUI
865            0x02, 0x01, 0x01, // WMM Param IE header
866            0x80, // QoS Info: U-APSD enabled
867            0x00, // reserved
868                  // truncated
869        ];
870        let wmm_param_ie = parse_vendor_ie(&raw_body[..]).expect("expected Ok");
871        assert_matches!(wmm_param_ie, VendorIe::WmmParam(body) => {
872            parse_wmm_param(&body[..]).expect_err("parsed truncated WMM param ie")
873        });
874    }
875
876    #[test]
877    fn parse_unknown_msft_ie() {
878        let raw_body: Vec<u8> = vec![
879            0x00, 0x50, 0xf2, // MSFT OUI
880            0xff, 0x01, 0x00, // header with unknown vendor specific IE type
881            0x00, 0x50, 0xf2, 0x02, // multicast cipher: AKM
882            0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, // 1 unicast cipher: TKIP
883            0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, // 1 AKM: PSK
884        ];
885        let ie = parse_vendor_ie(&raw_body[..]).expect("failed to parse ie");
886        assert_matches!(ie, VendorIe::Unknown { .. });
887    }
888
889    #[test]
890    fn parse_unknown_vendor_ie() {
891        let raw_body: Vec<u8> = vec![0x00, 0x12, 0x34]; // Made up OUI
892        let ie = parse_vendor_ie(&raw_body[..]).expect("failed to parse wpa vendor ie");
893        assert_matches!(ie, VendorIe::Unknown { .. });
894    }
895
896    #[test]
897    fn to_and_from_fidl_ht_cap() {
898        fidl_ieee80211::HtCapabilities {
899            bytes: fake_ht_capabilities().as_bytes().try_into().expect("HT Cap to FIDL"),
900        };
901        let fidl =
902            fidl_ieee80211::HtCapabilities { bytes: [0; fidl_ieee80211::HT_CAP_LEN as usize] };
903        assert!(parse_ht_capabilities(&fidl.bytes[..]).is_ok());
904    }
905
906    #[test]
907    fn to_and_from_fidl_vht_cap() {
908        fidl_ieee80211::VhtCapabilities {
909            bytes: fake_vht_capabilities().as_bytes().try_into().expect("VHT Cap to FIDL"),
910        };
911        let fidl =
912            fidl_ieee80211::VhtCapabilities { bytes: [0; fidl_ieee80211::VHT_CAP_LEN as usize] };
913        assert!(parse_vht_capabilities(&fidl.bytes[..]).is_ok());
914    }
915
916    #[test]
917    fn to_and_from_fidl_ht_op() {
918        fidl_ieee80211::HtOperation {
919            bytes: fake_ht_operation().as_bytes().try_into().expect("HT Op to FIDL"),
920        };
921        let fidl = fidl_ieee80211::HtOperation { bytes: [0; fidl_ieee80211::HT_OP_LEN as usize] };
922        assert!(parse_ht_operation(&fidl.bytes[..]).is_ok());
923    }
924
925    #[test]
926    fn to_and_from_fidl_vht_op() {
927        fidl_ieee80211::VhtOperation {
928            bytes: fake_vht_operation().as_bytes().try_into().expect("VHT Op to FIDL"),
929        };
930        let fidl = fidl_ieee80211::VhtOperation { bytes: [0; fidl_ieee80211::VHT_OP_LEN as usize] };
931        assert!(parse_vht_operation(&fidl.bytes[..]).is_ok());
932    }
933}