vfs/
node.rs

1// Copyright 2023 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//! Implementation of a (limited) node connection.
6
7use crate::common::IntoAny;
8use crate::directory::entry::GetEntryInfo;
9use crate::directory::entry_container::MutableDirectory;
10use crate::execution_scope::ExecutionScope;
11use crate::name::Name;
12use crate::object_request::{ConnectionCreator, Representation, run_synchronous_future_or_spawn};
13use crate::protocols::ToNodeOptions;
14use crate::request_handler::{RequestHandler, RequestListener};
15use crate::{ObjectRequest, ObjectRequestRef};
16use anyhow::Error;
17use fidl::endpoints::{DiscoverableProtocolMarker as _, ServerEnd};
18use fidl_fuchsia_io as fio;
19use libc::{S_IRUSR, S_IWUSR};
20use std::future::{Future, ready};
21use std::ops::ControlFlow;
22use std::pin::Pin;
23use std::sync::Arc;
24use zx_status::Status;
25
26/// POSIX emulation layer access attributes for all services created with service().
27#[cfg(not(target_os = "macos"))]
28pub const POSIX_READ_WRITE_PROTECTION_ATTRIBUTES: u32 = S_IRUSR | S_IWUSR;
29#[cfg(target_os = "macos")]
30pub const POSIX_READ_WRITE_PROTECTION_ATTRIBUTES: u16 = S_IRUSR | S_IWUSR;
31
32#[derive(Clone, Copy)]
33pub struct NodeOptions {
34    pub rights: fio::Operations,
35}
36
37impl From<&NodeOptions> for fio::Flags {
38    fn from(options: &NodeOptions) -> Self {
39        // There is 1:1 mapping between `fio::Operations` and `fio::Flags`.
40        fio::Flags::PROTOCOL_NODE | fio::Flags::from_bits_truncate(options.rights.bits())
41    }
42}
43
44/// All nodes must implement this trait.
45pub trait Node: GetEntryInfo + IntoAny + Send + Sync + 'static {
46    /// Returns node attributes (io2).
47    fn get_attributes(
48        &self,
49        requested_attributes: fio::NodeAttributesQuery,
50    ) -> impl Future<Output = Result<fio::NodeAttributes2, Status>> + Send
51    where
52        Self: Sized;
53
54    /// Called when the node is about to be opened as the node protocol.  Implementers can use this
55    /// to perform any initialization or reference counting.  Errors here will result in the open
56    /// failing.  By default, this forwards to the infallible will_clone.
57    fn will_open_as_node(&self) -> Result<(), Status> {
58        self.will_clone();
59        Ok(())
60    }
61
62    /// Called when the node is about to be cloned (and also by the default implementation of
63    /// will_open_as_node).  Implementations that perform their own open count can use this.  Each
64    /// call to `will_clone` will be accompanied by an eventual call to `close`.
65    fn will_clone(&self) {}
66
67    /// Called when the node is closed.
68    fn close(self: Arc<Self>) {}
69
70    fn link_into(
71        self: Arc<Self>,
72        _destination_dir: Arc<dyn MutableDirectory>,
73        _name: Name,
74    ) -> impl Future<Output = Result<(), Status>> + Send
75    where
76        Self: Sized,
77    {
78        ready(Err(Status::NOT_SUPPORTED))
79    }
80
81    /// Returns information about the filesystem.
82    fn query_filesystem(&self) -> Result<fio::FilesystemInfo, Status> {
83        Err(Status::NOT_SUPPORTED)
84    }
85
86    /// Opens the node using the node protocol.
87    fn open_as_node(
88        self: Arc<Self>,
89        scope: ExecutionScope,
90        options: NodeOptions,
91        object_request: ObjectRequestRef<'_>,
92    ) -> Result<(), Status>
93    where
94        Self: Sized,
95    {
96        self.will_open_as_node()?;
97        Connection::create_sync(scope, self, options, object_request.take());
98        Ok(())
99    }
100}
101
102/// Represents a FIDL (limited) node connection.
103pub struct Connection<N: Node> {
104    // Execution scope this connection and any async operations and connections it creates will
105    // use.
106    scope: ExecutionScope,
107
108    // The underlying node.
109    node: OpenNode<N>,
110
111    // Node options.
112    options: NodeOptions,
113}
114
115/// Return type for [`handle_request()`] functions.
116enum ConnectionState {
117    /// Connection is still alive.
118    Alive,
119    /// Connection have received Node::Close message, it was dropped by the peer, or an error had
120    /// occurred.  As we do not perform any actions, except for closing our end we do not
121    /// distinguish those cases, unlike file and directory connections.
122    Closed,
123}
124
125impl<N: Node> Connection<N> {
126    /// Creates a new connection to serve the node. The node will be served from a new async `Task`,
127    /// not from the current `Task`. Errors in constructing the connection are not guaranteed to be
128    /// returned, they may be sent directly to the client end of the connection. This method should
129    /// be called from within an `ObjectRequest` handler to ensure that errors are sent to the
130    /// client end of the connection.
131    pub async fn create(
132        scope: ExecutionScope,
133        node: Arc<N>,
134        options: impl ToNodeOptions,
135        object_request: ObjectRequestRef<'_>,
136    ) -> Result<(), Status> {
137        let node = OpenNode::new(node);
138        let options = options.to_node_options(node.entry_info().type_())?;
139        let connection = Connection { scope: scope.clone(), node, options };
140        if let Ok(requests) = object_request.take().into_request_stream(&connection).await {
141            scope.spawn(RequestListener::new(requests, connection));
142        }
143        Ok(())
144    }
145
146    /// Similar to `create` but optimized for nodes whose implementation is synchronous and creating
147    /// the connection is being done from a non-async context.
148    pub fn create_sync(
149        scope: ExecutionScope,
150        node: Arc<N>,
151        options: impl ToNodeOptions,
152        object_request: ObjectRequest,
153    ) {
154        run_synchronous_future_or_spawn(
155            scope.clone(),
156            object_request.handle_async(async |object_request| {
157                Self::create(scope, node, options, object_request).await
158            }),
159        )
160    }
161
162    /// Handle a [`NodeRequest`].
163    async fn handle_request(&mut self, req: fio::NodeRequest) -> Result<ConnectionState, Error> {
164        match req {
165            #[cfg(any(
166                fuchsia_api_level_at_least = "PLATFORM",
167                not(fuchsia_api_level_at_least = "NEXT")
168            ))]
169            fio::NodeRequest::DeprecatedClone { flags, object, control_handle: _ } => {
170                crate::common::send_on_open_with_error(
171                    flags.contains(fio::OpenFlags::DESCRIBE),
172                    object,
173                    Status::NOT_SUPPORTED,
174                );
175            }
176            fio::NodeRequest::Clone { request, control_handle: _ } => {
177                // Suppress any errors in the event a bad `request` channel was provided.
178                self.handle_clone(ServerEnd::new(request.into_channel()));
179            }
180            fio::NodeRequest::Close { responder } => {
181                responder.send(Ok(()))?;
182                return Ok(ConnectionState::Closed);
183            }
184            fio::NodeRequest::Sync { responder } => {
185                responder.send(Err(Status::NOT_SUPPORTED.into_raw()))?;
186            }
187            #[cfg(fuchsia_api_level_at_least = "28")]
188            fio::NodeRequest::DeprecatedGetAttr { responder } => {
189                let (status, attrs) =
190                    crate::common::io2_to_io1_attrs(self.node.as_ref(), self.options.rights).await;
191                responder.send(status.into_raw(), &attrs)?;
192            }
193            #[cfg(not(fuchsia_api_level_at_least = "28"))]
194            fio::NodeRequest::GetAttr { responder } => {
195                let (status, attrs) =
196                    crate::common::io2_to_io1_attrs(self.node.as_ref(), self.options.rights).await;
197                responder.send(status.into_raw(), &attrs)?;
198            }
199            #[cfg(fuchsia_api_level_at_least = "28")]
200            fio::NodeRequest::DeprecatedSetAttr { flags: _, attributes: _, responder } => {
201                responder.send(Status::BAD_HANDLE.into_raw())?;
202            }
203            #[cfg(not(fuchsia_api_level_at_least = "28"))]
204            fio::NodeRequest::SetAttr { flags: _, attributes: _, responder } => {
205                responder.send(Status::BAD_HANDLE.into_raw())?;
206            }
207            fio::NodeRequest::GetAttributes { query, responder } => {
208                let result = self.node.get_attributes(query).await;
209                responder.send(
210                    result
211                        .as_ref()
212                        .map(|attrs| (&attrs.mutable_attributes, &attrs.immutable_attributes))
213                        .map_err(|status| status.into_raw()),
214                )?;
215            }
216            fio::NodeRequest::UpdateAttributes { payload: _, responder } => {
217                responder.send(Err(Status::BAD_HANDLE.into_raw()))?;
218            }
219            fio::NodeRequest::ListExtendedAttributes { iterator, .. } => {
220                iterator.close_with_epitaph(Status::NOT_SUPPORTED)?;
221            }
222            fio::NodeRequest::GetExtendedAttribute { responder, .. } => {
223                responder.send(Err(Status::NOT_SUPPORTED.into_raw()))?;
224            }
225            fio::NodeRequest::SetExtendedAttribute { responder, .. } => {
226                responder.send(Err(Status::NOT_SUPPORTED.into_raw()))?;
227            }
228            fio::NodeRequest::RemoveExtendedAttribute { responder, .. } => {
229                responder.send(Err(Status::NOT_SUPPORTED.into_raw()))?;
230            }
231            #[cfg(fuchsia_api_level_at_least = "27")]
232            fio::NodeRequest::GetFlags { responder } => {
233                responder.send(Ok(fio::Flags::from(&self.options)))?;
234            }
235            #[cfg(fuchsia_api_level_at_least = "27")]
236            fio::NodeRequest::SetFlags { flags: _, responder } => {
237                responder.send(Err(Status::NOT_SUPPORTED.into_raw()))?;
238            }
239            #[cfg(fuchsia_api_level_at_least = "27")]
240            fio::NodeRequest::DeprecatedGetFlags { responder } => {
241                responder.send(Status::OK.into_raw(), fio::OpenFlags::NODE_REFERENCE)?;
242            }
243            #[cfg(fuchsia_api_level_at_least = "27")]
244            fio::NodeRequest::DeprecatedSetFlags { flags: _, responder } => {
245                responder.send(Status::BAD_HANDLE.into_raw())?;
246            }
247            #[cfg(not(fuchsia_api_level_at_least = "27"))]
248            fio::NodeRequest::GetFlags { responder } => {
249                responder.send(Status::OK.into_raw(), fio::OpenFlags::NODE_REFERENCE)?;
250            }
251            #[cfg(not(fuchsia_api_level_at_least = "27"))]
252            fio::NodeRequest::SetFlags { flags: _, responder } => {
253                responder.send(Status::BAD_HANDLE.into_raw())?;
254            }
255            fio::NodeRequest::Query { responder } => {
256                responder.send(fio::NodeMarker::PROTOCOL_NAME.as_bytes())?;
257            }
258            fio::NodeRequest::QueryFilesystem { responder } => {
259                responder.send(Status::NOT_SUPPORTED.into_raw(), None)?;
260            }
261            fio::NodeRequest::_UnknownMethod { .. } => (),
262        }
263        Ok(ConnectionState::Alive)
264    }
265
266    fn handle_clone(&mut self, server_end: ServerEnd<fio::NodeMarker>) {
267        self.node.will_clone();
268        let connection = Self {
269            scope: self.scope.clone(),
270            node: OpenNode::new(self.node.clone()),
271            options: self.options,
272        };
273        self.scope.spawn(RequestListener::new(server_end.into_stream(), connection));
274    }
275}
276
277impl<N: Node> RequestHandler for Connection<N> {
278    type Request = Result<fio::NodeRequest, fidl::Error>;
279
280    async fn handle_request(self: Pin<&mut Self>, request: Self::Request) -> ControlFlow<()> {
281        let this = self.get_mut();
282        if let Some(_guard) = this.scope.try_active_guard() {
283            match request {
284                Ok(request) => match this.handle_request(request).await {
285                    Ok(ConnectionState::Alive) => ControlFlow::Continue(()),
286                    Ok(ConnectionState::Closed) | Err(_) => ControlFlow::Break(()),
287                },
288                Err(_) => ControlFlow::Break(()),
289            }
290        } else {
291            ControlFlow::Break(())
292        }
293    }
294}
295
296impl<N: Node> Representation for Connection<N> {
297    type Protocol = fio::NodeMarker;
298
299    #[cfg(fuchsia_api_level_at_least = "27")]
300    async fn get_representation(
301        &self,
302        requested_attributes: fio::NodeAttributesQuery,
303    ) -> Result<fio::Representation, Status> {
304        Ok(fio::Representation::Node(fio::NodeInfo {
305            attributes: if requested_attributes.is_empty() {
306                None
307            } else {
308                Some(self.node.get_attributes(requested_attributes).await?)
309            },
310            ..Default::default()
311        }))
312    }
313
314    #[cfg(not(fuchsia_api_level_at_least = "27"))]
315    async fn get_representation(
316        &self,
317        requested_attributes: fio::NodeAttributesQuery,
318    ) -> Result<fio::Representation, Status> {
319        Ok(fio::Representation::Connector(fio::ConnectorInfo {
320            attributes: if requested_attributes.is_empty() {
321                None
322            } else {
323                Some(self.node.get_attributes(requested_attributes).await?)
324            },
325            ..Default::default()
326        }))
327    }
328
329    async fn node_info(&self) -> Result<fio::NodeInfoDeprecated, Status> {
330        Ok(fio::NodeInfoDeprecated::Service(fio::Service))
331    }
332}
333
334impl<N: Node> ConnectionCreator<N> for Connection<N> {
335    async fn create<'a>(
336        scope: ExecutionScope,
337        node: Arc<N>,
338        protocols: impl crate::ProtocolsExt,
339        object_request: ObjectRequestRef<'a>,
340    ) -> Result<(), Status> {
341        Self::create(scope, node, protocols, object_request).await
342    }
343}
344
345/// This struct is a RAII wrapper around a node that will call close() on it when dropped.
346pub struct OpenNode<T: Node> {
347    node: Arc<T>,
348}
349
350impl<T: Node> OpenNode<T> {
351    pub fn new(node: Arc<T>) -> Self {
352        Self { node }
353    }
354}
355
356impl<T: Node> Drop for OpenNode<T> {
357    fn drop(&mut self) {
358        self.node.clone().close();
359    }
360}
361
362impl<T: Node> std::ops::Deref for OpenNode<T> {
363    type Target = Arc<T>;
364
365    fn deref(&self) -> &Self::Target {
366        &self.node
367    }
368}