Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update littlefs2 #171

Merged
merged 4 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ delog = "0.1.0"
cbor-smol = { version = "0.5", features = ["heapless-bytes-v0-3"] }
heapless-bytes = { version = "0.3.0" }
interchange = "0.3.0"
littlefs2 = "0.4.0"
littlefs2 = "0.5.0"
littlefs2-core = { version = "0.1", features = ["heapless-bytes03"] }
p256-cortex-m4 = { version = "0.1.0-alpha.6", features = ["prehash", "sec1-signatures"] }
salty = { version = "0.3.0", features = ["cose"] }
serde-indexed = "0.1.0"
Expand Down Expand Up @@ -145,6 +146,3 @@ test-attestation-cert-ids = []
[package.metadata.docs.rs]
features = ["serde-extensions", "virt"]
rustdoc-args = ["--cfg", "docsrs"]

[patch.crates-io]
littlefs2 = { git = "https://github.com/sosthene-nitrokey/littlefs2.git", rev = "2b45a7559ff44260c6dd693e4cb61f54ae5efc53" }
18 changes: 7 additions & 11 deletions src/service.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
use littlefs2::{
object_safe::DynFilesystem,
path,
path::{Path, PathBuf},
};
use littlefs2_core::{path, DynFilesystem, Path, PathBuf};
use rand_chacha::ChaCha8Rng;
pub use rand_core::{RngCore, SeedableRng};

Expand Down Expand Up @@ -122,7 +118,7 @@ impl<P: Platform> ServiceResources<P> {
}

pub fn trussed_filestore(&mut self) -> ClientFilestore<P::S> {
ClientFilestore::new(PathBuf::from("trussed"), self.platform.store())
ClientFilestore::new(PathBuf::from(path!("trussed")), self.platform.store())
}

