blob: 85a8371af12afe0b038e3e1047f75c4663597fe8 [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 Hsiehf393a722021-12-08 13:04:27 -080040 validate_basename, Attr, InMemoryDir, RandomWrite, ReadByChunk, RemoteDirEditor,
41 RemoteFileEditor, 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 Hsiehf393a722021-12-08 13:04:27 -080069 VerifiedNew { editor: VerifiedFileEditor<RemoteFileEditor>, attr: Attr },
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.
Victor Hsiehf393a722021-12-08 13:04:27 -080072 VerifiedNewDirectory { dir: RemoteDirEditor, attr: Attr },
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080073}
74
Victor Hsiehdd99b462021-12-02 17:36:15 -080075impl AuthFsEntry {
Victor Hsiehf393a722021-12-08 13:04:27 -080076 fn expect_empty_deletable_directory(&self) -> io::Result<()> {
Victor Hsiehdd99b462021-12-02 17:36:15 -080077 match self {
Victor Hsiehf393a722021-12-08 13:04:27 -080078 AuthFsEntry::VerifiedNewDirectory { dir, .. } => {
Victor Hsiehdd99b462021-12-02 17:36:15 -080079 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,
Victor Hsiehf393a722021-12-08 13:04:27 -0800307 Variable(u32),
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800308}
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 Hsiehf393a722021-12-08 13:04:27 -0800320 AccessMode::ReadOnly => {
321 // Until needed, let's just grant the owner access.
322 libc::S_IFREG | libc::S_IRUSR
323 }
324 AccessMode::Variable(mode) => libc::S_IFREG | mode,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800325 };
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800326 st.st_nlink = 1;
327 st.st_uid = 0;
328 st.st_gid = 0;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800329 st.st_size = libc::off64_t::try_from(file_size)
330 .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?;
331 st.st_blksize = blk_size();
332 // Per man stat(2), st_blocks is "Number of 512B blocks allocated".
333 st.st_blocks = libc::c_longlong::try_from(divide_roundup(file_size, 512))
334 .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?;
335 Ok(st)
336}
337
Victor Hsiehf393a722021-12-08 13:04:27 -0800338fn create_dir_stat(
339 ino: libc::ino_t,
340 file_number: u16,
341 access_mode: AccessMode,
342) -> io::Result<libc::stat64> {
Victor Hsieh45636232021-10-15 17:52:51 -0700343 // SAFETY: stat64 is a plan C struct without pointer.
344 let mut st = unsafe { MaybeUninit::<libc::stat64>::zeroed().assume_init() };
345
346 st.st_ino = ino;
Victor Hsiehf393a722021-12-08 13:04:27 -0800347 st.st_mode = match access_mode {
348 AccessMode::ReadOnly => {
349 // Until needed, let's just grant the owner access and search to group and others.
350 libc::S_IFDIR | libc::S_IXUSR | libc::S_IRUSR | libc::S_IXGRP | libc::S_IXOTH
351 }
352 AccessMode::Variable(mode) => libc::S_IFDIR | mode,
353 };
Victor Hsieh45636232021-10-15 17:52:51 -0700354
355 // 2 extra for . and ..
356 st.st_nlink = file_number
357 .checked_add(2)
358 .ok_or_else(|| io::Error::from_raw_os_error(libc::EOVERFLOW))?
359 .into();
360
361 st.st_uid = 0;
362 st.st_gid = 0;
363 Ok(st)
364}
365
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800366fn offset_to_chunk_index(offset: u64) -> u64 {
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800367 offset / CHUNK_SIZE
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800368}
369
Victor Hsiehd0bb5d32021-03-19 12:48:03 -0700370fn read_chunks<W: io::Write, T: ReadByChunk>(
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800371 mut w: W,
372 file: &T,
373 file_size: u64,
374 offset: u64,
375 size: u32,
376) -> io::Result<usize> {
377 let remaining = file_size.saturating_sub(offset);
378 let size_to_read = std::cmp::min(size as usize, remaining as usize);
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800379 let total = ChunkedSizeIter::new(size_to_read, offset, CHUNK_SIZE as usize).try_fold(
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800380 0,
381 |total, (current_offset, planned_data_size)| {
382 // TODO(victorhsieh): There might be a non-trivial way to avoid this copy. For example,
383 // instead of accepting a buffer, the writer could expose the final destination buffer
384 // for the reader to write to. It might not be generally applicable though, e.g. with
385 // virtio transport, the buffer may not be continuous.
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800386 let mut buf = [0u8; CHUNK_SIZE as usize];
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800387 let read_size = file.read_chunk(offset_to_chunk_index(current_offset), &mut buf)?;
388 if read_size < planned_data_size {
389 return Err(io::Error::from_raw_os_error(libc::ENODATA));
390 }
391
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800392 let begin = (current_offset % CHUNK_SIZE) as usize;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800393 let end = begin + planned_data_size;
394 let s = w.write(&buf[begin..end])?;
395 if s != planned_data_size {
396 return Err(io::Error::from_raw_os_error(libc::EIO));
397 }
398 Ok(total + s)
399 },
400 )?;
401
402 Ok(total)
403}
404
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800405// TODO(205715172): Support enumerating directory entries.
406pub struct EmptyDirectoryIterator {}
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800407
408impl DirectoryIterator for EmptyDirectoryIterator {
409 fn next(&mut self) -> Option<DirEntry> {
410 None
411 }
412}
413
414impl FileSystem for AuthFs {
415 type Inode = Inode;
416 type Handle = Handle;
417 type DirIter = EmptyDirectoryIterator;
418
419 fn max_buffer_size(&self) -> u32 {
Victor Hsieh766e5332021-11-09 09:41:25 -0800420 MAX_WRITE_BYTES
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800421 }
422
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800423 fn init(&self, _capable: FsOptions) -> io::Result<FsOptions> {
424 // Enable writeback cache for better performance especially since our bandwidth to the
425 // backend service is limited.
426 Ok(FsOptions::WRITEBACK_CACHE)
427 }
428
Victor Hsieh45636232021-10-15 17:52:51 -0700429 fn lookup(&self, _ctx: Context, parent: Inode, name: &CStr) -> io::Result<Entry> {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800430 let mut inode_table = self.inode_table.lock().unwrap();
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800431
Victor Hsieh3dccf702021-12-02 15:45:14 -0800432 // Look up the entry's inode number in parent directory.
433 let inode =
434 handle_inode_locked(&inode_table, &parent, |inode_state| match &inode_state.entry {
435 AuthFsEntry::ReadonlyDirectory { dir } => {
436 let path = cstr_to_path(name);
437 dir.lookup_inode(path).ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))
438 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800439 AuthFsEntry::VerifiedNewDirectory { dir, .. } => {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800440 let path = cstr_to_path(name);
Victor Hsiehdd99b462021-12-02 17:36:15 -0800441 dir.find_inode(path)
Victor Hsieh3dccf702021-12-02 15:45:14 -0800442 }
443 _ => Err(io::Error::from_raw_os_error(libc::ENOTDIR)),
444 })?;
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800445
446 // Create the entry's stat if found.
Victor Hsieh3dccf702021-12-02 15:45:14 -0800447 let st = handle_inode_mut_locked(
448 &mut inode_table,
449 &inode,
450 |InodeState { entry, handle_ref_count, .. }| {
451 let st = match entry {
452 AuthFsEntry::ReadonlyDirectory { dir } => {
Victor Hsiehf393a722021-12-08 13:04:27 -0800453 create_dir_stat(inode, dir.number_of_entries(), AccessMode::ReadOnly)
Victor Hsieh3dccf702021-12-02 15:45:14 -0800454 }
455 AuthFsEntry::UnverifiedReadonly { file_size, .. }
456 | AuthFsEntry::VerifiedReadonly { file_size, .. } => {
457 create_stat(inode, *file_size, AccessMode::ReadOnly)
458 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800459 AuthFsEntry::VerifiedNew { editor, attr, .. } => {
460 create_stat(inode, editor.size(), AccessMode::Variable(attr.mode()))
Victor Hsieh3dccf702021-12-02 15:45:14 -0800461 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800462 AuthFsEntry::VerifiedNewDirectory { dir, attr } => create_dir_stat(
463 inode,
464 dir.number_of_entries(),
465 AccessMode::Variable(attr.mode()),
466 ),
Victor Hsieh3dccf702021-12-02 15:45:14 -0800467 }?;
468 *handle_ref_count += 1;
469 Ok(st)
470 },
471 )?;
472
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800473 Ok(Entry {
474 inode,
475 generation: 0,
476 attr: st,
477 entry_timeout: DEFAULT_METADATA_TIMEOUT,
478 attr_timeout: DEFAULT_METADATA_TIMEOUT,
479 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800480 }
481
Victor Hsieh3dccf702021-12-02 15:45:14 -0800482 fn forget(&self, _ctx: Context, inode: Self::Inode, count: u64) {
483 let mut inode_table = self.inode_table.lock().unwrap();
Victor Hsiehdd99b462021-12-02 17:36:15 -0800484 let delete_now = handle_inode_mut_locked(
Victor Hsieh3dccf702021-12-02 15:45:14 -0800485 &mut inode_table,
486 &inode,
Victor Hsiehdd99b462021-12-02 17:36:15 -0800487 |InodeState { handle_ref_count, unlinked, .. }| {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800488 if count > *handle_ref_count {
489 error!(
490 "Trying to decrease refcount of inode {} by {} (> current {})",
491 inode, count, *handle_ref_count
492 );
493 panic!(); // log to logcat with error!
494 }
495 *handle_ref_count = handle_ref_count.saturating_sub(count);
Victor Hsiehdd99b462021-12-02 17:36:15 -0800496 Ok(*unlinked && *handle_ref_count == 0)
Victor Hsieh3dccf702021-12-02 15:45:14 -0800497 },
498 );
Victor Hsiehdd99b462021-12-02 17:36:15 -0800499
500 match delete_now {
501 Ok(true) => {
502 let _ = inode_table.remove(&inode).expect("Removed an existing entry");
503 }
504 Ok(false) => { /* Let the inode stay */ }
505 Err(e) => {
506 warn!(
507 "Unexpected failure when tries to forget an inode {} by refcount {}: {:?}",
508 inode, count, e
509 );
510 }
511 }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800512 }
513
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800514 fn getattr(
515 &self,
516 _ctx: Context,
517 inode: Inode,
518 _handle: Option<Handle>,
519 ) -> io::Result<(libc::stat64, Duration)> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700520 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700521 Ok((
522 match config {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800523 AuthFsEntry::ReadonlyDirectory { dir } => {
Victor Hsiehf393a722021-12-08 13:04:27 -0800524 create_dir_stat(inode, dir.number_of_entries(), AccessMode::ReadOnly)
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800525 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700526 AuthFsEntry::UnverifiedReadonly { file_size, .. }
527 | AuthFsEntry::VerifiedReadonly { file_size, .. } => {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800528 create_stat(inode, *file_size, AccessMode::ReadOnly)
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700529 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800530 AuthFsEntry::VerifiedNew { editor, attr, .. } => {
531 create_stat(inode, editor.size(), AccessMode::Variable(attr.mode()))
Victor Hsieh45636232021-10-15 17:52:51 -0700532 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800533 AuthFsEntry::VerifiedNewDirectory { dir, attr } => create_dir_stat(
534 inode,
535 dir.number_of_entries(),
536 AccessMode::Variable(attr.mode()),
537 ),
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800538 }?,
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700539 DEFAULT_METADATA_TIMEOUT,
540 ))
541 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800542 }
543
544 fn open(
545 &self,
546 _ctx: Context,
547 inode: Self::Inode,
548 flags: u32,
549 ) -> io::Result<(Option<Self::Handle>, fuse::sys::OpenOptions)> {
550 // Since file handle is not really used in later operations (which use Inode directly),
Victor Hsieh09e26262021-03-03 16:00:55 -0800551 // return None as the handle.
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700552 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700553 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700554 AuthFsEntry::VerifiedReadonly { .. } | AuthFsEntry::UnverifiedReadonly { .. } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700555 check_access_mode(flags, libc::O_RDONLY)?;
556 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700557 AuthFsEntry::VerifiedNew { .. } => {
Victor Hsiehf393a722021-12-08 13:04:27 -0800558 // TODO(victorhsieh): Imeplement ACL check using the attr and ctx. Always allow
559 // for now.
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700560 }
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800561 AuthFsEntry::ReadonlyDirectory { .. }
562 | AuthFsEntry::VerifiedNewDirectory { .. } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700563 // TODO(victorhsieh): implement when needed.
564 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
565 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800566 }
Victor Hsieh45636232021-10-15 17:52:51 -0700567 // Always cache the file content. There is currently no need to support direct I/O or
568 // avoid the cache buffer. Memory mapping is only possible with cache enabled.
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700569 Ok((None, fuse::sys::OpenOptions::KEEP_CACHE))
570 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800571 }
572
Victor Hsieh45636232021-10-15 17:52:51 -0700573 fn create(
574 &self,
575 _ctx: Context,
576 parent: Self::Inode,
577 name: &CStr,
Victor Hsiehf393a722021-12-08 13:04:27 -0800578 mode: u32,
Victor Hsieh45636232021-10-15 17:52:51 -0700579 _flags: u32,
Victor Hsiehf393a722021-12-08 13:04:27 -0800580 umask: u32,
Victor Hsieh45636232021-10-15 17:52:51 -0700581 ) -> io::Result<(Entry, Option<Self::Handle>, fuse::sys::OpenOptions)> {
Victor Hsieh45636232021-10-15 17:52:51 -0700582 // TODO(205172873): handle O_TRUNC and O_EXCL properly.
Victor Hsieh3dccf702021-12-02 15:45:14 -0800583 let new_inode = self.create_new_entry_with_ref_count(
584 parent,
585 name,
586 |parent_entry, basename, new_inode| match parent_entry {
Victor Hsiehf393a722021-12-08 13:04:27 -0800587 AuthFsEntry::VerifiedNewDirectory { dir, .. } => {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800588 if dir.has_entry(basename) {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800589 return Err(io::Error::from_raw_os_error(libc::EEXIST));
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800590 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800591 let mode = mode & !umask;
592 let (new_file, new_attr) = dir.create_file(basename, new_inode, mode)?;
593 Ok(AuthFsEntry::VerifiedNew { editor: new_file, attr: new_attr })
Victor Hsieh45636232021-10-15 17:52:51 -0700594 }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800595 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
596 },
597 )?;
Victor Hsieh45636232021-10-15 17:52:51 -0700598
599 Ok((
600 Entry {
601 inode: new_inode,
602 generation: 0,
Victor Hsiehf393a722021-12-08 13:04:27 -0800603 attr: create_stat(new_inode, /* file_size */ 0, AccessMode::Variable(mode))?,
Victor Hsieh45636232021-10-15 17:52:51 -0700604 entry_timeout: DEFAULT_METADATA_TIMEOUT,
605 attr_timeout: DEFAULT_METADATA_TIMEOUT,
606 },
607 // See also `open`.
608 /* handle */ None,
609 fuse::sys::OpenOptions::KEEP_CACHE,
610 ))
611 }
612
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800613 fn read<W: io::Write + ZeroCopyWriter>(
614 &self,
615 _ctx: Context,
616 inode: Inode,
617 _handle: Handle,
618 w: W,
619 size: u32,
620 offset: u64,
621 _lock_owner: Option<u64>,
622 _flags: u32,
623 ) -> io::Result<usize> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700624 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700625 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700626 AuthFsEntry::VerifiedReadonly { reader, file_size } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700627 read_chunks(w, reader, *file_size, offset, size)
628 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700629 AuthFsEntry::UnverifiedReadonly { reader, file_size } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700630 read_chunks(w, reader, *file_size, offset, size)
631 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800632 AuthFsEntry::VerifiedNew { editor, .. } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700633 // Note that with FsOptions::WRITEBACK_CACHE, it's possible for the kernel to
634 // request a read even if the file is open with O_WRONLY.
635 read_chunks(w, editor, editor.size(), offset, size)
636 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800637 AuthFsEntry::ReadonlyDirectory { .. }
638 | AuthFsEntry::VerifiedNewDirectory { .. } => {
639 Err(io::Error::from_raw_os_error(libc::EISDIR))
640 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800641 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700642 })
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800643 }
644
645 fn write<R: io::Read + ZeroCopyReader>(
646 &self,
647 _ctx: Context,
648 inode: Self::Inode,
649 _handle: Self::Handle,
650 mut r: R,
651 size: u32,
652 offset: u64,
653 _lock_owner: Option<u64>,
654 _delayed_write: bool,
655 _flags: u32,
656 ) -> io::Result<usize> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700657 self.handle_inode(&inode, |config| match config {
Victor Hsiehf393a722021-12-08 13:04:27 -0800658 AuthFsEntry::VerifiedNew { editor, .. } => {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800659 let mut buf = vec![0; size as usize];
660 r.read_exact(&mut buf)?;
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700661 editor.write_at(&buf, offset)
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800662 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800663 AuthFsEntry::VerifiedReadonly { .. } | AuthFsEntry::UnverifiedReadonly { .. } => {
664 Err(io::Error::from_raw_os_error(libc::EPERM))
665 }
666 AuthFsEntry::ReadonlyDirectory { .. } | AuthFsEntry::VerifiedNewDirectory { .. } => {
667 Err(io::Error::from_raw_os_error(libc::EISDIR))
668 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700669 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800670 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700671
672 fn setattr(
673 &self,
674 _ctx: Context,
675 inode: Inode,
Victor Hsiehf393a722021-12-08 13:04:27 -0800676 in_attr: libc::stat64,
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700677 _handle: Option<Handle>,
678 valid: SetattrValid,
679 ) -> io::Result<(libc::stat64, Duration)> {
Victor Hsiehf393a722021-12-08 13:04:27 -0800680 let mut inode_table = self.inode_table.lock().unwrap();
681 handle_inode_mut_locked(&mut inode_table, &inode, |InodeState { entry, .. }| match entry {
682 AuthFsEntry::VerifiedNew { editor, attr } => {
683 check_unsupported_setattr_request(valid)?;
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700684
Victor Hsiehf393a722021-12-08 13:04:27 -0800685 // Initialize the default stat.
686 let mut new_attr =
687 create_stat(inode, editor.size(), AccessMode::Variable(attr.mode()))?;
688 // `valid` indicates what fields in `attr` are valid. Update to return correctly.
689 if valid.contains(SetattrValid::SIZE) {
690 // st_size is i64, but the cast should be safe since kernel should not give a
691 // negative size.
692 debug_assert!(in_attr.st_size >= 0);
693 new_attr.st_size = in_attr.st_size;
694 editor.resize(in_attr.st_size as u64)?;
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700695 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800696 if valid.contains(SetattrValid::MODE) {
697 attr.set_mode(in_attr.st_mode)?;
698 new_attr.st_mode = in_attr.st_mode;
699 }
700 Ok((new_attr, DEFAULT_METADATA_TIMEOUT))
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700701 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800702 AuthFsEntry::VerifiedNewDirectory { dir, attr } => {
703 check_unsupported_setattr_request(valid)?;
704 if valid.contains(SetattrValid::SIZE) {
705 return Err(io::Error::from_raw_os_error(libc::EISDIR));
706 }
707
708 // Initialize the default stat.
709 let mut new_attr = create_dir_stat(
710 inode,
711 dir.number_of_entries(),
712 AccessMode::Variable(attr.mode()),
713 )?;
714 if valid.contains(SetattrValid::MODE) {
715 attr.set_mode(in_attr.st_mode)?;
716 new_attr.st_mode = in_attr.st_mode;
717 }
718 Ok((new_attr, DEFAULT_METADATA_TIMEOUT))
719 }
720 _ => Err(io::Error::from_raw_os_error(libc::EPERM)),
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700721 })
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700722 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700723
724 fn getxattr(
725 &self,
726 _ctx: Context,
727 inode: Self::Inode,
728 name: &CStr,
729 size: u32,
730 ) -> io::Result<GetxattrReply> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700731 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700732 match config {
Victor Hsiehf393a722021-12-08 13:04:27 -0800733 AuthFsEntry::VerifiedNew { editor, .. } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700734 // FUSE ioctl is limited, thus we can't implement fs-verity ioctls without a kernel
735 // change (see b/196635431). Until it's possible, use xattr to expose what we need
736 // as an authfs specific API.
737 if name != CStr::from_bytes_with_nul(b"authfs.fsverity.digest\0").unwrap() {
738 return Err(io::Error::from_raw_os_error(libc::ENODATA));
739 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700740
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700741 if size == 0 {
742 // Per protocol, when size is 0, return the value size.
743 Ok(GetxattrReply::Count(editor.get_fsverity_digest_size() as u32))
Victor Hsieh71f10032021-08-13 11:24:02 -0700744 } else {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700745 let digest = editor.calculate_fsverity_digest()?;
746 if digest.len() > size as usize {
747 Err(io::Error::from_raw_os_error(libc::ERANGE))
748 } else {
749 Ok(GetxattrReply::Value(digest.to_vec()))
750 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700751 }
752 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700753 _ => Err(io::Error::from_raw_os_error(libc::ENODATA)),
Victor Hsieh71f10032021-08-13 11:24:02 -0700754 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700755 })
Victor Hsieh71f10032021-08-13 11:24:02 -0700756 }
Victor Hsieh45636232021-10-15 17:52:51 -0700757
758 fn mkdir(
759 &self,
760 _ctx: Context,
761 parent: Self::Inode,
762 name: &CStr,
Victor Hsiehf393a722021-12-08 13:04:27 -0800763 mode: u32,
764 umask: u32,
Victor Hsieh45636232021-10-15 17:52:51 -0700765 ) -> io::Result<Entry> {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800766 let new_inode = self.create_new_entry_with_ref_count(
767 parent,
768 name,
769 |parent_entry, basename, new_inode| match parent_entry {
Victor Hsiehf393a722021-12-08 13:04:27 -0800770 AuthFsEntry::VerifiedNewDirectory { dir, .. } => {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800771 if dir.has_entry(basename) {
Victor Hsieh3dccf702021-12-02 15:45:14 -0800772 return Err(io::Error::from_raw_os_error(libc::EEXIST));
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -0800773 }
Victor Hsiehf393a722021-12-08 13:04:27 -0800774 let mode = mode & !umask;
775 let (new_dir, new_attr) = dir.mkdir(basename, new_inode, mode)?;
776 Ok(AuthFsEntry::VerifiedNewDirectory { dir: new_dir, attr: new_attr })
Victor Hsieh45636232021-10-15 17:52:51 -0700777 }
Victor Hsieh3dccf702021-12-02 15:45:14 -0800778 AuthFsEntry::ReadonlyDirectory { .. } => {
779 Err(io::Error::from_raw_os_error(libc::EACCES))
780 }
781 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
782 },
783 )?;
Victor Hsieh45636232021-10-15 17:52:51 -0700784
785 Ok(Entry {
786 inode: new_inode,
787 generation: 0,
Victor Hsiehf393a722021-12-08 13:04:27 -0800788 attr: create_dir_stat(new_inode, /* file_number */ 0, AccessMode::Variable(mode))?,
Victor Hsieh45636232021-10-15 17:52:51 -0700789 entry_timeout: DEFAULT_METADATA_TIMEOUT,
790 attr_timeout: DEFAULT_METADATA_TIMEOUT,
791 })
792 }
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800793
Victor Hsiehdd99b462021-12-02 17:36:15 -0800794 fn unlink(&self, _ctx: Context, parent: Self::Inode, name: &CStr) -> io::Result<()> {
795 let mut inode_table = self.inode_table.lock().unwrap();
796 handle_inode_mut_locked(
797 &mut inode_table,
798 &parent,
799 |InodeState { entry, unlinked, .. }| match entry {
Victor Hsiehf393a722021-12-08 13:04:27 -0800800 AuthFsEntry::VerifiedNewDirectory { dir, .. } => {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800801 let basename: &Path = cstr_to_path(name);
802 // Delete the file from in both the local and remote directories.
803 let _inode = dir.delete_file(basename)?;
804 *unlinked = true;
805 Ok(())
806 }
807 AuthFsEntry::ReadonlyDirectory { .. } => {
808 Err(io::Error::from_raw_os_error(libc::EACCES))
809 }
810 AuthFsEntry::VerifiedNew { .. } => {
811 // Deleting a entry in filesystem root is not currently supported.
812 Err(io::Error::from_raw_os_error(libc::ENOSYS))
813 }
814 AuthFsEntry::UnverifiedReadonly { .. } | AuthFsEntry::VerifiedReadonly { .. } => {
815 Err(io::Error::from_raw_os_error(libc::ENOTDIR))
816 }
817 },
818 )
819 }
820
821 fn rmdir(&self, _ctx: Context, parent: Self::Inode, name: &CStr) -> io::Result<()> {
822 let mut inode_table = self.inode_table.lock().unwrap();
823
824 // Check before actual removal, with readonly borrow.
825 handle_inode_locked(&inode_table, &parent, |inode_state| match &inode_state.entry {
Victor Hsiehf393a722021-12-08 13:04:27 -0800826 AuthFsEntry::VerifiedNewDirectory { dir, .. } => {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800827 let basename: &Path = cstr_to_path(name);
828 let existing_inode = dir.find_inode(basename)?;
829 handle_inode_locked(&inode_table, &existing_inode, |inode_state| {
Victor Hsiehf393a722021-12-08 13:04:27 -0800830 inode_state.entry.expect_empty_deletable_directory()
Victor Hsiehdd99b462021-12-02 17:36:15 -0800831 })
832 }
833 AuthFsEntry::ReadonlyDirectory { .. } => {
834 Err(io::Error::from_raw_os_error(libc::EACCES))
835 }
836 _ => Err(io::Error::from_raw_os_error(libc::ENOTDIR)),
837 })?;
838
839 // Look up again, this time with mutable borrow. This needs to be done separately because
840 // the previous lookup needs to borrow multiple entry references in the table.
841 handle_inode_mut_locked(
842 &mut inode_table,
843 &parent,
844 |InodeState { entry, unlinked, .. }| match entry {
Victor Hsiehf393a722021-12-08 13:04:27 -0800845 AuthFsEntry::VerifiedNewDirectory { dir, .. } => {
Victor Hsiehdd99b462021-12-02 17:36:15 -0800846 let basename: &Path = cstr_to_path(name);
847 let _inode = dir.force_delete_directory(basename)?;
848 *unlinked = true;
849 Ok(())
850 }
851 _ => unreachable!("Mismatched entry type that is just checked"),
852 },
853 )
854 }
855
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800856 fn statfs(&self, _ctx: Context, _inode: Self::Inode) -> io::Result<libc::statvfs64> {
857 let remote_stat = self.remote_fs_stats_reader.statfs()?;
858
859 // Safe because we are zero-initializing a struct with only POD fields. Not all fields
860 // matter to FUSE. See also:
861 // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/fuse/inode.c?h=v5.15#n460
862 let mut st: libc::statvfs64 = unsafe { zeroed() };
863
864 // Use the remote stat as a template, since it'd matter the most to consider the writable
865 // files/directories that are written to the remote.
866 st.f_bsize = remote_stat.block_size;
867 st.f_frsize = remote_stat.fragment_size;
868 st.f_blocks = remote_stat.block_numbers;
869 st.f_bavail = remote_stat.block_available;
870 st.f_favail = remote_stat.inodes_available;
871 st.f_namemax = remote_stat.max_filename;
872 // Assuming we are not privileged to use all free spaces on the remote server, set the free
873 // blocks/fragment to the same available amount.
874 st.f_bfree = st.f_bavail;
875 st.f_ffree = st.f_favail;
876 // Number of inodes on the filesystem
877 st.f_files = self.inode_table.lock().unwrap().len() as u64;
878
879 Ok(st)
880 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800881}
882
Victor Hsieh3dccf702021-12-02 15:45:14 -0800883fn handle_inode_locked<F, R>(
884 inode_table: &BTreeMap<Inode, InodeState>,
885 inode: &Inode,
886 handle_fn: F,
887) -> io::Result<R>
888where
889 F: FnOnce(&InodeState) -> io::Result<R>,
890{
891 if let Some(inode_state) = inode_table.get(inode) {
892 handle_fn(inode_state)
893 } else {
894 Err(io::Error::from_raw_os_error(libc::ENOENT))
895 }
896}
897
898fn handle_inode_mut_locked<F, R>(
899 inode_table: &mut BTreeMap<Inode, InodeState>,
900 inode: &Inode,
901 handle_fn: F,
902) -> io::Result<R>
903where
904 F: FnOnce(&mut InodeState) -> io::Result<R>,
905{
906 if let Some(inode_state) = inode_table.get_mut(inode) {
907 handle_fn(inode_state)
908 } else {
909 Err(io::Error::from_raw_os_error(libc::ENOENT))
910 }
911}
912
Victor Hsiehf393a722021-12-08 13:04:27 -0800913fn check_unsupported_setattr_request(valid: SetattrValid) -> io::Result<()> {
914 if valid.contains(SetattrValid::UID) {
915 warn!("Changing st_uid is not currently supported");
916 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
917 }
918 if valid.contains(SetattrValid::GID) {
919 warn!("Changing st_gid is not currently supported");
920 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
921 }
922 if valid.intersects(
923 SetattrValid::CTIME
924 | SetattrValid::ATIME
925 | SetattrValid::ATIME_NOW
926 | SetattrValid::MTIME
927 | SetattrValid::MTIME_NOW,
928 ) {
929 debug!("Ignoring ctime/atime/mtime change as authfs does not maintain timestamp currently");
930 }
931 Ok(())
932}
933
Victor Hsieh45636232021-10-15 17:52:51 -0700934fn cstr_to_path(cstr: &CStr) -> &Path {
935 OsStr::from_bytes(cstr.to_bytes()).as_ref()
936}