|
| 1 | +//! Wi-Fi Easy Connect (DPP) support |
| 2 | +//! |
| 3 | +//! To use this feature, you must add CONFIG_WPA_DPP_SUPPORT=y to your sdkconfig. |
| 4 | +
|
| 5 | +use ::log::*; |
| 6 | + |
| 7 | +use std::ffi::{c_char, CStr, CString}; |
| 8 | +use std::fmt::Write; |
| 9 | +use std::ops::Deref; |
| 10 | +use std::ptr; |
| 11 | +use std::sync::mpsc::{Receiver, sync_channel, SyncSender}; |
| 12 | +use embedded_svc::wifi::{ClientConfiguration, Configuration, Wifi}; |
| 13 | +use esp_idf_sys::*; |
| 14 | +use esp_idf_sys::EspError; |
| 15 | +use crate::private::common::Newtype; |
| 16 | +use crate::private::mutex; |
| 17 | +use crate::wifi::EspWifi; |
| 18 | + |
| 19 | +static EVENTS_TX: mutex::Mutex<Option<SyncSender<DppEvent>>> = |
| 20 | + mutex::Mutex::wrap(mutex::RawMutex::new(), None); |
| 21 | + |
| 22 | +pub struct EspDppBootstrapper<'d, 'w> { |
| 23 | + wifi: &'d mut EspWifi<'w>, |
| 24 | + events_rx: Receiver<DppEvent>, |
| 25 | +} |
| 26 | + |
| 27 | +impl<'d, 'w> EspDppBootstrapper<'d, 'w> { |
| 28 | + pub fn new(wifi: &'d mut EspWifi<'w>) -> Result<Self, EspError> { |
| 29 | + if wifi.is_started()? { |
| 30 | + wifi.disconnect()?; |
| 31 | + wifi.stop()?; |
| 32 | + } |
| 33 | + |
| 34 | + Self::init(wifi) |
| 35 | + } |
| 36 | + |
| 37 | + fn init(wifi: &'d mut EspWifi<'w>) -> Result<Self, EspError> { |
| 38 | + let (events_tx, events_rx) = sync_channel(1); |
| 39 | + let mut dpp_event_relay = EVENTS_TX.lock(); |
| 40 | + *dpp_event_relay = Some(events_tx); |
| 41 | + drop(dpp_event_relay); |
| 42 | + esp!(unsafe { esp_supp_dpp_init(Some(Self::dpp_event_cb_unsafe)) })?; |
| 43 | + Ok(Self { |
| 44 | + wifi, |
| 45 | + events_rx, |
| 46 | + }) |
| 47 | + } |
| 48 | + |
| 49 | + /// Generate a QR code that can be scanned by a mobile phone or other configurator |
| 50 | + /// to securely provide us with the Wi-Fi credentials. Must invoke a listen API on the returned |
| 51 | + /// bootstrapped instance (e.g. [EspDppBootstrapped::listen_once]) or scanning the |
| 52 | + /// QR code will not be able to deliver the credentials to us. |
| 53 | + /// |
| 54 | + /// Important implementation notes: |
| 55 | + /// |
| 56 | + /// 1. You must provide _all_ viable channels that the AP could be using |
| 57 | + /// in order to successfully acquire credentials! For example, in the US, you can use |
| 58 | + /// `(1..=11).collect()`. |
| 59 | + /// |
| 60 | + /// 2. The WiFi driver will be forced started and with a default STA config unless the |
| 61 | + /// state is set-up ahead of time. It's unclear if the AuthMethod that you select |
| 62 | + /// for this STA config affects the results. |
| 63 | + pub fn gen_qrcode<'b>( |
| 64 | + &'b mut self, |
| 65 | + channels: &[u8], |
| 66 | + key: Option<&[u8; 32]>, |
| 67 | + associated_data: Option<&[u8]> |
| 68 | + ) -> Result<EspDppBootstrapped<'b, QrCode>, EspError> { |
| 69 | + let mut channels_str = channels.into_iter() |
| 70 | + .fold(String::new(), |mut a, c| { |
| 71 | + write!(a, "{c},").unwrap(); |
| 72 | + a |
| 73 | + }); |
| 74 | + channels_str.pop(); |
| 75 | + let channels_cstr = CString::new(channels_str).unwrap(); |
| 76 | + let key_ascii_cstr = key.map(|k| { |
| 77 | + let result = k.iter() |
| 78 | + .fold(String::new(), |mut a, b| { |
| 79 | + write!(a, "{b:02X}").unwrap(); |
| 80 | + a |
| 81 | + }); |
| 82 | + CString::new(result).unwrap() |
| 83 | + }); |
| 84 | + let associated_data_cstr = match associated_data { |
| 85 | + Some(associated_data) => { |
| 86 | + Some(CString::new(associated_data) |
| 87 | + .map_err(|_| { |
| 88 | + warn!("associated data contains an embedded NUL character!"); |
| 89 | + EspError::from_infallible::<ESP_ERR_INVALID_ARG>() |
| 90 | + })?) |
| 91 | + } |
| 92 | + None => None, |
| 93 | + }; |
| 94 | + debug!("dpp_bootstrap_gen..."); |
| 95 | + esp!(unsafe { |
| 96 | + esp_supp_dpp_bootstrap_gen( |
| 97 | + channels_cstr.as_ptr(), |
| 98 | + dpp_bootstrap_type_DPP_BOOTSTRAP_QR_CODE, |
| 99 | + key_ascii_cstr.map_or_else(ptr::null, |x| x.as_ptr()), |
| 100 | + associated_data_cstr.map_or_else(ptr::null, |x| x.as_ptr())) |
| 101 | + })?; |
| 102 | + let event = self.events_rx.recv() |
| 103 | + .map_err(|_| { |
| 104 | + warn!("Internal error receiving event!"); |
| 105 | + EspError::from_infallible::<ESP_ERR_INVALID_STATE>() |
| 106 | + })?; |
| 107 | + debug!("dpp_bootstrap_gen got: {event:?}"); |
| 108 | + match event { |
| 109 | + DppEvent::UriReady(qrcode) => { |
| 110 | + // Bit of a hack to put the wifi driver in the correct mode. |
| 111 | + self.ensure_config_and_start()?; |
| 112 | + Ok(EspDppBootstrapped::<QrCode> { |
| 113 | + events_rx: &self.events_rx, |
| 114 | + data: QrCode(qrcode), |
| 115 | + }) |
| 116 | + } |
| 117 | + _ => { |
| 118 | + warn!("Got unexpected event: {event:?}"); |
| 119 | + Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>()) |
| 120 | + }, |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + fn ensure_config_and_start(&mut self) -> Result<ClientConfiguration, EspError> { |
| 125 | + let operating_config = match self.wifi.get_configuration()? { |
| 126 | + Configuration::Client(c) => c, |
| 127 | + _ => { |
| 128 | + let fallback_config = ClientConfiguration::default(); |
| 129 | + self.wifi.set_configuration(&Configuration::Client(fallback_config.clone()))?; |
| 130 | + fallback_config |
| 131 | + }, |
| 132 | + }; |
| 133 | + if !self.wifi.is_started()? { |
| 134 | + self.wifi.start()?; |
| 135 | + } |
| 136 | + Ok(operating_config) |
| 137 | + } |
| 138 | + |
| 139 | + unsafe extern "C" fn dpp_event_cb_unsafe( |
| 140 | + evt: esp_supp_dpp_event_t, |
| 141 | + data: *mut ::core::ffi::c_void |
| 142 | + ) { |
| 143 | + debug!("dpp_event_cb_unsafe: evt={evt}"); |
| 144 | + let event = match evt { |
| 145 | + esp_supp_dpp_event_t_ESP_SUPP_DPP_URI_READY => { |
| 146 | + DppEvent::UriReady(CStr::from_ptr(data as *mut c_char).to_str().unwrap().into()) |
| 147 | + }, |
| 148 | + esp_supp_dpp_event_t_ESP_SUPP_DPP_CFG_RECVD => { |
| 149 | + let config = data as *mut wifi_config_t; |
| 150 | + // TODO: We're losing pmf_cfg.required=true setting due to missing |
| 151 | + // information in ClientConfiguration. |
| 152 | + DppEvent::ConfigurationReceived(Newtype((*config).sta).into()) |
| 153 | + }, |
| 154 | + esp_supp_dpp_event_t_ESP_SUPP_DPP_FAIL => { |
| 155 | + DppEvent::Fail(EspError::from(data as esp_err_t).unwrap()) |
| 156 | + } |
| 157 | + _ => panic!(), |
| 158 | + }; |
| 159 | + dpp_event_cb(event) |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +fn dpp_event_cb(event: DppEvent) { |
| 164 | + match EVENTS_TX.lock().deref() { |
| 165 | + Some(tx) => { |
| 166 | + debug!("Sending: {event:?}"); |
| 167 | + if let Err(e) = tx.try_send(event) { |
| 168 | + error!("Cannot relay event: {e}"); |
| 169 | + } |
| 170 | + } |
| 171 | + None => warn!("Got spurious {event:?} ???"), |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | + |
| 176 | +#[derive(Debug)] |
| 177 | +enum DppEvent { |
| 178 | + UriReady(String), |
| 179 | + ConfigurationReceived(ClientConfiguration), |
| 180 | + Fail(EspError), |
| 181 | +} |
| 182 | + |
| 183 | +impl<'d, 'w> Drop for EspDppBootstrapper<'d, 'w> { |
| 184 | + fn drop(&mut self) { |
| 185 | + unsafe { esp_supp_dpp_deinit() }; |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +pub struct EspDppBootstrapped<'d, T> { |
| 190 | + events_rx: &'d Receiver<DppEvent>, |
| 191 | + pub data: T, |
| 192 | +} |
| 193 | + |
| 194 | +#[derive(Debug, Clone)] |
| 195 | +pub struct QrCode(pub String); |
| 196 | + |
| 197 | +impl<'d, T> EspDppBootstrapped<'d, T> { |
| 198 | + pub fn listen_once(&self) -> Result<ClientConfiguration, EspError> { |
| 199 | + esp!(unsafe { esp_supp_dpp_start_listen() })?; |
| 200 | + let event = self.events_rx.recv() |
| 201 | + .map_err(|e| { |
| 202 | + warn!("Internal receive error: {e}"); |
| 203 | + EspError::from_infallible::<ESP_ERR_INVALID_STATE>() |
| 204 | + })?; |
| 205 | + match event { |
| 206 | + DppEvent::ConfigurationReceived(config) => Ok(config), |
| 207 | + DppEvent::Fail(e) => Err(e), |
| 208 | + _ => { |
| 209 | + warn!("Ignoring unexpected event {event:?}"); |
| 210 | + Err(EspError::from_infallible::<ESP_ERR_INVALID_STATE>()) |
| 211 | + } |
| 212 | + } |
| 213 | + } |
| 214 | + |
| 215 | + pub fn listen_forever(&self) -> Result<ClientConfiguration, EspError> { |
| 216 | + loop { |
| 217 | + match self.listen_once() { |
| 218 | + Ok(config) => return Ok(config), |
| 219 | + Err(e) => warn!("DPP error: {e}, trying again..."), |
| 220 | + } |
| 221 | + } |
| 222 | + } |
| 223 | +} |
0 commit comments