1#![warn(missing_docs)]
8
9use crate::common::IntoAny;
10use crate::directory::entry_container::Directory;
11use crate::execution_scope::ExecutionScope;
12use crate::file::{self, FileLike};
13use crate::object_request::ObjectRequestSend;
14use crate::path::Path;
15use crate::service::{self, ServiceLike};
16use crate::symlink::{self, Symlink};
17use crate::{ObjectRequestRef, ToObjectRequest};
18
19use fidl::endpoints::{create_endpoints, ClientEnd};
20use fidl_fuchsia_io as fio;
21use std::fmt;
22use std::future::Future;
23use std::sync::Arc;
24use zx_status::Status;
25
26#[derive(PartialEq, Eq, Clone)]
30pub struct EntryInfo(u64, fio::DirentType);
31
32impl EntryInfo {
33 pub fn new(inode: u64, type_: fio::DirentType) -> Self {
35 Self(inode, type_)
36 }
37
38 pub fn inode(&self) -> u64 {
40 let Self(inode, _type) = self;
41 *inode
42 }
43
44 pub fn type_(&self) -> fio::DirentType {
46 let Self(_inode, type_) = self;
47 *type_
48 }
49}
50
51impl fmt::Debug for EntryInfo {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 let Self(inode, type_) = self;
54 if *inode == fio::INO_UNKNOWN {
55 write!(f, "{:?}(fio::INO_UNKNOWN)", type_)
56 } else {
57 write!(f, "{:?}({})", type_, inode)
58 }
59 }
60}
61
62pub trait GetEntryInfo {
64 fn entry_info(&self) -> EntryInfo;
66}
67
68pub trait DirectoryEntry: GetEntryInfo + IntoAny + Sync + Send + 'static {
74 fn open_entry(self: Arc<Self>, request: OpenRequest<'_>) -> Result<(), Status>;
76}
77
78pub trait DirectoryEntryAsync: DirectoryEntry {
80 fn open_entry_async(
82 self: Arc<Self>,
83 request: OpenRequest<'_>,
84 ) -> impl Future<Output = Result<(), Status>> + Send;
85}
86
87#[derive(Debug)]
89pub struct OpenRequest<'a> {
90 scope: ExecutionScope,
91 request_flags: RequestFlags,
92 path: Path,
93 object_request: ObjectRequestRef<'a>,
94}
95
96#[derive(Debug)]
99pub enum RequestFlags {
100 Open1(fio::OpenFlags),
102 Open3(fio::Flags),
104}
105
106impl From<fio::OpenFlags> for RequestFlags {
107 fn from(value: fio::OpenFlags) -> Self {
108 RequestFlags::Open1(value)
109 }
110}
111
112impl From<fio::Flags> for RequestFlags {
113 fn from(value: fio::Flags) -> Self {
114 RequestFlags::Open3(value)
115 }
116}
117
118impl<'a> OpenRequest<'a> {
119 pub fn new(
121 scope: ExecutionScope,
122 request_flags: impl Into<RequestFlags>,
123 path: Path,
124 object_request: ObjectRequestRef<'a>,
125 ) -> Self {
126 Self { scope, request_flags: request_flags.into(), path, object_request }
127 }
128
129 pub fn path(&self) -> &Path {
131 &self.path
132 }
133
134 pub fn prepend_path(&mut self, prefix: &Path) {
136 self.path = self.path.with_prefix(prefix);
137 }
138
139 pub fn set_path(&mut self, path: Path) {
141 self.path = path;
142 }
143
144 pub async fn wait_till_ready(&self) -> bool {
148 self.object_request.wait_till_ready().await
149 }
150
151 pub fn requires_event(&self) -> bool {
157 self.object_request.what_to_send() != ObjectRequestSend::Nothing
158 }
159
160 pub fn open_dir(self, dir: Arc<impl Directory>) -> Result<(), Status> {
162 match self {
163 OpenRequest {
164 scope,
165 request_flags: RequestFlags::Open1(flags),
166 path,
167 object_request,
168 } => {
169 dir.open(scope, flags, path, object_request.take().into_server_end());
170 Ok(())
173 }
174 OpenRequest {
175 scope,
176 request_flags: RequestFlags::Open3(flags),
177 path,
178 object_request,
179 } => dir.open3(scope, path, flags, object_request),
180 }
181 }
182
183 pub fn open_file(self, file: Arc<impl FileLike>) -> Result<(), Status> {
185 match self {
186 OpenRequest {
187 scope,
188 request_flags: RequestFlags::Open1(flags),
189 path,
190 object_request,
191 } => {
192 if !path.is_empty() {
193 return Err(Status::NOT_DIR);
194 }
195 file::serve(file, scope, &flags, object_request)
196 }
197 OpenRequest {
198 scope,
199 request_flags: RequestFlags::Open3(flags),
200 path,
201 object_request,
202 } => {
203 if !path.is_empty() {
204 return Err(Status::NOT_DIR);
205 }
206 file::serve(file, scope, &flags, object_request)
207 }
208 }
209 }
210
211 pub fn open_symlink(self, service: Arc<impl Symlink>) -> Result<(), Status> {
213 match self {
214 OpenRequest {
215 scope,
216 request_flags: RequestFlags::Open1(flags),
217 path,
218 object_request,
219 } => {
220 if !path.is_empty() {
221 return Err(Status::NOT_DIR);
222 }
223 symlink::serve(service, scope, flags, object_request)
224 }
225 OpenRequest {
226 scope,
227 request_flags: RequestFlags::Open3(flags),
228 path,
229 object_request,
230 } => {
231 if !path.is_empty() {
232 return Err(Status::NOT_DIR);
233 }
234 symlink::serve(service, scope, flags, object_request)
235 }
236 }
237 }
238
239 pub fn open_service(self, service: Arc<impl ServiceLike>) -> Result<(), Status> {
241 match self {
242 OpenRequest {
243 scope,
244 request_flags: RequestFlags::Open1(flags),
245 path,
246 object_request,
247 } => {
248 if !path.is_empty() {
249 return Err(Status::NOT_DIR);
250 }
251 service::serve(service, scope, &flags, object_request)
252 }
253 OpenRequest {
254 scope,
255 request_flags: RequestFlags::Open3(flags),
256 path,
257 object_request,
258 } => {
259 if !path.is_empty() {
260 return Err(Status::NOT_DIR);
261 }
262 service::serve(service, scope, &flags, object_request)
263 }
264 }
265 }
266
267 pub fn open_remote(
269 self,
270 remote: Arc<impl crate::remote::RemoteLike + Send + Sync + 'static>,
271 ) -> Result<(), Status> {
272 match self {
273 OpenRequest {
274 scope,
275 request_flags: RequestFlags::Open1(flags),
276 path,
277 object_request,
278 } => {
279 if object_request.what_to_send() == ObjectRequestSend::Nothing && remote.lazy(&path)
280 {
281 let object_request = object_request.take();
282 scope.clone().spawn(async move {
283 if object_request.wait_till_ready().await {
284 remote.open(scope, flags, path, object_request.into_server_end());
285 }
286 });
287 } else {
288 remote.open(scope, flags, path, object_request.take().into_server_end());
289 }
290 Ok(())
291 }
292 OpenRequest {
293 scope,
294 request_flags: RequestFlags::Open3(flags),
295 path,
296 object_request,
297 } => {
298 if object_request.what_to_send() == ObjectRequestSend::Nothing && remote.lazy(&path)
299 {
300 let object_request = object_request.take();
301 scope.clone().spawn(async move {
302 if object_request.wait_till_ready().await {
303 object_request.handle(|object_request| {
304 remote.open3(scope, path, flags, object_request)
305 });
306 }
307 });
308 Ok(())
309 } else {
310 remote.open3(scope, path, flags, object_request)
311 }
312 }
313 }
314 }
315
316 pub fn spawn(self, entry: Arc<impl DirectoryEntryAsync>) {
318 let OpenRequest { scope, request_flags, path, object_request } = self;
319 let mut object_request = object_request.take();
320 match request_flags {
321 RequestFlags::Open1(flags) => {
322 scope.clone().spawn(async move {
323 match entry
324 .open_entry_async(OpenRequest::new(
325 scope,
326 RequestFlags::Open1(flags),
327 path,
328 &mut object_request,
329 ))
330 .await
331 {
332 Ok(()) => {}
333 Err(s) => object_request.shutdown(s),
334 }
335 });
336 }
337 RequestFlags::Open3(flags) => {
338 scope.clone().spawn(async move {
339 match entry
340 .open_entry_async(OpenRequest::new(
341 scope,
342 RequestFlags::Open3(flags),
343 path,
344 &mut object_request,
345 ))
346 .await
347 {
348 Ok(()) => {}
349 Err(s) => object_request.shutdown(s),
350 }
351 });
352 }
353 }
354 }
355
356 pub fn scope(&self) -> &ExecutionScope {
358 &self.scope
359 }
360
361 pub fn set_scope(&mut self, scope: ExecutionScope) {
364 self.scope = scope;
365 }
366}
367
368pub struct SubNode<T: ?Sized> {
371 parent: Arc<T>,
372 path: Path,
373 entry_type: fio::DirentType,
374}
375
376impl<T: DirectoryEntry + ?Sized> SubNode<T> {
377 pub fn new(parent: Arc<T>, path: Path, entry_type: fio::DirentType) -> SubNode<T> {
380 assert_eq!(parent.entry_info().type_(), fio::DirentType::Directory);
381 Self { parent, path, entry_type }
382 }
383}
384
385impl<T: DirectoryEntry + ?Sized> GetEntryInfo for SubNode<T> {
386 fn entry_info(&self) -> EntryInfo {
387 EntryInfo::new(fio::INO_UNKNOWN, self.entry_type)
388 }
389}
390
391impl<T: DirectoryEntry + ?Sized> DirectoryEntry for SubNode<T> {
392 fn open_entry(self: Arc<Self>, mut request: OpenRequest<'_>) -> Result<(), Status> {
393 request.path = request.path.with_prefix(&self.path);
394 self.parent.clone().open_entry(request)
395 }
396}
397
398pub fn serve_directory(
401 dir: Arc<impl DirectoryEntry + ?Sized>,
402 scope: &ExecutionScope,
403 flags: fio::Flags,
404) -> Result<ClientEnd<fio::DirectoryMarker>, Status> {
405 assert_eq!(dir.entry_info().type_(), fio::DirentType::Directory);
406 let (client, server) = create_endpoints::<fio::DirectoryMarker>();
407 flags
408 .to_object_request(server)
409 .handle(|object_request| {
410 Ok(dir.open_entry(OpenRequest::new(scope.clone(), flags, Path::dot(), object_request)))
411 })
412 .unwrap()?;
413 Ok(client)
414}
415
416#[cfg(test)]
417mod tests {
418 use super::{
419 DirectoryEntry, DirectoryEntryAsync, EntryInfo, OpenRequest, RequestFlags, SubNode,
420 };
421 use crate::directory::entry::GetEntryInfo;
422 use crate::directory::entry_container::Directory;
423 use crate::execution_scope::ExecutionScope;
424 use crate::file::read_only;
425 use crate::path::Path;
426 use crate::{assert_read, pseudo_directory, ObjectRequest, ToObjectRequest};
427 use assert_matches::assert_matches;
428 use fidl::endpoints::{create_endpoints, create_proxy, ClientEnd};
429 use fidl_fuchsia_io as fio;
430 use futures::StreamExt;
431 use std::sync::Arc;
432 use zx_status::Status;
433
434 #[fuchsia::test]
435 async fn sub_node() {
436 let root = pseudo_directory!(
437 "a" => pseudo_directory!(
438 "b" => pseudo_directory!(
439 "c" => pseudo_directory!(
440 "d" => read_only(b"foo")
441 )
442 )
443 )
444 );
445 let sub_node = Arc::new(SubNode::new(
446 root,
447 Path::validate_and_split("a/b").unwrap(),
448 fio::DirentType::Directory,
449 ));
450 let scope = ExecutionScope::new();
451 let (client, server) = create_endpoints();
452
453 let root2 = pseudo_directory!(
454 "e" => sub_node
455 );
456
457 root2.open(
458 scope.clone(),
459 fio::OpenFlags::RIGHT_READABLE,
460 Path::validate_and_split("e/c/d").unwrap(),
461 server,
462 );
463 assert_read!(ClientEnd::<fio::FileMarker>::from(client.into_channel()).into_proxy(), "foo");
464 }
465
466 #[fuchsia::test]
467 async fn object_request_spawn() {
468 struct MockNode<F: Send + Sync + 'static>
469 where
470 for<'a> F: Fn(OpenRequest<'a>) -> Status,
471 {
472 callback: F,
473 }
474 impl<F: Send + Sync + 'static> DirectoryEntry for MockNode<F>
475 where
476 for<'a> F: Fn(OpenRequest<'a>) -> Status,
477 {
478 fn open_entry(self: Arc<Self>, request: OpenRequest<'_>) -> Result<(), Status> {
479 request.spawn(self);
480 Ok(())
481 }
482 }
483 impl<F: Send + Sync + 'static> GetEntryInfo for MockNode<F>
484 where
485 for<'a> F: Fn(OpenRequest<'a>) -> Status,
486 {
487 fn entry_info(&self) -> EntryInfo {
488 EntryInfo::new(fio::INO_UNKNOWN, fio::DirentType::Unknown)
489 }
490 }
491 impl<F: Send + Sync + 'static> DirectoryEntryAsync for MockNode<F>
492 where
493 for<'a> F: Fn(OpenRequest<'a>) -> Status,
494 {
495 async fn open_entry_async(
496 self: Arc<Self>,
497 request: OpenRequest<'_>,
498 ) -> Result<(), Status> {
499 Err((self.callback)(request))
500 }
501 }
502
503 let scope = ExecutionScope::new();
504 let (proxy, server) = create_proxy::<fio::NodeMarker>();
505 let flags = fio::OpenFlags::DIRECTORY | fio::OpenFlags::RIGHT_READABLE;
506 let mut object_request = flags.to_object_request(server);
507
508 let flags_copy = flags;
509 Arc::new(MockNode {
510 callback: move |request| {
511 assert_matches!(
512 request,
513 OpenRequest {
514 request_flags: RequestFlags::Open1(f),
515 path,
516 ..
517 } if f == flags_copy && path.as_ref() == "a/b/c"
518 );
519 Status::BAD_STATE
520 },
521 })
522 .open_entry(OpenRequest::new(
523 scope.clone(),
524 flags,
525 "a/b/c".try_into().unwrap(),
526 &mut object_request,
527 ))
528 .unwrap();
529
530 assert_matches!(
531 proxy.take_event_stream().next().await,
532 Some(Err(fidl::Error::ClientChannelClosed { status, .. }))
533 if status == Status::BAD_STATE
534 );
535
536 let (proxy, server) = create_proxy::<fio::NodeMarker>();
537 let flags = fio::Flags::PROTOCOL_FILE | fio::Flags::FILE_APPEND;
538 let mut object_request =
539 ObjectRequest::new(flags, &Default::default(), server.into_channel());
540
541 Arc::new(MockNode {
542 callback: move |request| {
543 assert_matches!(
544 request,
545 OpenRequest {
546 request_flags: RequestFlags::Open3(f),
547 path,
548 ..
549 } if f == flags && path.as_ref() == "a/b/c"
550 );
551 Status::BAD_STATE
552 },
553 })
554 .open_entry(OpenRequest::new(
555 scope.clone(),
556 flags,
557 "a/b/c".try_into().unwrap(),
558 &mut object_request,
559 ))
560 .unwrap();
561
562 assert_matches!(
563 proxy.take_event_stream().next().await,
564 Some(Err(fidl::Error::ClientChannelClosed { status, .. }))
565 if status == Status::BAD_STATE
566 );
567 }
568}