blob: 2eaaddd08c721920910ffce10ba0aa52a88d2bfe [file] [log] [blame]
Victor Hsieh45636232021-10-15 17:52:51 -07001/*
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 Hsieh4d6b9d42021-11-08 15:53:49 -080017use std::collections::{hash_map, HashMap};
Victor Hsieh45636232021-10-15 17:52:51 -070018use std::io;
19use std::path::{Path, PathBuf};
20
21use super::remote_file::RemoteFileEditor;
Victor Hsieh4d6b9d42021-11-08 15:53:49 -080022use super::{validate_basename, VirtFdService, VirtFdServiceStatus};
Victor Hsieh45636232021-10-15 17:52:51 -070023use crate::fsverity::VerifiedFileEditor;
24use crate::fusefs::Inode;
25
26const MAX_ENTRIES: u16 = 100; // Arbitrary limit
27
28/// A remote directory backed by a remote directory FD, where the provider/fd_server is not
29/// trusted.
30///
31/// The directory is assumed empty initially without the trust to the storage. Functionally, when
32/// the backing storage is not clean, the fd_server can fail to create a file or directory when
33/// there is name collision. From RemoteDirEditor's perspective of security, the creation failure
34/// is just one of possible errors that can happen, and what matters is RemoteDirEditor maintains
35/// the integrity itself.
36///
37/// When new files are created through RemoteDirEditor, the file integrity are maintained within the
38/// VM. Similarly, integrity (namely the list of entries) of the directory, or new directories
39/// created within such a directory, are also maintained within the VM. A compromised fd_server or
40/// malicious client can't affect the view to the files and directories within such a directory in
41/// the VM.
42pub struct RemoteDirEditor {
43 service: VirtFdService,
44 remote_dir_fd: i32,
45
46 /// Mapping of entry names to the corresponding inode number. The actual file/directory is
47 /// stored in the global pool in fusefs.
48 entries: HashMap<PathBuf, Inode>,
49}
50
51impl RemoteDirEditor {
52 pub fn new(service: VirtFdService, remote_dir_fd: i32) -> Self {
53 RemoteDirEditor { service, remote_dir_fd, entries: HashMap::new() }
54 }
55
56 /// Returns the number of entries created.
57 pub fn number_of_entries(&self) -> u16 {
58 self.entries.len() as u16 // limited to MAX_ENTRIES
59 }
60
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -080061 /// Creates a remote file named `basename` with corresponding `inode` at the current directory.
Victor Hsieh45636232021-10-15 17:52:51 -070062 pub fn create_file(
63 &mut self,
64 basename: &Path,
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -080065 inode: Inode,
66 ) -> io::Result<VerifiedFileEditor<RemoteFileEditor>> {
Victor Hsieh45636232021-10-15 17:52:51 -070067 self.validate_argument(basename)?;
68
69 let basename_str =
70 basename.to_str().ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
71 let new_fd = self
72 .service
73 .createFileInDirectory(self.remote_dir_fd, basename_str)
74 .map_err(into_io_error)?;
Victor Hsieh45636232021-10-15 17:52:51 -070075
76 let new_remote_file =
77 VerifiedFileEditor::new(RemoteFileEditor::new(self.service.clone(), new_fd));
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -080078 self.entries.insert(basename.to_path_buf(), inode);
79 Ok(new_remote_file)
Victor Hsieh45636232021-10-15 17:52:51 -070080 }
81
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -080082 /// Creates a remote directory named `basename` with corresponding `inode` at the current
83 /// directory.
84 pub fn mkdir(&mut self, basename: &Path, inode: Inode) -> io::Result<RemoteDirEditor> {
Victor Hsieh45636232021-10-15 17:52:51 -070085 self.validate_argument(basename)?;
86
87 let basename_str =
88 basename.to_str().ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
89 let new_fd = self
90 .service
91 .createDirectoryInDirectory(self.remote_dir_fd, basename_str)
92 .map_err(into_io_error)?;
Victor Hsieh45636232021-10-15 17:52:51 -070093
94 let new_remote_dir = RemoteDirEditor::new(self.service.clone(), new_fd);
Victor Hsiehd5a5b1e2021-11-09 11:42:34 -080095 self.entries.insert(basename.to_path_buf(), inode);
96 Ok(new_remote_dir)
Victor Hsieh45636232021-10-15 17:52:51 -070097 }
98
99 /// Returns the inode number of a file or directory named `name` previously created through
100 /// `RemoteDirEditor`.
101 pub fn find_inode(&self, name: &Path) -> Option<Inode> {
102 self.entries.get(name).copied()
103 }
104
105 fn validate_argument(&self, basename: &Path) -> io::Result<()> {
106 // Kernel should only give us a basename.
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800107 debug_assert!(validate_basename(basename).is_ok());
108
Victor Hsieh45636232021-10-15 17:52:51 -0700109 if self.entries.contains_key(basename) {
110 Err(io::Error::from_raw_os_error(libc::EEXIST))
111 } else if self.entries.len() >= MAX_ENTRIES.into() {
112 Err(io::Error::from_raw_os_error(libc::EMLINK))
113 } else {
114 Ok(())
115 }
116 }
117}
118
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800119/// An in-memory directory representation of a directory structure.
120pub struct InMemoryDir(HashMap<PathBuf, Inode>);
121
122impl InMemoryDir {
123 /// Creates an empty instance of `InMemoryDir`.
124 pub fn new() -> Self {
125 // Hash map is empty since "." and ".." are excluded in entries.
126 InMemoryDir(HashMap::new())
127 }
128
129 /// Returns the number of entries in the directory (not including "." and "..").
130 pub fn number_of_entries(&self) -> u16 {
131 self.0.len() as u16 // limited to MAX_ENTRIES
132 }
133
134 /// Adds an entry (name and the inode number) to the directory. Fails if already exists. The
135 /// caller is responsible for ensure the inode uniqueness.
136 pub fn add_entry(&mut self, basename: &Path, inode: Inode) -> io::Result<()> {
137 validate_basename(basename)?;
138 if self.0.len() >= MAX_ENTRIES.into() {
139 return Err(io::Error::from_raw_os_error(libc::EMLINK));
140 }
141
142 if let hash_map::Entry::Vacant(entry) = self.0.entry(basename.to_path_buf()) {
143 entry.insert(inode);
144 Ok(())
145 } else {
146 Err(io::Error::from_raw_os_error(libc::EEXIST))
147 }
148 }
149
150 /// Looks up an entry inode by name. `None` if not found.
151 pub fn lookup_inode(&self, basename: &Path) -> Option<Inode> {
152 self.0.get(basename).copied()
153 }
154}
155
Victor Hsieh45636232021-10-15 17:52:51 -0700156fn into_io_error(e: VirtFdServiceStatus) -> io::Error {
157 let maybe_errno = e.service_specific_error();
158 if maybe_errno > 0 {
159 io::Error::from_raw_os_error(maybe_errno)
160 } else {
161 io::Error::new(io::ErrorKind::Other, e.get_description())
162 }
163}