wlan_common/
scan.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::bss::BssDescription;
use crate::mac::MacRole;
use crate::security::SecurityDescriptor;
use anyhow::format_err;
use fidl_fuchsia_wlan_sme as fidl_sme;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::error;
use std::fmt::{self, Display, Formatter};

#[cfg(target_os = "fuchsia")]
use anyhow::Context as _;

/// The compatibility of a BSS with respect to a scanning interface.
///
/// Describes the possible configurations for connection to a compatible BSS or disjoint features
/// that prevent a connection to an incompatible BSS. Here, _compatibility_ refers to the ability
/// to establish a connection.
///
/// When compatibility is `Err` for a BSS, then the scanning interface cannot establish a
/// connection.
pub type Compatibility = Result<Compatible, Incompatible>;

pub trait CompatibilityExt: Sized {
    fn try_from_fidl(
        compatibility: fidl_sme::Compatibility,
    ) -> Result<Self, fidl_sme::Compatibility>;

    fn into_fidl(self) -> fidl_sme::Compatibility;
}

impl CompatibilityExt for Compatibility {
    fn try_from_fidl(
        compatibility: fidl_sme::Compatibility,
    ) -> Result<Self, fidl_sme::Compatibility> {
        match compatibility {
            fidl_sme::Compatibility::Compatible(compatible) => Compatible::try_from(compatible)
                .map(Ok)
                .map_err(fidl_sme::Compatibility::Compatible),
            fidl_sme::Compatibility::Incompatible(incompatible) => {
                Incompatible::try_from(incompatible)
                    .map(Err)
                    .map_err(fidl_sme::Compatibility::Incompatible)
            }
        }
    }

    fn into_fidl(self) -> fidl_sme::Compatibility {
        match self {
            Ok(compatible) => fidl_sme::Compatibility::Compatible(compatible.into()),
            Err(incompatible) => fidl_sme::Compatibility::Incompatible(incompatible.into()),
        }
    }
}

/// Supported configurations for a compatible BSS with respect to a scanning interface.
///
/// Describes the mutually supported features between a compatible BSS and a local scanning
/// interface that can be negotiated and/or used to establish a connection.
#[derive(Debug, Clone, PartialEq)]
pub struct Compatible {
    mutual_security_protocols: HashSet<SecurityDescriptor>,
}

impl Compatible {
    /// Constructs a `Compatible` from mutually supported features.
    ///
    /// Returns `None` if any set of mutually supported features is empty, because this implies
    /// incompatibility.
    ///
    /// Note that the features considered by `Compatible` depend on the needs of downstream code
    /// and may change. This function accepts parameters that represent only these features, which
    /// may be as few in number as one and may grow to many.
    pub fn try_from_features(
        mutual_security_protocols: impl IntoIterator<Item = SecurityDescriptor>,
    ) -> Option<Self> {
        let mutual_security_protocols: HashSet<_> = mutual_security_protocols.into_iter().collect();
        if mutual_security_protocols.is_empty() {
            None
        } else {
            Some(Compatible { mutual_security_protocols })
        }
    }

    /// Constructs a [`Compatibility`] from a `Compatible` from mutually supported features.
    ///
    /// While this function presents a fallible interface and returns a `Compatibility` (`Result`),
    /// it panics on failure and never returns `Err`. This can be used when a `Compatibility` is
    /// needed but it is important to assert that it is compatible (`Ok`), most notably in tests.
    ///
    /// See [`Compatible::try_from_features`].
    ///
    /// # Panics
    ///
    /// Panics if a `Compatible` cannot be constructed from the given mutually supported features.
    /// This occurs if `Compatible::try_from_features` returns `None`.
    pub fn expect_ok(
        mutual_security_protocols: impl IntoIterator<Item = SecurityDescriptor>,
    ) -> Compatibility {
        match Compatible::try_from_features(mutual_security_protocols) {
            Some(compatibility) => Ok(compatibility),
            None => panic!("mutual modes of operation are absent and imply incompatiblity"),
        }
    }

