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
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use crate::assert_variant;
242    use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
243
244    #[repr(C)]
245    #[derive(IntoBytes, KnownLayout, FromBytes, Immutable)]
246    pub struct SomeIe {
247        some_field: u16,
248    }
249    simple_parse_func!(some_ie);
250
251    #[test]
252    pub fn simple_parse_func_ok() {
253        let some_ie = parse_some_ie(&[0xfa, 0xde][..]).unwrap();
254        assert_eq!(some_ie.some_field, 0xdefa);
255    }
256
257    #[test]
258    pub fn simple_parse_func_wrong_size() {
259        let err_too_short = parse_some_ie(&[0xfa][..]).err().unwrap();
260        assert_eq!(
261            "Error parsing frame: Invalid length or alignment for SomeIe",
262            &err_too_short.to_string()
263        );
264        let err_too_long = parse_some_ie(&[0xfa, 0xde, 0xed][..]).err().unwrap();
265        assert_eq!(
266            "Error parsing frame: Invalid length or alignment for SomeIe",
267            &err_too_long.to_string()
268        );
269    }
270
271    #[test]
272    pub fn simple_parse_func_wrong_alignment() {
273        // Construct valid length but incorrectly aligned SomeIe
274        struct Buf {
275            b: [u8; 3],
276            _t: u16, // Make Buf align to u16
277        }
278        let buf = Buf { b: [0x00, 0xfa, 0xde], _t: 0 };
279        let buf_slice = &buf.b[1..];
280        assert_eq!(buf_slice.len(), std::mem::size_of::<SomeIe>());
281
282        let err_not_aligned = parse_some_ie(buf_slice).err().unwrap();
283        assert_eq!(
284            "Error parsing frame: Invalid length or alignment for SomeIe",
285            &err_not_aligned.to_string()
286        );
287    }
288
289    #[test]
290    pub fn ssid_ok() {
291        assert_eq!(Ok(&[][..]), parse_ssid(&[][..]));
292        assert_eq!(Ok(&[1, 2, 3][..]), parse_ssid(&[1, 2, 3][..]));
293    }
294
295    #[test]
296    pub fn ssid_too_long() {
297        assert_eq!(Err(FrameParseError(format!("SSID is too long"))), parse_ssid(&[0u8; 33][..]));
298    }
299
300    #[test]
301    pub fn supported_rates_ok() {
302        let r = parse_supported_rates(&[1, 2, 3][..]).expect("expected Ok");
303        assert_eq!(&[SupportedRate(1), SupportedRate(2), SupportedRate(3)][..], &r[..]);
304    }
305
306    #[test]
307    pub fn supported_rates_empty() {
308        let err = parse_supported_rates(&[][..]).expect_err("expected Err");
309        assert_eq!("Error parsing frame: Empty Supported Rates IE", &err.to_string());
310    }
311
312    // This test expects to pass despite IEEE Std 802.11-2016, 9.2.4.3 specifying a limit of eight
313    // rates. This limit is intentionally ignored when parsing Supported Rates to improve
314    // interoperability with devices that write more than eight rates into the IE.
315    #[test]
316    pub fn supported_rates_ok_overloaded() {
317        let rates =
318            parse_supported_rates(&[0u8; 9][..]).expect("rejected overloaded Supported Rates IE");
319        assert_eq!(&rates[..], &[SupportedRate(0); 9][..],);
320    }
321
322    #[test]
323    pub fn tim_ok() {
324        let r = parse_tim(&[1, 2, 3, 4, 5][..]).expect("expected Ok");
325        assert_eq!(2, r.header.dtim_period);
326        assert_eq!(&[4, 5][..], r.bitmap);
327    }
328
329    #[test]
330    pub fn tim_too_short_for_header() {
331        let err = parse_tim(&[1, 2][..]).err().expect("expected Err");
332        assert_eq!(
333            "Error parsing frame: Element body is too short to include a TIM header",
334            &err.to_string()
335        );
336    }
337
338    #[test]
339    pub fn tim_empty_bitmap() {
340        let err = parse_tim(&[1, 2, 3][..]).err().expect("expected Err");
341        assert_eq!("Error parsing frame: Bitmap in TIM is empty", &err.to_string());
342    }
343
344    #[test]
345    pub fn tim_bitmap_too_long() {
346        let err = parse_tim(&[0u8; 255][..]).err().expect("expected Err");
347        assert_eq!("Error parsing frame: Bitmap in TIM is too long", &err.to_string());
348    }
349
350    #[test]
351    pub fn country_ok() {
352        // Country element without Element Id and length
353        #[rustfmt::skip]
354        let raw_body = [
355            0x55, 0x53, // Country: US
356            0x20, // Environment: Any
357            0x24, 0x04, 0x24, // Subband triplet 1
358            0x34, 0x04, 0x1e, // Subband triplet 2
359            0x64, 0x0c, 0x1e, // Subband triplet 3
360            0x95, 0x05, 0x24, // Subband triplet 4
361            0x00, // padding
362        ];
363        let country = parse_country(&raw_body[..]).expect("valid frame should result in OK");
364
365        assert_eq!(country.country_code, [0x55, 0x53]);
366        assert_eq!(country.environment, CountryEnvironment::ANY);
367        assert_eq!(country.subbands, &raw_body[3..]);
368    }
369
370    #[test]
371    pub fn country_too_short() {
372        let err = parse_country(&[0x55, 0x53][..]).err().expect("expected Err");
373        assert_eq!(
374            "Error parsing frame: Element body is too short to include the whole country string",
375            &err.to_string()
376        );
377    }
378
379    #[test]
380    pub fn channel_switch_announcement() {
381        let raw_csa = [1, 30, 40];
382        let csa =
383            parse_channel_switch_announcement(&raw_csa[..]).expect("valid CSA should result in OK");
384        assert_eq!(csa.mode, 1);
385        assert_eq!(csa.new_channel_number, 30);
386        assert_eq!(csa.channel_switch_count, 40);
387    }
388
389    #[test]
390    pub fn extended_channel_switch_announcement() {
391        let raw_ecsa = [1, 20, 30, 40];
392        let ecsa = parse_extended_channel_switch_announcement(&raw_ecsa[..])
393            .expect("valid CSA should result in OK");
394        assert_eq!(ecsa.mode, 1);
395        assert_eq!(ecsa.new_operating_class, 20);
396        assert_eq!(ecsa.new_channel_number, 30);
397        assert_eq!(ecsa.channel_switch_count, 40);
398    }
399
400    #[test]
401    pub fn wide_bandwidth_channel_switch() {
402        let raw_wbcs = [0, 10, 20];
403        let wbcs = parse_wide_bandwidth_channel_switch(&raw_wbcs[..])
404            .expect("valid WBCS should result in OK");
405        assert_eq!(wbcs.new_width, VhtChannelBandwidth::CBW_20_40);
406        assert_eq!(wbcs.new_center_freq_seg0, 10);
407        assert_eq!(wbcs.new_center_freq_seg1, 20);
408    }
409
410    #[test]
411    pub fn transmit_power_envelope_view() {
412        #[rustfmt::skip]
413        let raw_tpe = [
414            // transmit power information: All fields present, EIRP unit
415            0b00_000_011,
416            20, 40, 80, 160,
417        ];
418        let tpe =
419            parse_transmit_power_envelope(&raw_tpe[..]).expect("valid TPE should result in OK");
420        assert_eq!(tpe.transmit_power_info.max_transmit_power_count(), 3);
421        assert_eq!(
422            tpe.transmit_power_info.max_transmit_power_unit_interpretation(),
423            MaxTransmitPowerUnitInterpretation::EIRP
424        );
425        assert_eq!(*tpe.max_transmit_power_20, TransmitPower(20));
426        assert_eq!(tpe.max_transmit_power_40.map(|t| *t), Some(TransmitPower(40)));
427        assert_eq!(tpe.max_transmit_power_80.map(|t| *t), Some(TransmitPower(80)));
428        assert_eq!(tpe.max_transmit_power_160.map(|t| *t), Some(TransmitPower(160)));
429    }
430
431    #[test]
432    pub fn transmit_power_envelope_view_20_only() {
433        #[rustfmt::skip]
434        let raw_tpe = [
435            // transmit power information: Only 20 MHz, EIRP unit
436            0b00_000_000,
437            20,
438        ];
439        let tpe =
440            parse_transmit_power_envelope(&raw_tpe[..]).expect("valid TPE should result in OK");
441        assert_eq!(tpe.transmit_power_info.max_transmit_power_count(), 0);
442        assert_eq!(
443            tpe.transmit_power_info.max_transmit_power_unit_interpretation(),
444            MaxTransmitPowerUnitInterpretation::EIRP
445        );
446        assert_eq!(*tpe.max_transmit_power_20, TransmitPower(20));
447        assert_eq!(tpe.max_transmit_power_40, None);
448        assert_eq!(tpe.max_transmit_power_80, None);
449        assert_eq!(tpe.max_transmit_power_160, None);
450    }
451
452    #[test]
453    pub fn transmit_power_envelope_view_too_long() {
454        #[rustfmt::skip]
455        let raw_tpe = [
456            // transmit power information: Only 20 MHz, EIRP unit
457            0b00_000_000,
458            20, 40, 80, 160
459        ];
460        let err = parse_transmit_power_envelope(&raw_tpe[..]).err().expect("expected Err");
461        assert_eq!(
462            "Error parsing frame: Transmit Power Envelope element too long",
463            &err.to_string()
464        );
465    }
466
467    #[test]
468    pub fn transmit_power_envelope_view_too_short() {
469        #[rustfmt::skip]
470        let raw_tpe = [
471            // transmit power information: 20 + 40 MHz, EIRP unit
472            0b00_000_001,
473            20,
474        ];
475        let err = parse_transmit_power_envelope(&raw_tpe[..]).err().expect("expected Err");
476        assert_eq!(
477            "Error parsing frame: Transmit Power Envelope element too short",
478            &err.to_string()
479        );
480    }
481
482    #[test]
483    pub fn transmit_power_envelope_invalid_count() {
484        #[rustfmt::skip]
485        let raw_tpe = [
486            // transmit power information: Invalid count (4), EIRP unit
487            0b00_000_100,
488            20,
489        ];
490        let err = parse_transmit_power_envelope(&raw_tpe[..]).err().expect("expected Err");
491        assert_eq!(
492            "Error parsing frame: Invalid transmit power count for Transmit Power Envelope element",
493            &err.to_string()
494        );
495    }
496
497    #[test]
498    pub fn channel_switch_wrapper_view() {
499        #[rustfmt::skip]
500        let raw_csw = [
501            Id::COUNTRY.0, 3, b'U', b'S', b'O',
502            Id::WIDE_BANDWIDTH_CHANNEL_SWITCH.0, 3, 0, 10, 20,
503            Id::TRANSMIT_POWER_ENVELOPE.0, 2, 0b00_000_000, 20,
504        ];
505        let csw =
506            parse_channel_switch_wrapper(&raw_csw[..]).expect("valid CSW should result in OK");
507        let country = csw.new_country.expect("New country present in CSW.");
508        assert_eq!(country.country_code, [b'U', b'S']);
509        assert_eq!(country.environment, CountryEnvironment::OUTDOOR);
510        assert_variant!(csw.wide_bandwidth_channel_switch, Some(wbcs) => {
511            assert_eq!(wbcs.new_width, VhtChannelBandwidth::CBW_20_40);
512            assert_eq!(wbcs.new_center_freq_seg0, 10);
513            assert_eq!(wbcs.new_center_freq_seg1, 20);
514        });
515        let tpe = csw.new_transmit_power_envelope.expect("Transmit power present in CSW.");
516        assert_eq!(*tpe.max_transmit_power_20, TransmitPower(20));
517        assert_eq!(tpe.max_transmit_power_40, None);
518        assert_eq!(tpe.max_transmit_power_80, None);
519        assert_eq!(tpe.max_transmit_power_160, None);
520    }
521
522    #[test]
523    pub fn partial_channel_switch_wrapper_view() {
524        #[rustfmt::skip]
525        let raw_csw = [
526            Id::WIDE_BANDWIDTH_CHANNEL_SWITCH.0, 3, 0, 10, 20,
527        ];
528        let csw =
529            parse_channel_switch_wrapper(&raw_csw[..]).expect("valid CSW should result in OK");
530        assert!(csw.new_country.is_none());
531        assert_variant!(csw.wide_bandwidth_channel_switch, Some(wbcs) => {
532            assert_eq!(wbcs.new_width, VhtChannelBandwidth::CBW_20_40);
533            assert_eq!(wbcs.new_center_freq_seg0, 10);
534            assert_eq!(wbcs.new_center_freq_seg1, 20);
535        });
536        assert!(csw.new_transmit_power_envelope.is_none());
537    }
538
539    #[test]
540    pub fn channel_switch_wrapper_view_unexpected_subelement() {
541        #[rustfmt::skip]
542        let raw_csw = [
543            Id::WIDE_BANDWIDTH_CHANNEL_SWITCH.0, 3, 40, 10, 20,
544            Id::HT_OPERATION.0, 3, 1, 2, 3,
545        ];
546        let err = parse_channel_switch_wrapper(&raw_csw[..]).err().expect("expected Err");
547        assert_eq!(
548            "Error parsing frame: Unexpected sub-element Id in Channel Switch Wrapper",
549            &err.to_string()
550        );
551    }
552
553    #[test]
554    fn ht_capabilities_ok() {
555        // HtCapabilities element without Element Id and length
556        #[rustfmt::skip]
557        let raw_body = [
558            0x4e, 0x11, // HtCapabilitiInfo(u16)
559            0x1b, // AmpduParams(u8)
560            0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
561            0x00, 0x00, 0xab, 0xcd, 0x00, 0x00, 0x00, 0x00, // SupportedMcsSet(u128)
562            0x06, 0x03, // HtExtCapabilities(u16)
563            0xc0, 0xb0, 0xcb, 0x13, // TxBfCapability(u32)
564            0x00, // AselCapability(u8)
565        ];
566        let ht_cap = parse_ht_capabilities(&raw_body[..]).expect("valid frame should result in OK");
567
568        let ht_cap_info = ht_cap.ht_cap_info;
569        assert_eq!(ht_cap_info.0, 0x114e);
570        assert_eq!(ht_cap_info.chan_width_set(), ChanWidthSet::TWENTY_FORTY);
571        assert_eq!(ht_cap_info.sm_power_save(), SmPowerSave::DISABLED);
572        assert_eq!(ht_cap_info.max_amsdu_len(), MaxAmsduLen::OCTETS_3839);
573
574        let ampdu_params = ht_cap.ampdu_params;
575        assert_eq!(ampdu_params.0, 0x1b);
576        assert_eq!(ampdu_params.max_ampdu_exponent().to_len(), 65535);
577        assert_eq!(ampdu_params.min_start_spacing(), MinMpduStartSpacing::EIGHT_USEC);
578
579        let mcs_set = ht_cap.mcs_set;
580        assert_eq!(mcs_set.0, 0x00000000_cdab0000_00000000_000000ff);
581        assert_eq!(mcs_set.rx_mcs().0, 0xff);
582        assert_eq!(mcs_set.rx_mcs().support(7), true);
583        assert_eq!(mcs_set.rx_mcs().support(8), false);
584        assert_eq!(mcs_set.rx_highest_rate(), 0x01ab);
585
586        let ht_ext_cap = ht_cap.ht_ext_cap;
587        let raw_value = ht_ext_cap.0;
588        assert_eq!(raw_value, 0x0306);
589        assert_eq!(ht_ext_cap.pco_transition(), PcoTransitionTime::PCO_5000_USEC);
590        assert_eq!(ht_ext_cap.mcs_feedback(), McsFeedback::BOTH);
591
592        let txbf_cap = ht_cap.txbf_cap;
593        let raw_value = txbf_cap.0;
594        assert_eq!(raw_value, 0x13cbb0c0);
595        assert_eq!(txbf_cap.calibration(), Calibration::RESPOND_INITIATE);
596        assert_eq!(txbf_cap.csi_feedback(), Feedback::IMMEDIATE);
597        assert_eq!(txbf_cap.noncomp_feedback(), Feedback::DELAYED);
598        assert_eq!(txbf_cap.min_grouping(), MinGroup::TWO);
599
600        // human-readable representation
601        assert_eq!(txbf_cap.csi_antennas().to_human(), 2);
602        assert_eq!(txbf_cap.noncomp_steering_ants().to_human(), 3);
603        assert_eq!(txbf_cap.comp_steering_ants().to_human(), 4);
604        assert_eq!(txbf_cap.csi_rows().to_human(), 2);
605        assert_eq!(txbf_cap.chan_estimation().to_human(), 3);
606
607        let asel_cap = ht_cap.asel_cap;
608        assert_eq!(asel_cap.0, 0);
609    }
610
611    #[test]
612    pub fn extended_supported_rates_ok() {
613        let r = parse_extended_supported_rates(&[1, 2, 3][..]).expect("expected Ok");
614        assert_eq!(&[SupportedRate(1), SupportedRate(2), SupportedRate(3)][..], &r[..]);
615    }
616
617    #[test]
618    pub fn extended_supported_rates_empty() {
619        let err = parse_extended_supported_rates(&[][..]).expect_err("expected Err");
620        assert_eq!("Error parsing frame: Empty Extended Supported Rates IE", &err.to_string());
621    }
622
623    #[test]
624    fn ht_operation_ok() {
625        // HtOperation element without Element Id and length
626        #[rustfmt::skip]
627        let raw_body = [
628            99, // primary_channel
629            0xff, 0xfe, 0xff, 0xff, 0xff, // ht_op_info
630            // basic_ht_mcs_set
631            0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
632            0x00, 0x00, 0xab, 0xcd, 0x00, 0x00, 0x00, 0x00,
633        ];
634        let ht_op = parse_ht_operation(&raw_body[..]).expect("valid frame should result in OK");
635
636        assert_eq!(ht_op.primary_channel, 99);
637
638        let ht_op_info = ht_op.ht_op_info;
639        assert_eq!(ht_op_info.secondary_chan_offset(), SecChanOffset::SECONDARY_BELOW);
640        assert_eq!(ht_op_info.sta_chan_width(), StaChanWidth::ANY);
641        assert_eq!(ht_op_info.ht_protection(), HtProtection::TWENTY_MHZ);
642        assert_eq!(ht_op_info.pco_phase(), PcoPhase::FORTY_MHZ);
643
644        let basic_mcs_set = ht_op.basic_ht_mcs_set;
645        assert_eq!(basic_mcs_set.0, 0x00000000_cdab0000_00000000_000000ff);
646    }
647
648    #[test]
649    fn rm_enabled_capabilities_ok() {
650        #[rustfmt::skip]
651        let raw_body = [
652            0x03, 0x00, 0x00, 0x00, 0x02, // rm_enabled_capabilities
653        ];
654
655        let caps =
656            parse_rm_enabled_capabilities(&raw_body[..]).expect("valid frame should result in OK");
657        assert!(caps.link_measurement_enabled());
658        assert!(caps.neighbor_report_enabled());
659        assert!(!caps.lci_azimuth_enabled());
660        assert!(caps.antenna_enabled());
661        assert!(!caps.ftm_range_report_enabled());
662    }
663
664    #[test]
665    fn sec_chan_offset_ok() {
666        let sec_chan_offset =
667            parse_sec_chan_offset(&[3][..]).expect("valid sec chan offset should result in OK");
668        assert_eq!(sec_chan_offset.0, 3);
669    }
670
671    #[test]
672    fn ext_capabilities_ok() {
673        let data = [0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x40];
674        let ext_capabilities = parse_ext_capabilities(&data[..]);
675        assert_variant!(ext_capabilities.ext_caps_octet_1, Some(caps) => {
676            assert!(caps.extended_channel_switching());
677            assert!(!caps.psmp_capability());
678        });
679        assert_variant!(ext_capabilities.ext_caps_octet_2, Some(caps) => {
680            assert!(!caps.civic_location());
681        });
682        assert_variant!(ext_capabilities.ext_caps_octet_3, Some(caps) => {
683            assert!(caps.bss_transition());
684            assert!(!caps.ac_station_count());
685        });
686        assert_eq!(ext_capabilities.remaining, &[0x00, 0x00, 0x00, 0x00, 0x40]);
687    }
688
689    #[test]
690    fn vht_capabilities_ok() {
691        // VhtCapabilities element without Element Id and length
692        #[rustfmt::skip]
693        let raw_body = [
694            0xfe, 0xff, 0xff, 0xff, // VhtCapabilitiesInfo(u32)
695            0xff, 0xaa, 0x00, 0x00, 0x55, 0xff, 0x00, 0x00, // VhtMcsNssSet(u64)
696        ];
697        let vht_cap = parse_vht_capabilities(&raw_body[..]).expect("expected OK from valid frames");
698
699        let cap_info = vht_cap.vht_cap_info;
700        assert_eq!(cap_info.max_mpdu_len(), MaxMpduLen::OCTECTS_11454);
701        assert_eq!(cap_info.link_adapt(), VhtLinkAdaptation::BOTH);
702        let max_ampdu_component = cap_info.max_ampdu_exponent();
703        assert_eq!(max_ampdu_component.to_len(), 1048575);
704
705        let mcs_nss = vht_cap.vht_mcs_nss;
706        assert_eq!(mcs_nss.rx_max_mcs().ss1(), VhtMcsSet::NONE);
707        assert_eq!(mcs_nss.rx_max_mcs().ss7(), VhtMcsSet::UP_TO_9);
708        assert_eq!(mcs_nss.tx_max_mcs().ss1(), VhtMcsSet::UP_TO_8);
709        assert_eq!(mcs_nss.tx_max_mcs().ss7(), VhtMcsSet::NONE);
710
711        assert_eq!(mcs_nss.rx_max_mcs().ss(2), Ok(VhtMcsSet::NONE));
712        assert_eq!(mcs_nss.rx_max_mcs().ss(6), Ok(VhtMcsSet::UP_TO_9));
713        assert_eq!(mcs_nss.tx_max_mcs().ss(2), Ok(VhtMcsSet::UP_TO_8));
714        assert_eq!(mcs_nss.tx_max_mcs().ss(6), Ok(VhtMcsSet::NONE));
715    }
716
717    #[test]
718    fn vht_operation_ok() {
719        // VhtOperation element without Element Id and length
720        #[rustfmt::skip]
721        let raw_body = [
722            231, // vht_cbw(u8)
723            232, // center_freq_seg0(u8)
724            233, // center_freq_seg1(u8)
725            0xff, 0x66, // basic_mcs_nss(VhtMcsNssMap(u16))
726        ];
727        let vht_op = parse_vht_operation(&raw_body[..]).expect("expected OK from valid frames");
728        assert_eq!(231, vht_op.vht_cbw.0);
729        assert_eq!(232, vht_op.center_freq_seg0);
730        assert_eq!(233, vht_op.center_freq_seg1);
731    }
732
733    #[test]
734    fn parse_wpa_ie_ok() {
735        let raw_body: Vec<u8> = vec![
736            0x00, 0x50, 0xf2, // MSFT OUI
737            0x01, 0x01, 0x00, // WPA IE header
738            0x00, 0x50, 0xf2, 0x02, // multicast cipher: AKM
739            0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, // 1 unicast cipher: TKIP
740            0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, // 1 AKM: PSK
741        ];
742        let wpa_ie = parse_vendor_ie(&raw_body[..]).expect("failed to parse wpa vendor ie");
743        assert_variant!(wpa_ie, VendorIe::MsftLegacyWpa(wpa_body) => {
744            parse_wpa_ie(&wpa_body[..]).expect("failed to parse wpa vendor ie")
745        });
746    }
747
748    #[test]
749    fn parse_bad_wpa_ie() {
750        let raw_body: Vec<u8> = vec![
751            0x00, 0x50, 0xf2, // MSFT OUI
752            0x01, 0x01, 0x00, // WPA IE header
753            0x00, 0x50, 0xf2, 0x02, // multicast cipher: AKM
754                  // truncated
755        ];
756        // parse_vendor_ie does not validate the actual wpa ie body, so this
757        // succeeds.
758        let wpa_ie = parse_vendor_ie(&raw_body[..]).expect("failed to parse wpa vendor ie");
759        assert_variant!(wpa_ie, VendorIe::MsftLegacyWpa(wpa_body) => {
760            parse_wpa_ie(&wpa_body[..]).expect_err("parsed truncated wpa ie")
761        });
762    }
763
764    #[test]
765    fn parse_wmm_info_ie_ok() {
766        let raw_body = [
767            0x00, 0x50, 0xf2, // MSFT OUI
768            0x02, 0x00, 0x01, // WMM Info IE header
769            0x80, // QoS Info: U-APSD enabled
770        ];
771        let wmm_info_ie = parse_vendor_ie(&raw_body[..]).expect("expected Ok");
772        assert_variant!(wmm_info_ie, VendorIe::WmmInfo(body) => {
773            assert_variant!(parse_wmm_info(&body[..]), Ok(wmm_info) => {
774                assert_eq!(wmm_info.0, 0x80);
775            })
776        });
777    }
778
779    #[test]
780    fn parse_wmm_info_ie_too_short() {
781        let raw_body = [
782            0x00, 0x50, 0xf2, // MSFT OUI
783            0x02, 0x00, 0x01, // WMM Info IE header
784                  // truncated
785        ];
786        let wmm_info_ie = parse_vendor_ie(&raw_body[..]).expect("expected Ok");
787        assert_variant!(wmm_info_ie, VendorIe::WmmInfo(body) => {
788            parse_wmm_info(&body[..]).expect_err("parsed truncated WMM info ie")
789        });
790    }
791
792    #[test]
793    fn parse_wmm_param_ie_ok() {
794        let raw_body = [
795            0x00, 0x50, 0xf2, // MSFT OUI
796            0x02, 0x01, 0x01, // WMM Param IE header
797            0x80, // QoS Info: U-APSD enabled
798            0x00, // reserved
799            0x03, 0xa4, 0x00, 0x00, // AC_BE Params - ACM no, AIFSN 3, ECWmin/max 4/10, TXOP 0
800            0x27, 0xa4, 0x00, 0x00, // AC_BK Params - ACM no, AIFSN 7, ECWmin/max 4/10, TXOP 0
801            0x42, 0x43, 0x5e, 0x00, // AC_VI Params - ACM no, AIFSN 2, ECWmin/max 3/4, TXOP 94
802            0x62, 0x32, 0x2f, 0x00, // AC_VO Params - ACM no, AIFSN 2, ECWmin/max 2/3, TXOP 47
803        ];
804        let wmm_param_ie = parse_vendor_ie(&raw_body[..]).expect("expected Ok");
805        assert_variant!(wmm_param_ie, VendorIe::WmmParam(body) => {
806            assert_variant!(parse_wmm_param(&body[..]), Ok(wmm_param) => {
807                assert_eq!(wmm_param.wmm_info.0, 0x80);
808                let ac_be = wmm_param.ac_be_params;
809                assert_eq!(ac_be.aci_aifsn.aifsn(), 3);
810                assert_eq!(ac_be.aci_aifsn.acm(), false);
811                assert_eq!(ac_be.aci_aifsn.aci(), 0);
812                assert_eq!(ac_be.ecw_min_max.ecw_min(), 4);
813                assert_eq!(ac_be.ecw_min_max.ecw_max(), 10);
814                assert_eq!({ ac_be.txop_limit }, 0);
815
816                let ac_bk = wmm_param.ac_bk_params;
817                assert_eq!(ac_bk.aci_aifsn.aifsn(), 7);
818                assert_eq!(ac_bk.aci_aifsn.acm(), false);
819                assert_eq!(ac_bk.aci_aifsn.aci(), 1);
820                assert_eq!(ac_bk.ecw_min_max.ecw_min(), 4);
821                assert_eq!(ac_bk.ecw_min_max.ecw_max(), 10);
822                assert_eq!({ ac_bk.txop_limit }, 0);
823
824                let ac_vi = wmm_param.ac_vi_params;
825                assert_eq!(ac_vi.aci_aifsn.aifsn(), 2);
826                assert_eq!(ac_vi.aci_aifsn.acm(), false);
827                assert_eq!(ac_vi.aci_aifsn.aci(), 2);
828                assert_eq!(ac_vi.ecw_min_max.ecw_min(), 3);
829                assert_eq!(ac_vi.ecw_min_max.ecw_max(), 4);
830                assert_eq!({ ac_vi.txop_limit }, 94);
831
832                let ac_vo = wmm_param.ac_vo_params;
833                assert_eq!(ac_vo.aci_aifsn.aifsn(), 2);
834                assert_eq!(ac_vo.aci_aifsn.acm(), false);
835                assert_eq!(ac_vo.aci_aifsn.aci(), 3);
836                assert_eq!(ac_vo.ecw_min_max.ecw_min(), 2);
837                assert_eq!(ac_vo.ecw_min_max.ecw_max(), 3);
838                assert_eq!({ ac_vo.txop_limit }, 47);
839            });
840        });
841    }
842
843    #[test]
844    fn parse_wmm_param_ie_too_short() {
845        let raw_body = [
846            0x00, 0x50, 0xf2, // MSFT OUI
847            0x02, 0x01, 0x01, // WMM Param IE header
848            0x80, // QoS Info: U-APSD enabled
849            0x00, // reserved
850                  // truncated
851        ];
852        let wmm_param_ie = parse_vendor_ie(&raw_body[..]).expect("expected Ok");
853        assert_variant!(wmm_param_ie, VendorIe::WmmParam(body) => {
854            parse_wmm_param(&body[..]).expect_err("parsed truncated WMM param ie")
855        });
856    }
857
858    #[test]
859    fn parse_unknown_msft_ie() {
860        let raw_body: Vec<u8> = vec![
861            0x00, 0x50, 0xf2, // MSFT OUI
862            0xff, 0x01, 0x00, // header with unknown vendor specific IE type
863            0x00, 0x50, 0xf2, 0x02, // multicast cipher: AKM
864            0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, // 1 unicast cipher: TKIP
865            0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, // 1 AKM: PSK
866        ];
867        let ie = parse_vendor_ie(&raw_body[..]).expect("failed to parse ie");
868        assert_variant!(ie, VendorIe::Unknown { .. });
869    }
870
871    #[test]
872    fn parse_unknown_vendor_ie() {
873        let raw_body: Vec<u8> = vec![0x00, 0x12, 0x34]; // Made up OUI
874        let ie = parse_vendor_ie(&raw_body[..]).expect("failed to parse wpa vendor ie");
875        assert_variant!(ie, VendorIe::Unknown { .. });
876    }
877
878    #[test]
879    fn to_and_from_fidl_ht_cap() {
880        fidl_ieee80211::HtCapabilities {
881            bytes: fake_ht_capabilities().as_bytes().try_into().expect("HT Cap to FIDL"),
882        };
883        let fidl =
884            fidl_ieee80211::HtCapabilities { bytes: [0; fidl_ieee80211::HT_CAP_LEN as usize] };
885        assert!(parse_ht_capabilities(&fidl.bytes[..]).is_ok());
886    }
887
888    #[test]
889    fn to_and_from_fidl_vht_cap() {
890        fidl_ieee80211::VhtCapabilities {
891            bytes: fake_vht_capabilities().as_bytes().try_into().expect("VHT Cap to FIDL"),
892        };
893        let fidl =
894            fidl_ieee80211::VhtCapabilities { bytes: [0; fidl_ieee80211::VHT_CAP_LEN as usize] };
895        assert!(parse_vht_capabilities(&fidl.bytes[..]).is_ok());
896    }
897
898    #[test]
899    fn to_and_from_fidl_ht_op() {
900        fidl_ieee80211::HtOperation {
901            bytes: fake_ht_operation().as_bytes().try_into().expect("HT Op to FIDL"),
902        };
903        let fidl = fidl_ieee80211::HtOperation { bytes: [0; fidl_ieee80211::HT_OP_LEN as usize] };
904        assert!(parse_ht_operation(&fidl.bytes[..]).is_ok());
905    }
906
907    #[test]
908    fn to_and_from_fidl_vht_op() {
909        fidl_ieee80211::VhtOperation {
910            bytes: fake_vht_operation().as_bytes().try_into().expect("VHT Op to FIDL"),
911        };
912        let fidl = fidl_ieee80211::VhtOperation { bytes: [0; fidl_ieee80211::VHT_OP_LEN as usize] };
913        assert!(parse_vht_operation(&fidl.bytes[..]).is_ok());
914    }
915}