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
// 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, security::SecurityDescriptor},
    anyhow::format_err,
    fidl_fuchsia_wlan_sme as fidl_sme,
    std::collections::HashSet,
};

#[cfg(target_os = "fuchsia")]
use {anyhow::Context as _, fuchsia_zircon as zx};

/// Compatibility of a BSS with respect to a scanning interface.
///
/// Describes the mutually supported modes of operation between a compatible BSS and a local
/// scanning interface. Here, _compatibility_ refers to the ability to establish a connection.
#[derive(Debug, Clone, PartialEq)]
pub struct Compatibility {
    mutual_security_protocols: HashSet<SecurityDescriptor>,
}

impl Compatibility {
    /// Constructs a `Compatibility` from a set of mutually supported security protocols.
    ///
    /// Returns `None` if the set of mutually supported security protocols is empty, because this
    /// implies incompatibility.
    pub fn try_new(
        mutual_security_protocols: impl IntoIterator<Item = SecurityDescriptor>,
    ) -> Option<Self> {
        let mut mutual_security_protocols = mutual_security_protocols.into_iter();
        let first_security_protocol = mutual_security_protocols.next();
        first_security_protocol.map(|first_security_protocol| Compatibility {
            mutual_security_protocols: Some(first_security_protocol)
                .into_iter()
                .chain(mutual_security_protocols)
                .collect(),
        })
    }

    /// Constructs a `Compatibility` from a set of mutually supported security protocols.
    ///
    /// While this function presents a fallible interface and returns an `Option`, it panics on
    /// failure and never returns `None`. This can be used when `Compatibility` is optional but it
    /// is important to assert success, such as in tests.
    ///
    /// # Panics
    ///
    /// Panics if a `Compatibility` cannot be constructed from the given set of mutually supported
    /// security protocols. This occurs if `Compatibility::try_new` returns `None`.
    pub fn expect_some(
        mutual_security_protocols: impl IntoIterator<Item = SecurityDescriptor>,
    ) -> Option<Self> {
        match Compatibility::try_new(mutual_security_protocols) {
            Some(compatibility) => Some(compatibility),
            None => panic!("compatibility modes 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 TryFrom<fidl_sme::Compatibility> for Compatibility {
    type Error = ();

    fn try_from(compatibility: fidl_sme::Compatibility) -> Result<Self, Self::Error> {
        let fidl_sme::Compatibility { mutual_security_protocols } = compatibility;
        Compatibility::try_new(mutual_security_protocols.into_iter().map(From::from)).ok_or(())
    }
}

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

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

#[derive(Debug, Clone, PartialEq)]
pub struct ScanResult {
    pub compatibility: Option<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::Time,
    pub bss_description: BssDescription,
}

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

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.map(From::from).map(Box::new),
            #[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> {
        #[allow(unused_variables)]
        let fidl_sme::ScanResult { compatibility, timestamp_nanos, bss_description } = scan_result;
        Ok(ScanResult {
            compatibility: compatibility
                .map(|compatibility| *compatibility)
                .map(TryFrom::try_from)
                .transpose()
                .map_err(|_| format_err!("failed to convert FIDL `Compatibility`"))?,
            #[cfg(target_os = "fuchsia")]
            timestamp: zx::Time::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)
}