    /// Gets the set of mutually supported security protocols.
    ///
    /// This set represents the intersection of security protocols supported by the BSS and the
    /// scanning interface. In this context, this set is never empty, as that would imply
    /// incompatibility.
    pub fn mutual_security_protocols(&self) -> &HashSet<SecurityDescriptor> {
        &self.mutual_security_protocols
    }
}

impl From<Compatible> for fidl_sme::Compatible {
    fn from(compatibility: Compatible) -> Self {
        let Compatible { mutual_security_protocols } = compatibility;
        fidl_sme::Compatible {
            mutual_security_protocols: mutual_security_protocols
                .into_iter()
                .map(From::from)
                .collect(),
        }
    }
}

impl From<Compatible> for HashSet<SecurityDescriptor> {
    fn from(compatibility: Compatible) -> Self {
        compatibility.mutual_security_protocols
    }
}

impl TryFrom<fidl_sme::Compatible> for Compatible {
    type Error = fidl_sme::Compatible;

    fn try_from(compatibility: fidl_sme::Compatible) -> Result<Self, Self::Error> {
        let fidl_sme::Compatible { mutual_security_protocols } = compatibility;
        match Compatible::try_from_features(
            mutual_security_protocols.iter().cloned().map(From::from),
        ) {
            Some(compatible) => Ok(compatible),
            None => Err(fidl_sme::Compatible { mutual_security_protocols }),
        }
    }
}

// TODO(https://fxbug.dev/384797729): Consider supported channels and data rates.
/// Unsupported configurations for an incompatible BSS with respect to a scanning interface.
///
/// Describes disjoint features between an incompatible BSS and a local scanning interface that
/// prevent establishing a connection. Information about modes of operation is best effort;
/// `Incompatible` may provide no additional information at all.
#[derive(Debug, Clone, PartialEq)]
pub struct Incompatible {
    description: Cow<'static, str>,
    disjoint_security_protocols: Option<HashMap<SecurityDescriptor, MacRole>>,
}

impl Incompatible {
    /// Constructs an `Incompatible` from a description with no feature information.
    pub fn from_description(description: impl Into<Cow<'static, str>>) -> Self {
        Incompatible { description: description.into(), disjoint_security_protocols: None }
    }

    /// Constructs an `Incompatible` from a description and disjoint features.
    ///
    /// Returns `None` if any given features are **not** disjoint. For example, `None` is returned
    /// if a security protocol appears more than once with differing roles, because this implies
    /// compatibility (a mutually supported security protocol).
    ///
    /// Note that the features considered by `Incompatible` depend on the needs of downstream code
    /// and may change. This function accepts parameters that represent only these features, which
    /// may be as few in number as one and may grow to many.
    pub fn try_from_features(
        description: impl Into<Cow<'static, str>>,
        disjoint_security_protocols: Option<
            impl IntoIterator<Item = (SecurityDescriptor, MacRole)>,
        >,
    ) -> Option<Self> {
        disjoint_security_protocols
            .map(|disjoint_security_protocols| {
                let mut unique_security_protocols = HashMap::new();
                for (descriptor, role) in disjoint_security_protocols {
                    if let Some(previous) = unique_security_protocols.insert(descriptor, role) {
                        if role != previous {
                            return Err(role);
                        }
                    }
                }
                Ok(unique_security_protocols)
            })
            .transpose()
            .ok()
            .map(move |disjoint_security_protocols| Incompatible {
                description: description.into(),
                disjoint_security_protocols,
            })
    }

    /// Constructs a [`Compatibility`] from an `Incompatible` with no feature information.
    pub const fn unknown() -> Compatibility {
        Err(Incompatible {
            description: Cow::Borrowed("unknown"),
            disjoint_security_protocols: None,
        })
    }

