blob: 64ccc4196b401e48fa5784b2291573917a04592e [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
17use anyhow::Result;
Victor Hsieh45636232021-10-15 17:52:51 -070018use log::{debug, error, warn};
Victor Hsieh60c2f412021-11-03 13:02:19 -070019use std::collections::{btree_map, BTreeMap, HashMap};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080020use std::convert::TryFrom;
Victor Hsieh45636232021-10-15 17:52:51 -070021use std::ffi::{CStr, OsStr};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080022use std::fs::OpenOptions;
23use std::io;
24use std::mem::MaybeUninit;
25use std::option::Option;
Victor Hsieh45636232021-10-15 17:52:51 -070026use std::os::unix::{ffi::OsStrExt, io::AsRawFd};
Victor Hsieh60c2f412021-11-03 13:02:19 -070027use std::path::{Path, PathBuf};
28use std::sync::Mutex;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080029use std::time::Duration;
30
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080031use fuse::filesystem::{
Victor Hsieh71f10032021-08-13 11:24:02 -070032 Context, DirEntry, DirectoryIterator, Entry, FileSystem, FsOptions, GetxattrReply,
33 SetattrValid, ZeroCopyReader, ZeroCopyWriter,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080034};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080035use fuse::mount::MountOption;
36
Victor Hsiehac4f3f42021-02-26 12:35:58 -080037use crate::common::{divide_roundup, ChunkedSizeIter, CHUNK_SIZE};
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080038use crate::file::{
Victor Hsieh45636232021-10-15 17:52:51 -070039 RandomWrite, ReadByChunk, RemoteDirEditor, RemoteFileEditor, RemoteFileReader,
40 RemoteMerkleTreeReader,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080041};
42use crate::fsverity::{VerifiedFileEditor, VerifiedFileReader};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080043
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080044pub type Inode = u64;
45type Handle = u64;
46
Victor Hsieh26cea2f2021-11-03 10:28:33 -070047const DEFAULT_METADATA_TIMEOUT: Duration = Duration::from_secs(5);
48const ROOT_INODE: Inode = 1;
49
50/// `AuthFsEntry` defines the filesystem entry type supported by AuthFS.
51pub enum AuthFsEntry {
Victor Hsieh1bcf4112021-03-19 14:26:57 -070052 /// A file type that is verified against fs-verity signature (thus read-only). The file is
Victor Hsieh1bcf4112021-03-19 14:26:57 -070053 /// served from a remote server.
Victor Hsieh88e50172021-10-15 13:27:13 -070054 VerifiedReadonly {
Victor Hsieh1bcf4112021-03-19 14:26:57 -070055 reader: VerifiedFileReader<RemoteFileReader, RemoteMerkleTreeReader>,
56 file_size: u64,
57 },
58 /// A file type that is a read-only passthrough from a file on a remote serrver.
Victor Hsieh88e50172021-10-15 13:27:13 -070059 UnverifiedReadonly { reader: RemoteFileReader, file_size: u64 },
Victor Hsieh1bcf4112021-03-19 14:26:57 -070060 /// A file type that is initially empty, and the content is stored on a remote server. File
61 /// integrity is guaranteed with private Merkle tree.
Victor Hsieh88e50172021-10-15 13:27:13 -070062 VerifiedNew { editor: VerifiedFileEditor<RemoteFileEditor> },
Victor Hsieh45636232021-10-15 17:52:51 -070063 /// A directory type that is initially empty. One can create new file (`VerifiedNew`) and new
64 /// directory (`VerifiedNewDirectory` itself) with integrity guaranteed within the VM.
65 VerifiedNewDirectory { dir: RemoteDirEditor },
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080066}
67
Victor Hsieh60c2f412021-11-03 13:02:19 -070068// AuthFS needs to be `Sync` to be accepted by fuse::worker::start_message_loop as a `FileSystem`.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080069struct AuthFs {
Victor Hsieh60c2f412021-11-03 13:02:19 -070070 /// Table for `Inode` to `AuthFsEntry` lookup. This needs to be `Sync` to be used in
71 /// `fuse::worker::start_message_loop`.
72 inode_table: Mutex<BTreeMap<Inode, AuthFsEntry>>,
73
74 /// Root directory entry table for path to `Inode` lookup. The root directory content should
75 /// remain constant throughout the filesystem's lifetime.
76 root_entries: HashMap<PathBuf, Inode>,
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080077
Victor Hsieh26cea2f2021-11-03 10:28:33 -070078 /// Maximum bytes in the write transaction to the FUSE device. This limits the maximum buffer
79 /// size in a read request (including FUSE protocol overhead) that the filesystem writes to.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080080 max_write: u32,
81}
82
83impl AuthFs {
Victor Hsieh60c2f412021-11-03 13:02:19 -070084 pub fn new(root_entries_by_path: HashMap<PathBuf, AuthFsEntry>, max_write: u32) -> AuthFs {
85 let mut next_inode = ROOT_INODE + 1;
86 let mut inode_table = BTreeMap::new();
87 let mut root_entries = HashMap::new();
88
89 root_entries_by_path.into_iter().for_each(|(path_buf, entry)| {
90 next_inode += 1;
91 root_entries.insert(path_buf, next_inode);
92 inode_table.insert(next_inode, entry);
93 });
94
95 AuthFs { inode_table: Mutex::new(inode_table), root_entries, max_write }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080096 }
97
Victor Hsieh45636232021-10-15 17:52:51 -070098 /// Handles the file associated with `inode` if found. This function returns whatever
99 /// `handle_fn` returns.
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700100 fn handle_inode<F, R>(&self, inode: &Inode, handle_fn: F) -> io::Result<R>
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700101 where
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700102 F: FnOnce(&AuthFsEntry) -> io::Result<R>,
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700103 {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700104 let inode_table = self.inode_table.lock().unwrap();
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700105 let config =
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700106 inode_table.get(inode).ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))?;
Victor Hsieh45636232021-10-15 17:52:51 -0700107 handle_fn(config)
108 }
109
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700110 /// Inserts a new inode and corresponding `AuthFsEntry` created by `create_fn` to the inode
111 /// table, then returns the new inode number.
Victor Hsieh45636232021-10-15 17:52:51 -0700112 fn insert_new_inode<F>(&self, inode: &Inode, create_fn: F) -> io::Result<Inode>
113 where
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700114 F: FnOnce(&mut AuthFsEntry) -> io::Result<(Inode, AuthFsEntry)>,
Victor Hsieh45636232021-10-15 17:52:51 -0700115 {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700116 let mut inode_table = self.inode_table.lock().unwrap();
Victor Hsieh45636232021-10-15 17:52:51 -0700117 let mut config =
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700118 inode_table.get_mut(inode).ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))?;
Victor Hsieh45636232021-10-15 17:52:51 -0700119 let (new_inode, new_file_config) = create_fn(&mut config)?;
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700120 if let btree_map::Entry::Vacant(entry) = inode_table.entry(new_inode) {
Victor Hsieh45636232021-10-15 17:52:51 -0700121 entry.insert(new_file_config);
122 Ok(new_inode)
123 } else {
124 // We can't assume fd_server is trusted, so the returned FD may collide with existing
125 // one, even when we are creating a new file. Do not override an existing FD. In terms
126 // of security, it is better to "leak" the file created earlier, than returning an
127 // existing inode as a new file.
128 error!("Inode {} already exists, do not override", new_inode);
129 Err(io::Error::from_raw_os_error(libc::EIO))
130 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800131 }
132}
133
134fn check_access_mode(flags: u32, mode: libc::c_int) -> io::Result<()> {
135 if (flags & libc::O_ACCMODE as u32) == mode as u32 {
136 Ok(())
137 } else {
138 Err(io::Error::from_raw_os_error(libc::EACCES))
139 }
140}
141
142cfg_if::cfg_if! {
143 if #[cfg(all(target_arch = "aarch64", target_pointer_width = "64"))] {
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800144 fn blk_size() -> libc::c_int { CHUNK_SIZE as libc::c_int }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800145 } else {
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800146 fn blk_size() -> libc::c_long { CHUNK_SIZE as libc::c_long }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800147 }
148}
149
Victor Hsieh45636232021-10-15 17:52:51 -0700150#[allow(clippy::enum_variant_names)]
151enum AccessMode {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800152 ReadOnly,
153 ReadWrite,
154}
155
Victor Hsieh45636232021-10-15 17:52:51 -0700156fn create_stat(
157 ino: libc::ino_t,
158 file_size: u64,
159 access_mode: AccessMode,
160) -> io::Result<libc::stat64> {
161 // SAFETY: stat64 is a plan C struct without pointer.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800162 let mut st = unsafe { MaybeUninit::<libc::stat64>::zeroed().assume_init() };
163
164 st.st_ino = ino;
Victor Hsieh45636232021-10-15 17:52:51 -0700165 st.st_mode = match access_mode {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800166 // Until needed, let's just grant the owner access.
Victor Hsieh45636232021-10-15 17:52:51 -0700167 // TODO(205169366): Implement mode properly.
168 AccessMode::ReadOnly => libc::S_IFREG | libc::S_IRUSR,
169 AccessMode::ReadWrite => libc::S_IFREG | libc::S_IRUSR | libc::S_IWUSR,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800170 };
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800171 st.st_nlink = 1;
172 st.st_uid = 0;
173 st.st_gid = 0;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800174 st.st_size = libc::off64_t::try_from(file_size)
175 .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?;
176 st.st_blksize = blk_size();
177 // Per man stat(2), st_blocks is "Number of 512B blocks allocated".
178 st.st_blocks = libc::c_longlong::try_from(divide_roundup(file_size, 512))
179 .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?;
180 Ok(st)
181}
182
Victor Hsieh45636232021-10-15 17:52:51 -0700183fn create_dir_stat(ino: libc::ino_t, file_number: u16) -> io::Result<libc::stat64> {
184 // SAFETY: stat64 is a plan C struct without pointer.
185 let mut st = unsafe { MaybeUninit::<libc::stat64>::zeroed().assume_init() };
186
187 st.st_ino = ino;
188 // TODO(205169366): Implement mode properly.
189 st.st_mode = libc::S_IFDIR
190 | libc::S_IXUSR
191 | libc::S_IWUSR
192 | libc::S_IRUSR
193 | libc::S_IXGRP
194 | libc::S_IXOTH;
195
196 // 2 extra for . and ..
197 st.st_nlink = file_number
198 .checked_add(2)
199 .ok_or_else(|| io::Error::from_raw_os_error(libc::EOVERFLOW))?
200 .into();
201
202 st.st_uid = 0;
203 st.st_gid = 0;
204 Ok(st)
205}
206
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800207fn offset_to_chunk_index(offset: u64) -> u64 {
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800208 offset / CHUNK_SIZE
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800209}
210
Victor Hsiehd0bb5d32021-03-19 12:48:03 -0700211fn read_chunks<W: io::Write, T: ReadByChunk>(
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800212 mut w: W,
213 file: &T,
214 file_size: u64,
215 offset: u64,
216 size: u32,
217) -> io::Result<usize> {
218 let remaining = file_size.saturating_sub(offset);
219 let size_to_read = std::cmp::min(size as usize, remaining as usize);
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800220 let total = ChunkedSizeIter::new(size_to_read, offset, CHUNK_SIZE as usize).try_fold(
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800221 0,
222 |total, (current_offset, planned_data_size)| {
223 // TODO(victorhsieh): There might be a non-trivial way to avoid this copy. For example,
224 // instead of accepting a buffer, the writer could expose the final destination buffer
225 // for the reader to write to. It might not be generally applicable though, e.g. with
226 // virtio transport, the buffer may not be continuous.
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800227 let mut buf = [0u8; CHUNK_SIZE as usize];
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800228 let read_size = file.read_chunk(offset_to_chunk_index(current_offset), &mut buf)?;
229 if read_size < planned_data_size {
230 return Err(io::Error::from_raw_os_error(libc::ENODATA));
231 }
232
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800233 let begin = (current_offset % CHUNK_SIZE) as usize;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800234 let end = begin + planned_data_size;
235 let s = w.write(&buf[begin..end])?;
236 if s != planned_data_size {
237 return Err(io::Error::from_raw_os_error(libc::EIO));
238 }
239 Ok(total + s)
240 },
241 )?;
242
243 Ok(total)
244}
245
246// No need to support enumerating directory entries.
247struct EmptyDirectoryIterator {}
248
249impl DirectoryIterator for EmptyDirectoryIterator {
250 fn next(&mut self) -> Option<DirEntry> {
251 None
252 }
253}
254
255impl FileSystem for AuthFs {
256 type Inode = Inode;
257 type Handle = Handle;
258 type DirIter = EmptyDirectoryIterator;
259
260 fn max_buffer_size(&self) -> u32 {
261 self.max_write
262 }
263
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800264 fn init(&self, _capable: FsOptions) -> io::Result<FsOptions> {
265 // Enable writeback cache for better performance especially since our bandwidth to the
266 // backend service is limited.
267 Ok(FsOptions::WRITEBACK_CACHE)
268 }
269
Victor Hsieh45636232021-10-15 17:52:51 -0700270 fn lookup(&self, _ctx: Context, parent: Inode, name: &CStr) -> io::Result<Entry> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700271 if parent == ROOT_INODE {
Victor Hsieh60c2f412021-11-03 13:02:19 -0700272 let inode = *self
273 .root_entries
274 .get(cstr_to_path(name))
275 .ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))?;
Victor Hsieh45636232021-10-15 17:52:51 -0700276 // Normally, `lookup` is required to increase a reference count for the inode (while
Victor Hsieh60c2f412021-11-03 13:02:19 -0700277 // `forget` will decrease it). It is not yet necessary until we start to support
278 // deletion (only for `VerifiedNewDirectory`).
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700279 let st = self.handle_inode(&inode, |config| match config {
280 AuthFsEntry::UnverifiedReadonly { file_size, .. }
281 | AuthFsEntry::VerifiedReadonly { file_size, .. } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700282 create_stat(inode, *file_size, AccessMode::ReadOnly)
283 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700284 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700285 create_stat(inode, editor.size(), AccessMode::ReadWrite)
286 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700287 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700288 create_dir_stat(inode, dir.number_of_entries())
289 }
290 })?;
291 Ok(Entry {
292 inode,
293 generation: 0,
294 attr: st,
295 entry_timeout: DEFAULT_METADATA_TIMEOUT,
296 attr_timeout: DEFAULT_METADATA_TIMEOUT,
297 })
298 } else {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700299 let inode = self.handle_inode(&parent, |config| match config {
300 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700301 let path: &Path = cstr_to_path(name);
302 dir.find_inode(path).ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))
303 }
304 _ => Err(io::Error::from_raw_os_error(libc::ENOTDIR)),
305 })?;
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700306 let st = self.handle_inode(&inode, |config| match config {
307 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700308 create_stat(inode, editor.size(), AccessMode::ReadWrite)
309 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700310 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700311 create_dir_stat(inode, dir.number_of_entries())
312 }
313 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
314 })?;
315 Ok(Entry {
316 inode,
317 generation: 0,
318 attr: st,
319 entry_timeout: DEFAULT_METADATA_TIMEOUT,
320 attr_timeout: DEFAULT_METADATA_TIMEOUT,
321 })
322 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800323 }
324
325 fn getattr(
326 &self,
327 _ctx: Context,
328 inode: Inode,
329 _handle: Option<Handle>,
330 ) -> io::Result<(libc::stat64, Duration)> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700331 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700332 Ok((
333 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700334 AuthFsEntry::UnverifiedReadonly { file_size, .. }
335 | AuthFsEntry::VerifiedReadonly { file_size, .. } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700336 create_stat(inode, *file_size, AccessMode::ReadOnly)?
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700337 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700338 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700339 create_stat(inode, editor.size(), AccessMode::ReadWrite)?
340 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700341 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700342 create_dir_stat(inode, dir.number_of_entries())?
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700343 }
344 },
345 DEFAULT_METADATA_TIMEOUT,
346 ))
347 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800348 }
349
350 fn open(
351 &self,
352 _ctx: Context,
353 inode: Self::Inode,
354 flags: u32,
355 ) -> io::Result<(Option<Self::Handle>, fuse::sys::OpenOptions)> {
356 // Since file handle is not really used in later operations (which use Inode directly),
Victor Hsieh09e26262021-03-03 16:00:55 -0800357 // return None as the handle.
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700358 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700359 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700360 AuthFsEntry::VerifiedReadonly { .. } | AuthFsEntry::UnverifiedReadonly { .. } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700361 check_access_mode(flags, libc::O_RDONLY)?;
362 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700363 AuthFsEntry::VerifiedNew { .. } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700364 // No need to check access modes since all the modes are allowed to the
365 // read-writable file.
366 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700367 AuthFsEntry::VerifiedNewDirectory { .. } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700368 // TODO(victorhsieh): implement when needed.
369 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
370 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800371 }
Victor Hsieh45636232021-10-15 17:52:51 -0700372 // Always cache the file content. There is currently no need to support direct I/O or
373 // avoid the cache buffer. Memory mapping is only possible with cache enabled.
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700374 Ok((None, fuse::sys::OpenOptions::KEEP_CACHE))
375 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800376 }
377
Victor Hsieh45636232021-10-15 17:52:51 -0700378 fn create(
379 &self,
380 _ctx: Context,
381 parent: Self::Inode,
382 name: &CStr,
383 _mode: u32,
384 _flags: u32,
385 _umask: u32,
386 ) -> io::Result<(Entry, Option<Self::Handle>, fuse::sys::OpenOptions)> {
387 // TODO(205169366): Implement mode properly.
388 // TODO(205172873): handle O_TRUNC and O_EXCL properly.
389 let new_inode = self.insert_new_inode(&parent, |config| match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700390 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700391 let basename: &Path = cstr_to_path(name);
392 if dir.find_inode(basename).is_some() {
393 return Err(io::Error::from_raw_os_error(libc::EEXIST));
394 }
395 let (new_inode, new_file) = dir.create_file(basename)?;
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700396 Ok((new_inode, AuthFsEntry::VerifiedNew { editor: new_file }))
Victor Hsieh45636232021-10-15 17:52:51 -0700397 }
398 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
399 })?;
400
401 Ok((
402 Entry {
403 inode: new_inode,
404 generation: 0,
405 attr: create_stat(new_inode, /* file_size */ 0, AccessMode::ReadWrite)?,
406 entry_timeout: DEFAULT_METADATA_TIMEOUT,
407 attr_timeout: DEFAULT_METADATA_TIMEOUT,
408 },
409 // See also `open`.
410 /* handle */ None,
411 fuse::sys::OpenOptions::KEEP_CACHE,
412 ))
413 }
414
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800415 fn read<W: io::Write + ZeroCopyWriter>(
416 &self,
417 _ctx: Context,
418 inode: Inode,
419 _handle: Handle,
420 w: W,
421 size: u32,
422 offset: u64,
423 _lock_owner: Option<u64>,
424 _flags: u32,
425 ) -> io::Result<usize> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700426 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700427 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700428 AuthFsEntry::VerifiedReadonly { reader, file_size } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700429 read_chunks(w, reader, *file_size, offset, size)
430 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700431 AuthFsEntry::UnverifiedReadonly { reader, file_size } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700432 read_chunks(w, reader, *file_size, offset, size)
433 }
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700434 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700435 // Note that with FsOptions::WRITEBACK_CACHE, it's possible for the kernel to
436 // request a read even if the file is open with O_WRONLY.
437 read_chunks(w, editor, editor.size(), offset, size)
438 }
Victor Hsieh45636232021-10-15 17:52:51 -0700439 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800440 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700441 })
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800442 }
443
444 fn write<R: io::Read + ZeroCopyReader>(
445 &self,
446 _ctx: Context,
447 inode: Self::Inode,
448 _handle: Self::Handle,
449 mut r: R,
450 size: u32,
451 offset: u64,
452 _lock_owner: Option<u64>,
453 _delayed_write: bool,
454 _flags: u32,
455 ) -> io::Result<usize> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700456 self.handle_inode(&inode, |config| match config {
457 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800458 let mut buf = vec![0; size as usize];
459 r.read_exact(&mut buf)?;
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700460 editor.write_at(&buf, offset)
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800461 }
462 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700463 })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800464 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700465
466 fn setattr(
467 &self,
468 _ctx: Context,
469 inode: Inode,
470 attr: libc::stat64,
471 _handle: Option<Handle>,
472 valid: SetattrValid,
473 ) -> io::Result<(libc::stat64, Duration)> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700474 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700475 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700476 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700477 // Initialize the default stat.
Victor Hsieh45636232021-10-15 17:52:51 -0700478 let mut new_attr = create_stat(inode, editor.size(), AccessMode::ReadWrite)?;
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700479 // `valid` indicates what fields in `attr` are valid. Update to return correctly.
480 if valid.contains(SetattrValid::SIZE) {
481 // st_size is i64, but the cast should be safe since kernel should not give a
482 // negative size.
483 debug_assert!(attr.st_size >= 0);
484 new_attr.st_size = attr.st_size;
485 editor.resize(attr.st_size as u64)?;
486 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700487
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700488 if valid.contains(SetattrValid::MODE) {
489 warn!("Changing st_mode is not currently supported");
490 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
491 }
492 if valid.contains(SetattrValid::UID) {
493 warn!("Changing st_uid is not currently supported");
494 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
495 }
496 if valid.contains(SetattrValid::GID) {
497 warn!("Changing st_gid is not currently supported");
498 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
499 }
500 if valid.contains(SetattrValid::CTIME) {
501 debug!(
502 "Ignoring ctime change as authfs does not maintain timestamp currently"
503 );
504 }
505 if valid.intersects(SetattrValid::ATIME | SetattrValid::ATIME_NOW) {
506 debug!(
507 "Ignoring atime change as authfs does not maintain timestamp currently"
508 );
509 }
510 if valid.intersects(SetattrValid::MTIME | SetattrValid::MTIME_NOW) {
511 debug!(
512 "Ignoring mtime change as authfs does not maintain timestamp currently"
513 );
514 }
515 Ok((new_attr, DEFAULT_METADATA_TIMEOUT))
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700516 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700517 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700518 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700519 })
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700520 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700521
522 fn getxattr(
523 &self,
524 _ctx: Context,
525 inode: Self::Inode,
526 name: &CStr,
527 size: u32,
528 ) -> io::Result<GetxattrReply> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700529 self.handle_inode(&inode, |config| {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700530 match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700531 AuthFsEntry::VerifiedNew { editor } => {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700532 // FUSE ioctl is limited, thus we can't implement fs-verity ioctls without a kernel
533 // change (see b/196635431). Until it's possible, use xattr to expose what we need
534 // as an authfs specific API.
535 if name != CStr::from_bytes_with_nul(b"authfs.fsverity.digest\0").unwrap() {
536 return Err(io::Error::from_raw_os_error(libc::ENODATA));
537 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700538
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700539 if size == 0 {
540 // Per protocol, when size is 0, return the value size.
541 Ok(GetxattrReply::Count(editor.get_fsverity_digest_size() as u32))
Victor Hsieh71f10032021-08-13 11:24:02 -0700542 } else {
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700543 let digest = editor.calculate_fsverity_digest()?;
544 if digest.len() > size as usize {
545 Err(io::Error::from_raw_os_error(libc::ERANGE))
546 } else {
547 Ok(GetxattrReply::Value(digest.to_vec()))
548 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700549 }
550 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700551 _ => Err(io::Error::from_raw_os_error(libc::ENODATA)),
Victor Hsieh71f10032021-08-13 11:24:02 -0700552 }
Victor Hsiehc85e4ef2021-10-18 15:28:53 -0700553 })
Victor Hsieh71f10032021-08-13 11:24:02 -0700554 }
Victor Hsieh45636232021-10-15 17:52:51 -0700555
556 fn mkdir(
557 &self,
558 _ctx: Context,
559 parent: Self::Inode,
560 name: &CStr,
561 _mode: u32,
562 _umask: u32,
563 ) -> io::Result<Entry> {
564 // TODO(205169366): Implement mode properly.
565 let new_inode = self.insert_new_inode(&parent, |config| match config {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700566 AuthFsEntry::VerifiedNewDirectory { dir } => {
Victor Hsieh45636232021-10-15 17:52:51 -0700567 let basename: &Path = cstr_to_path(name);
568 if dir.find_inode(basename).is_some() {
569 return Err(io::Error::from_raw_os_error(libc::EEXIST));
570 }
571 let (new_inode, new_dir) = dir.mkdir(basename)?;
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700572 Ok((new_inode, AuthFsEntry::VerifiedNewDirectory { dir: new_dir }))
Victor Hsieh45636232021-10-15 17:52:51 -0700573 }
574 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
575 })?;
576
577 Ok(Entry {
578 inode: new_inode,
579 generation: 0,
580 attr: create_dir_stat(new_inode, /* file_number */ 0)?,
581 entry_timeout: DEFAULT_METADATA_TIMEOUT,
582 attr_timeout: DEFAULT_METADATA_TIMEOUT,
583 })
584 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800585}
586
587/// Mount and start the FUSE instance. This requires CAP_SYS_ADMIN.
588pub fn loop_forever(
Victor Hsieh60c2f412021-11-03 13:02:19 -0700589 root_entries: HashMap<PathBuf, AuthFsEntry>,
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800590 mountpoint: &Path,
Victor Hsieh4cc3b792021-08-04 12:00:04 -0700591 extra_options: &Option<String>,
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800592) -> Result<(), fuse::Error> {
593 let max_read: u32 = 65536;
594 let max_write: u32 = 65536;
595 let dev_fuse = OpenOptions::new()
596 .read(true)
597 .write(true)
598 .open("/dev/fuse")
599 .expect("Failed to open /dev/fuse");
600
Victor Hsieh4cc3b792021-08-04 12:00:04 -0700601 let mut mount_options = vec![
602 MountOption::FD(dev_fuse.as_raw_fd()),
603 MountOption::RootMode(libc::S_IFDIR | libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH),
604 MountOption::AllowOther,
605 MountOption::UserId(0),
606 MountOption::GroupId(0),
607 MountOption::MaxRead(max_read),
608 ];
609 if let Some(value) = extra_options {
610 mount_options.push(MountOption::Extra(value));
611 }
612
613 fuse::mount(mountpoint, "authfs", libc::MS_NOSUID | libc::MS_NODEV, &mount_options)
614 .expect("Failed to mount fuse");
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800615
616 fuse::worker::start_message_loop(
617 dev_fuse,
618 max_write,
619 max_read,
Victor Hsieh60c2f412021-11-03 13:02:19 -0700620 AuthFs::new(root_entries, max_write),
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800621 )
622}
Victor Hsieh45636232021-10-15 17:52:51 -0700623
624fn cstr_to_path(cstr: &CStr) -> &Path {
625 OsStr::from_bytes(cstr.to_bytes()).as_ref()
626}