diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index 8d4cca1b3..5b9ce7265 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -1,6 +1,31 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] +/// A modals initiator will: +/// +/// 1. unpack the specification from the incoming message +/// 2. check the API token +/// 3. if valid, set the `op` with the appropriate enum to encapsulate the spec +/// 4. store the memory message in the `dr` (deferred response) Option +/// 5. send a message to itself to initiate the operation +/// +/// The operation proceeds within this server, perhaps through multiple states. +/// +/// On completion, the final state(s) do the following: +/// +/// 1. unpack the return data message, which came from an internal (within-modals) state +/// 2. `take()` the `dr` record, preparing for its lifetime to be ended +/// 3. unpack the `memory_message` inside the `dr` record into a Buffer +/// 4. `replace()` the return data into the `Buffer` +/// 5. Set the op to `RenderState::None` +/// 6. (implicit) the memory_message previously held in the `dr` record is dropped, trigging the caller to unblock +/// 7. once you are sure you're finished, call `token_lock = next_lock(&mut work_queue);` to pull any waiting work from the work queue +/// +/// Between 5 & 7 is where the TextEntry is weird: because you can "fail" on the return, +/// it doesn't automatically do step 7. It's an extra step that the library implementation +/// does after it does the text validation on its side, once it validates the caller sends +/// a `TextResponseValid` message which pumps the work queue. + mod api; use api::*; mod tests; diff --git a/services/net/src/protocols/ping.rs b/services/net/src/protocols/ping.rs index b76f6978e..dfca138b6 100644 --- a/services/net/src/protocols/ping.rs +++ b/services/net/src/protocols/ping.rs @@ -15,7 +15,7 @@ use num_traits::*; /// formatter, but it's built into the socket handle itself. The reasoning behind /// this was to keep memory allocations small and static. /// -/// In a single-threaded implemnetation, one would normally have no problem simply +/// In a single-threaded implementation, one would normally have no problem simply /// pulling up the socket handle and jamming or unpacking data using that handle. /// Unfortunately, in Xous, we want to keep smoltcp inside the Net crate, and not /// have it bleed into other parts of the OS. The first take at implementing this diff --git a/services/pddb/locales/i18n.json b/services/pddb/locales/i18n.json index 6484fcc0a..62d347fa5 100644 --- a/services/pddb/locales/i18n.json +++ b/services/pddb/locales/i18n.json @@ -108,11 +108,17 @@ "en-tts": "Enter name of Basis" }, "pddb.password": { - "en": "Basis Password:", + "en": "Enter Basis password", "ja": "Basis パスワード", "zh": "基础密码", "en-tts": "Enter password for Basis" }, + "pddb.password_for": { + "en": "For basis: ", + "ja": "Basis 名前: ", + "zh": "基础姓名: ", + "en-tts": "For basis: " + }, "pddb.menu.listbasis": { "en": "List unlocked bases", "ja": "ロック解除されたベースをー覧表します", diff --git a/services/pddb/src/api.rs b/services/pddb/src/api.rs index c3df8a0ae..43cac7163 100644 --- a/services/pddb/src/api.rs +++ b/services/pddb/src/api.rs @@ -194,7 +194,7 @@ pub struct PddbKeyRequest { pub create_dict: bool, pub create_key: bool, pub alloc_hint: Option, // this is a usize but for IPC we must have defined memory sizes, so we pick the big option. - pub cb_sid: [u32; 4], + pub cb_sid: Option<[u32; 4]>, pub result: PddbRequestCode, } diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index 603c2dca2..1f194758a 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -20,7 +20,7 @@ pub(crate) static REFCOUNT: AtomicU32 = AtomicU32::new(0); pub(crate) static POLLER_REFCOUNT: AtomicU32 = AtomicU32::new(0); #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] -enum CbOp { +pub enum CbOp { Change, Quit } @@ -73,8 +73,7 @@ impl Drop for PddbMountPoller { pub struct Pddb { conn: CID, /// a SID that we can directly share with the PDDB server for the purpose of handling key change callbacks - cb_sid: SID, - cb_handle: Option>, + cb: Option<(SID, JoinHandle::<()>)>, /// Handle key change updates. The general intent is that the closure implements a /// `send` of a message to the server to deal with a key change appropriately, /// but no mutable data is allowed within the closure itself due to safety problems. @@ -93,41 +92,45 @@ impl Pddb { REFCOUNT.fetch_add(1, Ordering::Relaxed); let xns = xous_names::XousNames::new().unwrap(); let conn = xns.request_connection_blocking(api::SERVER_NAME_PDDB).expect("can't connect to Pddb server"); - let sid = xous::create_server().unwrap(); let keys: Arc >>> = Arc::new(Mutex::new(HashMap::new())); - let handle = thread::spawn({ - let keys = Arc::clone(&keys); - let sid = sid.clone(); - move || { - loop { - let msg = xous::receive_message(sid).unwrap(); - match FromPrimitive::from_usize(msg.body.id()) { - Some(CbOp::Change) => msg_scalar_unpack!(msg, t0, t1, t2, _, { - let token: ApiToken = [t0 as u32, t1 as u32, t2 as u32]; - if let Some(cb) = keys.lock().unwrap().get(&token) { - cb(); - } else { - log::warn!("Key changed but no callback was hooked to receive it"); - } - }), - Some(CbOp::Quit) => { // blocking scalar - xous::return_scalar(msg.sender, 0).unwrap(); - break; - }, - _ =>log::warn!("Got unknown opcode: {:?}", msg), - } - } - xous::destroy_server(sid).unwrap(); - } - }); Pddb { conn, - cb_sid: sid, - cb_handle: Some(handle), + cb: None, keys, trng: trng::Trng::new(&xns).unwrap(), } } + fn ensure_async_responder(&mut self) { + if self.cb.is_none() { + let sid = xous::create_server().unwrap(); + let handle = thread::spawn({ + let keys = Arc::clone(&self.keys); + let sid = sid.clone(); + move || { + loop { + let msg = xous::receive_message(sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(CbOp::Change) => msg_scalar_unpack!(msg, t0, t1, t2, _, { + let token: ApiToken = [t0 as u32, t1 as u32, t2 as u32]; + if let Some(cb) = keys.lock().unwrap().get(&token) { + cb(); + } else { + log::warn!("Key changed but no callback was hooked to receive it"); + } + }), + Some(CbOp::Quit) => { // blocking scalar + xous::return_scalar(msg.sender, 0).unwrap(); + break; + }, + _ =>log::warn!("Got unknown opcode: {:?}", msg), + } + } + xous::destroy_server(sid).unwrap(); + } + }); + self.cb = Some((sid, handle)); + } + } /// This blocks until the PDDB is mounted by the end user. If `None` is specified for the poll_interval_ms, /// A random interval between 1 and 2 seconds is chosen for the poll wait time. Randomizing the waiting time /// helps to level out the task scheduler in the case that many threads are waiting on the PDDB simultaneously. @@ -310,6 +313,14 @@ impl Pddb { xous_ipc::String::::new() }; + if key_changed_cb.is_some() { + self.ensure_async_responder(); + } + let cb_sid = if let Some((sid, _handle)) = &self.cb { + Some(sid.to_array()) + } else { + None + }; let request = PddbKeyRequest { basis_specified: basis_name.is_some(), basis: xous_ipc::String::::from_str(&bname), @@ -319,7 +330,7 @@ impl Pddb { create_key, token: None, result: PddbRequestCode::Uninit, - cb_sid: self.cb_sid.to_array(), + cb_sid, alloc_hint: if let Some(a) = alloc_hint {Some(a as u64)} else {None}, }; let mut buf = Buffer::into_buf(request) @@ -380,6 +391,11 @@ impl Pddb { xous_ipc::String::::new() }; + let cb_sid = if let Some((sid, _handle)) = &self.cb { + Some(sid.to_array()) + } else { + None + }; let request = PddbKeyRequest { basis_specified: basis_name.is_some(), basis: xous_ipc::String::::from_str(&bname), @@ -389,7 +405,7 @@ impl Pddb { create_key: false, token: None, result: PddbRequestCode::Uninit, - cb_sid: self.cb_sid.to_array(), + cb_sid, alloc_hint: None, }; let mut buf = Buffer::into_buf(request) @@ -418,6 +434,11 @@ impl Pddb { xous_ipc::String::::new() }; + let cb_sid = if let Some((sid, _handle)) = &self.cb { + Some(sid.to_array()) + } else { + None + }; let request = PddbKeyRequest { basis_specified: basis_name.is_some(), basis: xous_ipc::String::::from_str(&bname), @@ -427,7 +448,7 @@ impl Pddb { create_key: false, token: None, result: PddbRequestCode::Uninit, - cb_sid: self.cb_sid.to_array(), + cb_sid, alloc_hint: None, }; let mut buf = Buffer::into_buf(request) @@ -607,10 +628,10 @@ impl Pddb { impl Drop for Pddb { fn drop(&mut self) { - let cid = xous::connect(self.cb_sid).unwrap(); - send_message(cid, Message::new_blocking_scalar(CbOp::Quit.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); - unsafe{xous::disconnect(cid).ok();} - if let Some(handle) = self.cb_handle.take() { + if let Some((cb_sid, handle)) = self.cb.take() { + let cid = xous::connect(cb_sid).unwrap(); + send_message(cid, Message::new_blocking_scalar(CbOp::Quit.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); + unsafe{xous::disconnect(cid).ok();} handle.join().expect("couldn't terminate callback helper thread"); } diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index bc9eeea69..f6a0c603c 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -405,12 +405,13 @@ pub(crate) enum PasswordState { Uninit, } +#[derive(Debug)] struct TokenRecord { pub dict: String, pub key: String, pub basis: Option, pub alloc_hint: Option, - pub conn: xous::CID, // callback connection + pub conn: Option, // callback connection, if one was specified } #[xous::xous_main] @@ -649,24 +650,28 @@ fn xmain() -> ! { basis_cache.basis_add(basis); finished = true; mgmt.code = PddbRequestCode::NoErr; + } else { + 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) { + finished = false; + // this will cause just another go-around + } else if response.as_str() == t!("pddb.no", xous::LANG) { + finished = true; + mgmt.code = PddbRequestCode::AccessDenied; // this will cause a return of AccessDenied + } else { + panic!("Got unexpected return from radiobutton"); + } + } + _ => panic!("get_radiobutton failed"), + } + xous::yield_slice(); // allow a redraw to happen before repeating the request } } else { - 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) { - finished = false; - // this will cause just another go-around - } else if response.as_str() == t!("pddb.no", xous::LANG) { - finished = true; - mgmt.code = PddbRequestCode::AccessDenied; // this will cause a return of AccessDenied - } else { - panic!("Got unexpected return from radiobutton"); - } - } - _ => panic!("get_radiobutton failed"), - } + finished = true; + log::error!("internal error in basis unlock, aborting!"); } } } @@ -679,6 +684,7 @@ fn xmain() -> ! { Some(Opcode::CloseBasis) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut mgmt = buffer.to_original::().unwrap(); + notify_of_disconnect(&mut pddb_os, &token_dict, &mut basis_cache); match mgmt.code { PddbRequestCode::Close => { match basis_cache.basis_unmount(&mut pddb_os, mgmt.name.as_str().expect("name is not valid utf-8")) { @@ -698,6 +704,7 @@ fn xmain() -> ! { Some(Opcode::DeleteBasis) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut mgmt = buffer.to_original::().unwrap(); + notify_of_disconnect(&mut pddb_os, &token_dict, &mut basis_cache); match mgmt.code { PddbRequestCode::Delete => { match basis_cache.basis_delete(&mut pddb_os, mgmt.name.as_str().expect("name is not valid utf-8")) { @@ -767,7 +774,11 @@ fn xmain() -> ! { } // at this point, we have established a basis/dict/key tuple. let token: ApiToken = [pddb_os.trng_u32(), pddb_os.trng_u32(), pddb_os.trng_u32()]; - let cid = xous::connect(xous::SID::from_array(req.cb_sid)).expect("couldn't connect for callback"); + let cid = if let Some(cb_sid) = req.cb_sid { + Some(xous::connect(xous::SID::from_array(cb_sid)).expect("couldn't connect for callback")) + } else { + None + }; let token_record = TokenRecord { dict: String::from(dict), key: String::from(key), @@ -785,15 +796,23 @@ fn xmain() -> ! { if let Some(rec) = token_dict.remove(&token) { // now check if we can safely disconnect and recycle our connection number. // This is important because we can only have 32 outgoing connections... - let mut has_cid = false; - for r in token_dict.values() { - if r.conn == rec.conn { - has_cid = true; - break; + if let Some(conn_to_remove) = rec.conn { + let mut still_needs_cid = false; + for r in token_dict.values() { + // check through the remaining dictionary values to see if they have a connection that is the same as our number + if let Some(existing_conn) = r.conn { + if existing_conn == conn_to_remove { + still_needs_cid = true; + break; + } + } } - } - if !has_cid { - unsafe{xous::disconnect(rec.conn).expect("couldn't disconnect from callback server")}; + // if nobody else had my connection number, disconnect it. + if !still_needs_cid { + unsafe{xous::disconnect(conn_to_remove).expect("couldn't disconnect from callback server")}; + } + } else { + // if there was no/never a connection allocated, there's no connection to remove. do nothing. } } xous::return_scalar(msg.sender, 1).expect("couldn't ack KeyDrop"); @@ -1388,3 +1407,34 @@ pub(crate) fn hw_testcase(pddb_os: &mut PddbOs) { pddb_os.dbg_dump(Some("manual".to_string()), None); } +fn notify_of_disconnect(pddb_os: &mut PddbOs, token_dict: &HashMap::, basis_cache: &mut BasisCache) { + // 1. search to see if any of the active tokens are are in our token_dict + // 2. notify them of the disconnect, if there is a callback set. + for (api_key, entry) in token_dict.iter() { + log::debug!("disconnect notify searching {:?}", entry); + if let Some(cb) = entry.conn { + match basis_cache.key_attributes(pddb_os, &entry.dict, &entry.key, entry.basis.as_deref()) { + Ok(_) => { + match send_message(cb, Message::new_scalar( + pddb::CbOp::Change.to_usize().unwrap(), + api_key[0] as _, + api_key[1] as _, + api_key[2] as _, + 0, + )) { + Err(e) => { + log::warn!("Callback on {}:{} for basis removal failed: {:?}", &entry.dict, &entry.key, e); + }, + _ => { + log::debug!("Callback on {}:{} for basis removal success", &entry.dict, &entry.key); + } + } + }, + Err(_) => { + // do nothing. It's probably not right that a key doesn't exist that we don't have in our records, but don't crash the system. + log::warn!("Disconnect basis inconsistent state, {}:{} not found", &entry.dict, &entry.key); + } + } + } + } +} \ No newline at end of file diff --git a/services/pddb/src/ux.rs b/services/pddb/src/ux.rs index 2dfaed2c0..164a47901 100644 --- a/services/pddb/src/ux.rs +++ b/services/pddb/src/ux.rs @@ -1,19 +1,13 @@ use xous::{SID, CID}; -use xous::{msg_scalar_unpack, send_message}; +use xous::msg_scalar_unpack; use xous_ipc::Buffer; -use std::sync::{Arc, Mutex}; -use std::thread; -use core::sync::atomic::{AtomicBool, Ordering}; - use num_traits::*; use gam::modal::*; use locales::t; -use std::fmt::Write; - use crate::BasisRequestPassword; /* Conclusions: @@ -54,12 +48,6 @@ GAM Modal Object -> redraw -> gam requests pub(crate) enum PwManagerOpcode { // blocking call to get a password RequestPassword, - Quit, -} - -#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] -pub(crate) enum PwRendererOpcode { - RaisePwModal, PwReturn, ModalRedraw, ModalKeypress, @@ -73,144 +61,99 @@ pub(crate) fn password_ux_manager( // the SID we're to use for our loop handler, for getting requests ux_sid: SID) { - let tt = ticktimer_server::Ticktimer::new().unwrap(); - - let renderer_sid = xous::create_server().expect("couldn't create a server for the password UX renderer"); - let renderer_cid = xous::connect(renderer_sid).expect("couldn't connect to the password UX renderer"); - let plaintext_pw = Arc::new(Mutex::new(xous_ipc::String::<{crate::api::PASSWORD_LEN}>::new())); - - let renderer_active = Arc::new(AtomicBool::new(false)); + let ux_cid = xous::connect(ux_sid).unwrap(); // create a thread that just handles the redrawing requests - let redraw_handle = thread::spawn({ - let renderer_active = Arc::clone(&renderer_active); - let plaintext_pw = Arc::clone(&plaintext_pw); - move || { - // build the core data structure here - let password_action = TextEntry { - is_password: true, - visibility: TextEntryVisibility::LastChars, - action_conn: renderer_cid, - action_opcode: PwRendererOpcode::PwReturn.to_u32().unwrap(), - action_payload: TextEntryPayload::new(), - validator: None, - }; + // build the core data structure here + let password_action = TextEntry { + is_password: true, + visibility: TextEntryVisibility::LastChars, + action_conn: ux_cid, + action_opcode: PwManagerOpcode::PwReturn.to_u32().unwrap(), + action_payload: TextEntryPayload::new(), + validator: None, + }; - let mut pddb_modal = - Modal::new( - gam::PDDB_MODAL_NAME, - ActionType::TextEntry(password_action), - Some(t!("pddb.password", xous::LANG)), - None, - GlyphStyle::Regular, - 8 - ); - pddb_modal.spawn_helper(renderer_sid, pddb_modal.sid, - PwRendererOpcode::ModalRedraw.to_u32().unwrap(), - PwRendererOpcode::ModalKeypress.to_u32().unwrap(), - PwRendererOpcode::ModalDrop.to_u32().unwrap(), - ); + let mut pddb_modal = + Modal::new( + gam::PDDB_MODAL_NAME, + ActionType::TextEntry(password_action), + Some(t!("pddb.password", xous::LANG)), + None, + GlyphStyle::Regular, + 8 + ); + pddb_modal.spawn_helper(ux_sid, pddb_modal.sid, + PwManagerOpcode::ModalRedraw.to_u32().unwrap(), + PwManagerOpcode::ModalKeypress.to_u32().unwrap(), + PwManagerOpcode::ModalDrop.to_u32().unwrap(), + ); - loop { - let msg = xous::receive_message(renderer_sid).unwrap(); - log::debug!("message: {:?}", msg); - match FromPrimitive::from_usize(msg.body.id()) { - Some(PwRendererOpcode::RaisePwModal) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let db_name = buffer.to_original::, _>().unwrap(); - pddb_modal.modify( - Some(ActionType::TextEntry(password_action)), - Some(t!("pddb.password", xous::LANG)), false, - Some(db_name.as_str().unwrap()), false, None - ); - pddb_modal.activate(); - } - Some(PwRendererOpcode::PwReturn) => { - if renderer_active.load(Ordering::SeqCst) { - let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let mut pw = buf.to_original::().unwrap(); - - plaintext_pw.lock().unwrap().clear(); - write!(plaintext_pw.lock().unwrap(), "{}", pw.as_str()).expect("couldn't transfer password to local buffer"); - - pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave - buf.volatile_clear(); - } else { - log::warn!("Fat finger event received from Ux, ignoring"); - } - - // this resumes the waiting Ux Manager thread - renderer_active.store(false, Ordering::SeqCst); - }, - Some(PwRendererOpcode::ModalRedraw) => { - pddb_modal.redraw(); - }, - Some(PwRendererOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { - let keys = [ - core::char::from_u32(k1 as u32).unwrap_or('\u{0000}'), - core::char::from_u32(k2 as u32).unwrap_or('\u{0000}'), - core::char::from_u32(k3 as u32).unwrap_or('\u{0000}'), - core::char::from_u32(k4 as u32).unwrap_or('\u{0000}'), - ]; - pddb_modal.key_event(keys); - }), - Some(PwRendererOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service - panic!("Password modal for PDDB quit unexpectedly"); - }, - Some(PwRendererOpcode::Quit) => { - log::warn!("received quit on PDDB password UX renderer loop"); - xous::return_scalar(msg.sender, 0).unwrap(); - break; - }, - None => { - log::error!("Couldn't convert opcode: {:?}", msg); - } - } - } - xous::destroy_server(renderer_sid).unwrap(); - } - }); + let mut dr: Option = None; // the main loop merely wraps a blocking wrapper around the renderer thread loop { - let mut msg = xous::receive_message(ux_sid).unwrap(); + let msg = xous::receive_message(ux_sid).unwrap(); log::debug!("message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(PwManagerOpcode::RequestPassword) => { - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; - let mut request = buffer.to_original::().unwrap(); - let fwd_buf = Buffer::into_buf(request.db_name).unwrap(); - renderer_active.store(true, Ordering::SeqCst); - fwd_buf.lend(renderer_cid, PwRendererOpcode::RaisePwModal.to_u32().unwrap()).expect("couldn't request renderer to raise the password modal"); - // this returns almost immediately, because the Ux Manager thread can't block (it has to manage rendering), but the password hasn't come back yet. - // so...."busy wait" by polling once every 100ms until the Ux is finished with its task. - // I can't seem to figure out a way to do this using a solely asynchronous method. I really want a spsc queue, but these don't exist in xous stdlib yet. - // apparently the thing I'm looking for is a `condvar`, which is coming Real Soon Now. - while renderer_active.load(Ordering::SeqCst) { - tt.sleep_ms(100).unwrap(); - } - // when this unblocks, the password request cycle is done. - let retpw = xous_ipc::String::<{crate::api::PASSWORD_LEN}>::from_str(plaintext_pw.lock().unwrap().as_str().unwrap()); - request.plaintext_pw = Some(retpw); + let db_name = { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let request = buffer.to_original::().unwrap(); + request.db_name + }; + pddb_modal.modify( + Some(ActionType::TextEntry(password_action)), + Some(t!("pddb.password", xous::LANG)), false, + Some(format!("{}'{}'", t!("pddb.password_for", xous::LANG), db_name.as_str().unwrap()).as_str()), false, None + ); + pddb_modal.activate(); + dr = Some(msg); - // return the password to the caller - buffer.replace(request).unwrap(); + }, + Some(PwManagerOpcode::PwReturn) => { + let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let mut pw = buf.to_original::().unwrap(); + + if let Some(mut response) = dr.take() { + let mut buffer = unsafe { Buffer::from_memory_message_mut(response.body.memory_message_mut().unwrap()) }; + let mut request = buffer.to_original::().unwrap(); + request.plaintext_pw = Some(xous_ipc::String::from_str(pw.as_str())); + // return the password to the caller + buffer.replace(request).unwrap(); + // response goes out of scope here and calls Drop which returns the message + } else { + log::error!("Password return received, but no deferred response on record"); + } + + pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave + buf.volatile_clear(); + }, + Some(PwManagerOpcode::ModalRedraw) => { + pddb_modal.redraw(); + }, + Some(PwManagerOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { + let keys = [ + core::char::from_u32(k1 as u32).unwrap_or('\u{0000}'), + core::char::from_u32(k2 as u32).unwrap_or('\u{0000}'), + core::char::from_u32(k3 as u32).unwrap_or('\u{0000}'), + core::char::from_u32(k4 as u32).unwrap_or('\u{0000}'), + ]; + pddb_modal.key_event(keys); + }), + Some(PwManagerOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service + panic!("Password modal for PDDB quit unexpectedly"); }, Some(PwManagerOpcode::Quit) => { - log::warn!("PDDB password handler exiting."); - send_message( - renderer_cid, - xous::Message::new_blocking_scalar(PwRendererOpcode::Quit.to_usize().unwrap(), - 0, 0, 0, 0)).unwrap(); + log::warn!("received quit on PDDB password UX renderer loop"); xous::return_scalar(msg.sender, 0).unwrap(); - break + break; }, + None => { log::error!("couldn't convert opcode"); } } } - redraw_handle.join().expect("redraw thread didn't quit as expected"); - unsafe{xous::disconnect(renderer_cid).unwrap()}; // can't remember if this is...necessary? it'll throw an error if it's not. xous::destroy_server(ux_sid).unwrap(); } diff --git a/services/shellchat/src/cmds/pddb_cmd.rs b/services/shellchat/src/cmds/pddb_cmd.rs index 918037dbe..0726905b8 100644 --- a/services/shellchat/src/cmds/pddb_cmd.rs +++ b/services/shellchat/src/cmds/pddb_cmd.rs @@ -21,9 +21,9 @@ impl<'a> ShellCmdApi<'a> for PddbCmd { use core::fmt::Write; let mut ret = String::<1024>::new(); #[cfg(not(feature="pddbtest"))] - let helpstring = "pddb [basislist] [dictlist] [keylist] [query] [dictdelete] [keydelete]"; + let helpstring = "pddb [basislist] [basiscreate] [basisunlock] [basislock] [basisdelete] [default]\n[dictlist] [keylist] [query] [dictdelete] [keydelete]"; #[cfg(feature="pddbtest")] - let helpstring = "pddb [basislist] [dictlist] [keylist] [query] [dictdelete] [keydelete] [test]"; + let helpstring = "pddb [basislist] [basiscreate] [basisunlock] [basislock] [basisdelete] [default]\n[dictlist] [keylist] [query] [dictdelete] [keydelete]\n[test]"; let mut tokens = args.as_str().unwrap().split(' '); if let Some(sub_cmd) = tokens.next() { @@ -43,6 +43,52 @@ impl<'a> ShellCmdApi<'a> for PddbCmd { }}) ).unwrap();*/ } + "default" => { + match self.pddb.latest_basis() { + Some(latest) => write!(ret, "The current default basis is: {}", latest).unwrap(), + None => write!(ret, "No open basis detected").unwrap(), + } + } + "basiscreate" => { + if let Some(bname) = tokens.next() { + match self.pddb.create_basis(bname) { + Ok(_) => write!(ret, "basis {} created successfully", bname).unwrap(), + Err(e) => write!(ret, "basis {} could not be created: {:?}", bname, e).unwrap(), + } + } else { + write!(ret, "usage: pddb basiscreate [basis name]").unwrap() + } + } + "basisunlock" => { + if let Some(bname) = tokens.next() { + match self.pddb.unlock_basis(bname, None) { + Ok(_) => write!(ret, "basis {} unlocked successfully", bname).unwrap(), + Err(e) => write!(ret, "basis {} could not be unlocked: {:?}", bname, e).unwrap(), + } + } else { + write!(ret, "usage: pddb basisunlock [basis name]").unwrap() + } + } + "basislock" => { + if let Some(bname) = tokens.next() { + match self.pddb.lock_basis(bname) { + Ok(_) => write!(ret, "basis {} locked successfully", bname).unwrap(), + Err(e) => write!(ret, "basis {} could not be locked: {:?}", bname, e).unwrap(), + } + } else { + write!(ret, "usage: pddb basisunlock [basis name]").unwrap() + } + } + "basisdelete" => { + if let Some(bname) = tokens.next() { + match self.pddb.delete_basis(bname) { + Ok(_) => write!(ret, "basis {} deleted successfully", bname).unwrap(), + Err(e) => write!(ret, "basis {} could not be deleted: {:?}", bname, e).unwrap(), + } + } else { + write!(ret, "usage: pddb basisdelete [basis name]").unwrap() + } + } "query" => { if let Some(descriptor) = tokens.next() { if let Some((dict, keyname)) = descriptor.split_once(':') { @@ -171,6 +217,7 @@ impl<'a> ShellCmdApi<'a> for PddbCmd { // note that this feature only works in hosted mode #[cfg(feature="pddbtest")] "test" => { + let bname = tokens.next(); // zero-length key test let mut test_handle = pddb::Pddb::new(); // build a key, but don't write to it. @@ -179,10 +226,22 @@ impl<'a> ShellCmdApi<'a> for PddbCmd { "zerolength", None, true, true, Some(8), - None:: + None::, ).expect("couldn't build empty key"); self.pddb.sync().unwrap(); + if let Some(name) = bname { + match self.pddb.lock_basis(name) { + Ok(_) => log::info!("basis {} lock successful", name), + Err(e) => log::info!("basis {} could not be unmounted: {:?}", name, e), + } + } self.pddb.dbg_remount().unwrap(); + if let Some(name) = bname { + match self.pddb.unlock_basis(name, None) { + Ok(_) => log::info!("basis {} unlocked successfully", name), + Err(e) => log::info!("basis {} could not be unlocked: {:?}", name, e), + } + } self.pddb.dbg_dump("std_test1").unwrap(); write!(ret, "dumped std_test1\n").unwrap(); log::info!("finished zero-length alloc"); @@ -202,7 +261,9 @@ impl<'a> ShellCmdApi<'a> for PddbCmd { "seekwrite", None, true, true, Some(64), - None:: + Some(|| { + log::info!("test:seekwrite key was unmounted"); + }) ).expect("couldn't build empty key"); // 1, 1, 1, 1 log::info!("wrote {} bytes at offset 0", @@ -215,6 +276,18 @@ impl<'a> ShellCmdApi<'a> for PddbCmd { log::info!("wrote {} bytes at offset 2", seekwrite.write(&[2, 2, 2, 2]).unwrap() ); + if let Some(name) = bname { + match self.pddb.lock_basis(name) { + Ok(_) => log::info!("basis {} lock successful", name), + Err(e) => log::info!("basis {} could not be unmounted: {:?}", name, e), + } + } + if let Some(name) = bname { + match self.pddb.unlock_basis(name, None) { + Ok(_) => log::info!("basis {} unlocked successfully", name), + Err(e) => log::info!("basis {} could not be unlocked: {:?}", name, e), + } + } // 1, 1, 2, 2, 2, 2, 0, 0, 3, 3 log::info!("seek to {}", seekwrite.seek(SeekFrom::Start(8)).unwrap()