123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849 |
- // SPDX-License-Identifier: AGPL-3.0-or-later
- /// Test data and functions to help with testing.
- use btserde::{Error, Result};
- use fuse_backend_rs::{
- api::filesystem::{ZeroCopyReader, ZeroCopyWriter},
- file_buf::FileVolatileSlice,
- file_traits::FileReadWriteVolatile,
- };
- use std::{
- cell::RefCell,
- fmt::Write as FmtWrite,
- fs::File,
- io::{Cursor, Write},
- };
- use vm_memory::bytes::Bytes;
- use super::*;
- use crate::{crypto::*, sectored_buf::SectoredBuf, Cursor as PioCursor};
- /// A smaller default sector size for use in tests.
- pub const SECTOR_SZ_DEFAULT: usize = 4096;
- pub const PRINCIPAL: [u8; 32] = [
- 0x75, 0x28, 0xA9, 0xE0, 0x9D, 0x24, 0xBA, 0xB3, 0x79, 0x56, 0x15, 0x68, 0xFD, 0xA4, 0xE2, 0xA4,
- 0xCF, 0xB2, 0xC0, 0xE3, 0x96, 0xAE, 0xA2, 0x6E, 0x45, 0x15, 0x50, 0xED, 0xA6, 0xBE, 0x6D, 0xEC,
- ];
- pub const PRINCIPAL2: [u8; 32] = [
- 0x6E, 0x8A, 0x76, 0x1D, 0xC7, 0x3B, 0x50, 0x90, 0x51, 0x9E, 0x73, 0x9B, 0xEE, 0x7B, 0x02, 0xF9,
- 0xB9, 0x17, 0x7C, 0xF6, 0xBB, 0xC8, 0xD5, 0x30, 0xBF, 0x2A, 0xB4, 0xDE, 0x1B, 0x38, 0xCC, 0xF6,
- ];
- pub const SIGNATURE: [u8; 384] = [
- 0x12, 0xB1, 0x09, 0x2F, 0x2B, 0x3C, 0x53, 0xE8, 0x1B, 0x2B, 0x6A, 0xE7, 0x97, 0x42, 0x9D, 0x83,
- 0x71, 0x75, 0x65, 0x25, 0xFD, 0xB0, 0x0E, 0x2F, 0xAB, 0x53, 0xB7, 0x03, 0x03, 0x39, 0xEE, 0xE9,
- 0x15, 0x19, 0xAB, 0x1A, 0xF1, 0x2C, 0x3C, 0xAB, 0x5C, 0x02, 0xEA, 0xD6, 0xF6, 0x94, 0x36, 0x80,
- 0x5F, 0xD1, 0x8E, 0xC4, 0xB9, 0xB5, 0x04, 0x73, 0xBB, 0x77, 0x2C, 0x9C, 0xAF, 0xE6, 0x38, 0xB7,
- 0xD8, 0xC1, 0xA3, 0x1B, 0xAD, 0xFB, 0xB2, 0x5E, 0x77, 0xBD, 0x79, 0xDC, 0x4E, 0xEC, 0xEA, 0xFA,
- 0x80, 0x9F, 0x12, 0x60, 0xC4, 0xB3, 0x71, 0xAF, 0x1C, 0x28, 0xEE, 0x91, 0x1D, 0x6A, 0x69, 0x31,
- 0xA4, 0x5A, 0xAA, 0xBE, 0x0B, 0x20, 0x6A, 0xE1, 0x61, 0x0E, 0x0B, 0x9F, 0x60, 0x73, 0xBE, 0x29,
- 0x1F, 0x11, 0x0A, 0x8F, 0x42, 0x8F, 0x80, 0xC1, 0x06, 0x40, 0x29, 0xE9, 0xF1, 0x74, 0x44, 0x69,
- 0xCC, 0xD3, 0x05, 0x22, 0x24, 0x87, 0x94, 0x49, 0x4B, 0x5B, 0x62, 0x48, 0x01, 0x7B, 0x05, 0x28,
- 0xBE, 0x4D, 0x50, 0x06, 0xE5, 0x67, 0xA8, 0xFB, 0x9A, 0x19, 0x52, 0x57, 0x4B, 0xC4, 0xBB, 0x6A,
- 0xF5, 0x0D, 0x67, 0xD0, 0x08, 0x93, 0x81, 0xD2, 0x9E, 0xE2, 0xC8, 0xFA, 0x25, 0xEE, 0x9D, 0xC5,
- 0xD8, 0xF4, 0xD5, 0x17, 0xE4, 0xEF, 0xFC, 0x09, 0xB0, 0x09, 0xCA, 0xCA, 0x71, 0x36, 0x61, 0xBE,
- 0xC1, 0xD0, 0x53, 0x6D, 0x0C, 0x0A, 0x4D, 0xF1, 0xE0, 0xAB, 0x2C, 0x89, 0x98, 0x81, 0xED, 0x25,
- 0xF8, 0x81, 0x8E, 0x2C, 0x46, 0x74, 0x57, 0xCF, 0x5B, 0xE2, 0x14, 0xA5, 0xBF, 0x56, 0xED, 0xD3,
- 0x11, 0xE7, 0xB4, 0x8D, 0x89, 0x3A, 0xB2, 0x78, 0xF1, 0xA9, 0x82, 0x9D, 0x3B, 0xE5, 0x6B, 0xD2,
- 0xA5, 0xB6, 0xFB, 0x71, 0x0F, 0x98, 0x52, 0x54, 0x1E, 0x98, 0xD2, 0x3B, 0x78, 0x51, 0xD1, 0xE2,
- 0x57, 0xAE, 0xB3, 0x34, 0x0E, 0x20, 0x26, 0xCF, 0x4B, 0x1F, 0x12, 0xCA, 0xB1, 0xD5, 0x67, 0x55,
- 0xF9, 0xE2, 0xA9, 0x7B, 0xAE, 0x35, 0x35, 0x67, 0xA3, 0xCA, 0xBD, 0xF2, 0x41, 0x4E, 0x3F, 0x7E,
- 0x20, 0x72, 0xC2, 0xCC, 0xE4, 0x90, 0x00, 0x04, 0x5D, 0xF7, 0xD9, 0xC7, 0x0C, 0x2C, 0xF8, 0x80,
- 0xCB, 0xF2, 0x3E, 0x1A, 0xE9, 0x43, 0x23, 0xAF, 0x62, 0x57, 0xD1, 0x4C, 0xFD, 0x05, 0xB6, 0xB6,
- 0x86, 0xB9, 0x86, 0x40, 0xC2, 0x56, 0x45, 0x52, 0xE2, 0x93, 0x62, 0x65, 0x23, 0xE7, 0x1D, 0x89,
- 0xCA, 0x40, 0x23, 0x44, 0xDB, 0x56, 0x90, 0x4A, 0x0E, 0xB1, 0xB1, 0xE1, 0x9B, 0x5A, 0x5D, 0x53,
- 0xEF, 0x4E, 0xE1, 0x0E, 0x12, 0xA9, 0x7C, 0x11, 0x0B, 0x6A, 0x4C, 0x3A, 0x8F, 0x2B, 0x9F, 0xC6,
- 0x42, 0xD7, 0xFE, 0x7D, 0x10, 0x02, 0xBD, 0x31, 0x21, 0xCD, 0xD1, 0x32, 0x04, 0x22, 0xE2, 0x36,
- ];
- /// The key of the parent of test blocks.
- pub static PARENT_KEY: SymKey = {
- let key = [
- 0x35, 0x3D, 0x8C, 0x95, 0x6C, 0x8D, 0xE6, 0xC0, 0xB0, 0xD5, 0x1C, 0xE9, 0x94, 0xB0, 0x58,
- 0xD3, 0x80, 0x46, 0x12, 0x1C, 0xF3, 0x9B, 0x8A, 0xEC, 0x38, 0xD5, 0x8B, 0x05, 0x92, 0x8D,
- 0xA1, 0x18,
- ];
- let iv = [
- 0xDA, 0x96, 0x0E, 0xF5, 0x00, 0xDB, 0xC8, 0x4E, 0xFB, 0x83, 0x59, 0x99, 0x6C, 0x18, 0xD1,
- 0x27,
- ];
- SymKey::Aes256Cbc { key, iv }
- };
- lazy_static! {
- static ref INHERIT: Ciphertext<SymKey> = PARENT_KEY
- .ser_encrypt(&BLOCK_KEY)
- .expect("failed to encrypt block key");
- }
- /// The key used to encrypt test blocks.
- pub static BLOCK_KEY: SymKey = {
- let key = [
- 0xB2, 0xB3, 0xDA, 0x5A, 0x1A, 0xF6, 0xB3, 0x78, 0x30, 0xAB, 0x1D, 0x33, 0x33, 0xE7, 0xE3,
- 0x5B, 0xBB, 0xF9, 0xFE, 0xD0, 0xC1, 0xF7, 0x90, 0x34, 0x69, 0xB7, 0xE7, 0xC6, 0x1C, 0x46,
- 0x85, 0x48,
- ];
- let iv = [
- 0xEC, 0x19, 0x59, 0x3A, 0x1D, 0x1E, 0x4A, 0x58, 0x66, 0xC1, 0xD1, 0x9A, 0x61, 0x6E, 0xBA,
- 0x16,
- ];
- SymKey::Aes256Cbc { key, iv }
- };
- lazy_static! {
- pub static ref ROOT_CREDS: ConcreteCreds =
- ConcreteCreds::generate().expect("root cred generation failed");
- pub static ref NODE_CREDS: ConcreteCreds = {
- let mut node_creds = ConcreteCreds::generate().expect("node cred generation failed");
- let expires = Epoch::now() + Duration::from_secs(3600);
- let writecap = ROOT_CREDS
- .issue_writecap(node_creds.principal(), vec![], expires)
- .expect("failed to issue writecap to test_helpers::NODE_CREDS");
- node_creds.set_writecap(writecap);
- node_creds
- };
- }
- pub fn node_creds() -> &'static ConcreteCreds {
- &NODE_CREDS
- }
- pub fn root_creds() -> &'static ConcreteCreds {
- &ROOT_CREDS
- }
- /// Converts the given error to a serde_block_tree error by turning it into a message.
- fn convert_err<E: Display>(err: E) -> Error {
- Error::Message(err.to_string())
- }
- pub fn make_principal() -> Principal {
- Principal(VarHash::Sha2_256(PRINCIPAL.into()))
- }
- pub fn make_path_with_root(root: Principal, rel_components: Vec<&str>) -> BlockPath {
- let mut components = Vec::with_capacity(rel_components.len());
- for component in rel_components {
- components.push(component.to_string());
- }
- BlockPath::new(root, components)
- }
- pub fn make_path(rel_components: Vec<&str>) -> BlockPath {
- make_path_with_root(make_principal(), rel_components)
- }
- pub fn make_writecap_and_creds(rel_components: Vec<&str>) -> (Writecap, impl Creds) {
- let (root_writecap, root_key) = make_self_signed_writecap();
- let issued_to = Principal(VarHash::Sha2_256(PRINCIPAL.into()));
- (
- make_writecap_trusted_by(root_writecap, &root_key, issued_to, rel_components),
- root_key,
- )
- }
- pub fn make_writecap(rel_components: Vec<&str>) -> Writecap {
- let (writecap, ..) = make_writecap_and_creds(rel_components);
- writecap
- }
- pub fn make_writecap_trusted_by<C: Creds>(
- next: Writecap,
- trusting_creds: &C,
- issued_to: Principal,
- path_components: Vec<&str>,
- ) -> Writecap {
- let hour_hence = Epoch::now() + Duration::from_secs(3600);
- let mut writecap = Writecap {
- body: WritecapBody {
- issued_to,
- path: make_path_with_root(next.body.path.root().clone(), path_components),
- expires: hour_hence,
- signing_key: trusting_creds.public_sign().clone(),
- },
- signature: Signature::empty(Sign::RSA_PSS_3072_SHA_256),
- next: Some(Box::from(next)),
- };
- trusting_creds
- .sign_writecap(&mut writecap)
- .map_err(convert_err)
- .expect("failed to sign writecap");
- writecap
- }
- pub fn make_key_pair() -> impl Creds {
- NODE_CREDS.clone()
- }
- pub fn make_self_signed_writecap() -> (Writecap, impl Creds) {
- let key = make_key_pair();
- (make_self_signed_writecap_with(&key), key)
- }
- pub fn make_self_signed_writecap_with<C: Creds>(key: &C) -> Writecap {
- let root_principal = key.principal();
- let hour_hence = Epoch::now() + Duration::from_secs(3600);
- let mut writecap = Writecap {
- body: WritecapBody {
- issued_to: root_principal.clone(),
- path: make_path_with_root(root_principal, vec![]),
- expires: hour_hence,
- signing_key: key.public_sign().clone(),
- },
- signature: Signature::empty(Sign::RSA_PSS_3072_SHA_256),
- next: None,
- };
- key.sign_writecap(&mut writecap)
- .map_err(convert_err)
- .expect("failed to sign writecap");
- writecap
- }
- pub fn make_block_with() -> SectoredBuf<SecretStream<PioCursor<impl Block>>> {
- let block_key = SymKey::generate(SymKeyKind::default()).unwrap();
- // Notice that the writecap path contains the block path. If this were not the case, the block
- // would be invalid.
- let (writecap, creds) = make_writecap_and_creds(vec!["apps"]);
- let root_writecap = writecap.next.as_ref().unwrap();
- let path = make_path_with_root(root_writecap.body.issued_to.clone(), vec!["apps", "verse"]);
- let header = BlockMetaBody::new(&creds).unwrap();
- let sig = Signature::copy_from(Sign::RSA_PSS_3072_SHA_256, &SIGNATURE);
- let mut stream = BlockStream::new(
- SectoredCursor::new(Vec::new(), SECTOR_SZ_DEFAULT).require_sect_sz(false),
- creds,
- None,
- path,
- )
- .expect("create block stream failed");
- stream.meta.body = header;
- stream.meta.sig = sig;
- let stream = MerkleStream::new(stream).expect("create merkle stream failed");
- let stream = SecretStream::new(block_key)
- .try_compose(PioCursor::new(stream))
- .expect("create secret stream failed");
- SectoredBuf::new(stream).expect("failed to compose with SectoredBuf")
- }
- /// This function can be run as a test to write a new RSA key pair, as two Rust arrays,
- /// out to a file.
- #[allow(dead_code)]
- fn write_test_keys() -> Result<()> {
- write_rsa_keys_to_file("test_keys.rs")
- }
- struct NamedSlice<'a> {
- name: &'a str,
- slice: &'a [u8],
- }
- impl<'a> NamedSlice<'a> {
- fn new(name: &'a str, slice: &'a [u8]) -> NamedSlice<'a> {
- NamedSlice { name, slice }
- }
- }
- fn write_rsa_keys_to_file(path: &str) -> Result<()> {
- use openssl::rsa::Rsa;
- let rsa = Rsa::generate(3072).map_err(convert_err)?;
- let public_der = rsa.public_key_to_der().map_err(convert_err)?;
- let private_der = rsa.private_key_to_der().map_err(convert_err)?;
- let slices = [
- NamedSlice::new("PUBLIC", public_der.as_slice()),
- NamedSlice::new("PRIVATE", private_der.as_slice()),
- ];
- write_to_file(path, slices.into_iter())
- }
- fn write_to_file<'a, I: Iterator<Item = NamedSlice<'a>>>(path: &str, slices: I) -> Result<()> {
- let path = std::path::Path::new(path);
- let mut file = File::create(path).map_err(Error::Io)?;
- for NamedSlice { name, slice } in slices {
- write_slice(&mut file, name, slice)?;
- }
- Ok(())
- }
- fn write_slice<W: Write>(output: &mut W, name: &str, slice: &[u8]) -> Result<()> {
- const LINE_LEN: usize = 100;
- let mut line = String::with_capacity(LINE_LEN);
- write!(line, " ").map_err(Error::Format)?;
- writeln!(output, "pub const {}: [u8; {}] = [", name, slice.len()).map_err(Error::Io)?;
- for byte in slice {
- if line.len() + 6 > LINE_LEN {
- writeln!(output, "{}", line).map_err(Error::Io)?;
- line.clear();
- write!(line, " ").map_err(Error::Format)?;
- }
- write!(line, "0x{:02X?}, ", byte).map_err(Error::Format)?;
- }
- writeln!(output, "{}", line).map_err(Error::Io)?;
- writeln!(output, "];").map_err(Error::Io)?;
- writeln!(output).map_err(Error::Io)?;
- Ok(())
- }
- /// A naive randomizer implementation that is intended only for testing.
- pub struct Randomizer {
- state: [u8; Self::HASH.len()],
- buf: [u8; Self::HASH.len()],
- }
- impl Randomizer {
- pub const HASH: HashKind = HashKind::Sha2_256;
- pub fn new(seed: [u8; Self::HASH.len()]) -> Randomizer {
- Randomizer {
- state: seed,
- buf: [0u8; Self::HASH.len()],
- }
- }
- }
- impl Iterator for Randomizer {
- type Item = usize;
- fn next(&mut self) -> Option<Self::Item> {
- const BYTES: usize = usize::BITS as usize / 8;
- Self::HASH
- .digest(&mut self.buf, std::iter::once(self.state.as_slice()))
- .expect("digest failed");
- self.state.copy_from_slice(&self.buf);
- let int_bytes = self.buf.as_slice()[..BYTES]
- .try_into()
- .expect("failed to convert to array");
- Some(usize::from_ne_bytes(int_bytes))
- }
- }
- pub fn write_sector(mut buf: &mut [u8], sect_index: usize) {
- let data = (sect_index + 1).to_ne_bytes();
- for chunk in std::iter::repeat(data).take(buf.len() / data.len()) {
- (&mut buf[..chunk.len()]).copy_from_slice(chunk.as_slice());
- buf = &mut buf[chunk.len()..];
- }
- }
- pub fn write_fill<W: Write>(mut write: W, sect_sz: usize, sect_ct: usize) {
- let mut buf = vec![0u8; sect_sz];
- for sect_index in 0..sect_ct {
- write_sector(&mut buf, sect_index);
- write.write_all(&mut buf).expect("write failed");
- }
- write.flush().expect("flush failed");
- }
- pub fn read_check<R: Read>(mut read: R, sect_sz: usize, sect_ct: usize) {
- let mut actual = vec![0u8; sect_sz];
- let mut expected = vec![0u8; sect_sz];
- for sect_index in 0..sect_ct {
- write_sector(&mut expected, sect_index);
- read.read_exact(&mut actual).expect("read failed");
- assert_eq!(expected, actual);
- }
- }
- #[allow(dead_code)]
- pub fn write_indices<W: Write + Seek, I: Iterator<Item = usize>>(
- mut write: W,
- sect_sz: usize,
- indices: I,
- ) {
- let mut buf = vec![0u8; sect_sz];
- for sect_index in indices {
- let offset = sect_index * sect_sz;
- write
- .seek(SeekFrom::Start(offset as u64))
- .expect("seek failed");
- write_sector(&mut buf, sect_index);
- write.write_all(&mut buf).expect("write failed");
- }
- write.flush().expect("flush failed");
- }
- #[allow(dead_code)]
- pub fn read_indices<R: Read + Seek, I: Iterator<Item = usize>>(
- mut read: R,
- sect_sz: usize,
- indices: I,
- ) {
- let mut actual = vec![0u8; sect_sz];
- let mut expected = vec![0u8; sect_sz];
- for sect_index in indices {
- let offset = sect_index * sect_sz;
- read.seek(SeekFrom::Start(offset as u64))
- .expect("seek failed");
- write_sector(&mut expected, sect_index);
- read.read_exact(&mut actual).expect("read failed");
- assert_eq!(expected, actual);
- }
- }
- #[allow(dead_code)]
- pub fn random_indices<'a>(
- rando: &'a mut Randomizer,
- sect_ct: usize,
- ) -> impl Iterator<Item = usize> + 'a {
- rando.take(sect_ct).map(move |e| e % sect_ct)
- }
- /// Returns an integer array starting at the given value and increasing by one for each subsequent
- /// entry.
- pub const fn integer_array<const N: usize>(start: u8) -> [u8; N] {
- let mut array = [0u8; N];
- let mut k = 0usize;
- while k < N {
- array[k] = start.wrapping_add(k as u8);
- k += 1;
- }
- array
- }
- /// Trait for types which can be referenced as slices and which support conversion from `Vec<u8>`.
- pub trait FromVec: AsRef<[u8]> {
- fn from_vec(vec: Vec<u8>) -> Self;
- }
- impl FromVec for Vec<u8> {
- fn from_vec(vec: Vec<u8>) -> Self {
- vec
- }
- }
- impl<const N: usize> FromVec for [u8; N] {
- fn from_vec(vec: Vec<u8>) -> Self {
- assert_eq!(N, vec.len());
- let mut buf = [0u8; N];
- buf.copy_from_slice(&vec);
- buf
- }
- }
- /// Module containing functions for serializing and deserializing buffers in `SectoredCursor<T>`.
- mod serde_cursor {
- use super::FromVec;
- use serde::{Deserialize, Deserializer, Serialize, Serializer};
- use std::{
- cell::RefCell,
- io::{Cursor, Read},
- result::Result,
- };
- pub fn serialize<T: AsRef<[u8]>, S: Serializer>(
- cursor: &RefCell<Cursor<T>>,
- ser: S,
- ) -> Result<S::Ok, S::Error> {
- let mut cursor = cursor.borrow_mut();
- let pos = cursor.position();
- cursor.set_position(0);
- let mut data = Vec::new();
- cursor
- .read_to_end(&mut data)
- .expect("reading from cursor failed");
- cursor.set_position(pos);
- data.serialize(ser)
- }
- pub fn deserialize<'de, T: FromVec, D: Deserializer<'de>>(
- de: D,
- ) -> Result<RefCell<Cursor<T>>, D::Error> {
- let data = Vec::<u8>::deserialize(de)?;
- Ok(RefCell::new(Cursor::new(T::from_vec(data))))
- }
- }
- /// A wrapper for `Cursor<T>` which implements additional traits.
- #[derive(Debug, PartialEq, Serialize, Deserialize)]
- pub struct BtCursor<T: FromVec> {
- #[serde(with = "serde_cursor")]
- cursor: RefCell<Cursor<T>>,
- }
- impl<T: FromVec> BtCursor<T> {
- pub fn new(inner: T) -> BtCursor<T> {
- BtCursor {
- cursor: RefCell::new(Cursor::new(inner)),
- }
- }
- }
- impl<T: FromVec> Decompose<T> for BtCursor<T> {
- fn into_inner(self) -> T {
- self.cursor.into_inner().into_inner()
- }
- }
- impl<T: FromVec + AsMut<[u8]>> BtCursor<T> {
- /// Access the data in this cursor as a mutable slice of bytes. The callback which access the
- /// bytes is expected to return the number of bytes to advance the cursor position by.
- fn access_advance<F: FnOnce(&mut [u8]) -> u64>(&mut self, limit: usize, accessor: F) -> u64 {
- let mut cursor = self.cursor.borrow_mut();
- let pos = cursor.position();
- let byte_slice = cursor.get_mut().as_mut();
- let max = byte_slice.len().max(limit);
- let pos_usize: usize = pos.try_into().unwrap();
- let byte_slice = &mut byte_slice[pos_usize..max];
- let advance_by = accessor(byte_slice);
- cursor.set_position(pos + advance_by);
- advance_by
- }
- /// Gives a `accessor` access to a slice containing all of the data in this cursor.
- fn access_whole<U, F: FnOnce(&mut [u8]) -> U>(&mut self, accessor: F) -> U {
- let mut cursor = self.cursor.borrow_mut();
- let byte_slice = cursor.get_mut().as_mut();
- accessor(byte_slice)
- }
- fn write_from_impl(
- &mut self,
- f: &mut dyn FileReadWriteVolatile,
- count: usize,
- off: u64,
- ) -> io::Result<usize> {
- let read = self.access_advance(count, |byte_slice| {
- let slice = unsafe {
- FileVolatileSlice::from_raw_ptr(byte_slice.as_mut_ptr(), byte_slice.len())
- };
- let read = f.read_at_volatile(slice, off).expect("read failed");
- read.try_into().unwrap()
- });
- Ok(read.try_into().unwrap())
- }
- }
- impl Write for BtCursor<Vec<u8>> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.cursor.get_mut().write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- self.cursor.get_mut().flush()
- }
- }
- impl<const N: usize> Write for BtCursor<[u8; N]> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.cursor.get_mut().write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- self.cursor.get_mut().flush()
- }
- }
- impl WriteAt for BtCursor<Vec<u8>> {
- fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result<usize> {
- let pos: usize = pos.try_into().box_err()?;
- let vec = self.cursor.get_mut().get_mut();
- let end = pos + buf.len();
- if end > vec.len() {
- vec.resize(end, 0);
- }
- let slice = &mut vec[pos..end];
- slice.copy_from_slice(buf);
- Ok(end - pos)
- }
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
- }
- impl<const N: usize> WriteAt for BtCursor<[u8; N]> {
- fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result<usize> {
- let pos: usize = pos.try_into().box_err()?;
- let slice = self.cursor.get_mut().get_mut().as_mut();
- let end = pos + buf.len();
- let slice = &mut slice[pos..end];
- slice.copy_from_slice(buf);
- Ok(end - pos)
- }
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
- }
- impl<T: FromVec> Read for BtCursor<T> {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
- self.cursor.get_mut().read(buf)
- }
- }
- impl<T: FromVec> ReadAt for BtCursor<T> {
- fn read_at(&self, pos: u64, buf: &mut [u8]) -> io::Result<usize> {
- let pos: usize = pos.try_into().box_err()?;
- let borrow = self.cursor.try_borrow().box_err()?;
- let slice: &[u8] = borrow.get_ref().as_ref();
- let end = slice.len().min(pos + buf.len());
- let buf = &mut buf[..(end - pos)];
- buf.copy_from_slice(&slice[pos..end]);
- Ok(end - pos)
- }
- }
- impl<T: FromVec> Seek for BtCursor<T> {
- fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
- self.cursor.get_mut().seek(pos)
- }
- }
- impl WriteInteg for BtCursor<Vec<u8>> {
- fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> {
- Ok(())
- }
- }
- impl<const N: usize> WriteInteg for BtCursor<[u8; N]> {
- fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> {
- Ok(())
- }
- }
- impl<T: AsMut<[u8]> + FromVec> FileReadWriteVolatile for BtCursor<T> {
- fn read_volatile(
- &mut self,
- slice: fuse_backend_rs::file_buf::FileVolatileSlice,
- ) -> io::Result<usize> {
- let read = self.access_advance(usize::MAX, |byte_slice| {
- let written = slice.as_volatile_slice().write(byte_slice, 0).unwrap();
- written.try_into().unwrap()
- });
- Ok(read.try_into().unwrap())
- }
- fn write_volatile(
- &mut self,
- slice: fuse_backend_rs::file_buf::FileVolatileSlice,
- ) -> io::Result<usize> {
- let written = self.access_advance(usize::MAX, |byte_slice| {
- let read = slice.as_volatile_slice().read(byte_slice, 0).unwrap();
- read.try_into().unwrap()
- });
- Ok(written.try_into().unwrap())
- }
- fn read_at_volatile(
- &mut self,
- slice: fuse_backend_rs::file_buf::FileVolatileSlice,
- offset: u64,
- ) -> io::Result<usize> {
- Ok(self.access_whole(|byte_slice| {
- let offset = offset.try_into().unwrap();
- let byte_slice = &mut byte_slice[offset..];
- slice.as_volatile_slice().write(byte_slice, 0).unwrap()
- }))
- }
- fn write_at_volatile(
- &mut self,
- slice: fuse_backend_rs::file_buf::FileVolatileSlice,
- offset: u64,
- ) -> io::Result<usize> {
- Ok(self.access_whole(|byte_slice| {
- let offset = offset.try_into().unwrap();
- let byte_slice = &mut byte_slice[offset..];
- slice.as_volatile_slice().read(byte_slice, 0).unwrap()
- }))
- }
- }
- impl<T: AsMut<[u8]> + FromVec> ZeroCopyReader for BtCursor<T> {
- fn read_to(
- &mut self,
- f: &mut dyn FileReadWriteVolatile,
- count: usize,
- off: u64,
- ) -> io::Result<usize> {
- let written = self.access_advance(count, |byte_slice| {
- // Safety: The mut borrow of cursor is guaranteed to be the only one in existence
- // because this method takes &mut self.
- let slice = unsafe {
- FileVolatileSlice::from_raw_ptr(byte_slice.as_mut_ptr(), byte_slice.len())
- };
- let written = f.write_at_volatile(slice, off).expect("write failed");
- let written_u64: u64 = written.try_into().unwrap();
- written_u64
- });
- Ok(written.try_into().unwrap())
- }
- }
- impl ZeroCopyWriter for BtCursor<Vec<u8>> {
- fn write_from(
- &mut self,
- f: &mut dyn FileReadWriteVolatile,
- count: usize,
- off: u64,
- ) -> io::Result<usize> {
- self.write_from_impl(f, count, off)
- }
- }
- impl<const N: usize> ZeroCopyWriter for BtCursor<[u8; N]> {
- fn write_from(
- &mut self,
- f: &mut dyn FileReadWriteVolatile,
- count: usize,
- off: u64,
- ) -> io::Result<usize> {
- self.write_from_impl(f, count, off)
- }
- }
- impl<T: FromVec> Size for BtCursor<T> {
- fn size(&self) -> io::Result<Option<u64>> {
- let borrow = self.cursor.borrow();
- let slice: &[u8] = borrow.get_ref().as_ref();
- Ok(Some(slice.len() as u64))
- }
- }
- #[derive(Debug, PartialEq, Serialize, Deserialize)]
- pub struct SectoredCursor<T: FromVec> {
- cursor: BtCursor<T>,
- sect_sz: usize,
- meta: BlockMeta,
- require_sect_sz: bool,
- }
- impl<T: FromVec> SectoredCursor<T> {
- pub fn new(inner: T, sect_sz: usize) -> SectoredCursor<T> {
- SectoredCursor {
- cursor: BtCursor::new(inner),
- sect_sz,
- meta: BlockMeta::new(&*NODE_CREDS).unwrap(),
- require_sect_sz: true,
- }
- }
- pub fn require_sect_sz(mut self, require: bool) -> Self {
- self.require_sect_sz = require;
- self
- }
- }
- impl<T: FromVec> Sectored for SectoredCursor<T> {
- fn sector_sz(&self) -> usize {
- self.sect_sz
- }
- }
- impl<T: FromVec> Decompose<T> for SectoredCursor<T> {
- fn into_inner(self) -> T {
- self.cursor.into_inner()
- }
- }
- impl Write for SectoredCursor<Vec<u8>> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- if self.require_sect_sz {
- self.assert_sector_sz(buf.len())?;
- }
- self.cursor.write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- Write::flush(&mut self.cursor)
- }
- }
- impl<const N: usize> Write for SectoredCursor<[u8; N]> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- if self.require_sect_sz {
- self.assert_sector_sz(buf.len())?;
- }
- self.cursor.write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- Write::flush(&mut self.cursor)
- }
- }
- impl WriteAt for SectoredCursor<Vec<u8>> {
- fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result<usize> {
- self.cursor.write_at(pos, buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- Write::flush(&mut self.cursor)
- }
- }
- impl<const N: usize> WriteAt for SectoredCursor<[u8; N]> {
- fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result<usize> {
- self.cursor.write_at(pos, buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- Write::flush(&mut self.cursor)
- }
- }
- impl<T: FromVec> SectoredCursor<T> {
- fn flush_integ_impl(&mut self, integrity: &[u8]) -> io::Result<()> {
- let dest = self
- .meta
- .body
- .integrity
- .get_or_insert_with(<VarHash as Default>::default);
- dest.as_mut_slice().copy_from_slice(integrity);
- Ok(())
- }
- }
- impl WriteInteg for SectoredCursor<Vec<u8>> {
- fn flush_integ(&mut self, integrity: &[u8]) -> io::Result<()> {
- self.flush_integ_impl(integrity)
- }
- }
- impl<const N: usize> WriteInteg for SectoredCursor<[u8; N]> {
- fn flush_integ(&mut self, integrity: &[u8]) -> io::Result<()> {
- self.flush_integ_impl(integrity)
- }
- }
- impl<T: FromVec> Read for SectoredCursor<T> {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
- if self.require_sect_sz {
- self.assert_sector_sz(buf.len())?;
- }
- self.cursor.read(buf)
- }
- }
- impl<T: FromVec> ReadAt for SectoredCursor<T> {
- fn read_at(&self, pos: u64, buf: &mut [u8]) -> io::Result<usize> {
- if self.require_sect_sz {
- self.assert_sector_sz(buf.len())?;
- }
- self.cursor.read_at(pos, buf)
- }
- }
- impl<T: FromVec> Seek for SectoredCursor<T> {
- fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
- self.cursor.seek(pos)
- }
- }
- impl<T: FromVec> AsRef<BlockMeta> for SectoredCursor<T> {
- fn as_ref(&self) -> &BlockMeta {
- &self.meta
- }
- }
- impl<T: FromVec> AsMut<BlockMeta> for SectoredCursor<T> {
- fn as_mut(&mut self) -> &mut BlockMeta {
- &mut self.meta
- }
- }
- impl<T: FromVec> Size for SectoredCursor<T> {
- fn size(&self) -> io::Result<Option<u64>> {
- self.cursor.size()
- }
- }
|