1use crate::root_dir::RootDir;
6use crate::usize_to_u64_safe;
7use fidl_fuchsia_io as fio;
8use std::sync::Arc;
9use vfs::directory::entry::EntryInfo;
10use vfs::directory::immutable::connection::ImmutableConnection;
11use vfs::directory::traversal_position::TraversalPosition;
12use vfs::execution_scope::ExecutionScope;
13use vfs::{ObjectRequestRef, immutable_attributes};
14
15pub(crate) struct MetaAsDir<S: crate::NonMetaStorage> {
16 root_dir: Arc<RootDir<S>>,
17}
18
19impl<S: crate::NonMetaStorage> MetaAsDir<S> {
20 pub(crate) fn new(root_dir: Arc<RootDir<S>>) -> Arc<Self> {
21 Arc::new(MetaAsDir { root_dir })
22 }
23}
24
25impl<S: crate::NonMetaStorage> vfs::directory::entry::GetEntryInfo for MetaAsDir<S> {
26 fn entry_info(&self) -> EntryInfo {
27 EntryInfo::new(fio::INO_UNKNOWN, fio::DirentType::Directory)
28 }
29}
30
31impl<S: crate::NonMetaStorage> vfs::node::Node for MetaAsDir<S> {
32 async fn get_attributes(
33 &self,
34 requested_attributes: fio::NodeAttributesQuery,
35 ) -> Result<fio::NodeAttributes2, zx::Status> {
36 Ok(immutable_attributes!(
37 requested_attributes,
38 Immutable {
39 protocols: fio::NodeProtocolKinds::DIRECTORY,
40 abilities: crate::DIRECTORY_ABILITIES,
41 content_size: usize_to_u64_safe(self.root_dir.meta_files.element_len()),
42 storage_size: usize_to_u64_safe(self.root_dir.meta_files.element_len()),
43 id: 1,
44 }
45 ))
46 }
47}
48
49impl<S: crate::NonMetaStorage> vfs::directory::entry_container::Directory for MetaAsDir<S> {
50 fn open(
51 self: Arc<Self>,
52 scope: ExecutionScope,
53 path: vfs::Path,
54 flags: fio::Flags,
55 object_request: ObjectRequestRef<'_>,
56 ) -> Result<(), zx::Status> {
57 if !flags.difference(crate::ALLOWED_FLAGS).is_empty() {
58 return Err(zx::Status::NOT_SUPPORTED);
59 }
60 if flags.contains(fio::Flags::PERM_EXECUTE) {
62 return Err(zx::Status::NOT_SUPPORTED);
63 }
64
65 if path.is_empty() {
67 object_request
75 .take()
76 .create_connection_sync::<ImmutableConnection<_>, _>(scope, self, flags);
77 return Ok(());
78 }
79
80 let file_path =
82 format!("meta/{}", path.as_ref().strip_suffix('/').unwrap_or_else(|| path.as_ref()));
83
84 if let Some(file) = self.root_dir.get_meta_file(&file_path)? {
85 if path.is_dir() {
86 return Err(zx::Status::NOT_DIR);
87 }
88 return vfs::file::serve(file, scope, &flags, object_request);
89 }
90
91 if let Some(subdir) = self.root_dir.get_meta_subdir(file_path + "/") {
92 return subdir.open(scope, vfs::Path::dot(), flags, object_request);
93 }
94
95 Err(zx::Status::NOT_FOUND)
96 }
97
98 async fn read_dirents(
99 &self,
100 pos: &TraversalPosition,
101 sink: Box<dyn vfs::directory::dirents_sink::Sink + 'static>,
102 ) -> Result<
103 (TraversalPosition, Box<dyn vfs::directory::dirents_sink::Sealed + 'static>),
104 zx::Status,
105 > {
106 vfs::directory::read_dirents::read_dirents(
107 &crate::get_dir_children(self.root_dir.meta_files.keys(), "meta/"),
108 pos,
109 sink,
110 )
111 }
112
113 fn register_watcher(
114 self: Arc<Self>,
115 _: ExecutionScope,
116 _: fio::WatchMask,
117 _: vfs::directory::entry_container::DirectoryWatcher,
118 ) -> Result<(), zx::Status> {
119 Err(zx::Status::NOT_SUPPORTED)
120 }
121
122 fn unregister_watcher(self: Arc<Self>, _: usize) {}
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129 use assert_matches::assert_matches;
130 use fuchsia_fs::directory::{DirEntry, DirentKind};
131 use fuchsia_pkg_testing::PackageBuilder;
132 use fuchsia_pkg_testing::blobfs::Fake as FakeBlobfs;
133 use futures::TryStreamExt as _;
134
135 struct TestEnv {
136 _blobfs_fake: FakeBlobfs,
137 }
138
139 impl TestEnv {
140 async fn new() -> (Self, fio::DirectoryProxy) {
141 let pkg = PackageBuilder::new("pkg")
142 .add_resource_at("meta/dir/file", &b"contents"[..])
143 .build()
144 .await
145 .unwrap();
146 let (metafar_blob, _) = pkg.contents();
147 let (blobfs_fake, blobfs_client) = FakeBlobfs::new();
148 blobfs_fake.add_blob(metafar_blob.merkle, metafar_blob.contents);
149 let root_dir = RootDir::new(blobfs_client, metafar_blob.merkle).await.unwrap();
150 let meta_as_dir = MetaAsDir::new(root_dir);
151 (
152 Self { _blobfs_fake: blobfs_fake },
153 vfs::directory::serve_read_only(
154 meta_as_dir,
155 vfs::execution_scope::ExecutionScope::new(),
156 ),
157 )
158 }
159 }
160
161 #[fuchsia::test]
166 async fn meta_as_dir_cannot_be_served_as_mutable() {
167 let pkg = PackageBuilder::new("pkg")
168 .add_resource_at("meta/dir/file", &b"contents"[..])
169 .build()
170 .await
171 .unwrap();
172 let (metafar_blob, _) = pkg.contents();
173 let (blobfs_fake, blobfs_client) = FakeBlobfs::new();
174 blobfs_fake.add_blob(metafar_blob.merkle, metafar_blob.contents);
175 let meta_as_dir =
176 MetaAsDir::new(RootDir::new(blobfs_client, metafar_blob.merkle).await.unwrap());
177 for flags in [fio::PERM_WRITABLE, fio::PERM_EXECUTABLE] {
178 let proxy = vfs::directory::serve(meta_as_dir.clone(), ExecutionScope::new(), flags);
179 assert_matches!(
180 proxy.take_event_stream().try_next().await,
181 Err(fidl::Error::ClientChannelClosed { status: zx::Status::NOT_SUPPORTED, .. })
182 );
183 }
184 }
185
186 #[fuchsia::test]
187 async fn meta_as_dir_readdir() {
188 let (_env, meta_as_dir) = TestEnv::new().await;
189 assert_eq!(
190 fuchsia_fs::directory::readdir_inclusive(&meta_as_dir).await.unwrap(),
191 vec![
192 DirEntry { name: ".".to_string(), kind: DirentKind::Directory },
193 DirEntry { name: "contents".to_string(), kind: DirentKind::File },
194 DirEntry { name: "dir".to_string(), kind: DirentKind::Directory },
195 DirEntry { name: "fuchsia.abi".to_string(), kind: DirentKind::Directory },
196 DirEntry { name: "package".to_string(), kind: DirentKind::File }
197 ]
198 );
199 }
200
201 #[fuchsia::test]
202 async fn meta_as_dir_get_attributes() {
203 let (_env, meta_as_dir) = TestEnv::new().await;
204 let (mutable_attributes, immutable_attributes) =
205 meta_as_dir.get_attributes(fio::NodeAttributesQuery::all()).await.unwrap().unwrap();
206 assert_eq!(
207 fio::NodeAttributes2 { mutable_attributes, immutable_attributes },
208 immutable_attributes!(
209 fio::NodeAttributesQuery::all(),
210 Immutable {
211 protocols: fio::NodeProtocolKinds::DIRECTORY,
212 abilities: crate::DIRECTORY_ABILITIES,
213 content_size: 4,
214 storage_size: 4,
215 id: 1,
216 }
217 )
218 );
219 }
220
221 #[fuchsia::test]
222 async fn meta_as_dir_watch_not_supported() {
223 let (_env, meta_as_dir) = TestEnv::new().await;
224 let (_client, server) = fidl::endpoints::create_endpoints();
225 let status = zx::Status::from_raw(
226 meta_as_dir.watch(fio::WatchMask::empty(), 0, server).await.unwrap(),
227 );
228 assert_eq!(status, zx::Status::NOT_SUPPORTED);
229 }
230
231 #[fuchsia::test]
232 async fn meta_as_dir_open_file() {
233 let (_env, meta_as_dir) = TestEnv::new().await;
234 let proxy = fuchsia_fs::directory::open_file(&meta_as_dir, "dir/file", fio::PERM_READABLE)
235 .await
236 .unwrap();
237 assert_eq!(fuchsia_fs::file::read(&proxy).await.unwrap(), b"contents".to_vec());
238 }
239
240 #[fuchsia::test]
241 async fn meta_as_dir_open_directory() {
242 let (_env, meta_as_dir) = TestEnv::new().await;
243 for path in ["dir", "dir/"] {
244 let proxy =
245 fuchsia_fs::directory::open_directory(&meta_as_dir, path, fio::PERM_READABLE)
246 .await
247 .unwrap();
248 assert_eq!(
249 fuchsia_fs::directory::readdir(&proxy).await.unwrap(),
250 vec![DirEntry { name: "file".to_string(), kind: DirentKind::File }]
251 );
252 }
253 }
254}