diff --git a/services/pddb/src/api.rs b/services/pddb/src/api.rs index 100eaedef..0cbedb970 100644 --- a/services/pddb/src/api.rs +++ b/services/pddb/src/api.rs @@ -64,6 +64,12 @@ pub(crate) const PDDB_MODAL_NAME: &'static str = "pddb modal"; pub(crate) enum Opcode { ListBasis, LatestBasis, + /// Note that creating a basis does not automatically open it! + CreateBasis, + OpenBasis, + CloseBasis, + /// warning, the Delete routine has not been well tested + DeleteBasis, KeyRequest, @@ -83,6 +89,27 @@ pub struct PddbBasisList { /// total number of basis open. Should be <= 63, but we allow it to be larger to indicate cases where this structure wasn't big enough. pub num: u32, } +#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub enum PddbBasisMgmtCode { + Create, + Open, + Close, + Delete, + NoErr, + NotMounted, + NoFreeSpace, + NotFound, + InternalError, + AccessDenied, + Uninit, +} +#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub struct PddbBasisMgmt { + /// the first 63 that fit in the list -- generally we anticipate not more than a few being open at a time, so this should be enough. + pub name: [u8; BASIS_NAME_LEN], + /// total number of basis open. Should be <= 63, but we allow it to be larger to indicate cases where this structure wasn't big enough. + pub code: PddbBasisMgmtCode, +} /// A structure for requesting a token to access a particular key/value pair #[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] diff --git a/services/pddb/src/backend/basis.rs b/services/pddb/src/backend/basis.rs index 862952529..b0e1aa13e 100644 --- a/services/pddb/src/backend/basis.rs +++ b/services/pddb/src/backend/basis.rs @@ -921,15 +921,20 @@ impl BasisCache { /// note: you can "delete" a basis simply by forgetting its password, but this is more thorough. /// there might also need to be a variant to make which is a "change my password" function, but that is actually /// surprisingly hard. - #[allow(dead_code)] - pub(crate) fn basis_delete(&mut self, hw: &mut PddbOs, mut basis: BasisCacheEntry) { - let mut temp: [u8; PAGE_SIZE] = [0; PAGE_SIZE]; - for page in basis.v2p_map.values_mut() { - hw.trng_slice(&mut temp); - hw.patch_data(&temp, page.page_number() * PAGE_SIZE as u32); - hw.fast_space_free(page); + pub(crate) fn basis_delete(&mut self, hw: &mut PddbOs, basis_name: &str) -> Result<()> { + if let Some(basis_index) = self.select_basis(Some(basis_name)) { + let basis = &mut self.cache[basis_index]; + let mut temp: [u8; PAGE_SIZE] = [0; PAGE_SIZE]; + for page in basis.v2p_map.values_mut() { + hw.trng_slice(&mut temp); + hw.patch_data(&temp, page.page_number() * PAGE_SIZE as u32); + hw.fast_space_free(page); + } + basis.pt_sync(hw); + Ok(()) + } else { + Err(Error::new(ErrorKind::NotFound, "Basis not found")) } - basis.pt_sync(hw); } pub(crate) fn sync(&mut self, hw: &mut PddbOs, basis_name: Option<&str>) -> Result<()> { diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index 4cbc6facd..89f7bb5ca 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -51,35 +51,104 @@ impl PddbBasisManager { /// returns the latest basis that is opened -- this is where all new values are being sent by default /// if the PDDB is not mounted, returns None pub fn latest_basis(&self) -> Option { - // just re-use this structure -- because we have to clear the whole page anyways to share it - let list_alloc = PddbBasisList { - list: [[0u8; BASIS_NAME_LEN]; 63], - num: 0 + let mgmt = PddbBasisMgmt { + name: [0u8; BASIS_NAME_LEN], + code: PddbBasisMgmtCode::Uninit, }; - let mut buf = Buffer::into_buf(list_alloc).expect("Couldn't convert to memory structure"); + let mut buf = Buffer::into_buf(mgmt).expect("Couldn't convert to memory structure"); buf.lend_mut(self.conn, Opcode::LatestBasis.to_u32().unwrap()).expect("Couldn't execute ListBasis opcode"); - let list = buf.to_original::().expect("couldn't restore list structure"); - if list.num == 1 { - Some(cstr_to_string(&list.list[0])) - } else if list.num == 0 { - None - } else { - log::error!("Either 1 or 0 items should be returned by the latest basis call"); - panic!("Either 1 or 0 items should be returned by the latest basis call"); + let ret = buf.to_original::().expect("couldn't restore list structure"); + match ret.code { + PddbBasisMgmtCode::NoErr => { + Some(cstr_to_string(&ret.name)) + } + PddbBasisMgmtCode::NotMounted => { + None + } + _ => { + log::error!("Invalid return from latest basis call"); + panic!("Invalid return from latest basis call"); + } } } - pub fn create(basis_name: &str) -> Result<()> { - Ok(()) + pub fn create(&self, basis_name: &str) -> Result<()> { + let mut mgmt = PddbBasisMgmt { + name: [0u8; BASIS_NAME_LEN], + code: PddbBasisMgmtCode::Create, + }; + for (&src, dst) in basis_name.as_bytes().iter().zip(mgmt.name.iter_mut()) {*dst = src} + let mut buf = Buffer::into_buf(mgmt).expect("Couldn't convert to memory structure"); + buf.lend_mut(self.conn, Opcode::CreateBasis.to_u32().unwrap()).expect("Couldn't execute CreateBasis opcode"); + let ret = buf.to_original::().expect("couldn't restore mgmt structure"); + match ret.code { + PddbBasisMgmtCode::NoErr => Ok(()), + PddbBasisMgmtCode::NoFreeSpace => Err(Error::new(ErrorKind::OutOfMemory, "No free space to create basis")), + PddbBasisMgmtCode::InternalError => Err(Error::new(ErrorKind::Other, "Internal error creating basis")), + _ => { + log::error!("Invalid return code"); + panic!("Invalid return code"); + } + } } - pub fn open(basis_name: &str) -> Result<()> { - Ok(()) + pub fn open(&self, basis_name: &str) -> Result<()> { + let mut mgmt = PddbBasisMgmt { + name: [0u8; BASIS_NAME_LEN], + code: PddbBasisMgmtCode::Open, + }; + for (&src, dst) in basis_name.as_bytes().iter().zip(mgmt.name.iter_mut()) {*dst = src} + let mut buf = Buffer::into_buf(mgmt).expect("Couldn't convert to memory structure"); + buf.lend_mut(self.conn, Opcode::OpenBasis.to_u32().unwrap()).expect("Couldn't execute OpenBasis opcode"); + let ret = buf.to_original::().expect("couldn't restore mgmt structure"); + match ret.code { + PddbBasisMgmtCode::NoErr => Ok(()), + PddbBasisMgmtCode::AccessDenied => Err(Error::new(ErrorKind::PermissionDenied, "Authentication error")), + PddbBasisMgmtCode::InternalError => Err(Error::new(ErrorKind::Other, "Internal error creating basis")), + _ => { + log::error!("Invalid return code"); + panic!("Invalid return code"); + } + } } - pub fn close(basis_name: &str) -> Result<()> { - Ok(()) + pub fn close(&self, basis_name: &str) -> Result<()> { + let mut mgmt = PddbBasisMgmt { + name: [0u8; BASIS_NAME_LEN], + code: PddbBasisMgmtCode::Close, + }; + for (&src, dst) in basis_name.as_bytes().iter().zip(mgmt.name.iter_mut()) {*dst = src} + let mut buf = Buffer::into_buf(mgmt).expect("Couldn't convert to memory structure"); + buf.lend_mut(self.conn, Opcode::CloseBasis.to_u32().unwrap()).expect("Couldn't execute CloseBasis opcode"); + let ret = buf.to_original::().expect("couldn't restore mgmt structure"); + match ret.code { + PddbBasisMgmtCode::NoErr => Ok(()), + PddbBasisMgmtCode::NotFound => Err(Error::new(ErrorKind::NotFound, "Basis not found")), + PddbBasisMgmtCode::InternalError => Err(Error::new(ErrorKind::Other, "Internal error closing basis")), + _ => { + log::error!("Invalid return code"); + panic!("Invalid return code"); + } + } + } + pub fn delete(&self, basis_name: &str) -> Result<()> { + let mut mgmt = PddbBasisMgmt { + name: [0u8; BASIS_NAME_LEN], + code: PddbBasisMgmtCode::Delete, + }; + for (&src, dst) in basis_name.as_bytes().iter().zip(mgmt.name.iter_mut()) {*dst = src} + let mut buf = Buffer::into_buf(mgmt).expect("Couldn't convert to memory structure"); + buf.lend_mut(self.conn, Opcode::DeleteBasis.to_u32().unwrap()).expect("Couldn't execute DeleteBasis opcode"); + let ret = buf.to_original::().expect("couldn't restore mgmt structure"); + match ret.code { + PddbBasisMgmtCode::NoErr => Ok(()), + PddbBasisMgmtCode::NotFound => Err(Error::new(ErrorKind::NotFound, "Basis not found")), + PddbBasisMgmtCode::InternalError => Err(Error::new(ErrorKind::Other, "Internal error deleting basis")), + _ => { + log::error!("Invalid return code"); + panic!("Invalid return code"); + } + } } } -// this structure can be shared on the user side? pub struct Pddb<'a> { conn: CID, contents: HashMap, &'a [u8]>, diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index c526449a4..20937dfc1 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -374,6 +374,7 @@ use ux::*; #[cfg(not(any(target_os = "none", target_os = "xous")))] mod tests; #[cfg(not(any(target_os = "none", target_os = "xous")))] +#[allow(unused_imports)] use tests::*; use num_traits::*; @@ -384,6 +385,7 @@ use std::rc::Rc; use std::thread; use std::collections::HashSet; use std::hash::{Hash, Hasher}; +use std::io::ErrorKind; use locales::t; @@ -461,17 +463,7 @@ fn xmain() -> ! { ) } }); - // stub for testing the password request mechanism - if false { - let request = BasisRequestPassword { - db_name: xous_ipc::String::<{crate::api::BASIS_NAME_LEN}>::from_str("test basis"), - plaintext_pw: None, - }; - let mut buf = Buffer::into_buf(request).unwrap(); - buf.lend_mut(pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap()).unwrap(); - let ret = buf.to_original::().unwrap(); - log::info!("Got password: {:?}", ret.plaintext_pw); - } + // 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"); @@ -556,6 +548,7 @@ fn xmain() -> ! { } } } + // main server loop loop { let mut msg = xous::receive_message(pddb_sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { @@ -573,14 +566,132 @@ fn xmain() -> ! { } Some(Opcode::LatestBasis) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; - let mut list_ipc = buffer.to_original::().unwrap(); + let mut mgmt = buffer.to_original::().unwrap(); if let Some(name) = basis_cache.basis_latest() { - for (&src, dst) in name.as_bytes().iter().zip(list_ipc.list[0].iter_mut()) { *dst = src } - list_ipc.num = 1; + for (&src, dst) in name.as_bytes().iter().zip(mgmt.name.iter_mut()) { *dst = src } + mgmt.code = PddbBasisMgmtCode::NoErr; } else { - list_ipc.num = 0; + mgmt.code = PddbBasisMgmtCode::NotMounted; } - buffer.replace(list_ipc).unwrap(); + buffer.replace(mgmt).unwrap(); + } + Some(Opcode::CreateBasis) => { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut mgmt = buffer.to_original::().unwrap(); + match mgmt.code { + PddbBasisMgmtCode::Create => { + let name = cstr_to_string(&mgmt.name); + let request = BasisRequestPassword { + db_name: xous_ipc::String::<{crate::api::BASIS_NAME_LEN}>::from_str(name.as_str()), + plaintext_pw: None, + }; + let mut buf = Buffer::into_buf(request).unwrap(); + buf.lend_mut(pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap()).unwrap(); + let ret = buf.to_original::().unwrap(); + if let Some(pw) = ret.plaintext_pw { + match basis_cache.basis_create(&mut pddb_os, &name, pw.as_str().expect("password was not valid utf-8")) { + Ok(_) => mgmt.code = PddbBasisMgmtCode::NoErr, + _ => mgmt.code = PddbBasisMgmtCode::InternalError, + } + } else { + mgmt.code = PddbBasisMgmtCode::InternalError; + } + } + _ => { + mgmt.code = PddbBasisMgmtCode::InternalError; + } + } + buffer.replace(mgmt).unwrap(); + } + Some(Opcode::OpenBasis) => { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut mgmt = buffer.to_original::().unwrap(); + match mgmt.code { + PddbBasisMgmtCode::Open => { + let name = cstr_to_string(&mgmt.name); + let mut finished = false; + while !finished { + let request = BasisRequestPassword { + db_name: xous_ipc::String::<{crate::api::BASIS_NAME_LEN}>::from_str(name.as_str()), + plaintext_pw: None, + }; + let mut buf = Buffer::into_buf(request).unwrap(); + buf.lend_mut(pw_cid, PwManagerOpcode::RequestPassword.to_u32().unwrap()).unwrap(); + let ret = buf.to_original::().unwrap(); + if let Some(pw) = ret.plaintext_pw { + if let Some(basis) = basis_cache.basis_unlock( + &mut pddb_os, &name, pw.as_str().expect("password was not valid utf-8"), + BasisRetentionPolicy::Persist + ) { + basis_cache.basis_add(basis); + finished = true; + mgmt.code = PddbBasisMgmtCode::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 = PddbBasisMgmtCode::AccessDenied; // this will cause a return of AccessDenied + } else { + panic!("Got unexpected return from radiobutton"); + } + } + _ => panic!("get_radiobutton failed"), + } + } + } + } + _ => { + mgmt.code = PddbBasisMgmtCode::InternalError; + } + } + buffer.replace(mgmt).unwrap(); + } + 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(); + match mgmt.code { + PddbBasisMgmtCode::Close => { + let name = cstr_to_string(&mgmt.name); + match basis_cache.basis_unmount(&mut pddb_os, &name) { + Ok(_) => mgmt.code = PddbBasisMgmtCode::NoErr, + Err(e) => match e.kind() { + ErrorKind::NotFound => mgmt.code = PddbBasisMgmtCode::NotFound, + _ => mgmt.code = PddbBasisMgmtCode::InternalError, + } + } + } + _ => { + mgmt.code = PddbBasisMgmtCode::InternalError; + } + } + buffer.replace(mgmt).unwrap(); + } + 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(); + match mgmt.code { + PddbBasisMgmtCode::Delete => { + let name = cstr_to_string(&mgmt.name); + match basis_cache.basis_delete(&mut pddb_os, &name) { + Ok(_) => mgmt.code = PddbBasisMgmtCode::NoErr, + Err(e) => match e.kind() { + ErrorKind::NotFound => mgmt.code = PddbBasisMgmtCode::NotFound, + _ => mgmt.code = PddbBasisMgmtCode::InternalError, + } + } + } + _ => { + mgmt.code = PddbBasisMgmtCode::InternalError; + } + } + buffer.replace(mgmt).unwrap(); } Some(Opcode::KeyRequest) => { // placeholder