Merge branch 'bunnie-dev' into main

This commit is contained in:
bunnie 2022-04-07 19:28:39 +08:00
commit cf9265316d
8 changed files with 321 additions and 203 deletions

View file

@ -1,6 +1,31 @@
#![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)] #![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; mod api;
use api::*; use api::*;
mod tests; mod tests;

View file

@ -15,7 +15,7 @@ use num_traits::*;
/// formatter, but it's built into the socket handle itself. The reasoning behind /// formatter, but it's built into the socket handle itself. The reasoning behind
/// this was to keep memory allocations small and static. /// 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. /// 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 /// 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 /// have it bleed into other parts of the OS. The first take at implementing this

View file

@ -108,11 +108,17 @@
"en-tts": "Enter name of Basis" "en-tts": "Enter name of Basis"
}, },
"pddb.password": { "pddb.password": {
"en": "Basis Password:", "en": "Enter Basis password",
"ja": "Basis パスワード", "ja": "Basis パスワード",
"zh": "基础密码", "zh": "基础密码",
"en-tts": "Enter password for Basis" "en-tts": "Enter password for Basis"
}, },
"pddb.password_for": {
"en": "For basis: ",
"ja": "Basis 名前: ",
"zh": "基础姓名: ",
"en-tts": "For basis: "
},
"pddb.menu.listbasis": { "pddb.menu.listbasis": {
"en": "List unlocked bases", "en": "List unlocked bases",
"ja": "ロック解除されたベースをー覧表します", "ja": "ロック解除されたベースをー覧表します",

View file

@ -194,7 +194,7 @@ pub struct PddbKeyRequest {
pub create_dict: bool, pub create_dict: bool,
pub create_key: bool, pub create_key: bool,
pub alloc_hint: Option<u64>, // this is a usize but for IPC we must have defined memory sizes, so we pick the big option. pub alloc_hint: Option<u64>, // 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, pub result: PddbRequestCode,
} }

View file

@ -20,7 +20,7 @@ pub(crate) static REFCOUNT: AtomicU32 = AtomicU32::new(0);
pub(crate) static POLLER_REFCOUNT: AtomicU32 = AtomicU32::new(0); pub(crate) static POLLER_REFCOUNT: AtomicU32 = AtomicU32::new(0);
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
enum CbOp { pub enum CbOp {
Change, Change,
Quit Quit
} }
@ -73,8 +73,7 @@ impl Drop for PddbMountPoller {
pub struct Pddb { pub struct Pddb {
conn: CID, conn: CID,
/// a SID that we can directly share with the PDDB server for the purpose of handling key change callbacks /// a SID that we can directly share with the PDDB server for the purpose of handling key change callbacks
cb_sid: SID, cb: Option<(SID, JoinHandle::<()>)>,
cb_handle: Option<JoinHandle::<()>>,
/// Handle key change updates. The general intent is that the closure implements a /// 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, /// `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. /// but no mutable data is allowed within the closure itself due to safety problems.
@ -93,10 +92,19 @@ impl Pddb {
REFCOUNT.fetch_add(1, Ordering::Relaxed); REFCOUNT.fetch_add(1, Ordering::Relaxed);
let xns = xous_names::XousNames::new().unwrap(); 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 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<Mutex<HashMap<ApiToken, Box<dyn Fn() + 'static + Send> >>> = Arc::new(Mutex::new(HashMap::new())); let keys: Arc<Mutex<HashMap<ApiToken, Box<dyn Fn() + 'static + Send> >>> = Arc::new(Mutex::new(HashMap::new()));
Pddb {
conn,
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 handle = thread::spawn({
let keys = Arc::clone(&keys); let keys = Arc::clone(&self.keys);
let sid = sid.clone(); let sid = sid.clone();
move || { move || {
loop { loop {
@ -120,12 +128,7 @@ impl Pddb {
xous::destroy_server(sid).unwrap(); xous::destroy_server(sid).unwrap();
} }
}); });
Pddb { self.cb = Some((sid, handle));
conn,
cb_sid: sid,
cb_handle: Some(handle),
keys,
trng: trng::Trng::new(&xns).unwrap(),
} }
} }
/// This blocks until the PDDB is mounted by the end user. If `None` is specified for the poll_interval_ms, /// This blocks until the PDDB is mounted by the end user. If `None` is specified for the poll_interval_ms,
@ -310,6 +313,14 @@ impl Pddb {
xous_ipc::String::<BASIS_NAME_LEN>::new() xous_ipc::String::<BASIS_NAME_LEN>::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 { let request = PddbKeyRequest {
basis_specified: basis_name.is_some(), basis_specified: basis_name.is_some(),
basis: xous_ipc::String::<BASIS_NAME_LEN>::from_str(&bname), basis: xous_ipc::String::<BASIS_NAME_LEN>::from_str(&bname),
@ -319,7 +330,7 @@ impl Pddb {
create_key, create_key,
token: None, token: None,
result: PddbRequestCode::Uninit, 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}, alloc_hint: if let Some(a) = alloc_hint {Some(a as u64)} else {None},
}; };
let mut buf = Buffer::into_buf(request) let mut buf = Buffer::into_buf(request)
@ -380,6 +391,11 @@ impl Pddb {
xous_ipc::String::<BASIS_NAME_LEN>::new() xous_ipc::String::<BASIS_NAME_LEN>::new()
}; };
let cb_sid = if let Some((sid, _handle)) = &self.cb {
Some(sid.to_array())
} else {
None
};
let request = PddbKeyRequest { let request = PddbKeyRequest {
basis_specified: basis_name.is_some(), basis_specified: basis_name.is_some(),
basis: xous_ipc::String::<BASIS_NAME_LEN>::from_str(&bname), basis: xous_ipc::String::<BASIS_NAME_LEN>::from_str(&bname),
@ -389,7 +405,7 @@ impl Pddb {
create_key: false, create_key: false,
token: None, token: None,
result: PddbRequestCode::Uninit, result: PddbRequestCode::Uninit,
cb_sid: self.cb_sid.to_array(), cb_sid,
alloc_hint: None, alloc_hint: None,
}; };
let mut buf = Buffer::into_buf(request) let mut buf = Buffer::into_buf(request)
@ -418,6 +434,11 @@ impl Pddb {
xous_ipc::String::<BASIS_NAME_LEN>::new() xous_ipc::String::<BASIS_NAME_LEN>::new()
}; };
let cb_sid = if let Some((sid, _handle)) = &self.cb {
Some(sid.to_array())
} else {
None
};
let request = PddbKeyRequest { let request = PddbKeyRequest {
basis_specified: basis_name.is_some(), basis_specified: basis_name.is_some(),
basis: xous_ipc::String::<BASIS_NAME_LEN>::from_str(&bname), basis: xous_ipc::String::<BASIS_NAME_LEN>::from_str(&bname),
@ -427,7 +448,7 @@ impl Pddb {
create_key: false, create_key: false,
token: None, token: None,
result: PddbRequestCode::Uninit, result: PddbRequestCode::Uninit,
cb_sid: self.cb_sid.to_array(), cb_sid,
alloc_hint: None, alloc_hint: None,
}; };
let mut buf = Buffer::into_buf(request) let mut buf = Buffer::into_buf(request)
@ -607,10 +628,10 @@ impl Pddb {
impl Drop for Pddb { impl Drop for Pddb {
fn drop(&mut self) { fn drop(&mut self) {
let cid = xous::connect(self.cb_sid).unwrap(); 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(); send_message(cid, Message::new_blocking_scalar(CbOp::Quit.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
unsafe{xous::disconnect(cid).ok();} unsafe{xous::disconnect(cid).ok();}
if let Some(handle) = self.cb_handle.take() {
handle.join().expect("couldn't terminate callback helper thread"); handle.join().expect("couldn't terminate callback helper thread");
} }

View file

@ -405,12 +405,13 @@ pub(crate) enum PasswordState {
Uninit, Uninit,
} }
#[derive(Debug)]
struct TokenRecord { struct TokenRecord {
pub dict: String, pub dict: String,
pub key: String, pub key: String,
pub basis: Option<String>, pub basis: Option<String>,
pub alloc_hint: Option<usize>, pub alloc_hint: Option<usize>,
pub conn: xous::CID, // callback connection pub conn: Option<xous::CID>, // callback connection, if one was specified
} }
#[xous::xous_main] #[xous::xous_main]
@ -649,7 +650,6 @@ fn xmain() -> ! {
basis_cache.basis_add(basis); basis_cache.basis_add(basis);
finished = true; finished = true;
mgmt.code = PddbRequestCode::NoErr; mgmt.code = PddbRequestCode::NoErr;
}
} else { } else {
modals.add_list_item(t!("pddb.yes", 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");
modals.add_list_item(t!("pddb.no", 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");
@ -667,6 +667,11 @@ fn xmain() -> ! {
} }
_ => panic!("get_radiobutton failed"), _ => panic!("get_radiobutton failed"),
} }
xous::yield_slice(); // allow a redraw to happen before repeating the request
}
} else {
finished = true;
log::error!("internal error in basis unlock, aborting!");
} }
} }
} }
@ -679,6 +684,7 @@ fn xmain() -> ! {
Some(Opcode::CloseBasis) => { Some(Opcode::CloseBasis) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut mgmt = buffer.to_original::<PddbBasisRequest, _>().unwrap(); let mut mgmt = buffer.to_original::<PddbBasisRequest, _>().unwrap();
notify_of_disconnect(&mut pddb_os, &token_dict, &mut basis_cache);
match mgmt.code { match mgmt.code {
PddbRequestCode::Close => { PddbRequestCode::Close => {
match basis_cache.basis_unmount(&mut pddb_os, mgmt.name.as_str().expect("name is not valid utf-8")) { 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) => { Some(Opcode::DeleteBasis) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut mgmt = buffer.to_original::<PddbBasisRequest, _>().unwrap(); let mut mgmt = buffer.to_original::<PddbBasisRequest, _>().unwrap();
notify_of_disconnect(&mut pddb_os, &token_dict, &mut basis_cache);
match mgmt.code { match mgmt.code {
PddbRequestCode::Delete => { PddbRequestCode::Delete => {
match basis_cache.basis_delete(&mut pddb_os, mgmt.name.as_str().expect("name is not valid utf-8")) { 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. // 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 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 { let token_record = TokenRecord {
dict: String::from(dict), dict: String::from(dict),
key: String::from(key), key: String::from(key),
@ -785,15 +796,23 @@ fn xmain() -> ! {
if let Some(rec) = token_dict.remove(&token) { if let Some(rec) = token_dict.remove(&token) {
// now check if we can safely disconnect and recycle our connection number. // now check if we can safely disconnect and recycle our connection number.
// This is important because we can only have 32 outgoing connections... // This is important because we can only have 32 outgoing connections...
let mut has_cid = false; if let Some(conn_to_remove) = rec.conn {
let mut still_needs_cid = false;
for r in token_dict.values() { for r in token_dict.values() {
if r.conn == rec.conn { // check through the remaining dictionary values to see if they have a connection that is the same as our number
has_cid = true; if let Some(existing_conn) = r.conn {
if existing_conn == conn_to_remove {
still_needs_cid = true;
break; 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"); 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); pddb_os.dbg_dump(Some("manual".to_string()), None);
} }
fn notify_of_disconnect(pddb_os: &mut PddbOs, token_dict: &HashMap::<ApiToken, TokenRecord>, 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);
}
}
}
}
}

View file

@ -1,19 +1,13 @@
use xous::{SID, CID}; use xous::{SID, CID};
use xous::{msg_scalar_unpack, send_message}; use xous::msg_scalar_unpack;
use xous_ipc::Buffer; use xous_ipc::Buffer;
use std::sync::{Arc, Mutex};
use std::thread;
use core::sync::atomic::{AtomicBool, Ordering};
use num_traits::*; use num_traits::*;
use gam::modal::*; use gam::modal::*;
use locales::t; use locales::t;
use std::fmt::Write;
use crate::BasisRequestPassword; use crate::BasisRequestPassword;
/* /*
Conclusions: Conclusions:
@ -54,12 +48,6 @@ GAM Modal Object -> redraw -> gam requests
pub(crate) enum PwManagerOpcode { pub(crate) enum PwManagerOpcode {
// blocking call to get a password // blocking call to get a password
RequestPassword, RequestPassword,
Quit,
}
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum PwRendererOpcode {
RaisePwModal,
PwReturn, PwReturn,
ModalRedraw, ModalRedraw,
ModalKeypress, ModalKeypress,
@ -73,24 +61,14 @@ pub(crate) fn password_ux_manager(
// the SID we're to use for our loop handler, for getting requests // the SID we're to use for our loop handler, for getting requests
ux_sid: SID) { ux_sid: SID) {
let tt = ticktimer_server::Ticktimer::new().unwrap(); let ux_cid = xous::connect(ux_sid).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));
// create a thread that just handles the redrawing requests // 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 // build the core data structure here
let password_action = TextEntry { let password_action = TextEntry {
is_password: true, is_password: true,
visibility: TextEntryVisibility::LastChars, visibility: TextEntryVisibility::LastChars,
action_conn: renderer_cid, action_conn: ux_cid,
action_opcode: PwRendererOpcode::PwReturn.to_u32().unwrap(), action_opcode: PwManagerOpcode::PwReturn.to_u32().unwrap(),
action_payload: TextEntryPayload::new(), action_payload: TextEntryPayload::new(),
validator: None, validator: None,
}; };
@ -104,47 +82,56 @@ pub(crate) fn password_ux_manager(
GlyphStyle::Regular, GlyphStyle::Regular,
8 8
); );
pddb_modal.spawn_helper(renderer_sid, pddb_modal.sid, pddb_modal.spawn_helper(ux_sid, pddb_modal.sid,
PwRendererOpcode::ModalRedraw.to_u32().unwrap(), PwManagerOpcode::ModalRedraw.to_u32().unwrap(),
PwRendererOpcode::ModalKeypress.to_u32().unwrap(), PwManagerOpcode::ModalKeypress.to_u32().unwrap(),
PwRendererOpcode::ModalDrop.to_u32().unwrap(), PwManagerOpcode::ModalDrop.to_u32().unwrap(),
); );
let mut dr: Option<xous::MessageEnvelope> = None;
// the main loop merely wraps a blocking wrapper around the renderer thread
loop { loop {
let msg = xous::receive_message(renderer_sid).unwrap(); let msg = xous::receive_message(ux_sid).unwrap();
log::debug!("message: {:?}", msg); log::debug!("message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(PwRendererOpcode::RaisePwModal) => { Some(PwManagerOpcode::RequestPassword) => {
let db_name = {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let db_name = buffer.to_original::<xous_ipc::String::<{crate::api::BASIS_NAME_LEN}>, _>().unwrap(); let request = buffer.to_original::<BasisRequestPassword, _>().unwrap();
request.db_name
};
pddb_modal.modify( pddb_modal.modify(
Some(ActionType::TextEntry(password_action)), Some(ActionType::TextEntry(password_action)),
Some(t!("pddb.password", xous::LANG)), false, Some(t!("pddb.password", xous::LANG)), false,
Some(db_name.as_str().unwrap()), false, None Some(format!("{}'{}'", t!("pddb.password_for", xous::LANG), db_name.as_str().unwrap()).as_str()), false, None
); );
pddb_modal.activate(); pddb_modal.activate();
} dr = Some(msg);
Some(PwRendererOpcode::PwReturn) => {
if renderer_active.load(Ordering::SeqCst) { },
Some(PwManagerOpcode::PwReturn) => {
let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let mut pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap(); let mut pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap();
plaintext_pw.lock().unwrap().clear(); if let Some(mut response) = dr.take() {
write!(plaintext_pw.lock().unwrap(), "{}", pw.as_str()).expect("couldn't transfer password to local buffer"); let mut buffer = unsafe { Buffer::from_memory_message_mut(response.body.memory_message_mut().unwrap()) };
let mut request = buffer.to_original::<BasisRequestPassword, _>().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 pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave
buf.volatile_clear(); 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) => { Some(PwManagerOpcode::ModalRedraw) => {
pddb_modal.redraw(); pddb_modal.redraw();
}, },
Some(PwRendererOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { Some(PwManagerOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [ let keys = [
core::char::from_u32(k1 as u32).unwrap_or('\u{0000}'), 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(k2 as u32).unwrap_or('\u{0000}'),
@ -153,64 +140,20 @@ pub(crate) fn password_ux_manager(
]; ];
pddb_modal.key_event(keys); pddb_modal.key_event(keys);
}), }),
Some(PwRendererOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service Some(PwManagerOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service
panic!("Password modal for PDDB quit unexpectedly"); panic!("Password modal for PDDB quit unexpectedly");
}, },
Some(PwRendererOpcode::Quit) => { Some(PwManagerOpcode::Quit) => {
log::warn!("received quit on PDDB password UX renderer loop"); log::warn!("received quit on PDDB password UX renderer loop");
xous::return_scalar(msg.sender, 0).unwrap(); xous::return_scalar(msg.sender, 0).unwrap();
break; break;
}, },
None => {
log::error!("Couldn't convert opcode: {:?}", msg);
}
}
}
xous::destroy_server(renderer_sid).unwrap();
}
});
// the main loop merely wraps a blocking wrapper around the renderer thread
loop {
let mut 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::<BasisRequestPassword, _>().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);
// return the password to the caller
buffer.replace(request).unwrap();
},
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();
xous::return_scalar(msg.sender, 0).unwrap();
break
},
None => { None => {
log::error!("couldn't convert opcode"); 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(); xous::destroy_server(ux_sid).unwrap();
} }

View file

@ -21,9 +21,9 @@ impl<'a> ShellCmdApi<'a> for PddbCmd {
use core::fmt::Write; use core::fmt::Write;
let mut ret = String::<1024>::new(); let mut ret = String::<1024>::new();
#[cfg(not(feature="pddbtest"))] #[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")] #[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(' '); let mut tokens = args.as_str().unwrap().split(' ');
if let Some(sub_cmd) = tokens.next() { if let Some(sub_cmd) = tokens.next() {
@ -43,6 +43,52 @@ impl<'a> ShellCmdApi<'a> for PddbCmd {
}}) }})
).unwrap();*/ ).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" => { "query" => {
if let Some(descriptor) = tokens.next() { if let Some(descriptor) = tokens.next() {
if let Some((dict, keyname)) = descriptor.split_once(':') { 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 // note that this feature only works in hosted mode
#[cfg(feature="pddbtest")] #[cfg(feature="pddbtest")]
"test" => { "test" => {
let bname = tokens.next();
// zero-length key test // zero-length key test
let mut test_handle = pddb::Pddb::new(); let mut test_handle = pddb::Pddb::new();
// build a key, but don't write to it. // build a key, but don't write to it.
@ -179,10 +226,22 @@ impl<'a> ShellCmdApi<'a> for PddbCmd {
"zerolength", "zerolength",
None, true, true, None, true, true,
Some(8), Some(8),
None::<fn()> None::<fn()>,
).expect("couldn't build empty key"); ).expect("couldn't build empty key");
self.pddb.sync().unwrap(); 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(); 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(); self.pddb.dbg_dump("std_test1").unwrap();
write!(ret, "dumped std_test1\n").unwrap(); write!(ret, "dumped std_test1\n").unwrap();
log::info!("finished zero-length alloc"); log::info!("finished zero-length alloc");
@ -202,7 +261,9 @@ impl<'a> ShellCmdApi<'a> for PddbCmd {
"seekwrite", "seekwrite",
None, true, true, None, true, true,
Some(64), Some(64),
None::<fn()> Some(|| {
log::info!("test:seekwrite key was unmounted");
})
).expect("couldn't build empty key"); ).expect("couldn't build empty key");
// 1, 1, 1, 1 // 1, 1, 1, 1
log::info!("wrote {} bytes at offset 0", log::info!("wrote {} bytes at offset 0",
@ -215,6 +276,18 @@ impl<'a> ShellCmdApi<'a> for PddbCmd {
log::info!("wrote {} bytes at offset 2", log::info!("wrote {} bytes at offset 2",
seekwrite.write(&[2, 2, 2, 2]).unwrap() 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 // 1, 1, 2, 2, 2, 2, 0, 0, 3, 3
log::info!("seek to {}", log::info!("seek to {}",
seekwrite.seek(SeekFrom::Start(8)).unwrap() seekwrite.seek(SeekFrom::Start(8)).unwrap()