add basis management functions and debug some basis issues

there's some problems with the automatic basis unionization
feature. now debugging...
This commit is contained in:
bunnie 2022-06-26 02:11:13 +08:00
parent 475fadb255
commit e62c9bf3d3
5 changed files with 270 additions and 90 deletions

View file

@ -1,4 +1,34 @@
{ {
"vault.basis.name": {
"en": "Enter name of Basis to unlock:",
"ja": "ロックを解除する基準の名前を入力してください:",
"zh": "输入要解锁的基础名称:",
"en-tts": "Enter name of Basis to unlock:"
},
"vault.basis.create": {
"en": "Enter name of Basis to create:",
"ja": "作成する基準の名前を入力します:",
"zh": "输入要创建的基础名称:",
"en-tts": "Enter name of Basis to create:"
},
"vault.basis.created_mount": {
"en": "Basis created. Mount it now?",
"ja": "ベーシスが作成されました。 今それをマウントしますか?",
"zh": "创建的基础。 现在装吗?",
"en-tts": "Basis created. Mount it now?"
},
"vault.basis.none": {
"en": "No active secret Bases. Would you like to create one?",
"ja": "アクティブな秘密の根拠はありません。 作成しますか?",
"zh": "没有有效的秘密基础。 你想创建一个吗?",
"en-tts": "No active secret Bases. Would you like to create one?"
},
"vault.basis.unmount": {
"en": "Select the Bases to unmount:",
"ja": "アンマウントするベースを選択します:",
"zh": "选择要卸载的基础:",
"en-tts": "Select the Bases to unmount:"
},
"vault.edit_dialog": { "vault.edit_dialog": {
"en": "Make your changes and press enter.\nUse the d-pad to navigate entries.", "en": "Make your changes and press enter.\nUse the d-pad to navigate entries.",
"ja": "変更を加えてEnterキーを押します。 D-PADを使用してエントリをナビゲートします。", "ja": "変更を加えてEnterキーを押します。 D-PADを使用してエントリをナビゲートします。",
@ -17,6 +47,12 @@
"zh": "现在自动输入...", "zh": "现在自动输入...",
"en-tts": "Autotyping..." "en-tts": "Autotyping..."
}, },
"vault.error.basis_unlock_error": {
"en": "Basis does not exist. Or maybe wrong password?",
"ja": "根拠は存在しません。 または多分間違ったパスワード?",
"zh": "基础不存在。 或者密码错误?",
"en-tts": "Basis does not exist. Or maybe wrong password?"
},
"vault.error.mount_pddb": { "vault.error.mount_pddb": {
"en": "PDDB not mounted. Please init root keys and then init PDDB.", "en": "PDDB not mounted. Please init root keys and then init PDDB.",
"ja": "PDDBがマウントされていません。 ルートキーを初期化してから、PDDBを初期化してください。", "ja": "PDDBがマウントされていません。 ルートキーを初期化してから、PDDBを初期化してください。",
@ -359,6 +395,18 @@
"zh": "更改字体", "zh": "更改字体",
"en-tts": "🔇" "en-tts": "🔇"
}, },
"vault.menu_unlock_basis": {
"en": "Unlock secret Basis",
"ja": "シークレットベースのロックを解除",
"zh": "解锁秘密基础",
"en-tts": "Unlock secret basis"
},
"vault.menu_manage_basis": {
"en": "Manage Bases",
"ja": "管理基盤",
"zh": "管理基础",
"en-tts": "Manage Bases"
},
"vault.menu_close": { "vault.menu_close": {
"en": "Close submenu", "en": "Close submenu",
"ja": "メニューを閉じる", "ja": "メニューを閉じる",

View file

@ -1,6 +1,7 @@
use core::convert::TryFrom; use core::convert::TryFrom;
use std::thread; use std::{thread, io::ErrorKind};
use gam::TextEntryPayload; use gam::TextEntryPayload;
use pddb::BasisRetentionPolicy;
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use num_traits::*; use num_traits::*;
use xous::{SID, msg_blocking_scalar_unpack, Message, send_message}; use xous::{SID, msg_blocking_scalar_unpack, Message, send_message};
@ -58,6 +59,8 @@ pub(crate) enum ActionOp {
MenuEditStage2, MenuEditStage2,
MenuDeleteStage2, MenuDeleteStage2,
MenuClose, MenuClose,
MenuUnlockBasis,
MenuManageBasis,
/// Internal ops /// Internal ops
UpdateMode, UpdateMode,
Quit, Quit,
@ -103,6 +106,16 @@ pub(crate) fn start_actions_thread(
manager.retrieve_db(); manager.retrieve_db();
manager.deactivate(); manager.deactivate();
}, },
Some(ActionOp::MenuUnlockBasis) => {
manager.activate();
manager.unlock_basis();
manager.deactivate();
},
Some(ActionOp::MenuManageBasis) => {
manager.activate();
manager.manage_basis();
manager.deactivate();
}
Some(ActionOp::MenuClose) => { Some(ActionOp::MenuClose) => {
// dummy activate/de-activate cycle because we have to trigger a redraw of the underlying UX // dummy activate/de-activate cycle because we have to trigger a redraw of the underlying UX
manager.activate(); manager.activate();
@ -876,6 +889,87 @@ impl ActionManager {
} }
il.sort(); il.sort();
} }
pub(crate) fn unlock_basis(&mut self) {
let name = match self.modals
.alert_builder(t!("vault.basis.name", xous::LANG))
.field(None, Some(name_validator))
.build()
{
Ok(text) => {
text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string()
},
_ => {log::error!("Name entry failed"); self.action_active.store(false, Ordering::SeqCst); return}
};
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
match self.pddb.borrow().unlock_basis(&name, Some(BasisRetentionPolicy::Persist)) {
Ok(_) => log::debug!("Basis {} unlocked", name),
Err(e) => match e.kind() {
ErrorKind::PermissionDenied => {
self.report_err(t!("vault.error.basis_unlock_error", xous::LANG), None::<std::io::Error>)
},
_ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
}
}
pub(crate) fn manage_basis(&mut self) {
let mut bases = self.pddb.borrow().list_basis();
bases.retain(|name| name != pddb::PDDB_DEFAULT_SYSTEM_BASIS);
let b: Vec<&str> = bases.iter().map(AsRef::as_ref).collect();
if bases.len() > 0 {
self.modals
.add_list(
b
).expect("couldn't create unmount modal");
match self.modals.get_checkbox(t!("vault.basis.unmount", xous::LANG)) {
Ok(unmount) => {
for b in unmount {
match self.pddb.borrow().lock_basis(&b) {
Ok(_) => log::debug!("basis {} locked", b),
Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
}
}
Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
} else {
if self.yes_no_approval(t!("vault.basis.none", xous::LANG)) {
let name = match self.modals
.alert_builder(t!("vault.basis.create", xous::LANG))
.field(None, Some(name_validator))
.build()
{
Ok(text) => {
text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string()
},
Err(e) => {self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)); return}
};
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
match self.pddb.borrow().create_basis(&name) {
Ok(_) => {
if self.yes_no_approval(t!("vault.basis.created_mount", xous::LANG)) {
match self.pddb.borrow().unlock_basis(&name, Some(BasisRetentionPolicy::Persist)) {
Ok(_) => log::debug!("Basis {} unlocked", name),
Err(e) => match e.kind() {
ErrorKind::PermissionDenied => {
self.report_err(t!("vault.error.basis_unlock_error", xous::LANG), None::<std::io::Error>)
},
_ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
}
} else {
// do nothing
}
}
Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
} else {
// do nothing
}
}
}
#[cfg(feature="testing")] #[cfg(feature="testing")]
pub(crate) fn populate_tests(&mut self) { pub(crate) fn populate_tests(&mut self) {
use crate::ux::serialize_app_info; use crate::ux::serialize_app_info;

View file

@ -22,6 +22,20 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr:
action_payload: MenuPayload::Scalar([0, 0, 0, 0]), action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true, close_on_select: true,
}); });
menu_items.push(MenuItem {
name: xous_ipc::String::from_str(t!("vault.menu_unlock_basis", xous::LANG)),
action_conn: Some(actions_conn),
action_opcode: ActionOp::MenuUnlockBasis.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
menu_items.push(MenuItem {
name: xous_ipc::String::from_str(t!("vault.menu_manage_basis", xous::LANG)),
action_conn: Some(actions_conn),
action_opcode: ActionOp::MenuManageBasis.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
menu_items.push(MenuItem { menu_items.push(MenuItem {
name: xous_ipc::String::from_str(t!("vault.menu_change_font", xous::LANG)), name: xous_ipc::String::from_str(t!("vault.menu_change_font", xous::LANG)),
action_conn: Some(vault_conn), action_conn: Some(vault_conn),

View file

@ -256,6 +256,14 @@ impl BasisCache {
tt: ticktimer_server::Ticktimer::new().unwrap(), tt: ticktimer_server::Ticktimer::new().unwrap(),
} }
} }
/// Returns a Vec which is a list of Bases to visit, in order of visitation, to create the union view.
pub(crate) fn access_list(&self) -> Vec::<String> {
let mut al = Vec::<String>::new();
for entry in self.cache.iter().rev() {
al.push(entry.name.to_string());
}
al
}
fn select_basis(&mut self, basis_name: Option<&str>) -> Option<usize> { fn select_basis(&mut self, basis_name: Option<&str>) -> Option<usize> {
if self.cache.len() == 0 { if self.cache.len() == 0 {
log::error!("Can't select basis: PDDB is not mounted"); log::error!("Can't select basis: PDDB is not mounted");
@ -941,6 +949,7 @@ impl BasisCache {
} }
} else { } else {
for basis in self.cache.iter_mut() { for basis in self.cache.iter_mut() {
log::info!("syncing {}", basis.name);
basis.sync(hw)?; basis.sync(hw)?;
} }
} }

View file

@ -779,74 +779,76 @@ fn main() -> ! {
buffer.replace(mgmt).unwrap(); buffer.replace(mgmt).unwrap();
} }
Some(Opcode::KeyRequest) => { Some(Opcode::KeyRequest) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; for basis in basis_cache.access_list().iter() {
let mut req: PddbKeyRequest = buffer.to_original::<PddbKeyRequest, _>().unwrap(); let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let bname = if req.basis_specified { let mut req: PddbKeyRequest = buffer.to_original::<PddbKeyRequest, _>().unwrap();
Some(req.basis.as_str().unwrap()) let bname = if req.basis_specified {
} else { Some(req.basis.as_str().unwrap())
None } else {
}; Some(basis.as_str())
let dict = req.dict.as_str().expect("dict utf-8 decode error"); };
let key = req.key.as_str().expect("key utf-8 decode error"); let dict = req.dict.as_str().expect("dict utf-8 decode error");
if basis_cache.dict_attributes(&mut pddb_os, dict, bname).is_err() { let key = req.key.as_str().expect("key utf-8 decode error");
if req.create_dict { if basis_cache.dict_attributes(&mut pddb_os, dict, bname).is_err() {
match basis_cache.dict_add(&mut pddb_os, dict, bname) { if req.create_dict {
Ok(_) => (), match basis_cache.dict_add(&mut pddb_os, dict, bname) {
Err(e) => { Ok(_) => (),
match e.kind() { Err(e) => {
std::io::ErrorKind::OutOfMemory => {req.result = PddbRequestCode::NoFreeSpace; buffer.replace(req).unwrap(); continue} match e.kind() {
std::io::ErrorKind::NotFound => {req.result = PddbRequestCode::NotMounted; buffer.replace(req).unwrap(); continue} std::io::ErrorKind::OutOfMemory => {req.result = PddbRequestCode::NoFreeSpace; buffer.replace(req).unwrap(); continue}
_ => {req.result = PddbRequestCode::InternalError; buffer.replace(req).unwrap(); continue} std::io::ErrorKind::NotFound => {req.result = PddbRequestCode::NotMounted; buffer.replace(req).unwrap(); continue}
_ => {req.result = PddbRequestCode::InternalError; buffer.replace(req).unwrap(); continue}
}
}
}
} else {
req.result = PddbRequestCode::NotFound;
buffer.replace(req).unwrap(); continue
}
}
let alloc_hint = if let Some(hint) = req.alloc_hint {Some(hint as usize)} else {None};
if basis_cache.key_attributes(&mut pddb_os, dict, key, bname).is_err() {
if !req.create_key {
req.result = PddbRequestCode::NotFound;
buffer.replace(req).unwrap(); continue
} else {
// create an empty key placeholder
let empty: [u8; 0] = [];
match basis_cache.key_update(&mut pddb_os,
dict, key, &empty, None, alloc_hint, bname, true
) {
Ok(_) => {},
Err(e) => {
log::error!("Couldn't allocate key: {:?}", e);
match e.kind() {
std::io::ErrorKind::NotFound => req.result = PddbRequestCode::NotMounted,
std::io::ErrorKind::OutOfMemory => req.result = PddbRequestCode::NoFreeSpace,
_ => req.result = PddbRequestCode::InternalError,
}
buffer.replace(req).unwrap(); continue
} }
} }
} }
} else {
req.result = PddbRequestCode::NotFound;
buffer.replace(req).unwrap(); continue
} }
} // at this point, we have established a basis/dict/key tuple.
let alloc_hint = if let Some(hint) = req.alloc_hint {Some(hint as usize)} else {None}; let token: ApiToken = [pddb_os.trng_u32(), pddb_os.trng_u32(), pddb_os.trng_u32()];
if basis_cache.key_attributes(&mut pddb_os, dict, key, bname).is_err() { let cid = if let Some(cb_sid) = req.cb_sid {
if !req.create_key { Some(xous::connect(xous::SID::from_array(cb_sid)).expect("couldn't connect for callback"))
req.result = PddbRequestCode::NotFound;
buffer.replace(req).unwrap(); continue
} else { } else {
// create an empty key placeholder None
let empty: [u8; 0] = []; };
match basis_cache.key_update(&mut pddb_os, let token_record = TokenRecord {
dict, key, &empty, None, alloc_hint, bname, true dict: String::from(dict),
) { key: String::from(key),
Ok(_) => {}, basis: if let Some(name) = bname {Some(String::from(name))} else {None},
Err(e) => { conn: cid,
log::error!("Couldn't allocate key: {:?}", e); alloc_hint,
match e.kind() { };
std::io::ErrorKind::NotFound => req.result = PddbRequestCode::NotMounted, token_dict.insert(token, token_record);
std::io::ErrorKind::OutOfMemory => req.result = PddbRequestCode::NoFreeSpace, req.token = Some(token);
_ => req.result = PddbRequestCode::InternalError, req.result = PddbRequestCode::NoErr;
} buffer.replace(req).unwrap();
buffer.replace(req).unwrap(); continue
}
}
}
} }
// 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 = 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),
basis: if let Some(name) = bname {Some(String::from(name))} else {None},
conn: cid,
alloc_hint,
};
token_dict.insert(token, token_record);
req.token = Some(token);
req.result = PddbRequestCode::NoErr;
buffer.replace(req).unwrap();
} }
Some(Opcode::KeyDrop) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, _, { Some(Opcode::KeyDrop) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, _, {
let token: ApiToken = [t0 as u32, t1 as u32, t2 as u32]; let token: ApiToken = [t0 as u32, t1 as u32, t2 as u32];
@ -1124,19 +1126,28 @@ fn main() -> ! {
let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance
let token = pbuf.token; let token = pbuf.token;
if let Some(rec) = token_dict.get(&token) { if let Some(rec) = token_dict.get(&token) {
match basis_cache.key_read(&mut pddb_os, for basis in basis_cache.access_list().iter() {
&rec.dict, &rec.key, let temp = if let Some (name) = &rec.basis {Some(name)} else {Some(basis)};
&mut pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), log::info!("accessing {:?}", temp);
if let Some (name) = &rec.basis {Some(&name)} else {None}) { match basis_cache.key_read(&mut pddb_os,
Ok(readlen) => { &rec.dict, &rec.key,
pbuf.len = readlen as u16; &mut pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize),
pbuf.retcode = PddbRetcode::Ok; // this is a bit inefficient because if a specific basis is specified *and* the key does not exist,
} // it'll retry the same basis for a number of times equal to the number of bases open.
Err(e) => match e.kind() { // However, usually, there's only 1-2 bases open, and usually, if you specify a basis,
std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost, // the key will be a hit, so, we let it stand.
std::io::ErrorKind::UnexpectedEof => pbuf.retcode = PddbRetcode::UnexpectedEof, if let Some (name) = &rec.basis {Some(&name)} else {Some(basis)}) {
std::io::ErrorKind::OutOfMemory => pbuf.retcode = PddbRetcode::DiskFull, Ok(readlen) => {
_ => pbuf.retcode = PddbRetcode::InternalError, pbuf.len = readlen as u16;
pbuf.retcode = PddbRetcode::Ok;
break;
}
Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost,
std::io::ErrorKind::UnexpectedEof => pbuf.retcode = PddbRetcode::UnexpectedEof,
std::io::ErrorKind::OutOfMemory => pbuf.retcode = PddbRetcode::DiskFull,
_ => pbuf.retcode = PddbRetcode::InternalError,
}
} }
} }
} else { } else {
@ -1149,20 +1160,23 @@ fn main() -> ! {
let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance
let token = pbuf.token; let token = pbuf.token;
if let Some(rec) = token_dict.get(&token) { if let Some(rec) = token_dict.get(&token) {
match basis_cache.key_update(&mut pddb_os, for basis in basis_cache.access_list().iter() {
&rec.dict, &rec.key, match basis_cache.key_update(&mut pddb_os,
&pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), &rec.dict, &rec.key,
rec.alloc_hint, if let Some (name) = &rec.basis {Some(&name)} else {None}, &pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize),
false rec.alloc_hint, if let Some (name) = &rec.basis {Some(&name)} else {Some(basis)},
) { false
Ok(_) => { ) {
pbuf.retcode = PddbRetcode::Ok; Ok(_) => {
} pbuf.retcode = PddbRetcode::Ok;
Err(e) => match e.kind() { break;
std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost, }
std::io::ErrorKind::UnexpectedEof => pbuf.retcode = PddbRetcode::UnexpectedEof, Err(e) => match e.kind() {
std::io::ErrorKind::OutOfMemory => pbuf.retcode = PddbRetcode::DiskFull, std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost,
_ => pbuf.retcode = PddbRetcode::InternalError, std::io::ErrorKind::UnexpectedEof => pbuf.retcode = PddbRetcode::UnexpectedEof,
std::io::ErrorKind::OutOfMemory => pbuf.retcode = PddbRetcode::DiskFull,
_ => pbuf.retcode = PddbRetcode::InternalError,
}
} }
} }
} else { } else {
@ -1188,6 +1202,7 @@ fn main() -> ! {
let mut note = String::from(t!("pddb.menu.listbasis_response", xous::LANG)); let mut note = String::from(t!("pddb.menu.listbasis_response", xous::LANG));
for basis in bases.iter() { for basis in bases.iter() {
note.push_str(basis); note.push_str(basis);
note.push_str("\n");
} }
modals.show_notification(&note, None).expect("couldn't show basis list"); modals.show_notification(&note, None).expect("couldn't show basis list");
}, },