pub fn keystore(&mut self, client_id: PathBuf) -> Result<ClientKeystore<P::S>> {
Expand Down Expand Up @@ -182,7 +178,7 @@ impl<P: Platform> ServiceResources<P> {
#[cfg(feature = "crypto-client-attest")]
Request::Attest(request) => {
let mut attn_keystore: ClientKeystore<P::S> = ClientKeystore::new(
PathBuf::from("attn"),
PathBuf::from(path!("attn")),
self.rng().map_err(|_| Error::EntropyMalfunction)?,
full_store,
);
Expand Down Expand Up @@ -419,7 +415,7 @@ impl<P: Platform> ServiceResources<P> {
recursively_list(fs, entry.path());
}
if entry.file_type().is_file() {
let _contents = fs.read::<256>(entry.path()).unwrap();
let _contents = fs.read::<Bytes<256>>(entry.path()).unwrap();
// info_now!("{} ?= {}", entry.metadata().len(), contents.len()).ok();
// info_now!("{:?}", &contents).ok();
}
Expand Down Expand Up @@ -858,7 +854,7 @@ impl<P: Platform> Service<P> {
syscall: S,
interrupt: Option<&'static InterruptFlag>,
) -> Result<ClientImplementation<S>, Error> {
ClientBuilder::new(client_id)
ClientBuilder::new(PathBuf::try_from(client_id).unwrap())
.interrupt(interrupt)
.prepare(self)
.map(|p| p.build(syscall))
Expand All @@ -872,7 +868,7 @@ impl<P: Platform> Service<P> {
client_id: &str,
interrupt: Option<&'static InterruptFlag>,
) -> Result<ClientImplementation<&mut Self>, Error> {
ClientBuilder::new(client_id)
ClientBuilder::new(PathBuf::try_from(client_id).unwrap())
.interrupt(interrupt)
.prepare(self)
.map(|p| p.build(self))
Expand All @@ -885,7 +881,7 @@ impl<P: Platform> Service<P> {
client_id: &str,
interrupt: Option<&'static InterruptFlag>,
) -> Result<ClientImplementation<Self>, Error> {
ClientBuilder::new(client_id)
ClientBuilder::new(PathBuf::try_from(client_id).unwrap())
.interrupt(interrupt)
.prepare(&mut self)
.map(|p| p.build(self))
Expand Down
25 changes: 5 additions & 20 deletions src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
use littlefs2::{driver::Storage, fs::Filesystem};

use crate::error::Error;
use crate::types::{Bytes, Location, PathBuf};
use crate::types::{Bytes, Location};
#[allow(unused_imports)]
use littlefs2::{
fs::{DirEntry, Metadata},
Expand Down Expand Up @@ -492,24 +492,10 @@ macro_rules! store {
};
}

// TODO: replace this with "fs.create_dir_all(path.parent())"
pub fn create_directories(fs: &dyn DynFilesystem, path: &Path) -> Result<(), Error> {
let path_bytes = path.as_ref().as_bytes();

for i in 0..path_bytes.len() {
if path_bytes[i] == b'/' {
let dir_bytes = &path_bytes[..i];
let dir = PathBuf::from(dir_bytes);
// let dir_str = core::str::from_utf8(dir).unwrap();
// fs.create_dir(dir).map_err(|_| Error::FilesystemWriteFailure)?;
match fs.create_dir(&dir) {
Err(littlefs2::io::Error::EntryAlreadyExisted) => {}
Ok(()) => {}
error => {
panic!("{:?}", &error);
}
}
}
if let Some(parent) = path.parent() {
fs.create_dir_all(&parent)
.map_err(|_| Error::FilesystemWriteFailure)?;
}
Ok(())
}
Expand All @@ -525,7 +511,6 @@ pub fn read<const N: usize>(
store
.fs(location)
.read(path)
.map(From::from)
.map_err(|_| Error::FilesystemReadFailure)
}

Expand Down Expand Up @@ -581,7 +566,7 @@ pub fn metadata(
debug_now!("checking existence of {}", &path);
match store.fs(location).metadata(path) {
Ok(metadata) => Ok(Some(metadata)),
Err(littlefs2::io::Error::NoSuchEntry) => Ok(None),
Err(littlefs2::io::Error::NO_SUCH_ENTRY) => Ok(None),
Err(_) => Err(Error::FilesystemReadFailure),
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/store/certstore.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use littlefs2::{path, path::PathBuf};
use littlefs2_core::{path, PathBuf};
use rand_chacha::ChaCha8Rng;

use crate::{
Expand Down Expand Up @@ -66,7 +66,7 @@ impl<S: Store> ClientCertstore<S> {
let mut path = PathBuf::new();
path.push(&self.client_id);
path.push(path!("x5c"));
path.push(&PathBuf::from(id.hex().as_slice()));
path.push(&id.hex_path());
path
}

Expand Down
4 changes: 2 additions & 2 deletions src/store/counterstore.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use littlefs2::{path, path::PathBuf};
use littlefs2_core::{path, PathBuf};
use rand_chacha::ChaCha8Rng;

use crate::{
Expand Down Expand Up @@ -31,7 +31,7 @@ impl<S: Store> ClientCounterstore<S> {
let mut path = PathBuf::new();
path.push(&self.client_id);
path.push(path!("ctr"));
path.push(&PathBuf::from(id.hex().as_slice()));
path.push(&id.hex_path());
path
}

Expand Down
35 changes: 18 additions & 17 deletions src/store/filestore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
types::{Location, Message, UserAttribute},
Bytes,
};
use littlefs2::path;
use littlefs2_core::{path, DirEntry, Metadata, Path, PathBuf};

#[derive(Clone)]
pub struct ReadDirState {
Expand All @@ -25,11 +25,6 @@ pub struct ReadDirFilesState {
user_attribute: Option<UserAttribute>,
}

use littlefs2::{
fs::{DirEntry, Metadata},
path::{Path, PathBuf},
};

pub struct ClientFilestore<S>
where
S: Store,
Expand Down Expand Up @@ -81,7 +76,7 @@ impl<S: Store> ClientFilestore<S> {
// oh oh oh
.unwrap();
let dat_offset = "/dat/".len();
PathBuf::from(&bytes[end_of_namespace + 1 + offset + dat_offset..])
PathBuf::try_from(&bytes[end_of_namespace + 1 + offset + dat_offset..]).unwrap()
}
}

Expand Down Expand Up @@ -204,7 +199,7 @@ impl<S: Store> ClientFilestore<S> {
// `read_dir_and_then` wants to see Results (although we naturally have an Option
// at this point)
})
.ok_or(littlefs2::io::Error::Io)
.ok_or(littlefs2_core::Error::IO)
})
.ok())
}
Expand Down Expand Up @@ -241,7 +236,7 @@ impl<S: Store> ClientFilestore<S> {

(entry, read_dir_state)
})
.ok_or(littlefs2::io::Error::Io)
.ok_or(littlefs2_core::Error::IO)
})
.ok())
}
Expand All @@ -268,14 +263,17 @@ impl<S: Store> ClientFilestore<S> {
// take first entry that meets requirements
.find(|(_, entry)| {
if let Some(user_attribute) = user_attribute.as_ref() {
let mut buffer = UserAttribute::new();
buffer.resize_to_capacity();
let mut path = dir.clone();
path.push(entry.file_name());
let attribute = fs
.attribute(&path, crate::config::USER_ATTRIBUTE_NUMBER)
.attribute(&path, crate::config::USER_ATTRIBUTE_NUMBER, &mut buffer)
.unwrap();

if let Some(attribute) = attribute {
user_attribute == attribute.data()
user_attribute.len() == attribute.total_size()
&& user_attribute == attribute.data()
} else {
false
}
Expand All @@ -295,7 +293,7 @@ impl<S: Store> ClientFilestore<S> {
// `read_dir_and_then` wants to see Results (although we naturally have an Option
// at this point)
})
.ok_or(littlefs2::io::Error::Io)
.ok_or(littlefs2_core::Error::IO)
})
.ok()
.map(|(i, data)| {
Expand Down Expand Up @@ -335,13 +333,16 @@ impl<S: Store> ClientFilestore<S> {
// take first entry that meets requirements
.find(|(_, entry)| {
if let Some(user_attribute) = user_attribute.as_ref() {
let mut buffer = UserAttribute::new();
buffer.resize_to_capacity();
let mut path = real_dir.clone();
path.push(entry.file_name());
let attribute = fs
.attribute(&path, crate::config::USER_ATTRIBUTE_NUMBER)
.attribute(&path, crate::config::USER_ATTRIBUTE_NUMBER, &mut buffer)
.unwrap();
if let Some(attribute) = attribute {
user_attribute == attribute.data()
user_attribute.len() == attribute.total_size()
&& user_attribute == attribute.data()
} else {
false
}
Expand All @@ -355,7 +356,7 @@ impl<S: Store> ClientFilestore<S> {
(i, data)
})
// convert Option into Result, again because `read_dir_and_then` expects this
.ok_or(littlefs2::io::Error::Io)
.ok_or(littlefs2_core::Error::IO)
})
.ok()
.map(|(i, data)| {
Expand Down Expand Up @@ -493,7 +494,7 @@ impl<S: Store> Filestore for ClientFilestore<S> {
.filter_map(|entry| {
let is_file = entry.file_type().is_file();
if is_file {
if PathBuf::from(entry.file_name()) == PathBuf::from(filename) {
if entry.file_name() == filename {
Some(PathBuf::from(entry.path()))
} else {
None
Expand All @@ -503,7 +504,7 @@ impl<S: Store> Filestore for ClientFilestore<S> {
}
})
.next()
.ok_or(littlefs2::io::Error::Io)
.ok_or(littlefs2_core::Error::IO)
})
.ok()
}
Expand Down
4 changes: 2 additions & 2 deletions src/store/keystore.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use littlefs2::{path, path::PathBuf};
use littlefs2_core::{path, PathBuf};
use rand_chacha::ChaCha8Rng;

use crate::{
Expand Down Expand Up @@ -86,7 +86,7 @@ impl<S: Store> ClientKeystore<S> {

pub fn key_path(&self, secrecy: key::Secrecy, id: &KeyId) -> PathBuf {
let mut path = self.key_directory(secrecy);
path.push(&PathBuf::from(id.hex().as_slice()));
path.push(&id.hex_path());
path
}
}
Expand Down
25 changes: 11 additions & 14 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use littlefs2::const_ram_storage;
use littlefs2::driver::Storage as LfsStorage;
use littlefs2::fs::{Allocation, Filesystem};
use littlefs2::io::Result as LfsResult;
use littlefs2_core::path;
use rand_core::{CryptoRng, RngCore};

#[cfg(any(feature = "p256", feature = "p384", feature = "p521",))]
Expand Down Expand Up @@ -172,7 +173,7 @@ macro_rules! setup {
let (test_trussed_requester, test_trussed_responder) = crate::pipe::TRUSSED_INTERCHANGE
.claim()
.expect("could not setup TEST TrussedInterchange");
let test_client_id = "TEST";
let test_client_id = path!("TEST");

assert!(trussed
.add_endpoint(test_trussed_responder, test_client_id, &[], None)
Expand Down Expand Up @@ -873,35 +874,31 @@ fn rng() {
#[test]
#[serial]
fn filesystem() {
let path = PathBuf::from(path!("test_file"));
setup!(client);

assert!(block!(client
.entry_metadata(Location::Internal, PathBuf::from("test_file"))
.entry_metadata(Location::Internal, path.clone())
.expect("no client error"))
.expect("no errors")
.metadata
.is_none(),);

let data = Bytes::from_slice(&[0; 20]).unwrap();
block!(client
.write_file(
Location::Internal,
PathBuf::from("test_file"),
data.clone(),
None,
)
.write_file(Location::Internal, path.clone(), data.clone(), None,)
.expect("no client error"))
.expect("no errors");

let recv_data = block!(client
.read_file(Location::Internal, PathBuf::from("test_file"))
.read_file(Location::Internal, path.clone())
.expect("no client error"))
.expect("no errors")
.data;
assert_eq!(data, recv_data);

let metadata = block!(client
.entry_metadata(Location::Internal, PathBuf::from("test_file"))
.entry_metadata(Location::Internal, path.clone())
.expect("no client error"))
.expect("no errors")
.metadata
Expand All @@ -910,23 +907,23 @@ fn filesystem() {

// This returns an error because the name doesn't exist
block!(client
.remove_file(Location::Internal, PathBuf::from("bad_name"))
.remove_file(Location::Internal, path!("bad_name").into())
.expect("no client error"))
.ok();
let metadata = block!(client
.entry_metadata(Location::Internal, PathBuf::from("test_file"))
.entry_metadata(Location::Internal, path.clone())
.expect("no client error"))
.expect("no errors")
.metadata
.unwrap();
assert!(metadata.is_file());

block!(client
.remove_file(Location::Internal, PathBuf::from("test_file"))
.remove_file(Location::Internal, path.clone())
.expect("no client error"))
.expect("no errors");
assert!(block!(client
.entry_metadata(Location::Internal, PathBuf::from("test_file"))
.entry_metadata(Location::Internal, path.clone())
.expect("no client error"))
.expect("no errors")
.metadata
Expand Down
Loading
Loading