    /// Constructs a [`Compatibility`] from an `Incompatible` from disjoint features.
    ///
    /// While this function presents a fallible interface and returns a `Compatibility` (`Result`),
    /// it panics on failure and never returns `Ok`. This can be used when a `Compatibility` is
    /// needed but it is important to assert that it is incompatible (`Err`), most notably in tests.
    ///
    /// See [`Incompatible::try_from_features`].
    ///
    /// # Panics
    ///
    /// Panics if an `Incompatible` cannot be constructed from the given disjoint features. This
    /// occurs if `Incompatible::try_from_features` returns `None`.
    pub fn expect_err(
        description: impl Into<Cow<'static, str>>,
        disjoint_security_protocols: Option<
            impl IntoIterator<Item = (SecurityDescriptor, MacRole)>,
        >,
    ) -> Compatibility {
        match Incompatible::try_from_features(description, disjoint_security_protocols) {
            Some(incompatible) => Err(incompatible),
            None => panic!("disjoint modes of operation intersect and imply compatiblity"),
        }
    }

    /// Gets the sets of disjoint security protocols, if any.
    ///
    /// The disjoint sets are represented as a map from `SecurityDescriptor` to `MacRole`, where
    /// each security protocol is supported only by one station in a particular role (e.g., client
    /// and AP). There is a disjoint set of security protocols for each unique role in the map.
    ///
    /// Returns `None` if no security protocol incompatibility has been detected. When `Some` but
    /// with an empty map, security protocol support is considered incompatible even though the
    /// protocols are not described.
    pub fn disjoint_security_protocols(&self) -> Option<&HashMap<SecurityDescriptor, MacRole>> {
        self.disjoint_security_protocols.as_ref()
    }
}

impl Display for Incompatible {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(formatter, "incompatibility detected")?;
        if !self.description.is_empty() {
            write!(formatter, ": {}", self.description)?;
        }
        if let Some(disjoint_security_protocols) = self.disjoint_security_protocols() {
            let (client_security_protocols, bss_security_protocols) = disjoint_security_protocols
                .iter()
                .partition::<Vec<_>, _>(|(_, role)| matches!(role, MacRole::Client));
            write!(
                formatter,
                ": supported BSS vs. client security protocols: {:?} vs. {:?}",
                bss_security_protocols, client_security_protocols,
            )?;
        }
        write!(formatter, ".")
    }
}

impl error::Error for Incompatible {}

impl From<Incompatible> for fidl_sme::Incompatible {
    fn from(incompatible: Incompatible) -> Self {
        let Incompatible { description, disjoint_security_protocols } = incompatible;
        fidl_sme::Incompatible {
            description: description.into(),
            disjoint_security_protocols: disjoint_security_protocols.map(
                |disjoint_security_protocols| {
                    disjoint_security_protocols
                        .into_iter()
                        .map(|(security_protocol, role)| fidl_sme::DisjointSecurityProtocol {
                            protocol: security_protocol.into(),
                            role: role.into(),
                        })
                        .collect()
                },
            ),
        }
    }
}

impl TryFrom<fidl_sme::Incompatible> for Incompatible {
    type Error = fidl_sme::Incompatible;

