fdf_component/
incoming.rs

1// Copyright 2024 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
5use std::marker::PhantomData;
6
7use anyhow::{Context, Error, anyhow};
8use cm_types::{IterablePath, RelativePath};
9use fdf_sys::fdf_token_transfer;
10use fidl::endpoints::{ClientEnd, DiscoverableProtocolMarker, ServiceMarker, ServiceProxy};
11use fidl_fuchsia_io as fio;
12use fidl_fuchsia_io::Flags;
13use fidl_next_bind::Service;
14use fuchsia_component::client::{Connect, connect_to_service_instance_at_dir_svc};
15use fuchsia_component::directory::{AsRefDirectory, Directory, open_directory_async};
16use fuchsia_component::{DEFAULT_SERVICE_INSTANCE, SVC_DIR};
17use log::error;
18use namespace::{Entry, Namespace};
19use zx::{HandleBased, Status};
20
21/// Implements access to the incoming namespace for a driver. It provides methods
22/// for accessing incoming protocols and services by either their marker or proxy
23/// types, and can be used as a [`Directory`] with the functions in
24/// [`fuchsia_component::client`].
25pub struct Incoming(Vec<Entry>);
26
27impl Incoming {
28    /// Connects to the protocol in the service instance's path in the incoming namespace. Logs and
29    /// returns a [`Status::CONNECTION_REFUSED`] if the service instance couldn't be opened.
30    pub fn connect_protocol<T: Connect>(&self) -> Result<T, Status> {
31        T::connect_at_dir_svc(&self).map_err(|e| {
32            error!(
33                "Failed to connect to discoverable protocol `{}`: {e}",
34                T::Protocol::PROTOCOL_NAME
35            );
36            Status::CONNECTION_REFUSED
37        })
38    }
39
40    /// Creates a connector to the given service's default instance by its marker type. This can be
41    /// convenient when the compiler can't deduce the [`ServiceProxy`] type on its own.
42    ///
43    /// See [`ServiceConnector`] for more about what you can do with the connector.
44    ///
45    /// # Example
46    ///
47    /// ```ignore
48    /// let service = context.incoming.service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker).connect()?;
49    /// let device = service.connect_to_device()?;
50    /// ```
51    pub fn service_marker<M: ServiceMarker>(&self, _marker: M) -> ServiceConnector<'_, M::Proxy> {
52        ServiceConnector { incoming: self, instance: DEFAULT_SERVICE_INSTANCE, _p: PhantomData }
53    }
54
55    /// Creates a connector to the given service's default instance by its proxy type. This can be
56    /// convenient when the compiler can deduce the [`ServiceProxy`] type on its own.
57    ///
58    /// See [`ServiceConnector`] for more about what you can do with the connector.
59    ///
60    /// # Example
61    ///
62    /// ```ignore
63    /// struct MyProxies {
64    ///     i2c_service: fidl_fuchsia_hardware_i2c::ServiceProxy,
65    /// }
66    /// let proxies = MyProxies {
67    ///     i2c_service: context.incoming.service().connect()?;
68    /// };
69    /// ```
70    pub fn service<P>(&self) -> ServiceConnector<'_, P> {
71        ServiceConnector { incoming: self, instance: DEFAULT_SERVICE_INSTANCE, _p: PhantomData }
72    }
73}
74
75/// A builder for connecting to an aggregated service instance in the driver's incoming namespace.
76/// By default, it will connect to the default instance, named `default`. You can override this
77/// by calling [`Self::instance`].
78pub struct ServiceConnector<'incoming, ServiceProxy> {
79    incoming: &'incoming Incoming,
80    instance: &'incoming str,
81    _p: PhantomData<ServiceProxy>,
82}
83
84impl<'a, S> ServiceConnector<'a, S> {
85    /// Overrides the instance name to connect to when [`Self::connect`] is called.
86    pub fn instance(self, instance: &'a str) -> Self {
87        let Self { incoming, _p, .. } = self;
88        Self { incoming, instance, _p }
89    }
90}
91
92impl<'a, S: ServiceProxy> ServiceConnector<'a, S>
93where
94    S::Service: ServiceMarker,
95{
96    /// Connects to the service instance's path in the incoming namespace. Logs and returns
97    /// a [`Status::CONNECTION_REFUSED`] if the service instance couldn't be opened.
98    pub fn connect(self) -> Result<S, Status> {
99        connect_to_service_instance_at_dir_svc::<S::Service>(self.incoming, self.instance).map_err(
100            |e| {
101                error!(
102                    "Failed to connect to aggregated service connector `{}`, instance `{}`: {e}",
103                    S::Service::SERVICE_NAME,
104                    self.instance
105                );
106                Status::CONNECTION_REFUSED
107            },
108        )
109    }
110}
111
112/// Used with [`ServiceHandlerAdapter`] as a connector to members of a service instance.
113pub struct ServiceMemberConnector(fio::DirectoryProxy);
114
115fn connect(
116    dir: &fio::DirectoryProxy,
117    member: &str,
118    server_end: zx::Channel,
119) -> Result<(), fidl::Error> {
120    #[cfg(fuchsia_api_level_at_least = "27")]
121    return dir.open(member, fio::Flags::PROTOCOL_SERVICE, &fio::Options::default(), server_end);
122    #[cfg(not(fuchsia_api_level_at_least = "27"))]
123    return dir.open3(member, fio::Flags::PROTOCOL_SERVICE, &fio::Options::default(), server_end);
124}
125
126impl fidl_next_protocol::ServiceConnector<zx::Channel> for ServiceMemberConnector {
127    type Error = fidl::Error;
128    fn connect_to_member(&self, member: &str, server_end: zx::Channel) -> Result<(), Self::Error> {
129        connect(&self.0, member, server_end)
130    }
131}
132
133impl fidl_next_protocol::ServiceConnector<fdf_fidl::DriverChannel> for ServiceMemberConnector {
134    type Error = Status;
135    fn connect_to_member(
136        &self,
137        member: &str,
138        server_end: fdf_fidl::DriverChannel,
139    ) -> Result<(), Self::Error> {
140        let (client_token, server_token) = zx::Channel::create();
141        connect(&self.0, member, server_token).map_err(|err| {
142            error!("Failed to connect to service member {member}: {err:?}");
143            Status::CONNECTION_REFUSED
144        })?;
145        // SAFETY: client_token and server_end are valid by construction and `fdf_token_transfer`
146        // consumes both handles and does not interact with rust memory.
147        Status::ok(unsafe {
148            fdf_token_transfer(
149                client_token.into_raw(),
150                server_end.into_driver_handle().into_raw().get(),
151            )
152        })
153    }
154}
155
156/// A type alias representing a service instance with members that can be connected to using the
157/// [`fidl_next`] bindings.
158pub type ServiceInstance<S> = fidl_next_bind::ServiceConnector<S, ServiceMemberConnector>;
159
160impl<'a, S: Service<ServiceMemberConnector>> ServiceConnector<'a, ServiceInstance<S>> {
161    /// Connects to the service instance's path in the incoming namespace with the new wire bindings.
162    /// Logs and returns a [`Status::CONNECTION_REFUSED`] if the service instance couldn't be opened.
163    pub fn connect_next(self) -> Result<ServiceInstance<S>, Status> {
164        let service_path = format!("{SVC_DIR}/{}/{}", S::SERVICE_NAME, self.instance);
165        let dir = open_directory_async(self.incoming, &service_path, fio::Rights::empty())
166            .map_err(|e| {
167                error!(
168                    "Failed to connect to aggregated service connector `{}`, instance `{}`: {e}",
169                    S::SERVICE_NAME,
170                    self.instance
171                );
172                Status::CONNECTION_REFUSED
173            })?;
174        Ok(fidl_next_bind::ServiceConnector::from_untyped(ServiceMemberConnector(dir)))
175    }
176}
177
178impl From<Namespace> for Incoming {
179    fn from(value: Namespace) -> Self {
180        Incoming(value.flatten())
181    }
182}
183
184impl From<ClientEnd<fio::DirectoryMarker>> for Incoming {
185    fn from(client: ClientEnd<fio::DirectoryMarker>) -> Self {
186        Incoming(vec![Entry {
187            path: cm_types::NamespacePath::new("/").unwrap(),
188            directory: client,
189        }])
190    }
191}
192
193/// Returns the remainder of a prefix match of `prefix` against `self` in terms of path segments.
194///
195/// For example:
196/// ```ignore
197/// match_prefix("pkg/data", "pkg") == Some("/data")
198/// match_prefix("pkg_data", "pkg") == None
199/// ```
200fn match_prefix(match_in: &impl IterablePath, prefix: &impl IterablePath) -> Option<RelativePath> {
201    let mut my_segments = match_in.iter_segments();
202    let mut prefix_segments = prefix.iter_segments();
203    for prefix in prefix_segments.by_ref() {
204        if prefix != my_segments.next()? {
205            return None;
206        }
207    }
208    if prefix_segments.next().is_some() {
209        // did not match all prefix segments
210        return None;
211    }
212    let segments = Vec::from_iter(my_segments);
213    Some(RelativePath::from(segments))
214}
215
216impl Directory for Incoming {
217    fn open(&self, path: &str, flags: Flags, server_end: zx::Channel) -> Result<(), Error> {
218        let path = path.strip_prefix("/").unwrap_or(path);
219        let path = RelativePath::new(path)?;
220
221        for entry in &self.0 {
222            if let Some(remain) = match_prefix(&path, &entry.path) {
223                return entry.directory.open(&format!("/{}", remain), flags, server_end);
224            }
225        }
226        Err(Status::NOT_FOUND)
227            .with_context(|| anyhow!("Path {path} not found in incoming namespace"))
228    }
229}
230
231impl AsRefDirectory for Incoming {
232    fn as_ref_directory(&self) -> &dyn Directory {
233        self
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use fuchsia_async::Task;
241    use fuchsia_component::server::ServiceFs;
242    use futures::stream::StreamExt;
243
244    enum IncomingServices {
245        Device(fidl_fuchsia_hardware_i2c::DeviceRequestStream),
246        DefaultService(fidl_fuchsia_hardware_i2c::ServiceRequest),
247        OtherService(fidl_fuchsia_hardware_i2c::ServiceRequest),
248    }
249
250    impl IncomingServices {
251        async fn handle_device_stream(
252            stream: fidl_fuchsia_hardware_i2c::DeviceRequestStream,
253            name: &str,
254        ) {
255            stream
256                .for_each(|msg| async move {
257                    match msg.unwrap() {
258                        fidl_fuchsia_hardware_i2c::DeviceRequest::GetName { responder } => {
259                            responder.send(Ok(name)).unwrap();
260                        }
261                        _ => unimplemented!(),
262                    }
263                })
264                .await
265        }
266
267        async fn handle(self) {
268            use IncomingServices::*;
269            match self {
270                Device(stream) => Self::handle_device_stream(stream, "device").await,
271                DefaultService(fidl_fuchsia_hardware_i2c::ServiceRequest::Device(stream)) => {
272                    Self::handle_device_stream(stream, "default").await
273                }
274                OtherService(fidl_fuchsia_hardware_i2c::ServiceRequest::Device(stream)) => {
275                    Self::handle_device_stream(stream, "other").await
276                }
277            }
278        }
279    }
280
281    async fn make_incoming() -> Incoming {
282        let (client, server) = fidl::endpoints::create_endpoints();
283        let mut fs = ServiceFs::new();
284        fs.dir("svc")
285            .add_fidl_service(IncomingServices::Device)
286            .add_fidl_service_instance("default", IncomingServices::DefaultService)
287            .add_fidl_service_instance("other", IncomingServices::OtherService);
288        fs.serve_connection(server).expect("error serving handle");
289
290        Task::spawn(fs.for_each_concurrent(100, IncomingServices::handle)).detach_on_drop();
291        Incoming::from(client)
292    }
293
294    #[fuchsia::test]
295    async fn protocol_connect_present() -> anyhow::Result<()> {
296        let incoming = make_incoming().await;
297        // try a protocol that we did set up
298        incoming
299            .connect_protocol::<fidl_fuchsia_hardware_i2c::DeviceProxy>()?
300            .get_name()
301            .await?
302            .unwrap();
303        Ok(())
304    }
305
306    #[fuchsia::test]
307    async fn protocol_connect_not_present() -> anyhow::Result<()> {
308        let incoming = make_incoming().await;
309        // try one we didn't
310        incoming
311            .connect_protocol::<fidl_fuchsia_hwinfo::DeviceProxy>()?
312            .get_info()
313            .await
314            .unwrap_err();
315        Ok(())
316    }
317
318    #[fuchsia::test]
319    async fn service_connect_default_instance() -> anyhow::Result<()> {
320        let incoming = make_incoming().await;
321        // try the default service instance that we did set up
322        assert_eq!(
323            "default",
324            &incoming
325                .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
326                .connect()?
327                .connect_to_device()?
328                .get_name()
329                .await?
330                .unwrap()
331        );
332        assert_eq!(
333            "default",
334            &incoming
335                .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
336                .connect()?
337                .connect_to_device()?
338                .get_name()
339                .await?
340                .unwrap()
341        );
342        Ok(())
343    }
344
345    #[fuchsia::test]
346    async fn service_connect_other_instance() -> anyhow::Result<()> {
347        let incoming = make_incoming().await;
348        // try the other service instance that we did set up
349        assert_eq!(
350            "other",
351            &incoming
352                .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
353                .instance("other")
354                .connect()?
355                .connect_to_device()?
356                .get_name()
357                .await?
358                .unwrap()
359        );
360        assert_eq!(
361            "other",
362            &incoming
363                .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
364                .instance("other")
365                .connect()?
366                .connect_to_device()?
367                .get_name()
368                .await?
369                .unwrap()
370        );
371        Ok(())
372    }
373
374    #[fuchsia::test]
375    async fn service_connect_invalid_instance() -> anyhow::Result<()> {
376        let incoming = make_incoming().await;
377        // try the invalid service instance that we did not set up
378        incoming
379            .service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
380            .instance("invalid")
381            .connect()?
382            .connect_to_device()?
383            .get_name()
384            .await
385            .unwrap_err();
386        incoming
387            .service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
388            .instance("invalid")
389            .connect()?
390            .connect_to_device()?
391            .get_name()
392            .await
393            .unwrap_err();
394        Ok(())
395    }
396}