Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | use anyhow::Result; |
| 18 | use std::collections::BTreeMap; |
| 19 | use std::convert::TryFrom; |
| 20 | use std::ffi::CStr; |
| 21 | use std::fs::OpenOptions; |
| 22 | use std::io; |
| 23 | use std::mem::MaybeUninit; |
| 24 | use std::option::Option; |
| 25 | use std::os::unix::io::AsRawFd; |
| 26 | use std::path::Path; |
| 27 | use std::time::Duration; |
| 28 | |
| 29 | use fuse::filesystem::{Context, DirEntry, DirectoryIterator, Entry, FileSystem, ZeroCopyWriter}; |
| 30 | use fuse::mount::MountOption; |
| 31 | |
Victor Hsieh | da3fbc4 | 2021-02-23 16:12:49 -0800 | [diff] [blame^] | 32 | use crate::common::{divide_roundup, CHUNK_SIZE}; |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 33 | use crate::fsverity::FsverityChunkedFileReader; |
| 34 | use crate::reader::{ChunkedFileReader, ReadOnlyDataByChunk}; |
Victor Hsieh | f01f323 | 2020-12-11 13:31:31 -0800 | [diff] [blame] | 35 | use crate::remote_file::{RemoteChunkedFileReader, RemoteFsverityMerkleTreeReader}; |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 36 | |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 37 | const DEFAULT_METADATA_TIMEOUT: std::time::Duration = Duration::from_secs(5); |
| 38 | |
| 39 | pub type Inode = u64; |
| 40 | type Handle = u64; |
| 41 | |
Victor Hsieh | f01f323 | 2020-12-11 13:31:31 -0800 | [diff] [blame] | 42 | type RemoteFsverityChunkedFileReader = |
| 43 | FsverityChunkedFileReader<RemoteChunkedFileReader, RemoteFsverityMerkleTreeReader>; |
| 44 | |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 45 | // A debug only type where everything are stored as local files. |
| 46 | type FileBackedFsverityChunkedFileReader = |
| 47 | FsverityChunkedFileReader<ChunkedFileReader, ChunkedFileReader>; |
| 48 | |
| 49 | pub enum FileConfig { |
| 50 | LocalVerifiedFile(FileBackedFsverityChunkedFileReader, u64), |
| 51 | LocalUnverifiedFile(ChunkedFileReader, u64), |
Victor Hsieh | f01f323 | 2020-12-11 13:31:31 -0800 | [diff] [blame] | 52 | RemoteVerifiedFile(RemoteFsverityChunkedFileReader, u64), |
| 53 | RemoteUnverifiedFile(RemoteChunkedFileReader, u64), |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 54 | } |
| 55 | |
| 56 | struct AuthFs { |
| 57 | /// Store `FileConfig`s using the `Inode` number as the search index. |
| 58 | /// |
| 59 | /// For further optimization to minimize the search cost, since Inode is integer, we may |
| 60 | /// consider storing them in a Vec if we can guarantee that the numbers are small and |
| 61 | /// consecutive. |
| 62 | file_pool: BTreeMap<Inode, FileConfig>, |
| 63 | |
| 64 | /// Maximum bytes in the write transaction to the FUSE device. This limits the maximum size to |
| 65 | /// a read request (including FUSE protocol overhead). |
| 66 | max_write: u32, |
| 67 | } |
| 68 | |
| 69 | impl AuthFs { |
| 70 | pub fn new(file_pool: BTreeMap<Inode, FileConfig>, max_write: u32) -> AuthFs { |
| 71 | AuthFs { file_pool, max_write } |
| 72 | } |
| 73 | |
| 74 | fn get_file_config(&self, inode: &Inode) -> io::Result<&FileConfig> { |
| 75 | self.file_pool.get(&inode).ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT)) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | fn check_access_mode(flags: u32, mode: libc::c_int) -> io::Result<()> { |
| 80 | if (flags & libc::O_ACCMODE as u32) == mode as u32 { |
| 81 | Ok(()) |
| 82 | } else { |
| 83 | Err(io::Error::from_raw_os_error(libc::EACCES)) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | cfg_if::cfg_if! { |
| 88 | if #[cfg(all(target_arch = "aarch64", target_pointer_width = "64"))] { |
Victor Hsieh | da3fbc4 | 2021-02-23 16:12:49 -0800 | [diff] [blame^] | 89 | fn blk_size() -> libc::c_int { CHUNK_SIZE as libc::c_int } |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 90 | } else { |
Victor Hsieh | da3fbc4 | 2021-02-23 16:12:49 -0800 | [diff] [blame^] | 91 | fn blk_size() -> libc::c_long { CHUNK_SIZE as libc::c_long } |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 92 | } |
| 93 | } |
| 94 | |
| 95 | fn create_stat(ino: libc::ino_t, file_size: u64) -> io::Result<libc::stat64> { |
| 96 | let mut st = unsafe { MaybeUninit::<libc::stat64>::zeroed().assume_init() }; |
| 97 | |
| 98 | st.st_ino = ino; |
| 99 | st.st_mode = libc::S_IFREG | libc::S_IRUSR | libc::S_IRGRP | libc::S_IROTH; |
| 100 | st.st_dev = 0; |
| 101 | st.st_nlink = 1; |
| 102 | st.st_uid = 0; |
| 103 | st.st_gid = 0; |
| 104 | st.st_rdev = 0; |
| 105 | st.st_size = libc::off64_t::try_from(file_size) |
| 106 | .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?; |
| 107 | st.st_blksize = blk_size(); |
| 108 | // Per man stat(2), st_blocks is "Number of 512B blocks allocated". |
| 109 | st.st_blocks = libc::c_longlong::try_from(divide_roundup(file_size, 512)) |
| 110 | .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?; |
| 111 | Ok(st) |
| 112 | } |
| 113 | |
| 114 | /// An iterator that generates (offset, size) for a chunked read operation, where offset is the |
| 115 | /// global file offset, and size is the amount of read from the offset. |
| 116 | struct ChunkReadIter { |
| 117 | remaining: usize, |
| 118 | offset: u64, |
| 119 | } |
| 120 | |
| 121 | impl ChunkReadIter { |
| 122 | pub fn new(remaining: usize, offset: u64) -> Self { |
| 123 | ChunkReadIter { remaining, offset } |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | impl Iterator for ChunkReadIter { |
| 128 | type Item = (u64, usize); |
| 129 | |
| 130 | fn next(&mut self) -> Option<Self::Item> { |
| 131 | if self.remaining == 0 { |
| 132 | return None; |
| 133 | } |
| 134 | let chunk_data_size = |
Victor Hsieh | da3fbc4 | 2021-02-23 16:12:49 -0800 | [diff] [blame^] | 135 | std::cmp::min(self.remaining, (CHUNK_SIZE - self.offset % CHUNK_SIZE) as usize); |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 136 | let retval = (self.offset, chunk_data_size); |
| 137 | self.offset += chunk_data_size as u64; |
| 138 | self.remaining = self.remaining.saturating_sub(chunk_data_size); |
| 139 | Some(retval) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | fn offset_to_chunk_index(offset: u64) -> u64 { |
Victor Hsieh | da3fbc4 | 2021-02-23 16:12:49 -0800 | [diff] [blame^] | 144 | offset / CHUNK_SIZE |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 145 | } |
| 146 | |
| 147 | fn read_chunks<W: io::Write, T: ReadOnlyDataByChunk>( |
| 148 | mut w: W, |
| 149 | file: &T, |
| 150 | file_size: u64, |
| 151 | offset: u64, |
| 152 | size: u32, |
| 153 | ) -> io::Result<usize> { |
| 154 | let remaining = file_size.saturating_sub(offset); |
| 155 | let size_to_read = std::cmp::min(size as usize, remaining as usize); |
| 156 | let total = ChunkReadIter::new(size_to_read, offset).try_fold( |
| 157 | 0, |
| 158 | |total, (current_offset, planned_data_size)| { |
| 159 | // TODO(victorhsieh): There might be a non-trivial way to avoid this copy. For example, |
| 160 | // instead of accepting a buffer, the writer could expose the final destination buffer |
| 161 | // for the reader to write to. It might not be generally applicable though, e.g. with |
| 162 | // virtio transport, the buffer may not be continuous. |
Victor Hsieh | da3fbc4 | 2021-02-23 16:12:49 -0800 | [diff] [blame^] | 163 | let mut buf = [0u8; CHUNK_SIZE as usize]; |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 164 | let read_size = file.read_chunk(offset_to_chunk_index(current_offset), &mut buf)?; |
| 165 | if read_size < planned_data_size { |
| 166 | return Err(io::Error::from_raw_os_error(libc::ENODATA)); |
| 167 | } |
| 168 | |
Victor Hsieh | da3fbc4 | 2021-02-23 16:12:49 -0800 | [diff] [blame^] | 169 | let begin = (current_offset % CHUNK_SIZE) as usize; |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 170 | let end = begin + planned_data_size; |
| 171 | let s = w.write(&buf[begin..end])?; |
| 172 | if s != planned_data_size { |
| 173 | return Err(io::Error::from_raw_os_error(libc::EIO)); |
| 174 | } |
| 175 | Ok(total + s) |
| 176 | }, |
| 177 | )?; |
| 178 | |
| 179 | Ok(total) |
| 180 | } |
| 181 | |
| 182 | // No need to support enumerating directory entries. |
| 183 | struct EmptyDirectoryIterator {} |
| 184 | |
| 185 | impl DirectoryIterator for EmptyDirectoryIterator { |
| 186 | fn next(&mut self) -> Option<DirEntry> { |
| 187 | None |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | impl FileSystem for AuthFs { |
| 192 | type Inode = Inode; |
| 193 | type Handle = Handle; |
| 194 | type DirIter = EmptyDirectoryIterator; |
| 195 | |
| 196 | fn max_buffer_size(&self) -> u32 { |
| 197 | self.max_write |
| 198 | } |
| 199 | |
| 200 | fn lookup(&self, _ctx: Context, _parent: Inode, name: &CStr) -> io::Result<Entry> { |
| 201 | // Only accept file name that looks like an integrer. Files in the pool are simply exposed |
| 202 | // by their inode number. Also, there is currently no directory structure. |
| 203 | let num = name.to_str().map_err(|_| io::Error::from_raw_os_error(libc::EINVAL))?; |
| 204 | // Normally, `lookup` is required to increase a reference count for the inode (while |
| 205 | // `forget` will decrease it). It is not necessary here since the files are configured to |
| 206 | // be static. |
| 207 | let inode = num.parse::<Inode>().map_err(|_| io::Error::from_raw_os_error(libc::ENOENT))?; |
| 208 | let st = match self.get_file_config(&inode)? { |
| 209 | FileConfig::LocalVerifiedFile(_, file_size) |
Victor Hsieh | f01f323 | 2020-12-11 13:31:31 -0800 | [diff] [blame] | 210 | | FileConfig::LocalUnverifiedFile(_, file_size) |
| 211 | | FileConfig::RemoteUnverifiedFile(_, file_size) |
| 212 | | FileConfig::RemoteVerifiedFile(_, file_size) => create_stat(inode, *file_size)?, |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 213 | }; |
| 214 | Ok(Entry { |
| 215 | inode, |
| 216 | generation: 0, |
| 217 | attr: st, |
| 218 | entry_timeout: DEFAULT_METADATA_TIMEOUT, |
| 219 | attr_timeout: DEFAULT_METADATA_TIMEOUT, |
| 220 | }) |
| 221 | } |
| 222 | |
| 223 | fn getattr( |
| 224 | &self, |
| 225 | _ctx: Context, |
| 226 | inode: Inode, |
| 227 | _handle: Option<Handle>, |
| 228 | ) -> io::Result<(libc::stat64, Duration)> { |
| 229 | Ok(( |
| 230 | match self.get_file_config(&inode)? { |
| 231 | FileConfig::LocalVerifiedFile(_, file_size) |
Victor Hsieh | f01f323 | 2020-12-11 13:31:31 -0800 | [diff] [blame] | 232 | | FileConfig::LocalUnverifiedFile(_, file_size) |
| 233 | | FileConfig::RemoteUnverifiedFile(_, file_size) |
| 234 | | FileConfig::RemoteVerifiedFile(_, file_size) => create_stat(inode, *file_size)?, |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 235 | }, |
| 236 | DEFAULT_METADATA_TIMEOUT, |
| 237 | )) |
| 238 | } |
| 239 | |
| 240 | fn open( |
| 241 | &self, |
| 242 | _ctx: Context, |
| 243 | inode: Self::Inode, |
| 244 | flags: u32, |
| 245 | ) -> io::Result<(Option<Self::Handle>, fuse::sys::OpenOptions)> { |
| 246 | // Since file handle is not really used in later operations (which use Inode directly), |
| 247 | // return None as the handle.. |
| 248 | match self.get_file_config(&inode)? { |
Victor Hsieh | f01f323 | 2020-12-11 13:31:31 -0800 | [diff] [blame] | 249 | FileConfig::LocalVerifiedFile(_, _) | FileConfig::RemoteVerifiedFile(_, _) => { |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 250 | check_access_mode(flags, libc::O_RDONLY)?; |
| 251 | // Once verified, and only if verified, the file content can be cached. This is not |
| 252 | // really needed for a local file, but is the behavior of RemoteVerifiedFile later. |
| 253 | Ok((None, fuse::sys::OpenOptions::KEEP_CACHE)) |
| 254 | } |
Victor Hsieh | f01f323 | 2020-12-11 13:31:31 -0800 | [diff] [blame] | 255 | FileConfig::LocalUnverifiedFile(_, _) | FileConfig::RemoteUnverifiedFile(_, _) => { |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 256 | check_access_mode(flags, libc::O_RDONLY)?; |
| 257 | // Do not cache the content. This type of file is supposed to be verified using |
| 258 | // dm-verity. The filesystem mount over dm-verity already is already cached, so use |
| 259 | // direct I/O here to avoid double cache. |
| 260 | Ok((None, fuse::sys::OpenOptions::DIRECT_IO)) |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | fn read<W: io::Write + ZeroCopyWriter>( |
| 266 | &self, |
| 267 | _ctx: Context, |
| 268 | inode: Inode, |
| 269 | _handle: Handle, |
| 270 | w: W, |
| 271 | size: u32, |
| 272 | offset: u64, |
| 273 | _lock_owner: Option<u64>, |
| 274 | _flags: u32, |
| 275 | ) -> io::Result<usize> { |
| 276 | match self.get_file_config(&inode)? { |
| 277 | FileConfig::LocalVerifiedFile(file, file_size) => { |
| 278 | read_chunks(w, file, *file_size, offset, size) |
| 279 | } |
| 280 | FileConfig::LocalUnverifiedFile(file, file_size) => { |
| 281 | read_chunks(w, file, *file_size, offset, size) |
| 282 | } |
Victor Hsieh | f01f323 | 2020-12-11 13:31:31 -0800 | [diff] [blame] | 283 | FileConfig::RemoteVerifiedFile(file, file_size) => { |
| 284 | read_chunks(w, file, *file_size, offset, size) |
| 285 | } |
| 286 | FileConfig::RemoteUnverifiedFile(file, file_size) => { |
| 287 | read_chunks(w, file, *file_size, offset, size) |
| 288 | } |
Victor Hsieh | 88ac6ca | 2020-11-13 15:20:24 -0800 | [diff] [blame] | 289 | } |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | /// Mount and start the FUSE instance. This requires CAP_SYS_ADMIN. |
| 294 | pub fn loop_forever( |
| 295 | file_pool: BTreeMap<Inode, FileConfig>, |
| 296 | mountpoint: &Path, |
| 297 | ) -> Result<(), fuse::Error> { |
| 298 | let max_read: u32 = 65536; |
| 299 | let max_write: u32 = 65536; |
| 300 | let dev_fuse = OpenOptions::new() |
| 301 | .read(true) |
| 302 | .write(true) |
| 303 | .open("/dev/fuse") |
| 304 | .expect("Failed to open /dev/fuse"); |
| 305 | |
| 306 | fuse::mount( |
| 307 | mountpoint, |
| 308 | "authfs", |
| 309 | libc::MS_NOSUID | libc::MS_NODEV, |
| 310 | &[ |
| 311 | MountOption::FD(dev_fuse.as_raw_fd()), |
| 312 | MountOption::RootMode(libc::S_IFDIR | libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH), |
| 313 | MountOption::AllowOther, |
| 314 | MountOption::UserId(0), |
| 315 | MountOption::GroupId(0), |
| 316 | MountOption::MaxRead(max_read), |
| 317 | ], |
| 318 | ) |
| 319 | .expect("Failed to mount fuse"); |
| 320 | |
| 321 | fuse::worker::start_message_loop( |
| 322 | dev_fuse, |
| 323 | max_write, |
| 324 | max_read, |
| 325 | AuthFs::new(file_pool, max_write), |
| 326 | ) |
| 327 | } |
| 328 | |
| 329 | #[cfg(test)] |
| 330 | mod tests { |
| 331 | use super::*; |
| 332 | |
| 333 | fn collect_chunk_read_iter(remaining: usize, offset: u64) -> Vec<(u64, usize)> { |
| 334 | ChunkReadIter::new(remaining, offset).collect::<Vec<_>>() |
| 335 | } |
| 336 | |
| 337 | #[test] |
| 338 | fn test_chunk_read_iter() { |
| 339 | assert_eq!(collect_chunk_read_iter(4096, 0), [(0, 4096)]); |
| 340 | assert_eq!(collect_chunk_read_iter(8192, 0), [(0, 4096), (4096, 4096)]); |
| 341 | assert_eq!(collect_chunk_read_iter(8192, 4096), [(4096, 4096), (8192, 4096)]); |
| 342 | |
| 343 | assert_eq!( |
| 344 | collect_chunk_read_iter(16384, 1), |
| 345 | [(1, 4095), (4096, 4096), (8192, 4096), (12288, 4096), (16384, 1)] |
| 346 | ); |
| 347 | |
| 348 | assert_eq!(collect_chunk_read_iter(0, 0), []); |
| 349 | assert_eq!(collect_chunk_read_iter(0, 100), []); |
| 350 | } |
| 351 | } |