    fn try_from(incompatible: fidl_sme::Incompatible) -> Result<Self, Self::Error> {
        let fidl_sme::Incompatible { description, disjoint_security_protocols } = incompatible;
        match disjoint_security_protocols
            .as_ref()
            .map(|disjoint_security_protocols| {
                disjoint_security_protocols
                    .iter()
                    .copied()
                    .map(|fidl_sme::DisjointSecurityProtocol { protocol, role }| {
                        MacRole::try_from(role).map(|role| (protocol.into(), role))
                    })
                    .collect::<Result<Vec<_>, _>>()
            })
            .transpose()
        {
            Ok(converted_security_protocols) => {
                Incompatible::try_from_features(description.clone(), converted_security_protocols)
                    .ok_or_else(|| fidl_sme::Incompatible {
                        description,
                        disjoint_security_protocols,
                    })
            }
            Err(_) => Err(fidl_sme::Incompatible { description, disjoint_security_protocols }),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ScanResult {
    pub compatibility: Compatibility,
    // Time of the scan result relative to when the system was powered on.
    // See https://fuchsia.dev/fuchsia-src/concepts/time/language_support?hl=en#monotonic_time
    #[cfg(target_os = "fuchsia")]
    pub timestamp: zx::MonotonicInstant,
    pub bss_description: BssDescription,
}

impl ScanResult {
    pub fn is_compatible(&self) -> bool {
        self.compatibility.is_ok()
    }
}

impl From<ScanResult> for fidl_sme::ScanResult {
    fn from(scan_result: ScanResult) -> fidl_sme::ScanResult {
        let ScanResult {
            compatibility,
            #[cfg(target_os = "fuchsia")]
            timestamp,
            bss_description,
        } = scan_result;
        fidl_sme::ScanResult {
            compatibility: compatibility.into_fidl(),
            #[cfg(target_os = "fuchsia")]
            timestamp_nanos: timestamp.into_nanos(),
            #[cfg(not(target_os = "fuchsia"))]
            timestamp_nanos: 0,
            bss_description: bss_description.into(),
        }
    }
}

impl TryFrom<fidl_sme::ScanResult> for ScanResult {
    type Error = anyhow::Error;

    fn try_from(scan_result: fidl_sme::ScanResult) -> Result<ScanResult, Self::Error> {
        let fidl_sme::ScanResult { compatibility, timestamp_nanos, bss_description } = scan_result;
        Ok(ScanResult {
            compatibility: Compatibility::try_from_fidl(compatibility)
                .map_err(|_| format_err!("failed to convert FIDL `Compatibility`"))?,
            #[cfg(target_os = "fuchsia")]
            timestamp: zx::MonotonicInstant::from_nanos(timestamp_nanos),
            bss_description: bss_description.try_into()?,
        })
    }
}

/// Creates a VMO containing FIDL-encoded scan results.
#[cfg(target_os = "fuchsia")]
pub fn write_vmo(results: Vec<fidl_sme::ScanResult>) -> Result<fidl::Vmo, anyhow::Error> {
    let bytes =
        fidl::persist(&fidl_sme::ScanResultVector { results }).context("encoding scan results")?;
    let vmo = fidl::Vmo::create(bytes.len() as u64).context("creating VMO for scan results")?;
    vmo.write(&bytes, 0).context("writing scan results to VMO")?;
    Ok(vmo)
}

/// Reads FIDL-encoded scan results from a VMO.
#[cfg(target_os = "fuchsia")]
pub fn read_vmo(vmo: fidl::Vmo) -> Result<Vec<fidl_sme::ScanResult>, anyhow::Error> {
    let size = vmo.get_content_size().context("getting VMO content size")?;
    let bytes = vmo.read_to_vec(0, size).context("reading VMO of scan results")?;
    let scan_result_vector =
        fidl::unpersist::<fidl_sme::ScanResultVector>(&bytes).context("decoding scan results")?;
    Ok(scan_result_vector.results)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn compatible_from_only_empty_is_none() {
        assert!(Compatible::try_from_features([]).is_none());
    }

    #[test]
    fn compatible_from_mutual_security_protocols_is_some() {
        assert!(Compatible::try_from_features([
            SecurityDescriptor::WPA2_PERSONAL,
            SecurityDescriptor::WPA3_PERSONAL,
        ])
        .is_some());
    }

    #[test]
    fn incompatible_from_only_none_is_some() {
        assert!(Incompatible::try_from_features(
            "dunno",
            None::<[(SecurityDescriptor, MacRole); 0]>
        )
        .is_some());
    }

    #[test]
    fn incompatible_from_only_some_empty_is_some() {
        assert!(Incompatible::try_from_features("dunno", Some([])).is_some());
    }

    #[test]
    fn incompatible_from_disjoint_security_protocols_is_some() {
        assert!(Incompatible::try_from_features(
            "dunno",
            Some([
                (SecurityDescriptor::WPA2_PERSONAL, MacRole::Client),
                (SecurityDescriptor::WPA3_PERSONAL, MacRole::Ap),
            ])
        )
        .is_some());
    }

    #[test]
    fn incompatible_from_mutual_security_protocols_is_none() {
        assert!(Incompatible::try_from_features(
            "dunno",
            Some([
                (SecurityDescriptor::WPA3_PERSONAL, MacRole::Client),
                (SecurityDescriptor::WPA3_PERSONAL, MacRole::Ap),
            ])
        )
        .is_none());
    }

    #[test]
    fn fidl_from_compatible_eq_expected() {
        let security_protocol = SecurityDescriptor::OPEN;
        let fidl =
            fidl_sme::Compatible::from(Compatible::try_from_features([security_protocol]).unwrap());
        assert_eq!(
            fidl,
            fidl_sme::Compatible { mutual_security_protocols: vec![security_protocol.into()] },
        );
    }

    #[test]
    fn compatible_try_from_fidl_eq_ok() {
        let security_protocol = SecurityDescriptor::OPEN;
        let compatible = Compatible::try_from(fidl_sme::Compatible {
            mutual_security_protocols: vec![security_protocol.into()],
        });
        assert_eq!(compatible, Ok(Compatible::try_from_features([security_protocol]).unwrap()));
    }

    #[test]
    fn compatible_try_from_fidl_eq_err() {
        let fidl = fidl_sme::Compatible { mutual_security_protocols: vec![] };
        let compatible = Compatible::try_from(fidl.clone());
        assert_eq!(compatible, Err(fidl));
    }

    #[test]
    fn fidl_from_incompatible_eq_expected() {
        let fidl = fidl_sme::Incompatible::from(
            Incompatible::try_from_features(
                "dunno",
                // Only one protocol-role entry is used here, because entries are stored in a
                // `HashMap` and ordering is arbitrary when this is converted into a `Vec` in the
                // FIDL representation. This causes spurious errors, since `[a, b]` does not equal
                // `[b, a]`, though they are semantically equivalent here.
                Some([(SecurityDescriptor::WPA3_PERSONAL, MacRole::Ap)]),
            )
            .unwrap(),
        );
        assert_eq!(
            fidl,
            fidl_sme::Incompatible {
                description: String::from("dunno"),
                disjoint_security_protocols: Some(vec![fidl_sme::DisjointSecurityProtocol {
                    protocol: SecurityDescriptor::WPA3_PERSONAL.into(),
                    role: MacRole::Ap.into(),
                },]),
            },
        );
    }

    #[test]
    fn incompatible_try_from_fidl_eq_expected() {
        let incompatible = Incompatible::try_from(fidl_sme::Incompatible {
            description: String::from("dunno"),
            disjoint_security_protocols: Some(vec![
                fidl_sme::DisjointSecurityProtocol {
                    protocol: SecurityDescriptor::WPA2_PERSONAL.into(),
                    role: MacRole::Client.into(),
                },
                fidl_sme::DisjointSecurityProtocol {
                    protocol: SecurityDescriptor::WPA3_PERSONAL.into(),
                    role: MacRole::Ap.into(),
                },
            ]),
        });
        assert_eq!(
            incompatible,
            Ok(Incompatible::try_from_features(
                "dunno",
                Some([
                    (SecurityDescriptor::WPA2_PERSONAL, MacRole::Client),
                    (SecurityDescriptor::WPA3_PERSONAL, MacRole::Ap),
                ])
            )
            .unwrap()),
        );
    }

    #[test]
    fn fidl_from_compatibility_eq_expected() {
        let security_protocol = SecurityDescriptor::OPEN;
        let fidl = Compatible::expect_ok([security_protocol]).into_fidl();
        assert_eq!(
            fidl,
            fidl_sme::Compatibility::Compatible(fidl_sme::Compatible {
                mutual_security_protocols: vec![security_protocol.into()],
            }),
        );
    }

    #[test]
    fn compatibility_try_from_fidl_eq_ok() {
        let security_protocol = SecurityDescriptor::OPEN;
        let compatibility = Compatibility::try_from_fidl(fidl_sme::Compatibility::Compatible(
            fidl_sme::Compatible { mutual_security_protocols: vec![security_protocol.into()] },
        ));
        assert_eq!(compatibility, Ok(Compatible::expect_ok([security_protocol])));
    }

    #[test]
    fn compatibility_try_from_fidl_eq_err() {
        let fidl = fidl_sme::Compatibility::Compatible(fidl_sme::Compatible {
            mutual_security_protocols: vec![],
        });
        let compatibility = Compatibility::try_from_fidl(fidl.clone());
        assert_eq!(compatibility, Err(fidl));
    }
}