vfs/directory/
entry.rs

1// Copyright 2019 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Common trait for all the directory entry objects.
6
7#![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/// Information about a directory entry, used to populate ReadDirents() output.
27/// The first element is the inode number, or INO_UNKNOWN (from fuchsia.io) if not set, and the second
28/// element is one of the DIRENT_TYPE_* constants defined in the fuchsia.io.
29#[derive(PartialEq, Eq, Clone)]
30pub struct EntryInfo(u64, fio::DirentType);
31
32impl EntryInfo {
33    /// Constructs a new directory entry information object.
34    pub fn new(inode: u64, type_: fio::DirentType) -> Self {
35        Self(inode, type_)
36    }
37
38    /// Retrives the `inode` argument of the [`EntryInfo::new()`] constructor.
39    pub fn inode(&self) -> u64 {
40        let Self(inode, _type) = self;
41        *inode
42    }
43
44    /// Retrieves the `type_` argument of the [`EntryInfo::new()`] constructor.
45    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
62/// Give useful information about the entry, for example, the directory entry type.
63pub trait GetEntryInfo {
64    /// This method is used to populate ReadDirents() output.
65    fn entry_info(&self) -> EntryInfo;
66}
67
68/// Pseudo directories contain items that implement this trait.  Pseudo directories refer to the
69/// items they contain as `Arc<dyn DirectoryEntry>`.
70///
71/// *NOTE*: This trait only needs to be implemented if you want to add your nodes to a pseudo
72/// directory.
73pub trait DirectoryEntry: GetEntryInfo + IntoAny + Sync + Send + 'static {
74    /// Opens this entry.
75    fn open_entry(self: Arc<Self>, request: OpenRequest<'_>) -> Result<(), Status>;
76}
77
78/// Trait that can be implemented to process open requests asynchronously.
79pub trait DirectoryEntryAsync: DirectoryEntry {
80    /// Implementers may use this if desired by using the `spawn` method below.
81    fn open_entry_async(
82        self: Arc<Self>,
83        request: OpenRequest<'_>,
84    ) -> impl Future<Output = Result<(), Status>> + Send;
85}
86
87/// An open request.
88#[derive(Debug)]
89pub struct OpenRequest<'a> {
90    scope: ExecutionScope,
91    request_flags: RequestFlags,
92    path: Path,
93    object_request: ObjectRequestRef<'a>,
94}
95
96/// Wraps flags used for open requests based on which fuchsia.io/Directory.Open method was used.
97/// Used to delegate [`OpenRequest`] to the corresponding method when the entry is opened.
98#[derive(Debug)]
99pub enum RequestFlags {
100    /// fuchsia.io/Directory.Open1 (io1)
101    Open1(fio::OpenFlags),
102    /// fuchsia.io/Directory.Open3 (io2)
103    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    /// Creates a new open request.
120    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    /// Returns the path for this request.
130    pub fn path(&self) -> &Path {
131        &self.path
132    }
133
134    /// Prepends `prefix` to the path.
135    pub fn prepend_path(&mut self, prefix: &Path) {
136        self.path = self.path.with_prefix(prefix);
137    }
138
139    /// Sets the path to `path`.
140    pub fn set_path(&mut self, path: Path) {
141        self.path = path;
142    }
143
144    /// Waits until the request has a request waiting in its channel.  Returns immediately if this
145    /// request requires sending an initial event such as OnOpen or OnRepresentation.  Returns
146    /// `true` if the channel is readable (rather than just clased).
147    pub async fn wait_till_ready(&self) -> bool {
148        self.object_request.wait_till_ready().await
149    }
150
151    /// Returns `true` if the request requires the server to send an event (e.g. either OnOpen or
152    /// OnRepresentation).  If `true`, `wait_till_ready` will return immediately.  If `false`, the
153    /// caller might choose to call `wait_till_ready` if other conditions are satisfied (checking
154    /// for an empty path is usually a good idea since it is hard to know where a non-empty path
155    /// might end up being terminated).
156    pub fn requires_event(&self) -> bool {
157        self.object_request.what_to_send() != ObjectRequestSend::Nothing
158    }
159
160    /// Opens a directory.
161    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                // This will cause issues for heavily nested directory structures because it thwarts
171                // tail recursion optimization, but that shouldn't occur in practice.
172                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    /// Opens a file.
184    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    /// Opens a symlink.
212    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    /// Opens a service.
240    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    /// Forwards the request to a remote.
268    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    /// Spawns a task to handle the request.  `entry` must implement DirectoryEntryAsync.
317    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    /// Returns the execution scope for this request.
357    pub fn scope(&self) -> &ExecutionScope {
358        &self.scope
359    }
360
361    /// Replaces the scope in this request.  This is the right thing to do if any subsequently
362    /// spawned tasks should be in a different scope to the task that received this open request.
363    pub fn set_scope(&mut self, scope: ExecutionScope) {
364        self.scope = scope;
365    }
366}
367
368/// A sub-node of a directory.  This will work with types that implement Directory as well as
369/// RemoteDir.
370pub 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    /// Returns a sub node of an existing entry.  The parent should be a directory (it accepts
378    /// DirectoryEntry so that it works for remotes).
379    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
398/// Serves a directory with the given rights.  Returns a client end.  This takes a DirectoryEntry
399/// so that it works for remotes.
400pub 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}