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
// 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::legacy::IfaceRef,
    fidl_fuchsia_wlan_product_deprecatedclient as deprecated, fidl_fuchsia_wlan_sme as fidl_sme,
    futures::prelude::*,
    tracing::{debug, error},
};

const MAX_CONCURRENT_WLAN_REQUESTS: usize = 1000;

/// Takes in stream of deprecated client requests and handles each one.
pub async fn serve_deprecated_client(
    requests: deprecated::DeprecatedClientRequestStream,
    iface: IfaceRef,
) -> Result<(), fidl::Error> {
    requests
        .try_for_each_concurrent(MAX_CONCURRENT_WLAN_REQUESTS, |req| {
            handle_request(iface.clone(), req)
        })
        .await
}

/// Handles an individual request from the deprecated client API.
async fn handle_request(
    iface: IfaceRef,
    req: deprecated::DeprecatedClientRequest,
) -> Result<(), fidl::Error> {
    match req {
        deprecated::DeprecatedClientRequest::Status { responder } => {
            debug!("Deprecated WLAN client API used for status request");
            let r = status(&iface).await;
            responder.send(&r)
        }
    }
}

/// Produces a status representing the state where no client interface is present.
fn no_client_status() -> deprecated::WlanStatus {
    deprecated::WlanStatus { state: deprecated::State::NoClient, current_ap: None }
}

/// Manages the calling of client SME status and translation into a format that is compatible with
/// the deprecated client API.
async fn status(iface: &IfaceRef) -> deprecated::WlanStatus {
    let iface = match iface.get() {
        Ok(iface) => iface,
        Err(_) => return no_client_status(),
    };

    let status = match iface.sme.status().await {
        Ok(status) => status,
        Err(e) => {
            // An error here indicates that the SME channel is broken.
            error!("Failed to query status: {}", e);
            return no_client_status();
        }
    };

    deprecated::WlanStatus {
        state: convert_state(&status),
        current_ap: extract_current_ap(&status),
    }
}

/// Translates a client SME's status information into a deprecated client state.
fn convert_state(status: &fidl_sme::ClientStatusResponse) -> deprecated::State {
    match status {
        fidl_sme::ClientStatusResponse::Connected(_) => deprecated::State::Associated,
        fidl_sme::ClientStatusResponse::Connecting(_) => deprecated::State::Associating,
        fidl_sme::ClientStatusResponse::Idle(_) => deprecated::State::Disassociated,
    }
}

