From af9c71273b6e6abb0f40f7a3b2377f9086dad4ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 29 Jul 2022 15:18:49 +0200 Subject: [PATCH] improvement(vault): get rid of monomorphization on most storage::Manager methods Less kernel bloat! --- apps/vault/src/actions.rs | 12 +- apps/vault/src/storage.rs | 219 ++++++++++++++++++++++++++---- apps/vault/src/vendor_commands.rs | 8 +- 3 files changed, 204 insertions(+), 35 deletions(-) diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index 6cecc6f88..9c9b4f0f3 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -304,7 +304,7 @@ impl ActionManager { maybe_password }; } - let record = storage::PasswordRecord { + let mut record = storage::PasswordRecord { version: VAULT_PASSWORD_REC_VERSION, description, username, @@ -315,7 +315,7 @@ impl ActionManager { count: 0, }; - match self.storage.borrow_mut().new_record(record, None) { + match self.storage.borrow_mut().new_record(&mut record, None) { Ok(_) => (), Err(error) => { log::error!("internal error"); @@ -366,7 +366,7 @@ impl ActionManager { }; let validated_secret = base32::encode(base32::Alphabet::RFC4648 { padding: false }, &ss_vec); // time, hash, etc. are all the "expected defaults" -- if you want to change them, edit the record after entering it. - let totp = storage::TotpRecord { + let mut totp = storage::TotpRecord { version: VAULT_TOTP_REC_VERSION, name: description, secret: validated_secret, @@ -377,7 +377,7 @@ impl ActionManager { notes: t!("vault.notes", xous::LANG).to_string(), }; - match self.storage.borrow_mut().new_record(totp, None) { + match self.storage.borrow_mut().new_record(&mut totp, None) { Ok(_) => (), Err(error) => { log::error!("internal error"); @@ -532,7 +532,7 @@ impl ActionManager { pw.digits = d; } - storage.update(&choice, key_name, pw) + storage.update(&choice, key_name, &mut pw) }, storage::ContentKind::Password => { let mut pw: storage::PasswordRecord = match storage.get_record(&choice, key_name) { @@ -554,7 +554,7 @@ impl ActionManager { pw.username = edit_data.content()[1].content.as_str().unwrap().to_string(); pw.password = edit_data.content()[2].content.as_str().unwrap().to_string(); pw.notes = edit_data.content()[3].content.as_str().unwrap().to_string(); - storage.update(&choice, key_name, pw) + storage.update(&choice, key_name, &mut pw) }, }; diff --git a/apps/vault/src/storage.rs b/apps/vault/src/storage.rs index ef24ffa75..76f8e26a3 100644 --- a/apps/vault/src/storage.rs +++ b/apps/vault/src/storage.rs @@ -42,10 +42,13 @@ pub struct Manager { trng: trng::Trng, } -pub trait StorageContent: Into> + TryFrom> { +pub trait StorageContent { fn settings(&self) -> ContentPDDBSettings; fn set_ctime(&mut self, value: u64); + + fn from_vec(&mut self, data: Vec) -> Result<(), Error>; + fn to_vec(&self) -> Vec; } #[derive(Clone)] @@ -144,15 +147,15 @@ impl Manager { } } - pub fn new_record( + pub fn new_record( &mut self, - record: T, + record: &mut dyn StorageContent, basis: Option, ) -> Result<(), Error> { let mut record = record; let settings = record.settings(); record.set_ctime(utc_now().timestamp() as u64); - let serialized_record: Vec = record.into(); + let serialized_record: Vec = record.to_vec(); let guid = self.gen_guid(); self.pddb_store( @@ -164,9 +167,7 @@ impl Manager { ) } - pub fn all(&self, kind: ContentKind) -> Result, Error> - where - Error: From<>>::Error>, + pub fn all(&self, kind: ContentKind) -> Result, Error> { let settings = kind.settings(); @@ -175,35 +176,33 @@ impl Manager { let mut ret = vec![]; for key in keylist { - let record = T::try_from(self.pddb_get(&settings.dict, &key)?)?; + let mut record = T::default(); + record.from_vec(self.pddb_get(&settings.dict, &key)?)?; ret.push(record); } Ok(ret) } - pub fn get_record( + pub fn get_record( &self, kind: &ContentKind, key_name: &str, ) -> Result - where - Error: From<>>::Error>, { let settings = kind.settings(); - let t = T::try_from(self.pddb_get(&settings.dict, key_name)?)?; + let mut record = T::default(); + record.from_vec(self.pddb_get(&settings.dict, &key_name)?)?; - Ok(t) + Ok(record) } - pub fn update( + pub fn update( &mut self, kind: &ContentKind, key_name: &str, - record: T, + record: &mut dyn StorageContent, ) -> Result<(), Error> - where - Error: From<>>::Error>, { let settings = kind.settings(); @@ -211,20 +210,16 @@ impl Manager { self.pddb .delete_key(&settings.dict, key_name, Some(&basis))?; - self.new_record(record, Some(basis)) + self.new_record(&mut *record, Some(basis)) } - pub fn delete( - &mut self, - kind: ContentKind, - key_name: &str, - ) -> Result<(), Error> - { + pub fn delete(&mut self, kind: ContentKind, key_name: &str) -> Result<(), Error> { let settings = kind.settings(); let basis = self.basis_for_key(&settings.dict, key_name)?; self.pddb - .delete_key(&settings.dict, key_name, Some(&basis)).map_err(|error| Error::IoError(error)) + .delete_key(&settings.dict, key_name, Some(&basis)) + .map_err(|error| Error::IoError(error)) } } @@ -262,6 +257,96 @@ impl StorageContent for TotpRecord { fn set_ctime(&mut self, value: u64) { self.ctime = value; } + + fn from_vec(&mut self, data: Vec) -> Result<(), Error> { + let desc_str = String::from_utf8(data).or(Err(TOTPSerializationError::MalformedInput))?; + + let mut pr = TotpRecord::default(); + + let lines = desc_str.split('\n'); + for line in lines { + if let Some((tag, data)) = line.split_once(':') { + match tag { + "version" => { + if let Ok(ver) = u32::from_str_radix(data, 10) { + pr.version = ver + } else { + log::warn!("ver error"); + return Err(TOTPSerializationError::BadVersion)?; + } + } + "secret" => pr.secret.push_str(data), + "name" => pr.name.push_str(data), + "algorithm" => { + pr.algorithm = match crate::totp::TotpAlgorithm::try_from(data) { + Ok(a) => a, + Err(_) => return Err(TOTPSerializationError::BadAlgorithm)?, + } + } + "notes" => pr.notes.push_str(data), + "digits" => { + if let Ok(digits) = u32::from_str_radix(data, 10) { + pr.digits = digits; + } else { + log::warn!("digits error"); + return Err(TOTPSerializationError::BadDigitsAmount)?; + } + } + "ctime" => { + if let Ok(ctime) = u64::from_str_radix(data, 10) { + pr.ctime = ctime; + } else { + log::warn!("ctime error"); + return Err(TOTPSerializationError::BadCtime)?; + } + } + "timestep" => { + if let Ok(timestep) = u64::from_str_radix(data, 10) { + pr.timestep = timestep; + } else { + log::warn!("timestep error"); + return Err(TOTPSerializationError::BadTimestep)?; + } + } + _ => { + log::warn!( + "unexpected tag {} encountered parsing TOTP info, ignoring", + tag + ); + } + } + } else { + log::trace!("invalid line skipped: {:?}", line); + } + } + + *self = pr; + + Ok(()) + } + fn to_vec(&self) -> Vec { + let ta: String = self.algorithm.into(); + format!( + "{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n", + "version", + self.version, + "secret", + self.secret, + "name", + self.name, + "algorithm", + ta, + "notes", + self.notes, + "digits", + self.digits, + "timestep", + self.timestep, + "ctime", + self.ctime, + ) + .into_bytes() + } } impl TryFrom> for TotpRecord { @@ -399,6 +484,90 @@ impl StorageContent for PasswordRecord { fn set_ctime(&mut self, value: u64) { self.ctime = value; } + + fn from_vec(&mut self, data: Vec) -> Result<(), Error> { + let desc_str = + String::from_utf8(data).or(Err(PasswordSerializationError::MalformedInput))?; + + let mut pr = PasswordRecord::default(); + + let lines = desc_str.split('\n'); + for line in lines { + if let Some((tag, data)) = line.split_once(':') { + match tag { + "version" => { + if let Ok(ver) = u32::from_str_radix(data, 10) { + pr.version = ver + } else { + log::warn!("ver error"); + return Err(PasswordSerializationError::BadVersion)?; + } + } + "description" => pr.description.push_str(data), + "username" => pr.username.push_str(data), + "password" => pr.password.push_str(data), + "notes" => pr.notes.push_str(data), + "ctime" => { + if let Ok(ctime) = u64::from_str_radix(data, 10) { + pr.ctime = ctime; + } else { + log::warn!("ctime error"); + return Err(PasswordSerializationError::BadCtime)?; + } + } + "atime" => { + if let Ok(atime) = u64::from_str_radix(data, 10) { + pr.atime = atime; + } else { + log::warn!("atime error"); + return Err(PasswordSerializationError::BadAtime)?; + } + } + "count" => { + if let Ok(count) = u64::from_str_radix(data, 10) { + pr.count = count; + } else { + log::warn!("count error"); + return Err(PasswordSerializationError::BadCount)?; + } + } + _ => { + log::warn!( + "unexpected tag {} encountered parsing password info, ignoring", + tag + ); + } + } + } else { + log::trace!("invalid line skipped: {:?}", line); + } + } + + *self = pr; + Ok(()) + } + fn to_vec(&self) -> Vec { + format!( + "{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n", + "version", + self.version, + "description", + self.description, + "username", + self.username, + "password", + self.password, + "notes", + self.notes, + "ctime", + self.ctime, + "atime", + self.atime, + "count", + self.count, + ) + .into_bytes() + } } impl TryFrom> for PasswordRecord { diff --git a/apps/vault/src/vendor_commands.rs b/apps/vault/src/vendor_commands.rs index 63e7049b8..c5d406f5c 100644 --- a/apps/vault/src/vendor_commands.rs +++ b/apps/vault/src/vendor_commands.rs @@ -97,7 +97,7 @@ fn handle_restore(data: Vec, xns: &xous_names::XousNames) -> Result, match data { backup::DataPacket::TOTP(totp_entries) => { for elem in totp_entries.0 { - let totp = TotpRecord { + let mut totp = TotpRecord { version: 1, name: elem.name, secret: elem.shared_secret, @@ -112,12 +112,12 @@ fn handle_restore(data: Vec, xns: &xous_names::XousNames) -> Result, notes: t!("vault.notes", xous::LANG).to_string(), }; - storage.new_record(totp, None)?; + storage.new_record(&mut totp, None)?; } } backup::DataPacket::Password(password_entries) => { for elem in password_entries.0 { - let password = PasswordRecord { + let mut password = PasswordRecord { version: 1, description: elem.description, username: elem.username, @@ -128,7 +128,7 @@ fn handle_restore(data: Vec, xns: &xous_names::XousNames) -> Result, atime: 0, }; - storage.new_record(password, None)?; + storage.new_record(&mut password, None)?; } } };