1 mod attr;
2 mod dir;
3 mod remote_file;
4 
5 pub use attr::Attr;
6 pub use dir::{InMemoryDir, RemoteDirEditor};
7 pub use remote_file::{RemoteFileEditor, RemoteFileReader, RemoteMerkleTreeReader};
8 
9 use crate::common::{divide_roundup, CHUNK_SIZE};
10 use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::IVirtFdService;
11 use binder::{Status, StatusCode, Strong};
12 use rpcbinder::RpcSession;
13 use std::convert::TryFrom;
14 use std::io;
15 use std::path::{Path, MAIN_SEPARATOR};
16 
17 pub type VirtFdService = Strong<dyn IVirtFdService>;
18 pub type VirtFdServiceStatus = Status;
19 
20 pub type ChunkBuffer = [u8; CHUNK_SIZE as usize];
21 
22 pub const RPC_SERVICE_PORT: u32 = 3264;
23 
get_rpc_binder_service(cid: u32) -> io::Result<VirtFdService>24 pub fn get_rpc_binder_service(cid: u32) -> io::Result<VirtFdService> {
25     RpcSession::new().setup_vsock_client(cid, RPC_SERVICE_PORT).map_err(|e| match e {
26         StatusCode::BAD_VALUE => {
27             io::Error::new(io::ErrorKind::InvalidInput, "Invalid raw AIBinder")
28         }
29         _ => io::Error::new(
30             io::ErrorKind::AddrNotAvailable,
31             format!("Cannot connect to RPC service: {}", e),
32         ),
33     })
34 }
35 
36 /// A trait for reading data by chunks. Chunks can be read by specifying the chunk index. Only the
37 /// last chunk may have incomplete chunk size.
38 pub trait ReadByChunk {
39     /// Reads the `chunk_index`-th chunk to a `ChunkBuffer`. Returns the size read, which has to be
40     /// `CHUNK_SIZE` except for the last incomplete chunk. Reading beyond the file size (including
41     /// empty file) should return 0.
read_chunk(&self, chunk_index: u64, buf: &mut ChunkBuffer) -> io::Result<usize>42     fn read_chunk(&self, chunk_index: u64, buf: &mut ChunkBuffer) -> io::Result<usize>;
43 }
44 
45 /// A trait to write a buffer to the destination at a given offset. The implementation does not
46 /// necessarily own or maintain the destination state.
47 ///
48 /// NB: The trait is required in a member of `fusefs::AuthFs`, which is required to be Sync and
49 /// immutable (this the member).
50 pub trait RandomWrite {
51     /// Writes `buf` to the destination at `offset`. Returns the written size, which may not be the
52     /// full buffer.
write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize>53     fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize>;
54 
55     /// Writes the full `buf` to the destination at `offset`.
write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()>56     fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
57         let mut input_offset = 0;
58         let mut output_offset = offset;
59         while input_offset < buf.len() {
60             let size = self.write_at(&buf[input_offset..], output_offset)?;
61             input_offset += size;
62             output_offset += size as u64;
63         }
64         Ok(())
65     }
66 
67     /// Resizes the file to the new size.
resize(&self, size: u64) -> io::Result<()>68     fn resize(&self, size: u64) -> io::Result<()>;
69 }
70 
71 /// Checks whether the path is a simple file name without any directory separator.
validate_basename(path: &Path) -> io::Result<()>72 pub fn validate_basename(path: &Path) -> io::Result<()> {
73     if matches!(path.to_str(), Some(path_str) if !path_str.contains(MAIN_SEPARATOR)) {
74         Ok(())
75     } else {
76         Err(io::Error::from_raw_os_error(libc::EINVAL))
77     }
78 }
79 
80 pub struct EagerChunkReader {
81     buffer: Vec<u8>,
82 }
83 
84 impl EagerChunkReader {
new<F: ReadByChunk>(chunked_file: F, file_size: u64) -> io::Result<EagerChunkReader>85     pub fn new<F: ReadByChunk>(chunked_file: F, file_size: u64) -> io::Result<EagerChunkReader> {
86         let last_index = divide_roundup(file_size, CHUNK_SIZE);
87         let file_size = usize::try_from(file_size).unwrap();
88         let mut buffer = Vec::with_capacity(file_size);
89         let mut chunk_buffer = [0; CHUNK_SIZE as usize];
90         for index in 0..last_index {
91             let size = chunked_file.read_chunk(index, &mut chunk_buffer)?;
92             buffer.extend_from_slice(&chunk_buffer[..size]);
93         }
94         if buffer.len() < file_size {
95             Err(io::Error::new(
96                 io::ErrorKind::InvalidData,
97                 format!("Insufficient data size ({} < {})", buffer.len(), file_size),
98             ))
99         } else {
100             Ok(EagerChunkReader { buffer })
101         }
102     }
103 }
104 
105 impl ReadByChunk for EagerChunkReader {
read_chunk(&self, chunk_index: u64, buf: &mut ChunkBuffer) -> io::Result<usize>106     fn read_chunk(&self, chunk_index: u64, buf: &mut ChunkBuffer) -> io::Result<usize> {
107         if let Some(chunk) = &self.buffer.chunks(CHUNK_SIZE as usize).nth(chunk_index as usize) {
108             buf[..chunk.len()].copy_from_slice(chunk);
109             Ok(chunk.len())
110         } else {
111             Ok(0) // Read beyond EOF is normal
112         }
113     }
114 }
115