1mod akm_algorithm;
14pub mod ap;
15pub mod auth;
16mod block_ack;
17pub mod client;
18mod ddk_converter;
19pub mod device;
20pub mod disconnect;
21pub mod error;
22mod minstrel;
23mod probe_sequence;
24
25use anyhow::{bail, format_err, Error};
26pub use ddk_converter::*;
27use device::DeviceOps;
28use fuchsia_sync::Mutex;
29use futures::channel::mpsc::{self, TrySendError};
30use futures::channel::oneshot;
31use futures::{select, Future, StreamExt};
32use log::info;
33use std::sync::Arc;
34use std::time::Duration;
35use std::{cmp, fmt};
36use wlan_ffi_transport::{EthernetTxEvent, EthernetTxEventSender, WlanRxEvent, WlanRxEventSender};
37use wlan_fidl_ext::{ResponderExt, SendResultExt};
38use {
39 fidl_fuchsia_wlan_common as fidl_common, fidl_fuchsia_wlan_softmac as fidl_softmac,
40 fuchsia_trace as trace, wlan_trace as wtrace,
41};
42pub use {fidl_fuchsia_wlan_ieee80211 as fidl_ieee80211, wlan_common as common};
43
44trait WlanSoftmacBandCapabilityExt {
55 fn basic_rates(&self) -> Option<&[u8]>;
57
58 fn operating_channels(&self) -> Option<&[u8]>;
60}
61
62impl WlanSoftmacBandCapabilityExt for fidl_softmac::WlanSoftmacBandCapability {
63 fn basic_rates(&self) -> Option<&[u8]> {
64 match (&self.basic_rates, (&self.basic_rate_count, &self.basic_rate_list)) {
65 (Some(basic_rates), _) => Some(basic_rates),
67 (None, (Some(n), Some(basic_rates))) => {
68 Some(&basic_rates[..cmp::min(usize::from(*n), basic_rates.len())])
69 }
70 _ => None,
71 }
72 }
73
74 fn operating_channels(&self) -> Option<&[u8]> {
75 match (
76 &self.operating_channels,
77 (&self.operating_channel_count, &self.operating_channel_list),
78 ) {
79 (Some(operating_channels), _) => Some(operating_channels),
81 (None, (Some(n), Some(operating_channels))) => {
82 Some(&operating_channels[..cmp::min(usize::from(*n), operating_channels.len())])
83 }
84 _ => None,
85 }
86 }
87}
88
89trait WlanTxPacketExt {
90 fn template(mac_frame: Vec<u8>) -> Self;
91}
92
93impl WlanTxPacketExt for fidl_softmac::WlanTxPacket {
94 fn template(mac_frame: Vec<u8>) -> Self {
95 fidl_softmac::WlanTxPacket {
96 mac_frame,
97 info: fidl_softmac::WlanTxInfo {
101 tx_flags: 0,
102 valid_fields: 0,
103 tx_vector_idx: 0,
104 phy: fidl_common::WlanPhyType::Dsss,
105 channel_bandwidth: fidl_common::ChannelBandwidth::Cbw20,
106 mcs: 0,
107 },
108 }
109 }
110}
111
112pub trait MlmeImpl {
113 type Config;
114 type Device: DeviceOps;
115 type TimerEvent;
116 fn new(
117 config: Self::Config,
118 device: Self::Device,
119 scheduler: common::timer::Timer<Self::TimerEvent>,
120 ) -> impl Future<Output = Result<Self, Error>>
121 where
122 Self: Sized;
123 fn handle_mlme_request(
124 &mut self,
125 msg: wlan_sme::MlmeRequest,
126 ) -> impl Future<Output = Result<(), Error>>;
127 fn handle_mac_frame_rx(
128 &mut self,
129 bytes: &[u8],
130 rx_info: fidl_softmac::WlanRxInfo,
131 async_id: trace::Id,
132 ) -> impl Future<Output = ()>;
133 fn handle_eth_frame_tx(&mut self, bytes: &[u8], async_id: trace::Id) -> Result<(), Error>;
134 fn handle_scan_complete(
135 &mut self,
136 status: zx::Status,
137 scan_id: u64,
138 ) -> impl Future<Output = ()>;
139 fn handle_timeout(&mut self, event: Self::TimerEvent) -> impl Future<Output = ()>;
140 fn access_device(&mut self) -> &mut Self::Device;
141}
142
143pub struct MinstrelTimer {
144 timer: wlan_common::timer::Timer<()>,
145 current_timer: Option<common::timer::EventHandle>,
146}
147
148impl minstrel::TimerManager for MinstrelTimer {
149 fn schedule(&mut self, from_now: Duration) {
150 self.current_timer.replace(self.timer.schedule_after(from_now.into(), ()));
151 }
152 fn cancel(&mut self) {
153 self.current_timer.take();
154 }
155}
156
157type MinstrelWrapper = Arc<Mutex<minstrel::MinstrelRateSelector<MinstrelTimer>>>;
158
159#[derive(Clone)]
165pub struct DriverEventSink(mpsc::UnboundedSender<DriverEvent>);
166
167impl DriverEventSink {
168 pub fn new() -> (Self, mpsc::UnboundedReceiver<DriverEvent>) {
169 let (sink, stream) = mpsc::unbounded();
170 (Self(sink), stream)
171 }
172
173 pub fn unbounded_send(
174 &self,
175 driver_event: DriverEvent,
176 ) -> Result<(), TrySendError<DriverEvent>> {
177 self.0.unbounded_send(driver_event)
178 }
179
180 pub fn disconnect(&mut self) {
181 self.0.disconnect()
182 }
183
184 pub fn unbounded_send_or_respond<R>(
185 &self,
186 driver_event: DriverEvent,
187 responder: R,
188 response: R::Response<'_>,
189 ) -> Result<R, anyhow::Error>
190 where
191 R: ResponderExt,
192 {
193 match self.unbounded_send(driver_event) {
194 Err(e) => {
195 let error_string = e.to_string();
196 let event = e.into_inner();
197 let e = format_err!("Failed to queue {}: {}", event, error_string);
198
199 match responder.send(response).format_send_err() {
200 Ok(()) => Err(e),
201 Err(send_error) => Err(send_error.context(e)),
202 }
203 }
204 Ok(()) => Ok(responder),
205 }
206 }
207}
208
209impl EthernetTxEventSender for DriverEventSink {
210 fn unbounded_send(&self, event: EthernetTxEvent) -> Result<(), (String, EthernetTxEvent)> {
211 DriverEventSink::unbounded_send(self, DriverEvent::EthernetTxEvent(event)).map_err(|e| {
212 if let (error, DriverEvent::EthernetTxEvent(event)) =
213 (format!("{:?}", e), e.into_inner())
214 {
215 (error, event)
216 } else {
217 unreachable!();
218 }
219 })
220 }
221}
222
223impl WlanRxEventSender for DriverEventSink {
224 fn unbounded_send(&self, event: WlanRxEvent) -> Result<(), (String, WlanRxEvent)> {
225 DriverEventSink::unbounded_send(self, DriverEvent::WlanRxEvent(event)).map_err(|e| {
226 if let (error, DriverEvent::WlanRxEvent(event)) = (format!("{:?}", e), e.into_inner()) {
227 (error, event)
228 } else {
229 unreachable!();
230 }
231 })
232 }
233}
234
235pub enum DriverEvent {
236 Stop { responder: fidl_softmac::WlanSoftmacIfcBridgeStopBridgedDriverResponder },
238 ScanComplete { status: zx::Status, scan_id: u64 },
240 TxResultReport { tx_result: fidl_common::WlanTxResult },
242 EthernetTxEvent(EthernetTxEvent),
243 WlanRxEvent(WlanRxEvent),
244}
245
246impl fmt::Display for DriverEvent {
247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248 write!(
249 f,
250 "{}",
251 match self {
252 DriverEvent::Stop { .. } => "Stop",
253 DriverEvent::ScanComplete { .. } => "ScanComplete",
254 DriverEvent::TxResultReport { .. } => "TxResultReport",
255 DriverEvent::EthernetTxEvent(EthernetTxEvent { .. }) => "EthernetTxEvent",
256 DriverEvent::WlanRxEvent(WlanRxEvent { .. }) => "WlanRxEvent",
257 }
258 )
259 }
260}
261
262impl fmt::Debug for DriverEvent {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 write!(
269 f,
270 "{}",
271 match self {
272 DriverEvent::Stop { .. } => "Stop",
273 DriverEvent::ScanComplete { .. } => "ScanComplete",
274 DriverEvent::TxResultReport { .. } => "TxResultReport",
275 DriverEvent::EthernetTxEvent(EthernetTxEvent { .. }) => "EthernetTxEvent",
276 DriverEvent::WlanRxEvent(WlanRxEvent { .. }) => "WlanRxEvent",
277 }
278 )
279 }
280}
281
282fn should_enable_minstrel(mac_sublayer: &fidl_common::MacSublayerSupport) -> bool {
283 mac_sublayer.device.tx_status_report_supported && !mac_sublayer.rate_selection_offload.supported
284}
285
286const MINSTREL_UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);
287const MINSTREL_UPDATE_INTERVAL_HW_SIM: std::time::Duration = std::time::Duration::from_millis(83);
294
295pub async fn mlme_main_loop<T: MlmeImpl>(
296 init_sender: oneshot::Sender<()>,
297 config: T::Config,
298 mut device: T::Device,
299 mlme_request_stream: mpsc::UnboundedReceiver<wlan_sme::MlmeRequest>,
300 driver_event_stream: mpsc::UnboundedReceiver<DriverEvent>,
301) -> Result<(), Error> {
302 info!("Starting MLME main loop...");
303 let (minstrel_timer, minstrel_time_stream) = common::timer::create_timer();
304 let minstrel = device.mac_sublayer_support().await.ok().filter(should_enable_minstrel).map(
305 |mac_sublayer_support| {
306 let minstrel = Arc::new(Mutex::new(minstrel::MinstrelRateSelector::new(
307 MinstrelTimer { timer: minstrel_timer, current_timer: None },
308 if mac_sublayer_support.device.is_synthetic {
309 MINSTREL_UPDATE_INTERVAL_HW_SIM
310 } else {
311 MINSTREL_UPDATE_INTERVAL
312 },
313 probe_sequence::ProbeSequence::random_new(),
314 )));
315 device.set_minstrel(minstrel.clone());
316 minstrel
317 },
318 );
319 let (timer, time_stream) = common::timer::create_timer();
320
321 let mlme_impl = T::new(config, device, timer).await.expect("Failed to create MLME.");
324
325 info!("MLME initialization complete!");
326 init_sender.send(()).map_err(|_| format_err!("Failed to signal init complete."))?;
327
328 main_loop_impl(
329 mlme_impl,
330 minstrel,
331 mlme_request_stream,
332 driver_event_stream,
333 time_stream,
334 minstrel_time_stream,
335 )
336 .await
337}
338
339async fn main_loop_impl<T: MlmeImpl>(
343 mut mlme_impl: T,
344 minstrel: Option<MinstrelWrapper>,
345 mut mlme_request_stream: mpsc::UnboundedReceiver<wlan_sme::MlmeRequest>,
347 mut driver_event_stream: mpsc::UnboundedReceiver<DriverEvent>,
350 time_stream: common::timer::EventStream<T::TimerEvent>,
351 minstrel_time_stream: common::timer::EventStream<()>,
352) -> Result<(), Error> {
353 let mut timer_stream = common::timer::make_async_timed_event_stream(time_stream).fuse();
354 let mut minstrel_timer_stream =
355 common::timer::make_async_timed_event_stream(minstrel_time_stream).fuse();
356
357 loop {
358 select! {
359 mlme_request = mlme_request_stream.next() => match mlme_request {
361 Some(req) => {
362 let method_name = req.name();
363 if let Err(e) = mlme_impl.handle_mlme_request(req).await {
364 info!("Failed to handle mlme {} request: {}", method_name, e);
365 }
366 },
367 None => bail!("MLME request stream terminated unexpectedly."),
368 },
369 driver_event = driver_event_stream.next() => match driver_event {
371 Some(event) => match event {
372 DriverEvent::Stop {responder} => {
374 responder.send().format_send_err_with_context("Stop")?;
375 return Ok(())
376 },
377 DriverEvent::ScanComplete { status, scan_id } => {
378 mlme_impl.handle_scan_complete(status, scan_id).await
379 },
380 DriverEvent::TxResultReport { tx_result } => {
381 if let Some(minstrel) = minstrel.as_ref() {
382 minstrel.lock().handle_tx_result_report(&tx_result)
383 }
384 }
385 DriverEvent::EthernetTxEvent(EthernetTxEvent { bytes, async_id, borrowed_operation }) => {
386 wtrace::duration!(c"DriverEvent::EthernetTxEvent");
387 let bytes: &[u8] = unsafe { &*bytes.as_ptr() };
388 match mlme_impl.handle_eth_frame_tx(&bytes[..], async_id) {
389 Ok(()) => borrowed_operation.reply(Ok(())),
390 Err(e) => {
391 info!("Failed to handle eth frame: {}", e);
393 wtrace::async_end_wlansoftmac_tx(async_id, zx::Status::INTERNAL);
394 borrowed_operation.reply(Err(zx::Status::INTERNAL));
395 }
396 }
397 }
398 DriverEvent::WlanRxEvent(WlanRxEvent { bytes, rx_info, async_id }) => {
399 wtrace::duration!(c"DriverEvent::WlanRxEvent");
400 mlme_impl.handle_mac_frame_rx(&bytes[..], rx_info, async_id).await;
401 }
402
403
404 },
405 None => bail!("Driver event stream terminated unexpectedly."),
406 },
407 timed_event = timer_stream.select_next_some() => {
408 mlme_impl.handle_timeout(timed_event.event).await;
409 }
410 _minstrel_timeout = minstrel_timer_stream.select_next_some() => {
411 if let Some(minstrel) = minstrel.as_ref() {
412 minstrel.lock().handle_timeout()
413 }
414 }
415 }
416 }
417}
418
419#[cfg(test)]
420pub mod test_utils {
421 use super::*;
422 use crate::device::FakeDevice;
423 use ieee80211::{MacAddr, MacAddrBytes};
424 use wlan_common::channel;
425 use {fidl_fuchsia_wlan_common as fidl_common, fidl_fuchsia_wlan_mlme as fidl_mlme};
426
427 pub struct FakeMlme {
428 device: FakeDevice,
429 }
430
431 impl MlmeImpl for FakeMlme {
432 type Config = ();
433 type Device = FakeDevice;
434 type TimerEvent = ();
435
436 async fn new(
437 _config: Self::Config,
438 device: Self::Device,
439 _scheduler: wlan_common::timer::Timer<Self::TimerEvent>,
440 ) -> Result<Self, Error> {
441 Ok(Self { device })
442 }
443
444 async fn handle_mlme_request(
445 &mut self,
446 _msg: wlan_sme::MlmeRequest,
447 ) -> Result<(), anyhow::Error> {
448 unimplemented!()
449 }
450
451 async fn handle_mac_frame_rx(
452 &mut self,
453 _bytes: &[u8],
454 _rx_info: fidl_softmac::WlanRxInfo,
455 _async_id: trace::Id,
456 ) {
457 unimplemented!()
458 }
459
460 fn handle_eth_frame_tx(
461 &mut self,
462 _bytes: &[u8],
463 _async_id: trace::Id,
464 ) -> Result<(), anyhow::Error> {
465 unimplemented!()
466 }
467
468 async fn handle_scan_complete(&mut self, _status: zx::Status, _scan_id: u64) {
469 unimplemented!()
470 }
471
472 async fn handle_timeout(&mut self, _event: Self::TimerEvent) {
473 unimplemented!()
474 }
475
476 fn access_device(&mut self) -> &mut Self::Device {
477 &mut self.device
478 }
479 }
480
481 pub(crate) fn fake_wlan_channel() -> channel::Channel {
482 channel::Channel { primary: 1, cbw: channel::Cbw::Cbw20 }
483 }
484
485 #[derive(Copy, Clone, Debug)]
486 pub struct MockWlanRxInfo {
487 pub rx_flags: fidl_softmac::WlanRxInfoFlags,
488 pub valid_fields: fidl_softmac::WlanRxInfoValid,
489 pub phy: fidl_common::WlanPhyType,
490 pub data_rate: u32,
491 pub channel: fidl_common::WlanChannel,
492 pub mcs: u8,
493 pub rssi_dbm: i8,
494 pub snr_dbh: i16,
495 }
496
497 impl MockWlanRxInfo {
498 pub(crate) fn with_channel(channel: fidl_common::WlanChannel) -> Self {
499 Self {
500 valid_fields: fidl_softmac::WlanRxInfoValid::CHAN_WIDTH
501 | fidl_softmac::WlanRxInfoValid::RSSI
502 | fidl_softmac::WlanRxInfoValid::SNR,
503 channel,
504 rssi_dbm: -40,
505 snr_dbh: 35,
506
507 rx_flags: fidl_softmac::WlanRxInfoFlags::empty(),
510 phy: fidl_common::WlanPhyType::Dsss,
511 data_rate: 0,
512 mcs: 0,
513 }
514 }
515 }
516
517 impl From<MockWlanRxInfo> for fidl_softmac::WlanRxInfo {
518 fn from(mock_rx_info: MockWlanRxInfo) -> fidl_softmac::WlanRxInfo {
519 fidl_softmac::WlanRxInfo {
520 rx_flags: mock_rx_info.rx_flags,
521 valid_fields: mock_rx_info.valid_fields,
522 phy: mock_rx_info.phy,
523 data_rate: mock_rx_info.data_rate,
524 channel: mock_rx_info.channel,
525 mcs: mock_rx_info.mcs,
526 rssi_dbm: mock_rx_info.rssi_dbm,
527 snr_dbh: mock_rx_info.snr_dbh,
528 }
529 }
530 }
531
532 pub(crate) fn fake_key(address: MacAddr) -> fidl_mlme::SetKeyDescriptor {
533 fidl_mlme::SetKeyDescriptor {
534 cipher_suite_oui: [1, 2, 3],
535 cipher_suite_type: fidl_ieee80211::CipherSuiteType::from_primitive_allow_unknown(4),
536 key_type: fidl_mlme::KeyType::Pairwise,
537 address: address.to_array(),
538 key_id: 6,
539 key: vec![1, 2, 3, 4, 5, 6, 7],
540 rsc: 8,
541 }
542 }
543
544 pub(crate) fn fake_set_keys_req(address: MacAddr) -> wlan_sme::MlmeRequest {
545 wlan_sme::MlmeRequest::SetKeys(fidl_mlme::SetKeysRequest {
546 keylist: vec![fake_key(address)],
547 })
548 }
549}
550
551#[cfg(test)]
552mod tests {
553 use super::device::FakeDevice;
554 use super::test_utils::FakeMlme;
555 use super::*;
556 use fuchsia_async::TestExecutor;
557 use std::task::Poll;
558 use wlan_common::assert_variant;
559
560 enum Request {
566 Ax { responder: RequestAxResponder },
567 Cx { responder: RequestCxResponder },
568 }
569
570 struct RequestAxResponder {}
571 impl RequestAxResponder {
572 fn send(self) -> Result<(), fidl::Error> {
573 Ok(())
574 }
575 }
576
577 struct RequestCxResponder {}
578 impl RequestCxResponder {
579 fn send(self, _result: Result<u64, u64>) -> Result<(), fidl::Error> {
580 Ok(())
581 }
582 }
583
584 impl ResponderExt for RequestAxResponder {
585 type Response<'a> = ();
586 const REQUEST_NAME: &'static str = stringify!(RequestAx);
587
588 fn send(self, _: Self::Response<'_>) -> Result<(), fidl::Error> {
589 Self::send(self)
590 }
591 }
592
593 impl ResponderExt for RequestCxResponder {
594 type Response<'a> = Result<u64, u64>;
595 const REQUEST_NAME: &'static str = stringify!(RequestCx);
596
597 fn send(self, response: Self::Response<'_>) -> Result<(), fidl::Error> {
598 Self::send(self, response)
599 }
600 }
601
602 #[test]
603 fn unbounded_send_or_respond_with_error_simple() {
604 let (driver_event_sink, _driver_event_stream) = DriverEventSink::new();
605 if let Request::Ax { responder } = (Request::Ax { responder: RequestAxResponder {} }) {
606 let _responder: RequestAxResponder = driver_event_sink
607 .unbounded_send_or_respond(
608 DriverEvent::ScanComplete { status: zx::Status::OK, scan_id: 3 },
609 responder,
610 (),
611 )
612 .unwrap();
613 }
614 }
615
616 #[test]
617 fn unbounded_send_or_respond_with_error_simple_with_error() {
618 let (driver_event_sink, _driver_event_stream) = DriverEventSink::new();
619 if let Request::Cx { responder } = (Request::Cx { responder: RequestCxResponder {} }) {
620 let _responder: RequestCxResponder = driver_event_sink
621 .unbounded_send_or_respond(
622 DriverEvent::ScanComplete { status: zx::Status::IO_REFUSED, scan_id: 0 },
623 responder,
624 Err(10),
625 )
626 .unwrap();
627 }
628 }
629
630 #[fuchsia::test(allow_stalls = false)]
631 async fn start_and_stop_main_loop() {
632 let (fake_device, _fake_device_state) = FakeDevice::new().await;
633 let (device_sink, device_stream) = mpsc::unbounded();
634 let (_mlme_request_sink, mlme_request_stream) = mpsc::unbounded();
635 let (init_sender, mut init_receiver) = oneshot::channel();
636 let mut main_loop = Box::pin(mlme_main_loop::<FakeMlme>(
637 init_sender,
638 (),
639 fake_device,
640 mlme_request_stream,
641 device_stream,
642 ));
643 assert_variant!(TestExecutor::poll_until_stalled(&mut main_loop).await, Poll::Pending);
644 assert_eq!(TestExecutor::poll_until_stalled(&mut init_receiver).await, Poll::Ready(Ok(())));
645
646 let (softmac_ifc_bridge_proxy, mut softmac_ifc_bridge_request_stream) =
649 fidl::endpoints::create_proxy_and_stream::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();
650
651 let mut stop_response_fut = softmac_ifc_bridge_proxy.stop_bridged_driver();
652 assert_variant!(
653 TestExecutor::poll_until_stalled(&mut stop_response_fut).await,
654 Poll::Pending
655 );
656 let Some(Ok(fidl_softmac::WlanSoftmacIfcBridgeRequest::StopBridgedDriver { responder })) =
657 softmac_ifc_bridge_request_stream.next().await
658 else {
659 panic!("Did not receive StopBridgedDriver message");
660 };
661
662 device_sink
663 .unbounded_send(DriverEvent::Stop { responder })
664 .expect("Failed to send stop event");
665 assert_variant!(
666 TestExecutor::poll_until_stalled(&mut main_loop).await,
667 Poll::Ready(Ok(()))
668 );
669 assert_variant!(
670 TestExecutor::poll_until_stalled(&mut stop_response_fut).await,
671 Poll::Ready(Ok(()))
672 );
673 assert!(device_sink.is_closed());
674 }
675}