1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Copyright 2023 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Module for directory operations.
//
// TODO(https://fxbug.dev/42083023): These operations can be merged into `fuchsia-fs` if Rust FIDL bindings
// support making one-way calls on a client endpoint without turning it into a proxy.

use anyhow::{Context, Error};
use fidl::endpoints::ClientEnd;
use fidl_fuchsia_io as fio;
use std::sync::Arc;
use zx::AsHandleRef as _;

/// A trait for opening filesystem nodes.
pub trait Directory {
    /// Open a node relative to the directory.
    fn open(&self, path: &str, flags: fio::Flags, server_end: zx::Channel) -> Result<(), Error>;
}

impl Directory for fio::DirectoryProxy {
    fn open(&self, path: &str, flags: fio::Flags, server_end: zx::Channel) -> Result<(), Error> {
        let () = self.open3(path, flags, &fio::Options::default(), server_end.into())?;
        Ok(())
    }
}

impl Directory for fio::DirectorySynchronousProxy {
    fn open(&self, path: &str, flags: fio::Flags, server_end: zx::Channel) -> Result<(), Error> {
        let () = self.open3(path, flags, &fio::Options::default(), server_end.into())?;
        Ok(())
    }
}

impl Directory for ClientEnd<fio::DirectoryMarker> {
    fn open(&self, path: &str, flags: fio::Flags, server_end: zx::Channel) -> Result<(), Error> {
        let raw_handle = self.channel().as_handle_ref().raw_handle();
        // Safety: we call forget on objects that reference `raw_handle` leaving it usable.
        unsafe {
            let borrowed: zx::Channel = zx::Handle::from_raw(raw_handle).into();
            let proxy = fio::DirectorySynchronousProxy::new(borrowed);
            proxy.open3(path, flags, &fio::Options::default(), server_end.into())?;
            std::mem::forget(proxy.into_channel());
        }
        Ok(())
    }
}

/// A trait for types that can vend out a [`Directory`] reference.
///
/// A new trait is needed because both `DirectoryProxy` and `AsRef` are external types.
/// As a result, implementing `AsRef<&dyn Directory>` for `DirectoryProxy` is not allowed
/// under coherence rules.
pub trait AsRefDirectory {
    /// Get a [`Directory`] reference.
    fn as_ref_directory(&self) -> &dyn Directory;
}

impl AsRefDirectory for fio::DirectoryProxy {
    fn as_ref_directory(&self) -> &dyn Directory {
        self
    }
}

impl AsRefDirectory for fio::DirectorySynchronousProxy {
    fn as_ref_directory(&self) -> &dyn Directory {
        self
    }
}

impl AsRefDirectory for ClientEnd<fio::DirectoryMarker> {
    fn as_ref_directory(&self) -> &dyn Directory {
        self
    }
}

impl<T: Directory> AsRefDirectory for Box<T> {
    fn as_ref_directory(&self) -> &dyn Directory {
        &**self
    }
}

impl<T: Directory> AsRefDirectory for Arc<T> {
    fn as_ref_directory(&self) -> &dyn Directory {
        &**self
    }
}

impl<T: Directory> AsRefDirectory for &T {
    fn as_ref_directory(&self) -> &dyn Directory {
        *self
    }
}

/// Opens the given `path` from the given `parent` directory as a [`DirectoryProxy`] asynchronously.
pub fn open_directory_async(
    parent: &impl AsRefDirectory,
    path: &str,
    rights: fio::Rights,
) -> Result<fio::DirectoryProxy, Error> {
    let (dir, server_end) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>()
        .context("creating directory proxy")?;

    let flags = fio::Flags::PROTOCOL_DIRECTORY | fio::Flags::from_bits_truncate(rights.bits());
    let () = parent
        .as_ref_directory()
        .open(path, flags, server_end.into_channel())
        .context("opening directory without describe")?;

    Ok(dir)
}

/// Opens the given `path` from the given `parent` directory as a [`FileProxy`] asynchronously.
pub fn open_file_async(
    parent: &impl AsRefDirectory,
    path: &str,
    rights: fio::Rights,
) -> Result<fio::FileProxy, Error> {
    let (file, server_end) =
        fidl::endpoints::create_proxy::<fio::FileMarker>().context("creating file proxy")?;

    let flags = fio::Flags::PROTOCOL_FILE | fio::Flags::from_bits_truncate(rights.bits());
    let () = parent
        .as_ref_directory()
        .open(path, flags, server_end.into_channel())
        .context("opening file without describe")?;

    Ok(file)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::test_util::run_directory_server;
    use assert_matches::assert_matches;
    use fuchsia_async as fasync;
    use vfs::directory::immutable::simple;
    use vfs::file::vmo::read_only;
    use vfs::pseudo_directory;

    #[fasync::run_singlethreaded(test)]
    async fn open_directory_async_real() {
        let dir = pseudo_directory! {
            "dir" => simple(),
        };
        let dir = run_directory_server(dir);
        let dir = open_directory_async(&dir, "dir", fio::Rights::empty()).unwrap();
        fuchsia_fs::directory::close(dir).await.unwrap();
    }

    #[fasync::run_singlethreaded(test)]
    async fn open_directory_async_fake() {
        let dir = pseudo_directory! {
            "dir" => simple(),
        };
        let dir = run_directory_server(dir);
        let dir = open_directory_async(&dir, "fake", fio::Rights::empty()).unwrap();
        // The open error is not detected until the proxy is interacted with.
        assert_matches!(fuchsia_fs::directory::close(dir).await, Err(_));
    }

    #[fasync::run_singlethreaded(test)]
    async fn open_file_async_real() {
        let dir = pseudo_directory! {
            "file" => read_only("read_only"),
        };
        let dir = run_directory_server(dir);
        let file = open_file_async(&dir, "file", fio::Rights::READ_BYTES).unwrap();
        fuchsia_fs::file::close(file).await.unwrap();
    }

    #[fasync::run_singlethreaded(test)]
    async fn open_file_async_fake() {
        let dir = pseudo_directory! {
            "file" => read_only("read_only"),
        };
        let dir = run_directory_server(dir);
        let fake = open_file_async(&dir, "fake", fio::Rights::READ_BYTES).unwrap();
        // The open error is not detected until the proxy is interacted with.
        assert_matches!(fuchsia_fs::file::close(fake).await, Err(_));
    }
}