blob: 17a368f1c2e2aa12b0eb9f9857cc0ab59ed9b344 [file] [log] [blame]
Victor Hsieh88ac6ca2020-11-13 15:20:24 -08001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Victor Hsieh79f296b2021-12-02 15:38:08 -080017mod mount;
18
Victor Hsiehd18b9752021-11-09 16:03:34 -080019use anyhow::{anyhow, bail, Result};
Victor Hsieh3dccf702021-12-02 15:45:14 -080020use log::{debug, error, warn};
Victor Hsieh4d6b9d42021-11-08 15:53:49 -080021use std::collections::{btree_map, BTreeMap};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080022use std::convert::TryFrom;
Victor Hsieh45636232021-10-15 17:52:51 -070023use std::ffi::{CStr, OsStr};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080024use std::io;
Victor Hsiehf7fc3d32021-11-22 10:20:33 -080025use std::mem::{zeroed, MaybeUninit};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080026use std::option::Option;
Victor Hsieh79f296b2021-12-02 15:38:08 -080027use std::os::unix::ffi::OsStrExt;
Victor Hsiehd18b9752021-11-09 16:03:34 -080028use std::path::{Component, Path, PathBuf};
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -080029use std::sync::atomic::{AtomicU64, Ordering};
Victor Hsieh60c2f412021-11-03 13:02:19 -070030use std::sync::Mutex;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080031use std::time::Duration;
32
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080033use fuse::filesystem::{
Victor Hsieh71f10032021-08-13 11:24:02 -070034 Context, DirEntry, DirectoryIterator, Entry, FileSystem, FsOptions, GetxattrReply,
35 SetattrValid, ZeroCopyReader, ZeroCopyWriter,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080036};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080037
Victor Hsiehac4f3f42021-02-26 12:35:58 -080038use crate::common::{divide_roundup, ChunkedSizeIter, CHUNK_SIZE};
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080039use crate::file::{
Victor Hsiehd18b9752021-11-09 16:03:34 -080040 validate_basename, InMemoryDir, RandomWrite, ReadByChunk, RemoteDirEditor, RemoteFileEditor,
41 RemoteFileReader, RemoteMerkleTreeReader,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080042};
Victor Hsiehf7fc3d32021-11-22 10:20:33 -080043use crate::fsstat::RemoteFsStatsReader;
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080044use crate::fsverity::{VerifiedFileEditor, VerifiedFileReader};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080045
Victor Hsieh79f296b2021-12-02 15:38:08 -080046pub use self::mount::mount_and_enter_message_loop;
47use self::mount::MAX_WRITE_BYTES;
48
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080049pub type Inode = u64;
50type Handle = u64;
51
Victor Hsieh26cea2f2021-11-03 10:28:33 -070052const DEFAULT_METADATA_TIMEOUT: Duration = Duration::from_secs(5);
53const ROOT_INODE: Inode = 1;
54
55/// `AuthFsEntry` defines the filesystem entry type supported by AuthFS.
56pub enum AuthFsEntry {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -080057 /// A read-only directory (writable during initialization). Root directory is an example.
58 ReadonlyDirectory { dir: InMemoryDir },
Victor Hsieh1bcf4112021-03-19 14:26:57 -070059 /// A file type that is verified against fs-verity signature (thus read-only). The file is
Victor Hsieh1bcf4112021-03-19 14:26:57 -070060 /// served from a remote server.
Victor Hsieh88e50172021-10-15 13:27:13 -070061 VerifiedReadonly {
Victor Hsieh1bcf4112021-03-19 14:26:57 -070062 reader: VerifiedFileReader<RemoteFileReader, RemoteMerkleTreeReader>,
63 file_size: u64,
64 },
Victor Hsiehf7fc3d32021-11-22 10:20:33 -080065 /// A file type that is a read-only passthrough from a file on a remote server.
Victor Hsieh88e50172021-10-15 13:27:13 -070066 UnverifiedReadonly { reader: RemoteFileReader, file_size: u64 },
Victor Hsieh1bcf4112021-03-19 14:26:57 -070067 /// A file type that is initially empty, and the content is stored on a remote server. File
68 /// integrity is guaranteed with private Merkle tree.
Victor Hsieh88e50172021-10-15 13:27:13 -070069 VerifiedNew { editor: VerifiedFileEditor<RemoteFileEditor> },
Victor Hsieh45636232021-10-15 17:52:51 -070070 /// A directory type that is initially empty. One can create new file (`VerifiedNew`) and new
71 /// directory (`VerifiedNewDirectory` itself) with integrity guaranteed within the VM.
72 VerifiedNewDirectory { dir: RemoteDirEditor },
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080073}
74
Victor Hsiehdd99b462021-12-02 17:36:15 -080075impl AuthFsEntry {
76 fn expect_empty_writable_directory(&self) -> io::Result<()> {
77 match self {
78 AuthFsEntry::VerifiedNewDirectory { dir } => {
79 if dir.number_of_entries() == 0 {
80 Ok(())
81 } else {
82 Err(io::Error::from_raw_os_error(libc::ENOTEMPTY))
83 }
84 }
85 AuthFsEntry::ReadonlyDirectory { .. } => {
86 Err(io::Error::from_raw_os_error(libc::EACCES))
87 }
88 _ => Err(io::Error::from_raw_os_error(libc::ENOTDIR)),
89 }
90 }
91}
92
Victor Hsieh3dccf702021-12-02 15:45:14 -080093struct InodeState {
94 /// Actual inode entry.
95 entry: AuthFsEntry,
96
97 /// Number of `Handle`s (i.e. file descriptors) that are currently referring to the this inode.
98 ///
99 /// Technically, this does not matter to readonly entries, since they live forever. The
100 /// reference count is only needed for manageing lifetime of writable entries like `VerifiedNew`
101 /// and `VerifiedNewDirectory`. That is, when an entry is deleted, the actual entry needs to
102 /// stay alive until the reference count reaches zero.
103 ///
104 /// Note: This is not to be confused with hardlinks, which AuthFS doesn't currently implement.
105 handle_ref_count: u64,
Victor Hsiehdd99b462021-12-02 17:36:15 -0800106
107 /// Whether the inode is already unlinked, i.e. should be removed, once `handle_ref_count` is
108 /// down to zero.
109 unlinked: bool,
Victor Hsieh3dccf702021-12-02 15:45:14 -0800110}
111
112impl InodeState {
113 fn new(entry: AuthFsEntry) -> Self {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800114 InodeState { entry, handle_ref_count: 0, unlinked: false }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800115 }
116
117 fn new_with_ref_count(entry: AuthFsEntry, handle_ref_count: u64) -> Self {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800118 InodeState { entry, handle_ref_count, unlinked: false }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800119 }
120}
121
Victor Hsieh60c2f412021-11-03 13:02:19 -0700122// AuthFS needs to be `Sync` to be accepted by fuse::worker::start_message_loop as a `FileSystem`.
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800123pub struct AuthFs {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800124 /// Table for `Inode` to `InodeState` lookup. This needs to be `Sync` to be used in
Victor Hsieh60c2f412021-11-03 13:02:19 -0700125 /// `fuse::worker::start_message_loop`.
Victor Hsieh3dccf702021-12-02 15:45:14 -0800126 inode_table: Mutex<BTreeMap<Inode, InodeState>>,
Victor Hsieh60c2f412021-11-03 13:02:19 -0700127
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800128 /// The next available inode number.
129 next_inode: AtomicU64,
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800130
131 /// A reader to access the remote filesystem stats, which is supposed to be of "the" output
132 /// directory. We assume all output are stored in the same partition.
133 remote_fs_stats_reader: RemoteFsStatsReader,
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800134}
135
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800136// Implementation for preparing an `AuthFs` instance, before starting to serve.
137// TODO(victorhsieh): Consider implement a builder to separate the mutable initialization from the
138// immutable / interiorly mutable serving phase.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800139impl AuthFs {
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800140 pub fn new(remote_fs_stats_reader: RemoteFsStatsReader) -> AuthFs {
Victor Hsieh60c2f412021-11-03 13:02:19 -0700141 let mut inode_table = BTreeMap::new();
Victor Hsieh3dccf702021-12-02 15:45:14 -0800142 inode_table.insert(
143 ROOT_INODE,
144 InodeState::new(AuthFsEntry::ReadonlyDirectory { dir: InMemoryDir::new() }),
145 );
Victor Hsieh60c2f412021-11-03 13:02:19 -0700146
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800147 AuthFs {
148 inode_table: Mutex::new(inode_table),
149 next_inode: AtomicU64::new(ROOT_INODE + 1),
150 remote_fs_stats_reader,
151 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800152 }
153
Victor Hsiehd18b9752021-11-09 16:03:34 -0800154 /// Add an `AuthFsEntry` as `basename` to the filesystem root.
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800155 pub fn add_entry_at_root_dir(
156 &mut self,
157 basename: PathBuf,
158 entry: AuthFsEntry,
159 ) -> Result<Inode> {
Victor Hsiehd18b9752021-11-09 16:03:34 -0800160 validate_basename(&basename)?;
161 self.add_entry_at_ro_dir_by_path(ROOT_INODE, &basename, entry)
162 }
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800163
Victor Hsiehd18b9752021-11-09 16:03:34 -0800164 /// Add an `AuthFsEntry` by path from the `ReadonlyDirectory` represented by `dir_inode`. The
165 /// path must be a related path. If some ancestor directories do not exist, they will be
166 /// created (also as `ReadonlyDirectory`) automatically.
167 pub fn add_entry_at_ro_dir_by_path(
168 &mut self,
169 dir_inode: Inode,
170 path: &Path,
171 entry: AuthFsEntry,
172 ) -> Result<Inode> {
173 // 1. Make sure the parent directories all exist. Derive the entry's parent inode.
174 let parent_path =
175 path.parent().ok_or_else(|| anyhow!("No parent directory: {:?}", path))?;
176 let parent_inode =
177 parent_path.components().try_fold(dir_inode, |current_dir_inode, path_component| {
178 match path_component {
179 Component::RootDir => bail!("Absolute path is not supported"),
180 Component::Normal(name) => {
181 let inode_table = self.inode_table.get_mut().unwrap();
182 // Locate the internal directory structure.
Victor Hsieh3dccf702021-12-02 15:45:14 -0800183 let current_dir_entry = &mut inode_table
184 .get_mut(&current_dir_inode)
185 .ok_or_else(|| {
Victor Hsiehd18b9752021-11-09 16:03:34 -0800186 anyhow!("Unknown directory inode {}", current_dir_inode)
Victor Hsieh3dccf702021-12-02 15:45:14 -0800187 })?
188 .entry;
Victor Hsiehd18b9752021-11-09 16:03:34 -0800189 let dir = match current_dir_entry {
190 AuthFsEntry::ReadonlyDirectory { dir } => dir,
191 _ => unreachable!("Not a ReadonlyDirectory"),
192 };
193 // Return directory inode. Create first if not exists.
194 if let Some(existing_inode) = dir.lookup_inode(name.as_ref()) {
195 Ok(existing_inode)
196 } else {
197 let new_inode = self.next_inode.fetch_add(1, Ordering::Relaxed);
198 let new_dir_entry =
199 AuthFsEntry::ReadonlyDirectory { dir: InMemoryDir::new() };
200
201 // Actually update the tables.
202 dir.add_entry(name.as_ref(), new_inode)?;
Victor Hsieh3dccf702021-12-02 15:45:14 -0800203 if inode_table
204 .insert(new_inode, InodeState::new(new_dir_entry))
205 .is_some()
206 {
Victor Hsiehd18b9752021-11-09 16:03:34 -0800207 bail!("Unexpected to find a duplicated inode");
208 }
209 Ok(new_inode)
210 }
211 }
212 _ => Err(anyhow!("Path is not canonical: {:?}", path)),
213 }
214 })?;
215
216 // 2. Insert the entry to the parent directory, as well as the inode table.
217 let inode_table = self.inode_table.get_mut().unwrap();
Victor Hsieh3dccf702021-12-02 15:45:14 -0800218 let inode_state = inode_table.get_mut(&parent_inode).expect("previously returned inode");
219 match &mut inode_state.entry {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800220 AuthFsEntry::ReadonlyDirectory { dir } => {
Victor Hsiehd18b9752021-11-09 16:03:34 -0800221 let basename =
222 path.file_name().ok_or_else(|| anyhow!("Bad file name: {:?}", path))?;
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800223 let new_inode = self.next_inode.fetch_add(1, Ordering::Relaxed);
224
Victor Hsiehd18b9752021-11-09 16:03:34 -0800225 // Actually update the tables.
226 dir.add_entry(basename.as_ref(), new_inode)?;
Victor Hsieh3dccf702021-12-02 15:45:14 -0800227 if inode_table.insert(new_inode, InodeState::new(entry)).is_some() {
Victor Hsiehd18b9752021-11-09 16:03:34 -0800228 bail!("Unexpected to find a duplicated inode");
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800229 }
230 Ok(new_inode)
231 }
Victor Hsiehd18b9752021-11-09 16:03:34 -0800232 _ => unreachable!("Not a ReadonlyDirectory"),
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800233 }
234 }
235}
236
237// Implementation for serving requests.
238impl AuthFs {
Victor Hsieh45636232021-10-15 17:52:51 -0700239 /// Handles the file associated with `inode` if found. This function returns whatever
240 /// `handle_fn` returns.
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700241 fn handle_inode<F, R>(&self, inode: &Inode, handle_fn: F) -> io::Result<R>
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700242 where
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700243 F: FnOnce(&AuthFsEntry) -> io::Result<R>,
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700244 {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700245 let inode_table = self.inode_table.lock().unwrap();
Victor Hsieh3dccf702021-12-02 15:45:14 -0800246 handle_inode_locked(&inode_table, inode, |inode_state| handle_fn(&inode_state.entry))
Victor Hsieh45636232021-10-15 17:52:51 -0700247 }
248
Victor Hsieh3dccf702021-12-02 15:45:14 -0800249 /// Adds a new entry `name` created by `create_fn` at `parent_inode`, with an initial ref count
250 /// of one.
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800251 ///
252 /// The operation involves two updates: adding the name with a new allocated inode to the
253 /// parent directory, and insert the new inode and the actual `AuthFsEntry` to the global inode
254 /// table.
255 ///
256 /// `create_fn` receives the parent directory, through which it can create the new entry at and
257 /// register the new inode to. Its returned entry is then added to the inode table.
Victor Hsieh3dccf702021-12-02 15:45:14 -0800258 fn create_new_entry_with_ref_count<F>(
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800259 &self,
260 parent_inode: Inode,
261 name: &CStr,
262 create_fn: F,
263 ) -> io::Result<Inode>
Victor Hsieh45636232021-10-15 17:52:51 -0700264 where
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800265 F: FnOnce(&mut AuthFsEntry, &Path, Inode) -> io::Result<AuthFsEntry>,
Victor Hsieh45636232021-10-15 17:52:51 -0700266 {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700267 let mut inode_table = self.inode_table.lock().unwrap();
Victor Hsieh3dccf702021-12-02 15:45:14 -0800268 let (new_inode, new_file_entry) = handle_inode_mut_locked(
269 &mut inode_table,
270 &parent_inode,
271 |InodeState { entry, .. }| {
272 let new_inode = self.next_inode.fetch_add(1, Ordering::Relaxed);
273 let basename: &Path = cstr_to_path(name);
274 let new_file_entry = create_fn(entry, basename, new_inode)?;
275 Ok((new_inode, new_file_entry))
276 },
277 )?;
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800278
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700279 if let btree_map::Entry::Vacant(entry) = inode_table.entry(new_inode) {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800280 entry.insert(InodeState::new_with_ref_count(new_file_entry, 1));
Victor Hsieh45636232021-10-15 17:52:51 -0700281 Ok(new_inode)
282 } else {
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800283 unreachable!("Unexpected duplication of inode {}", new_inode);
Victor Hsieh45636232021-10-15 17:52:51 -0700284 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800285 }
286}
287
288fn check_access_mode(flags: u32, mode: libc::c_int) -> io::Result<()> {
289 if (flags & libc::O_ACCMODE as u32) == mode as u32 {
290 Ok(())
291 } else {
292 Err(io::Error::from_raw_os_error(libc::EACCES))
293 }
294}
295
296cfg_if::cfg_if! {
297 if #[cfg(all(target_arch = "aarch64", target_pointer_width = "64"))] {
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800298 fn blk_size() -> libc::c_int { CHUNK_SIZE as libc::c_int }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800299 } else {
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800300 fn blk_size() -> libc::c_long { CHUNK_SIZE as libc::c_long }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800301 }
302}
303
Victor Hsieh45636232021-10-15 17:52:51 -0700304#[allow(clippy::enum_variant_names)]
305enum AccessMode {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800306 ReadOnly,
307 ReadWrite,
308}
309
Victor Hsieh45636232021-10-15 17:52:51 -0700310fn create_stat(
311 ino: libc::ino_t,
312 file_size: u64,
313 access_mode: AccessMode,
314) -> io::Result<libc::stat64> {
315 // SAFETY: stat64 is a plan C struct without pointer.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800316 let mut st = unsafe { MaybeUninit::<libc::stat64>::zeroed().assume_init() };
317
318 st.st_ino = ino;
Victor Hsieh45636232021-10-15 17:52:51 -0700319 st.st_mode = match access_mode {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800320 // Until needed, let's just grant the owner access.
Victor Hsieh45636232021-10-15 17:52:51 -0700321 // TODO(205169366): Implement mode properly.
322 AccessMode::ReadOnly => libc::S_IFREG | libc::S_IRUSR,
323 AccessMode::ReadWrite => libc::S_IFREG | libc::S_IRUSR | libc::S_IWUSR,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800324 };
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800325 st.st_nlink = 1;
326 st.st_uid = 0;
327 st.st_gid = 0;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800328 st.st_size = libc::off64_t::try_from(file_size)
329 .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?;
330 st.st_blksize = blk_size();
331 // Per man stat(2), st_blocks is "Number of 512B blocks allocated".
332 st.st_blocks = libc::c_longlong::try_from(divide_roundup(file_size, 512))
333 .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?;
334 Ok(st)
335}
336
Victor Hsieh45636232021-10-15 17:52:51 -0700337fn create_dir_stat(ino: libc::ino_t, file_number: u16) -> io::Result<libc::stat64> {
338 // SAFETY: stat64 is a plan C struct without pointer.
339 let mut st = unsafe { MaybeUninit::<libc::stat64>::zeroed().assume_init() };
340
341 st.st_ino = ino;
342 // TODO(205169366): Implement mode properly.
343 st.st_mode = libc::S_IFDIR
344 | libc::S_IXUSR
345 | libc::S_IWUSR
346 | libc::S_IRUSR
347 | libc::S_IXGRP
348 | libc::S_IXOTH;
349
350 // 2 extra for . and ..
351 st.st_nlink = file_number
352 .checked_add(2)
353 .ok_or_else(|| io::Error::from_raw_os_error(libc::EOVERFLOW))?
354 .into();
355
356 st.st_uid = 0;
357 st.st_gid = 0;
358 Ok(st)
359}
360
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800361fn offset_to_chunk_index(offset: u64) -> u64 {
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800362 offset / CHUNK_SIZE
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800363}
364
Victor Hsiehd0bb5d32021-03-19 12:48:03 -0700365fn read_chunks<W: io::Write, T: ReadByChunk>(
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800366 mut w: W,
367 file: &T,
368 file_size: u64,
369 offset: u64,
370 size: u32,
371) -> io::Result<usize> {
372 let remaining = file_size.saturating_sub(offset);
373 let size_to_read = std::cmp::min(size as usize, remaining as usize);
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800374 let total = ChunkedSizeIter::new(size_to_read, offset, CHUNK_SIZE as usize).try_fold(
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800375 0,
376 |total, (current_offset, planned_data_size)| {
377 // TODO(victorhsieh): There might be a non-trivial way to avoid this copy. For example,
378 // instead of accepting a buffer, the writer could expose the final destination buffer
379 // for the reader to write to. It might not be generally applicable though, e.g. with
380 // virtio transport, the buffer may not be continuous.
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800381 let mut buf = [0u8; CHUNK_SIZE as usize];
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800382 let read_size = file.read_chunk(offset_to_chunk_index(current_offset), &mut buf)?;
383 if read_size < planned_data_size {
384 return Err(io::Error::from_raw_os_error(libc::ENODATA));
385 }
386
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800387 let begin = (current_offset % CHUNK_SIZE) as usize;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800388 let end = begin + planned_data_size;
389 let s = w.write(&buf[begin..end])?;
390 if s != planned_data_size {
391 return Err(io::Error::from_raw_os_error(libc::EIO));
392 }
393 Ok(total + s)
394 },
395 )?;
396
397 Ok(total)
398}
399
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800400// TODO(205715172): Support enumerating directory entries.
401pub struct EmptyDirectoryIterator {}
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800402
403impl DirectoryIterator for EmptyDirectoryIterator {
404 fn next(&mut self) -> Option<DirEntry> {
405 None
406 }
407}
408
409impl FileSystem for AuthFs {
410 type Inode = Inode;
411 type Handle = Handle;
412 type DirIter = EmptyDirectoryIterator;
413
414 fn max_buffer_size(&self) -> u32 {
Victor Hsieh766e5332021-11-09 09:41:25 -0800415 MAX_WRITE_BYTES
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800416 }
417
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800418 fn init(&self, _capable: FsOptions) -> io::Result<FsOptions> {
419 // Enable writeback cache for better performance especially since our bandwidth to the
420 // backend service is limited.
421 Ok(FsOptions::WRITEBACK_CACHE)
422 }
423
Victor Hsieh45636232021-10-15 17:52:51 -0700424 fn lookup(&self, _ctx: Context, parent: Inode, name: &CStr) -> io::Result<Entry> {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800425 let mut inode_table = self.inode_table.lock().unwrap();
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800426
Victor Hsieh3dccf702021-12-02 15:45:14 -0800427 // Look up the entry's inode number in parent directory.
428 let inode =
429 handle_inode_locked(&inode_table, &parent, |inode_state| match &inode_state.entry {
430 AuthFsEntry::ReadonlyDirectory { dir } => {
431 let path = cstr_to_path(name);
432 dir.lookup_inode(path).ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))
433 }
434 AuthFsEntry::VerifiedNewDirectory { dir } => {
435 let path = cstr_to_path(name);
Victor Hsiehdd99b462021-12-02 17:36:15 -0800436 dir.find_inode(path)
Victor Hsieh3dccf702021-12-02 15:45:14 -0800437 }
438 _ => Err(io::Error::from_raw_os_error(libc::ENOTDIR)),
439 })?;
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800440
441 // Create the entry's stat if found.
Victor Hsieh3dccf702021-12-02 15:45:14 -0800442 let st = handle_inode_mut_locked(
443 &mut inode_table,
444 &inode,
445 |InodeState { entry, handle_ref_count, .. }| {
446 let st = match entry {
447 AuthFsEntry::ReadonlyDirectory { dir } => {
448 create_dir_stat(inode, dir.number_of_entries())
449 }
450 AuthFsEntry::UnverifiedReadonly { file_size, .. }
451 | AuthFsEntry::VerifiedReadonly { file_size, .. } => {
452 create_stat(inode, *file_size, AccessMode::ReadOnly)
453 }
454 AuthFsEntry::VerifiedNew { editor } => {
455 create_stat(inode, editor.size(), AccessMode::ReadWrite)
456 }
457 AuthFsEntry::VerifiedNewDirectory { dir } => {
458 create_dir_stat(inode, dir.number_of_entries())
459 }
460 }?;
461 *handle_ref_count += 1;
462 Ok(st)
463 },
464 )?;
465
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800466 Ok(Entry {
467 inode,
468 generation: 0,
469 attr: st,
470 entry_timeout: DEFAULT_METADATA_TIMEOUT,
471 attr_timeout: DEFAULT_METADATA_TIMEOUT,
472 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800473 }
474
Victor Hsieh3dccf702021-12-02 15:45:14 -0800475 fn forget(&self, _ctx: Context, inode: Self::Inode, count: u64) {
476 let mut inode_table = self.inode_table.lock().unwrap();
Victor Hsiehdd99b462021-12-02 17:36:15 -0800477 let delete_now = handle_inode_mut_locked(
Victor Hsieh3dccf702021-12-02 15:45:14 -0800478 &mut inode_table,
479 &inode,
Victor Hsiehdd99b462021-12-02 17:36:15 -0800480 |InodeState { handle_ref_count, unlinked, .. }| {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800481 if count > *handle_ref_count {
482 error!(
483 "Trying to decrease refcount of inode {} by {} (> current {})",
484 inode, count, *handle_ref_count
485 );
486 panic!(); // log to logcat with error!
487 }
488 *handle_ref_count = handle_ref_count.saturating_sub(count);
Victor Hsiehdd99b462021-12-02 17:36:15 -0800489 Ok(*unlinked && *handle_ref_count == 0)
Victor Hsieh3dccf702021-12-02 15:45:14 -0800490 },
491 );
Victor Hsiehdd99b462021-12-02 17:36:15 -0800492
493 match delete_now {
494 Ok(true) => {
495 let _ = inode_table.remove(&inode).expect("Removed an existing entry");
496 }
497 Ok(false) => { /* Let the inode stay */ }
498 Err(e) => {
499 warn!(
500 "Unexpected failure when tries to forget an inode {} by refcount {}: {:?}",
501 inode, count, e
502 );
503 }
504 }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800505 }
506
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800507 fn getattr(
508 &self,
509 _ctx: Context,
510 inode: Inode,
511 _handle: Option<Handle>,
512 ) -> io::Result<(libc::stat64, Duration)> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700513 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700514 Ok((
515 match config {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800516 AuthFsEntry::ReadonlyDirectory { dir } => {
517 create_dir_stat(inode, dir.number_of_entries())
518 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700519 AuthFsEntry::UnverifiedReadonly { file_size, .. }
520 | AuthFsEntry::VerifiedReadonly { file_size, .. } => {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800521 create_stat(inode, *file_size, AccessMode::ReadOnly)
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700522 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700523 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800524 create_stat(inode, editor.size(), AccessMode::ReadWrite)
Victor Hsieh45636232021-10-15 17:52:51 -0700525 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700526 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800527 create_dir_stat(inode, dir.number_of_entries())
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700528 }
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800529 }?,
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700530 DEFAULT_METADATA_TIMEOUT,
531 ))
532 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800533 }
534
535 fn open(
536 &self,
537 _ctx: Context,
538 inode: Self::Inode,
539 flags: u32,
540 ) -> io::Result<(Option<Self::Handle>, fuse::sys::OpenOptions)> {
541 // Since file handle is not really used in later operations (which use Inode directly),
Victor Hsieh09e26262021-03-03 16:00:55 -0800542 // return None as the handle.
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700543 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700544 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700545 AuthFsEntry::VerifiedReadonly { .. } | AuthFsEntry::UnverifiedReadonly { .. } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700546 check_access_mode(flags, libc::O_RDONLY)?;
547 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700548 AuthFsEntry::VerifiedNew { .. } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700549 // No need to check access modes since all the modes are allowed to the
550 // read-writable file.
551 }
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800552 AuthFsEntry::ReadonlyDirectory { .. }
553 | AuthFsEntry::VerifiedNewDirectory { .. } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700554 // TODO(victorhsieh): implement when needed.
555 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
556 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800557 }
Victor Hsieh45636232021-10-15 17:52:51 -0700558 // Always cache the file content. There is currently no need to support direct I/O or
559 // avoid the cache buffer. Memory mapping is only possible with cache enabled.
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700560 Ok((None, fuse::sys::OpenOptions::KEEP_CACHE))
561 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800562 }
563
Victor Hsieh45636232021-10-15 17:52:51 -0700564 fn create(
565 &self,
566 _ctx: Context,
567 parent: Self::Inode,
568 name: &CStr,
569 _mode: u32,
570 _flags: u32,
571 _umask: u32,
572 ) -> io::Result<(Entry, Option<Self::Handle>, fuse::sys::OpenOptions)> {
573 // TODO(205169366): Implement mode properly.
574 // TODO(205172873): handle O_TRUNC and O_EXCL properly.
Victor Hsieh3dccf702021-12-02 15:45:14 -0800575 let new_inode = self.create_new_entry_with_ref_count(
576 parent,
577 name,
578 |parent_entry, basename, new_inode| match parent_entry {
579 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800580 if dir.has_entry(basename) {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800581 return Err(io::Error::from_raw_os_error(libc::EEXIST));
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800582 }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800583 let new_file = dir.create_file(basename, new_inode)?;
584 Ok(AuthFsEntry::VerifiedNew { editor: new_file })
Victor Hsieh45636232021-10-15 17:52:51 -0700585 }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800586 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
587 },
588 )?;
Victor Hsieh45636232021-10-15 17:52:51 -0700589
590 Ok((
591 Entry {
592 inode: new_inode,
593 generation: 0,
594 attr: create_stat(new_inode, /* file_size */ 0, AccessMode::ReadWrite)?,
595 entry_timeout: DEFAULT_METADATA_TIMEOUT,
596 attr_timeout: DEFAULT_METADATA_TIMEOUT,
597 },
598 // See also `open`.
599 /* handle */ None,
600 fuse::sys::OpenOptions::KEEP_CACHE,
601 ))
602 }
603
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800604 fn read<W: io::Write + ZeroCopyWriter>(
605 &self,
606 _ctx: Context,
607 inode: Inode,
608 _handle: Handle,
609 w: W,
610 size: u32,
611 offset: u64,
612 _lock_owner: Option<u64>,
613 _flags: u32,
614 ) -> io::Result<usize> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700615 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700616 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700617 AuthFsEntry::VerifiedReadonly { reader, file_size } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700618 read_chunks(w, reader, *file_size, offset, size)
619 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700620 AuthFsEntry::UnverifiedReadonly { reader, file_size } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700621 read_chunks(w, reader, *file_size, offset, size)
622 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700623 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700624 // Note that with FsOptions::WRITEBACK_CACHE, it's possible for the kernel to
625 // request a read even if the file is open with O_WRONLY.
626 read_chunks(w, editor, editor.size(), offset, size)
627 }
Victor Hsieh45636232021-10-15 17:52:51 -0700628 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800629 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700630 })
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800631 }
632
633 fn write<R: io::Read + ZeroCopyReader>(
634 &self,
635 _ctx: Context,
636 inode: Self::Inode,
637 _handle: Self::Handle,
638 mut r: R,
639 size: u32,
640 offset: u64,
641 _lock_owner: Option<u64>,
642 _delayed_write: bool,
643 _flags: u32,
644 ) -> io::Result<usize> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700645 self.handle_inode(&inode, |config| match config {
646 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800647 let mut buf = vec![0; size as usize];
648 r.read_exact(&mut buf)?;
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700649 editor.write_at(&buf, offset)
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800650 }
651 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700652 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800653 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700654
655 fn setattr(
656 &self,
657 _ctx: Context,
658 inode: Inode,
659 attr: libc::stat64,
660 _handle: Option<Handle>,
661 valid: SetattrValid,
662 ) -> io::Result<(libc::stat64, Duration)> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700663 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700664 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700665 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700666 // Initialize the default stat.
Victor Hsieh45636232021-10-15 17:52:51 -0700667 let mut new_attr = create_stat(inode, editor.size(), AccessMode::ReadWrite)?;
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700668 // `valid` indicates what fields in `attr` are valid. Update to return correctly.
669 if valid.contains(SetattrValid::SIZE) {
670 // st_size is i64, but the cast should be safe since kernel should not give a
671 // negative size.
672 debug_assert!(attr.st_size >= 0);
673 new_attr.st_size = attr.st_size;
674 editor.resize(attr.st_size as u64)?;
675 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700676
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700677 if valid.contains(SetattrValid::MODE) {
678 warn!("Changing st_mode is not currently supported");
679 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
680 }
681 if valid.contains(SetattrValid::UID) {
682 warn!("Changing st_uid is not currently supported");
683 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
684 }
685 if valid.contains(SetattrValid::GID) {
686 warn!("Changing st_gid is not currently supported");
687 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
688 }
689 if valid.contains(SetattrValid::CTIME) {
690 debug!(
691 "Ignoring ctime change as authfs does not maintain timestamp currently"
692 );
693 }
694 if valid.intersects(SetattrValid::ATIME | SetattrValid::ATIME_NOW) {
695 debug!(
696 "Ignoring atime change as authfs does not maintain timestamp currently"
697 );
698 }
699 if valid.intersects(SetattrValid::MTIME | SetattrValid::MTIME_NOW) {
700 debug!(
701 "Ignoring mtime change as authfs does not maintain timestamp currently"
702 );
703 }
704 Ok((new_attr, DEFAULT_METADATA_TIMEOUT))
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700705 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700706 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700707 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700708 })
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700709 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700710
711 fn getxattr(
712 &self,
713 _ctx: Context,
714 inode: Self::Inode,
715 name: &CStr,
716 size: u32,
717 ) -> io::Result<GetxattrReply> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700718 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700719 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700720 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700721 // FUSE ioctl is limited, thus we can't implement fs-verity ioctls without a kernel
722 // change (see b/196635431). Until it's possible, use xattr to expose what we need
723 // as an authfs specific API.
724 if name != CStr::from_bytes_with_nul(b"authfs.fsverity.digest\0").unwrap() {
725 return Err(io::Error::from_raw_os_error(libc::ENODATA));
726 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700727
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700728 if size == 0 {
729 // Per protocol, when size is 0, return the value size.
730 Ok(GetxattrReply::Count(editor.get_fsverity_digest_size() as u32))
Victor Hsieh71f10032021-08-13 11:24:02 -0700731 } else {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700732 let digest = editor.calculate_fsverity_digest()?;
733 if digest.len() > size as usize {
734 Err(io::Error::from_raw_os_error(libc::ERANGE))
735 } else {
736 Ok(GetxattrReply::Value(digest.to_vec()))
737 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700738 }
739 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700740 _ => Err(io::Error::from_raw_os_error(libc::ENODATA)),
Victor Hsieh71f10032021-08-13 11:24:02 -0700741 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700742 })
Victor Hsieh71f10032021-08-13 11:24:02 -0700743 }
Victor Hsieh45636232021-10-15 17:52:51 -0700744
745 fn mkdir(
746 &self,
747 _ctx: Context,
748 parent: Self::Inode,
749 name: &CStr,
750 _mode: u32,
751 _umask: u32,
752 ) -> io::Result<Entry> {
753 // TODO(205169366): Implement mode properly.
Victor Hsieh3dccf702021-12-02 15:45:14 -0800754 let new_inode = self.create_new_entry_with_ref_count(
755 parent,
756 name,
757 |parent_entry, basename, new_inode| match parent_entry {
758 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800759 if dir.has_entry(basename) {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800760 return Err(io::Error::from_raw_os_error(libc::EEXIST));
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800761 }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800762 let new_dir = dir.mkdir(basename, new_inode)?;
763 Ok(AuthFsEntry::VerifiedNewDirectory { dir: new_dir })
Victor Hsieh45636232021-10-15 17:52:51 -0700764 }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800765 AuthFsEntry::ReadonlyDirectory { .. } => {
766 Err(io::Error::from_raw_os_error(libc::EACCES))
767 }
768 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
769 },
770 )?;
Victor Hsieh45636232021-10-15 17:52:51 -0700771
772 Ok(Entry {
773 inode: new_inode,
774 generation: 0,
775 attr: create_dir_stat(new_inode, /* file_number */ 0)?,
776 entry_timeout: DEFAULT_METADATA_TIMEOUT,
777 attr_timeout: DEFAULT_METADATA_TIMEOUT,
778 })
779 }
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800780
Victor Hsiehdd99b462021-12-02 17:36:15 -0800781 fn unlink(&self, _ctx: Context, parent: Self::Inode, name: &CStr) -> io::Result<()> {
782 let mut inode_table = self.inode_table.lock().unwrap();
783 handle_inode_mut_locked(
784 &mut inode_table,
785 &parent,
786 |InodeState { entry, unlinked, .. }| match entry {
787 AuthFsEntry::VerifiedNewDirectory { dir } => {
788 let basename: &Path = cstr_to_path(name);
789 // Delete the file from in both the local and remote directories.
790 let _inode = dir.delete_file(basename)?;
791 *unlinked = true;
792 Ok(())
793 }
794 AuthFsEntry::ReadonlyDirectory { .. } => {
795 Err(io::Error::from_raw_os_error(libc::EACCES))
796 }
797 AuthFsEntry::VerifiedNew { .. } => {
798 // Deleting a entry in filesystem root is not currently supported.
799 Err(io::Error::from_raw_os_error(libc::ENOSYS))
800 }
801 AuthFsEntry::UnverifiedReadonly { .. } | AuthFsEntry::VerifiedReadonly { .. } => {
802 Err(io::Error::from_raw_os_error(libc::ENOTDIR))
803 }
804 },
805 )
806 }
807
808 fn rmdir(&self, _ctx: Context, parent: Self::Inode, name: &CStr) -> io::Result<()> {
809 let mut inode_table = self.inode_table.lock().unwrap();
810
811 // Check before actual removal, with readonly borrow.
812 handle_inode_locked(&inode_table, &parent, |inode_state| match &inode_state.entry {
813 AuthFsEntry::VerifiedNewDirectory { dir } => {
814 let basename: &Path = cstr_to_path(name);
815 let existing_inode = dir.find_inode(basename)?;
816 handle_inode_locked(&inode_table, &existing_inode, |inode_state| {
817 inode_state.entry.expect_empty_writable_directory()
818 })
819 }
820 AuthFsEntry::ReadonlyDirectory { .. } => {
821 Err(io::Error::from_raw_os_error(libc::EACCES))
822 }
823 _ => Err(io::Error::from_raw_os_error(libc::ENOTDIR)),
824 })?;
825
826 // Look up again, this time with mutable borrow. This needs to be done separately because
827 // the previous lookup needs to borrow multiple entry references in the table.
828 handle_inode_mut_locked(
829 &mut inode_table,
830 &parent,
831 |InodeState { entry, unlinked, .. }| match entry {
832 AuthFsEntry::VerifiedNewDirectory { dir } => {
833 let basename: &Path = cstr_to_path(name);
834 let _inode = dir.force_delete_directory(basename)?;
835 *unlinked = true;
836 Ok(())
837 }
838 _ => unreachable!("Mismatched entry type that is just checked"),
839 },
840 )
841 }
842
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800843 fn statfs(&self, _ctx: Context, _inode: Self::Inode) -> io::Result<libc::statvfs64> {
844 let remote_stat = self.remote_fs_stats_reader.statfs()?;
845
846 // Safe because we are zero-initializing a struct with only POD fields. Not all fields
847 // matter to FUSE. See also:
848 // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/fuse/inode.c?h=v5.15#n460
849 let mut st: libc::statvfs64 = unsafe { zeroed() };
850
851 // Use the remote stat as a template, since it'd matter the most to consider the writable
852 // files/directories that are written to the remote.
853 st.f_bsize = remote_stat.block_size;
854 st.f_frsize = remote_stat.fragment_size;
855 st.f_blocks = remote_stat.block_numbers;
856 st.f_bavail = remote_stat.block_available;
857 st.f_favail = remote_stat.inodes_available;
858 st.f_namemax = remote_stat.max_filename;
859 // Assuming we are not privileged to use all free spaces on the remote server, set the free
860 // blocks/fragment to the same available amount.
861 st.f_bfree = st.f_bavail;
862 st.f_ffree = st.f_favail;
863 // Number of inodes on the filesystem
864 st.f_files = self.inode_table.lock().unwrap().len() as u64;
865
866 Ok(st)
867 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800868}
869
Victor Hsieh3dccf702021-12-02 15:45:14 -0800870fn handle_inode_locked<F, R>(
871 inode_table: &BTreeMap<Inode, InodeState>,
872 inode: &Inode,
873 handle_fn: F,
874) -> io::Result<R>
875where
876 F: FnOnce(&InodeState) -> io::Result<R>,
877{
878 if let Some(inode_state) = inode_table.get(inode) {
879 handle_fn(inode_state)
880 } else {
881 Err(io::Error::from_raw_os_error(libc::ENOENT))
882 }
883}
884
885fn handle_inode_mut_locked<F, R>(
886 inode_table: &mut BTreeMap<Inode, InodeState>,
887 inode: &Inode,
888 handle_fn: F,
889) -> io::Result<R>
890where
891 F: FnOnce(&mut InodeState) -> io::Result<R>,
892{
893 if let Some(inode_state) = inode_table.get_mut(inode) {
894 handle_fn(inode_state)
895 } else {
896 Err(io::Error::from_raw_os_error(libc::ENOENT))
897 }
898}
899
Victor Hsieh45636232021-10-15 17:52:51 -0700900fn cstr_to_path(cstr: &CStr) -> &Path {
901 OsStr::from_bytes(cstr.to_bytes()).as_ref()
902}