diff --git a/Cargo.lock b/Cargo.lock index bb773708d..1261917c6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1289,6 +1289,7 @@ dependencies = [ "log-server", "num-derive", "num-traits", + "pddb", "rkyv", "smoltcp", "susres", diff --git a/services/com/src/api.rs b/services/com/src/api.rs index b868f445c..036f3b348 100644 --- a/services/com/src/api.rs +++ b/services/com/src/api.rs @@ -3,6 +3,10 @@ // the COM server on the SoC side abstracts much of the EC bus complexity away. pub(crate) const SERVER_NAME_COM: &str = "_COM manager_"; pub use com_rs_ref::serdes::Ipv4Conf; +#[allow(dead_code)] +pub const WF200_PASS_MAX_LEN: usize = 64; +#[allow(dead_code)] +pub const WF200_SSID_MAX_LEN: usize = 32; // extra 30 bytes for the header over 1500 pub const NET_MTU: usize = 1530; diff --git a/services/com/src/lib.rs b/services/com/src/lib.rs index 3e53a1400..1d91e597c 100644 --- a/services/com/src/lib.rs +++ b/services/com/src/lib.rs @@ -380,27 +380,25 @@ impl Com { ) } - pub fn wlan_set_ssid(&mut self, s: &String<1024>) -> Result { + pub fn wlan_set_ssid(&mut self, s: &str) -> Result { use core::fmt::Write; // Enforce WF200 driver API length limit - const WF200_SSID_MAX_LEN: usize = 32; - if s.len() > WF200_SSID_MAX_LEN { + if s.len() > api::WF200_SSID_MAX_LEN { return Err(xous::Error::InvalidString); } - let mut copy: String:: = String::new(); + let mut copy: String::<{api::WF200_SSID_MAX_LEN}> = String::new(); let _ = write!(copy, "{}", s); let buf = Buffer::into_buf(copy).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::WlanSetSSID.to_u32().unwrap()) } - pub fn wlan_set_pass(&mut self, s: &String<1024>) -> Result { + pub fn wlan_set_pass(&mut self, s: &str) -> Result { use core::fmt::Write; // Enforce WF200 driver API length limit - const WF200_PASS_MAX_LEN: usize = 64; - if s.len() > WF200_PASS_MAX_LEN { + if s.len() > api::WF200_PASS_MAX_LEN { return Err(xous::Error::InvalidString); } - let mut copy: String:: = String::new(); + let mut copy: String::<{api::WF200_PASS_MAX_LEN}> = String::new(); let _ = write!(copy, "{}", s); let buf = Buffer::into_buf(copy).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::WlanSetPass.to_u32().unwrap()) @@ -421,14 +419,14 @@ impl Com { ) } - pub fn wlan_status(&mut self) -> Result, xous::Error> { + pub fn wlan_status(&mut self) -> Result { // TODO: how to make this return IP, netmask, gateway, DNS server, and STA MAC? const STATUS_MAX_LEN: usize = 160; let status = xous_ipc::String::::new(); let mut buf = Buffer::into_buf(status).or(Err(xous::Error::InternalError))?; buf.lend_mut(self.conn, Opcode::WlanStatus.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; let response = buf.to_original::, _>().unwrap(); - Ok(response) + Ok(std::string::String::from(response.as_str().expect("status contained non-utf8 characters"))) } pub fn wlan_get_config(&self) -> Result { diff --git a/services/com/src/main.rs b/services/com/src/main.rs index 5eb5cc279..761169231 100644 --- a/services/com/src/main.rs +++ b/services/com/src/main.rs @@ -740,11 +740,19 @@ fn xmain() -> ! { let mut des = StringDes::::new(); match des.decode_u16(&rx_buf) { Ok(status) => { - info!("status: {}", status); + log::debug!("status: {}", status); let status_str = String::::from_str(&status); let _ = buffer.replace(status_str); } - _ => info!("status decode failed"), + _ => { + #[cfg(not(any(target_os = "none", target_os = "xous")))] + { + let status_str = String::::from_str("down"); + let _ = buffer.replace(status_str); + log::info!("replacing status with bogus data"); + } + info!("status decode failed"); + }, }; } Some(Opcode::WlanGetConfig) => { diff --git a/services/net/Cargo.toml b/services/net/Cargo.toml index 289a7f39e..6e0c28028 100644 --- a/services/net/Cargo.toml +++ b/services/net/Cargo.toml @@ -22,6 +22,9 @@ com = {path = "../com"} byteorder = { version = "1.0", default-features = false } trng = {path = "../trng"} +# for automatic SSID management and AP list storage +pddb = {path = "../pddb"} + [dependencies.smoltcp] # ugh. have to reference `main` directly because they haven't pushed a new tag in months, and none # of the worked examples match the actual documentation now. diff --git a/services/net/src/api.rs b/services/net/src/api.rs index 5c1f0419f..b1b1764d6 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -16,6 +16,8 @@ use std::io::Write; pub use smoltcp::wire::Icmpv4DstUnreachable; pub(crate) const SERVER_NAME_NET: &str = "_Middleware Network Server_"; +#[allow(dead_code)] +pub const AP_DICT_NAME: &'static str = "wlan_ap_list"; /// Dispatch opcodes to the Net crate main loop. #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs new file mode 100644 index 000000000..65ce87e72 --- /dev/null +++ b/services/net/src/connection_manager.rs @@ -0,0 +1,99 @@ +use crate::api::*; +use std::sync::Arc; +use core::sync::atomic::{AtomicU32, Ordering}; +use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack, send_message, Message}; +use num_traits::*; +use std::io::Read; + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum ConnectionManagerOpcode { + Run, + Poll, + Stop, + Quit, +} +#[allow(dead_code)] +const POLL_INTERVAL_MS: usize = 10_151; // stagger slightly off of an integer-seconds interval to even out loads + +pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc) { + let tt = ticktimer_server::Ticktimer::new().unwrap(); + let xns = xous_names::XousNames::new().unwrap(); + let mut com = com::Com::new(&xns).unwrap(); + let mut pddb = pddb::Pddb::new(); + let self_cid = xous::connect(sid).unwrap(); + // give the system some time to boot before trying to run this + tt.sleep_ms(POLL_INTERVAL_MS).unwrap(); + + let mut run = true; + send_message(self_cid, Message::new_scalar(ConnectionManagerOpcode::Poll.to_usize().unwrap(), POLL_INTERVAL_MS, 0, 0, 0)).expect("couldn't kick off next poll"); + loop { + let msg = xous::receive_message(sid).unwrap(); + log::debug!("got msg: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(ConnectionManagerOpcode::Run) => msg_scalar_unpack!(msg, poll_interval, _, _, _, { + if !run { + run = true; + send_message(self_cid, Message::new_scalar(ConnectionManagerOpcode::Poll.to_usize().unwrap(), poll_interval, 0, 0, 0)).expect("couldn't kick off next poll"); + } + }), + Some(ConnectionManagerOpcode::Poll) => msg_scalar_unpack!(msg, next_poll, _, _, _, { + if activity_interval.fetch_add(POLL_INTERVAL_MS as u32, Ordering::SeqCst) > POLL_INTERVAL_MS as u32 { + log::info!("wlan activity interval timeout"); + // if the pddb isn't mounted, don't even bother checking -- we can't connect until we have a place to get keys + if pddb.is_mounted() { + // the status check code is going to get refactored, so this is a "bare minimum" check + let status = com.wlan_status().unwrap(); + if status.contains("down") { + log::info!("wlan is not connected, attempting auto-reconnect to known AP list"); + if let Ok(ap_list) = pddb.list_keys(AP_DICT_NAME, None) { + com.wlan_leave().expect("couldn't issue leave command"); // leave the previous config to reset state + // TODO: add an SSID scan phase, so we only try to connect to SSIDs that are currently visible. + // for now, just try every single one as a brute force approach. + for ap in ap_list { + let mut wpa_pw_file = pddb.get(AP_DICT_NAME, &ap, None, false, false, None, Some(||{})).expect("couldn't retrieve AP password"); + let mut wp_pw_raw = [0u8; com::api::WF200_PASS_MAX_LEN]; + if let Ok(readlen) = wpa_pw_file.read(&mut wp_pw_raw) { + let pw = std::str::from_utf8(&wp_pw_raw[..readlen]).expect("password was not valid utf-8"); + com.wlan_set_ssid(&ap).expect("couldn't set SSID"); + com.wlan_set_pass(pw).expect("couldn't set password"); + com.wlan_join().expect("couldn't issue join command"); + } + // this needs to not be a dead-wait loop, but for now the WLAN API doesn't support anything better + tt.sleep_ms(5_000).unwrap(); + if !com.wlan_status().unwrap().contains("down") { + break; + } + } + } else { + log::warn!("Connection manager couldn't access {}, but continuing to poll.", AP_DICT_NAME); + } + } else { + // we're up, reset the interval + activity_interval.store(0, Ordering::SeqCst); + } + } + } + if run { + tt.sleep_ms(next_poll).unwrap(); + send_message(self_cid, Message::new_scalar(ConnectionManagerOpcode::Poll.to_usize().unwrap(), next_poll, 0, 0, 0)).expect("couldn't kick off next poll"); + } + }), + // stop is blocking because we need to ensure the previous poll has finished before moving on, otherwise, + // we could get a double-run condition + Some(ConnectionManagerOpcode::Stop) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + run = false; + xous::return_scalar(msg.sender, 0).expect("couldn't ack stop"); + }), + Some(ConnectionManagerOpcode::Quit) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + xous::return_scalar(msg.sender, 0).unwrap(); + log::warn!("exiting connection manager"); + break; + }), + None => { + log::error!("couldn't convert opcode: {:?}", msg); + } + } + } + unsafe{xous::disconnect(self_cid).ok()}; + xous::destroy_server(sid).unwrap(); +} \ No newline at end of file diff --git a/services/net/src/main.rs b/services/net/src/main.rs index e84090178..eb6bbedfc 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -7,6 +7,7 @@ use num_traits::*; use com::api::{ComIntSources, Ipv4Conf, NET_MTU}; mod device; +mod connection_manager; use xous::{Message, CID, SID, msg_scalar_unpack, msg_blocking_scalar_unpack}; use xous_ipc::Buffer; @@ -182,6 +183,17 @@ fn xmain() -> ! { let sr_cid = xous::connect(net_sid).expect("couldn't create suspend callback connection"); let mut susres = susres::Susres::new(&xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); + // kick off the connection manager thread + let cm_sid = xous::create_server().expect("couldn't create connection manager server"); + let cm_cid = xous::connect(cm_sid).unwrap(); + let activity_interval = Arc::new(AtomicU32::new(0)); + thread::spawn({ + let activity_interval = activity_interval.clone(); + move || { + connection_manager::connection_manager(cm_sid, activity_interval); + } + }); + let mut cid_to_disconnect: Option = None; loop { let mut msg = xous::receive_message(net_sid).unwrap(); @@ -612,6 +624,7 @@ fn xmain() -> ! { } }, ComIntSources::WlanRxReady => { + activity_interval.store(0, Ordering::Relaxed); // reset the activity interval to 0 if let Some(_config) = net_config { if let Some(rxlen) = maybe_rxlen { match iface.device_mut().push_rx_avail(rxlen) { @@ -952,6 +965,8 @@ fn xmain() -> ! { } // clean up our program log::trace!("main loop exit, destroying servers"); + xous::send_message(cm_cid, Message::new_blocking_scalar(connection_manager::ConnectionManagerOpcode::Quit.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't quit connection manager server"); + unsafe{xous::disconnect(cm_cid).ok()}; xns.unregister_server(net_sid).unwrap(); xous::destroy_server(net_sid).unwrap(); log::trace!("quitting"); diff --git a/services/pddb/src/api.rs b/services/pddb/src/api.rs index 3e5d94bb0..8965b9973 100644 --- a/services/pddb/src/api.rs +++ b/services/pddb/src/api.rs @@ -66,6 +66,9 @@ pub(crate) const PDDB_MODAL_NAME: &'static str = "pddb modal"; #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] pub(crate) enum Opcode { + IsMounted, + TryMount, + ListBasis, LatestBasis, /// Note that creating a basis does not automatically open it! diff --git a/services/pddb/src/backend/basis.rs b/services/pddb/src/backend/basis.rs index 4f1ec2cc3..b376aa5ac 100644 --- a/services/pddb/src/backend/basis.rs +++ b/services/pddb/src/backend/basis.rs @@ -261,6 +261,7 @@ impl BasisCache { Some(self.cache.len() - 1) } } + pub(crate) fn basis_count(&self) -> usize {self.cache.len()} /// Adds a dictionary with `name` to: /// - if `basis_name` is None, the most recently opened basis diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index c3df21dda..4e7e42cbb 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -88,6 +88,26 @@ impl Pddb { trng: trng::Trng::new(&xns).unwrap(), } } + pub fn is_mounted(&self) -> bool { + let ret = send_message(self.conn, Message::new_blocking_scalar( + Opcode::IsMounted.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't execute IsMounted query"); + match ret { + xous::Result::Scalar1(code) => { + if code == 0 {false} else {true} + }, + _ => panic!("Internal error"), + } + } + pub fn try_mount(&self) -> bool { + let ret = send_message(self.conn, Message::new_blocking_scalar( + Opcode::TryMount.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't execute IsMounted query"); + match ret { + xous::Result::Scalar1(code) => { + if code == 0 {false} else {true} + }, + _ => panic!("Internal error"), + } + } /// return a list of all open bases pub fn list_basis(&self) -> Vec:: { let list_alloc = PddbBasisList { diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index afd07417d..1e8b302c8 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -406,7 +406,7 @@ struct TokenRecord { #[xous::xous_main] fn xmain() -> ! { log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Debug); + log::set_max_level(log::LevelFilter::Info); log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); @@ -455,105 +455,8 @@ fn xmain() -> ! { // try to mount the PDDB automatically before starting the server if pddb_os.rootkeys_initialized() { tt.sleep_ms(1000).unwrap(); // wait 1 second after boot before attempting to mount, to let the boot screen finish redrawing (cometic issue). - log::info!("Requesting login password"); - let mut done = false; - let mut skip = false; - while !done { - done = pddb_os.try_login(); - if !done { - pddb_os.clear_password(); // clear the bad password entry - modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list"); - modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list"); - match modals.get_radiobutton(t!("pddb.badpass", xous::LANG)) { - Ok(response) => { - if response.as_str() == t!("pddb.yes", xous::LANG) { - done = false; - } else if response.as_str() == t!("pddb.no", xous::LANG) { - done = true; - skip = true; - } else { - panic!("Got unexpected return from radiobutton"); - } - } - _ => panic!("get_radiobutton failed"), - } - } - } - - if !skip { - log::info!("Attempting to mount the PDDB"); - if let Some(sys_basis) = pddb_os.pddb_mount() { - log::info!("PDDB mount operation finished successfully"); - basis_cache.basis_add(sys_basis); - } else { - #[cfg(any(target_os = "none", target_os = "xous"))] - { - log::debug!("PDDB did not mount; requesting format"); - modals.add_list_item(t!("pddb.okay", xous::LANG)).expect("couldn't build radio item list"); - modals.add_list_item(t!("pddb.cancel", xous::LANG)).expect("couldn't build radio item list"); - let do_format: bool; - match modals.get_radiobutton(t!("pddb.requestformat", xous::LANG)) { - Ok(response) => { - if response.as_str() == t!("pddb.okay", xous::LANG) { - do_format = true; - } else if response.as_str() == t!("pddb.cancel", xous::LANG) { - log::info!("PDDB format aborted by user"); - do_format = false; - } else { - panic!("Got unexpected return from radiobutton"); - } - } - _ => panic!("get_radiobutton failed"), - } - if do_format { - let fast: bool; - if false { - modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list"); - modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list"); - match modals.get_radiobutton(t!("pddb.devbypass", xous::LANG)) { - Ok(response) => { - if response.as_str() == t!("pddb.yes", xous::LANG) { - fast = true; - } else if response.as_str() == t!("pddb.no", xous::LANG) { - fast = false; - } else { - panic!("Got unexpected return from radiobutton"); - } - } - _ => panic!("get_radiobutton failed"), - } - } else { - fast = false; - } - - pddb_os.pddb_format(fast, Some(&modals)).expect("couldn't format PDDB"); - - if let Some(sys_basis) = pddb_os.pddb_mount() { - log::info!("PDDB mount operation finished successfully"); - basis_cache.basis_add(sys_basis); - } else { - log::error!("Despite formatting, no PDDB was found!"); - let mut err = String::from(t!("pddb.internalerror", xous::LANG)); - err.push_str(" #1"); // punt and leave an error code, because this "should" be rare - modals.show_notification(err.as_str()).expect("notification failed"); - } - } - } - #[cfg(not(any(target_os = "none", target_os = "xous")))] - { - pddb_os.pddb_format(false, Some(&modals)).expect("couldn't format PDDB"); - pddb_os.dbg_dump(Some("full".to_string()), None); - if let Some(sys_basis) = pddb_os.pddb_mount() { - log::info!("PDDB mount operation finished successfully"); - basis_cache.basis_add(sys_basis); - } else { - log::error!("Despite formatting, no PDDB was found!"); - let mut err = String::from(t!("pddb.internalerror", xous::LANG)); - err.push_str(" #1"); // punt and leave an error code, because this "should" be rare - modals.show_notification(err.as_str()).expect("notification failed"); - } - } - } + if ensure_password(&modals, &mut pddb_os) { + try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache); } } // main server loop @@ -572,6 +475,33 @@ fn xmain() -> ! { basis_cache.suspend(&mut pddb_os); susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); }), + Some(Opcode::IsMounted) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { + if basis_cache.basis_count() > 0 { // if there's anything in the cache, we're mounted. + xous::return_scalar(msg.sender, 1).expect("couldn't return scalar"); + } else { + xous::return_scalar(msg.sender, 0).expect("couldn't return scalar"); + } + }), + Some(Opcode::TryMount) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { + if basis_cache.basis_count() > 0 { + xous::return_scalar(msg.sender, 1).expect("couldn't return scalar"); + } else { + if !pddb_os.rootkeys_initialized() { + // can't mount if we have no root keys + xous::return_scalar(msg.sender, 0).expect("could't return scalar"); + } else { + if ensure_password(&modals, &mut pddb_os) { + if try_mount_or_format(&modals, &mut pddb_os, &mut basis_cache) { + xous::return_scalar(msg.sender, 1).expect("couldn't return scalar"); + } else { + xous::return_scalar(msg.sender, 0).expect("couldn't return scalar"); + } + } else { + xous::return_scalar(msg.sender, 0).expect("couldn't return scalar"); + } + } + } + }), Some(Opcode::ListBasis) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut list_ipc = buffer.to_original::().unwrap(); @@ -900,6 +830,7 @@ fn xmain() -> ! { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut req = buffer.to_original::().unwrap(); if key_token.is_some() { + log::debug!("key list already in progress"); req.code = PddbRequestCode::AccessDenied; buffer.replace(req).unwrap(); continue; @@ -912,17 +843,31 @@ fn xmain() -> ! { None }; let dict = req.dict.as_str().expect("dict utf-8 decode error"); + log::debug!("counting keys in dict {} basis {:?}", dict, bname); match basis_cache.key_list(&mut pddb_os, dict, bname) { Ok(list) => { - req.index = list.len() as u32; - for key in list { - key_list.push(key); + log::debug!("count: {}", list.len()); + if list.len() > 0 { + req.index = list.len() as u32; + for key in list { + log::debug!("key list: {}", key); + key_list.push(key); + } + } else { + log::debug!("count is 0, resetting state"); + // no keys to list, so reset the state + key_token = None; + key_list.clear(); } req.code = PddbRequestCode::NoErr; } - Err(e) => match e.kind() { - std::io::ErrorKind::NotFound => req.code = PddbRequestCode::NotFound, - _ => req.code = PddbRequestCode::InternalError, + Err(e) => { + key_token = None; + key_list.clear(); + match e.kind() { + std::io::ErrorKind::NotFound => req.code = PddbRequestCode::NotFound, + _ => req.code = PddbRequestCode::InternalError, + } } } buffer.replace(req).unwrap(); @@ -939,14 +884,17 @@ fn xmain() -> ! { } else { req.key = xous_ipc::String::::from_str(&key_list[req.index as usize]); req.code = PddbRequestCode::NoErr; + log::debug!("fetching key at index {}: {}", req.index, req.key); // the last index requested must be the highest one! if req.index == key_list.len() as u32 - 1 { + log::debug!("last key, resetting state"); key_token = None; key_list.clear(); } } } } else { + log::debug!("multiple concurrent requests detected, returning error"); req.code = PddbRequestCode::AccessDenied; } buffer.replace(req).unwrap(); @@ -967,9 +915,14 @@ fn xmain() -> ! { None }; let list = basis_cache.dict_list(&mut pddb_os, bname); - req.index = list.len() as u32; - for dict in list { - dict_list.push(dict); + if list.len() > 0 { + req.index = list.len() as u32; + for dict in list { + dict_list.push(dict); + } + } else { // no dicts to list, reset the state + dict_token = None; + dict_list.clear(); } req.code = PddbRequestCode::NoErr; buffer.replace(req).unwrap(); @@ -1082,6 +1035,116 @@ fn xmain() -> ! { xous::terminate_process(0) } +fn ensure_password(modals: &modals::Modals, pddb_os: &mut PddbOs) -> bool { + log::info!("Requesting login password"); + let mut done = false; + let mut skip = false; + while !done { + done = pddb_os.try_login(); + if !done { + pddb_os.clear_password(); // clear the bad password entry + modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list"); + modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list"); + match modals.get_radiobutton(t!("pddb.badpass", xous::LANG)) { + Ok(response) => { + if response.as_str() == t!("pddb.yes", xous::LANG) { + done = false; + } else if response.as_str() == t!("pddb.no", xous::LANG) { + done = true; + skip = true; + } else { + panic!("Got unexpected return from radiobutton"); + } + } + _ => panic!("get_radiobutton failed"), + } + } + } + !skip +} +fn try_mount_or_format(modals: &modals::Modals, pddb_os: &mut PddbOs, basis_cache: &mut BasisCache) -> bool { + log::info!("Attempting to mount the PDDB"); + if let Some(sys_basis) = pddb_os.pddb_mount() { + log::info!("PDDB mount operation finished successfully"); + basis_cache.basis_add(sys_basis); + true + } else { + #[cfg(any(target_os = "none", target_os = "xous"))] + { + log::debug!("PDDB did not mount; requesting format"); + modals.add_list_item(t!("pddb.okay", xous::LANG)).expect("couldn't build radio item list"); + modals.add_list_item(t!("pddb.cancel", xous::LANG)).expect("couldn't build radio item list"); + let do_format: bool; + match modals.get_radiobutton(t!("pddb.requestformat", xous::LANG)) { + Ok(response) => { + if response.as_str() == t!("pddb.okay", xous::LANG) { + do_format = true; + } else if response.as_str() == t!("pddb.cancel", xous::LANG) { + log::info!("PDDB format aborted by user"); + do_format = false; + } else { + panic!("Got unexpected return from radiobutton"); + } + } + _ => panic!("get_radiobutton failed"), + } + if do_format { + let fast: bool; + if false { + modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list"); + modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list"); + match modals.get_radiobutton(t!("pddb.devbypass", xous::LANG)) { + Ok(response) => { + if response.as_str() == t!("pddb.yes", xous::LANG) { + fast = true; + } else if response.as_str() == t!("pddb.no", xous::LANG) { + fast = false; + } else { + panic!("Got unexpected return from radiobutton"); + } + } + _ => panic!("get_radiobutton failed"), + } + } else { + fast = false; + } + + pddb_os.pddb_format(fast, Some(&modals)).expect("couldn't format PDDB"); + + if let Some(sys_basis) = pddb_os.pddb_mount() { + log::info!("PDDB mount operation finished successfully"); + basis_cache.basis_add(sys_basis); + true + } else { + log::error!("Despite formatting, no PDDB was found!"); + let mut err = String::from(t!("pddb.internalerror", xous::LANG)); + err.push_str(" #1"); // punt and leave an error code, because this "should" be rare + modals.show_notification(err.as_str()).expect("notification failed"); + false + } + } else { + false + } + } + #[cfg(not(any(target_os = "none", target_os = "xous")))] + { + pddb_os.pddb_format(false, Some(&modals)).expect("couldn't format PDDB"); + pddb_os.dbg_dump(Some("full".to_string()), None); + if let Some(sys_basis) = pddb_os.pddb_mount() { + log::info!("PDDB mount operation finished successfully"); + basis_cache.basis_add(sys_basis); + true + } else { + log::error!("Despite formatting, no PDDB was found!"); + let mut err = String::from(t!("pddb.internalerror", xous::LANG)); + err.push_str(" #1"); // punt and leave an error code, because this "should" be rare + modals.show_notification(err.as_str()).expect("notification failed"); + false + } + } + } +} + // Test cases that have been coded to run directly on hardware (that is, they do not require host-OS debug features) #[allow(dead_code)] pub(crate) fn manual_testcase(hw: &mut PddbOs) { diff --git a/services/shellchat/src/cmds.rs b/services/shellchat/src/cmds.rs index 4b19059b9..9fbf399fb 100644 --- a/services/shellchat/src/cmds.rs +++ b/services/shellchat/src/cmds.rs @@ -127,6 +127,7 @@ pub struct CmdEnv { jtag_cmd: JtagCmd, net_cmd: NetCmd, pddb_cmd: PddbCmd, + wlan_cmd: Wlan, //fcc_cmd: Fcc, } @@ -181,6 +182,7 @@ impl CmdEnv { jtag_cmd: JtagCmd::new(&xns), net_cmd: NetCmd::new(&xns), pddb_cmd: PddbCmd::new(&xns), + wlan_cmd: Wlan::new(), //fcc_cmd: fcc, } @@ -190,7 +192,6 @@ impl CmdEnv { let mut ret = String::<1024>::new(); let mut echo_cmd = Echo {}; // this command has no persistent storage, so we can "create" it every time we call dispatch (but it's a zero-cost absraction so this doesn't actually create any instructions) - let mut wlan_cmd = Wlan {}; let mut ver_cmd = Ver{}; let mut backlight_cmd = Backlight{}; let mut accel_cmd = Accel{}; @@ -217,7 +218,7 @@ impl CmdEnv { &mut console_cmd, // &mut self.memtest_cmd, &mut self.keys_cmd, - &mut wlan_cmd, + &mut self.wlan_cmd, &mut self.jtag_cmd, &mut self.net_cmd, &mut self.pddb_cmd, diff --git a/services/shellchat/src/cmds/test.rs b/services/shellchat/src/cmds/test.rs index d48ec052c..b6aa07543 100644 --- a/services/shellchat/src/cmds/test.rs +++ b/services/shellchat/src/cmds/test.rs @@ -417,9 +417,9 @@ impl<'a> ShellCmdApi<'a> for Test { write!(ret, "FAIL: JTAG self access").unwrap(); return Ok(Some(ret)); } - env.com.wlan_set_ssid(&String::<1024>::from_str("precursortest")).unwrap(); + env.com.wlan_set_ssid("precursortest").unwrap(); env.ticktimer.sleep_ms(500).unwrap(); - env.com.wlan_set_pass(&String::<1024>::from_str("notasecret")).unwrap(); + env.com.wlan_set_pass("notasecret").unwrap(); env.ticktimer.sleep_ms(500).unwrap(); env.com.wlan_join().unwrap(); @@ -472,7 +472,7 @@ impl<'a> ShellCmdApi<'a> for Test { loop { // parse and see if we connected from the first attempt (called before this loop) if let Ok(msg) = env.com.wlan_status() { - let mut elements = msg.as_str().unwrap().split(' '); + let mut elements = msg.as_str().split(' '); rssi_pass = if let Some(_rssi_str) = elements.next() { //rssi_str.parse::().unwrap() < -10 // for now always pass, don't use RSSI as it's not reliable @@ -497,10 +497,10 @@ impl<'a> ShellCmdApi<'a> for Test { }; // if connected, break if rssi_pass && net_up && dhcp_ok && ssid_ok { - write!(ret, "WLAN OK: {}\n", msg.as_str().unwrap()).unwrap(); + write!(ret, "WLAN OK: {}\n", msg.as_str()).unwrap(); break; } else { - write!(ret, "WLAN TRY: {}", msg.as_str().unwrap()).unwrap(); + write!(ret, "WLAN TRY: {}", msg.as_str()).unwrap(); } } else { write!(ret, "WLAN TRY: Couldn't get status!\n").unwrap(); @@ -509,9 +509,9 @@ impl<'a> ShellCmdApi<'a> for Test { // else retry the connection sequence -- leave, ssid, pass, join. takes some time. env.com.wlan_leave().unwrap(); env.ticktimer.sleep_ms(2000).unwrap(); - env.com.wlan_set_ssid(&String::<1024>::from_str("precursortest")).unwrap(); + env.com.wlan_set_ssid("precursortest").unwrap(); env.ticktimer.sleep_ms(800).unwrap(); - env.com.wlan_set_pass(&String::<1024>::from_str("notasecret")).unwrap(); + env.com.wlan_set_pass("notasecret").unwrap(); env.ticktimer.sleep_ms(800).unwrap(); env.com.wlan_join().unwrap(); env.ticktimer.sleep_ms(8000).unwrap(); diff --git a/services/shellchat/src/cmds/wlan.rs b/services/shellchat/src/cmds/wlan.rs index 3ea702ce9..9bea64405 100644 --- a/services/shellchat/src/cmds/wlan.rs +++ b/services/shellchat/src/cmds/wlan.rs @@ -1,9 +1,18 @@ use crate::{CommonEnv, ShellCmdApi}; use core::fmt::Write; +use std::io::Write as PddbWrite; use xous_ipc::String; #[derive(Debug)] -pub struct Wlan {} +pub struct Wlan { + current_ssid: Option, + current_pass: Option, +} +impl Wlan { + pub fn new() -> Self { + Wlan { current_ssid: None, current_pass: None } + } +} /** wlan shell command: @@ -25,7 +34,7 @@ impl<'a> ShellCmdApi<'a> for Wlan { env: &mut CommonEnv, ) -> Result>, xous::Error> { let mut ret = String::<1024>::new(); - let helpstring = "wlan [on] [off] [setssid ...] [setpass ...] [join] [leave] [status]"; + let helpstring = "wlan [on] [off] [setssid ...] [setpass ...] [join] [leave] [status] [save]"; let mut show_help = false; let mut tokens = args.as_str().unwrap().split(' '); @@ -49,20 +58,62 @@ impl<'a> ShellCmdApi<'a> for Wlan { if val.len() == 0 { let _ = write!(ret, "Error: SSID too short"); } else { - let _ = match env.com.wlan_set_ssid(&val) { - Ok(_) => write!(ret, "wlan setssid {}", val), - Err(_) => write!(ret, "Error: SSID too long for WF200"), + let _ = match env.com.wlan_set_ssid(val.as_str().expect("not valid utf-8")) { + Ok(_) => { + self.current_ssid = Some(std::string::String::from(val.as_str().unwrap())); + write!(ret, "wlan setssid {}", val).unwrap() + }, + Err(_) => write!(ret, "Error: SSID too long for WF200").unwrap(), }; } } "setpass" => { let mut val = String::<1024>::new(); join_tokens(&mut val, &mut tokens); - let _ = match env.com.wlan_set_pass(&val) { - Ok(_) => write!(ret, "wlan setpass {}", val), - Err(_) => write!(ret, "Error: passphrase too long for WF200"), + let _ = match env.com.wlan_set_pass(val.as_str().expect("not valid utf-8")) { + Ok(_) => { + self.current_pass = Some(std::string::String::from(val.as_str().unwrap())); + write!(ret, "wlan setpass {}", val).unwrap() + }, + Err(_) => write!(ret, "Error: passphrase too long for WF200").unwrap(), }; } + "save" => { + let mut pddb = pddb::Pddb::new(); + if let Some(ssid) = &self.current_ssid { + if let Some(pass) = &self.current_pass { + match pddb.get( + net::AP_DICT_NAME, &ssid, None, + true, true, Some(com::api::WF200_PASS_MAX_LEN), Some(||{})) { + Ok(mut entry) => { + match entry.write(&pass.as_bytes()) { + Ok(len) => { + if len != pass.len() { + write!(ret, "PDDB wrote only {} of {} bytes of password", len, pass.len()).unwrap(); + } else { + // for now, we should always call flush at the end of a routine; perhaps in the + // future we'll have a timer that automatically syncs the pddb + entry.flush().expect("couldn't sync pddb cache"); + write!(ret, "SSID/pass combo saved to PDDB").unwrap(); + } + } + Err(e) => { + write!(ret, "PDDB error storing key: {:?}", e).unwrap(); + } + } + }, + Err(e) => { + write!(ret, "PDDB error creating key: {:?}", e).unwrap(); + } + } + } else { + write!(ret, "No password currently set").unwrap(); + } + } else { + write!(ret, "No SSID currently set").unwrap(); + } + + } "join" => { let _ = match env.com.wlan_join() { Ok(_) => write!(ret, "wlan join"),