/// Parses a Client SME's status and extracts AP SSID and RSSI if applicable.
fn extract_current_ap(status: &fidl_sme::ClientStatusResponse) -> Option<Box<deprecated::Ap>> {
    match status {
        fidl_sme::ClientStatusResponse::Connected(serving_ap_info) => {
            let ssid = String::from_utf8_lossy(&serving_ap_info.ssid).to_string();
            let rssi_dbm = serving_ap_info.rssi_dbm;
            Some(Box::new(deprecated::Ap { ssid, rssi_dbm }))
        }
        fidl_sme::ClientStatusResponse::Connecting(_) | fidl_sme::ClientStatusResponse::Idle(_) => {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*, crate::legacy::Iface, fidl::endpoints::create_proxy,
        fidl_fuchsia_wlan_common as fidl_common, fuchsia_async as fasync, futures::task::Poll,
        std::pin::pin, wlan_common::assert_variant,
    };

    struct TestValues {
        iface: IfaceRef,
        sme_stream: fidl_sme::ClientSmeRequestStream,
    }

    fn test_setup() -> TestValues {
        let (sme, server) =
            create_proxy::<fidl_sme::ClientSmeMarker>().expect("failed to create ClientSmeProxy");

        let iface = Iface { sme, iface_id: 0 };
        let iface_ref = IfaceRef::new();
        iface_ref.set_if_empty(iface);

        TestValues {
            iface: iface_ref,
            sme_stream: server.into_stream().expect("failed to create ClientSmeRequestStream"),
        }
    }

    #[fuchsia::test]
    fn test_no_client() {
        let mut exec = fasync::TestExecutor::new();
        let iface = IfaceRef::new();
        let status_fut = status(&iface);
        let mut status_fut = pin!(status_fut);

        // Expect that no client is reported and the AP status information is empty.
        assert_variant!(
            exec.run_until_stalled(&mut status_fut),
            Poll::Ready(deprecated::WlanStatus {
                state: deprecated::State::NoClient,
                current_ap: None,
            })
        );
    }

    #[fuchsia::test]
    fn test_broken_sme() {
        let mut exec = fasync::TestExecutor::new();
        let test_values = test_setup();

        // Drop the SME request stream so that the client request will fail.
        drop(test_values.sme_stream);

        let status_fut = status(&test_values.iface);
        let mut status_fut = pin!(status_fut);

        // Expect that no client is reported and the AP status information is empty.
        assert_variant!(
            exec.run_until_stalled(&mut status_fut),
            Poll::Ready(deprecated::WlanStatus {
                state: deprecated::State::NoClient,
                current_ap: None,
            })
        );
    }

    #[fuchsia::test]
    fn test_disconnected_client() {
        let mut exec = fasync::TestExecutor::new();
        let mut test_values = test_setup();
        let status_fut = status(&test_values.iface);
        let mut status_fut = pin!(status_fut);

        // Expect an SME status request and send back a response indicating that the SME is neither
        // connected nor connecting.
        assert_variant!(exec.run_until_stalled(&mut status_fut), Poll::Pending);
        assert_variant!(
            exec.run_until_stalled(&mut test_values.sme_stream.next()),
            Poll::Ready(Some(Ok(fidl_sme::ClientSmeRequest::Status { responder }))) => {
                responder.send(&fidl_sme::ClientStatusResponse::Idle(fidl_sme::Empty{})).expect("could not send sme response")
            }
        );

        // Expect a disconnected status.
        assert_variant!(
            exec.run_until_stalled(&mut status_fut),
            Poll::Ready(deprecated::WlanStatus {
                state: deprecated::State::Disassociated,
                current_ap: None,
            })
        );
    }

    #[fuchsia::test]
    fn test_connecting_client() {
        let mut exec = fasync::TestExecutor::new();
        let mut test_values = test_setup();
        let status_fut = status(&test_values.iface);
        let mut status_fut = pin!(status_fut);

        // Expect an SME status request and send back a response indicating that the SME is
        // connecting.
        assert_variant!(exec.run_until_stalled(&mut status_fut), Poll::Pending);
        assert_variant!(
                    exec.run_until_stalled(&mut test_values.sme_stream.next()),
                    Poll::Ready(Some(Ok(fidl_sme::ClientSmeRequest::Status { responder }))) => {
                        responder.send(&fidl_sme::ClientStatusResponse::Connecting("test_ssid".as_bytes().to_vec()))
        .expect("could not send sme response")
                    }
                );

        // Expect a connecting status.
        assert_variant!(
            exec.run_until_stalled(&mut status_fut),
            Poll::Ready(deprecated::WlanStatus {
                state: deprecated::State::Associating,
                current_ap: None,
            })
        );
    }

    #[fuchsia::test]
    fn test_connected_client() {
        let mut exec = fasync::TestExecutor::new();
        let mut test_values = test_setup();
        let ssid = "test_ssid";
        let rssi_dbm = -70;
        let status_fut = status(&test_values.iface);
        let mut status_fut = pin!(status_fut);

        // Expect an SME status request and send back a response indicating that the SME is
        // connected.
        assert_variant!(exec.run_until_stalled(&mut status_fut), Poll::Pending);
        assert_variant!(
            exec.run_until_stalled(&mut test_values.sme_stream.next()),
            Poll::Ready(Some(Ok(fidl_sme::ClientSmeRequest::Status { responder }))) => {
                responder.send(&fidl_sme::ClientStatusResponse::Connected(
                    fidl_sme::ServingApInfo{
                        bssid: [0, 0, 0, 0, 0, 0],
                        ssid: ssid.as_bytes().to_vec(),
                        rssi_dbm,
                        snr_db: 0,
                        channel: fidl_common::WlanChannel {
                            primary: 1,
                            cbw: fidl_common::ChannelBandwidth::Cbw20,
                            secondary80: 0,
                        },
                        protection: fidl_sme::Protection::Unknown,
                    })).expect("could not send sme response")
            }
        );

        // Expect a connected status.
        let expected_current_ap =
            Some(Box::new(deprecated::Ap { ssid: ssid.to_string(), rssi_dbm }));
        assert_variant!(
            exec.run_until_stalled(&mut status_fut),
            Poll::Ready(deprecated::WlanStatus {
                state: deprecated::State::Associated,
                current_ap,
            }) => {
                assert_eq!(current_ap, expected_current_ap);
            }
        );
    }
}